1 /* NeXT/Open/GNUstep / MacOSX communication module.
2 Copyright (C) 1989, 1993, 1994, 2005, 2006, 2008, 2009
3 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 Originally by Carl Edman
22 Updated by Christian Limpach (chris@nice.ch)
23 OpenStep/Rhapsody port by Scott Bender (sbender@harmony-ds.com)
24 MacOSX/Aqua port by Christophe de Dinechin (descubes@earthlink.net)
25 GNUstep port and post-20 update by Adrian Robert (arobert@cogsci.ucsd.edu)
28 /* This should be the first include, as it may set up #defines affecting
29 interpretation of even the system includes. */
33 #include <sys/types.h>
39 #include "blockinput.h"
40 #include "sysselect.h"
43 #include "character.h"
45 #include "composite.h"
48 #include "termhooks.h"
59 int term_trace_num = 0;
60 #define NSTRACE(x) fprintf (stderr, "%s:%d: [%d] " #x "\n", \
61 __FILE__, __LINE__, ++term_trace_num)
67 /* ==========================================================================
71 ========================================================================== */
73 /* Convert a symbol indexed with an NSxxx value to a value as defined
74 in keyboard.c (lispy_function_key). I hope this is a correct way
76 static unsigned convert_ns_to_X_keysym[] =
78 NSHomeFunctionKey, 0x50,
79 NSLeftArrowFunctionKey, 0x51,
80 NSUpArrowFunctionKey, 0x52,
81 NSRightArrowFunctionKey, 0x53,
82 NSDownArrowFunctionKey, 0x54,
83 NSPageUpFunctionKey, 0x55,
84 NSPageDownFunctionKey, 0x56,
85 NSEndFunctionKey, 0x57,
86 NSBeginFunctionKey, 0x58,
87 NSSelectFunctionKey, 0x60,
88 NSPrintFunctionKey, 0x61,
89 NSExecuteFunctionKey, 0x62,
90 NSInsertFunctionKey, 0x63,
91 NSUndoFunctionKey, 0x65,
92 NSRedoFunctionKey, 0x66,
93 NSMenuFunctionKey, 0x67,
94 NSFindFunctionKey, 0x68,
95 NSHelpFunctionKey, 0x6A,
96 NSBreakFunctionKey, 0x6B,
98 NSF1FunctionKey, 0xBE,
99 NSF2FunctionKey, 0xBF,
100 NSF3FunctionKey, 0xC0,
101 NSF4FunctionKey, 0xC1,
102 NSF5FunctionKey, 0xC2,
103 NSF6FunctionKey, 0xC3,
104 NSF7FunctionKey, 0xC4,
105 NSF8FunctionKey, 0xC5,
106 NSF9FunctionKey, 0xC6,
107 NSF10FunctionKey, 0xC7,
108 NSF11FunctionKey, 0xC8,
109 NSF12FunctionKey, 0xC9,
110 NSF13FunctionKey, 0xCA,
111 NSF14FunctionKey, 0xCB,
112 NSF15FunctionKey, 0xCC,
114 NSBackspaceCharacter, 0x08, /* 8: Not on some KBs. */
115 NSDeleteCharacter, 0xFF, /* 127: Big 'delete' key upper right. */
116 NSDeleteFunctionKey, 0x9F, /* 63272: Del forw key off main array. */
118 NSTabCharacter, 0x09,
119 0x19, 0x09, /* left tab->regular since pass shift */
120 NSCarriageReturnCharacter, 0x0D,
121 NSNewlineCharacter, 0x0D,
122 NSEnterCharacter, 0x8D,
124 0x1B, 0x1B /* escape */
128 /* Lisp communications */
129 Lisp_Object ns_input_file, ns_input_font, ns_input_fontsize, ns_input_line;
130 Lisp_Object ns_input_color, ns_input_text, ns_working_text;
131 Lisp_Object ns_input_spi_name, ns_input_spi_arg;
132 Lisp_Object Vx_toolkit_scroll_bars;
133 static Lisp_Object Qmodifier_value;
134 /* TODO: unsure why these defined in term files, anyway we need in keymap.c */
135 Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper;
136 extern Lisp_Object Qcursor_color, Qcursor_type, Qns;
139 /* Some preferences equivalent to those set by X resources under X are
140 managed through the OpenStep defaults system. We depart from X
141 behavior and refuse to read defaults when started under these
144 /* Set in emacs.c. */
147 /* Specifies which emacs modifier should be generated when NS receives
148 the Alternate modifer. May be Qnone or any of the modifier lisp symbols. */
149 Lisp_Object ns_alternate_modifier;
151 /* Specifies which emacs modifier should be generated when NS receives
152 the Command modifer. May be any of the modifier lisp symbols. */
153 Lisp_Object ns_command_modifier;
155 /* Specifies which emacs modifier should be generated when NS receives
156 the Control modifer. May be any of the modifier lisp symbols. */
157 Lisp_Object ns_control_modifier;
159 /* Specifies which emacs modifier should be generated when NS receives
160 the Function modifer (laptops). May be any of the modifier lisp symbols. */
161 Lisp_Object ns_function_modifier;
163 /* Control via default 'GSFontAntiAlias' on OS X and GNUstep. */
164 Lisp_Object ns_antialias_text;
166 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
167 the maximum font size to NOT antialias. On GNUstep there is currently
168 no way to control this behavior. */
169 float ns_antialias_threshold;
171 /* Controls use of an undocumented CG function to do Quickdraw-style font
172 smoothing (less heavy) instead of regular Quartz smoothing. */
173 Lisp_Object ns_use_qd_smoothing;
175 /* Used to pick up AppleHighlightColor on OS X */
176 Lisp_Object ns_use_system_highlight_color;
177 NSString *ns_selection_color;
179 /* Confirm on exit. */
180 Lisp_Object ns_confirm_quit;
182 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
184 /* Display variables */
185 struct ns_display_info *x_display_list; /* Chain of existing displays */
186 Lisp_Object ns_display_name_list;
187 long context_menu_value = 0;
190 NSPoint last_mouse_motion_position;
191 static NSRect last_mouse_glyph;
192 static unsigned long last_mouse_movement_time = 0;
193 static Lisp_Object last_mouse_motion_frame;
194 static EmacsScroller *last_mouse_scroll_bar = nil;
195 static struct frame *ns_updating_frame;
196 static NSView *focus_view = NULL;
197 static int ns_window_num =0;
199 static BOOL gsaved = NO;
200 BOOL ns_in_resize = NO;
201 static BOOL ns_fake_keydown = NO;
202 int ns_tmp_flags; /* FIXME */
203 struct nsfont_info *ns_tmp_font; /* FIXME */
204 /*static int debug_lock = 0; */
207 /* This undocumented Quartz function controls how fonts are anti-aliased.
208 (Found from code in Mac wxWindows impl, discovered by running `nm' on
210 Mode 0 is normal anti-aliasing, mode 1 is no anti-aliasing, and mode 2 is
211 4-bit pixel-aligned anti-aliasing (the old QuickDraw standard). */
212 extern void CGContextSetFontRenderingMode (CGContextRef cg, int v);
217 static BOOL send_appdefined = YES;
218 static NSEvent *last_appdefined_event = 0;
219 static NSTimer *timed_entry = 0;
220 static NSTimer *fd_entry = nil;
221 static NSTimer *scroll_repeat_entry = nil;
222 static fd_set select_readfds, t_readfds;
223 static struct timeval select_timeout;
224 static int select_nfds;
225 static NSAutoreleasePool *outerpool;
226 static struct input_event *emacs_event = NULL;
227 static struct input_event *q_event_ptr = NULL;
228 static int n_emacs_events_pending = 0;
229 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
230 *ns_pending_service_args;
231 static BOOL inNsSelect = 0;
233 /* Convert modifiers in a NeXTSTEP event to emacs style modifiers. */
234 #define NS_FUNCTION_KEY_MASK 0x800000
235 #define EV_MODIFIERS(e) \
236 ((([e modifierFlags] & NSHelpKeyMask) ? \
237 hyper_modifier : 0) \
238 | (([e modifierFlags] & NSAlternateKeyMask) ? \
239 parse_solitary_modifier (ns_alternate_modifier) : 0) \
240 | (([e modifierFlags] & NSShiftKeyMask) ? \
241 shift_modifier : 0) \
242 | (([e modifierFlags] & NSControlKeyMask) ? \
243 parse_solitary_modifier (ns_control_modifier) : 0) \
244 | (([e modifierFlags] & NS_FUNCTION_KEY_MASK) ? \
245 parse_solitary_modifier (ns_function_modifier) : 0) \
246 | (([e modifierFlags] & NSCommandKeyMask) ? \
247 parse_solitary_modifier (ns_command_modifier):0))
249 #define EV_UDMODIFIERS(e) \
250 ((([e type] == NSLeftMouseDown) ? down_modifier : 0) \
251 | (([e type] == NSRightMouseDown) ? down_modifier : 0) \
252 | (([e type] == NSOtherMouseDown) ? down_modifier : 0) \
253 | (([e type] == NSLeftMouseDragged) ? down_modifier : 0) \
254 | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
255 | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
256 | (([e type] == NSLeftMouseUp) ? up_modifier : 0) \
257 | (([e type] == NSRightMouseUp) ? up_modifier : 0) \
258 | (([e type] == NSOtherMouseUp) ? up_modifier : 0))
260 #define EV_BUTTON(e) \
261 ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 : \
262 (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
263 [e buttonNumber] - 1)
265 /* Convert the time field to a timestamp in milliseconds. */
266 #ifdef NS_IMPL_GNUSTEP
267 /* Apple says timestamp is in seconds, but GNUstep seems to be returning msec */
268 #define EV_TIMESTAMP(e) ([e timestamp])
270 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
271 #endif /* not gnustep */
273 /* This is a piece of code which is common to all the event handling
274 methods. Maybe it should even be a function. */
275 #define EV_TRAILER(e) \
277 XSETFRAME (emacs_event->frame_or_window, emacsframe); \
278 if (e) emacs_event->timestamp = EV_TIMESTAMP (e); \
279 n_emacs_events_pending++; \
280 kbd_buffer_store_event_hold (emacs_event, q_event_ptr); \
281 EVENT_INIT (*emacs_event); \
282 ns_send_appdefined (-1); \
285 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
287 /* TODO: get rid of need for these forward declarations */
288 static void ns_condemn_scroll_bars (struct frame *f);
289 static void ns_judge_scroll_bars (struct frame *f);
290 void x_set_frame_alpha (struct frame *f);
292 /* unused variables needed for compatibility reasons */
293 int x_use_underline_position_properties, x_underline_at_descent_line;
294 /* FIXME: figure out what to do with underline_minimum_offset. */
297 /* ==========================================================================
301 ========================================================================== */
305 append2 (Lisp_Object list, Lisp_Object item)
306 /* --------------------------------------------------------------------------
307 Utility to append to a list
308 -------------------------------------------------------------------------- */
310 Lisp_Object array[2];
312 array[1] = Fcons (item, Qnil);
313 return Fnconc (2, &array[0]);
319 /* --------------------------------------------------------------------------
320 Used to allow emacs to find its resources under Emacs.app
321 Called from emacs.c at startup.
322 -------------------------------------------------------------------------- */
324 NSBundle *bundle = [NSBundle mainBundle];
325 NSString *binDir = [bundle bundlePath], *resourceDir = [bundle resourcePath];
326 NSString *resourcePath, *resourcePaths;
328 BOOL onWindows = NO; /* how do I determine this? */
329 NSString *pathSeparator = onWindows ? @";" : @":";
330 NSFileManager *fileManager = [NSFileManager defaultManager];
332 /*NSLog (@"ns_init_paths: '%@'\n%@\n", [[NSBundle mainBundle] bundlePath], [[NSBundle mainBundle] resourcePath]); */
334 /* get bindir from base */
335 range = [resourceDir rangeOfString: @"Contents"];
336 if (range.location != NSNotFound)
338 binDir = [binDir stringByAppendingPathComponent: @"Contents"];
340 binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
344 /* the following based on Andrew Choi's init_mac_osx_environment () */
345 if (!getenv ("EMACSLOADPATH"))
347 NSArray *paths = [resourceDir stringsByAppendingPaths:
348 [NSArray arrayWithObjects:
349 @"site-lisp", @"lisp", @"leim", nil]];
350 NSEnumerator *pathEnum = [paths objectEnumerator];
352 while (resourcePath = [pathEnum nextObject])
354 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
357 if ([resourcePaths length] > 0)
359 = [resourcePaths stringByAppendingString: pathSeparator];
361 = [resourcePaths stringByAppendingString: resourcePath];
364 if ([resourcePaths length] > 0)
365 setenv ("EMACSLOADPATH", [resourcePaths UTF8String], 1);
366 /*NSLog (@"loadPath: '%s'\n", resourcePaths); */
369 if (!getenv ("EMACSPATH"))
371 NSArray *paths = [binDir stringsByAppendingPaths:
372 [NSArray arrayWithObjects: @"bin",
374 NSEnumerator *pathEnum = [paths objectEnumerator];
376 while (resourcePath = [pathEnum nextObject])
378 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
381 if ([resourcePaths length] > 0)
383 = [resourcePaths stringByAppendingString: pathSeparator];
385 = [resourcePaths stringByAppendingString: resourcePath];
388 if ([resourcePaths length] > 0)
389 setenv ("EMACSPATH", [resourcePaths UTF8String], 1);
392 resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
393 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
397 if (!getenv ("EMACSDATA"))
398 setenv ("EMACSDATA", [resourcePath UTF8String], 1);
399 if (!getenv ("EMACSDOC"))
400 setenv ("EMACSDOC", [resourcePath UTF8String], 1);
404 if (!getenv ("INFOPATH"))
406 resourcePath = [resourceDir stringByAppendingPathComponent: @"info"];
407 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
409 setenv ("INFOPATH", [resourcePath UTF8String], 1);
415 timeval_subtract (struct timeval *result, struct timeval x, struct timeval y)
416 /* --------------------------------------------------------------------------
417 Subtract the `struct timeval' values X and Y, storing the result in RESULT.
418 Return 1 if the difference is negative, otherwise 0.
419 -------------------------------------------------------------------------- */
421 /* Perform the carry for the later subtraction by updating y.
422 This is safer because on some systems
423 the tv_sec member is unsigned. */
424 if (x.tv_usec < y.tv_usec)
426 int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
427 y.tv_usec -= 1000000 * nsec;
430 if (x.tv_usec - y.tv_usec > 1000000)
432 int nsec = (y.tv_usec - x.tv_usec) / 1000000;
433 y.tv_usec += 1000000 * nsec;
437 /* Compute the time remaining to wait. tv_usec is certainly positive. */
438 result->tv_sec = x.tv_sec - y.tv_sec;
439 result->tv_usec = x.tv_usec - y.tv_usec;
441 /* Return indication of whether the result should be considered negative. */
442 return x.tv_sec < y.tv_sec;
446 ns_timeout (int usecs)
447 /* --------------------------------------------------------------------------
448 Blocking timer utility used by ns_ring_bell
449 -------------------------------------------------------------------------- */
451 struct timeval wakeup;
453 EMACS_GET_TIME (wakeup);
455 /* Compute time to wait until, propagating carry from usecs. */
456 wakeup.tv_usec += usecs;
457 wakeup.tv_sec += (wakeup.tv_usec / 1000000);
458 wakeup.tv_usec %= 1000000;
460 /* Keep waiting until past the time wakeup. */
463 struct timeval timeout;
465 EMACS_GET_TIME (timeout);
467 /* In effect, timeout = wakeup - timeout.
468 Break if result would be negative. */
469 if (timeval_subtract (&timeout, wakeup, timeout))
472 /* Try to wait that long--but we might wake up sooner. */
473 select (0, NULL, NULL, NULL, &timeout);
479 ns_release_object (void *obj)
480 /* --------------------------------------------------------------------------
481 Release an object (callable from C)
482 -------------------------------------------------------------------------- */
489 ns_retain_object (void *obj)
490 /* --------------------------------------------------------------------------
491 Retain an object (callable from C)
492 -------------------------------------------------------------------------- */
499 ns_alloc_autorelease_pool ()
500 /* --------------------------------------------------------------------------
501 Allocate a pool for temporary objects (callable from C)
502 -------------------------------------------------------------------------- */
504 return [[NSAutoreleasePool alloc] init];
509 ns_release_autorelease_pool (void *pool)
510 /* --------------------------------------------------------------------------
511 Free a pool and temporary objects it refers to (callable from C)
512 -------------------------------------------------------------------------- */
514 ns_release_object (pool);
519 /* ==========================================================================
521 Focus (clipping) and screen update
523 ========================================================================== */
526 ns_resize_handle_rect (NSWindow *window)
528 NSRect r = [window frame];
529 r.origin.x = r.size.width - RESIZE_HANDLE_SIZE;
531 r.size.width = r.size.height = RESIZE_HANDLE_SIZE;
537 ns_update_begin (struct frame *f)
538 /* --------------------------------------------------------------------------
539 Prepare for a grouped sequence of drawing calls
540 external (RIF) call; whole frame, called before update_window_begin
541 -------------------------------------------------------------------------- */
543 NSView *view = FRAME_NS_VIEW (f);
544 NSTRACE (ns_update_begin);
546 ns_updating_frame = f;
549 #ifdef NS_IMPL_GNUSTEP
550 uRect = NSMakeRect (0, 0, 0, 0);
556 ns_update_window_begin (struct window *w)
557 /* --------------------------------------------------------------------------
558 Prepare for a grouped sequence of drawing calls
559 external (RIF) call; for one window, called after update_begin
560 -------------------------------------------------------------------------- */
562 struct frame *f = XFRAME (WINDOW_FRAME (w));
563 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
564 NSTRACE (ns_update_window_begin);
567 set_output_cursor (&w->cursor);
571 if (f == dpyinfo->mouse_face_mouse_frame)
573 /* Don't do highlighting for mouse motion during the update. */
574 dpyinfo->mouse_face_defer = 1;
576 /* If the frame needs to be redrawn,
577 simply forget about any prior mouse highlighting. */
578 if (FRAME_GARBAGED_P (f))
579 dpyinfo->mouse_face_window = Qnil;
581 /* (further code for mouse faces ifdef'd out in other terms elided) */
589 ns_update_window_end (struct window *w, int cursor_on_p,
590 int mouse_face_overwritten_p)
591 /* --------------------------------------------------------------------------
592 Finished a grouped sequence of drawing calls
593 external (RIF) call; for one window called before update_end
594 -------------------------------------------------------------------------- */
596 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (XFRAME (w->frame));
598 /* note: this fn is nearly identical in all terms */
599 if (!w->pseudo_window_p)
604 display_and_set_cursor (w, 1,
605 output_cursor.hpos, output_cursor.vpos,
606 output_cursor.x, output_cursor.y);
608 if (draw_window_fringes (w, 1))
609 x_draw_vertical_border (w);
614 /* If a row with mouse-face was overwritten, arrange for
615 frame_up_to_date to redisplay the mouse highlight. */
616 if (mouse_face_overwritten_p)
618 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
619 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
620 dpyinfo->mouse_face_window = Qnil;
623 updated_window = NULL;
624 NSTRACE (update_window_end);
629 ns_update_end (struct frame *f)
630 /* --------------------------------------------------------------------------
631 Finished a grouped sequence of drawing calls
632 external (RIF) call; for whole frame, called after update_window_end
633 -------------------------------------------------------------------------- */
635 NSView *view = FRAME_NS_VIEW (f);
637 /* if (f == FRAME_NS_DISPLAY_INFO (f)->mouse_face_mouse_frame) */
638 FRAME_NS_DISPLAY_INFO (f)->mouse_face_defer = 0;
642 #ifdef NS_IMPL_GNUSTEP
643 /* trigger flush only in the rectangle we tracked as being drawn */
644 [view unlockFocusNeedsFlush: NO];
645 /*fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", uRect.origin.x, uRect.origin.y, uRect.size.width, uRect.size.height); */
646 [view lockFocusInRect: uRect];
650 [[view window] flushWindow];
653 ns_updating_frame = NULL;
654 NSTRACE (ns_update_end);
659 ns_flush (struct frame *f)
660 /* --------------------------------------------------------------------------
662 NS impl is no-op since currently we flush in ns_update_end and elsewhere
663 -------------------------------------------------------------------------- */
670 ns_focus (struct frame *f, NSRect *r, int n)
671 /* --------------------------------------------------------------------------
672 Internal: Focus on given frame. During small local updates this is used to
673 draw, however during large updates, ns_update_begin and ns_update_end are
674 called to wrap the whole thing, in which case these calls are stubbed out.
675 Except, on GNUstep, we accumulate the rectangle being drawn into, because
676 the back end won't do this automatically, and will just end up flushing
678 -------------------------------------------------------------------------- */
680 // NSTRACE (ns_focus);
681 #ifdef NS_IMPL_GNUSTEP
684 u = NSUnionRect (r[0], r[1]);
689 fprintf (stderr, "focus: %d", c++);
690 if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
691 fprintf (stderr, "\n"); */
693 if (f != ns_updating_frame)
695 NSView *view = FRAME_NS_VIEW (f);
696 if (view != focus_view)
698 if (focus_view != NULL)
700 [focus_view unlockFocus];
701 [[focus_view window] flushWindow];
706 #ifdef NS_IMPL_GNUSTEP
707 r ? [view lockFocusInRect: u] : [view lockFocus];
712 /*if (view) debug_lock++; */
714 #ifdef NS_IMPL_GNUSTEP
717 /* more than one rect being drawn into */
720 [view unlockFocus]; /* add prev rect to redraw list */
721 [view lockFocusInRect: u]; /* focus for draw in new rect */
726 #ifdef NS_IMPL_GNUSTEP
729 /* in batch mode, but in GNUstep must still track rectangles explicitly */
730 uRect = (r ? NSUnionRect (uRect, u) : [FRAME_NS_VIEW (f) visibleRect]);
737 [[NSGraphicsContext currentContext] saveGraphicsState];
739 NSRectClipList (r, 2);
748 ns_unfocus (struct frame *f)
749 /* --------------------------------------------------------------------------
750 Internal: Remove focus on given frame
751 -------------------------------------------------------------------------- */
753 // NSTRACE (ns_unfocus);
757 [[NSGraphicsContext currentContext] restoreGraphicsState];
761 if (f != ns_updating_frame)
763 if (focus_view != NULL)
765 [focus_view unlockFocus];
766 [[focus_view window] flushWindow];
775 ns_clip_to_row (struct window *w, struct glyph_row *row, int area, BOOL gc)
776 /* --------------------------------------------------------------------------
777 Internal (but parallels other terms): Focus drawing on given row
778 -------------------------------------------------------------------------- */
780 struct frame *f = XFRAME (WINDOW_FRAME (w));
782 int window_x, window_y, window_width;
784 window_box (w, area, &window_x, &window_y, &window_width, 0);
786 clip_rect.origin.x = window_x - FRAME_INTERNAL_BORDER_WIDTH (f);
787 clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
788 clip_rect.origin.y = max (clip_rect.origin.y, window_y);
789 clip_rect.size.width = window_width + 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
790 clip_rect.size.height = row->visible_height;
792 /* allow a full-height row at the top when requested
793 (used to draw fringe all the way through internal border area) */
794 if (gc && clip_rect.origin.y < 5)
796 clip_rect.origin.y -= FRAME_INTERNAL_BORDER_WIDTH (f);
797 clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
800 /* likewise at bottom */
802 FRAME_PIXEL_HEIGHT (f) - (clip_rect.origin.y + clip_rect.size.height) < 5)
803 clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
805 ns_focus (f, &clip_rect, 1);
811 /* --------------------------------------------------------------------------
813 -------------------------------------------------------------------------- */
815 NSTRACE (ns_ring_bell);
818 NSAutoreleasePool *pool;
819 struct frame *frame = SELECTED_FRAME ();
823 pool = [[NSAutoreleasePool alloc] init];
825 view = FRAME_NS_VIEW (frame);
829 NSPoint dim = NSMakePoint (128, 128);
832 r.origin.x += (r.size.width - dim.x) / 2;
833 r.origin.y += (r.size.height - dim.y) / 2;
834 r.size.width = dim.x;
835 r.size.height = dim.y;
836 surr = NSInsetRect (r, -2, -2);
837 ns_focus (frame, &surr, 1);
838 [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
839 [ns_lookup_indexed_color (NS_FACE_FOREGROUND
840 (FRAME_DEFAULT_FACE (frame)), frame) set];
842 [[view window] flushWindow];
844 [[view window] restoreCachedImage];
845 [[view window] flushWindow];
859 ns_reset_terminal_modes (struct terminal *terminal)
860 /* Externally called as hook */
862 NSTRACE (ns_reset_terminal_modes);
866 ns_set_terminal_modes (struct terminal *terminal)
867 /* Externally called as hook */
869 NSTRACE (ns_set_terminal_modes);
874 /* ==========================================================================
876 Frame / window manager related functions
878 ========================================================================== */
882 ns_raise_frame (struct frame *f)
883 /* --------------------------------------------------------------------------
884 Bring window to foreground and make it active
885 -------------------------------------------------------------------------- */
887 NSView *view = FRAME_NS_VIEW (f);
890 [[view window] makeKeyAndOrderFront: NSApp];
896 ns_lower_frame (struct frame *f)
897 /* --------------------------------------------------------------------------
899 -------------------------------------------------------------------------- */
901 NSView *view = FRAME_NS_VIEW (f);
904 [[view window] orderBack: NSApp];
910 ns_frame_raise_lower (struct frame *f, int raise)
911 /* --------------------------------------------------------------------------
913 -------------------------------------------------------------------------- */
915 NSTRACE (ns_frame_raise_lower);
925 ns_frame_rehighlight (struct frame *frame)
926 /* --------------------------------------------------------------------------
927 External (hook): called on things like window switching within frame
928 -------------------------------------------------------------------------- */
930 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
931 struct frame *old_highlight = dpyinfo->x_highlight_frame;
933 NSTRACE (ns_frame_rehighlight);
934 if (dpyinfo->x_focus_frame)
936 dpyinfo->x_highlight_frame
937 = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
938 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
939 : dpyinfo->x_focus_frame);
940 if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
942 FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
943 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
947 dpyinfo->x_highlight_frame = 0;
949 if (dpyinfo->x_highlight_frame &&
950 dpyinfo->x_highlight_frame != old_highlight)
954 x_update_cursor (old_highlight, 1);
955 x_set_frame_alpha (old_highlight);
957 if (dpyinfo->x_highlight_frame)
959 x_update_cursor (dpyinfo->x_highlight_frame, 1);
960 x_set_frame_alpha (dpyinfo->x_highlight_frame);
967 x_make_frame_visible (struct frame *f)
968 /* --------------------------------------------------------------------------
969 External: Show the window (X11 semantics)
970 -------------------------------------------------------------------------- */
972 NSTRACE (x_make_frame_visible);
973 /* XXX: at some points in past this was not needed, as the only place that
974 called this (frame.c:Fraise_frame ()) also called raise_lower;
975 if this ends up the case again, comment this out again. */
976 if (!FRAME_VISIBLE_P (f))
982 x_make_frame_invisible (struct frame *f)
983 /* --------------------------------------------------------------------------
984 External: Hide the window (X11 semantics)
985 -------------------------------------------------------------------------- */
987 NSView * view = FRAME_NS_VIEW (f);
988 NSTRACE (x_make_frame_invisible);
990 [[view window] orderOut: NSApp];
991 f->async_visible = 0;
992 f->async_iconified = 0;
997 x_iconify_frame (struct frame *f)
998 /* --------------------------------------------------------------------------
999 External: Iconify window
1000 -------------------------------------------------------------------------- */
1002 NSView * view = FRAME_NS_VIEW (f);
1003 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1004 NSTRACE (x_iconify_frame);
1007 if (dpyinfo->x_highlight_frame == f)
1008 dpyinfo->x_highlight_frame = 0;
1010 if ([[view window] windowNumber] <= 0)
1012 /* the window is still deferred. Make it very small, bring it
1013 on screen and order it out. */
1014 NSRect s = { { 100, 100}, {0, 0} };
1016 t = [[view window] frame];
1017 [[view window] setFrame: s display: NO];
1018 [[view window] orderBack: NSApp];
1019 [[view window] orderOut: NSApp];
1020 [[view window] setFrame: t display: NO];
1022 [[view window] miniaturize: NSApp];
1027 x_destroy_window (struct frame *f)
1028 /* --------------------------------------------------------------------------
1029 External: Delete the window
1030 -------------------------------------------------------------------------- */
1032 NSView *view = FRAME_NS_VIEW (f);
1033 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1034 NSTRACE (x_destroy_window);
1037 [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1041 free_frame_menubar (f);
1043 if (FRAME_FACE_CACHE (f))
1044 free_frame_faces (f);
1046 if (f == dpyinfo->x_focus_frame)
1047 dpyinfo->x_focus_frame = 0;
1048 if (f == dpyinfo->x_highlight_frame)
1049 dpyinfo->x_highlight_frame = 0;
1050 if (f == dpyinfo->mouse_face_mouse_frame)
1052 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
1053 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
1054 dpyinfo->mouse_face_window = Qnil;
1055 dpyinfo->mouse_face_deferred_gc = 0;
1056 dpyinfo->mouse_face_mouse_frame = 0;
1059 xfree (f->output_data.ns);
1061 [[view window] close];
1070 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1071 /* --------------------------------------------------------------------------
1072 External: Position the window
1073 -------------------------------------------------------------------------- */
1076 NSView *view = FRAME_NS_VIEW (f);
1078 NSTRACE (x_set_offset);
1084 #ifdef NS_IMPL_GNUSTEP
1086 f->left_pos = 100; /* don't overlap menu */
1088 if (view != nil && (screen = [[view window] screen]))
1089 [[view window] setFrameTopLeftPoint:
1090 NSMakePoint (SCREENMAXBOUND (f->left_pos),
1091 SCREENMAXBOUND ([screen frame].size.height
1092 - NS_TOP_POS (f)))];
1098 x_set_window_size (struct frame *f, int change_grav, int cols, int rows)
1099 /* --------------------------------------------------------------------------
1100 Adjust window pixel size based on given character grid size
1101 Impl is a bit more complex than other terms, need to do some
1102 internal clipping and also pay attention to screen constraints.
1103 -------------------------------------------------------------------------- */
1105 EmacsView *view = FRAME_NS_VIEW (f);
1106 EmacsToolbar *toolbar = [view toolbar];
1107 NSWindow *window = [view window];
1108 NSScreen *screen = [window screen];
1109 NSRect wr = [window frame];
1110 int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1111 int pixelwidth, pixelheight;
1112 static int oldRows, oldCols, oldFontWidth, oldFontHeight;
1114 static struct frame *oldF;
1116 NSTRACE (x_set_window_size);
1120 && rows == oldRows && cols == oldCols
1121 && oldFontWidth == FRAME_COLUMN_WIDTH (f)
1122 && oldFontHeight == FRAME_LINE_HEIGHT (f)
1126 /*fprintf (stderr, "\tsetWindowSize: %d x %d, font size %d x %d\n", cols, rows, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f)); */
1130 check_frame_size (f, &rows, &cols);
1134 oldFontWidth = FRAME_COLUMN_WIDTH (f);
1135 oldFontHeight = FRAME_LINE_HEIGHT (f);
1138 f->scroll_bar_actual_width = NS_SCROLL_BAR_WIDTH (f);
1139 compute_fringe_widths (f, 0);
1141 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols);
1142 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
1144 /* If we have a toolbar, take its height into account. */
1145 /* XXX: GNUstep has not yet implemented the first method below, added
1146 in Panther, however the second is incorrect under Cocoa. */
1148 FRAME_NS_TOOLBAR_HEIGHT (f) =
1149 #ifdef NS_IMPL_COCOA
1150 NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1151 /* NOTE: previously this would generate wrong result if toolbar not
1152 yet displayed and fixing toolbar_height=32 helped, but
1153 now (200903) seems no longer needed */
1155 NSHeight ([NSWindow frameRectForContentRect: NSMakeRect (0, 0, 0, 0)
1156 styleMask: [window styleMask]])
1158 - FRAME_NS_TITLEBAR_HEIGHT (f);
1160 FRAME_NS_TOOLBAR_HEIGHT (f) = 0;
1162 wr.size.width = pixelwidth + f->border_width;
1163 wr.size.height = pixelheight + FRAME_NS_TITLEBAR_HEIGHT (f)
1164 + FRAME_NS_TOOLBAR_HEIGHT (f);
1166 /* constrain to screen if we can */
1169 NSSize sz = [screen visibleFrame].size;
1170 NSSize ez = { wr.size.width - sz.width, wr.size.height - sz.height };
1173 int cr = ez.width / FRAME_COLUMN_WIDTH (f) + 1;
1176 wr.size.width -= cr * FRAME_COLUMN_WIDTH (f);
1177 pixelwidth -= cr * FRAME_COLUMN_WIDTH (f);
1181 int rr = ez.height / FRAME_LINE_HEIGHT (f) + 1;
1184 wr.size.height -= rr * FRAME_LINE_HEIGHT (f);
1185 pixelheight -= rr * FRAME_LINE_HEIGHT (f);
1187 wr.origin.x = f->left_pos;
1188 wr.origin.y = [screen frame].size.height - NS_TOP_POS (f)
1192 [view setRows: rows andColumns: cols];
1193 [window setFrame: wr display: YES];
1195 /*fprintf (stderr, "\tx_set_window_size %d, %d\t%d, %d\n", cols, rows, pixelwidth, pixelheight); */
1197 /* This is a trick to compensate for Emacs' managing the scrollbar area
1198 as a fixed number of standard character columns. Instead of leaving
1199 blank space for the extra, we chopped it off above. Now for
1200 left-hand scrollbars, we shift all rendering to the left by the
1201 difference between the real width and Emacs' imagined one. For
1202 right-hand bars, don't worry about it since the extra is never used.
1203 (Obviously doesn't work for vertically split windows tho..) */
1204 NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1205 ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1206 - NS_SCROLL_BAR_WIDTH (f), 0)
1207 : NSMakePoint (0, 0);
1208 [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1209 [view setBoundsOrigin: origin];
1211 change_frame_size (f, rows, cols, 0, 1, 0); /* pretend, delay, safe */
1212 FRAME_PIXEL_WIDTH (f) = pixelwidth;
1213 FRAME_PIXEL_HEIGHT (f) = pixelheight;
1214 /* SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */
1216 mark_window_cursors_off (XWINDOW (f->root_window));
1217 cancel_mouse_face (f);
1224 /* ==========================================================================
1228 ========================================================================== */
1232 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1234 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1235 return color_table->colors[idx];
1240 ns_index_color (NSColor *color, struct frame *f)
1242 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1246 if (!color_table->colors)
1248 color_table->size = NS_COLOR_CAPACITY;
1249 color_table->avail = 1; /* skip idx=0 as marker */
1251 = (NSColor **)xmalloc (color_table->size * sizeof (NSColor *));
1252 color_table->empty_indices = [[NSMutableSet alloc] init];
1255 /* do we already have this color ? */
1258 for (i = 1; i < color_table->avail; i++)
1260 if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1262 [color_table->colors[i] retain];
1268 if ([color_table->empty_indices count] > 0)
1270 index = [color_table->empty_indices anyObject];
1271 [color_table->empty_indices removeObject: index];
1272 idx = [index unsignedIntValue];
1276 if (color_table->avail == color_table->size)
1278 color_table->size += NS_COLOR_CAPACITY;
1280 = (NSColor **)xrealloc (color_table->colors,
1281 color_table->size * sizeof (NSColor *));
1283 idx = color_table->avail++;
1286 color_table->colors[idx] = color;
1288 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1294 ns_free_indexed_color (unsigned long idx, struct frame *f)
1296 struct ns_color_table *color_table;
1303 color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1305 if (idx <= 0 || idx >= color_table->size) {
1306 message1("ns_free_indexed_color: Color index out of range.\n");
1310 index = [NSNumber numberWithUnsignedInt: idx];
1311 if ([color_table->empty_indices containsObject: index]) {
1312 message1("ns_free_indexed_color: attempt to free already freed color.\n");
1316 color = color_table->colors[idx];
1318 color_table->colors[idx] = nil;
1319 [color_table->empty_indices addObject: [NSNumber numberWithUnsignedInt: idx]];
1320 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1325 ns_get_color (const char *name, NSColor **col)
1326 /* --------------------------------------------------------------------------
1328 /* --------------------------------------------------------------------------
1329 /* On *Step, we recognize several color formats, in addition to a catalog
1330 of colors found in the file Emacs.clr. Color formats include:
1331 - #rrggbb or RGBrrggbb where rr, gg, bb specify red, green and blue in hex
1332 - ARGBaarrggbb is similar, with aa being the alpha channel (FF = opaque)
1333 - HSVhhssvv and AHSVaahhssvv (or HSB/AHSB) are similar for hue, saturation,
1335 - CMYKccmmyykk is similar for cyan, magenta, yellow, black. */
1337 NSColor * new = nil;
1338 const char *hex = NULL;
1339 enum { rgb, argb, hsv, ahsv, cmyk, gray } color_space;
1340 NSString *nsname = [NSString stringWithUTF8String: name];
1342 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1345 if ([nsname isEqualToString: @"ns_selection_color"])
1347 nsname = ns_selection_color;
1348 name = [ns_selection_color UTF8String];
1351 if (name[0] == '0' || name[0] == '1' || name[0] == '.')
1354 NSScanner *scanner = [NSScanner scannerWithString: nsname];
1356 [scanner scanFloat: &r];
1357 [scanner scanFloat: &g];
1358 [scanner scanFloat: &b];
1359 *col = [NSColor colorWithCalibratedRed: r green: g blue: b alpha: 1.0];
1364 /* FIXME: emacs seems to downcase everything before passing it here,
1365 which we can work around, except for GRAY, since gray##, where ## is
1366 decimal between 0 and 99, is also an X11 colorname. */
1367 if (name[0] == '#') /* X11 format */
1372 else if (!memcmp (name, "RGB", 3) || !memcmp (name, "rgb", 3))
1377 else if (!memcmp (name, "ARGB", 4) || !memcmp (name, "argb", 4))
1382 else if (!memcmp (name, "HSV", 3) || !memcmp (name, "hsv", 3) ||
1383 !memcmp (name, "HSB", 3) || !memcmp (name, "hsb", 3))
1388 else if (!memcmp (name, "AHSV", 4) || !memcmp (name, "ahsv", 4) ||
1389 !memcmp (name, "AHSB", 4) || !memcmp (name, "ahsb", 4))
1394 else if (!memcmp (name, "CMYK", 4) || !memcmp (name, "cmyk", 4))
1399 else if (!memcmp (name, "GRAY", 4) /*|| !memcmp (name, "gray", 4)*/)
1405 /* Direct colors (hex values) */
1408 unsigned long long color = 0;
1409 if (sscanf (hex, "%x", &color))
1411 float f1, f2, f3, f4;
1412 /* Assume it's either 1 byte or 2 per channel... */
1413 if (strlen(hex) > 8) {
1414 f1 = ((color >> 48) & 0xffff) / 65535.0;
1415 f2 = ((color >> 32) & 0xffff) / 65535.0;
1416 f3 = ((color >> 16) & 0xffff) / 65535.0;
1417 f4 = ((color ) & 0xffff) / 65535.0;
1419 f1 = ((color >> 24) & 0xff) / 255.0;
1420 f2 = ((color >> 16) & 0xff) / 255.0;
1421 f3 = ((color >> 8) & 0xff) / 255.0;
1422 f4 = ((color ) & 0xff) / 255.0;
1425 switch (color_space)
1428 *col = [NSColor colorWithCalibratedRed: f2
1434 *col = [NSColor colorWithCalibratedRed: f2
1440 *col = [NSColor colorWithCalibratedHue: f2
1446 *col = [NSColor colorWithCalibratedHue: f2
1452 *col = [NSColor colorWithCalibratedWhite: f3 alpha: f4];
1455 *col = [NSColor colorWithDeviceCyan: f1
1462 *col = [*col colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1468 /* Otherwise, color is expected to be from a list */
1470 NSEnumerator *lenum, *cenum;
1474 #ifdef NS_IMPL_GNUSTEP
1475 /* XXX: who is wrong, the requestor or the implementation? */
1476 if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1478 nsname = @"highlightColor";
1481 lenum = [[NSColorList availableColorLists] objectEnumerator];
1482 while ( (clist = [lenum nextObject]) && new == nil)
1484 cenum = [[clist allKeys] objectEnumerator];
1485 while ( (name = [cenum nextObject]) && new == nil )
1487 if ([name compare: nsname
1488 options: NSCaseInsensitiveSearch] == NSOrderedSame )
1489 new = [clist colorWithKey: name];
1495 *col = [new colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1497 NSLog (@"Failed to find color '%@'", nsname); */
1504 ns_get_color_default (const char *name, NSColor *dflt)
1505 /* --------------------------------------------------------------------------
1506 Parse a color or use a default value
1507 -------------------------------------------------------------------------- */
1511 if (ns_get_color (name, &col))
1519 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1520 /* --------------------------------------------------------------------------
1521 Convert a Lisp string object to a NS color
1522 -------------------------------------------------------------------------- */
1524 NSTRACE (ns_lisp_to_color);
1525 if (STRINGP (color))
1526 return ns_get_color (SDATA (color), col);
1527 else if (SYMBOLP (color))
1528 return ns_get_color (SDATA (SYMBOL_NAME (color)), col);
1534 ns_color_to_lisp (NSColor *col)
1535 /* --------------------------------------------------------------------------
1536 Convert a color to a lisp string with the RGB equivalent
1537 -------------------------------------------------------------------------- */
1539 float red, green, blue, alpha, gray;
1542 NSTRACE (ns_color_to_lisp);
1545 if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1547 if ((str =[[col colorNameComponent] UTF8String]))
1550 return build_string ((char *)str);
1553 [[col colorUsingColorSpaceName: NSCalibratedRGBColorSpace]
1554 getRed: &red green: &green blue: &blue alpha: &alpha];
1555 if (red ==green && red ==blue)
1557 [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1558 getWhite: &gray alpha: &alpha];
1559 snprintf (buf, sizeof (buf), "GRAY%02.2lx%02.2lx",
1560 lrint (gray * 0xff), lrint (alpha * 0xff));
1562 return build_string (buf);
1565 snprintf (buf, sizeof (buf), "ARGB%02.2lx%02.2lx%02.2lx%02.2lx",
1567 lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1570 return build_string (buf);
1575 ns_query_color(void *col, XColor *color_def, int setPixel)
1576 /* --------------------------------------------------------------------------
1577 Get ARGB values out of NSColor col and put them into color_def.
1578 If setPixel, set the pixel to a concatenated version.
1579 and set color_def pixel to the resulting index.
1580 -------------------------------------------------------------------------- */
1584 [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1585 color_def->red = r * 65535;
1586 color_def->green = g * 65535;
1587 color_def->blue = b * 65535;
1589 if (setPixel == YES)
1591 = ARGB_TO_ULONG((int)(a*255),
1592 (int)(r*255), (int)(g*255), (int)(b*255));
1597 ns_defined_color (struct frame *f, char *name, XColor *color_def, int alloc,
1599 /* --------------------------------------------------------------------------
1600 Return 1 if named color found, and set color_def rgb accordingly.
1601 If makeIndex and alloc are nonzero put the color in the color_table,
1602 and set color_def pixel to the resulting index.
1603 If makeIndex is zero, set color_def pixel to ARGB.
1604 Return 0 if not found
1605 -------------------------------------------------------------------------- */
1608 int notFound = ns_get_color (name, &temp);
1610 NSTRACE (ns_defined_color);
1615 if (makeIndex && alloc)
1616 color_def->pixel = ns_index_color(temp, f); /* [temp retain]; */
1618 ns_query_color (temp, color_def, !makeIndex);
1625 ns_get_rgb_color (struct frame *f, float r, float g, float b, float a)
1626 /* --------------------------------------------------------------------------
1627 return an autoreleased RGB color
1628 -------------------------------------------------------------------------- */
1630 /*static int c = 1; fprintf (stderr, "color request %d\n", c++); */
1631 if (r < 0.0) r = 0.0;
1632 else if (r > 1.0) r = 1.0;
1633 if (g < 0.0) g = 0.0;
1634 else if (g > 1.0) g = 1.0;
1635 if (b < 0.0) b = 0.0;
1636 else if (b > 1.0) b = 1.0;
1637 if (a < 0.0) a = 0.0;
1638 else if (a > 1.0) a = 1.0;
1639 return (unsigned long) ns_index_color(
1640 [NSColor colorWithCalibratedRed: r green: g blue: b alpha: a], f);
1645 x_set_frame_alpha (struct frame *f)
1646 /* --------------------------------------------------------------------------
1647 change the entire-frame transparency
1648 -------------------------------------------------------------------------- */
1650 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1651 EmacsView *view = FRAME_NS_VIEW (f);
1653 double alpha_min = 1.0;
1655 if (dpyinfo->x_highlight_frame == f)
1656 alpha = f->alpha[0];
1658 alpha = f->alpha[1];
1660 if (FLOATP (Vframe_alpha_lower_limit))
1661 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1662 else if (INTEGERP (Vframe_alpha_lower_limit))
1663 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1667 else if (1.0 < alpha)
1669 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1672 #ifdef NS_IMPL_COCOA
1673 [[view window] setAlphaValue: alpha];
1678 /* ==========================================================================
1682 ========================================================================== */
1686 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1687 /* --------------------------------------------------------------------------
1688 Programmatically reposition mouse pointer in pixel coordinates
1689 -------------------------------------------------------------------------- */
1691 NSTRACE (x_set_mouse_pixel_position);
1694 /* FIXME: this does not work, and what about GNUstep? */
1695 #ifdef NS_IMPL_COCOA
1696 [FRAME_NS_VIEW (f) lockFocus];
1697 PSsetmouse ((float)pix_x, (float)pix_y);
1698 [FRAME_NS_VIEW (f) unlockFocus];
1705 x_set_mouse_position (struct frame *f, int h, int v)
1706 /* --------------------------------------------------------------------------
1707 Programmatically reposition mouse pointer in character coordinates
1708 -------------------------------------------------------------------------- */
1712 pix_x = FRAME_COL_TO_PIXEL_X (f, h) + FRAME_COLUMN_WIDTH (f) / 2;
1713 pix_y = FRAME_LINE_TO_PIXEL_Y (f, v) + FRAME_LINE_HEIGHT (f) / 2;
1715 if (pix_x < 0) pix_x = 0;
1716 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
1718 if (pix_y < 0) pix_y = 0;
1719 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
1721 x_set_mouse_pixel_position (f, pix_x, pix_y);
1726 note_mouse_movement (struct frame *frame, float x, float y)
1727 /* ------------------------------------------------------------------------
1728 Called by EmacsView on mouseMovement events. Passes on
1729 to emacs mainstream code if we moved off of a rect of interest
1730 known as last_mouse_glyph.
1731 ------------------------------------------------------------------------ */
1733 // NSTRACE (note_mouse_movement);
1735 XSETFRAME (last_mouse_motion_frame, frame);
1737 /* Note, this doesn't get called for enter/leave, since we don't have a
1738 position. Those are taken care of in the corresponding NSView methods. */
1740 /* has movement gone beyond last rect we were tracking? */
1741 if (x < last_mouse_glyph.origin.x ||
1742 x >= (last_mouse_glyph.origin.x + last_mouse_glyph.size.width) ||
1743 y < last_mouse_glyph.origin.y ||
1744 y >= (last_mouse_glyph.origin.y + last_mouse_glyph.size.height))
1746 frame->mouse_moved = 1;
1747 note_mouse_highlight (frame, x, y);
1748 remember_mouse_glyph (frame, x, y, &last_mouse_glyph);
1757 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1758 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1759 unsigned long *time)
1760 /* --------------------------------------------------------------------------
1761 External (hook): inform emacs about mouse position and hit parts.
1762 If a scrollbar is being dragged, set bar_window, part, x, y, time.
1763 x & y should be position in the scrollbar (the whole bar, not the handle)
1764 and length of scrollbar respectively
1765 -------------------------------------------------------------------------- */
1770 Lisp_Object frame, tail;
1772 struct ns_display_info *dpyinfo;
1774 NSTRACE (ns_mouse_position);
1778 fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1782 dpyinfo = FRAME_NS_DISPLAY_INFO (*fp);
1786 if (last_mouse_scroll_bar != nil && insist == 0)
1788 /* TODO: we do not use this path at the moment because drag events will
1789 go directly to the EmacsScroller. Leaving code in for now. */
1790 [last_mouse_scroll_bar getMouseMotionPart: (int *)part window: bar_window
1792 if (time) *time = last_mouse_movement_time;
1793 last_mouse_scroll_bar = nil;
1797 /* Clear the mouse-moved flag for every frame on this display. */
1798 FOR_EACH_FRAME (tail, frame)
1799 if (FRAME_NS_P (XFRAME (frame))
1800 && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1801 XFRAME (frame)->mouse_moved = 0;
1803 last_mouse_scroll_bar = nil;
1804 if (last_mouse_frame && FRAME_LIVE_P (last_mouse_frame))
1805 f = last_mouse_frame;
1807 f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame
1808 : SELECTED_FRAME ();
1810 if (f && f->output_data.ns) /* TODO: 2nd check no longer needed? */
1812 view = FRAME_NS_VIEW (*fp);
1814 position = [[view window] mouseLocationOutsideOfEventStream];
1815 position = [view convertPoint: position fromView: nil];
1816 remember_mouse_glyph (f, position.x, position.y, &last_mouse_glyph);
1817 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1819 if (bar_window) *bar_window = Qnil;
1820 if (part) *part = 0; /*scroll_bar_handle; */
1822 if (x) XSETINT (*x, lrint (position.x));
1823 if (y) XSETINT (*y, lrint (position.y));
1824 if (time) *time = last_mouse_movement_time;
1834 ns_frame_up_to_date (struct frame *f)
1835 /* --------------------------------------------------------------------------
1836 External (hook): Fix up mouse highlighting right after a full update.
1837 Some highlighting was deferred if GC was happening during
1838 note_mouse_highlight (), while other highlighting was deferred for update.
1839 -------------------------------------------------------------------------- */
1841 NSTRACE (ns_frame_up_to_date);
1845 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1846 if ((dpyinfo->mouse_face_deferred_gc||f ==dpyinfo->mouse_face_mouse_frame)
1847 /*&& dpyinfo->mouse_face_mouse_frame*/)
1850 if (dpyinfo->mouse_face_mouse_frame)
1851 note_mouse_highlight (dpyinfo->mouse_face_mouse_frame,
1852 dpyinfo->mouse_face_mouse_x,
1853 dpyinfo->mouse_face_mouse_y);
1854 dpyinfo->mouse_face_deferred_gc = 0;
1862 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1863 /* --------------------------------------------------------------------------
1864 External (RIF): set frame mouse pointer type.
1865 -------------------------------------------------------------------------- */
1867 NSTRACE (ns_define_frame_cursor);
1868 if (FRAME_POINTER_TYPE (f) != cursor)
1870 EmacsView *view = FRAME_NS_VIEW (f);
1871 FRAME_POINTER_TYPE (f) = cursor;
1872 [[view window] invalidateCursorRectsForView: view];
1878 /* ==========================================================================
1882 ========================================================================== */
1886 ns_convert_key (unsigned code)
1887 /* --------------------------------------------------------------------------
1888 Internal call used by NSView-keyDown.
1889 -------------------------------------------------------------------------- */
1891 const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym)
1892 / sizeof (convert_ns_to_X_keysym[0]));
1894 /* An array would be faster, but less easy to read. */
1895 for (keysym = 0; keysym < last_keysym; keysym += 2)
1896 if (code == convert_ns_to_X_keysym[keysym])
1897 return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
1899 /* if decide to use keyCode and Carbon table, use this line:
1900 return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
1905 x_get_keysym_name (int keysym)
1906 /* --------------------------------------------------------------------------
1907 Called by keyboard.c. Not sure if the return val is important, except
1909 -------------------------------------------------------------------------- */
1911 static char value[16];
1912 NSTRACE (x_get_keysym_name);
1913 sprintf (value, "%d", keysym);
1919 /* ==========================================================================
1921 Block drawing operations
1923 ========================================================================== */
1927 ns_redraw_scroll_bars (struct frame *f)
1931 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
1932 NSTRACE (ns_judge_scroll_bars);
1933 for (i =[subviews count]-1; i >= 0; i--)
1935 view = [subviews objectAtIndex: i];
1936 if (![view isKindOfClass: [EmacsScroller class]]) continue;
1943 ns_clear_frame (struct frame *f)
1944 /* --------------------------------------------------------------------------
1945 External (hook): Erase the entire frame
1946 -------------------------------------------------------------------------- */
1948 NSView *view = FRAME_NS_VIEW (f);
1951 NSTRACE (ns_clear_frame);
1955 /* comes on initial frame because we have
1956 after-make-frame-functions = select-frame */
1957 if (!FRAME_DEFAULT_FACE (f))
1960 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
1962 output_cursor.hpos = output_cursor.vpos = 0;
1963 output_cursor.x = -1;
1968 ns_focus (f, &r, 1);
1969 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
1973 #ifdef NS_IMPL_COCOA
1974 [[view window] display]; /* redraw resize handle */
1977 /* as of 2006/11 or so this is now needed */
1978 ns_redraw_scroll_bars (f);
1984 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
1985 /* --------------------------------------------------------------------------
1986 External (RIF): Clear section of frame
1987 -------------------------------------------------------------------------- */
1989 NSRect r = NSMakeRect (x, y, width, height);
1990 NSView *view = FRAME_NS_VIEW (f);
1991 struct face *face = FRAME_DEFAULT_FACE (f);
1996 NSTRACE (ns_clear_frame_area);
1998 r = NSIntersectionRect (r, [view frame]);
1999 ns_focus (f, &r, 1);
2000 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2002 #ifdef NS_IMPL_COCOA
2004 /* clip out the resize handle */
2005 NSWindow *window = [FRAME_NS_VIEW (f) window];
2007 = [view convertRect: ns_resize_handle_rect (window) fromView: nil];
2009 ir = NSIntersectionRect (r, ir);
2010 if (NSIsEmptyRect (ir))
2016 #ifdef NS_IMPL_COCOA
2020 NSRect r1 = r, r2 = r; /* upper and lower non-intersecting */
2021 r1.size.height -= ir.size.height;
2022 r2.origin.y += r1.size.height;
2023 r2.size.width -= ir.size.width;
2024 r2.size.height = ir.size.height;
2037 ns_scroll_run (struct window *w, struct run *run)
2038 /* --------------------------------------------------------------------------
2039 External (RIF): Insert or delete n lines at line vpos
2040 -------------------------------------------------------------------------- */
2042 struct frame *f = XFRAME (w->frame);
2043 int x, y, width, height, from_y, to_y, bottom_y;
2045 NSTRACE (ns_scroll_run);
2047 /* begin copy from other terms */
2048 /* Get frame-relative bounding box of the text display area of W,
2049 without mode lines. Include in this box the left and right
2051 window_box (w, -1, &x, &y, &width, &height);
2053 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2054 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2055 bottom_y = y + height;
2059 /* Scrolling up. Make sure we don't copy part of the mode
2060 line at the bottom. */
2061 if (from_y + run->height > bottom_y)
2062 height = bottom_y - from_y;
2064 height = run->height;
2068 /* Scolling down. Make sure we don't copy over the mode line.
2070 if (to_y + run->height > bottom_y)
2071 height = bottom_y - to_y;
2073 height = run->height;
2075 /* end copy from other terms */
2086 NSRect srcRect = NSMakeRect (x, from_y, width, height);
2087 NSRect dstRect = NSMakeRect (x, to_y, width, height);
2088 NSPoint dstOrigin = NSMakePoint (x, to_y);
2090 ns_focus (f, &dstRect, 1);
2091 NSCopyBits (0, srcRect , dstOrigin);
2100 ns_after_update_window_line (struct glyph_row *desired_row)
2101 /* --------------------------------------------------------------------------
2102 External (RIF): preparatory to fringe update after text was updated
2103 -------------------------------------------------------------------------- */
2105 struct window *w = updated_window;
2109 NSTRACE (ns_after_update_window_line);
2111 /* begin copy from other terms */
2114 if (!desired_row->mode_line_p && !w->pseudo_window_p)
2115 desired_row->redraw_fringe_bitmaps_p = 1;
2117 /* When a window has disappeared, make sure that no rest of
2118 full-width rows stays visible in the internal border.
2119 Under NS this is drawn inside the fringes. */
2120 if (windows_or_buffers_changed
2121 && (f = XFRAME (w->frame),
2122 width = FRAME_INTERNAL_BORDER_WIDTH (f),
2124 && (height = desired_row->visible_height,
2127 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2129 /* Internal border is drawn below the tool bar. */
2130 if (WINDOWP (f->tool_bar_window)
2131 && w == XWINDOW (f->tool_bar_window))
2133 /* end copy from other terms */
2136 if (!desired_row->full_width_p)
2138 int x1 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2139 + WINDOW_LEFT_FRINGE_WIDTH (w);
2140 int x2 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2141 + FRAME_PIXEL_WIDTH (f) - NS_SCROLL_BAR_WIDTH (f)
2142 - WINDOW_RIGHT_FRINGE_WIDTH (w)
2143 - FRAME_INTERNAL_BORDER_WIDTH (f);
2144 ns_clear_frame_area (f, x1, y, width, height);
2145 ns_clear_frame_area (f, x2, y, width, height);
2153 ns_shift_glyphs_for_insert (struct frame *f,
2154 int x, int y, int width, int height,
2156 /* --------------------------------------------------------------------------
2157 External (RIF): copy an area horizontally, don't worry about clearing src
2158 -------------------------------------------------------------------------- */
2160 NSRect srcRect = NSMakeRect (x, y, width, height);
2161 NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2162 NSPoint dstOrigin = dstRect.origin;
2164 NSTRACE (ns_shift_glyphs_for_insert);
2166 ns_focus (f, &dstRect, 1);
2167 NSCopyBits (0, srcRect, dstOrigin);
2173 /* ==========================================================================
2175 Character encoding and metrics
2177 ========================================================================== */
2181 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2182 /* --------------------------------------------------------------------------
2183 External (RIF); compute left/right overhang of whole string and set in s
2184 -------------------------------------------------------------------------- */
2186 struct face *face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2187 struct font *font = s->font; /*face->font; */
2191 struct font_metrics metrics;
2192 unsigned int codes[2];
2193 codes[0] = *(s->char2b);
2194 codes[1] = *(s->char2b + s->nchars - 1);
2196 font->driver->text_extents (font, codes, 2, &metrics);
2197 s->left_overhang = -metrics.lbearing;
2199 = metrics.rbearing > metrics.width
2200 ? metrics.rbearing - metrics.width : 0;
2204 s->left_overhang = 0;
2205 s->right_overhang = ((struct nsfont_info *)font)->ital ?
2206 FONT_HEIGHT (font) * 0.2 : 0;
2212 /* ==========================================================================
2214 Fringe and cursor drawing
2216 ========================================================================== */
2219 extern int max_used_fringe_bitmap;
2221 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2222 struct draw_fringe_bitmap_params *p)
2223 /* --------------------------------------------------------------------------
2224 External (RIF); fringe-related
2225 -------------------------------------------------------------------------- */
2227 struct frame *f = XFRAME (WINDOW_FRAME (w));
2228 struct face *face = p->face;
2230 static EmacsImage **bimgs = NULL;
2231 static int nBimgs = 0;
2232 /* NS-specific: move internal border inside fringe */
2233 int x = p->bx < 0 ? p->x : p->bx;
2234 int wd = p->bx < 0 ? p->wd : p->nx;
2235 BOOL fringeOnVeryLeft
2236 = x - WINDOW_LEFT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w)
2237 - FRAME_INTERNAL_BORDER_WIDTH (f) < 10;
2238 BOOL fringeOnVeryRight
2239 = FRAME_PIXEL_WIDTH (f) - x - wd - FRAME_INTERNAL_BORDER_WIDTH (f)
2240 - WINDOW_RIGHT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w) < 10;
2241 int xAdjust = FRAME_INTERNAL_BORDER_WIDTH (f) *
2242 (fringeOnVeryLeft ? -1 : (fringeOnVeryRight ? 1 : 0));
2244 /* grow bimgs if needed */
2245 if (nBimgs < max_used_fringe_bitmap)
2247 EmacsImage **newBimgs
2248 = xmalloc (max_used_fringe_bitmap * sizeof (EmacsImage *));
2249 bzero (newBimgs, max_used_fringe_bitmap * sizeof (EmacsImage *));
2253 bcopy (bimgs, newBimgs, nBimgs * sizeof (EmacsImage *));
2258 nBimgs = max_used_fringe_bitmap;
2261 /* Must clip because of partially visible lines. */
2262 rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
2265 /* Adjust position of "bottom aligned" bitmap on partially
2266 visible last row. */
2268 int oldVH = row->visible_height;
2269 row->visible_height = p->h;
2270 row->y -= rowY - p->y;
2271 ns_clip_to_row (w, row, -1, NO);
2273 row->visible_height = oldVH;
2276 ns_clip_to_row (w, row, -1, YES);
2278 if (p->bx >= 0 && !p->overlay_p)
2280 int yAdjust = rowY - FRAME_INTERNAL_BORDER_WIDTH (f) < 5 ?
2281 -FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2282 int yIncr = FRAME_PIXEL_HEIGHT (f) - (p->by+yAdjust + p->ny) < 5 ?
2283 FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2285 yIncr += FRAME_INTERNAL_BORDER_WIDTH (f);
2286 NSRect r = NSMakeRect (p->bx+xAdjust, p->by+yAdjust, p->nx, p->ny+yIncr);
2288 [ns_lookup_indexed_color(face->background, f) set];
2294 NSRect r = NSMakeRect (p->x+xAdjust, p->y, p->wd, p->h);
2295 NSPoint pt = r.origin;
2296 EmacsImage *img = bimgs[p->which - 1];
2300 unsigned short *bits = p->bits + p->dh;
2301 int len = 8 * p->h/8;
2303 unsigned char *cbits = xmalloc (len);
2305 for (i =0; i<len; i++)
2306 cbits[i] = ~(bits[i] & 0xff);
2307 img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2309 bimgs[p->which - 1] = img;
2314 /* Since we composite the bitmap instead of just blitting it, we need
2315 to erase the whole background. */
2316 [ns_lookup_indexed_color(face->background, f) set];
2319 [img setXBMColor: ns_lookup_indexed_color(face->foreground, f)];
2320 [img compositeToPoint: pt operation: NSCompositeSourceOver];
2327 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2328 int x, int y, int cursor_type, int cursor_width,
2329 int on_p, int active_p)
2330 /* --------------------------------------------------------------------------
2331 External call (RIF): draw cursor
2332 (modeled after x_draw_window_cursor
2333 FIXME: cursor_width is effectively bogus -- it sometimes gets set
2334 in xdisp.c set_frame_cursor_types, sometimes left uninitialized;
2335 DON'T USE IT (no other terms do)
2336 -------------------------------------------------------------------------- */
2340 struct frame *f = WINDOW_XFRAME (w);
2341 struct glyph *phys_cursor_glyph;
2342 int overspill, cursorToDraw;
2344 NSTRACE (dumpcursor);
2345 //fprintf(stderr, "drawcursor (%d,%d) activep = %d\tonp = %d\tc_type = %d\twidth = %d\n",x,y, active_p,on_p,cursor_type,cursor_width);
2350 w->phys_cursor_type = cursor_type;
2351 w->phys_cursor_on_p = on_p;
2353 if (cursor_type == NO_CURSOR)
2355 w->phys_cursor_width = 0;
2359 if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2361 if (glyph_row->exact_window_width_line_p
2362 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2364 glyph_row->cursor_in_fringe_p = 1;
2365 draw_fringe_bitmap (w, glyph_row, 0);
2370 get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2372 r.origin.x = fx, r.origin.y = fy;
2374 r.size.width = w->phys_cursor_width;
2376 /* FIXME: if we overwrite the internal border area, it does not get erased;
2377 fix by truncating cursor, but better would be to erase properly */
2378 overspill = r.origin.x + r.size.width -
2379 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, WINDOW_BOX_RIGHT_EDGE_X (w)
2380 - WINDOW_TOTAL_FRINGE_WIDTH (w) - FRAME_INTERNAL_BORDER_WIDTH (f));
2382 r.size.width -= overspill;
2384 /* TODO: only needed in rare cases with last-resort font in HELLO..
2385 should we do this more efficiently? */
2386 ns_clip_to_row (w, glyph_row, -1, NO); /* do ns_focus(f, &r, 1); if remove */
2387 [FRAME_CURSOR_COLOR (f) set];
2389 #ifdef NS_IMPL_COCOA
2390 /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2391 atomic. Cleaner ways of doing this should be investigated.
2392 One way would be to set a global variable DRAWING_CURSOR
2393 when making the call to draw_phys..(), don't focus in that
2394 case, then move the ns_unfocus() here after that call. */
2395 NSDisableScreenUpdates ();
2398 cursorToDraw = active_p ? cursor_type : HOLLOW_BOX_CURSOR;
2399 switch (cursorToDraw)
2403 case FILLED_BOX_CURSOR:
2406 case HOLLOW_BOX_CURSOR:
2408 [FRAME_BACKGROUND_COLOR (f) set];
2409 NSRectFill (NSInsetRect (r, 1, 1));
2410 [FRAME_CURSOR_COLOR (f) set];
2414 s.origin.y += lrint (0.75 * s.size.height);
2415 s.size.width = min (FRAME_COLUMN_WIDTH (f), s.size.width);
2416 s.size.height = lrint (s.size.height * 0.25);
2421 s.size.width = min (cursor_width, 2); //FIXME(see above)
2427 /* draw the character under the cursor */
2428 if (cursorToDraw != NO_CURSOR)
2429 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2431 #ifdef NS_IMPL_COCOA
2432 NSEnableScreenUpdates ();
2439 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2440 /* --------------------------------------------------------------------------
2441 External (RIF): Draw a vertical line.
2442 -------------------------------------------------------------------------- */
2444 struct frame *f = XFRAME (WINDOW_FRAME (w));
2446 NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2448 NSTRACE (ns_draw_vertical_window_border);
2450 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2452 [ns_lookup_indexed_color(face->foreground, f) set];
2454 ns_focus (f, &r, 1);
2461 show_hourglass (struct atimer *timer)
2463 if (hourglass_shown_p)
2468 /* TODO: add NSProgressIndicator to selected frame (see macfns.c) */
2470 hourglass_shown_p = 1;
2478 if (!hourglass_shown_p)
2483 /* TODO: remove NSProgressIndicator from all frames */
2485 hourglass_shown_p = 0;
2491 /* ==========================================================================
2493 Glyph drawing operations
2495 ========================================================================== */
2498 static inline NSRect
2499 ns_fix_rect_ibw (NSRect r, int fibw, int frame_pixel_width)
2500 /* --------------------------------------------------------------------------
2501 Under NS we draw internal borders inside fringes, and want full-width
2502 rendering to go all the way to edge. This function makes that correction.
2503 -------------------------------------------------------------------------- */
2505 if (r.origin.y <= fibw+1)
2507 r.size.height += r.origin.y;
2510 if (r.origin.x <= fibw+1)
2512 r.size.width += r.origin.x;
2515 if (frame_pixel_width - (r.origin.x+r.size.width) <= fibw+1)
2516 r.size.width += fibw;
2523 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2524 /* --------------------------------------------------------------------------
2525 Wrapper utility to account for internal border width on full-width lines,
2526 and allow top full-width rows to hit the frame top. nr should be pointer
2527 to two successive NSRects. Number of rects actually used is returned.
2528 -------------------------------------------------------------------------- */
2530 int n = get_glyph_string_clip_rects (s, nr, 2);
2531 if (s->row->full_width_p)
2533 *nr = ns_fix_rect_ibw (*nr, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2534 FRAME_PIXEL_WIDTH (s->f));
2536 *nr = ns_fix_rect_ibw (*(nr+1), FRAME_INTERNAL_BORDER_WIDTH (s->f),
2537 FRAME_PIXEL_WIDTH (s->f));
2544 ns_draw_box (NSRect r, float thickness, NSColor *col, char left_p, char right_p)
2545 /* --------------------------------------------------------------------------
2546 Draw an unfilled rect inside r, optionally leaving left and/or right open.
2547 Note we can't just use an NSDrawRect command, because of the possibility
2548 of some sides not being drawn, and because the rect will be filled.
2549 -------------------------------------------------------------------------- */
2555 s.size.height = thickness;
2557 s.origin.y += r.size.height - thickness;
2560 s.size.height = r.size.height;
2561 s.origin.y = r.origin.y;
2563 /* left, right (optional) */
2564 s.size.width = thickness;
2569 s.origin.x += r.size.width - thickness;
2576 ns_draw_relief (NSRect r, int thickness, char raised_p,
2577 char top_p, char bottom_p, char left_p, char right_p,
2578 struct glyph_string *s)
2579 /* --------------------------------------------------------------------------
2580 Draw a relief rect inside r, optionally leaving some sides open.
2581 Note we can't just use an NSDrawBezel command, because of the possibility
2582 of some sides not being drawn, and because the rect will be filled.
2583 -------------------------------------------------------------------------- */
2585 static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2586 NSColor *newBaseCol = nil;
2589 NSTRACE (ns_draw_relief);
2593 if (s->face->use_box_color_for_shadows_p)
2595 newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2597 /* else if (s->first_glyph->type == IMAGE_GLYPH
2599 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2601 newBaseCol = IMAGE_BACKGROUND (s->img, s->f, 0);
2605 newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2608 if (newBaseCol == nil)
2609 newBaseCol = [NSColor grayColor];
2611 if (newBaseCol != baseCol) /* TODO: better check */
2614 baseCol = [newBaseCol retain];
2616 lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2618 darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2621 [(raised_p ? lightCol : darkCol) set];
2623 /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2626 sr.size.height = thickness;
2627 if (top_p) NSRectFill (sr);
2630 sr.size.height = r.size.height;
2631 sr.size.width = thickness;
2632 if (left_p) NSRectFill (sr);
2634 [(raised_p ? darkCol : lightCol) set];
2637 sr.size.width = r.size.width;
2638 sr.size.height = thickness;
2639 sr.origin.y += r.size.height - thickness;
2640 if (bottom_p) NSRectFill (sr);
2643 sr.size.height = r.size.height;
2644 sr.origin.y = r.origin.y;
2645 sr.size.width = thickness;
2646 sr.origin.x += r.size.width - thickness;
2647 if (right_p) NSRectFill (sr);
2652 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2653 /* --------------------------------------------------------------------------
2654 Function modeled after x_draw_glyph_string_box ().
2655 Sets up parameters for drawing.
2656 -------------------------------------------------------------------------- */
2658 int right_x, last_x;
2659 char left_p, right_p;
2660 struct glyph *last_glyph;
2665 if (s->hl == DRAW_MOUSE_FACE)
2668 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2670 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2675 thickness = face->box_line_width;
2677 NSTRACE (ns_dumpglyphs_box_or_relief);
2679 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2680 ? WINDOW_RIGHT_EDGE_X (s->w)
2681 : window_box_right (s->w, s->area));
2682 last_glyph = (s->cmp || s->img
2683 ? s->first_glyph : s->first_glyph + s->nchars-1);
2685 right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2686 ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2688 left_p = (s->first_glyph->left_box_line_p
2689 || (s->hl == DRAW_MOUSE_FACE
2690 && (s->prev == NULL || s->prev->hl != s->hl)));
2691 right_p = (last_glyph->right_box_line_p
2692 || (s->hl == DRAW_MOUSE_FACE
2693 && (s->next == NULL || s->next->hl != s->hl)));
2695 r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2697 /* expand full-width row over internal borders */
2698 if (s->row->full_width_p)
2699 r = ns_fix_rect_ibw (r, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2700 FRAME_PIXEL_WIDTH (s->f));
2702 if (s->face->box == FACE_SIMPLE_BOX)
2704 xassert (s->face->box_color != nil);
2705 ns_draw_box (r, abs (thickness),
2706 ns_lookup_indexed_color (face->box_color, s->f),
2711 ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2712 1, 1, left_p, right_p, s);
2718 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2719 /* --------------------------------------------------------------------------
2720 Modeled after x_draw_glyph_string_background, which draws BG in
2721 certain cases. Others are left to the text rendering routine.
2722 -------------------------------------------------------------------------- */
2724 NSTRACE (ns_maybe_dumpglyphs_background);
2726 if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2728 int box_line_width = max (s->face->box_line_width, 0);
2729 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2730 || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2733 if (s->hl == DRAW_MOUSE_FACE)
2736 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2738 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2741 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2743 [(NS_FACE_BACKGROUND (face) != 0
2744 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2745 : FRAME_BACKGROUND_COLOR (s->f)) set];
2748 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (s->f);
2749 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2752 if (s->hl != DRAW_CURSOR)
2754 NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2755 s->background_width,
2756 s->height-2*box_line_width);
2758 /* expand full-width row over internal borders */
2759 if (s->row->full_width_p)
2761 int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2762 if (r.origin.y <= fibw+1 + box_line_width)
2764 r.size.height += r.origin.y;
2767 if (r.origin.x <= fibw+1)
2769 r.size.width += 2*r.origin.x;
2772 if (FRAME_PIXEL_WIDTH (s->f) - (r.origin.x + r.size.width)
2774 r.size.width += fibw;
2780 s->background_filled_p = 1;
2787 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2788 /* --------------------------------------------------------------------------
2789 Renders an image and associated borders.
2790 -------------------------------------------------------------------------- */
2792 EmacsImage *img = s->img->pixmap;
2793 int box_line_vwidth = max (s->face->box_line_width, 0);
2794 int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2795 int bg_x, bg_y, bg_height;
2800 NSTRACE (ns_dumpglyphs_image);
2802 if (s->face->box != FACE_NO_BOX
2803 && s->first_glyph->left_box_line_p && s->slice.x == 0)
2804 x += abs (s->face->box_line_width);
2807 bg_y = s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2808 bg_height = s->height;
2809 /* other terms have this, but was causing problems w/tabbar mode */
2810 /* - 2 * box_line_vwidth; */
2812 if (s->slice.x == 0) x += s->img->hmargin;
2813 if (s->slice.y == 0) y += s->img->vmargin;
2815 /* Draw BG: if we need larger area than image itself cleared, do that,
2816 otherwise, since we composite the image under NS (instead of mucking
2817 with its background color), we must clear just the image area. */
2818 [ns_lookup_indexed_color (NS_FACE_BACKGROUND
2819 (FACE_FROM_ID (s->f, s->first_glyph->face_id)), s->f) set];
2821 if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
2822 || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
2824 br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
2825 s->background_filled_p = 1;
2829 br = NSMakeRect (x, y, s->slice.width, s->slice.height);
2832 /* expand full-width row over internal borders */
2833 if (s->row->full_width_p)
2835 int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2836 if (br.origin.y <= fibw+1 + box_line_vwidth)
2838 br.size.height += br.origin.y;
2841 if (br.origin.x <= fibw+1 + box_line_vwidth)
2843 br.size.width += br.origin.x;
2846 if (FRAME_PIXEL_WIDTH (s->f) - (br.origin.x + br.size.width) <= fibw+1)
2847 br.size.width += fibw;
2852 /* Draw the image.. do we need to draw placeholder if img ==nil? */
2854 [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
2855 operation: NSCompositeSourceOver];
2857 /* Draw relief, if requested */
2858 if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
2860 if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
2862 th = tool_bar_button_relief >= 0 ?
2863 tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2864 raised_p = (s->hl == DRAW_IMAGE_RAISED);
2868 th = abs (s->img->relief);
2869 raised_p = (s->img->relief > 0);
2872 r.origin.x = x - th;
2873 r.origin.y = y - th;
2874 r.size.width = s->slice.width + 2*th-1;
2875 r.size.height = s->slice.height + 2*th-1;
2876 ns_draw_relief (r, th, raised_p,
2878 s->slice.y + s->slice.height == s->img->height,
2880 s->slice.x + s->slice.width == s->img->width, s);
2886 ns_dumpglyphs_stretch (struct glyph_string *s)
2891 if (!s->background_filled_p)
2893 n = ns_get_glyph_string_clip_rect (s, r);
2894 *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
2898 if (!s->row->full_width_p)
2900 /* truncate to avoid overwriting fringe and/or scrollbar */
2901 int overrun = max (0, (s->x + s->background_width)
2902 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
2903 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
2904 r[i].size.width -= overrun;
2906 /* XXX: Try to work between problem where a stretch glyph on
2907 a partially-visible bottom row will clear part of the
2908 modeline, and another where list-buffers headers and similar
2909 rows erroneously have visible_height set to 0. Not sure
2910 where this is coming from as other terms seem not to show. */
2911 r[i].size.height = min (s->height, s->row->visible_height);
2914 /* expand full-width rows over internal borders */
2917 r[i] = ns_fix_rect_ibw (r[i], FRAME_INTERNAL_BORDER_WIDTH (s->f),
2918 FRAME_PIXEL_WIDTH (s->f));
2921 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
2922 overwriting cursor (usually when cursor on a tab) */
2923 if (s->hl == DRAW_CURSOR)
2925 r[i].origin.x += s->width;
2926 r[i].size.width -= s->width;
2930 ns_focus (s->f, r, n);
2931 [ns_lookup_indexed_color (NS_FACE_BACKGROUND
2932 (FACE_FROM_ID (s->f, s->first_glyph->face_id)), s->f) set];
2936 s->background_filled_p = 1;
2942 ns_draw_glyph_string (struct glyph_string *s)
2943 /* --------------------------------------------------------------------------
2944 External (RIF): Main draw-text call.
2945 -------------------------------------------------------------------------- */
2947 /* TODO (optimize): focus for box and contents draw */
2950 char box_drawn_p = 0;
2952 NSTRACE (ns_draw_glyph_string);
2954 if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
2957 struct glyph_string *next;
2959 for (width = 0, next = s->next;
2960 next && width < s->right_overhang;
2961 width += next->width, next = next->next)
2962 if (next->first_glyph->type != IMAGE_GLYPH)
2964 if (next->first_glyph->type != STRETCH_GLYPH)
2966 n = ns_get_glyph_string_clip_rect (s->next, r);
2967 ns_focus (s->f, r, n);
2968 ns_maybe_dumpglyphs_background (s->next, 1);
2973 ns_dumpglyphs_stretch (s->next);
2975 next->num_clips = 0;
2979 if (!s->for_overlaps && s->face->box != FACE_NO_BOX
2980 && (s->first_glyph->type == CHAR_GLYPH
2981 || s->first_glyph->type == COMPOSITE_GLYPH))
2983 n = ns_get_glyph_string_clip_rect (s, r);
2984 ns_focus (s->f, r, n);
2985 ns_maybe_dumpglyphs_background (s, 1);
2986 ns_dumpglyphs_box_or_relief (s);
2991 switch (s->first_glyph->type)
2995 n = ns_get_glyph_string_clip_rect (s, r);
2996 ns_focus (s->f, r, n);
2997 ns_dumpglyphs_image (s, r[0]);
3002 ns_dumpglyphs_stretch (s);
3006 case COMPOSITE_GLYPH:
3007 n = ns_get_glyph_string_clip_rect (s, r);
3008 ns_focus (s->f, r, n);
3010 if (s->for_overlaps || (s->cmp_from > 0
3011 && ! s->first_glyph->u.cmp.automatic))
3012 s->background_filled_p = 1;
3014 ns_maybe_dumpglyphs_background
3015 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3017 ns_tmp_flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3018 (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3019 (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3020 NS_DUMPGLYPH_NORMAL));
3021 ns_tmp_font = (struct nsfont_info *)s->face->font;
3022 if (ns_tmp_font == NULL)
3023 ns_tmp_font = (struct nsfont_info *)FRAME_FONT (s->f);
3025 ns_tmp_font->font.driver->draw
3026 (s, 0, s->nchars, s->x, s->y,
3027 (ns_tmp_flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3028 || ns_tmp_flags == NS_DUMPGLYPH_MOUSEFACE);
3037 /* Draw box if not done already. */
3038 if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3040 n = ns_get_glyph_string_clip_rect (s, r);
3041 ns_focus (s->f, r, n);
3042 ns_dumpglyphs_box_or_relief (s);
3051 /* ==========================================================================
3055 ========================================================================== */
3059 ns_send_appdefined (int value)
3060 /* --------------------------------------------------------------------------
3061 Internal: post an appdefined event which EmacsApp-sendEvent will
3062 recognize and take as a command to halt the event loop.
3063 -------------------------------------------------------------------------- */
3065 /*NSTRACE (ns_send_appdefined); */
3067 /* Only post this event if we haven't already posted one. This will end
3068 the [NXApp run] main loop after having processed all events queued at
3070 if (send_appdefined)
3074 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
3075 send_appdefined = NO;
3077 /* Don't need wakeup timer any more */
3080 [timed_entry invalidate];
3081 [timed_entry release];
3085 /* Ditto for file descriptor poller */
3088 [fd_entry invalidate];
3093 nxev = [NSEvent otherEventWithType: NSApplicationDefined
3094 location: NSMakePoint (0, 0)
3097 windowNumber: [[NSApp mainWindow] windowNumber]
3098 context: [NSApp context]
3103 /* Post an application defined event on the event queue. When this is
3104 received the [NXApp run] will return, thus having processed all
3105 events which are currently queued. */
3106 [NSApp postEvent: nxev atStart: NO];
3112 ns_read_socket (struct terminal *terminal, int expected,
3113 struct input_event *hold_quit)
3114 /* --------------------------------------------------------------------------
3115 External (hook): Post an event to ourself and keep reading events until
3116 we read it back again. In effect process all events which were waiting.
3117 From 21+ we have to manage the event buffer ourselves.
3118 -------------------------------------------------------------------------- */
3120 struct input_event ev;
3122 static NSDate *lastCheck = nil;
3124 /* NSTRACE (ns_read_socket); */
3126 if (interrupt_input_blocked)
3128 interrupt_input_pending = 1;
3130 pending_signals = 1;
3135 interrupt_input_pending = 0;
3137 pending_signals = pending_atimers;
3141 n_emacs_events_pending = 0;
3144 q_event_ptr = hold_quit;
3146 /* we manage autorelease pools by allocate/reallocate each time around
3147 the loop; strict nesting is occasionally violated but seems not to
3148 matter.. earlier methods using full nesting caused major memory leaks */
3149 [outerpool release];
3150 outerpool = [[NSAutoreleasePool alloc] init];
3152 /* If have pending open-file requests, attend to the next one of those. */
3153 if (ns_pending_files && [ns_pending_files count] != 0
3154 && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3156 [ns_pending_files removeObjectAtIndex: 0];
3158 /* Deal with pending service requests. */
3159 else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3161 NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3162 withArg: [ns_pending_service_args objectAtIndex: 0]])
3164 [ns_pending_service_names removeObjectAtIndex: 0];
3165 [ns_pending_service_args removeObjectAtIndex: 0];
3169 /* Run and wait for events. We must always send one NX_APPDEFINED event
3170 to ourself, otherwise [NXApp run] will never exit. */
3171 send_appdefined = YES;
3173 /* If called via ns_select, this is called once with expected=1,
3174 because we expect either the timeout or file descriptor activity.
3175 In this case the first event through will either be real input or
3176 one of these. read_avail_input() then calls once more with expected=0
3177 and in that case we need to return quickly if there is nothing.
3178 If we're being called outside of that, it's also OK to return quickly
3179 after one iteration through the event loop, since other terms do
3180 this and emacs expects it. */
3181 if (!(inNsSelect && expected)) // (!inNsSelect || !expected)
3183 /* Post an application defined event on the event queue. When this is
3184 received the [NXApp run] will return, thus having processed all
3185 events which are currently queued, if any. */
3186 ns_send_appdefined (-1);
3192 nevents = n_emacs_events_pending;
3193 n_emacs_events_pending = 0;
3194 emacs_event = q_event_ptr = NULL;
3202 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3203 fd_set *exceptfds, struct timeval *timeout)
3204 /* --------------------------------------------------------------------------
3205 Replacement for select, checking for events
3206 -------------------------------------------------------------------------- */
3211 /* NSTRACE (ns_select); */
3213 if (NSApp == nil || inNsSelect == 1 /* || ([NSApp isActive] == NO &&
3214 [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
3215 inMode:NSDefaultRunLoopMode dequeue:NO] == nil) */)
3216 return select (nfds, readfds, writefds, exceptfds, timeout);
3218 /* Save file descriptor set, which gets overwritten in calls to select ()
3219 Note, this is called from process.c, and only readfds is ever set */
3222 memcpy (&select_readfds, readfds, sizeof (fd_set));
3228 /* Try an initial select for pending data on input files */
3229 select_timeout.tv_sec = select_timeout.tv_usec = 0;
3230 result = select (nfds, readfds, writefds, exceptfds, &select_timeout);
3234 /* if (!timeout || timed_entry || fd_entry)
3235 fprintf (stderr, "assertion failed: timeout null or timed_entry/fd_entry non-null in ns_select\n"); */
3237 /* set a timeout and run the main AppKit event loop while continuing
3238 to monitor the files */
3239 time = ((double) timeout->tv_sec) + ((double) timeout->tv_usec)/1000000.0;
3240 timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3242 selector: @selector (timeout_handler:)
3244 repeats: YES] /* for safe removal */
3247 /* set a periodic task to try the select () again */
3248 fd_entry = [[NSTimer scheduledTimerWithTimeInterval: 0.1
3250 selector: @selector (fd_handler:)
3255 /* Let Application dispatch events until it receives an event of the type
3256 NX_APPDEFINED, which should only be sent by timeout_handler.
3257 We tell read_avail_input() that input is "expected" because we do expect
3258 either the timeout or fd handler to fire, and if they don't, the original
3259 call from process.c that got us here expects us to wait until some input
3263 ev = last_appdefined_event;
3269 if ([ev type] != NSApplicationDefined)
3273 last_appdefined_event = 0;
3277 /* The NX_APPDEFINED event we received was a timeout. */
3282 /* The NX_APPDEFINED event we received was the result of
3283 at least one real input event arriving. */
3289 /* Received back from select () in fd_handler; copy the results */
3291 memcpy (readfds, &select_readfds, sizeof (fd_set));
3295 /* never reached, shut compiler up */
3301 /* ==========================================================================
3305 ========================================================================== */
3309 ns_set_vertical_scroll_bar (struct window *window,
3310 int portion, int whole, int position)
3311 /* --------------------------------------------------------------------------
3312 External (hook): Update or add scrollbar
3313 -------------------------------------------------------------------------- */
3317 struct frame *f = XFRAME (WINDOW_FRAME (window));
3318 EmacsView *view = FRAME_NS_VIEW (f);
3319 int window_y, window_height;
3320 BOOL barOnVeryLeft, barOnVeryRight;
3321 int top, left, height, width, sb_width, sb_left;
3323 static int count = 0;
3325 /* optimization; display engine sends WAY too many of these.. */
3326 if (!NILP (window->vertical_scroll_bar))
3328 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3329 if ([bar checkSamePosition: position portion: portion whole: whole])
3331 if (view->scrollbarsNeedingUpdate == 0)
3333 if (!windows_or_buffers_changed)
3337 view->scrollbarsNeedingUpdate--;
3341 NSTRACE (ns_set_vertical_scroll_bar);
3343 /* Get dimensions. */
3344 window_box (window, -1, 0, &window_y, 0, &window_height);
3346 height = window_height;
3347 width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3348 left = WINDOW_SCROLL_BAR_AREA_X (window);
3350 if (top < 5) /* top scrollbar adjustment */
3352 top -= FRAME_INTERNAL_BORDER_WIDTH (f);
3353 height += FRAME_INTERNAL_BORDER_WIDTH (f);
3356 /* allow for displaying a skinnier scrollbar than char area allotted */
3357 sb_width = (WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) > 0) ?
3358 WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) : width;
3360 barOnVeryLeft = left < 5;
3361 barOnVeryRight = FRAME_PIXEL_WIDTH (f) - left - width < 5;
3362 sb_left = left + FRAME_INTERNAL_BORDER_WIDTH (f)
3363 * (barOnVeryLeft ? -1 : (barOnVeryRight ? 1 : 0));
3365 r = NSMakeRect (sb_left, top, sb_width, height);
3366 /* the parent view is flipped, so we need to flip y value */
3368 r.origin.y = (v.size.height - r.size.height - r.origin.y);
3370 XSETWINDOW (win, window);
3373 /* we want at least 5 lines to display a scrollbar */
3374 if (WINDOW_TOTAL_LINES (window) < 5)
3376 if (!NILP (window->vertical_scroll_bar))
3378 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3379 [bar removeFromSuperview];
3380 window->vertical_scroll_bar = Qnil;
3382 ns_clear_frame_area (f, sb_left, top, width, height);
3387 if (NILP (window->vertical_scroll_bar))
3389 ns_clear_frame_area (f, sb_left, top, width, height);
3390 bar = [[EmacsScroller alloc] initFrame: r window: win];
3391 window->vertical_scroll_bar = make_save_value (bar, 0);
3396 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3397 oldRect = [bar frame];
3398 r.size.width = oldRect.size.width;
3399 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3401 if (oldRect.origin.x != r.origin.x)
3402 ns_clear_frame_area (f, sb_left, top, width, height);
3407 [bar setPosition: position portion: portion whole: whole];
3413 ns_condemn_scroll_bars (struct frame *f)
3414 /* --------------------------------------------------------------------------
3415 External (hook): arrange for all frame's scrollbars to be removed
3416 at next call to judge_scroll_bars, except for those redeemed.
3417 -------------------------------------------------------------------------- */
3421 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3423 NSTRACE (ns_condemn_scroll_bars);
3425 for (i =[subviews count]-1; i >= 0; i--)
3427 view = [subviews objectAtIndex: i];
3428 if ([view isKindOfClass: [EmacsScroller class]])
3435 ns_redeem_scroll_bar (struct window *window)
3436 /* --------------------------------------------------------------------------
3437 External (hook): arrange to spare this window's scrollbar
3438 at next call to judge_scroll_bars.
3439 -------------------------------------------------------------------------- */
3442 NSTRACE (ns_redeem_scroll_bar);
3443 if (!NILP (window->vertical_scroll_bar))
3445 bar =XNS_SCROLL_BAR (window->vertical_scroll_bar);
3452 ns_judge_scroll_bars (struct frame *f)
3453 /* --------------------------------------------------------------------------
3454 External (hook): destroy all scrollbars on frame that weren't
3455 redeemed after call to condemn_scroll_bars.
3456 -------------------------------------------------------------------------- */
3460 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3461 NSTRACE (ns_judge_scroll_bars);
3462 for (i =[subviews count]-1; i >= 0; i--)
3464 view = [subviews objectAtIndex: i];
3465 if (![view isKindOfClass: [EmacsScroller class]]) continue;
3472 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
3474 /* XXX irrelevant under NS */
3479 /* ==========================================================================
3483 ========================================================================== */
3486 x_display_pixel_height (dpyinfo)
3487 struct ns_display_info *dpyinfo;
3489 NSScreen *screen = [NSScreen mainScreen];
3490 return [screen frame].size.height;
3494 x_display_pixel_width (dpyinfo)
3495 struct ns_display_info *dpyinfo;
3497 NSScreen *screen = [NSScreen mainScreen];
3498 return [screen frame].size.width;
3502 static Lisp_Object ns_string_to_lispmod (const char *s)
3503 /* --------------------------------------------------------------------------
3504 Convert modifier name to lisp symbol
3505 -------------------------------------------------------------------------- */
3507 if (!strncmp (SDATA (SYMBOL_NAME (Qmeta)), s, 10))
3509 else if (!strncmp (SDATA (SYMBOL_NAME (Qsuper)), s, 10))
3511 else if (!strncmp (SDATA (SYMBOL_NAME (Qcontrol)), s, 10))
3513 else if (!strncmp (SDATA (SYMBOL_NAME (Qalt)), s, 10))
3515 else if (!strncmp (SDATA (SYMBOL_NAME (Qhyper)), s, 10))
3517 else if (!strncmp (SDATA (SYMBOL_NAME (Qnone)), s, 10))
3524 static Lisp_Object ns_mod_to_lisp (int m)
3525 /* --------------------------------------------------------------------------
3526 Convert modifier code (see lisp.h) to lisp symbol
3527 -------------------------------------------------------------------------- */
3531 else if (m == CHAR_SUPER)
3533 else if (m == CHAR_CTL)
3535 else if (m == CHAR_ALT)
3537 else if (m == CHAR_HYPER)
3539 else /* if (m == 0) */
3545 ns_set_default_prefs ()
3546 /* --------------------------------------------------------------------------
3547 Initialize preference variables to defaults
3548 -------------------------------------------------------------------------- */
3550 ns_alternate_modifier = Qmeta;
3551 ns_command_modifier = Qsuper;
3552 ns_control_modifier = Qcontrol;
3553 ns_function_modifier = Qnone;
3554 ns_antialias_text = Qt;
3555 ns_antialias_threshold = 10.0; /* not exposed to lisp side */
3556 ns_use_qd_smoothing = Qnil;
3557 ns_use_system_highlight_color = Qt;
3558 ns_confirm_quit = Qnil;
3563 ns_default (const char *parameter, Lisp_Object *result,
3564 Lisp_Object yesval, Lisp_Object noval,
3565 BOOL is_float, BOOL is_modstring)
3566 /* --------------------------------------------------------------------------
3567 Check a parameter value in user's preferences
3568 -------------------------------------------------------------------------- */
3572 if ( (value =[[[NSUserDefaults standardUserDefaults]
3573 stringForKey: [NSString stringWithUTF8String: parameter]]
3578 if (strcasecmp (value, "YES") == 0)
3580 else if (strcasecmp (value, "NO") == 0)
3582 else if (is_float && (f = strtod (value, &pos), pos != value))
3583 *result = make_float (f);
3584 else if (is_modstring && value)
3585 *result = ns_string_to_lispmod (value);
3586 else fprintf (stderr,
3587 "Bad value for default \"%s\": \"%s\"\n", parameter, value);
3593 ns_initialize_display_info (struct ns_display_info *dpyinfo)
3594 /* --------------------------------------------------------------------------
3595 Initialize global info and storage for display.
3596 -------------------------------------------------------------------------- */
3598 NSScreen *screen = [NSScreen mainScreen];
3599 NSWindowDepth depth = [screen depth];
3601 dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
3602 dpyinfo->resy = 72.27;
3603 dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
3604 NSColorSpaceFromDepth (depth)]
3605 && ![NSCalibratedWhiteColorSpace isEqualToString:
3606 NSColorSpaceFromDepth (depth)];
3607 dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
3608 dpyinfo->image_cache = make_image_cache ();
3609 dpyinfo->color_table
3610 = (struct ns_color_table *)xmalloc (sizeof (struct ns_color_table));
3611 dpyinfo->color_table->colors = NULL;
3612 dpyinfo->root_window = 42; /* a placeholder.. */
3614 dpyinfo->mouse_face_mouse_frame = NULL;
3615 dpyinfo->mouse_face_deferred_gc = 0;
3616 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
3617 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
3618 dpyinfo->mouse_face_face_id = DEFAULT_FACE_ID;
3619 dpyinfo->mouse_face_window = dpyinfo->mouse_face_overlay = Qnil;
3620 dpyinfo->mouse_face_hidden = 0;
3622 dpyinfo->mouse_face_mouse_x = dpyinfo->mouse_face_mouse_y = 0;
3623 dpyinfo->mouse_face_defer = 0;
3625 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
3627 dpyinfo->n_fonts = 0;
3628 dpyinfo->smallest_font_height = 1;
3629 dpyinfo->smallest_char_width = 1;
3633 /* This and next define (many of the) public functions in this file. */
3634 /* x_... are generic versions in xdisp.c that we, and other terms, get away
3635 with using despite presence in the "system dependent" redisplay
3636 interface. In addition, many of the ns_ methods have code that is
3637 shared with all terms, indicating need for further refactoring. */
3638 extern frame_parm_handler ns_frame_parm_handlers[];
3639 static struct redisplay_interface ns_redisplay_interface =
3641 ns_frame_parm_handlers,
3645 x_clear_end_of_line,
3647 ns_after_update_window_line,
3648 ns_update_window_begin,
3649 ns_update_window_end,
3652 0, /* flush_display_optional */
3653 x_clear_window_mouse_face,
3654 x_get_glyph_overhangs,
3655 x_fix_overlapping_area,
3656 ns_draw_fringe_bitmap,
3657 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
3658 0, /* destroy_fringe_bitmap */
3659 ns_compute_glyph_string_overhangs,
3660 ns_draw_glyph_string, /* interface to nsfont.m */
3661 ns_define_frame_cursor,
3662 ns_clear_frame_area,
3663 ns_draw_window_cursor,
3664 ns_draw_vertical_window_border,
3665 ns_shift_glyphs_for_insert
3670 ns_delete_display (struct ns_display_info *dpyinfo)
3676 /* This function is called when the last frame on a display is deleted. */
3678 ns_delete_terminal (struct terminal *terminal)
3680 struct ns_display_info *dpyinfo = terminal->display_info.ns;
3683 /* Protect against recursive calls. delete_frame in
3684 delete_terminal calls us back when it deletes our last frame. */
3685 if (!terminal->name)
3690 x_destroy_all_bitmaps (dpyinfo);
3691 ns_delete_display (dpyinfo);
3696 static struct terminal *
3697 ns_create_terminal (struct ns_display_info *dpyinfo)
3698 /* --------------------------------------------------------------------------
3699 Set up use of NS before we make the first connection.
3700 -------------------------------------------------------------------------- */
3702 struct terminal *terminal;
3704 NSTRACE (ns_create_terminal);
3706 terminal = create_terminal ();
3708 terminal->type = output_ns;
3709 terminal->display_info.ns = dpyinfo;
3710 dpyinfo->terminal = terminal;
3712 terminal->rif = &ns_redisplay_interface;
3714 terminal->clear_frame_hook = ns_clear_frame;
3715 terminal->ins_del_lines_hook = 0; /* XXX vestigial? */
3716 terminal->delete_glyphs_hook = 0; /* XXX vestigial? */
3717 terminal->ring_bell_hook = ns_ring_bell;
3718 terminal->reset_terminal_modes_hook = ns_reset_terminal_modes;
3719 terminal->set_terminal_modes_hook = ns_set_terminal_modes;
3720 terminal->update_begin_hook = ns_update_begin;
3721 terminal->update_end_hook = ns_update_end;
3722 terminal->set_terminal_window_hook = NULL; /* XXX vestigial? */
3723 terminal->read_socket_hook = ns_read_socket;
3724 terminal->frame_up_to_date_hook = ns_frame_up_to_date;
3725 terminal->mouse_position_hook = ns_mouse_position;
3726 terminal->frame_rehighlight_hook = ns_frame_rehighlight;
3727 terminal->frame_raise_lower_hook = ns_frame_raise_lower;
3729 terminal->fullscreen_hook = 0; /* see XTfullscreen_hook */
3731 terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
3732 terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
3733 terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
3734 terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
3736 terminal->delete_frame_hook = x_destroy_window;
3737 terminal->delete_terminal_hook = ns_delete_terminal;
3739 terminal->scroll_region_ok = 1;
3740 terminal->char_ins_del_ok = 1;
3741 terminal->line_ins_del_ok = 1;
3742 terminal->fast_clear_end_of_line = 1;
3743 terminal->memory_below_frame = 0;
3749 struct ns_display_info *
3750 ns_term_init (Lisp_Object display_name)
3751 /* --------------------------------------------------------------------------
3752 Start the Application and get things rolling.
3753 -------------------------------------------------------------------------- */
3755 struct terminal *terminal;
3756 struct ns_display_info *dpyinfo;
3757 static int ns_initialized = 0;
3760 NSTRACE (ns_term_init);
3762 /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
3763 /*GSDebugAllocationActive (YES); */
3765 handling_signal = 0;
3767 if (!ns_initialized)
3770 Fset_input_interrupt_mode (Qnil);
3774 ns_pending_files = [[NSMutableArray alloc] init];
3775 ns_pending_service_names = [[NSMutableArray alloc] init];
3776 ns_pending_service_args = [[NSMutableArray alloc] init];
3778 /* Start app and create the main menu, window, view.
3779 Needs to be here because ns_initialize_display_info () uses AppKit classes.
3780 The view will then ask the NSApp to stop and return to Emacs. */
3781 [EmacsApp sharedApplication];
3784 [NSApp setDelegate: NSApp];
3786 /* debugging: log all notifications */
3787 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
3788 selector: @selector (logNotification:)
3789 name: nil object: nil]; */
3791 dpyinfo = (struct ns_display_info *)xmalloc (sizeof (struct ns_display_info));
3792 bzero (dpyinfo, sizeof (struct ns_display_info));
3794 ns_initialize_display_info (dpyinfo);
3795 terminal = ns_create_terminal (dpyinfo);
3797 terminal->kboard = (KBOARD *) xmalloc (sizeof (KBOARD));
3798 init_kboard (terminal->kboard);
3799 terminal->kboard->Vwindow_system = Qns;
3800 terminal->kboard->next_kboard = all_kboards;
3801 all_kboards = terminal->kboard;
3802 /* Don't let the initial kboard remain current longer than necessary.
3803 That would cause problems if a file loaded on startup tries to
3804 prompt in the mini-buffer. */
3805 if (current_kboard == initial_kboard)
3806 current_kboard = terminal->kboard;
3807 terminal->kboard->reference_count++;
3809 dpyinfo->next = x_display_list;
3810 x_display_list = dpyinfo;
3812 /* Put it on ns_display_name_list */
3813 ns_display_name_list = Fcons (Fcons (display_name, Qnil),
3814 ns_display_name_list);
3815 dpyinfo->name_list_element = XCAR (ns_display_name_list);
3817 /* Set the name of the terminal. */
3818 terminal->name = (char *) xmalloc (SBYTES (display_name) + 1);
3819 strncpy (terminal->name, SDATA (display_name), SBYTES (display_name));
3820 terminal->name[SBYTES (display_name)] = 0;
3824 /* Read various user defaults. */
3825 ns_set_default_prefs ();
3826 if (!ns_no_defaults)
3828 ns_default ("GSFontAntiAlias", &ns_antialias_text,
3831 /* this is a standard variable */
3832 ns_default ("AppleAntiAliasingThreshold", &tmp,
3833 make_float (10.0), make_float (6.0), YES, NO);
3834 ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
3837 ns_selection_color = [[NSUserDefaults standardUserDefaults]
3838 stringForKey: @"AppleHighlightColor"];
3839 if (ns_selection_color == nil)
3840 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
3843 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
3847 Lisp_Object color_file, color_map, color;
3852 color_file = Fexpand_file_name (build_string ("rgb.txt"),
3853 Fsymbol_value (intern ("data-directory")));
3854 if (NILP (Ffile_readable_p (color_file)))
3855 fatal ("Could not find %s.\n", SDATA (color_file));
3857 color_map = Fx_load_color_file (color_file);
3858 if (NILP (color_map))
3859 fatal ("Could not read %s.\n", SDATA (color_file));
3861 cl = [[NSColorList alloc] initWithName: @"Emacs"];
3862 for ( ; CONSP (color_map); color_map = XCDR (color_map))
3864 color = XCAR (color_map);
3865 name = SDATA (XCAR (color));
3866 c = XINT (XCDR (color));
3868 [NSColor colorWithCalibratedRed: RED_FROM_ULONG (c) / 255.0
3869 green: GREEN_FROM_ULONG (c) / 255.0
3870 blue: BLUE_FROM_ULONG (c) / 255.0
3872 forKey: [NSString stringWithUTF8String: name]];
3874 [cl writeToFile: nil];
3880 #ifdef NS_IMPL_GNUSTEP
3881 strncpy (c, gnustep_base_version, sizeof (c));
3883 /*PSnextrelease (128, c); */
3884 snprintf (c, sizeof (c), "%g", NSAppKitVersionNumber);
3886 Vwindow_system_version = build_string (c);
3889 delete_keyboard_wait_descriptor (0);
3891 /* Set up OS X app menu */
3892 #ifdef NS_IMPL_COCOA
3896 /* set up the application menu */
3897 svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
3898 [svcsMenu setAutoenablesItems: NO];
3899 appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
3900 [appMenu setAutoenablesItems: NO];
3901 mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
3902 dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
3904 [appMenu insertItemWithTitle: @"About Emacs"
3905 action: @selector (orderFrontStandardAboutPanel:)
3908 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
3909 [appMenu insertItemWithTitle: @"Preferences..."
3910 action: @selector (showPreferencesWindow:)
3913 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
3914 item = [appMenu insertItemWithTitle: @"Services"
3915 action: @selector (menuDown:)
3918 [appMenu setSubmenu: svcsMenu forItem: item];
3919 /* [svcsMenu setSupercell: item]; */
3920 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
3921 [appMenu insertItemWithTitle: @"Hide Emacs"
3922 action: @selector (hide:)
3925 item = [appMenu insertItemWithTitle: @"Hide Others"
3926 action: @selector (hideOtherApplications:)
3929 [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
3930 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
3931 [appMenu insertItemWithTitle: @"Quit Emacs"
3932 action: @selector (terminate:)
3936 item = [mainMenu insertItemWithTitle: @"Emacs"
3937 action: @selector (menuDown:)
3940 [mainMenu setSubmenu: appMenu forItem: item];
3941 [dockMenu insertItemWithTitle: @"New Frame"
3942 action: @selector (newFrame:)
3946 [NSApp setMainMenu: mainMenu];
3947 [NSApp setAppleMenu: appMenu];
3948 [NSApp setServicesMenu: svcsMenu];
3949 /* Needed at least on Cocoa, to get dock menu to show windows */
3950 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
3952 #endif /* MAC OS X menu setup */
3960 extern Lisp_Object Vauto_save_list_file_name;
3962 ns_term_shutdown (int sig)
3964 /* code not reached in emacs.c after this is called by shut_down_emacs: */
3965 if (STRINGP (Vauto_save_list_file_name))
3966 unlink (SDATA (Vauto_save_list_file_name));
3968 if (sig == 0 || sig == SIGTERM)
3970 [NSApp terminate: NSApp];
3972 else // force a stack trace to happen
3979 /* ==========================================================================
3981 EmacsApp implementation
3983 ========================================================================== */
3986 @implementation EmacsApp
3988 - (void)logNotification: (NSNotification *)notification
3990 const char *name = [[notification name] UTF8String];
3991 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
3992 && !strstr (name, "WindowNumber"))
3993 NSLog (@"notification: '%@'", [notification name]);
3997 - (void)sendEvent: (NSEvent *)theEvent
3998 /* --------------------------------------------------------------------------
3999 Called when NSApp is running for each event received. Used to stop
4000 the loop when we choose, since there's no way to just run one iteration.
4001 -------------------------------------------------------------------------- */
4003 int type = [theEvent type];
4004 NSWindow *window = [theEvent window];
4005 /* NSTRACE (sendEvent); */
4006 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4008 if (type == NSCursorUpdate && window == nil)
4010 fprintf (stderr, "Dropping external cursor update event.\n");
4014 #ifdef NS_IMPL_COCOA
4015 /* pass mouse down in resize handle and subsequent drags directly to
4016 EmacsWindow so we can generate continuous redisplays */
4019 if (type == NSLeftMouseDragged)
4021 [window mouseDragged: theEvent];
4024 else if (type == NSLeftMouseUp)
4026 [window mouseUp: theEvent];
4030 else if (type == NSLeftMouseDown)
4032 NSRect r = ns_resize_handle_rect (window);
4033 if (NSPointInRect ([theEvent locationInWindow], r))
4036 [window mouseDown: theEvent];
4042 if (type == NSApplicationDefined)
4044 /* Events posted by ns_send_appdefined interrupt the run loop here.
4045 But, if a modal window is up, an appdefined can still come through,
4046 (e.g., from a makeKeyWindow event) but stopping self also stops the
4047 modal loop. Just defer it until later. */
4048 if ([NSApp modalWindow] == nil)
4050 last_appdefined_event = theEvent;
4055 send_appdefined = YES;
4059 [super sendEvent: theEvent];
4063 - (void)showPreferencesWindow: (id)sender
4065 struct frame *emacsframe = SELECTED_FRAME ();
4066 NSEvent *theEvent = [NSApp currentEvent];
4070 emacs_event->kind = NS_NONKEY_EVENT;
4071 emacs_event->code = KEY_NS_SHOW_PREFS;
4072 emacs_event->modifiers = 0;
4073 EV_TRAILER (theEvent);
4077 - (void)newFrame: (id)sender
4079 struct frame *emacsframe = SELECTED_FRAME ();
4080 NSEvent *theEvent = [NSApp currentEvent];
4084 emacs_event->kind = NS_NONKEY_EVENT;
4085 emacs_event->code = KEY_NS_NEW_FRAME;
4086 emacs_event->modifiers = 0;
4087 EV_TRAILER (theEvent);
4091 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4092 - (BOOL) openFile: (NSString *)fileName
4094 struct frame *emacsframe = SELECTED_FRAME ();
4095 NSEvent *theEvent = [NSApp currentEvent];
4100 emacs_event->kind = NS_NONKEY_EVENT;
4101 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4102 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4103 ns_input_line = Qnil; /* can be start or cons start,end */
4104 emacs_event->modifiers =0;
4105 EV_TRAILER (theEvent);
4111 /* **************************************************************************
4113 EmacsApp delegate implementation
4115 ************************************************************************** */
4117 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4118 /* --------------------------------------------------------------------------
4119 When application is loaded, terminate event loop in ns_term_init
4120 -------------------------------------------------------------------------- */
4122 NSTRACE (applicationDidFinishLaunching);
4123 [NSApp setServicesProvider: NSApp];
4124 ns_send_appdefined (-2);
4128 /* Termination sequences:
4131 MenuBar | File | Exit:
4132 Select Quit from App menubar:
4134 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4137 Select Quit from Dock menu:
4140 Cancel -> Nothing else
4144 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4149 - (void) terminate: (id)sender
4151 struct frame *emacsframe = SELECTED_FRAME ();
4156 emacs_event->kind = NS_NONKEY_EVENT;
4157 emacs_event->code = KEY_NS_POWER_OFF;
4158 emacs_event->arg = Qt; /* mark as non-key event */
4159 EV_TRAILER ((id)nil);
4163 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4167 if (NILP (ns_confirm_quit)) // || ns_shutdown_properly --> TO DO
4168 return NSTerminateNow;
4170 ret = NSRunAlertPanel([[NSProcessInfo processInfo] processName],
4171 [NSString stringWithUTF8String:"Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?"],
4172 @"Save Buffers and Exit", @"Cancel", nil);
4174 if (ret == NSAlertDefaultReturn)
4175 return NSTerminateNow;
4176 else if (ret == NSAlertAlternateReturn)
4177 return NSTerminateCancel;
4178 return NSTerminateNow; /* just in case */
4182 /* Notification from the Workspace to open a file */
4183 - (BOOL)application: sender openFile: (NSString *)file
4185 [ns_pending_files addObject: file];
4190 /* Open a file as a temporary file */
4191 - (BOOL)application: sender openTempFile: (NSString *)file
4193 [ns_pending_files addObject: file];
4198 /* Notification from the Workspace to open a file noninteractively (?) */
4199 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4201 [ns_pending_files addObject: file];
4206 /* Notification from the Workspace to open multiple files */
4207 - (void)application: sender openFiles: (NSArray *)fileList
4209 NSEnumerator *files = [fileList objectEnumerator];
4211 while ((file = [files nextObject]) != nil)
4212 [ns_pending_files addObject: file];
4214 /* TODO: when GNUstep implements this (and we require that version of
4215 GNUstep), remove. */
4216 #ifndef NS_IMPL_GNUSTEP
4217 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4218 #endif /* !NS_IMPL_GNUSTEP */
4223 /* Handle dock menu requests. */
4224 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4230 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4231 - (void)applicationWillBecomeActive: (NSNotification *)notification
4233 //ns_app_active=YES;
4235 - (void)applicationDidBecomeActive: (NSNotification *)notification
4237 //ns_app_active=YES;
4239 - (void)applicationDidResignActive: (NSNotification *)notification
4242 ns_send_appdefined (-1);
4247 /* ==========================================================================
4249 EmacsApp aux handlers for managing event loop
4251 ========================================================================== */
4254 - (void)timeout_handler: (NSTimer *)timedEntry
4255 /* --------------------------------------------------------------------------
4256 The timeout specified to ns_select has passed.
4257 -------------------------------------------------------------------------- */
4259 /*NSTRACE (timeout_handler); */
4260 ns_send_appdefined (-2);
4263 extern void update_window_cursor (struct window *w, int on);
4265 - (void)fd_handler: (NSTimer *) fdEntry
4266 /* --------------------------------------------------------------------------
4267 Check data waiting on file descriptors and terminate if so
4268 -------------------------------------------------------------------------- */
4271 /* NSTRACE (fd_handler); */
4273 if (select_nfds == 0)
4276 memcpy (&t_readfds, &select_readfds, sizeof (fd_set));
4278 select_timeout.tv_sec = select_timeout.tv_usec = 0;
4279 result = select (select_nfds, &t_readfds, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
4283 memcpy (&select_readfds, &t_readfds, sizeof (fd_set));
4284 ns_send_appdefined (result);
4290 /* ==========================================================================
4294 ========================================================================== */
4296 /* called from system: queue for next pass through event loop */
4297 - (void)requestService: (NSPasteboard *)pboard
4298 userData: (NSString *)userData
4299 error: (NSString **)error
4301 [ns_pending_service_names addObject: userData];
4302 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
4303 SDATA (ns_string_from_pasteboard (pboard))]];
4307 /* called from ns_read_socket to clear queue */
4308 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
4310 struct frame *emacsframe = SELECTED_FRAME ();
4311 NSEvent *theEvent = [NSApp currentEvent];
4316 emacs_event->kind = NS_NONKEY_EVENT;
4317 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
4318 ns_input_spi_name = build_string ([name UTF8String]);
4319 ns_input_spi_arg = build_string ([arg UTF8String]);
4320 emacs_event->modifiers = EV_MODIFIERS (theEvent);
4321 EV_TRAILER (theEvent);
4331 /* ==========================================================================
4333 EmacsView implementation
4335 ========================================================================== */
4338 @implementation EmacsView
4340 /* needed to inform when window closed from LISP */
4341 - (void) setWindowClosing: (BOOL)closing
4343 windowClosing = closing;
4349 NSTRACE (EmacsView_dealloc);
4355 /* called on font panel selection */
4356 - (void)changeFont: (id)sender
4358 NSEvent *e =[[self window] currentEvent];
4359 struct face *face =FRAME_DEFAULT_FACE (emacsframe);
4363 NSTRACE (changeFont);
4367 if (newFont = [sender convertFont:
4368 ((struct nsfont_info *)face->font)->nsfont])
4370 SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
4372 emacs_event->kind = NS_NONKEY_EVENT;
4373 emacs_event->modifiers = 0;
4374 emacs_event->code = KEY_NS_CHANGE_FONT;
4376 size = [newFont pointSize];
4377 ns_input_fontsize = make_number (lrint (size));
4378 ns_input_font = build_string ([[newFont familyName] UTF8String]);
4384 - (BOOL)acceptsFirstResponder
4386 NSTRACE (acceptsFirstResponder);
4391 - (void)resetCursorRects
4393 NSRect visible = [self visibleRect];
4394 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
4395 NSTRACE (resetCursorRects);
4397 if (currentCursor == nil)
4398 currentCursor = [NSCursor arrowCursor];
4400 if (!NSIsEmptyRect (visible))
4401 [self addCursorRect: visible cursor: currentCursor];
4402 [currentCursor setOnMouseEntered: YES];
4407 /*****************************************************************************/
4408 /* Keyboard handling. */
4411 - (void)keyDown: (NSEvent *)theEvent
4413 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4415 unsigned fnKeysym = 0;
4417 static NSMutableArray *nsEvArray;
4418 static BOOL firstTime = YES;
4422 /* Rhapsody and OS X give up and down events for the arrow keys */
4423 if (ns_fake_keydown == YES)
4424 ns_fake_keydown = NO;
4425 else if ([theEvent type] != NSKeyDown)
4431 if (![[self window] isKeyWindow])
4433 /* XXX: There is an occasional condition in which, when Emacs display
4434 updates a different frame from the current one, and temporarily
4435 selects it, then processes some interrupt-driven input
4436 (dispnew.c:3878), OS will send the event to the correct NSWindow, but
4437 for some reason that window has its first responder set to the NSView
4438 most recently updated (I guess), which is not the correct one. */
4439 if ([[theEvent window] isKindOfClass: [EmacsWindow class]])
4440 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
4444 if (nsEvArray == nil)
4445 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
4447 [NSCursor setHiddenUntilMouseMoves: YES];
4449 if (dpyinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
4451 clear_mouse_face (dpyinfo);
4452 dpyinfo->mouse_face_hidden = 1;
4455 if (!processingCompose)
4457 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
4458 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
4459 /* (Carbon way: [theEvent keyCode]) */
4461 /* is it a "function key"? */
4462 fnKeysym = ns_convert_key (code);
4465 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
4466 because Emacs treats Delete and KP-Delete same (in simple.el). */
4467 if (fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
4468 code = 0xFF08; /* backspace */
4473 /* are there modifiers? */
4474 emacs_event->modifiers = 0;
4475 flags = [theEvent modifierFlags];
4477 if (flags & NSHelpKeyMask)
4478 emacs_event->modifiers |= hyper_modifier;
4480 if (flags & NSShiftKeyMask)
4481 emacs_event->modifiers |= shift_modifier;
4483 if (flags & NSCommandKeyMask)
4485 emacs_event->modifiers |= parse_solitary_modifier (ns_command_modifier);
4486 /* if super (default), take input manager's word so things like
4487 dvorak / qwerty layout work */
4488 if (EQ (ns_command_modifier, Qsuper)
4490 && [[theEvent characters] length] != 0)
4492 /* XXX: the code we get will be unshifted, so if we have
4493 a shift modifier, must convert ourselves */
4494 if (!(flags & NSShiftKeyMask))
4495 code = [[theEvent characters] characterAtIndex: 0];
4497 /* this is ugly and also requires linking w/Carbon framework
4498 (for LMGetKbdType) so for now leave this rare (?) case
4499 undealt with.. in future look into CGEvent methods */
4502 long smv = GetScriptManagerVariable (smKeyScript);
4503 Handle uchrHandle = GetResource
4504 ('uchr', GetScriptVariable (smv, smScriptKeys));
4506 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
4507 [[theEvent characters] characterAtIndex: 0],
4508 kUCKeyActionDisplay,
4509 (flags & ~NSCommandKeyMask) >> 8,
4510 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
4511 &dummy, 1, &dummy, &code);
4518 if (flags & NSControlKeyMask)
4519 emacs_event->modifiers |=
4520 parse_solitary_modifier (ns_control_modifier);
4522 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
4523 emacs_event->modifiers |=
4524 parse_solitary_modifier (ns_function_modifier);
4526 if (flags & NSAlternateKeyMask) /* default = meta */
4528 if ((NILP (ns_alternate_modifier) || EQ (ns_alternate_modifier, Qnone))
4530 { /* accept pre-interp alt comb */
4531 if ([[theEvent characters] length] > 0)
4532 code = [[theEvent characters] characterAtIndex: 0];
4533 /*HACK: clear lone shift modifier to stop next if from firing */
4534 if (emacs_event->modifiers == shift_modifier)
4535 emacs_event->modifiers = 0;
4538 emacs_event->modifiers |=
4539 parse_solitary_modifier (ns_alternate_modifier);
4543 fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
4544 code, fnKeysym, flags, emacs_event->modifiers);
4546 /* if it was a function key or had modifiers, pass it directly to emacs */
4547 if (fnKeysym || (emacs_event->modifiers
4548 && [[theEvent charactersIgnoringModifiers] length] > 0))
4549 /*[[theEvent characters] length] */
4551 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4553 code |= (1<<28)|(3<<16);
4554 else if (code == 0x7f)
4555 code |= (1<<28)|(3<<16);
4557 emacs_event->kind = code > 0xFF
4558 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4560 emacs_event->code = code;
4561 EV_TRAILER (theEvent);
4566 /* if we get here we should send the key for input manager processing */
4567 if (firstTime && [[NSInputManager currentInputManager]
4568 wantsToDelayTextChangeNotifications] == NO)
4570 "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
4573 if (NS_KEYLOG && !processingCompose)
4574 fprintf (stderr, "keyDown: Begin compose sequence.\n");
4576 processingCompose = YES;
4577 [nsEvArray addObject: theEvent];
4578 [self interpretKeyEvents: nsEvArray];
4579 [nsEvArray removeObject: theEvent];
4583 #ifdef NS_IMPL_COCOA
4584 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
4585 decided not to send key-down for.
4586 See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
4587 If it matches one of these, send it on to keyDown. */
4588 -(void)keyUp: (NSEvent *)theEvent
4590 int flags = [theEvent modifierFlags];
4591 int code = [theEvent keyCode];
4592 if (code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
4595 fprintf (stderr, "keyUp: passed test");
4596 ns_fake_keydown = YES;
4597 [self keyDown: theEvent];
4603 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
4606 /* <NSTextInput>: called when done composing;
4607 NOTE: also called when we delete over working text, followed immed.
4608 by doCommandBySelector: deleteBackward: */
4609 - (void)insertText: (id)aString
4612 int len = [(NSString *)aString length];
4616 NSLog (@"insertText '%@'\tlen = %d", aString, len);
4617 processingCompose = NO;
4622 /* first, clear any working text */
4623 if (workingText != nil)
4624 [self deleteWorkingText];
4626 /* now insert the string as keystrokes */
4627 for (i =0; i<len; i++)
4629 code = [aString characterAtIndex: i];
4630 /* TODO: still need this? */
4632 code = '~'; /* 0x7E */
4633 emacs_event->modifiers = 0;
4635 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4636 emacs_event->code = code;
4637 EV_TRAILER ((id)nil);
4642 /* <NSTextInput>: inserts display of composing characters */
4643 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
4645 NSString *str = [aString respondsToSelector: @selector (string)] ?
4646 [aString string] : aString;
4648 NSLog (@"setMarkedText '%@' len =%d range %d from %d", str, [str length],
4649 selRange.length, selRange.location);
4651 if (workingText != nil)
4652 [self deleteWorkingText];
4653 if ([str length] == 0)
4659 processingCompose = YES;
4660 workingText = [str copy];
4661 ns_working_text = build_string ([workingText UTF8String]);
4663 emacs_event->kind = NS_TEXT_EVENT;
4664 emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
4665 EV_TRAILER ((id)nil);
4669 /* delete display of composing characters [not in <NSTextInput>] */
4670 - (void)deleteWorkingText
4672 if (workingText == nil)
4675 NSLog(@"deleteWorkingText len =%d\n", [workingText length]);
4676 [workingText release];
4678 processingCompose = NO;
4683 emacs_event->kind = NS_TEXT_EVENT;
4684 emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
4685 EV_TRAILER ((id)nil);
4689 - (BOOL)hasMarkedText
4691 return workingText != nil;
4695 - (NSRange)markedRange
4697 NSRange rng = workingText != nil
4698 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
4700 NSLog (@"markedRange request");
4708 NSLog (@"unmark (accept) text");
4709 [self deleteWorkingText];
4710 processingCompose = NO;
4714 /* used to position char selection windows, etc. */
4715 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
4719 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
4721 NSLog (@"firstRectForCharRange request");
4723 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
4724 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
4725 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
4726 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
4727 +FRAME_LINE_HEIGHT (emacsframe));
4729 pt = [self convertPoint: pt toView: nil];
4730 pt = [[self window] convertBaseToScreen: pt];
4736 - (NSInteger)conversationIdentifier
4738 return (NSInteger)self;
4742 - (void)doCommandBySelector: (SEL)aSelector
4745 NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
4747 if (aSelector == @selector (deleteBackward:))
4749 /* happens when user backspaces over an ongoing composition:
4750 throw a 'delete' into the event queue */
4753 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4754 emacs_event->code = 0xFF08;
4755 EV_TRAILER ((id)nil);
4759 - (NSArray *)validAttributesForMarkedText
4761 static NSArray *arr = nil;
4762 if (arr == nil) arr = [NSArray new];
4763 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
4767 - (NSRange)selectedRange
4770 NSLog (@"selectedRange request");
4771 return NSMakeRange (NSNotFound, 0);
4774 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
4777 NSLog (@"characterIndexForPoint request");
4781 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
4783 static NSAttributedString *str = nil;
4784 if (str == nil) str = [NSAttributedString new];
4786 NSLog (@"attributedSubstringFromRange request");
4790 /* End <NSTextInput> impl. */
4791 /*****************************************************************************/
4794 /* This is what happens when the user presses a mouse button. */
4795 - (void)mouseDown: (NSEvent *)theEvent
4797 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
4800 NSTRACE (mouseDown);
4802 [self deleteWorkingText];
4807 last_mouse_frame = emacsframe;
4808 /* appears to be needed to prevent spurious movement events generated on
4810 last_mouse_frame->mouse_moved = 0;
4812 if ([theEvent type] == NSScrollWheel)
4814 float delta = [theEvent deltaY];
4815 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
4818 emacs_event->kind = WHEEL_EVENT;
4819 emacs_event->code = 0;
4820 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
4821 ((delta > 0) ? up_modifier : down_modifier);
4825 emacs_event->kind = MOUSE_CLICK_EVENT;
4826 emacs_event->code = EV_BUTTON (theEvent);
4827 emacs_event->modifiers = EV_MODIFIERS (theEvent)
4828 | EV_UDMODIFIERS (theEvent);
4830 XSETINT (emacs_event->x, lrint (p.x));
4831 XSETINT (emacs_event->y, lrint (p.y));
4832 EV_TRAILER (theEvent);
4836 - (void)rightMouseDown: (NSEvent *)theEvent
4838 NSTRACE (rightMouseDown);
4839 [self mouseDown: theEvent];
4843 - (void)otherMouseDown: (NSEvent *)theEvent
4845 NSTRACE (otherMouseDown);
4846 [self mouseDown: theEvent];
4850 - (void)mouseUp: (NSEvent *)theEvent
4853 [self mouseDown: theEvent];
4857 - (void)rightMouseUp: (NSEvent *)theEvent
4859 NSTRACE (rightMouseUp);
4860 [self mouseDown: theEvent];
4864 - (void)otherMouseUp: (NSEvent *)theEvent
4866 NSTRACE (otherMouseUp);
4867 [self mouseDown: theEvent];
4871 - (void) scrollWheel: (NSEvent *)theEvent
4873 NSTRACE (scrollWheel);
4874 [self mouseDown: theEvent];
4878 /* Tell emacs the mouse has moved. */
4879 - (void)mouseMoved: (NSEvent *)e
4881 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4884 // NSTRACE (mouseMoved);
4886 last_mouse_movement_time = EV_TIMESTAMP (e);
4887 last_mouse_motion_position
4888 = [self convertPoint: [e locationInWindow] fromView: nil];
4890 /* update any mouse face */
4891 if (dpyinfo->mouse_face_hidden)
4893 dpyinfo->mouse_face_hidden = 0;
4894 clear_mouse_face (dpyinfo);
4897 /* tooltip handling */
4898 previous_help_echo_string = help_echo_string;
4899 help_echo_string = Qnil;
4901 if (!note_mouse_movement (emacsframe, last_mouse_motion_position.x,
4902 last_mouse_motion_position.y))
4903 help_echo_string = previous_help_echo_string;
4905 XSETFRAME (frame, emacsframe);
4906 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
4908 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
4909 (note_mouse_highlight), which is called through the
4910 note_mouse_movement () call above */
4911 gen_help_event (help_echo_string, frame, help_echo_window,
4912 help_echo_object, help_echo_pos);
4916 help_echo_string = Qnil;
4917 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
4920 if (emacsframe->mouse_moved && send_appdefined)
4921 ns_send_appdefined (-1);
4925 - (void)mouseDragged: (NSEvent *)e
4927 NSTRACE (mouseDragged);
4928 [self mouseMoved: e];
4932 - (void)rightMouseDragged: (NSEvent *)e
4934 NSTRACE (rightMouseDragged);
4935 [self mouseMoved: e];
4939 - (void)otherMouseDragged: (NSEvent *)e
4941 NSTRACE (otherMouseDragged);
4942 [self mouseMoved: e];
4946 - (BOOL)windowShouldClose: (id)sender
4948 NSEvent *e =[[self window] currentEvent];
4950 NSTRACE (windowShouldClose);
4951 windowClosing = YES;
4954 emacs_event->kind = DELETE_WINDOW_EVENT;
4955 emacs_event->modifiers = 0;
4956 emacs_event->code = 0;
4958 /* Don't close this window, let this be done from lisp code. */
4963 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
4964 /* normalize frame to gridded text size */
4966 NSTRACE (windowWillResize);
4967 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
4969 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe,
4970 #ifdef NS_IMPL_GNUSTEP
4971 frameSize.width + 3);
4975 if (cols < MINWIDTH)
4977 frameSize.width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (emacsframe, cols);
4979 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, frameSize.height
4980 #ifdef NS_IMPL_GNUSTEP
4981 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe) + 3
4982 - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
4984 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
4985 - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
4987 if (rows < MINHEIGHT)
4989 frameSize.height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows)
4990 + FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
4991 + FRAME_NS_TOOLBAR_HEIGHT (emacsframe);
4992 #ifdef NS_IMPL_COCOA
4994 /* this sets window title to have size in it; the wm does this under GS */
4995 NSRect r = [[self window] frame];
4996 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
5007 NSWindow *window = [self window];
5010 const char *t = [[[self window] title] UTF8String];
5011 char *pos = strstr (t, " — ");
5014 old_title = (char *) xmalloc (strlen (t) + 1);
5015 strcpy (old_title, t);
5017 size_title = xmalloc (strlen (old_title) + 40);
5018 sprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
5019 [window setTitle: [NSString stringWithUTF8String: size_title]];
5024 #endif /* NS_IMPL_COCOA */
5025 /*fprintf (stderr," ...size became %.0f x %.0f (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
5031 - (void)windowDidResize: (NSNotification *)notification
5033 NSWindow *theWindow = [notification object];
5035 #ifdef NS_IMPL_GNUSTEP
5036 /* in GNUstep, at least currently, it's possible to get a didResize
5037 without getting a willResize.. therefore we need to act as if we got
5038 the willResize now */
5039 NSSize sz = [theWindow frame].size;
5040 sz = [self windowWillResize: theWindow toSize: sz];
5041 #endif /* NS_IMPL_GNUSTEP */
5043 NSTRACE (windowDidResize);
5044 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
5046 #ifdef NS_IMPL_COCOA
5052 #endif /* NS_IMPL_COCOA */
5054 if (cols > 0 && rows > 0)
5055 x_set_window_size (emacsframe, 0, cols, rows);
5057 ns_send_appdefined (-1);
5061 - (void)windowDidBecomeKey: (NSNotification *)notification
5062 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5064 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5065 struct frame *old_focus = dpyinfo->x_focus_frame;
5067 NSTRACE (windowDidBecomeKey);
5069 if (emacsframe != old_focus)
5070 dpyinfo->x_focus_frame = emacsframe;
5072 ns_frame_rehighlight (emacsframe);
5076 emacs_event->kind = FOCUS_IN_EVENT;
5077 EV_TRAILER ((id)nil);
5082 - (void)windowDidResignKey: (NSNotification *)notification
5083 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5085 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5086 NSTRACE (windowDidResignKey);
5088 if (dpyinfo->x_focus_frame == emacsframe)
5089 dpyinfo->x_focus_frame = 0;
5091 ns_frame_rehighlight (emacsframe);
5093 /* FIXME: for some reason needed on second and subsequent clicks away
5094 from sole-frame Emacs to get hollow box to show */
5095 if (!windowClosing && [[self window] isVisible] == YES)
5097 x_update_cursor (emacsframe, 1);
5098 x_set_frame_alpha (emacsframe);
5103 [self deleteWorkingText];
5104 emacs_event->kind = FOCUS_IN_EVENT;
5105 EV_TRAILER ((id)nil);
5110 - (void)windowWillMiniaturize: sender
5112 NSTRACE (windowWillMiniaturize);
5128 - initFrameFromEmacs: (struct frame *)f
5133 NSButton *toggleButton;
5134 int vbextra = NS_SCROLL_BAR_WIDTH (f);
5139 NSTRACE (initFrameFromEmacs);
5142 processingCompose = NO;
5143 scrollbarsNeedingUpdate = 0;
5145 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
5147 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
5148 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
5149 [self initWithFrame: r];
5151 FRAME_NS_VIEW (f) = self;
5155 win = [[EmacsWindow alloc]
5156 initWithContentRect: r
5157 styleMask: (NSResizableWindowMask |
5158 NSMiniaturizableWindowMask |
5159 NSClosableWindowMask)
5160 backing: NSBackingStoreBuffered
5164 f->border_width = wr.size.width - r.size.width;
5165 FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
5167 [win setAcceptsMouseMovedEvents: YES];
5168 [win setDelegate: self];
5169 [win useOptimizedDrawing: YES];
5171 sz.width = FRAME_COLUMN_WIDTH (f);
5172 sz.height = FRAME_LINE_HEIGHT (f);
5173 [win setResizeIncrements: sz];
5175 [[win contentView] addSubview: self];
5178 [self registerForDraggedTypes: ns_drag_types];
5181 name = [NSString stringWithUTF8String:
5182 NILP (tem) ? (unsigned char *)"Emacs" : SDATA (tem)];
5183 [win setTitle: name];
5185 /* toolbar support */
5186 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
5187 [NSString stringWithFormat: @"Emacs Frame %d",
5189 [win setToolbar: toolbar];
5190 [toolbar setVisible: NO];
5191 #ifdef NS_IMPL_COCOA
5192 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
5193 [toggleButton setTarget: self];
5194 [toggleButton setAction: @selector (toggleToolbar: )];
5196 FRAME_NS_TOOLBAR_HEIGHT (f) = 0;
5200 [win setMiniwindowTitle:
5201 [NSString stringWithUTF8String: SDATA (tem)]];
5204 NSScreen *screen = [win screen];
5207 [win setFrameTopLeftPoint: NSMakePoint
5208 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
5209 IN_BOUND (-SCREENMAX,
5210 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
5213 [win makeFirstResponder: self];
5215 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5216 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
5217 [win setBackgroundColor: col];
5218 if ([col alphaComponent] != 1.0)
5219 [win setOpaque: NO];
5221 [self allocateGState];
5228 - (void)windowDidMove: sender
5230 NSWindow *win = [self window];
5231 NSRect r = [win frame];
5232 NSScreen *screen = [win screen];
5233 NSRect sr = [screen frame];
5235 NSTRACE (windowDidMove);
5237 if (!emacsframe->output_data.ns)
5241 emacsframe->left_pos = r.origin.x; /* - sr.origin.x; */
5242 emacsframe->top_pos = sr.size.height -
5243 (r.origin.y + r.size.height); /* + sr.origin.y; */
5247 #ifdef NS_IMPL_COCOA
5248 /* if we don't do this manually, the window will resize but not move */
5249 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
5251 NSTRACE (windowShouldZoom);
5252 [[self window] setFrame: newFrame display: NO];
5258 /* Override to do something slightly nonstandard, but nice. First click on
5259 zoom button will zoom vertically. Second will zoom completely. Third
5260 returns to original. */
5261 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
5262 defaultFrame:(NSRect)defaultFrame
5264 NSRect result = [sender frame];
5265 NSTRACE (windowWillUseStandardFrame);
5267 if (result.size.height == defaultFrame.size.height) {
5268 result = defaultFrame;
5270 result.size.height = defaultFrame.size.height;
5271 result.origin.y = defaultFrame.origin.y;
5274 /* A windowWillResize does not get generated at least on Tiger. */
5275 [self windowWillResize: sender toSize: result.size];
5280 - (void)windowDidDeminiaturize: sender
5282 NSTRACE (windowDidDeminiaturize);
5283 if (!emacsframe->output_data.ns)
5285 emacsframe->async_iconified = 0;
5286 emacsframe->async_visible = 1;
5287 windows_or_buffers_changed++;
5291 emacs_event->kind = ICONIFY_EVENT;
5292 EV_TRAILER ((id)nil);
5297 - (void)windowDidExpose: sender
5299 NSTRACE (windowDidExpose);
5300 if (!emacsframe->output_data.ns)
5302 emacsframe->async_visible = 1;
5303 SET_FRAME_GARBAGED (emacsframe);
5305 if (send_appdefined)
5306 ns_send_appdefined (-1);
5310 - (void)windowDidMiniaturize: sender
5312 NSTRACE (windowDidMiniaturize);
5313 if (!emacsframe->output_data.ns)
5316 emacsframe->async_iconified = 1;
5317 emacsframe->async_visible = 0;
5321 emacs_event->kind = ICONIFY_EVENT;
5322 EV_TRAILER ((id)nil);
5327 - (void)mouseEntered: (NSEvent *)theEvent
5329 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5330 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5331 NSTRACE (mouseEntered);
5333 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5337 - (void)mouseExited: (NSEvent *)theEvent
5339 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5341 struct ns_display_info *dpyinfo
5342 = emacsframe ? FRAME_NS_DISPLAY_INFO (emacsframe) : NULL;
5344 NSTRACE (mouseExited);
5346 if (dpyinfo || !emacsframe)
5349 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5351 if (emacsframe == dpyinfo->mouse_face_mouse_frame)
5353 clear_mouse_face (dpyinfo);
5354 dpyinfo->mouse_face_mouse_frame = 0;
5362 if (context_menu_value == -1)
5363 context_menu_value = [sender tag];
5365 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
5366 emacsframe->menu_bar_vector,
5367 (void *)[sender tag]);
5368 ns_send_appdefined (-1);
5373 - (EmacsToolbar *)toolbar
5379 /* this gets called on toolbar button click */
5380 - toolbarClicked: (id)item
5383 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
5385 NSTRACE (toolbarClicked);
5390 /* send first event (for some reason two needed) */
5391 theEvent = [[self window] currentEvent];
5392 emacs_event->kind = TOOL_BAR_EVENT;
5393 XSETFRAME (emacs_event->arg, emacsframe);
5394 EV_TRAILER (theEvent);
5396 emacs_event->kind = TOOL_BAR_EVENT;
5397 /* XSETINT (emacs_event->code, 0); */
5398 emacs_event->arg = AREF (emacsframe->tool_bar_items,
5399 idx + TOOL_BAR_ITEM_KEY);
5400 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5401 EV_TRAILER (theEvent);
5406 - toggleToolbar: (id)sender
5411 emacs_event->kind = NS_NONKEY_EVENT;
5412 emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
5413 EV_TRAILER ((id)nil);
5418 - (void)drawRect: (NSRect)rect
5420 int x = NSMinX (rect), y = NSMinY (rect);
5421 int width = NSWidth (rect), height = NSHeight (rect);
5425 if (!emacsframe || !emacsframe->output_data.ns || ns_in_resize)
5428 ns_clear_frame_area (emacsframe, x, y, width, height);
5429 expose_frame (emacsframe, x, y, width, height);
5430 emacsframe->async_visible = 1;
5431 emacsframe->async_iconified = 0;
5435 /* NSDraggingDestination protocol methods. Actually this is not really a
5436 protocol, but a category of Object. O well... */
5438 -(unsigned int) draggingEntered: (id <NSDraggingInfo>) sender
5440 NSTRACE (draggingEntered);
5441 return NSDragOperationGeneric;
5445 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
5451 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
5456 NSEvent *theEvent = [[self window] currentEvent];
5459 NSTRACE (performDragOperation);
5464 position = [self convertPoint: [sender draggingLocation] fromView: nil];
5465 x = lrint (position.x); y = lrint (position.y);
5467 pb = [sender draggingPasteboard];
5468 type = [pb availableTypeFromArray: ns_drag_types];
5473 else if ([type isEqualToString: NSFilenamesPboardType])
5476 NSEnumerator *fenum;
5479 if (!(files = [pb propertyListForType: type]))
5482 fenum = [files objectEnumerator];
5483 while ( (file = [fenum nextObject]) )
5485 emacs_event->kind = NS_NONKEY_EVENT;
5486 emacs_event->code = KEY_NS_DRAG_FILE;
5487 XSETINT (emacs_event->x, x);
5488 XSETINT (emacs_event->y, y);
5489 ns_input_file = append2 (ns_input_file,
5490 build_string ([file UTF8String]));
5491 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5492 EV_TRAILER (theEvent);
5496 else if ([type isEqualToString: NSURLPboardType])
5501 if (!(fileURL = [NSURL URLFromPasteboard: pb]) ||
5502 [fileURL isFileURL] == NO)
5505 file = [fileURL path];
5506 emacs_event->kind = NS_NONKEY_EVENT;
5507 emacs_event->code = KEY_NS_DRAG_FILE;
5508 XSETINT (emacs_event->x, x);
5509 XSETINT (emacs_event->y, y);
5510 ns_input_file = append2 (ns_input_file, build_string ([file UTF8String]));
5511 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5512 EV_TRAILER (theEvent);
5515 else if ([type isEqualToString: NSStringPboardType]
5516 || [type isEqualToString: NSTabularTextPboardType])
5520 if (! (data = [pb stringForType: type]))
5523 emacs_event->kind = NS_NONKEY_EVENT;
5524 emacs_event->code = KEY_NS_DRAG_TEXT;
5525 XSETINT (emacs_event->x, x);
5526 XSETINT (emacs_event->y, y);
5527 ns_input_text = build_string ([data UTF8String]);
5528 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5529 EV_TRAILER (theEvent);
5532 else if ([type isEqualToString: NSColorPboardType])
5534 NSColor *c = [NSColor colorFromPasteboard: pb];
5535 emacs_event->kind = NS_NONKEY_EVENT;
5536 emacs_event->code = KEY_NS_DRAG_COLOR;
5537 XSETINT (emacs_event->x, x);
5538 XSETINT (emacs_event->y, y);
5539 ns_input_color = ns_color_to_lisp (c);
5540 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5541 EV_TRAILER (theEvent);
5544 else if ([type isEqualToString: NSFontPboardType])
5546 /* impl based on GNUstep NSTextView.m */
5547 NSData *data = [pb dataForType: NSFontPboardType];
5548 NSDictionary *dict = [NSUnarchiver unarchiveObjectWithData: data];
5549 NSFont *font = [dict objectForKey: NSFontAttributeName];
5555 emacs_event->kind = NS_NONKEY_EVENT;
5556 emacs_event->code = KEY_NS_CHANGE_FONT;
5557 XSETINT (emacs_event->x, x);
5558 XSETINT (emacs_event->y, y);
5559 ns_input_font = build_string ([[font fontName] UTF8String]);
5560 snprintf (fontSize, 10, "%f", [font pointSize]);
5561 ns_input_fontsize = build_string (fontSize);
5562 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5563 EV_TRAILER (theEvent);
5568 error ("Invalid data type in dragging pasteboard.");
5574 - validRequestorForSendType: (NSString *)typeSent
5575 returnType: (NSString *)typeReturned
5577 NSTRACE (validRequestorForSendType);
5578 if ([ns_send_types indexOfObjectIdenticalTo: typeSent] != NSNotFound &&
5579 [ns_return_types indexOfObjectIdenticalTo: typeSent] != NSNotFound)
5582 return [super validRequestorForSendType: typeSent
5583 returnType: typeReturned];
5587 /* The next two methods are part of NSServicesRequests informal protocol,
5588 supposedly called when a services menu item is chosen from this app.
5589 But this should not happen because we override the services menu with our
5590 own entries which call ns-perform-service.
5591 Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
5592 So let's at least stub them out until further investigation can be done. */
5594 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
5596 /* we could call ns_string_from_pasteboard(pboard) here but then it should
5597 be written into the buffer in place of the existing selection..
5598 ordinary service calls go through functions defined in ns-win.el */
5602 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
5604 /* supposed to write for as many of types as we are able */
5609 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
5610 (gives a miniaturized version of the window); currently we use the latter for
5611 frames whose active buffer doesn't correspond to any file
5612 (e.g., '*scratch*') */
5613 - setMiniwindowImage: (BOOL) setMini
5615 id image = [[self window] miniwindowImage];
5616 NSTRACE (setMiniwindowImage);
5618 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
5619 about "AppleDockIconEnabled" notwithstanding, however the set message
5620 below has its effect nonetheless. */
5621 if (image != emacsframe->output_data.ns->miniimage)
5623 if (image && [image isKindOfClass: [EmacsImage class]])
5625 [[self window] setMiniwindowImage:
5626 setMini ? emacsframe->output_data.ns->miniimage : nil];
5633 - (void) setRows: (int) r andColumns: (int) c
5639 @end /* EmacsView */
5643 /* ==========================================================================
5645 EmacsWindow implementation
5647 ========================================================================== */
5649 @implementation EmacsWindow
5651 /* called only on resize clicks by special case in EmacsApp-sendEvent */
5652 - (void)mouseDown: (NSEvent *)theEvent
5656 NSSize size = [[theEvent window] frame].size;
5657 grabOffset = [theEvent locationInWindow];
5658 grabOffset.x = size.width - grabOffset.x;
5661 [super mouseDown: theEvent];
5666 - (void)mouseUp: (NSEvent *)theEvent
5670 struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
5672 ns_set_name_as_filename (f);
5674 ns_send_appdefined (-1);
5677 [super mouseUp: theEvent];
5681 /* send resize events */
5682 - (void)mouseDragged: (NSEvent *)theEvent
5686 NSPoint p = [theEvent locationInWindow];
5687 NSSize size, vettedSize, origSize = [self frame].size;
5689 size.width = p.x + grabOffset.x;
5690 size.height = origSize.height - p.y + grabOffset.y;
5692 if (size.width == origSize.width && size.height == origSize.height)
5695 vettedSize = [[self delegate] windowWillResize: self toSize: size];
5696 if (vettedSize.width != size.width || vettedSize.height != size.height)
5698 [[NSNotificationCenter defaultCenter]
5699 postNotificationName: NSWindowDidResizeNotification
5704 [super mouseDragged: theEvent];
5707 @end /* EmacsWindow */
5710 /* ==========================================================================
5712 EmacsScroller implementation
5714 ========================================================================== */
5717 @implementation EmacsScroller
5719 /* for repeat button push */
5720 #define SCROLL_BAR_FIRST_DELAY 0.5
5721 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
5723 + (float) scrollerWidth
5725 /* TODO: if we want to allow variable widths, this is the place to do it,
5726 however neither GNUstep nor Cocoa support it very well */
5727 return [NSScroller scrollerWidth];
5731 - initFrame: (NSRect )r window: (Lisp_Object)nwin
5733 NSTRACE (EmacsScroller_initFrame);
5735 r.size.width = [EmacsScroller scrollerWidth];
5736 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
5737 [self setContinuous: YES];
5738 [self setEnabled: YES];
5740 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
5741 locked against the right, top and bottom edges. */
5742 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
5746 pixel_height = NSHeight (r);
5747 min_portion = 20 / pixel_height;
5749 frame = XFRAME (XWINDOW (win)->frame);
5750 if (FRAME_LIVE_P (frame))
5753 EmacsView *view = FRAME_NS_VIEW (frame);
5754 NSView *sview = [[view window] contentView];
5755 NSArray *subs = [sview subviews];
5757 /* disable optimization stopping redraw of other scrollbars */
5758 view->scrollbarsNeedingUpdate = 0;
5759 for (i =[subs count]-1; i >= 0; i--)
5760 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
5761 view->scrollbarsNeedingUpdate++;
5762 [sview addSubview: self];
5765 /* [self setFrame: r]; */
5771 - (void)setFrame: (NSRect)newRect
5773 NSTRACE (EmacsScroller_setFrame);
5775 pixel_height = NSHeight (newRect);
5776 min_portion = 20 / pixel_height;
5777 [super setFrame: newRect];
5779 /* UNBLOCK_INPUT; */
5785 NSTRACE (EmacsScroller_dealloc);
5787 XWINDOW (win)->vertical_scroll_bar = Qnil;
5814 /* ensure other scrollbar updates after deletion */
5815 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
5817 view->scrollbarsNeedingUpdate++;
5818 [self removeFromSuperview];
5826 - (void)resetCursorRects
5828 NSRect visible = [self visibleRect];
5829 NSTRACE (resetCursorRects);
5831 if (!NSIsEmptyRect (visible))
5832 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
5833 [[NSCursor arrowCursor] setOnMouseEntered: YES];
5837 - (int) checkSamePosition: (int) position portion: (int) portion
5840 return em_position ==position && em_portion ==portion && em_whole ==whole
5841 && portion != whole; /* needed for resize empty buf */
5845 - setPosition: (int)position portion: (int)portion whole: (int)whole
5847 NSTRACE (setPosition);
5849 em_position = position;
5850 em_portion = portion;
5853 if (portion >= whole)
5854 [self setFloatValue: 0.0 knobProportion: 1.0];
5858 portion = max ((float)whole*min_portion/pixel_height, portion);
5859 pos = (float)position / (whole - portion);
5860 por = (float)portion/whole;
5861 [self setFloatValue: pos knobProportion: por];
5863 #ifdef NS_IMPL_GNUSTEP
5869 /* FIXME: unused at moment (see ns_mouse_position) at the moment because
5870 drag events will go directly to the EmacsScroller. Leaving in for now. */
5871 -(void)getMouseMotionPart: (int *)part window: (Lisp_Object *)window
5872 x: (Lisp_Object *)x y: ( Lisp_Object *)y
5874 *part = last_hit_part;
5876 XSETINT (*y, pixel_height);
5877 if ([self floatValue] > 0.999)
5878 XSETINT (*x, pixel_height);
5880 XSETINT (*x, pixel_height * [self floatValue]);
5884 /* set up emacs_event */
5885 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
5890 emacs_event->part = last_hit_part;
5891 emacs_event->code = 0;
5892 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
5893 emacs_event->frame_or_window = win;
5894 emacs_event->timestamp = EV_TIMESTAMP (e);
5895 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
5896 emacs_event->arg = Qnil;
5897 XSETINT (emacs_event->x, loc * pixel_height);
5898 XSETINT (emacs_event->y, pixel_height-20);
5900 n_emacs_events_pending++;
5901 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
5902 EVENT_INIT (*emacs_event);
5903 ns_send_appdefined (-1);
5907 /* called manually thru timer to implement repeated button action w/hold-down */
5908 - repeatScroll: (NSTimer *)scrollEntry
5910 NSEvent *e = [[self window] currentEvent];
5911 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
5912 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
5914 /* clear timer if need be */
5915 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
5917 [scroll_repeat_entry invalidate];
5918 [scroll_repeat_entry release];
5919 scroll_repeat_entry = nil;
5925 = [[NSTimer scheduledTimerWithTimeInterval:
5926 SCROLL_BAR_CONTINUOUS_DELAY
5928 selector: @selector (repeatScroll:)
5934 [self sendScrollEventAtLoc: 0 fromEvent: e];
5939 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
5940 mouseDragged events without going into a modal loop. */
5941 - (void)mouseDown: (NSEvent *)e
5944 /* hitPart is only updated AFTER event is passed on */
5945 NSScrollerPart part = [self testPart: [e locationInWindow]];
5946 double inc = 0.0, loc, kloc, pos;
5949 NSTRACE (EmacsScroller_mouseDown);
5953 case NSScrollerDecrementPage:
5954 last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
5955 case NSScrollerIncrementPage:
5956 last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
5957 case NSScrollerDecrementLine:
5958 last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
5959 case NSScrollerIncrementLine:
5960 last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
5961 case NSScrollerKnob:
5962 last_hit_part = scroll_bar_handle; break;
5963 case NSScrollerKnobSlot: /* GNUstep-only */
5964 last_hit_part = scroll_bar_move_ratio; break;
5965 default: /* NSScrollerNoPart? */
5966 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %d\n", part);
5972 pos = 0; /* ignored */
5974 /* set a timer to repeat, as we can't let superclass do this modally */
5976 = [[NSTimer scheduledTimerWithTimeInterval: 0.5
5978 selector: @selector (repeatScroll:)
5985 /* handle, or on GNUstep possibly slot */
5986 NSEvent *fake_event;
5988 /* compute float loc in slot and mouse offset on knob */
5989 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
5991 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
5997 else if (loc >= NSHeight (sr))
5999 loc = NSHeight (sr);
6007 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
6009 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
6011 last_mouse_offset = kloc;
6013 /* if knob, tell emacs a location offset by knob pos
6014 (to indicate top of handle) */
6015 if (part == NSScrollerKnob)
6016 pos = (loc - last_mouse_offset) / NSHeight (sr);
6018 /* else this is a slot click on GNUstep: go straight there */
6019 pos = loc / NSHeight (sr);
6021 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
6022 fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
6023 location: [e locationInWindow]
6024 modifierFlags: [e modifierFlags]
6025 timestamp: [e timestamp]
6026 windowNumber: [e windowNumber]
6027 context: [e context]
6028 eventNumber: [e eventNumber]
6029 clickCount: [e clickCount]
6030 pressure: [e pressure]];
6031 [super mouseUp: fake_event];
6034 if (part != NSScrollerKnob)
6035 [self sendScrollEventAtLoc: pos fromEvent: e];
6039 /* Called as we manually track scroller drags, rather than superclass. */
6040 - (void)mouseDragged: (NSEvent *)e
6046 NSTRACE (EmacsScroller_mouseDragged);
6048 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6050 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6057 else if (loc >= NSHeight (sr) + last_mouse_offset)
6059 loc = NSHeight (sr) + last_mouse_offset;
6063 pos = /*(edge ? loc :*/ (loc - last_mouse_offset) / NSHeight (sr);
6064 [self sendScrollEventAtLoc: pos fromEvent: e];
6068 - (void)mouseUp: (NSEvent *)e
6070 if (scroll_repeat_entry)
6072 [scroll_repeat_entry invalidate];
6073 [scroll_repeat_entry release];
6074 scroll_repeat_entry = nil;
6080 /* treat scrollwheel events in the bar as though they were in the main window */
6081 - (void) scrollWheel: (NSEvent *)theEvent
6083 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
6084 [view mouseDown: theEvent];
6087 @end /* EmacsScroller */
6092 /* ==========================================================================
6094 Font-related functions; these used to be in nsfaces.m
6096 ========================================================================== */
6100 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
6102 struct font *font = XFONT_OBJECT (font_object);
6105 fontset = fontset_from_font (font_object);
6106 FRAME_FONTSET (f) = fontset;
6108 if (FRAME_FONT (f) == font)
6109 /* This font is already set in frame F. There's nothing more to
6113 FRAME_FONT (f) = font;
6115 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
6116 FRAME_COLUMN_WIDTH (f) = font->average_width;
6117 FRAME_SPACE_WIDTH (f) = font->space_width;
6118 FRAME_LINE_HEIGHT (f) = font->height;
6120 compute_fringe_widths (f, 1);
6122 /* Compute the scroll bar width in character columns. */
6123 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
6125 int wid = FRAME_COLUMN_WIDTH (f);
6126 FRAME_CONFIG_SCROLL_BAR_COLS (f)
6127 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
6131 int wid = FRAME_COLUMN_WIDTH (f);
6132 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
6135 /* Now make the frame display the given font. */
6136 if (FRAME_NS_WINDOW (f) != 0)
6137 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
6143 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
6144 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
6148 ns_xlfd_to_fontname (const char *xlfd)
6149 /* --------------------------------------------------------------------------
6150 Convert an X font name (XLFD) to an NS font name.
6151 Only family is used.
6152 The string returned is temporarily allocated.
6153 -------------------------------------------------------------------------- */
6155 char *name = xmalloc (180);
6159 if (!strncmp (xlfd, "--", 2))
6160 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
6162 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
6164 /* stopgap for malformed XLFD input */
6165 if (strlen (name) == 0)
6166 strcpy (name, "Monaco");
6168 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
6169 also uppercase after '-' or ' ' */
6170 name[0] = toupper (name[0]);
6171 for (len =strlen (name), i =0; i<len; i++)
6177 name[i+1] = toupper (name[i+1]);
6179 else if (name[i] == '_')
6183 name[i+1] = toupper (name[i+1]);
6186 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
6187 ret = [[NSString stringWithUTF8String: name] UTF8String];
6196 NSTRACE (syms_of_nsterm);
6197 DEFVAR_LISP ("ns-input-file", &ns_input_file,
6198 "The file specified in the last NS event.");
6199 ns_input_file =Qnil;
6201 DEFVAR_LISP ("ns-input-text", &ns_input_text,
6202 "The data received in the last NS text drag event.");
6203 ns_input_text =Qnil;
6205 DEFVAR_LISP ("ns-working-text", &ns_working_text,
6206 "String for visualizing working composition sequence.");
6207 ns_working_text =Qnil;
6209 DEFVAR_LISP ("ns-input-font", &ns_input_font,
6210 "The font specified in the last NS event.");
6211 ns_input_font =Qnil;
6213 DEFVAR_LISP ("ns-input-fontsize", &ns_input_fontsize,
6214 "The fontsize specified in the last NS event.");
6215 ns_input_fontsize =Qnil;
6217 DEFVAR_LISP ("ns-input-line", &ns_input_line,
6218 "The line specified in the last NS event.");
6219 ns_input_line =Qnil;
6221 DEFVAR_LISP ("ns-input-color", &ns_input_color,
6222 "The color specified in the last NS event.");
6223 ns_input_color =Qnil;
6225 DEFVAR_LISP ("ns-input-spi-name", &ns_input_spi_name,
6226 "The service name specified in the last NS event.");
6227 ns_input_spi_name =Qnil;
6229 DEFVAR_LISP ("ns-input-spi-arg", &ns_input_spi_arg,
6230 "The service argument specified in the last NS event.");
6231 ns_input_spi_arg =Qnil;
6233 DEFVAR_LISP ("ns-alternate-modifier", &ns_alternate_modifier,
6234 "This variable describes the behavior of the alternate or option key.\n\
6235 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6236 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6237 at all, allowing it to be used at a lower level for accented character entry.");
6239 DEFVAR_LISP ("ns-command-modifier", &ns_command_modifier,
6240 "This variable describes the behavior of the command key.\n\
6241 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6243 DEFVAR_LISP ("ns-control-modifier", &ns_control_modifier,
6244 "This variable describes the behavior of the control key.\n\
6245 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6247 DEFVAR_LISP ("ns-function-modifier", &ns_function_modifier,
6248 "This variable describes the behavior of the function key (on laptops).\n\
6249 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6250 Set to none means that the function key is not interpreted by Emacs at all,\n\
6251 allowing it to be used at a lower level for accented character entry.");
6253 DEFVAR_LISP ("ns-antialias-text", &ns_antialias_text,
6254 "Non-nil (the default) means to render text antialiased. Only has an effect on OS X Panther and above.");
6256 DEFVAR_LISP ("ns-use-qd-smoothing", &ns_use_qd_smoothing,
6257 "Whether to render text using QuickDraw (less heavy) antialiasing. Only has an effect on OS X Panther and above. Default is nil (use Quartz smoothing).");
6259 DEFVAR_LISP ("ns-use-system-highlight-color",
6260 &ns_use_system_highlight_color,
6261 "Whether to use the system default (on OS X only) for the highlight color. Nil means to use standard emacs (prior to version 21) 'grey'.");
6263 DEFVAR_LISP ("ns-confirm-quit", &ns_confirm_quit,
6264 "Whether to confirm application quit using dialog.");
6266 staticpro (&ns_display_name_list);
6267 ns_display_name_list = Qnil;
6269 staticpro (&last_mouse_motion_frame);
6270 last_mouse_motion_frame = Qnil;
6272 /* from 23+ we need to tell emacs what modifiers there are.. */
6273 Qmodifier_value = intern ("modifier-value");
6274 Qalt = intern ("alt");
6275 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
6276 Qhyper = intern ("hyper");
6277 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
6278 Qmeta = intern ("meta");
6279 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
6280 Qsuper = intern ("super");
6281 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
6282 Qcontrol = intern ("control");
6283 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
6285 /* TODO: move to common code */
6286 DEFVAR_LISP ("x-toolkit-scroll-bars", &Vx_toolkit_scroll_bars,
6287 doc: /* If not nil, Emacs uses toolkit scroll bars. */);
6288 #ifdef USE_TOOLKIT_SCROLL_BARS
6289 Vx_toolkit_scroll_bars = Qt;
6291 Vx_toolkit_scroll_bars = Qnil;
6294 /* these are unsupported but we need the declarations to avoid whining
6295 messages from cus-start.el */
6296 DEFVAR_BOOL ("x-use-underline-position-properties",
6297 &x_use_underline_position_properties,
6298 doc: /* NOT SUPPORTED UNDER NS.
6299 *Non-nil means make use of UNDERLINE_POSITION font properties.
6300 A value of nil means ignore them. If you encounter fonts with bogus
6301 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
6302 to 4.1, set this to nil.
6304 NOTE: Not supported on Mac yet. */);
6305 x_use_underline_position_properties = 0;
6307 DEFVAR_BOOL ("x-underline-at-descent-line",
6308 &x_underline_at_descent_line,
6309 doc: /* NOT SUPPORTED UNDER NS.
6310 *Non-nil means to draw the underline at the same place as the descent line.
6311 A value of nil means to draw the underline according to the value of the
6312 variable `x-use-underline-position-properties', which is usually at the
6313 baseline level. The default value is nil. */);
6314 x_underline_at_descent_line = 0;
6316 /* Tell emacs about this window system. */
6317 Fprovide (intern ("ns"), Qnil);
6321 // arch-tag: 6eaa8f7d-a69b-4e1c-b43d-ab31defbe0d2