1 /* NeXT/Open/GNUstep / MacOSX communication module.
2 Copyright (C) 1989, 1993, 1994, 2005, 2006, 2008, 2009, 2010
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>
40 #include "blockinput.h"
41 #include "sysselect.h"
44 #include "character.h"
46 #include "composite.h"
49 #include "termhooks.h"
60 int term_trace_num = 0;
61 #define NSTRACE(x) fprintf (stderr, "%s:%d: [%d] " #x "\n", \
62 __FILE__, __LINE__, ++term_trace_num)
68 /* ==========================================================================
72 ========================================================================== */
74 /* Convert a symbol indexed with an NSxxx value to a value as defined
75 in keyboard.c (lispy_function_key). I hope this is a correct way
77 static unsigned convert_ns_to_X_keysym[] =
79 NSHomeFunctionKey, 0x50,
80 NSLeftArrowFunctionKey, 0x51,
81 NSUpArrowFunctionKey, 0x52,
82 NSRightArrowFunctionKey, 0x53,
83 NSDownArrowFunctionKey, 0x54,
84 NSPageUpFunctionKey, 0x55,
85 NSPageDownFunctionKey, 0x56,
86 NSEndFunctionKey, 0x57,
87 NSBeginFunctionKey, 0x58,
88 NSSelectFunctionKey, 0x60,
89 NSPrintFunctionKey, 0x61,
90 NSExecuteFunctionKey, 0x62,
91 NSInsertFunctionKey, 0x63,
92 NSUndoFunctionKey, 0x65,
93 NSRedoFunctionKey, 0x66,
94 NSMenuFunctionKey, 0x67,
95 NSFindFunctionKey, 0x68,
96 NSHelpFunctionKey, 0x6A,
97 NSBreakFunctionKey, 0x6B,
99 NSF1FunctionKey, 0xBE,
100 NSF2FunctionKey, 0xBF,
101 NSF3FunctionKey, 0xC0,
102 NSF4FunctionKey, 0xC1,
103 NSF5FunctionKey, 0xC2,
104 NSF6FunctionKey, 0xC3,
105 NSF7FunctionKey, 0xC4,
106 NSF8FunctionKey, 0xC5,
107 NSF9FunctionKey, 0xC6,
108 NSF10FunctionKey, 0xC7,
109 NSF11FunctionKey, 0xC8,
110 NSF12FunctionKey, 0xC9,
111 NSF13FunctionKey, 0xCA,
112 NSF14FunctionKey, 0xCB,
113 NSF15FunctionKey, 0xCC,
114 NSF16FunctionKey, 0xCD,
115 NSF17FunctionKey, 0xCE,
116 NSF18FunctionKey, 0xCF,
117 NSF19FunctionKey, 0xD0,
118 NSF20FunctionKey, 0xD1,
119 NSF21FunctionKey, 0xD2,
120 NSF22FunctionKey, 0xD3,
121 NSF23FunctionKey, 0xD4,
122 NSF24FunctionKey, 0xD5,
124 NSBackspaceCharacter, 0x08, /* 8: Not on some KBs. */
125 NSDeleteCharacter, 0xFF, /* 127: Big 'delete' key upper right. */
126 NSDeleteFunctionKey, 0x9F, /* 63272: Del forw key off main array. */
128 NSTabCharacter, 0x09,
129 0x19, 0x09, /* left tab->regular since pass shift */
130 NSCarriageReturnCharacter, 0x0D,
131 NSNewlineCharacter, 0x0D,
132 NSEnterCharacter, 0x8D,
134 0x1B, 0x1B /* escape */
138 /* Lisp communications */
139 Lisp_Object ns_input_file, ns_input_font, ns_input_fontsize, ns_input_line;
140 Lisp_Object ns_input_color, ns_input_text, ns_working_text;
141 Lisp_Object ns_input_spi_name, ns_input_spi_arg;
142 Lisp_Object Vx_toolkit_scroll_bars;
143 static Lisp_Object Qmodifier_value;
144 Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper, Qnone;
145 extern Lisp_Object Qcursor_color, Qcursor_type, Qns, Qleft;
147 /* Specifies which emacs modifier should be generated when NS receives
148 the Alternate modifier. 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 right Alternate modifier. Has same values as ns_alternate_modifier plus
153 the value Qleft which means whatever value ns_alternate_modifier has. */
154 Lisp_Object ns_right_alternate_modifier;
156 /* Specifies which emacs modifier should be generated when NS receives
157 the Command modifier. May be any of the modifier lisp symbols. */
158 Lisp_Object ns_command_modifier;
160 /* Specifies which emacs modifier should be generated when NS receives
161 the Control modifier. May be any of the modifier lisp symbols. */
162 Lisp_Object ns_control_modifier;
164 /* Specifies which emacs modifier should be generated when NS receives
165 the Function modifier (laptops). May be any of the modifier lisp symbols. */
166 Lisp_Object ns_function_modifier;
168 /* Control via default 'GSFontAntiAlias' on OS X and GNUstep. */
169 Lisp_Object ns_antialias_text;
171 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
172 the maximum font size to NOT antialias. On GNUstep there is currently
173 no way to control this behavior. */
174 float ns_antialias_threshold;
176 /* Used to pick up AppleHighlightColor on OS X */
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;
183 NSString *ns_app_name = @"Emacs"; /* default changed later */
185 /* Display variables */
186 struct ns_display_info *x_display_list; /* Chain of existing displays */
187 Lisp_Object ns_display_name_list;
188 long context_menu_value = 0;
191 NSPoint last_mouse_motion_position;
192 static NSRect last_mouse_glyph;
193 static unsigned long last_mouse_movement_time = 0;
194 static Lisp_Object last_mouse_motion_frame;
195 static EmacsScroller *last_mouse_scroll_bar = nil;
196 static struct frame *ns_updating_frame;
197 static NSView *focus_view = NULL;
198 static int ns_window_num =0;
200 static BOOL gsaved = NO;
201 BOOL ns_in_resize = NO;
202 static BOOL ns_fake_keydown = NO;
203 int ns_tmp_flags; /* FIXME */
204 struct nsfont_info *ns_tmp_font; /* FIXME */
205 /*static int debug_lock = 0; */
208 static BOOL send_appdefined = YES;
209 static NSEvent *last_appdefined_event = 0;
210 static NSTimer *timed_entry = 0;
211 static NSTimer *fd_entry = nil;
212 static NSTimer *scroll_repeat_entry = nil;
213 static fd_set select_readfds, t_readfds;
214 static struct timeval select_timeout;
215 static int select_nfds;
216 static NSAutoreleasePool *outerpool;
217 static struct input_event *emacs_event = NULL;
218 static struct input_event *q_event_ptr = NULL;
219 static int n_emacs_events_pending = 0;
220 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
221 *ns_pending_service_args;
222 static BOOL inNsSelect = 0;
224 /* Convert modifiers in a NeXTSTEP event to emacs style modifiers. */
225 #define NS_FUNCTION_KEY_MASK 0x800000
226 #define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
227 #define EV_MODIFIERS(e) \
228 ((([e modifierFlags] & NSHelpKeyMask) ? \
229 hyper_modifier : 0) \
230 | (!EQ (ns_right_alternate_modifier, Qleft) && \
231 (([e modifierFlags] & NSRightAlternateKeyMask) \
232 == NSRightAlternateKeyMask) ? \
233 parse_solitary_modifier (ns_right_alternate_modifier) : 0) \
234 | (([e modifierFlags] & NSAlternateKeyMask) ? \
235 parse_solitary_modifier (ns_alternate_modifier) : 0) \
236 | (([e modifierFlags] & NSShiftKeyMask) ? \
237 shift_modifier : 0) \
238 | (([e modifierFlags] & NSControlKeyMask) ? \
239 parse_solitary_modifier (ns_control_modifier) : 0) \
240 | (([e modifierFlags] & NS_FUNCTION_KEY_MASK) ? \
241 parse_solitary_modifier (ns_function_modifier) : 0) \
242 | (([e modifierFlags] & NSCommandKeyMask) ? \
243 parse_solitary_modifier (ns_command_modifier):0))
245 #define EV_UDMODIFIERS(e) \
246 ((([e type] == NSLeftMouseDown) ? down_modifier : 0) \
247 | (([e type] == NSRightMouseDown) ? down_modifier : 0) \
248 | (([e type] == NSOtherMouseDown) ? down_modifier : 0) \
249 | (([e type] == NSLeftMouseDragged) ? down_modifier : 0) \
250 | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
251 | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
252 | (([e type] == NSLeftMouseUp) ? up_modifier : 0) \
253 | (([e type] == NSRightMouseUp) ? up_modifier : 0) \
254 | (([e type] == NSOtherMouseUp) ? up_modifier : 0))
256 #define EV_BUTTON(e) \
257 ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 : \
258 (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
259 [e buttonNumber] - 1)
261 /* Convert the time field to a timestamp in milliseconds. */
262 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
264 /* This is a piece of code which is common to all the event handling
265 methods. Maybe it should even be a function. */
266 #define EV_TRAILER(e) \
268 XSETFRAME (emacs_event->frame_or_window, emacsframe); \
269 if (e) emacs_event->timestamp = EV_TIMESTAMP (e); \
270 n_emacs_events_pending++; \
271 kbd_buffer_store_event_hold (emacs_event, q_event_ptr); \
272 EVENT_INIT (*emacs_event); \
273 ns_send_appdefined (-1); \
276 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
278 /* TODO: get rid of need for these forward declarations */
279 static void ns_condemn_scroll_bars (struct frame *f);
280 static void ns_judge_scroll_bars (struct frame *f);
281 void x_set_frame_alpha (struct frame *f);
283 /* unused variables needed for compatibility reasons */
284 int x_use_underline_position_properties, x_underline_at_descent_line;
285 /* FIXME: figure out what to do with underline_minimum_offset. */
288 /* ==========================================================================
292 ========================================================================== */
296 append2 (Lisp_Object list, Lisp_Object item)
297 /* --------------------------------------------------------------------------
298 Utility to append to a list
299 -------------------------------------------------------------------------- */
301 Lisp_Object array[2];
303 array[1] = Fcons (item, Qnil);
304 return Fnconc (2, &array[0]);
310 /* --------------------------------------------------------------------------
311 Used to allow emacs to find its resources under Emacs.app
312 Called from emacs.c at startup.
313 -------------------------------------------------------------------------- */
315 NSBundle *bundle = [NSBundle mainBundle];
316 NSString *binDir = [bundle bundlePath], *resourceDir = [bundle resourcePath];
317 NSString *resourcePath, *resourcePaths;
319 BOOL onWindows = NO; /* how do I determine this? */
320 NSString *pathSeparator = onWindows ? @";" : @":";
321 NSFileManager *fileManager = [NSFileManager defaultManager];
323 /*NSLog (@"ns_init_paths: '%@'\n%@\n", [[NSBundle mainBundle] bundlePath], [[NSBundle mainBundle] resourcePath]); */
325 /* get bindir from base */
326 range = [resourceDir rangeOfString: @"Contents"];
327 if (range.location != NSNotFound)
329 binDir = [binDir stringByAppendingPathComponent: @"Contents"];
331 binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
335 /* the following based on Andrew Choi's init_mac_osx_environment () */
336 if (!getenv ("EMACSLOADPATH"))
338 NSArray *paths = [resourceDir stringsByAppendingPaths:
339 [NSArray arrayWithObjects:
340 @"site-lisp", @"lisp", @"leim", nil]];
341 NSEnumerator *pathEnum = [paths objectEnumerator];
343 while (resourcePath = [pathEnum nextObject])
345 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
348 if ([resourcePaths length] > 0)
350 = [resourcePaths stringByAppendingString: pathSeparator];
352 = [resourcePaths stringByAppendingString: resourcePath];
355 if ([resourcePaths length] > 0)
356 setenv ("EMACSLOADPATH", [resourcePaths UTF8String], 1);
357 /*NSLog (@"loadPath: '%@'\n", resourcePaths); */
360 if (!getenv ("EMACSPATH"))
362 NSArray *paths = [binDir stringsByAppendingPaths:
363 [NSArray arrayWithObjects: @"bin",
365 NSEnumerator *pathEnum = [paths objectEnumerator];
367 while (resourcePath = [pathEnum nextObject])
369 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
372 if ([resourcePaths length] > 0)
374 = [resourcePaths stringByAppendingString: pathSeparator];
376 = [resourcePaths stringByAppendingString: resourcePath];
379 if ([resourcePaths length] > 0)
380 setenv ("EMACSPATH", [resourcePaths UTF8String], 1);
383 resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
384 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
388 if (!getenv ("EMACSDATA"))
389 setenv ("EMACSDATA", [resourcePath UTF8String], 1);
390 if (!getenv ("EMACSDOC"))
391 setenv ("EMACSDOC", [resourcePath UTF8String], 1);
395 if (!getenv ("INFOPATH"))
397 resourcePath = [resourceDir stringByAppendingPathComponent: @"info"];
398 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
400 setenv ("INFOPATH", [[resourcePath stringByAppendingString: @":"]
402 /* Note, extra colon needed to cause merge w/later user additions. */
408 timeval_subtract (struct timeval *result, struct timeval x, struct timeval y)
409 /* --------------------------------------------------------------------------
410 Subtract the `struct timeval' values X and Y, storing the result in RESULT.
411 Return 1 if the difference is negative, otherwise 0.
412 -------------------------------------------------------------------------- */
414 /* Perform the carry for the later subtraction by updating y.
415 This is safer because on some systems
416 the tv_sec member is unsigned. */
417 if (x.tv_usec < y.tv_usec)
419 int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
420 y.tv_usec -= 1000000 * nsec;
423 if (x.tv_usec - y.tv_usec > 1000000)
425 int nsec = (y.tv_usec - x.tv_usec) / 1000000;
426 y.tv_usec += 1000000 * nsec;
430 /* Compute the time remaining to wait. tv_usec is certainly positive. */
431 result->tv_sec = x.tv_sec - y.tv_sec;
432 result->tv_usec = x.tv_usec - y.tv_usec;
434 /* Return indication of whether the result should be considered negative. */
435 return x.tv_sec < y.tv_sec;
439 ns_timeout (int usecs)
440 /* --------------------------------------------------------------------------
441 Blocking timer utility used by ns_ring_bell
442 -------------------------------------------------------------------------- */
444 struct timeval wakeup;
446 EMACS_GET_TIME (wakeup);
448 /* Compute time to wait until, propagating carry from usecs. */
449 wakeup.tv_usec += usecs;
450 wakeup.tv_sec += (wakeup.tv_usec / 1000000);
451 wakeup.tv_usec %= 1000000;
453 /* Keep waiting until past the time wakeup. */
456 struct timeval timeout;
458 EMACS_GET_TIME (timeout);
460 /* In effect, timeout = wakeup - timeout.
461 Break if result would be negative. */
462 if (timeval_subtract (&timeout, wakeup, timeout))
465 /* Try to wait that long--but we might wake up sooner. */
466 select (0, NULL, NULL, NULL, &timeout);
472 ns_release_object (void *obj)
473 /* --------------------------------------------------------------------------
474 Release an object (callable from C)
475 -------------------------------------------------------------------------- */
482 ns_retain_object (void *obj)
483 /* --------------------------------------------------------------------------
484 Retain an object (callable from C)
485 -------------------------------------------------------------------------- */
492 ns_alloc_autorelease_pool (void)
493 /* --------------------------------------------------------------------------
494 Allocate a pool for temporary objects (callable from C)
495 -------------------------------------------------------------------------- */
497 return [[NSAutoreleasePool alloc] init];
502 ns_release_autorelease_pool (void *pool)
503 /* --------------------------------------------------------------------------
504 Free a pool and temporary objects it refers to (callable from C)
505 -------------------------------------------------------------------------- */
507 ns_release_object (pool);
512 /* ==========================================================================
514 Focus (clipping) and screen update
516 ========================================================================== */
519 ns_resize_handle_rect (NSWindow *window)
521 NSRect r = [window frame];
522 r.origin.x = r.size.width - RESIZE_HANDLE_SIZE;
524 r.size.width = r.size.height = RESIZE_HANDLE_SIZE;
530 ns_update_begin (struct frame *f)
531 /* --------------------------------------------------------------------------
532 Prepare for a grouped sequence of drawing calls
533 external (RIF) call; whole frame, called before update_window_begin
534 -------------------------------------------------------------------------- */
536 NSView *view = FRAME_NS_VIEW (f);
537 NSTRACE (ns_update_begin);
539 ns_updating_frame = f;
542 #ifdef NS_IMPL_GNUSTEP
543 uRect = NSMakeRect (0, 0, 0, 0);
549 ns_update_window_begin (struct window *w)
550 /* --------------------------------------------------------------------------
551 Prepare for a grouped sequence of drawing calls
552 external (RIF) call; for one window, called after update_begin
553 -------------------------------------------------------------------------- */
555 struct frame *f = XFRAME (WINDOW_FRAME (w));
556 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
557 NSTRACE (ns_update_window_begin);
560 set_output_cursor (&w->cursor);
564 if (f == dpyinfo->mouse_face_mouse_frame)
566 /* Don't do highlighting for mouse motion during the update. */
567 dpyinfo->mouse_face_defer = 1;
569 /* If the frame needs to be redrawn,
570 simply forget about any prior mouse highlighting. */
571 if (FRAME_GARBAGED_P (f))
572 dpyinfo->mouse_face_window = Qnil;
574 /* (further code for mouse faces ifdef'd out in other terms elided) */
582 ns_update_window_end (struct window *w, int cursor_on_p,
583 int mouse_face_overwritten_p)
584 /* --------------------------------------------------------------------------
585 Finished a grouped sequence of drawing calls
586 external (RIF) call; for one window called before update_end
587 -------------------------------------------------------------------------- */
589 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (XFRAME (w->frame));
591 /* note: this fn is nearly identical in all terms */
592 if (!w->pseudo_window_p)
597 display_and_set_cursor (w, 1,
598 output_cursor.hpos, output_cursor.vpos,
599 output_cursor.x, output_cursor.y);
601 if (draw_window_fringes (w, 1))
602 x_draw_vertical_border (w);
607 /* If a row with mouse-face was overwritten, arrange for
608 frame_up_to_date to redisplay the mouse highlight. */
609 if (mouse_face_overwritten_p)
611 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
612 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
613 dpyinfo->mouse_face_window = Qnil;
616 updated_window = NULL;
617 NSTRACE (update_window_end);
622 ns_update_end (struct frame *f)
623 /* --------------------------------------------------------------------------
624 Finished a grouped sequence of drawing calls
625 external (RIF) call; for whole frame, called after update_window_end
626 -------------------------------------------------------------------------- */
628 NSView *view = FRAME_NS_VIEW (f);
630 /* if (f == FRAME_NS_DISPLAY_INFO (f)->mouse_face_mouse_frame) */
631 FRAME_NS_DISPLAY_INFO (f)->mouse_face_defer = 0;
635 #ifdef NS_IMPL_GNUSTEP
636 /* trigger flush only in the rectangle we tracked as being drawn */
637 [view unlockFocusNeedsFlush: NO];
638 /*fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", uRect.origin.x, uRect.origin.y, uRect.size.width, uRect.size.height); */
639 [view lockFocusInRect: uRect];
643 [[view window] flushWindow];
646 ns_updating_frame = NULL;
647 NSTRACE (ns_update_end);
652 ns_flush (struct frame *f)
653 /* --------------------------------------------------------------------------
655 NS impl is no-op since currently we flush in ns_update_end and elsewhere
656 -------------------------------------------------------------------------- */
663 ns_focus (struct frame *f, NSRect *r, int n)
664 /* --------------------------------------------------------------------------
665 Internal: Focus on given frame. During small local updates this is used to
666 draw, however during large updates, ns_update_begin and ns_update_end are
667 called to wrap the whole thing, in which case these calls are stubbed out.
668 Except, on GNUstep, we accumulate the rectangle being drawn into, because
669 the back end won't do this automatically, and will just end up flushing
671 -------------------------------------------------------------------------- */
673 // NSTRACE (ns_focus);
674 #ifdef NS_IMPL_GNUSTEP
677 u = NSUnionRect (r[0], r[1]);
682 fprintf (stderr, "focus: %d", c++);
683 if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
684 fprintf (stderr, "\n"); */
686 if (f != ns_updating_frame)
688 NSView *view = FRAME_NS_VIEW (f);
689 if (view != focus_view)
691 if (focus_view != NULL)
693 [focus_view unlockFocus];
694 [[focus_view window] flushWindow];
699 #ifdef NS_IMPL_GNUSTEP
700 r ? [view lockFocusInRect: u] : [view lockFocus];
705 /*if (view) debug_lock++; */
707 #ifdef NS_IMPL_GNUSTEP
710 /* more than one rect being drawn into */
713 [view unlockFocus]; /* add prev rect to redraw list */
714 [view lockFocusInRect: u]; /* focus for draw in new rect */
719 #ifdef NS_IMPL_GNUSTEP
722 /* in batch mode, but in GNUstep must still track rectangles explicitly */
723 uRect = (r ? NSUnionRect (uRect, u) : [FRAME_NS_VIEW (f) visibleRect]);
730 [[NSGraphicsContext currentContext] saveGraphicsState];
732 NSRectClipList (r, 2);
741 ns_unfocus (struct frame *f)
742 /* --------------------------------------------------------------------------
743 Internal: Remove focus on given frame
744 -------------------------------------------------------------------------- */
746 // NSTRACE (ns_unfocus);
750 [[NSGraphicsContext currentContext] restoreGraphicsState];
754 if (f != ns_updating_frame)
756 if (focus_view != NULL)
758 [focus_view unlockFocus];
759 [[focus_view window] flushWindow];
768 ns_clip_to_row (struct window *w, struct glyph_row *row, int area, BOOL gc)
769 /* --------------------------------------------------------------------------
770 Internal (but parallels other terms): Focus drawing on given row
771 -------------------------------------------------------------------------- */
773 struct frame *f = XFRAME (WINDOW_FRAME (w));
775 int window_x, window_y, window_width;
777 window_box (w, area, &window_x, &window_y, &window_width, 0);
779 clip_rect.origin.x = window_x - FRAME_INTERNAL_BORDER_WIDTH (f);
780 clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
781 clip_rect.origin.y = max (clip_rect.origin.y, window_y);
782 clip_rect.size.width = window_width + 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
783 clip_rect.size.height = row->visible_height;
785 /* allow a full-height row at the top when requested
786 (used to draw fringe all the way through internal border area) */
787 if (gc && clip_rect.origin.y < 5)
789 clip_rect.origin.y -= FRAME_INTERNAL_BORDER_WIDTH (f);
790 clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
793 /* likewise at bottom */
795 FRAME_PIXEL_HEIGHT (f) - (clip_rect.origin.y + clip_rect.size.height) < 5)
796 clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
798 ns_focus (f, &clip_rect, 1);
803 ns_ring_bell (struct frame *f)
804 /* --------------------------------------------------------------------------
806 -------------------------------------------------------------------------- */
808 NSTRACE (ns_ring_bell);
811 NSAutoreleasePool *pool;
812 struct frame *frame = SELECTED_FRAME ();
816 pool = [[NSAutoreleasePool alloc] init];
818 view = FRAME_NS_VIEW (frame);
822 NSPoint dim = NSMakePoint (128, 128);
825 r.origin.x += (r.size.width - dim.x) / 2;
826 r.origin.y += (r.size.height - dim.y) / 2;
827 r.size.width = dim.x;
828 r.size.height = dim.y;
829 surr = NSInsetRect (r, -2, -2);
830 ns_focus (frame, &surr, 1);
831 [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
832 [ns_lookup_indexed_color (NS_FACE_FOREGROUND
833 (FRAME_DEFAULT_FACE (frame)), frame) set];
835 [[view window] flushWindow];
837 [[view window] restoreCachedImage];
838 [[view window] flushWindow];
852 ns_reset_terminal_modes (struct terminal *terminal)
853 /* Externally called as hook */
855 NSTRACE (ns_reset_terminal_modes);
860 ns_set_terminal_modes (struct terminal *terminal)
861 /* Externally called as hook */
863 NSTRACE (ns_set_terminal_modes);
868 /* ==========================================================================
870 Frame / window manager related functions
872 ========================================================================== */
876 ns_raise_frame (struct frame *f)
877 /* --------------------------------------------------------------------------
878 Bring window to foreground and make it active
879 -------------------------------------------------------------------------- */
881 NSView *view = FRAME_NS_VIEW (f);
884 FRAME_SAMPLE_VISIBILITY (f);
885 if (FRAME_VISIBLE_P (f))
887 [[view window] makeKeyAndOrderFront: NSApp];
894 ns_lower_frame (struct frame *f)
895 /* --------------------------------------------------------------------------
897 -------------------------------------------------------------------------- */
899 NSView *view = FRAME_NS_VIEW (f);
902 [[view window] orderBack: NSApp];
908 ns_frame_raise_lower (struct frame *f, int raise)
909 /* --------------------------------------------------------------------------
911 -------------------------------------------------------------------------- */
913 NSTRACE (ns_frame_raise_lower);
923 ns_frame_rehighlight (struct frame *frame)
924 /* --------------------------------------------------------------------------
925 External (hook): called on things like window switching within frame
926 -------------------------------------------------------------------------- */
928 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
929 struct frame *old_highlight = dpyinfo->x_highlight_frame;
931 NSTRACE (ns_frame_rehighlight);
932 if (dpyinfo->x_focus_frame)
934 dpyinfo->x_highlight_frame
935 = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
936 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
937 : dpyinfo->x_focus_frame);
938 if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
940 FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
941 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
945 dpyinfo->x_highlight_frame = 0;
947 if (dpyinfo->x_highlight_frame &&
948 dpyinfo->x_highlight_frame != old_highlight)
952 x_update_cursor (old_highlight, 1);
953 x_set_frame_alpha (old_highlight);
955 if (dpyinfo->x_highlight_frame)
957 x_update_cursor (dpyinfo->x_highlight_frame, 1);
958 x_set_frame_alpha (dpyinfo->x_highlight_frame);
965 x_make_frame_visible (struct frame *f)
966 /* --------------------------------------------------------------------------
967 External: Show the window (X11 semantics)
968 -------------------------------------------------------------------------- */
970 NSTRACE (x_make_frame_visible);
971 /* XXX: at some points in past this was not needed, as the only place that
972 called this (frame.c:Fraise_frame ()) also called raise_lower;
973 if this ends up the case again, comment this out again. */
974 if (!FRAME_VISIBLE_P (f))
976 f->async_visible = 1;
983 x_make_frame_invisible (struct frame *f)
984 /* --------------------------------------------------------------------------
985 External: Hide the window (X11 semantics)
986 -------------------------------------------------------------------------- */
988 NSView * view = FRAME_NS_VIEW (f);
989 NSTRACE (x_make_frame_invisible);
991 [[view window] orderOut: NSApp];
992 f->async_visible = 0;
993 f->async_iconified = 0;
998 x_iconify_frame (struct frame *f)
999 /* --------------------------------------------------------------------------
1000 External: Iconify window
1001 -------------------------------------------------------------------------- */
1003 NSView * view = FRAME_NS_VIEW (f);
1004 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1005 NSTRACE (x_iconify_frame);
1008 if (dpyinfo->x_highlight_frame == f)
1009 dpyinfo->x_highlight_frame = 0;
1011 if ([[view window] windowNumber] <= 0)
1013 /* the window is still deferred. Make it very small, bring it
1014 on screen and order it out. */
1015 NSRect s = { { 100, 100}, {0, 0} };
1017 t = [[view window] frame];
1018 [[view window] setFrame: s display: NO];
1019 [[view window] orderBack: NSApp];
1020 [[view window] orderOut: NSApp];
1021 [[view window] setFrame: t display: NO];
1023 [[view window] miniaturize: NSApp];
1028 x_destroy_window (struct frame *f)
1029 /* --------------------------------------------------------------------------
1030 External: Delete the window
1031 -------------------------------------------------------------------------- */
1033 NSView *view = FRAME_NS_VIEW (f);
1034 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1035 NSTRACE (x_destroy_window);
1038 [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1042 free_frame_menubar (f);
1044 if (FRAME_FACE_CACHE (f))
1045 free_frame_faces (f);
1047 if (f == dpyinfo->x_focus_frame)
1048 dpyinfo->x_focus_frame = 0;
1049 if (f == dpyinfo->x_highlight_frame)
1050 dpyinfo->x_highlight_frame = 0;
1051 if (f == dpyinfo->mouse_face_mouse_frame)
1053 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
1054 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
1055 dpyinfo->mouse_face_window = Qnil;
1056 dpyinfo->mouse_face_deferred_gc = 0;
1057 dpyinfo->mouse_face_mouse_frame = 0;
1060 xfree (f->output_data.ns);
1062 [[view window] close];
1071 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1072 /* --------------------------------------------------------------------------
1073 External: Position the window
1074 -------------------------------------------------------------------------- */
1077 NSView *view = FRAME_NS_VIEW (f);
1079 NSTRACE (x_set_offset);
1085 #ifdef NS_IMPL_GNUSTEP
1087 f->left_pos = 100; /* don't overlap menu */
1090 if (view != nil && (screen = [[view window] screen]))
1091 [[view window] setFrameTopLeftPoint:
1092 NSMakePoint (SCREENMAXBOUND (f->left_pos),
1093 SCREENMAXBOUND ([screen frame].size.height
1094 - NS_TOP_POS (f)))];
1100 x_set_window_size (struct frame *f, int change_grav, int cols, int rows)
1101 /* --------------------------------------------------------------------------
1102 Adjust window pixel size based on given character grid size
1103 Impl is a bit more complex than other terms, need to do some
1104 internal clipping and also pay attention to screen constraints.
1105 -------------------------------------------------------------------------- */
1107 EmacsView *view = FRAME_NS_VIEW (f);
1108 EmacsToolbar *toolbar = [view toolbar];
1109 NSWindow *window = [view window];
1110 NSScreen *screen = [window screen];
1111 NSRect wr = [window frame];
1112 int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1113 int pixelwidth, pixelheight;
1114 static int oldRows, oldCols, oldFontWidth, oldFontHeight;
1116 static struct frame *oldF;
1118 NSTRACE (x_set_window_size);
1122 && rows == oldRows && cols == oldCols
1123 && oldFontWidth == FRAME_COLUMN_WIDTH (f)
1124 && oldFontHeight == FRAME_LINE_HEIGHT (f)
1128 /*fprintf (stderr, "\tsetWindowSize: %d x %d, font size %d x %d\n", cols, rows, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f)); */
1132 check_frame_size (f, &rows, &cols);
1136 oldFontWidth = FRAME_COLUMN_WIDTH (f);
1137 oldFontHeight = FRAME_LINE_HEIGHT (f);
1140 f->scroll_bar_actual_width = NS_SCROLL_BAR_WIDTH (f);
1141 compute_fringe_widths (f, 0);
1143 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols);
1144 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
1146 /* If we have a toolbar, take its height into account. */
1148 /* NOTE: previously this would generate wrong result if toolbar not
1149 yet displayed and fixing toolbar_height=32 helped, but
1150 now (200903) seems no longer needed */
1151 FRAME_TOOLBAR_HEIGHT (f) =
1152 NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1153 - FRAME_NS_TITLEBAR_HEIGHT (f);
1155 FRAME_TOOLBAR_HEIGHT (f) = 0;
1157 wr.size.width = pixelwidth + f->border_width;
1158 wr.size.height = pixelheight + FRAME_NS_TITLEBAR_HEIGHT (f)
1159 + FRAME_TOOLBAR_HEIGHT (f);
1161 /* constrain to screen if we can */
1164 NSSize sz = [screen visibleFrame].size;
1165 NSSize ez = { wr.size.width - sz.width, wr.size.height - sz.height };
1168 int cr = ez.width / FRAME_COLUMN_WIDTH (f) + 1;
1171 wr.size.width -= cr * FRAME_COLUMN_WIDTH (f);
1172 pixelwidth -= cr * FRAME_COLUMN_WIDTH (f);
1176 int rr = ez.height / FRAME_LINE_HEIGHT (f) + 1;
1179 wr.size.height -= rr * FRAME_LINE_HEIGHT (f);
1180 pixelheight -= rr * FRAME_LINE_HEIGHT (f);
1182 wr.origin.x = f->left_pos;
1183 wr.origin.y = [screen frame].size.height - NS_TOP_POS (f)
1187 [view setRows: rows andColumns: cols];
1188 [window setFrame: wr display: YES];
1190 /*fprintf (stderr, "\tx_set_window_size %d, %d\t%d, %d\n", cols, rows, pixelwidth, pixelheight); */
1192 /* This is a trick to compensate for Emacs' managing the scrollbar area
1193 as a fixed number of standard character columns. Instead of leaving
1194 blank space for the extra, we chopped it off above. Now for
1195 left-hand scrollbars, we shift all rendering to the left by the
1196 difference between the real width and Emacs' imagined one. For
1197 right-hand bars, don't worry about it since the extra is never used.
1198 (Obviously doesn't work for vertically split windows tho..) */
1200 NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1201 ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1202 - NS_SCROLL_BAR_WIDTH (f), 0)
1203 : NSMakePoint (0, 0);
1204 [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1205 [view setBoundsOrigin: origin];
1208 change_frame_size (f, rows, cols, 0, 1, 0); /* pretend, delay, safe */
1209 FRAME_PIXEL_WIDTH (f) = pixelwidth;
1210 FRAME_PIXEL_HEIGHT (f) = pixelheight;
1211 /* SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */
1213 mark_window_cursors_off (XWINDOW (f->root_window));
1214 cancel_mouse_face (f);
1221 /* ==========================================================================
1225 ========================================================================== */
1229 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1231 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1232 if (idx < 1 || idx >= color_table->avail)
1234 return color_table->colors[idx];
1239 ns_index_color (NSColor *color, struct frame *f)
1241 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1245 if (!color_table->colors)
1247 color_table->size = NS_COLOR_CAPACITY;
1248 color_table->avail = 1; /* skip idx=0 as marker */
1250 = (NSColor **)xmalloc (color_table->size * sizeof (NSColor *));
1251 color_table->colors[0] = nil;
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 attempt to mimic the X11 platform here, down to installing an
1330 X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1331 See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1334 static char hex[20];
1336 float r = -1.0, g, b;
1337 NSString *nsname = [NSString stringWithUTF8String: name];
1339 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1342 if ([nsname isEqualToString: @"ns_selection_color"])
1344 nsname = ns_selection_color;
1345 name = [ns_selection_color UTF8String];
1348 /* First, check for some sort of numeric specification. */
1351 if (name[0] == '0' || name[0] == '1' || name[0] == '.') /* RGB decimal */
1353 NSScanner *scanner = [NSScanner scannerWithString: nsname];
1354 [scanner scanFloat: &r];
1355 [scanner scanFloat: &g];
1356 [scanner scanFloat: &b];
1358 else if (!strncmp(name, "rgb:", 4)) /* A newer X11 format -- rgb:r/g/b */
1360 strncpy (hex, name + 4, 19);
1362 scaling = (strlen(hex) - 2) / 3;
1364 else if (name[0] == '#') /* An old X11 format; convert to newer */
1366 int len = (strlen(name) - 1);
1367 int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1369 scaling = strlen(name+start) / 3;
1370 for (i=0; i<3; i++) {
1371 strncpy(hex + i * (scaling + 1), name + start + i * scaling, scaling);
1372 hex[(i+1) * (scaling + 1) - 1] = '/';
1374 hex[3 * (scaling + 1) - 1] = '\0';
1380 float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1381 if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1391 *col = [NSColor colorWithCalibratedRed: r green: g blue: b alpha: 1.0];
1396 /* Otherwise, color is expected to be from a list */
1398 NSEnumerator *lenum, *cenum;
1402 #ifdef NS_IMPL_GNUSTEP
1403 /* XXX: who is wrong, the requestor or the implementation? */
1404 if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1406 nsname = @"highlightColor";
1409 lenum = [[NSColorList availableColorLists] objectEnumerator];
1410 while ( (clist = [lenum nextObject]) && new == nil)
1412 cenum = [[clist allKeys] objectEnumerator];
1413 while ( (name = [cenum nextObject]) && new == nil )
1415 if ([name compare: nsname
1416 options: NSCaseInsensitiveSearch] == NSOrderedSame )
1417 new = [clist colorWithKey: name];
1423 *col = [new colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1430 ns_get_color_default (const char *name, NSColor *dflt)
1431 /* --------------------------------------------------------------------------
1432 Parse a color or use a default value
1433 -------------------------------------------------------------------------- */
1437 if (ns_get_color (name, &col))
1445 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1446 /* --------------------------------------------------------------------------
1447 Convert a Lisp string object to a NS color
1448 -------------------------------------------------------------------------- */
1450 NSTRACE (ns_lisp_to_color);
1451 if (STRINGP (color))
1452 return ns_get_color (SDATA (color), col);
1453 else if (SYMBOLP (color))
1454 return ns_get_color (SDATA (SYMBOL_NAME (color)), col);
1460 ns_color_to_lisp (NSColor *col)
1461 /* --------------------------------------------------------------------------
1462 Convert a color to a lisp string with the RGB equivalent
1463 -------------------------------------------------------------------------- */
1465 CGFloat red, green, blue, alpha, gray;
1468 NSTRACE (ns_color_to_lisp);
1471 if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1473 if ((str =[[col colorNameComponent] UTF8String]))
1476 return build_string ((char *)str);
1479 [[col colorUsingColorSpaceName: NSCalibratedRGBColorSpace]
1480 getRed: &red green: &green blue: &blue alpha: &alpha];
1481 if (red ==green && red ==blue)
1483 [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1484 getWhite: &gray alpha: &alpha];
1485 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1486 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1488 return build_string (buf);
1491 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1492 lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1495 return build_string (buf);
1500 ns_query_color(void *col, XColor *color_def, int setPixel)
1501 /* --------------------------------------------------------------------------
1502 Get ARGB values out of NSColor col and put them into color_def.
1503 If setPixel, set the pixel to a concatenated version.
1504 and set color_def pixel to the resulting index.
1505 -------------------------------------------------------------------------- */
1509 [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1510 color_def->red = r * 65535;
1511 color_def->green = g * 65535;
1512 color_def->blue = b * 65535;
1514 if (setPixel == YES)
1516 = ARGB_TO_ULONG((int)(a*255),
1517 (int)(r*255), (int)(g*255), (int)(b*255));
1522 ns_defined_color (struct frame *f,
1527 /* --------------------------------------------------------------------------
1528 Return 1 if named color found, and set color_def rgb accordingly.
1529 If makeIndex and alloc are nonzero put the color in the color_table,
1530 and set color_def pixel to the resulting index.
1531 If makeIndex is zero, set color_def pixel to ARGB.
1532 Return 0 if not found
1533 -------------------------------------------------------------------------- */
1536 NSTRACE (ns_defined_color);
1539 if (ns_get_color (name, &col) != 0) /* Color not found */
1544 if (makeIndex && alloc)
1545 color_def->pixel = ns_index_color (col, f);
1546 ns_query_color (col, color_def, !makeIndex);
1553 ns_get_rgb_color (struct frame *f, float r, float g, float b, float a)
1554 /* --------------------------------------------------------------------------
1555 return an autoreleased RGB color
1556 -------------------------------------------------------------------------- */
1558 /*static int c = 1; fprintf (stderr, "color request %d\n", c++); */
1559 if (r < 0.0) r = 0.0;
1560 else if (r > 1.0) r = 1.0;
1561 if (g < 0.0) g = 0.0;
1562 else if (g > 1.0) g = 1.0;
1563 if (b < 0.0) b = 0.0;
1564 else if (b > 1.0) b = 1.0;
1565 if (a < 0.0) a = 0.0;
1566 else if (a > 1.0) a = 1.0;
1567 return (unsigned long) ns_index_color(
1568 [NSColor colorWithCalibratedRed: r green: g blue: b alpha: a], f);
1573 x_set_frame_alpha (struct frame *f)
1574 /* --------------------------------------------------------------------------
1575 change the entire-frame transparency
1576 -------------------------------------------------------------------------- */
1578 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1579 EmacsView *view = FRAME_NS_VIEW (f);
1581 double alpha_min = 1.0;
1583 if (dpyinfo->x_highlight_frame == f)
1584 alpha = f->alpha[0];
1586 alpha = f->alpha[1];
1588 if (FLOATP (Vframe_alpha_lower_limit))
1589 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1590 else if (INTEGERP (Vframe_alpha_lower_limit))
1591 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1595 else if (1.0 < alpha)
1597 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1600 #ifdef NS_IMPL_COCOA
1601 [[view window] setAlphaValue: alpha];
1606 /* ==========================================================================
1610 ========================================================================== */
1614 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1615 /* --------------------------------------------------------------------------
1616 Programmatically reposition mouse pointer in pixel coordinates
1617 -------------------------------------------------------------------------- */
1619 NSTRACE (x_set_mouse_pixel_position);
1622 /* FIXME: this does not work, and what about GNUstep? */
1623 #ifdef NS_IMPL_COCOA
1624 [FRAME_NS_VIEW (f) lockFocus];
1625 PSsetmouse ((float)pix_x, (float)pix_y);
1626 [FRAME_NS_VIEW (f) unlockFocus];
1633 x_set_mouse_position (struct frame *f, int h, int v)
1634 /* --------------------------------------------------------------------------
1635 Programmatically reposition mouse pointer in character coordinates
1636 -------------------------------------------------------------------------- */
1640 pix_x = FRAME_COL_TO_PIXEL_X (f, h) + FRAME_COLUMN_WIDTH (f) / 2;
1641 pix_y = FRAME_LINE_TO_PIXEL_Y (f, v) + FRAME_LINE_HEIGHT (f) / 2;
1643 if (pix_x < 0) pix_x = 0;
1644 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
1646 if (pix_y < 0) pix_y = 0;
1647 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
1649 x_set_mouse_pixel_position (f, pix_x, pix_y);
1654 note_mouse_movement (struct frame *frame, float x, float y)
1655 /* ------------------------------------------------------------------------
1656 Called by EmacsView on mouseMovement events. Passes on
1657 to emacs mainstream code if we moved off of a rect of interest
1658 known as last_mouse_glyph.
1659 ------------------------------------------------------------------------ */
1661 // NSTRACE (note_mouse_movement);
1663 XSETFRAME (last_mouse_motion_frame, frame);
1665 /* Note, this doesn't get called for enter/leave, since we don't have a
1666 position. Those are taken care of in the corresponding NSView methods. */
1668 /* has movement gone beyond last rect we were tracking? */
1669 if (x < last_mouse_glyph.origin.x ||
1670 x >= (last_mouse_glyph.origin.x + last_mouse_glyph.size.width) ||
1671 y < last_mouse_glyph.origin.y ||
1672 y >= (last_mouse_glyph.origin.y + last_mouse_glyph.size.height))
1674 ns_update_begin(frame);
1675 frame->mouse_moved = 1;
1676 note_mouse_highlight (frame, x, y);
1677 remember_mouse_glyph (frame, x, y, &last_mouse_glyph);
1678 ns_update_end(frame);
1687 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1688 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1689 unsigned long *time)
1690 /* --------------------------------------------------------------------------
1691 External (hook): inform emacs about mouse position and hit parts.
1692 If a scrollbar is being dragged, set bar_window, part, x, y, time.
1693 x & y should be position in the scrollbar (the whole bar, not the handle)
1694 and length of scrollbar respectively
1695 -------------------------------------------------------------------------- */
1700 Lisp_Object frame, tail;
1702 struct ns_display_info *dpyinfo;
1704 NSTRACE (ns_mouse_position);
1708 fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1712 dpyinfo = FRAME_NS_DISPLAY_INFO (*fp);
1716 if (last_mouse_scroll_bar != nil && insist == 0)
1718 /* TODO: we do not use this path at the moment because drag events will
1719 go directly to the EmacsScroller. Leaving code in for now. */
1720 [last_mouse_scroll_bar getMouseMotionPart: (int *)part window: bar_window
1722 if (time) *time = last_mouse_movement_time;
1723 last_mouse_scroll_bar = nil;
1727 /* Clear the mouse-moved flag for every frame on this display. */
1728 FOR_EACH_FRAME (tail, frame)
1729 if (FRAME_NS_P (XFRAME (frame))
1730 && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1731 XFRAME (frame)->mouse_moved = 0;
1733 last_mouse_scroll_bar = nil;
1734 if (last_mouse_frame && FRAME_LIVE_P (last_mouse_frame))
1735 f = last_mouse_frame;
1737 f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame
1738 : SELECTED_FRAME ();
1740 if (f && f->output_data.ns) /* TODO: 2nd check no longer needed? */
1742 view = FRAME_NS_VIEW (*fp);
1744 position = [[view window] mouseLocationOutsideOfEventStream];
1745 position = [view convertPoint: position fromView: nil];
1746 remember_mouse_glyph (f, position.x, position.y, &last_mouse_glyph);
1747 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1749 if (bar_window) *bar_window = Qnil;
1750 if (part) *part = 0; /*scroll_bar_handle; */
1752 if (x) XSETINT (*x, lrint (position.x));
1753 if (y) XSETINT (*y, lrint (position.y));
1754 if (time) *time = last_mouse_movement_time;
1764 ns_frame_up_to_date (struct frame *f)
1765 /* --------------------------------------------------------------------------
1766 External (hook): Fix up mouse highlighting right after a full update.
1767 Some highlighting was deferred if GC was happening during
1768 note_mouse_highlight (), while other highlighting was deferred for update.
1769 -------------------------------------------------------------------------- */
1771 NSTRACE (ns_frame_up_to_date);
1775 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1776 if ((dpyinfo->mouse_face_deferred_gc||f ==dpyinfo->mouse_face_mouse_frame)
1777 /*&& dpyinfo->mouse_face_mouse_frame*/)
1781 if (dpyinfo->mouse_face_mouse_frame)
1782 note_mouse_highlight (dpyinfo->mouse_face_mouse_frame,
1783 dpyinfo->mouse_face_mouse_x,
1784 dpyinfo->mouse_face_mouse_y);
1785 dpyinfo->mouse_face_deferred_gc = 0;
1794 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1795 /* --------------------------------------------------------------------------
1796 External (RIF): set frame mouse pointer type.
1797 -------------------------------------------------------------------------- */
1799 NSTRACE (ns_define_frame_cursor);
1800 if (FRAME_POINTER_TYPE (f) != cursor)
1802 EmacsView *view = FRAME_NS_VIEW (f);
1803 FRAME_POINTER_TYPE (f) = cursor;
1804 [[view window] invalidateCursorRectsForView: view];
1805 /* Redisplay assumes this function also draws the changed frame
1806 cursor, but this function doesn't, so do it explicitly. */
1807 x_update_cursor (f, 1);
1813 /* ==========================================================================
1817 ========================================================================== */
1821 ns_convert_key (unsigned code)
1822 /* --------------------------------------------------------------------------
1823 Internal call used by NSView-keyDown.
1824 -------------------------------------------------------------------------- */
1826 const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym)
1827 / sizeof (convert_ns_to_X_keysym[0]));
1829 /* An array would be faster, but less easy to read. */
1830 for (keysym = 0; keysym < last_keysym; keysym += 2)
1831 if (code == convert_ns_to_X_keysym[keysym])
1832 return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
1834 /* if decide to use keyCode and Carbon table, use this line:
1835 return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
1840 x_get_keysym_name (int keysym)
1841 /* --------------------------------------------------------------------------
1842 Called by keyboard.c. Not sure if the return val is important, except
1844 -------------------------------------------------------------------------- */
1846 static char value[16];
1847 NSTRACE (x_get_keysym_name);
1848 sprintf (value, "%d", keysym);
1854 /* ==========================================================================
1856 Block drawing operations
1858 ========================================================================== */
1862 ns_redraw_scroll_bars (struct frame *f)
1866 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
1867 NSTRACE (ns_judge_scroll_bars);
1868 for (i =[subviews count]-1; i >= 0; i--)
1870 view = [subviews objectAtIndex: i];
1871 if (![view isKindOfClass: [EmacsScroller class]]) continue;
1878 ns_clear_frame (struct frame *f)
1879 /* --------------------------------------------------------------------------
1880 External (hook): Erase the entire frame
1881 -------------------------------------------------------------------------- */
1883 NSView *view = FRAME_NS_VIEW (f);
1886 NSTRACE (ns_clear_frame);
1890 /* comes on initial frame because we have
1891 after-make-frame-functions = select-frame */
1892 if (!FRAME_DEFAULT_FACE (f))
1895 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
1897 output_cursor.hpos = output_cursor.vpos = 0;
1898 output_cursor.x = -1;
1903 ns_focus (f, &r, 1);
1904 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
1908 #ifdef NS_IMPL_COCOA
1909 [[view window] display]; /* redraw resize handle */
1912 /* as of 2006/11 or so this is now needed */
1913 ns_redraw_scroll_bars (f);
1919 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
1920 /* --------------------------------------------------------------------------
1921 External (RIF): Clear section of frame
1922 -------------------------------------------------------------------------- */
1924 NSRect r = NSMakeRect (x, y, width, height);
1925 NSView *view = FRAME_NS_VIEW (f);
1926 struct face *face = FRAME_DEFAULT_FACE (f);
1931 NSTRACE (ns_clear_frame_area);
1933 r = NSIntersectionRect (r, [view frame]);
1934 ns_focus (f, &r, 1);
1935 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
1937 #ifdef NS_IMPL_COCOA
1939 /* clip out the resize handle */
1940 NSWindow *window = [FRAME_NS_VIEW (f) window];
1942 = [view convertRect: ns_resize_handle_rect (window) fromView: nil];
1944 ir = NSIntersectionRect (r, ir);
1945 if (NSIsEmptyRect (ir))
1951 #ifdef NS_IMPL_COCOA
1955 NSRect r1 = r, r2 = r; /* upper and lower non-intersecting */
1956 r1.size.height -= ir.size.height;
1957 r2.origin.y += r1.size.height;
1958 r2.size.width -= ir.size.width;
1959 r2.size.height = ir.size.height;
1972 ns_scroll_run (struct window *w, struct run *run)
1973 /* --------------------------------------------------------------------------
1974 External (RIF): Insert or delete n lines at line vpos
1975 -------------------------------------------------------------------------- */
1977 struct frame *f = XFRAME (w->frame);
1978 int x, y, width, height, from_y, to_y, bottom_y;
1980 NSTRACE (ns_scroll_run);
1982 /* begin copy from other terms */
1983 /* Get frame-relative bounding box of the text display area of W,
1984 without mode lines. Include in this box the left and right
1986 window_box (w, -1, &x, &y, &width, &height);
1988 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
1989 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
1990 bottom_y = y + height;
1994 /* Scrolling up. Make sure we don't copy part of the mode
1995 line at the bottom. */
1996 if (from_y + run->height > bottom_y)
1997 height = bottom_y - from_y;
1999 height = run->height;
2003 /* Scolling down. Make sure we don't copy over the mode line.
2005 if (to_y + run->height > bottom_y)
2006 height = bottom_y - to_y;
2008 height = run->height;
2010 /* end copy from other terms */
2021 NSRect srcRect = NSMakeRect (x, from_y, width, height);
2022 NSRect dstRect = NSMakeRect (x, to_y, width, height);
2023 NSPoint dstOrigin = NSMakePoint (x, to_y);
2025 ns_focus (f, &dstRect, 1);
2026 NSCopyBits (0, srcRect , dstOrigin);
2035 ns_after_update_window_line (struct glyph_row *desired_row)
2036 /* --------------------------------------------------------------------------
2037 External (RIF): preparatory to fringe update after text was updated
2038 -------------------------------------------------------------------------- */
2040 struct window *w = updated_window;
2044 NSTRACE (ns_after_update_window_line);
2046 /* begin copy from other terms */
2049 if (!desired_row->mode_line_p && !w->pseudo_window_p)
2050 desired_row->redraw_fringe_bitmaps_p = 1;
2052 /* When a window has disappeared, make sure that no rest of
2053 full-width rows stays visible in the internal border.
2054 Under NS this is drawn inside the fringes. */
2055 if (windows_or_buffers_changed
2056 && (f = XFRAME (w->frame),
2057 width = FRAME_INTERNAL_BORDER_WIDTH (f),
2059 && (height = desired_row->visible_height,
2062 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2064 /* Internal border is drawn below the tool bar. */
2065 if (WINDOWP (f->tool_bar_window)
2066 && w == XWINDOW (f->tool_bar_window))
2068 /* end copy from other terms */
2071 if (!desired_row->full_width_p)
2073 int x1 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2074 + WINDOW_LEFT_FRINGE_WIDTH (w);
2075 int x2 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2076 + FRAME_PIXEL_WIDTH (f) - NS_SCROLL_BAR_WIDTH (f)
2077 - WINDOW_RIGHT_FRINGE_WIDTH (w)
2078 - FRAME_INTERNAL_BORDER_WIDTH (f);
2079 ns_clear_frame_area (f, x1, y, width, height);
2080 ns_clear_frame_area (f, x2, y, width, height);
2088 ns_shift_glyphs_for_insert (struct frame *f,
2089 int x, int y, int width, int height,
2091 /* --------------------------------------------------------------------------
2092 External (RIF): copy an area horizontally, don't worry about clearing src
2093 -------------------------------------------------------------------------- */
2095 NSRect srcRect = NSMakeRect (x, y, width, height);
2096 NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2097 NSPoint dstOrigin = dstRect.origin;
2099 NSTRACE (ns_shift_glyphs_for_insert);
2101 ns_focus (f, &dstRect, 1);
2102 NSCopyBits (0, srcRect, dstOrigin);
2108 /* ==========================================================================
2110 Character encoding and metrics
2112 ========================================================================== */
2116 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2117 /* --------------------------------------------------------------------------
2118 External (RIF); compute left/right overhang of whole string and set in s
2119 -------------------------------------------------------------------------- */
2121 struct face *face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2122 struct font *font = s->font; /*face->font; */
2126 struct font_metrics metrics;
2127 unsigned int codes[2];
2128 codes[0] = *(s->char2b);
2129 codes[1] = *(s->char2b + s->nchars - 1);
2131 font->driver->text_extents (font, codes, 2, &metrics);
2132 s->left_overhang = -metrics.lbearing;
2134 = metrics.rbearing > metrics.width
2135 ? metrics.rbearing - metrics.width : 0;
2139 s->left_overhang = 0;
2140 s->right_overhang = ((struct nsfont_info *)font)->ital ?
2141 FONT_HEIGHT (font) * 0.2 : 0;
2147 /* ==========================================================================
2149 Fringe and cursor drawing
2151 ========================================================================== */
2154 extern int max_used_fringe_bitmap;
2156 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2157 struct draw_fringe_bitmap_params *p)
2158 /* --------------------------------------------------------------------------
2159 External (RIF); fringe-related
2160 -------------------------------------------------------------------------- */
2162 struct frame *f = XFRAME (WINDOW_FRAME (w));
2163 struct face *face = p->face;
2165 static EmacsImage **bimgs = NULL;
2166 static int nBimgs = 0;
2167 /* NS-specific: move internal border inside fringe */
2168 int x = p->bx < 0 ? p->x : p->bx;
2169 int wd = p->bx < 0 ? p->wd : p->nx;
2170 BOOL fringeOnVeryLeft
2171 = x - WINDOW_LEFT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w)
2172 - FRAME_INTERNAL_BORDER_WIDTH (f) < 10;
2173 BOOL fringeOnVeryRight
2174 = FRAME_PIXEL_WIDTH (f) - x - wd - FRAME_INTERNAL_BORDER_WIDTH (f)
2175 - WINDOW_RIGHT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w) < 10;
2176 int xAdjust = FRAME_INTERNAL_BORDER_WIDTH (f) *
2177 (fringeOnVeryLeft ? -1 : (fringeOnVeryRight ? 1 : 0));
2179 /* grow bimgs if needed */
2180 if (nBimgs < max_used_fringe_bitmap)
2182 EmacsImage **newBimgs
2183 = xmalloc (max_used_fringe_bitmap * sizeof (EmacsImage *));
2184 memset (newBimgs, 0, max_used_fringe_bitmap * sizeof (EmacsImage *));
2188 memcpy (newBimgs, bimgs, nBimgs * sizeof (EmacsImage *));
2193 nBimgs = max_used_fringe_bitmap;
2196 /* Must clip because of partially visible lines. */
2197 rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
2198 ns_clip_to_row (w, row, -1, YES);
2200 if (p->bx >= 0 && !p->overlay_p)
2202 int yAdjust = rowY - FRAME_INTERNAL_BORDER_WIDTH (f) < 5 ?
2203 -FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2204 int yIncr = FRAME_PIXEL_HEIGHT (f) - (p->by+yAdjust + p->ny) < 5 ?
2205 FRAME_INTERNAL_BORDER_WIDTH (f) : 0
2206 + (yAdjust ? FRAME_INTERNAL_BORDER_WIDTH (f) : 0);
2207 NSRect r = NSMakeRect (p->bx+xAdjust, p->by+yAdjust, p->nx, p->ny+yIncr);
2209 [ns_lookup_indexed_color(face->background, f) set];
2215 NSRect r = NSMakeRect (p->x+xAdjust, p->y, p->wd, p->h);
2216 NSPoint pt = r.origin;
2217 EmacsImage *img = bimgs[p->which - 1];
2221 unsigned short *bits = p->bits + p->dh;
2222 int len = 8 * p->h/8;
2224 unsigned char *cbits = xmalloc (len);
2226 for (i =0; i<len; i++)
2227 cbits[i] = ~(bits[i] & 0xff);
2228 img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2230 bimgs[p->which - 1] = img;
2235 /* Since we composite the bitmap instead of just blitting it, we need
2236 to erase the whole background. */
2237 [ns_lookup_indexed_color(face->background, f) set];
2240 [img setXBMColor: ns_lookup_indexed_color(face->foreground, f)];
2241 [img compositeToPoint: pt operation: NSCompositeSourceOver];
2248 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2249 int x, int y, int cursor_type, int cursor_width,
2250 int on_p, int active_p)
2251 /* --------------------------------------------------------------------------
2252 External call (RIF): draw cursor
2253 (modeled after x_draw_window_cursor
2254 FIXME: cursor_width is effectively bogus -- it sometimes gets set
2255 in xdisp.c set_frame_cursor_types, sometimes left uninitialized;
2256 DON'T USE IT (no other terms do)
2257 -------------------------------------------------------------------------- */
2261 struct frame *f = WINDOW_XFRAME (w);
2262 struct glyph *phys_cursor_glyph;
2264 struct glyph *cursor_glyph;
2266 /* If cursor is out of bounds, don't draw garbage. This can happen
2267 in mini-buffer windows when switching between echo area glyphs
2270 NSTRACE (dumpcursor);
2271 //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);
2276 w->phys_cursor_type = cursor_type;
2277 w->phys_cursor_on_p = on_p;
2279 if (cursor_type == NO_CURSOR)
2281 w->phys_cursor_width = 0;
2285 if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2287 if (glyph_row->exact_window_width_line_p
2288 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2290 glyph_row->cursor_in_fringe_p = 1;
2291 draw_fringe_bitmap (w, glyph_row, 0);
2296 get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2298 r.origin.x = fx, r.origin.y = fy;
2300 r.size.width = w->phys_cursor_width;
2302 /* FIXME: if we overwrite the internal border area, it does not get erased;
2303 fix by truncating cursor, but better would be to erase properly */
2304 overspill = r.origin.x + r.size.width -
2305 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, WINDOW_BOX_RIGHT_EDGE_X (w)
2306 - WINDOW_TOTAL_FRINGE_WIDTH (w) - FRAME_INTERNAL_BORDER_WIDTH (f));
2308 r.size.width -= overspill;
2310 /* TODO: only needed in rare cases with last-resort font in HELLO..
2311 should we do this more efficiently? */
2312 ns_clip_to_row (w, glyph_row, -1, NO); /* do ns_focus(f, &r, 1); if remove */
2313 [FRAME_CURSOR_COLOR (f) set];
2315 #ifdef NS_IMPL_COCOA
2316 /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2317 atomic. Cleaner ways of doing this should be investigated.
2318 One way would be to set a global variable DRAWING_CURSOR
2319 when making the call to draw_phys..(), don't focus in that
2320 case, then move the ns_unfocus() here after that call. */
2321 NSDisableScreenUpdates ();
2324 switch (cursor_type)
2328 case FILLED_BOX_CURSOR:
2331 case HOLLOW_BOX_CURSOR:
2333 [FRAME_BACKGROUND_COLOR (f) set];
2334 NSRectFill (NSInsetRect (r, 1, 1));
2335 [FRAME_CURSOR_COLOR (f) set];
2339 s.origin.y += lrint (0.75 * s.size.height);
2340 s.size.height = lrint (s.size.height * 0.25);
2345 s.size.width = min (cursor_width, 2); //FIXME(see above)
2347 /* If the character under cursor is R2L, draw the bar cursor
2348 on the right of its glyph, rather than on the left. */
2349 cursor_glyph = get_phys_cursor_glyph (w);
2350 if ((cursor_glyph->resolved_level & 1) != 0)
2351 s.origin.x += cursor_glyph->pixel_width - s.size.width;
2358 /* draw the character under the cursor */
2359 if (cursor_type != NO_CURSOR)
2360 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2362 #ifdef NS_IMPL_COCOA
2363 NSEnableScreenUpdates ();
2370 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2371 /* --------------------------------------------------------------------------
2372 External (RIF): Draw a vertical line.
2373 -------------------------------------------------------------------------- */
2375 struct frame *f = XFRAME (WINDOW_FRAME (w));
2377 NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2379 NSTRACE (ns_draw_vertical_window_border);
2381 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2383 [ns_lookup_indexed_color(face->foreground, f) set];
2385 ns_focus (f, &r, 1);
2392 show_hourglass (struct atimer *timer)
2394 if (hourglass_shown_p)
2399 /* TODO: add NSProgressIndicator to selected frame (see macfns.c) */
2401 hourglass_shown_p = 1;
2407 hide_hourglass (void)
2409 if (!hourglass_shown_p)
2414 /* TODO: remove NSProgressIndicator from all frames */
2416 hourglass_shown_p = 0;
2422 /* ==========================================================================
2424 Glyph drawing operations
2426 ========================================================================== */
2429 static inline NSRect
2430 ns_fix_rect_ibw (NSRect r, int fibw, int frame_pixel_width)
2431 /* --------------------------------------------------------------------------
2432 Under NS we draw internal borders inside fringes, and want full-width
2433 rendering to go all the way to edge. This function makes that correction.
2434 -------------------------------------------------------------------------- */
2436 if (r.origin.y <= fibw+1)
2438 r.size.height += r.origin.y;
2441 if (r.origin.x <= fibw+1)
2443 r.size.width += r.origin.x;
2446 if (frame_pixel_width - (r.origin.x+r.size.width) <= fibw+1)
2447 r.size.width += fibw;
2454 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2455 /* --------------------------------------------------------------------------
2456 Wrapper utility to account for internal border width on full-width lines,
2457 and allow top full-width rows to hit the frame top. nr should be pointer
2458 to two successive NSRects. Number of rects actually used is returned.
2459 -------------------------------------------------------------------------- */
2461 int n = get_glyph_string_clip_rects (s, nr, 2);
2462 if (s->row->full_width_p)
2464 *nr = ns_fix_rect_ibw (*nr, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2465 FRAME_PIXEL_WIDTH (s->f));
2467 *nr = ns_fix_rect_ibw (*(nr+1), FRAME_INTERNAL_BORDER_WIDTH (s->f),
2468 FRAME_PIXEL_WIDTH (s->f));
2475 ns_draw_box (NSRect r, float thickness, NSColor *col, char left_p, char right_p)
2476 /* --------------------------------------------------------------------------
2477 Draw an unfilled rect inside r, optionally leaving left and/or right open.
2478 Note we can't just use an NSDrawRect command, because of the possibility
2479 of some sides not being drawn, and because the rect will be filled.
2480 -------------------------------------------------------------------------- */
2486 s.size.height = thickness;
2488 s.origin.y += r.size.height - thickness;
2491 s.size.height = r.size.height;
2492 s.origin.y = r.origin.y;
2494 /* left, right (optional) */
2495 s.size.width = thickness;
2500 s.origin.x += r.size.width - thickness;
2507 ns_draw_relief (NSRect r, int thickness, char raised_p,
2508 char top_p, char bottom_p, char left_p, char right_p,
2509 struct glyph_string *s)
2510 /* --------------------------------------------------------------------------
2511 Draw a relief rect inside r, optionally leaving some sides open.
2512 Note we can't just use an NSDrawBezel command, because of the possibility
2513 of some sides not being drawn, and because the rect will be filled.
2514 -------------------------------------------------------------------------- */
2516 static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2517 NSColor *newBaseCol = nil;
2520 NSTRACE (ns_draw_relief);
2524 if (s->face->use_box_color_for_shadows_p)
2526 newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2528 /* else if (s->first_glyph->type == IMAGE_GLYPH
2530 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2532 newBaseCol = IMAGE_BACKGROUND (s->img, s->f, 0);
2536 newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2539 if (newBaseCol == nil)
2540 newBaseCol = [NSColor grayColor];
2542 if (newBaseCol != baseCol) /* TODO: better check */
2545 baseCol = [newBaseCol retain];
2547 lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2549 darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2552 [(raised_p ? lightCol : darkCol) set];
2554 /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2557 sr.size.height = thickness;
2558 if (top_p) NSRectFill (sr);
2561 sr.size.height = r.size.height;
2562 sr.size.width = thickness;
2563 if (left_p) NSRectFill (sr);
2565 [(raised_p ? darkCol : lightCol) set];
2568 sr.size.width = r.size.width;
2569 sr.size.height = thickness;
2570 sr.origin.y += r.size.height - thickness;
2571 if (bottom_p) NSRectFill (sr);
2574 sr.size.height = r.size.height;
2575 sr.origin.y = r.origin.y;
2576 sr.size.width = thickness;
2577 sr.origin.x += r.size.width - thickness;
2578 if (right_p) NSRectFill (sr);
2583 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2584 /* --------------------------------------------------------------------------
2585 Function modeled after x_draw_glyph_string_box ().
2586 Sets up parameters for drawing.
2587 -------------------------------------------------------------------------- */
2589 int right_x, last_x;
2590 char left_p, right_p;
2591 struct glyph *last_glyph;
2596 if (s->hl == DRAW_MOUSE_FACE)
2599 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2601 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2606 thickness = face->box_line_width;
2608 NSTRACE (ns_dumpglyphs_box_or_relief);
2610 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2611 ? WINDOW_RIGHT_EDGE_X (s->w)
2612 : window_box_right (s->w, s->area));
2613 last_glyph = (s->cmp || s->img
2614 ? s->first_glyph : s->first_glyph + s->nchars-1);
2616 right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2617 ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2619 left_p = (s->first_glyph->left_box_line_p
2620 || (s->hl == DRAW_MOUSE_FACE
2621 && (s->prev == NULL || s->prev->hl != s->hl)));
2622 right_p = (last_glyph->right_box_line_p
2623 || (s->hl == DRAW_MOUSE_FACE
2624 && (s->next == NULL || s->next->hl != s->hl)));
2626 r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2628 /* expand full-width row over internal borders */
2629 if (s->row->full_width_p)
2630 r = ns_fix_rect_ibw (r, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2631 FRAME_PIXEL_WIDTH (s->f));
2633 /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
2634 if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
2636 ns_draw_box (r, abs (thickness),
2637 ns_lookup_indexed_color (face->box_color, s->f),
2642 ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2643 1, 1, left_p, right_p, s);
2649 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2650 /* --------------------------------------------------------------------------
2651 Modeled after x_draw_glyph_string_background, which draws BG in
2652 certain cases. Others are left to the text rendering routine.
2653 -------------------------------------------------------------------------- */
2655 NSTRACE (ns_maybe_dumpglyphs_background);
2657 if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2659 int box_line_width = max (s->face->box_line_width, 0);
2660 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2661 || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2664 if (s->hl == DRAW_MOUSE_FACE)
2667 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2669 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2672 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2674 [(NS_FACE_BACKGROUND (face) != 0
2675 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2676 : FRAME_BACKGROUND_COLOR (s->f)) set];
2679 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (s->f);
2680 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2683 if (s->hl != DRAW_CURSOR)
2685 NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2686 s->background_width,
2687 s->height-2*box_line_width);
2689 /* expand full-width row over internal borders */
2690 if (s->row->full_width_p)
2692 int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2693 if (r.origin.y <= fibw+1 + box_line_width)
2695 r.size.height += r.origin.y;
2698 if (r.origin.x <= fibw+1)
2700 r.size.width += 2*r.origin.x;
2703 if (FRAME_PIXEL_WIDTH (s->f) - (r.origin.x + r.size.width)
2705 r.size.width += fibw;
2711 s->background_filled_p = 1;
2718 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2719 /* --------------------------------------------------------------------------
2720 Renders an image and associated borders.
2721 -------------------------------------------------------------------------- */
2723 EmacsImage *img = s->img->pixmap;
2724 int box_line_vwidth = max (s->face->box_line_width, 0);
2725 int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2726 int bg_x, bg_y, bg_height;
2732 NSTRACE (ns_dumpglyphs_image);
2734 if (s->face->box != FACE_NO_BOX
2735 && s->first_glyph->left_box_line_p && s->slice.x == 0)
2736 x += abs (s->face->box_line_width);
2739 bg_y = s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2740 bg_height = s->height;
2741 /* other terms have this, but was causing problems w/tabbar mode */
2742 /* - 2 * box_line_vwidth; */
2744 if (s->slice.x == 0) x += s->img->hmargin;
2745 if (s->slice.y == 0) y += s->img->vmargin;
2747 /* Draw BG: if we need larger area than image itself cleared, do that,
2748 otherwise, since we composite the image under NS (instead of mucking
2749 with its background color), we must clear just the image area. */
2750 if (s->hl == DRAW_MOUSE_FACE)
2753 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2755 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2758 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2760 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
2762 if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
2763 || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
2765 br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
2766 s->background_filled_p = 1;
2770 br = NSMakeRect (x, y, s->slice.width, s->slice.height);
2773 /* expand full-width row over internal borders */
2774 if (s->row->full_width_p)
2776 int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2777 if (br.origin.y <= fibw+1 + box_line_vwidth)
2779 br.size.height += br.origin.y;
2782 if (br.origin.x <= fibw+1 + box_line_vwidth)
2784 br.size.width += br.origin.x;
2787 if (FRAME_PIXEL_WIDTH (s->f) - (br.origin.x + br.size.width) <= fibw+1)
2788 br.size.width += fibw;
2793 /* Draw the image.. do we need to draw placeholder if img ==nil? */
2795 [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
2796 operation: NSCompositeSourceOver];
2798 /* Draw relief, if requested */
2799 if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
2801 if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
2803 th = tool_bar_button_relief >= 0 ?
2804 tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2805 raised_p = (s->hl == DRAW_IMAGE_RAISED);
2809 th = abs (s->img->relief);
2810 raised_p = (s->img->relief > 0);
2813 r.origin.x = x - th;
2814 r.origin.y = y - th;
2815 r.size.width = s->slice.width + 2*th-1;
2816 r.size.height = s->slice.height + 2*th-1;
2817 ns_draw_relief (r, th, raised_p,
2819 s->slice.y + s->slice.height == s->img->height,
2821 s->slice.x + s->slice.width == s->img->width, s);
2827 ns_dumpglyphs_stretch (struct glyph_string *s)
2833 if (!s->background_filled_p)
2835 n = ns_get_glyph_string_clip_rect (s, r);
2836 *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
2840 if (!s->row->full_width_p)
2842 /* truncate to avoid overwriting fringe and/or scrollbar */
2843 int overrun = max (0, (s->x + s->background_width)
2844 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
2845 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
2846 r[i].size.width -= overrun;
2848 /* XXX: Try to work between problem where a stretch glyph on
2849 a partially-visible bottom row will clear part of the
2850 modeline, and another where list-buffers headers and similar
2851 rows erroneously have visible_height set to 0. Not sure
2852 where this is coming from as other terms seem not to show. */
2853 r[i].size.height = min (s->height, s->row->visible_height);
2856 /* expand full-width rows over internal borders */
2859 r[i] = ns_fix_rect_ibw (r[i], FRAME_INTERNAL_BORDER_WIDTH (s->f),
2860 FRAME_PIXEL_WIDTH (s->f));
2863 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
2864 overwriting cursor (usually when cursor on a tab) */
2865 if (s->hl == DRAW_CURSOR)
2867 r[i].origin.x += s->width;
2868 r[i].size.width -= s->width;
2872 ns_focus (s->f, r, n);
2874 if (s->hl == DRAW_MOUSE_FACE)
2877 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2879 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2882 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2884 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
2889 s->background_filled_p = 1;
2895 ns_draw_glyph_string (struct glyph_string *s)
2896 /* --------------------------------------------------------------------------
2897 External (RIF): Main draw-text call.
2898 -------------------------------------------------------------------------- */
2900 /* TODO (optimize): focus for box and contents draw */
2903 char box_drawn_p = 0;
2905 NSTRACE (ns_draw_glyph_string);
2907 if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
2910 struct glyph_string *next;
2912 for (width = 0, next = s->next;
2913 next && width < s->right_overhang;
2914 width += next->width, next = next->next)
2915 if (next->first_glyph->type != IMAGE_GLYPH)
2917 if (next->first_glyph->type != STRETCH_GLYPH)
2919 n = ns_get_glyph_string_clip_rect (s->next, r);
2920 ns_focus (s->f, r, n);
2921 ns_maybe_dumpglyphs_background (s->next, 1);
2926 ns_dumpglyphs_stretch (s->next);
2928 next->num_clips = 0;
2932 if (!s->for_overlaps && s->face->box != FACE_NO_BOX
2933 && (s->first_glyph->type == CHAR_GLYPH
2934 || s->first_glyph->type == COMPOSITE_GLYPH))
2936 n = ns_get_glyph_string_clip_rect (s, r);
2937 ns_focus (s->f, r, n);
2938 ns_maybe_dumpglyphs_background (s, 1);
2939 ns_dumpglyphs_box_or_relief (s);
2944 switch (s->first_glyph->type)
2948 n = ns_get_glyph_string_clip_rect (s, r);
2949 ns_focus (s->f, r, n);
2950 ns_dumpglyphs_image (s, r[0]);
2955 ns_dumpglyphs_stretch (s);
2959 case COMPOSITE_GLYPH:
2960 n = ns_get_glyph_string_clip_rect (s, r);
2961 ns_focus (s->f, r, n);
2963 if (s->for_overlaps || (s->cmp_from > 0
2964 && ! s->first_glyph->u.cmp.automatic))
2965 s->background_filled_p = 1;
2967 ns_maybe_dumpglyphs_background
2968 (s, s->first_glyph->type == COMPOSITE_GLYPH);
2970 ns_tmp_flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
2971 (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
2972 (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
2973 NS_DUMPGLYPH_NORMAL));
2974 ns_tmp_font = (struct nsfont_info *)s->face->font;
2975 if (ns_tmp_font == NULL)
2976 ns_tmp_font = (struct nsfont_info *)FRAME_FONT (s->f);
2978 ns_tmp_font->font.driver->draw
2979 (s, 0, s->nchars, s->x, s->y,
2980 (ns_tmp_flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
2981 || ns_tmp_flags == NS_DUMPGLYPH_MOUSEFACE);
2990 /* Draw box if not done already. */
2991 if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
2993 n = ns_get_glyph_string_clip_rect (s, r);
2994 ns_focus (s->f, r, n);
2995 ns_dumpglyphs_box_or_relief (s);
3004 /* ==========================================================================
3008 ========================================================================== */
3012 ns_send_appdefined (int value)
3013 /* --------------------------------------------------------------------------
3014 Internal: post an appdefined event which EmacsApp-sendEvent will
3015 recognize and take as a command to halt the event loop.
3016 -------------------------------------------------------------------------- */
3018 /*NSTRACE (ns_send_appdefined); */
3020 /* Only post this event if we haven't already posted one. This will end
3021 the [NXApp run] main loop after having processed all events queued at
3023 if (send_appdefined)
3027 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
3028 send_appdefined = NO;
3030 /* Don't need wakeup timer any more */
3033 [timed_entry invalidate];
3034 [timed_entry release];
3038 /* Ditto for file descriptor poller */
3041 [fd_entry invalidate];
3046 nxev = [NSEvent otherEventWithType: NSApplicationDefined
3047 location: NSMakePoint (0, 0)
3050 windowNumber: [[NSApp mainWindow] windowNumber]
3051 context: [NSApp context]
3056 /* Post an application defined event on the event queue. When this is
3057 received the [NXApp run] will return, thus having processed all
3058 events which are currently queued. */
3059 [NSApp postEvent: nxev atStart: NO];
3065 ns_read_socket (struct terminal *terminal, int expected,
3066 struct input_event *hold_quit)
3067 /* --------------------------------------------------------------------------
3068 External (hook): Post an event to ourself and keep reading events until
3069 we read it back again. In effect process all events which were waiting.
3070 From 21+ we have to manage the event buffer ourselves.
3071 -------------------------------------------------------------------------- */
3073 struct input_event ev;
3076 /* NSTRACE (ns_read_socket); */
3078 if (interrupt_input_blocked)
3080 interrupt_input_pending = 1;
3082 pending_signals = 1;
3087 interrupt_input_pending = 0;
3089 pending_signals = pending_atimers;
3093 n_emacs_events_pending = 0;
3096 q_event_ptr = hold_quit;
3098 /* we manage autorelease pools by allocate/reallocate each time around
3099 the loop; strict nesting is occasionally violated but seems not to
3100 matter.. earlier methods using full nesting caused major memory leaks */
3101 [outerpool release];
3102 outerpool = [[NSAutoreleasePool alloc] init];
3104 /* If have pending open-file requests, attend to the next one of those. */
3105 if (ns_pending_files && [ns_pending_files count] != 0
3106 && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3108 [ns_pending_files removeObjectAtIndex: 0];
3110 /* Deal with pending service requests. */
3111 else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3113 NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3114 withArg: [ns_pending_service_args objectAtIndex: 0]])
3116 [ns_pending_service_names removeObjectAtIndex: 0];
3117 [ns_pending_service_args removeObjectAtIndex: 0];
3121 /* Run and wait for events. We must always send one NX_APPDEFINED event
3122 to ourself, otherwise [NXApp run] will never exit. */
3123 send_appdefined = YES;
3125 /* If called via ns_select, this is called once with expected=1,
3126 because we expect either the timeout or file descriptor activity.
3127 In this case the first event through will either be real input or
3128 one of these. read_avail_input() then calls once more with expected=0
3129 and in that case we need to return quickly if there is nothing.
3130 If we're being called outside of that, it's also OK to return quickly
3131 after one iteration through the event loop, since other terms do
3132 this and emacs expects it. */
3133 if (!(inNsSelect && expected))
3135 /* Post an application defined event on the event queue. When this is
3136 received the [NXApp run] will return, thus having processed all
3137 events which are currently queued, if any. */
3138 ns_send_appdefined (-1);
3144 nevents = n_emacs_events_pending;
3145 n_emacs_events_pending = 0;
3146 emacs_event = q_event_ptr = NULL;
3154 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3155 fd_set *exceptfds, struct timeval *timeout)
3156 /* --------------------------------------------------------------------------
3157 Replacement for select, checking for events
3158 -------------------------------------------------------------------------- */
3163 /* NSTRACE (ns_select); */
3165 if (NSApp == nil || inNsSelect == 1 /* || ([NSApp isActive] == NO &&
3166 [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
3167 inMode:NSDefaultRunLoopMode dequeue:NO] == nil) */)
3168 return select (nfds, readfds, writefds, exceptfds, timeout);
3170 /* Save file descriptor set, which gets overwritten in calls to select ()
3171 Note, this is called from process.c, and only readfds is ever set */
3174 memcpy (&select_readfds, readfds, sizeof (fd_set));
3180 /* Try an initial select for pending data on input files */
3181 select_timeout.tv_sec = select_timeout.tv_usec = 0;
3182 result = select (nfds, readfds, writefds, exceptfds, &select_timeout);
3186 /* if (!timeout || timed_entry || fd_entry)
3187 fprintf (stderr, "assertion failed: timeout null or timed_entry/fd_entry non-null in ns_select\n"); */
3189 /* set a timeout and run the main AppKit event loop while continuing
3190 to monitor the files */
3191 time = ((double) timeout->tv_sec) + ((double) timeout->tv_usec)/1000000.0;
3192 timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3194 selector: @selector (timeout_handler:)
3196 repeats: YES] /* for safe removal */
3199 /* set a periodic task to try the select () again */
3200 fd_entry = [[NSTimer scheduledTimerWithTimeInterval: 0.1
3202 selector: @selector (fd_handler:)
3207 /* Let Application dispatch events until it receives an event of the type
3208 NX_APPDEFINED, which should only be sent by timeout_handler.
3209 We tell read_avail_input() that input is "expected" because we do expect
3210 either the timeout or fd handler to fire, and if they don't, the original
3211 call from process.c that got us here expects us to wait until some input
3215 ev = last_appdefined_event;
3221 if ([ev type] != NSApplicationDefined)
3225 last_appdefined_event = 0;
3229 /* The NX_APPDEFINED event we received was a timeout. */
3234 /* The NX_APPDEFINED event we received was the result of
3235 at least one real input event arriving. */
3241 /* Received back from select () in fd_handler; copy the results */
3243 memcpy (readfds, &select_readfds, sizeof (fd_set));
3247 /* never reached, shut compiler up */
3253 /* ==========================================================================
3257 ========================================================================== */
3261 ns_set_vertical_scroll_bar (struct window *window,
3262 int portion, int whole, int position)
3263 /* --------------------------------------------------------------------------
3264 External (hook): Update or add scrollbar
3265 -------------------------------------------------------------------------- */
3269 struct frame *f = XFRAME (WINDOW_FRAME (window));
3270 EmacsView *view = FRAME_NS_VIEW (f);
3271 int window_y, window_height;
3272 BOOL barOnVeryLeft, barOnVeryRight;
3273 int top, left, height, width, sb_width, sb_left;
3275 static int count = 0;
3277 /* optimization; display engine sends WAY too many of these.. */
3278 if (!NILP (window->vertical_scroll_bar))
3280 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3281 if ([bar checkSamePosition: position portion: portion whole: whole])
3283 if (view->scrollbarsNeedingUpdate == 0)
3285 if (!windows_or_buffers_changed)
3289 view->scrollbarsNeedingUpdate--;
3293 NSTRACE (ns_set_vertical_scroll_bar);
3295 /* Get dimensions. */
3296 window_box (window, -1, 0, &window_y, 0, &window_height);
3298 height = window_height;
3299 width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3300 left = WINDOW_SCROLL_BAR_AREA_X (window);
3302 if (top < 5) /* top scrollbar adjustment */
3304 top -= FRAME_INTERNAL_BORDER_WIDTH (f);
3305 height += FRAME_INTERNAL_BORDER_WIDTH (f);
3308 /* allow for displaying a skinnier scrollbar than char area allotted */
3309 sb_width = (WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) > 0) ?
3310 WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) : width;
3312 barOnVeryLeft = left < 5;
3313 barOnVeryRight = FRAME_PIXEL_WIDTH (f) - left - width < 5;
3314 sb_left = left + FRAME_INTERNAL_BORDER_WIDTH (f)
3315 * (barOnVeryLeft ? -1 : (barOnVeryRight ? 1 : 0));
3317 r = NSMakeRect (sb_left, top, sb_width, height);
3318 /* the parent view is flipped, so we need to flip y value */
3320 r.origin.y = (v.size.height - r.size.height - r.origin.y);
3322 XSETWINDOW (win, window);
3325 /* we want at least 5 lines to display a scrollbar */
3326 if (WINDOW_TOTAL_LINES (window) < 5)
3328 if (!NILP (window->vertical_scroll_bar))
3330 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3331 [bar removeFromSuperview];
3332 window->vertical_scroll_bar = Qnil;
3334 ns_clear_frame_area (f, sb_left, top, width, height);
3339 if (NILP (window->vertical_scroll_bar))
3341 ns_clear_frame_area (f, sb_left, top, width, height);
3342 bar = [[EmacsScroller alloc] initFrame: r window: win];
3343 window->vertical_scroll_bar = make_save_value (bar, 0);
3348 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3349 oldRect = [bar frame];
3350 r.size.width = oldRect.size.width;
3351 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3353 if (oldRect.origin.x != r.origin.x)
3354 ns_clear_frame_area (f, sb_left, top, width, height);
3359 [bar setPosition: position portion: portion whole: whole];
3365 ns_condemn_scroll_bars (struct frame *f)
3366 /* --------------------------------------------------------------------------
3367 External (hook): arrange for all frame's scrollbars to be removed
3368 at next call to judge_scroll_bars, except for those redeemed.
3369 -------------------------------------------------------------------------- */
3373 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3375 NSTRACE (ns_condemn_scroll_bars);
3377 for (i =[subviews count]-1; i >= 0; i--)
3379 view = [subviews objectAtIndex: i];
3380 if ([view isKindOfClass: [EmacsScroller class]])
3387 ns_redeem_scroll_bar (struct window *window)
3388 /* --------------------------------------------------------------------------
3389 External (hook): arrange to spare this window's scrollbar
3390 at next call to judge_scroll_bars.
3391 -------------------------------------------------------------------------- */
3394 NSTRACE (ns_redeem_scroll_bar);
3395 if (!NILP (window->vertical_scroll_bar))
3397 bar =XNS_SCROLL_BAR (window->vertical_scroll_bar);
3404 ns_judge_scroll_bars (struct frame *f)
3405 /* --------------------------------------------------------------------------
3406 External (hook): destroy all scrollbars on frame that weren't
3407 redeemed after call to condemn_scroll_bars.
3408 -------------------------------------------------------------------------- */
3412 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3413 NSTRACE (ns_judge_scroll_bars);
3414 for (i =[subviews count]-1; i >= 0; i--)
3416 view = [subviews objectAtIndex: i];
3417 if (![view isKindOfClass: [EmacsScroller class]]) continue;
3424 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
3426 /* XXX irrelevant under NS */
3431 /* ==========================================================================
3435 ========================================================================== */
3438 x_display_pixel_height (struct ns_display_info *dpyinfo)
3440 NSScreen *screen = [NSScreen mainScreen];
3441 return [screen frame].size.height;
3445 x_display_pixel_width (struct ns_display_info *dpyinfo)
3447 NSScreen *screen = [NSScreen mainScreen];
3448 return [screen frame].size.width;
3452 static Lisp_Object ns_string_to_lispmod (const char *s)
3453 /* --------------------------------------------------------------------------
3454 Convert modifier name to lisp symbol
3455 -------------------------------------------------------------------------- */
3457 if (!strncmp (SDATA (SYMBOL_NAME (Qmeta)), s, 10))
3459 else if (!strncmp (SDATA (SYMBOL_NAME (Qsuper)), s, 10))
3461 else if (!strncmp (SDATA (SYMBOL_NAME (Qcontrol)), s, 10))
3463 else if (!strncmp (SDATA (SYMBOL_NAME (Qalt)), s, 10))
3465 else if (!strncmp (SDATA (SYMBOL_NAME (Qhyper)), s, 10))
3467 else if (!strncmp (SDATA (SYMBOL_NAME (Qnone)), s, 10))
3474 static Lisp_Object ns_mod_to_lisp (int m)
3475 /* --------------------------------------------------------------------------
3476 Convert modifier code (see lisp.h) to lisp symbol
3477 -------------------------------------------------------------------------- */
3481 else if (m == CHAR_SUPER)
3483 else if (m == CHAR_CTL)
3485 else if (m == CHAR_ALT)
3487 else if (m == CHAR_HYPER)
3489 else /* if (m == 0) */
3495 ns_default (const char *parameter, Lisp_Object *result,
3496 Lisp_Object yesval, Lisp_Object noval,
3497 BOOL is_float, BOOL is_modstring)
3498 /* --------------------------------------------------------------------------
3499 Check a parameter value in user's preferences
3500 -------------------------------------------------------------------------- */
3504 if ( (value =[[[NSUserDefaults standardUserDefaults]
3505 stringForKey: [NSString stringWithUTF8String: parameter]]
3510 if (strcasecmp (value, "YES") == 0)
3512 else if (strcasecmp (value, "NO") == 0)
3514 else if (is_float && (f = strtod (value, &pos), pos != value))
3515 *result = make_float (f);
3516 else if (is_modstring && value)
3517 *result = ns_string_to_lispmod (value);
3518 else fprintf (stderr,
3519 "Bad value for default \"%s\": \"%s\"\n", parameter, value);
3525 ns_initialize_display_info (struct ns_display_info *dpyinfo)
3526 /* --------------------------------------------------------------------------
3527 Initialize global info and storage for display.
3528 -------------------------------------------------------------------------- */
3530 NSScreen *screen = [NSScreen mainScreen];
3531 NSWindowDepth depth = [screen depth];
3533 dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
3534 dpyinfo->resy = 72.27;
3535 dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
3536 NSColorSpaceFromDepth (depth)]
3537 && ![NSCalibratedWhiteColorSpace isEqualToString:
3538 NSColorSpaceFromDepth (depth)];
3539 dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
3540 dpyinfo->image_cache = make_image_cache ();
3541 dpyinfo->color_table
3542 = (struct ns_color_table *)xmalloc (sizeof (struct ns_color_table));
3543 dpyinfo->color_table->colors = NULL;
3544 dpyinfo->root_window = 42; /* a placeholder.. */
3546 dpyinfo->mouse_face_mouse_frame = NULL;
3547 dpyinfo->mouse_face_deferred_gc = 0;
3548 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
3549 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
3550 dpyinfo->mouse_face_face_id = DEFAULT_FACE_ID;
3551 dpyinfo->mouse_face_window = dpyinfo->mouse_face_overlay = Qnil;
3552 dpyinfo->mouse_face_hidden = 0;
3554 dpyinfo->mouse_face_mouse_x = dpyinfo->mouse_face_mouse_y = 0;
3555 dpyinfo->mouse_face_defer = 0;
3557 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
3559 dpyinfo->n_fonts = 0;
3560 dpyinfo->smallest_font_height = 1;
3561 dpyinfo->smallest_char_width = 1;
3565 /* This and next define (many of the) public functions in this file. */
3566 /* x_... are generic versions in xdisp.c that we, and other terms, get away
3567 with using despite presence in the "system dependent" redisplay
3568 interface. In addition, many of the ns_ methods have code that is
3569 shared with all terms, indicating need for further refactoring. */
3570 extern frame_parm_handler ns_frame_parm_handlers[];
3571 static struct redisplay_interface ns_redisplay_interface =
3573 ns_frame_parm_handlers,
3577 x_clear_end_of_line,
3579 ns_after_update_window_line,
3580 ns_update_window_begin,
3581 ns_update_window_end,
3584 0, /* flush_display_optional */
3585 x_clear_window_mouse_face,
3586 x_get_glyph_overhangs,
3587 x_fix_overlapping_area,
3588 ns_draw_fringe_bitmap,
3589 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
3590 0, /* destroy_fringe_bitmap */
3591 ns_compute_glyph_string_overhangs,
3592 ns_draw_glyph_string, /* interface to nsfont.m */
3593 ns_define_frame_cursor,
3594 ns_clear_frame_area,
3595 ns_draw_window_cursor,
3596 ns_draw_vertical_window_border,
3597 ns_shift_glyphs_for_insert
3602 ns_delete_display (struct ns_display_info *dpyinfo)
3608 /* This function is called when the last frame on a display is deleted. */
3610 ns_delete_terminal (struct terminal *terminal)
3612 struct ns_display_info *dpyinfo = terminal->display_info.ns;
3615 /* Protect against recursive calls. delete_frame in
3616 delete_terminal calls us back when it deletes our last frame. */
3617 if (!terminal->name)
3622 x_destroy_all_bitmaps (dpyinfo);
3623 ns_delete_display (dpyinfo);
3628 static struct terminal *
3629 ns_create_terminal (struct ns_display_info *dpyinfo)
3630 /* --------------------------------------------------------------------------
3631 Set up use of NS before we make the first connection.
3632 -------------------------------------------------------------------------- */
3634 struct terminal *terminal;
3636 NSTRACE (ns_create_terminal);
3638 terminal = create_terminal ();
3640 terminal->type = output_ns;
3641 terminal->display_info.ns = dpyinfo;
3642 dpyinfo->terminal = terminal;
3644 terminal->rif = &ns_redisplay_interface;
3646 terminal->clear_frame_hook = ns_clear_frame;
3647 terminal->ins_del_lines_hook = 0; /* XXX vestigial? */
3648 terminal->delete_glyphs_hook = 0; /* XXX vestigial? */
3649 terminal->ring_bell_hook = ns_ring_bell;
3650 terminal->reset_terminal_modes_hook = ns_reset_terminal_modes;
3651 terminal->set_terminal_modes_hook = ns_set_terminal_modes;
3652 terminal->update_begin_hook = ns_update_begin;
3653 terminal->update_end_hook = ns_update_end;
3654 terminal->set_terminal_window_hook = NULL; /* XXX vestigial? */
3655 terminal->read_socket_hook = ns_read_socket;
3656 terminal->frame_up_to_date_hook = ns_frame_up_to_date;
3657 terminal->mouse_position_hook = ns_mouse_position;
3658 terminal->frame_rehighlight_hook = ns_frame_rehighlight;
3659 terminal->frame_raise_lower_hook = ns_frame_raise_lower;
3661 terminal->fullscreen_hook = 0; /* see XTfullscreen_hook */
3663 terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
3664 terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
3665 terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
3666 terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
3668 terminal->delete_frame_hook = x_destroy_window;
3669 terminal->delete_terminal_hook = ns_delete_terminal;
3671 terminal->scroll_region_ok = 1;
3672 terminal->char_ins_del_ok = 1;
3673 terminal->line_ins_del_ok = 1;
3674 terminal->fast_clear_end_of_line = 1;
3675 terminal->memory_below_frame = 0;
3681 struct ns_display_info *
3682 ns_term_init (Lisp_Object display_name)
3683 /* --------------------------------------------------------------------------
3684 Start the Application and get things rolling.
3685 -------------------------------------------------------------------------- */
3687 struct terminal *terminal;
3688 struct ns_display_info *dpyinfo;
3689 static int ns_initialized = 0;
3692 NSTRACE (ns_term_init);
3694 /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
3695 /*GSDebugAllocationActive (YES); */
3697 handling_signal = 0;
3699 if (!ns_initialized)
3702 Fset_input_interrupt_mode (Qnil);
3706 ns_pending_files = [[NSMutableArray alloc] init];
3707 ns_pending_service_names = [[NSMutableArray alloc] init];
3708 ns_pending_service_args = [[NSMutableArray alloc] init];
3710 /* Start app and create the main menu, window, view.
3711 Needs to be here because ns_initialize_display_info () uses AppKit classes.
3712 The view will then ask the NSApp to stop and return to Emacs. */
3713 [EmacsApp sharedApplication];
3716 [NSApp setDelegate: NSApp];
3718 /* debugging: log all notifications */
3719 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
3720 selector: @selector (logNotification:)
3721 name: nil object: nil]; */
3723 dpyinfo = (struct ns_display_info *)xmalloc (sizeof (struct ns_display_info));
3724 memset (dpyinfo, 0, sizeof (struct ns_display_info));
3726 ns_initialize_display_info (dpyinfo);
3727 terminal = ns_create_terminal (dpyinfo);
3729 terminal->kboard = (KBOARD *) xmalloc (sizeof (KBOARD));
3730 init_kboard (terminal->kboard);
3731 terminal->kboard->Vwindow_system = Qns;
3732 terminal->kboard->next_kboard = all_kboards;
3733 all_kboards = terminal->kboard;
3734 /* Don't let the initial kboard remain current longer than necessary.
3735 That would cause problems if a file loaded on startup tries to
3736 prompt in the mini-buffer. */
3737 if (current_kboard == initial_kboard)
3738 current_kboard = terminal->kboard;
3739 terminal->kboard->reference_count++;
3741 dpyinfo->next = x_display_list;
3742 x_display_list = dpyinfo;
3744 /* Put it on ns_display_name_list */
3745 ns_display_name_list = Fcons (Fcons (display_name, Qnil),
3746 ns_display_name_list);
3747 dpyinfo->name_list_element = XCAR (ns_display_name_list);
3749 /* Set the name of the terminal. */
3750 terminal->name = (char *) xmalloc (SBYTES (display_name) + 1);
3751 strncpy (terminal->name, SDATA (display_name), SBYTES (display_name));
3752 terminal->name[SBYTES (display_name)] = 0;
3756 if (!inhibit_x_resources)
3758 ns_default ("GSFontAntiAlias", &ns_antialias_text,
3761 /* this is a standard variable */
3762 ns_default ("AppleAntiAliasingThreshold", &tmp,
3763 make_float (10.0), make_float (6.0), YES, NO);
3764 ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
3767 ns_selection_color = [[NSUserDefaults standardUserDefaults]
3768 stringForKey: @"AppleHighlightColor"];
3769 if (ns_selection_color == nil)
3770 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
3773 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
3777 Lisp_Object color_file, color_map, color;
3782 color_file = Fexpand_file_name (build_string ("rgb.txt"),
3783 Fsymbol_value (intern ("data-directory")));
3784 if (NILP (Ffile_readable_p (color_file)))
3785 fatal ("Could not find %s.\n", SDATA (color_file));
3787 color_map = Fx_load_color_file (color_file);
3788 if (NILP (color_map))
3789 fatal ("Could not read %s.\n", SDATA (color_file));
3791 cl = [[NSColorList alloc] initWithName: @"Emacs"];
3792 for ( ; CONSP (color_map); color_map = XCDR (color_map))
3794 color = XCAR (color_map);
3795 name = SDATA (XCAR (color));
3796 c = XINT (XCDR (color));
3798 [NSColor colorWithCalibratedRed: RED_FROM_ULONG (c) / 255.0
3799 green: GREEN_FROM_ULONG (c) / 255.0
3800 blue: BLUE_FROM_ULONG (c) / 255.0
3802 forKey: [NSString stringWithUTF8String: name]];
3804 [cl writeToFile: nil];
3810 #ifdef NS_IMPL_GNUSTEP
3811 strncpy (c, gnustep_base_version, sizeof (c));
3813 /*PSnextrelease (128, c); */
3814 snprintf (c, sizeof (c), "%g", NSAppKitVersionNumber);
3816 Vwindow_system_version = build_string (c);
3819 delete_keyboard_wait_descriptor (0);
3821 ns_app_name = [[NSProcessInfo processInfo] processName];
3823 /* Set up OS X app menu */
3824 #ifdef NS_IMPL_COCOA
3828 /* set up the application menu */
3829 svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
3830 [svcsMenu setAutoenablesItems: NO];
3831 appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
3832 [appMenu setAutoenablesItems: NO];
3833 mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
3834 dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
3836 [appMenu insertItemWithTitle: @"About Emacs"
3837 action: @selector (orderFrontStandardAboutPanel:)
3840 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
3841 [appMenu insertItemWithTitle: @"Preferences..."
3842 action: @selector (showPreferencesWindow:)
3845 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
3846 item = [appMenu insertItemWithTitle: @"Services"
3847 action: @selector (menuDown:)
3850 [appMenu setSubmenu: svcsMenu forItem: item];
3851 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
3852 [appMenu insertItemWithTitle: @"Hide Emacs"
3853 action: @selector (hide:)
3856 item = [appMenu insertItemWithTitle: @"Hide Others"
3857 action: @selector (hideOtherApplications:)
3860 [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
3861 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
3862 [appMenu insertItemWithTitle: @"Quit Emacs"
3863 action: @selector (terminate:)
3867 item = [mainMenu insertItemWithTitle: ns_app_name
3868 action: @selector (menuDown:)
3871 [mainMenu setSubmenu: appMenu forItem: item];
3872 [dockMenu insertItemWithTitle: @"New Frame"
3873 action: @selector (newFrame:)
3877 [NSApp setMainMenu: mainMenu];
3878 [NSApp setAppleMenu: appMenu];
3879 [NSApp setServicesMenu: svcsMenu];
3880 /* Needed at least on Cocoa, to get dock menu to show windows */
3881 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
3883 #endif /* MAC OS X menu setup */
3891 extern Lisp_Object Vauto_save_list_file_name;
3893 ns_term_shutdown (int sig)
3895 /* code not reached in emacs.c after this is called by shut_down_emacs: */
3896 if (STRINGP (Vauto_save_list_file_name))
3897 unlink (SDATA (Vauto_save_list_file_name));
3899 if (sig == 0 || sig == SIGTERM)
3901 [NSApp terminate: NSApp];
3903 else // force a stack trace to happen
3910 /* ==========================================================================
3912 EmacsApp implementation
3914 ========================================================================== */
3917 @implementation EmacsApp
3919 - (void)logNotification: (NSNotification *)notification
3921 const char *name = [[notification name] UTF8String];
3922 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
3923 && !strstr (name, "WindowNumber"))
3924 NSLog (@"notification: '%@'", [notification name]);
3928 - (void)sendEvent: (NSEvent *)theEvent
3929 /* --------------------------------------------------------------------------
3930 Called when NSApp is running for each event received. Used to stop
3931 the loop when we choose, since there's no way to just run one iteration.
3932 -------------------------------------------------------------------------- */
3934 int type = [theEvent type];
3935 NSWindow *window = [theEvent window];
3936 /* NSTRACE (sendEvent); */
3937 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
3939 if (type == NSCursorUpdate && window == nil)
3941 fprintf (stderr, "Dropping external cursor update event.\n");
3945 #ifdef NS_IMPL_COCOA
3946 /* pass mouse down in resize handle and subsequent drags directly to
3947 EmacsWindow so we can generate continuous redisplays */
3950 if (type == NSLeftMouseDragged)
3952 [window mouseDragged: theEvent];
3955 else if (type == NSLeftMouseUp)
3957 [window mouseUp: theEvent];
3961 else if (type == NSLeftMouseDown)
3963 NSRect r = ns_resize_handle_rect (window);
3964 if (NSPointInRect ([theEvent locationInWindow], r))
3967 [window mouseDown: theEvent];
3973 if (type == NSApplicationDefined)
3975 /* Events posted by ns_send_appdefined interrupt the run loop here.
3976 But, if a modal window is up, an appdefined can still come through,
3977 (e.g., from a makeKeyWindow event) but stopping self also stops the
3978 modal loop. Just defer it until later. */
3979 if ([NSApp modalWindow] == nil)
3981 last_appdefined_event = theEvent;
3986 send_appdefined = YES;
3990 [super sendEvent: theEvent];
3994 - (void)showPreferencesWindow: (id)sender
3996 struct frame *emacsframe = SELECTED_FRAME ();
3997 NSEvent *theEvent = [NSApp currentEvent];
4001 emacs_event->kind = NS_NONKEY_EVENT;
4002 emacs_event->code = KEY_NS_SHOW_PREFS;
4003 emacs_event->modifiers = 0;
4004 EV_TRAILER (theEvent);
4008 - (void)newFrame: (id)sender
4010 struct frame *emacsframe = SELECTED_FRAME ();
4011 NSEvent *theEvent = [NSApp currentEvent];
4015 emacs_event->kind = NS_NONKEY_EVENT;
4016 emacs_event->code = KEY_NS_NEW_FRAME;
4017 emacs_event->modifiers = 0;
4018 EV_TRAILER (theEvent);
4022 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4023 - (BOOL) openFile: (NSString *)fileName
4025 struct frame *emacsframe = SELECTED_FRAME ();
4026 NSEvent *theEvent = [NSApp currentEvent];
4031 emacs_event->kind = NS_NONKEY_EVENT;
4032 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4033 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4034 ns_input_line = Qnil; /* can be start or cons start,end */
4035 emacs_event->modifiers =0;
4036 EV_TRAILER (theEvent);
4042 /* **************************************************************************
4044 EmacsApp delegate implementation
4046 ************************************************************************** */
4048 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4049 /* --------------------------------------------------------------------------
4050 When application is loaded, terminate event loop in ns_term_init
4051 -------------------------------------------------------------------------- */
4053 NSTRACE (applicationDidFinishLaunching);
4054 [NSApp setServicesProvider: NSApp];
4055 ns_send_appdefined (-2);
4059 /* Termination sequences:
4062 MenuBar | File | Exit:
4063 Select Quit from App menubar:
4065 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4068 Select Quit from Dock menu:
4071 Cancel -> Nothing else
4075 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4080 - (void) terminate: (id)sender
4082 struct frame *emacsframe = SELECTED_FRAME ();
4087 emacs_event->kind = NS_NONKEY_EVENT;
4088 emacs_event->code = KEY_NS_POWER_OFF;
4089 emacs_event->arg = Qt; /* mark as non-key event */
4090 EV_TRAILER ((id)nil);
4094 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4098 if (NILP (ns_confirm_quit)) // || ns_shutdown_properly --> TO DO
4099 return NSTerminateNow;
4101 ret = NSRunAlertPanel(ns_app_name,
4102 [NSString stringWithUTF8String:"Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?"],
4103 @"Save Buffers and Exit", @"Cancel", nil);
4105 if (ret == NSAlertDefaultReturn)
4106 return NSTerminateNow;
4107 else if (ret == NSAlertAlternateReturn)
4108 return NSTerminateCancel;
4109 return NSTerminateNow; /* just in case */
4113 /* Notification from the Workspace to open a file */
4114 - (BOOL)application: sender openFile: (NSString *)file
4116 [ns_pending_files addObject: file];
4121 /* Open a file as a temporary file */
4122 - (BOOL)application: sender openTempFile: (NSString *)file
4124 [ns_pending_files addObject: file];
4129 /* Notification from the Workspace to open a file noninteractively (?) */
4130 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4132 [ns_pending_files addObject: file];
4137 /* Notification from the Workspace to open multiple files */
4138 - (void)application: sender openFiles: (NSArray *)fileList
4140 NSEnumerator *files = [fileList objectEnumerator];
4142 while ((file = [files nextObject]) != nil)
4143 [ns_pending_files addObject: file];
4145 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4150 /* Handle dock menu requests. */
4151 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4157 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4158 - (void)applicationWillBecomeActive: (NSNotification *)notification
4160 //ns_app_active=YES;
4162 - (void)applicationDidBecomeActive: (NSNotification *)notification
4164 //ns_app_active=YES;
4166 - (void)applicationDidResignActive: (NSNotification *)notification
4169 ns_send_appdefined (-1);
4174 /* ==========================================================================
4176 EmacsApp aux handlers for managing event loop
4178 ========================================================================== */
4181 - (void)timeout_handler: (NSTimer *)timedEntry
4182 /* --------------------------------------------------------------------------
4183 The timeout specified to ns_select has passed.
4184 -------------------------------------------------------------------------- */
4186 /*NSTRACE (timeout_handler); */
4187 ns_send_appdefined (-2);
4190 - (void)fd_handler: (NSTimer *) fdEntry
4191 /* --------------------------------------------------------------------------
4192 Check data waiting on file descriptors and terminate if so
4193 -------------------------------------------------------------------------- */
4196 /* NSTRACE (fd_handler); */
4198 if (select_nfds == 0)
4201 memcpy (&t_readfds, &select_readfds, sizeof (fd_set));
4203 select_timeout.tv_sec = select_timeout.tv_usec = 0;
4204 result = select (select_nfds, &t_readfds, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
4208 memcpy (&select_readfds, &t_readfds, sizeof (fd_set));
4209 ns_send_appdefined (result);
4215 /* ==========================================================================
4219 ========================================================================== */
4221 /* called from system: queue for next pass through event loop */
4222 - (void)requestService: (NSPasteboard *)pboard
4223 userData: (NSString *)userData
4224 error: (NSString **)error
4226 [ns_pending_service_names addObject: userData];
4227 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
4228 SDATA (ns_string_from_pasteboard (pboard))]];
4232 /* called from ns_read_socket to clear queue */
4233 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
4235 struct frame *emacsframe = SELECTED_FRAME ();
4236 NSEvent *theEvent = [NSApp currentEvent];
4241 emacs_event->kind = NS_NONKEY_EVENT;
4242 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
4243 ns_input_spi_name = build_string ([name UTF8String]);
4244 ns_input_spi_arg = build_string ([arg UTF8String]);
4245 emacs_event->modifiers = EV_MODIFIERS (theEvent);
4246 EV_TRAILER (theEvent);
4256 /* ==========================================================================
4258 EmacsView implementation
4260 ========================================================================== */
4263 @implementation EmacsView
4265 /* needed to inform when window closed from LISP */
4266 - (void) setWindowClosing: (BOOL)closing
4268 windowClosing = closing;
4274 NSTRACE (EmacsView_dealloc);
4280 /* called on font panel selection */
4281 - (void)changeFont: (id)sender
4283 NSEvent *e =[[self window] currentEvent];
4284 struct face *face =FRAME_DEFAULT_FACE (emacsframe);
4288 NSTRACE (changeFont);
4292 if (newFont = [sender convertFont:
4293 ((struct nsfont_info *)face->font)->nsfont])
4295 SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
4297 emacs_event->kind = NS_NONKEY_EVENT;
4298 emacs_event->modifiers = 0;
4299 emacs_event->code = KEY_NS_CHANGE_FONT;
4301 size = [newFont pointSize];
4302 ns_input_fontsize = make_number (lrint (size));
4303 ns_input_font = build_string ([[newFont familyName] UTF8String]);
4309 - (BOOL)acceptsFirstResponder
4311 NSTRACE (acceptsFirstResponder);
4316 - (void)resetCursorRects
4318 NSRect visible = [self visibleRect];
4319 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
4320 NSTRACE (resetCursorRects);
4322 if (currentCursor == nil)
4323 currentCursor = [NSCursor arrowCursor];
4325 if (!NSIsEmptyRect (visible))
4326 [self addCursorRect: visible cursor: currentCursor];
4327 [currentCursor setOnMouseEntered: YES];
4332 /*****************************************************************************/
4333 /* Keyboard handling. */
4336 - (void)keyDown: (NSEvent *)theEvent
4338 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4340 unsigned fnKeysym = 0;
4342 static NSMutableArray *nsEvArray;
4343 static BOOL firstTime = YES;
4347 /* Rhapsody and OS X give up and down events for the arrow keys */
4348 if (ns_fake_keydown == YES)
4349 ns_fake_keydown = NO;
4350 else if ([theEvent type] != NSKeyDown)
4356 if (![[self window] isKeyWindow]
4357 && [[theEvent window] isKindOfClass: [EmacsWindow class]]
4358 /* we must avoid an infinite loop here. */
4359 && (EmacsView *)[[theEvent window] delegate] != self)
4361 /* XXX: There is an occasional condition in which, when Emacs display
4362 updates a different frame from the current one, and temporarily
4363 selects it, then processes some interrupt-driven input
4364 (dispnew.c:3878), OS will send the event to the correct NSWindow, but
4365 for some reason that window has its first responder set to the NSView
4366 most recently updated (I guess), which is not the correct one. */
4367 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
4371 if (nsEvArray == nil)
4372 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
4374 [NSCursor setHiddenUntilMouseMoves: YES];
4376 if (dpyinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
4378 clear_mouse_face (dpyinfo);
4379 dpyinfo->mouse_face_hidden = 1;
4382 if (!processingCompose)
4384 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
4385 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
4386 /* (Carbon way: [theEvent keyCode]) */
4388 /* is it a "function key"? */
4389 fnKeysym = ns_convert_key (code);
4392 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
4393 because Emacs treats Delete and KP-Delete same (in simple.el). */
4394 if (fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
4395 code = 0xFF08; /* backspace */
4400 /* are there modifiers? */
4401 emacs_event->modifiers = 0;
4402 flags = [theEvent modifierFlags];
4404 if (flags & NSHelpKeyMask)
4405 emacs_event->modifiers |= hyper_modifier;
4407 if (flags & NSShiftKeyMask)
4408 emacs_event->modifiers |= shift_modifier;
4410 if (flags & NSCommandKeyMask)
4412 emacs_event->modifiers |= parse_solitary_modifier (ns_command_modifier);
4413 /* if super (default), take input manager's word so things like
4414 dvorak / qwerty layout work */
4415 if (EQ (ns_command_modifier, Qsuper)
4417 && [[theEvent characters] length] != 0)
4419 /* XXX: the code we get will be unshifted, so if we have
4420 a shift modifier, must convert ourselves */
4421 if (!(flags & NSShiftKeyMask))
4422 code = [[theEvent characters] characterAtIndex: 0];
4424 /* this is ugly and also requires linking w/Carbon framework
4425 (for LMGetKbdType) so for now leave this rare (?) case
4426 undealt with.. in future look into CGEvent methods */
4429 long smv = GetScriptManagerVariable (smKeyScript);
4430 Handle uchrHandle = GetResource
4431 ('uchr', GetScriptVariable (smv, smScriptKeys));
4433 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
4434 [[theEvent characters] characterAtIndex: 0],
4435 kUCKeyActionDisplay,
4436 (flags & ~NSCommandKeyMask) >> 8,
4437 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
4438 &dummy, 1, &dummy, &code);
4445 if (flags & NSControlKeyMask)
4446 emacs_event->modifiers |=
4447 parse_solitary_modifier (ns_control_modifier);
4449 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
4450 emacs_event->modifiers |=
4451 parse_solitary_modifier (ns_function_modifier);
4453 if (!EQ (ns_right_alternate_modifier, Qleft)
4454 && ((flags & NSRightAlternateKeyMask) == NSRightAlternateKeyMask))
4456 emacs_event->modifiers |= parse_solitary_modifier
4457 (ns_right_alternate_modifier);
4459 else if (flags & NSAlternateKeyMask) /* default = meta */
4461 if ((NILP (ns_alternate_modifier) || EQ (ns_alternate_modifier, Qnone))
4463 { /* accept pre-interp alt comb */
4464 if ([[theEvent characters] length] > 0)
4465 code = [[theEvent characters] characterAtIndex: 0];
4466 /*HACK: clear lone shift modifier to stop next if from firing */
4467 if (emacs_event->modifiers == shift_modifier)
4468 emacs_event->modifiers = 0;
4471 emacs_event->modifiers |=
4472 parse_solitary_modifier (ns_alternate_modifier);
4476 fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
4477 code, fnKeysym, flags, emacs_event->modifiers);
4479 /* if it was a function key or had modifiers, pass it directly to emacs */
4480 if (fnKeysym || (emacs_event->modifiers
4481 && [[theEvent charactersIgnoringModifiers] length] > 0))
4482 /*[[theEvent characters] length] */
4484 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4486 code |= (1<<28)|(3<<16);
4487 else if (code == 0x7f)
4488 code |= (1<<28)|(3<<16);
4490 emacs_event->kind = code > 0xFF
4491 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4493 emacs_event->code = code;
4494 EV_TRAILER (theEvent);
4499 /* if we get here we should send the key for input manager processing */
4500 if (firstTime && [[NSInputManager currentInputManager]
4501 wantsToDelayTextChangeNotifications] == NO)
4503 "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
4506 if (NS_KEYLOG && !processingCompose)
4507 fprintf (stderr, "keyDown: Begin compose sequence.\n");
4509 processingCompose = YES;
4510 [nsEvArray addObject: theEvent];
4511 [self interpretKeyEvents: nsEvArray];
4512 [nsEvArray removeObject: theEvent];
4516 #ifdef NS_IMPL_COCOA
4517 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
4518 decided not to send key-down for.
4519 See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
4520 This only applies on Tiger and earlier.
4521 If it matches one of these, send it on to keyDown. */
4522 -(void)keyUp: (NSEvent *)theEvent
4524 int flags = [theEvent modifierFlags];
4525 int code = [theEvent keyCode];
4526 if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
4527 code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
4530 fprintf (stderr, "keyUp: passed test");
4531 ns_fake_keydown = YES;
4532 [self keyDown: theEvent];
4538 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
4541 /* <NSTextInput>: called when done composing;
4542 NOTE: also called when we delete over working text, followed immed.
4543 by doCommandBySelector: deleteBackward: */
4544 - (void)insertText: (id)aString
4547 int len = [(NSString *)aString length];
4551 NSLog (@"insertText '%@'\tlen = %d", aString, len);
4552 processingCompose = NO;
4557 /* first, clear any working text */
4558 if (workingText != nil)
4559 [self deleteWorkingText];
4561 /* now insert the string as keystrokes */
4562 for (i =0; i<len; i++)
4564 code = [aString characterAtIndex: i];
4565 /* TODO: still need this? */
4567 code = '~'; /* 0x7E */
4568 emacs_event->modifiers = 0;
4570 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4571 emacs_event->code = code;
4572 EV_TRAILER ((id)nil);
4577 /* <NSTextInput>: inserts display of composing characters */
4578 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
4580 NSString *str = [aString respondsToSelector: @selector (string)] ?
4581 [aString string] : aString;
4583 NSLog (@"setMarkedText '%@' len =%d range %d from %d", str, [str length],
4584 selRange.length, selRange.location);
4586 if (workingText != nil)
4587 [self deleteWorkingText];
4588 if ([str length] == 0)
4594 processingCompose = YES;
4595 workingText = [str copy];
4596 ns_working_text = build_string ([workingText UTF8String]);
4598 emacs_event->kind = NS_TEXT_EVENT;
4599 emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
4600 EV_TRAILER ((id)nil);
4604 /* delete display of composing characters [not in <NSTextInput>] */
4605 - (void)deleteWorkingText
4607 if (workingText == nil)
4610 NSLog(@"deleteWorkingText len =%d\n", [workingText length]);
4611 [workingText release];
4613 processingCompose = NO;
4618 emacs_event->kind = NS_TEXT_EVENT;
4619 emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
4620 EV_TRAILER ((id)nil);
4624 - (BOOL)hasMarkedText
4626 return workingText != nil;
4630 - (NSRange)markedRange
4632 NSRange rng = workingText != nil
4633 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
4635 NSLog (@"markedRange request");
4643 NSLog (@"unmark (accept) text");
4644 [self deleteWorkingText];
4645 processingCompose = NO;
4649 /* used to position char selection windows, etc. */
4650 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
4654 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
4656 NSLog (@"firstRectForCharRange request");
4658 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
4659 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
4660 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
4661 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
4662 +FRAME_LINE_HEIGHT (emacsframe));
4664 pt = [self convertPoint: pt toView: nil];
4665 pt = [[self window] convertBaseToScreen: pt];
4671 - (long)conversationIdentifier
4677 - (void)doCommandBySelector: (SEL)aSelector
4680 NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
4682 if (aSelector == @selector (deleteBackward:))
4684 /* happens when user backspaces over an ongoing composition:
4685 throw a 'delete' into the event queue */
4688 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4689 emacs_event->code = 0xFF08;
4690 EV_TRAILER ((id)nil);
4694 - (NSArray *)validAttributesForMarkedText
4696 static NSArray *arr = nil;
4697 if (arr == nil) arr = [NSArray new];
4698 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
4702 - (NSRange)selectedRange
4705 NSLog (@"selectedRange request");
4706 return NSMakeRange (NSNotFound, 0);
4709 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
4712 NSLog (@"characterIndexForPoint request");
4716 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
4718 static NSAttributedString *str = nil;
4719 if (str == nil) str = [NSAttributedString new];
4721 NSLog (@"attributedSubstringFromRange request");
4725 /* End <NSTextInput> impl. */
4726 /*****************************************************************************/
4729 /* This is what happens when the user presses a mouse button. */
4730 - (void)mouseDown: (NSEvent *)theEvent
4732 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
4735 NSTRACE (mouseDown);
4737 [self deleteWorkingText];
4742 last_mouse_frame = emacsframe;
4743 /* appears to be needed to prevent spurious movement events generated on
4745 last_mouse_frame->mouse_moved = 0;
4747 if ([theEvent type] == NSScrollWheel)
4749 float delta = [theEvent deltaY];
4750 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
4753 emacs_event->kind = WHEEL_EVENT;
4754 emacs_event->code = 0;
4755 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
4756 ((delta > 0) ? up_modifier : down_modifier);
4760 emacs_event->kind = MOUSE_CLICK_EVENT;
4761 emacs_event->code = EV_BUTTON (theEvent);
4762 emacs_event->modifiers = EV_MODIFIERS (theEvent)
4763 | EV_UDMODIFIERS (theEvent);
4765 XSETINT (emacs_event->x, lrint (p.x));
4766 XSETINT (emacs_event->y, lrint (p.y));
4767 EV_TRAILER (theEvent);
4771 - (void)rightMouseDown: (NSEvent *)theEvent
4773 NSTRACE (rightMouseDown);
4774 [self mouseDown: theEvent];
4778 - (void)otherMouseDown: (NSEvent *)theEvent
4780 NSTRACE (otherMouseDown);
4781 [self mouseDown: theEvent];
4785 - (void)mouseUp: (NSEvent *)theEvent
4788 [self mouseDown: theEvent];
4792 - (void)rightMouseUp: (NSEvent *)theEvent
4794 NSTRACE (rightMouseUp);
4795 [self mouseDown: theEvent];
4799 - (void)otherMouseUp: (NSEvent *)theEvent
4801 NSTRACE (otherMouseUp);
4802 [self mouseDown: theEvent];
4806 - (void) scrollWheel: (NSEvent *)theEvent
4808 NSTRACE (scrollWheel);
4809 [self mouseDown: theEvent];
4813 /* Tell emacs the mouse has moved. */
4814 - (void)mouseMoved: (NSEvent *)e
4816 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4819 // NSTRACE (mouseMoved);
4821 last_mouse_movement_time = EV_TIMESTAMP (e);
4822 last_mouse_motion_position
4823 = [self convertPoint: [e locationInWindow] fromView: nil];
4825 /* update any mouse face */
4826 if (dpyinfo->mouse_face_hidden)
4828 dpyinfo->mouse_face_hidden = 0;
4829 clear_mouse_face (dpyinfo);
4832 /* tooltip handling */
4833 previous_help_echo_string = help_echo_string;
4834 help_echo_string = Qnil;
4836 if (!note_mouse_movement (emacsframe, last_mouse_motion_position.x,
4837 last_mouse_motion_position.y))
4838 help_echo_string = previous_help_echo_string;
4840 XSETFRAME (frame, emacsframe);
4841 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
4843 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
4844 (note_mouse_highlight), which is called through the
4845 note_mouse_movement () call above */
4846 gen_help_event (help_echo_string, frame, help_echo_window,
4847 help_echo_object, help_echo_pos);
4851 help_echo_string = Qnil;
4852 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
4855 if (emacsframe->mouse_moved && send_appdefined)
4856 ns_send_appdefined (-1);
4860 - (void)mouseDragged: (NSEvent *)e
4862 NSTRACE (mouseDragged);
4863 [self mouseMoved: e];
4867 - (void)rightMouseDragged: (NSEvent *)e
4869 NSTRACE (rightMouseDragged);
4870 [self mouseMoved: e];
4874 - (void)otherMouseDragged: (NSEvent *)e
4876 NSTRACE (otherMouseDragged);
4877 [self mouseMoved: e];
4881 - (BOOL)windowShouldClose: (id)sender
4883 NSEvent *e =[[self window] currentEvent];
4885 NSTRACE (windowShouldClose);
4886 windowClosing = YES;
4889 emacs_event->kind = DELETE_WINDOW_EVENT;
4890 emacs_event->modifiers = 0;
4891 emacs_event->code = 0;
4893 /* Don't close this window, let this be done from lisp code. */
4898 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
4899 /* normalize frame to gridded text size */
4901 NSTRACE (windowWillResize);
4902 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
4904 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe,
4905 #ifdef NS_IMPL_GNUSTEP
4906 frameSize.width + 3);
4910 if (cols < MINWIDTH)
4912 frameSize.width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (emacsframe, cols);
4914 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, frameSize.height
4915 #ifdef NS_IMPL_GNUSTEP
4916 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe) + 3
4917 - FRAME_TOOLBAR_HEIGHT (emacsframe));
4919 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
4920 - FRAME_TOOLBAR_HEIGHT (emacsframe));
4922 if (rows < MINHEIGHT)
4924 frameSize.height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows)
4925 + FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
4926 + FRAME_TOOLBAR_HEIGHT (emacsframe);
4927 #ifdef NS_IMPL_COCOA
4929 /* this sets window title to have size in it; the wm does this under GS */
4930 NSRect r = [[self window] frame];
4931 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
4942 NSWindow *window = [self window];
4945 const char *t = [[[self window] title] UTF8String];
4946 char *pos = strstr (t, " — ");
4949 old_title = (char *) xmalloc (strlen (t) + 1);
4950 strcpy (old_title, t);
4952 size_title = xmalloc (strlen (old_title) + 40);
4953 sprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
4954 [window setTitle: [NSString stringWithUTF8String: size_title]];
4959 #endif /* NS_IMPL_COCOA */
4960 /*fprintf (stderr," ...size became %.0f x %.0f (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
4966 - (void)windowDidResize: (NSNotification *)notification
4968 NSWindow *theWindow = [notification object];
4970 #ifdef NS_IMPL_GNUSTEP
4971 /* in GNUstep, at least currently, it's possible to get a didResize
4972 without getting a willResize.. therefore we need to act as if we got
4973 the willResize now */
4974 NSSize sz = [theWindow frame].size;
4975 sz = [self windowWillResize: theWindow toSize: sz];
4976 #endif /* NS_IMPL_GNUSTEP */
4978 NSTRACE (windowDidResize);
4979 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
4981 #ifdef NS_IMPL_COCOA
4987 #endif /* NS_IMPL_COCOA */
4989 /* Avoid loop under GNUstep due to call at beginning of this function.
4990 (x_set_window_size causes a resize which causes
4991 a "windowDidResize" which calls x_set_window_size). */
4992 #ifndef NS_IMPL_GNUSTEP
4993 if (cols > 0 && rows > 0)
4994 x_set_window_size (emacsframe, 0, cols, rows);
4997 ns_send_appdefined (-1);
5001 - (void)windowDidBecomeKey: (NSNotification *)notification
5002 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5004 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5005 struct frame *old_focus = dpyinfo->x_focus_frame;
5007 NSTRACE (windowDidBecomeKey);
5009 if (emacsframe != old_focus)
5010 dpyinfo->x_focus_frame = emacsframe;
5012 ns_frame_rehighlight (emacsframe);
5016 emacs_event->kind = FOCUS_IN_EVENT;
5017 EV_TRAILER ((id)nil);
5022 - (void)windowDidResignKey: (NSNotification *)notification
5023 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5025 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5026 NSTRACE (windowDidResignKey);
5028 if (dpyinfo->x_focus_frame == emacsframe)
5029 dpyinfo->x_focus_frame = 0;
5031 ns_frame_rehighlight (emacsframe);
5033 /* FIXME: for some reason needed on second and subsequent clicks away
5034 from sole-frame Emacs to get hollow box to show */
5035 if (!windowClosing && [[self window] isVisible] == YES)
5037 x_update_cursor (emacsframe, 1);
5038 x_set_frame_alpha (emacsframe);
5043 [self deleteWorkingText];
5044 emacs_event->kind = FOCUS_IN_EVENT;
5045 EV_TRAILER ((id)nil);
5050 - (void)windowWillMiniaturize: sender
5052 NSTRACE (windowWillMiniaturize);
5068 - initFrameFromEmacs: (struct frame *)f
5073 NSButton *toggleButton;
5074 int vbextra = NS_SCROLL_BAR_WIDTH (f);
5079 NSTRACE (initFrameFromEmacs);
5082 processingCompose = NO;
5083 scrollbarsNeedingUpdate = 0;
5085 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
5087 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
5088 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
5089 [self initWithFrame: r];
5090 [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
5092 FRAME_NS_VIEW (f) = self;
5096 win = [[EmacsWindow alloc]
5097 initWithContentRect: r
5098 styleMask: (NSResizableWindowMask |
5099 NSMiniaturizableWindowMask |
5100 NSClosableWindowMask)
5101 backing: NSBackingStoreBuffered
5105 f->border_width = wr.size.width - r.size.width;
5106 FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
5108 [win setAcceptsMouseMovedEvents: YES];
5109 [win setDelegate: self];
5110 [win useOptimizedDrawing: YES];
5112 sz.width = FRAME_COLUMN_WIDTH (f);
5113 sz.height = FRAME_LINE_HEIGHT (f);
5114 [win setResizeIncrements: sz];
5116 [[win contentView] addSubview: self];
5119 [self registerForDraggedTypes: ns_drag_types];
5122 name = [NSString stringWithUTF8String:
5123 NILP (tem) ? (unsigned char *)"Emacs" : SDATA (tem)];
5124 [win setTitle: name];
5126 /* toolbar support */
5127 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
5128 [NSString stringWithFormat: @"Emacs Frame %d",
5130 [win setToolbar: toolbar];
5131 [toolbar setVisible: NO];
5132 #ifdef NS_IMPL_COCOA
5133 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
5134 [toggleButton setTarget: self];
5135 [toggleButton setAction: @selector (toggleToolbar: )];
5137 FRAME_TOOLBAR_HEIGHT (f) = 0;
5141 [win setMiniwindowTitle:
5142 [NSString stringWithUTF8String: SDATA (tem)]];
5145 NSScreen *screen = [win screen];
5148 [win setFrameTopLeftPoint: NSMakePoint
5149 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
5150 IN_BOUND (-SCREENMAX,
5151 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
5154 [win makeFirstResponder: self];
5156 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5157 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
5158 [win setBackgroundColor: col];
5159 if ([col alphaComponent] != 1.0)
5160 [win setOpaque: NO];
5162 [self allocateGState];
5169 - (void)windowDidMove: sender
5171 NSWindow *win = [self window];
5172 NSRect r = [win frame];
5173 NSScreen *screen = [win screen];
5175 NSTRACE (windowDidMove);
5177 if (!emacsframe->output_data.ns)
5181 emacsframe->left_pos = r.origin.x;
5182 emacsframe->top_pos =
5183 [screen frame].size.height - (r.origin.y + r.size.height);
5188 /* Called AFTER method below, but before our windowWillResize call there leads
5189 to windowDidResize -> x_set_window_size. Update emacs' notion of frame
5190 location so set_window_size moves the frame. */
5191 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
5193 NSTRACE (windowShouldZoom);
5194 emacsframe->left_pos = (int)newFrame.origin.x;
5195 emacsframe->top_pos = [[sender screen] frame].size.height
5196 - (newFrame.origin.y+newFrame.size.height);
5201 /* Override to do something slightly nonstandard, but nice. First click on
5202 zoom button will zoom vertically. Second will zoom completely. Third
5203 returns to original. */
5204 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
5205 defaultFrame:(NSRect)defaultFrame
5207 NSRect result = [sender frame];
5208 static NSRect ns_userRect = { 0, 0, 0, 0 };
5210 NSTRACE (windowWillUseStandardFrame);
5212 if (abs (defaultFrame.size.height - result.size.height)
5213 > FRAME_LINE_HEIGHT (emacsframe))
5216 ns_userRect = result;
5217 result.size.height = defaultFrame.size.height;
5218 result.origin.y = defaultFrame.origin.y;
5222 if (abs (defaultFrame.size.width - result.size.width)
5223 > FRAME_COLUMN_WIDTH (emacsframe))
5224 result = defaultFrame; /* second click */
5226 result = ns_userRect.size.height ? ns_userRect : result; /* restore */
5229 [self windowWillResize: sender toSize: result.size];
5234 - (void)windowDidDeminiaturize: sender
5236 NSTRACE (windowDidDeminiaturize);
5237 if (!emacsframe->output_data.ns)
5239 emacsframe->async_iconified = 0;
5240 emacsframe->async_visible = 1;
5241 windows_or_buffers_changed++;
5245 emacs_event->kind = ICONIFY_EVENT;
5246 EV_TRAILER ((id)nil);
5251 - (void)windowDidExpose: sender
5253 NSTRACE (windowDidExpose);
5254 if (!emacsframe->output_data.ns)
5256 emacsframe->async_visible = 1;
5257 SET_FRAME_GARBAGED (emacsframe);
5259 if (send_appdefined)
5260 ns_send_appdefined (-1);
5264 - (void)windowDidMiniaturize: sender
5266 NSTRACE (windowDidMiniaturize);
5267 if (!emacsframe->output_data.ns)
5270 emacsframe->async_iconified = 1;
5271 emacsframe->async_visible = 0;
5275 emacs_event->kind = ICONIFY_EVENT;
5276 EV_TRAILER ((id)nil);
5281 - (void)mouseEntered: (NSEvent *)theEvent
5283 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5284 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5285 NSTRACE (mouseEntered);
5287 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5291 - (void)mouseExited: (NSEvent *)theEvent
5293 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5295 struct ns_display_info *dpyinfo
5296 = emacsframe ? FRAME_NS_DISPLAY_INFO (emacsframe) : NULL;
5298 NSTRACE (mouseExited);
5300 if (dpyinfo || !emacsframe)
5303 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5305 if (emacsframe == dpyinfo->mouse_face_mouse_frame)
5307 clear_mouse_face (dpyinfo);
5308 dpyinfo->mouse_face_mouse_frame = 0;
5316 if (context_menu_value == -1)
5317 context_menu_value = [sender tag];
5319 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
5320 emacsframe->menu_bar_vector,
5321 (void *)[sender tag]);
5322 ns_send_appdefined (-1);
5327 - (EmacsToolbar *)toolbar
5333 /* this gets called on toolbar button click */
5334 - toolbarClicked: (id)item
5337 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
5339 NSTRACE (toolbarClicked);
5344 /* send first event (for some reason two needed) */
5345 theEvent = [[self window] currentEvent];
5346 emacs_event->kind = TOOL_BAR_EVENT;
5347 XSETFRAME (emacs_event->arg, emacsframe);
5348 EV_TRAILER (theEvent);
5350 emacs_event->kind = TOOL_BAR_EVENT;
5351 /* XSETINT (emacs_event->code, 0); */
5352 emacs_event->arg = AREF (emacsframe->tool_bar_items,
5353 idx + TOOL_BAR_ITEM_KEY);
5354 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5355 EV_TRAILER (theEvent);
5360 - toggleToolbar: (id)sender
5365 emacs_event->kind = NS_NONKEY_EVENT;
5366 emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
5367 EV_TRAILER ((id)nil);
5372 - (void)drawRect: (NSRect)rect
5374 int x = NSMinX (rect), y = NSMinY (rect);
5375 int width = NSWidth (rect), height = NSHeight (rect);
5379 if (!emacsframe || !emacsframe->output_data.ns || ns_in_resize)
5382 ns_clear_frame_area (emacsframe, x, y, width, height);
5383 expose_frame (emacsframe, x, y, width, height);
5386 drawRect: may be called (at least in OS X 10.5) for invisible
5387 views as well for some reason. Thus, do not infer visibility
5390 emacsframe->async_visible = 1;
5391 emacsframe->async_iconified = 0;
5396 /* NSDraggingDestination protocol methods. Actually this is not really a
5397 protocol, but a category of Object. O well... */
5399 -(NSUInteger) draggingEntered: (id <NSDraggingInfo>) sender
5401 NSTRACE (draggingEntered);
5402 return NSDragOperationGeneric;
5406 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
5412 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
5417 NSEvent *theEvent = [[self window] currentEvent];
5420 NSTRACE (performDragOperation);
5425 position = [self convertPoint: [sender draggingLocation] fromView: nil];
5426 x = lrint (position.x); y = lrint (position.y);
5428 pb = [sender draggingPasteboard];
5429 type = [pb availableTypeFromArray: ns_drag_types];
5434 else if ([type isEqualToString: NSFilenamesPboardType])
5437 NSEnumerator *fenum;
5440 if (!(files = [pb propertyListForType: type]))
5443 fenum = [files objectEnumerator];
5444 while ( (file = [fenum nextObject]) )
5446 emacs_event->kind = NS_NONKEY_EVENT;
5447 emacs_event->code = KEY_NS_DRAG_FILE;
5448 XSETINT (emacs_event->x, x);
5449 XSETINT (emacs_event->y, y);
5450 ns_input_file = append2 (ns_input_file,
5451 build_string ([file UTF8String]));
5452 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5453 EV_TRAILER (theEvent);
5457 else if ([type isEqualToString: NSURLPboardType])
5462 if (!(fileURL = [NSURL URLFromPasteboard: pb]) ||
5463 [fileURL isFileURL] == NO)
5466 file = [fileURL path];
5467 emacs_event->kind = NS_NONKEY_EVENT;
5468 emacs_event->code = KEY_NS_DRAG_FILE;
5469 XSETINT (emacs_event->x, x);
5470 XSETINT (emacs_event->y, y);
5471 ns_input_file = append2 (ns_input_file, build_string ([file UTF8String]));
5472 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5473 EV_TRAILER (theEvent);
5476 else if ([type isEqualToString: NSStringPboardType]
5477 || [type isEqualToString: NSTabularTextPboardType])
5481 if (! (data = [pb stringForType: type]))
5484 emacs_event->kind = NS_NONKEY_EVENT;
5485 emacs_event->code = KEY_NS_DRAG_TEXT;
5486 XSETINT (emacs_event->x, x);
5487 XSETINT (emacs_event->y, y);
5488 ns_input_text = build_string ([data UTF8String]);
5489 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5490 EV_TRAILER (theEvent);
5493 else if ([type isEqualToString: NSColorPboardType])
5495 NSColor *c = [NSColor colorFromPasteboard: pb];
5496 emacs_event->kind = NS_NONKEY_EVENT;
5497 emacs_event->code = KEY_NS_DRAG_COLOR;
5498 XSETINT (emacs_event->x, x);
5499 XSETINT (emacs_event->y, y);
5500 ns_input_color = ns_color_to_lisp (c);
5501 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5502 EV_TRAILER (theEvent);
5505 else if ([type isEqualToString: NSFontPboardType])
5507 /* impl based on GNUstep NSTextView.m */
5508 NSData *data = [pb dataForType: NSFontPboardType];
5509 NSDictionary *dict = [NSUnarchiver unarchiveObjectWithData: data];
5510 NSFont *font = [dict objectForKey: NSFontAttributeName];
5516 emacs_event->kind = NS_NONKEY_EVENT;
5517 emacs_event->code = KEY_NS_CHANGE_FONT;
5518 XSETINT (emacs_event->x, x);
5519 XSETINT (emacs_event->y, y);
5520 ns_input_font = build_string ([[font fontName] UTF8String]);
5521 snprintf (fontSize, 10, "%f", [font pointSize]);
5522 ns_input_fontsize = build_string (fontSize);
5523 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5524 EV_TRAILER (theEvent);
5529 error ("Invalid data type in dragging pasteboard.");
5535 - validRequestorForSendType: (NSString *)typeSent
5536 returnType: (NSString *)typeReturned
5538 NSTRACE (validRequestorForSendType);
5539 if ([ns_send_types indexOfObjectIdenticalTo: typeSent] != NSNotFound &&
5540 [ns_return_types indexOfObjectIdenticalTo: typeSent] != NSNotFound)
5543 return [super validRequestorForSendType: typeSent
5544 returnType: typeReturned];
5548 /* The next two methods are part of NSServicesRequests informal protocol,
5549 supposedly called when a services menu item is chosen from this app.
5550 But this should not happen because we override the services menu with our
5551 own entries which call ns-perform-service.
5552 Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
5553 So let's at least stub them out until further investigation can be done. */
5555 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
5557 /* we could call ns_string_from_pasteboard(pboard) here but then it should
5558 be written into the buffer in place of the existing selection..
5559 ordinary service calls go through functions defined in ns-win.el */
5563 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
5565 /* supposed to write for as many of types as we are able */
5570 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
5571 (gives a miniaturized version of the window); currently we use the latter for
5572 frames whose active buffer doesn't correspond to any file
5573 (e.g., '*scratch*') */
5574 - setMiniwindowImage: (BOOL) setMini
5576 id image = [[self window] miniwindowImage];
5577 NSTRACE (setMiniwindowImage);
5579 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
5580 about "AppleDockIconEnabled" notwithstanding, however the set message
5581 below has its effect nonetheless. */
5582 if (image != emacsframe->output_data.ns->miniimage)
5584 if (image && [image isKindOfClass: [EmacsImage class]])
5586 [[self window] setMiniwindowImage:
5587 setMini ? emacsframe->output_data.ns->miniimage : nil];
5594 - (void) setRows: (int) r andColumns: (int) c
5600 @end /* EmacsView */
5604 /* ==========================================================================
5606 EmacsWindow implementation
5608 ========================================================================== */
5610 @implementation EmacsWindow
5612 /* called only on resize clicks by special case in EmacsApp-sendEvent */
5613 - (void)mouseDown: (NSEvent *)theEvent
5617 NSSize size = [[theEvent window] frame].size;
5618 grabOffset = [theEvent locationInWindow];
5619 grabOffset.x = size.width - grabOffset.x;
5622 [super mouseDown: theEvent];
5627 - (void)mouseUp: (NSEvent *)theEvent
5631 struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
5633 ns_set_name_as_filename (f);
5635 ns_send_appdefined (-1);
5638 [super mouseUp: theEvent];
5642 /* send resize events */
5643 - (void)mouseDragged: (NSEvent *)theEvent
5647 NSPoint p = [theEvent locationInWindow];
5648 NSSize size, vettedSize, origSize = [self frame].size;
5650 size.width = p.x + grabOffset.x;
5651 size.height = origSize.height - p.y + grabOffset.y;
5653 if (size.width == origSize.width && size.height == origSize.height)
5656 vettedSize = [[self delegate] windowWillResize: self toSize: size];
5657 if (vettedSize.width != size.width || vettedSize.height != size.height)
5659 [[NSNotificationCenter defaultCenter]
5660 postNotificationName: NSWindowDidResizeNotification
5665 [super mouseDragged: theEvent];
5668 @end /* EmacsWindow */
5671 /* ==========================================================================
5673 EmacsScroller implementation
5675 ========================================================================== */
5678 @implementation EmacsScroller
5680 /* for repeat button push */
5681 #define SCROLL_BAR_FIRST_DELAY 0.5
5682 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
5684 + (CGFloat) scrollerWidth
5686 /* TODO: if we want to allow variable widths, this is the place to do it,
5687 however neither GNUstep nor Cocoa support it very well */
5688 return [NSScroller scrollerWidth];
5692 - initFrame: (NSRect )r window: (Lisp_Object)nwin
5694 NSTRACE (EmacsScroller_initFrame);
5696 r.size.width = [EmacsScroller scrollerWidth];
5697 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
5698 [self setContinuous: YES];
5699 [self setEnabled: YES];
5701 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
5702 locked against the top and bottom edges, and right edge on OS X, where
5703 scrollers are on right. */
5704 #ifdef NS_IMPL_GNUSTEP
5705 [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
5707 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
5712 pixel_height = NSHeight (r);
5713 min_portion = 20 / pixel_height;
5715 frame = XFRAME (XWINDOW (win)->frame);
5716 if (FRAME_LIVE_P (frame))
5719 EmacsView *view = FRAME_NS_VIEW (frame);
5720 NSView *sview = [[view window] contentView];
5721 NSArray *subs = [sview subviews];
5723 /* disable optimization stopping redraw of other scrollbars */
5724 view->scrollbarsNeedingUpdate = 0;
5725 for (i =[subs count]-1; i >= 0; i--)
5726 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
5727 view->scrollbarsNeedingUpdate++;
5728 [sview addSubview: self];
5731 /* [self setFrame: r]; */
5737 - (void)setFrame: (NSRect)newRect
5739 NSTRACE (EmacsScroller_setFrame);
5741 pixel_height = NSHeight (newRect);
5742 min_portion = 20 / pixel_height;
5743 [super setFrame: newRect];
5745 /* UNBLOCK_INPUT; */
5751 NSTRACE (EmacsScroller_dealloc);
5753 XWINDOW (win)->vertical_scroll_bar = Qnil;
5781 /* ensure other scrollbar updates after deletion */
5782 view = (EmacsView *)FRAME_NS_VIEW (frame);
5784 view->scrollbarsNeedingUpdate++;
5785 [self removeFromSuperview];
5793 - (void)resetCursorRects
5795 NSRect visible = [self visibleRect];
5796 NSTRACE (resetCursorRects);
5798 if (!NSIsEmptyRect (visible))
5799 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
5800 [[NSCursor arrowCursor] setOnMouseEntered: YES];
5804 - (int) checkSamePosition: (int) position portion: (int) portion
5807 return em_position ==position && em_portion ==portion && em_whole ==whole
5808 && portion != whole; /* needed for resize empty buf */
5812 - setPosition: (int)position portion: (int)portion whole: (int)whole
5814 NSTRACE (setPosition);
5816 em_position = position;
5817 em_portion = portion;
5820 if (portion >= whole)
5821 [self setFloatValue: 0.0 knobProportion: 1.0];
5825 portion = max ((float)whole*min_portion/pixel_height, portion);
5826 pos = (float)position / (whole - portion);
5827 por = (float)portion/whole;
5828 [self setFloatValue: pos knobProportion: por];
5833 /* FIXME: unused at moment (see ns_mouse_position) at the moment because
5834 drag events will go directly to the EmacsScroller. Leaving in for now. */
5835 -(void)getMouseMotionPart: (int *)part window: (Lisp_Object *)window
5836 x: (Lisp_Object *)x y: ( Lisp_Object *)y
5838 *part = last_hit_part;
5840 XSETINT (*y, pixel_height);
5841 if ([self floatValue] > 0.999)
5842 XSETINT (*x, pixel_height);
5844 XSETINT (*x, pixel_height * [self floatValue]);
5848 /* set up emacs_event */
5849 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
5854 emacs_event->part = last_hit_part;
5855 emacs_event->code = 0;
5856 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
5857 emacs_event->frame_or_window = win;
5858 emacs_event->timestamp = EV_TIMESTAMP (e);
5859 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
5860 emacs_event->arg = Qnil;
5861 XSETINT (emacs_event->x, loc * pixel_height);
5862 XSETINT (emacs_event->y, pixel_height-20);
5864 n_emacs_events_pending++;
5865 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
5866 EVENT_INIT (*emacs_event);
5867 ns_send_appdefined (-1);
5871 /* called manually thru timer to implement repeated button action w/hold-down */
5872 - repeatScroll: (NSTimer *)scrollEntry
5874 NSEvent *e = [[self window] currentEvent];
5875 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
5876 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
5878 /* clear timer if need be */
5879 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
5881 [scroll_repeat_entry invalidate];
5882 [scroll_repeat_entry release];
5883 scroll_repeat_entry = nil;
5889 = [[NSTimer scheduledTimerWithTimeInterval:
5890 SCROLL_BAR_CONTINUOUS_DELAY
5892 selector: @selector (repeatScroll:)
5898 [self sendScrollEventAtLoc: 0 fromEvent: e];
5903 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
5904 mouseDragged events without going into a modal loop. */
5905 - (void)mouseDown: (NSEvent *)e
5908 /* hitPart is only updated AFTER event is passed on */
5909 NSScrollerPart part = [self testPart: [e locationInWindow]];
5910 double inc = 0.0, loc, kloc, pos;
5913 NSTRACE (EmacsScroller_mouseDown);
5917 case NSScrollerDecrementPage:
5918 last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
5919 case NSScrollerIncrementPage:
5920 last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
5921 case NSScrollerDecrementLine:
5922 last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
5923 case NSScrollerIncrementLine:
5924 last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
5925 case NSScrollerKnob:
5926 last_hit_part = scroll_bar_handle; break;
5927 case NSScrollerKnobSlot: /* GNUstep-only */
5928 last_hit_part = scroll_bar_move_ratio; break;
5929 default: /* NSScrollerNoPart? */
5930 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
5937 pos = 0; /* ignored */
5939 /* set a timer to repeat, as we can't let superclass do this modally */
5941 = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
5943 selector: @selector (repeatScroll:)
5950 /* handle, or on GNUstep possibly slot */
5951 NSEvent *fake_event;
5953 /* compute float loc in slot and mouse offset on knob */
5954 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
5956 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
5962 else if (loc >= NSHeight (sr))
5964 loc = NSHeight (sr);
5972 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
5974 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
5976 last_mouse_offset = kloc;
5978 /* if knob, tell emacs a location offset by knob pos
5979 (to indicate top of handle) */
5980 if (part == NSScrollerKnob)
5981 pos = (loc - last_mouse_offset) / NSHeight (sr);
5983 /* else this is a slot click on GNUstep: go straight there */
5984 pos = loc / NSHeight (sr);
5986 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
5987 fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
5988 location: [e locationInWindow]
5989 modifierFlags: [e modifierFlags]
5990 timestamp: [e timestamp]
5991 windowNumber: [e windowNumber]
5992 context: [e context]
5993 eventNumber: [e eventNumber]
5994 clickCount: [e clickCount]
5995 pressure: [e pressure]];
5996 [super mouseUp: fake_event];
5999 if (part != NSScrollerKnob)
6000 [self sendScrollEventAtLoc: pos fromEvent: e];
6004 /* Called as we manually track scroller drags, rather than superclass. */
6005 - (void)mouseDragged: (NSEvent *)e
6011 NSTRACE (EmacsScroller_mouseDragged);
6013 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6015 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6022 else if (loc >= NSHeight (sr) + last_mouse_offset)
6024 loc = NSHeight (sr) + last_mouse_offset;
6028 pos = /*(edge ? loc :*/ (loc - last_mouse_offset) / NSHeight (sr);
6029 [self sendScrollEventAtLoc: pos fromEvent: e];
6033 - (void)mouseUp: (NSEvent *)e
6035 if (scroll_repeat_entry)
6037 [scroll_repeat_entry invalidate];
6038 [scroll_repeat_entry release];
6039 scroll_repeat_entry = nil;
6045 /* treat scrollwheel events in the bar as though they were in the main window */
6046 - (void) scrollWheel: (NSEvent *)theEvent
6048 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
6049 [view mouseDown: theEvent];
6052 @end /* EmacsScroller */
6057 /* ==========================================================================
6059 Font-related functions; these used to be in nsfaces.m
6061 ========================================================================== */
6065 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
6067 struct font *font = XFONT_OBJECT (font_object);
6070 fontset = fontset_from_font (font_object);
6071 FRAME_FONTSET (f) = fontset;
6073 if (FRAME_FONT (f) == font)
6074 /* This font is already set in frame F. There's nothing more to
6078 FRAME_FONT (f) = font;
6080 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
6081 FRAME_COLUMN_WIDTH (f) = font->average_width;
6082 FRAME_SPACE_WIDTH (f) = font->space_width;
6083 FRAME_LINE_HEIGHT (f) = font->height;
6085 compute_fringe_widths (f, 1);
6087 /* Compute the scroll bar width in character columns. */
6088 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
6090 int wid = FRAME_COLUMN_WIDTH (f);
6091 FRAME_CONFIG_SCROLL_BAR_COLS (f)
6092 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
6096 int wid = FRAME_COLUMN_WIDTH (f);
6097 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
6100 /* Now make the frame display the given font. */
6101 if (FRAME_NS_WINDOW (f) != 0)
6102 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
6108 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
6109 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
6113 ns_xlfd_to_fontname (const char *xlfd)
6114 /* --------------------------------------------------------------------------
6115 Convert an X font name (XLFD) to an NS font name.
6116 Only family is used.
6117 The string returned is temporarily allocated.
6118 -------------------------------------------------------------------------- */
6120 char *name = xmalloc (180);
6124 if (!strncmp (xlfd, "--", 2))
6125 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
6127 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
6129 /* stopgap for malformed XLFD input */
6130 if (strlen (name) == 0)
6131 strcpy (name, "Monaco");
6133 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
6134 also uppercase after '-' or ' ' */
6135 name[0] = toupper (name[0]);
6136 for (len =strlen (name), i =0; i<len; i++)
6142 name[i+1] = toupper (name[i+1]);
6144 else if (name[i] == '_')
6148 name[i+1] = toupper (name[i+1]);
6151 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
6152 ret = [[NSString stringWithUTF8String: name] UTF8String];
6159 syms_of_nsterm (void)
6161 NSTRACE (syms_of_nsterm);
6163 ns_antialias_threshold = 10.0;
6165 /* from 23+ we need to tell emacs what modifiers there are.. */
6166 DEFSYM (Qmodifier_value, "modifier-value");
6167 DEFSYM (Qalt, "alt");
6168 DEFSYM (Qhyper, "hyper");
6169 DEFSYM (Qmeta, "meta");
6170 DEFSYM (Qsuper, "super");
6171 DEFSYM (Qcontrol, "control");
6172 DEFSYM (Qnone, "none");
6173 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
6174 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
6175 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
6176 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
6177 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
6179 DEFVAR_LISP ("ns-input-file", &ns_input_file,
6180 "The file specified in the last NS event.");
6181 ns_input_file =Qnil;
6183 DEFVAR_LISP ("ns-input-text", &ns_input_text,
6184 "The data received in the last NS text drag event.");
6185 ns_input_text =Qnil;
6187 DEFVAR_LISP ("ns-working-text", &ns_working_text,
6188 "String for visualizing working composition sequence.");
6189 ns_working_text =Qnil;
6191 DEFVAR_LISP ("ns-input-font", &ns_input_font,
6192 "The font specified in the last NS event.");
6193 ns_input_font =Qnil;
6195 DEFVAR_LISP ("ns-input-fontsize", &ns_input_fontsize,
6196 "The fontsize specified in the last NS event.");
6197 ns_input_fontsize =Qnil;
6199 DEFVAR_LISP ("ns-input-line", &ns_input_line,
6200 "The line specified in the last NS event.");
6201 ns_input_line =Qnil;
6203 DEFVAR_LISP ("ns-input-color", &ns_input_color,
6204 "The color specified in the last NS event.");
6205 ns_input_color =Qnil;
6207 DEFVAR_LISP ("ns-input-spi-name", &ns_input_spi_name,
6208 "The service name specified in the last NS event.");
6209 ns_input_spi_name =Qnil;
6211 DEFVAR_LISP ("ns-input-spi-arg", &ns_input_spi_arg,
6212 "The service argument specified in the last NS event.");
6213 ns_input_spi_arg =Qnil;
6215 DEFVAR_LISP ("ns-alternate-modifier", &ns_alternate_modifier,
6216 "This variable describes the behavior of the alternate or option key.\n\
6217 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6218 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6219 at all, allowing it to be used at a lower level for accented character entry.");
6220 ns_alternate_modifier = Qmeta;
6222 DEFVAR_LISP ("ns-right-alternate-modifier", &ns_right_alternate_modifier,
6223 "This variable describes the behavior of the right alternate or option key.\n\
6224 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6225 Set to left means be the same key as `ns-alternate-modifier'.\n\
6226 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6227 at all, allowing it to be used at a lower level for accented character entry.");
6228 ns_right_alternate_modifier = Qleft;
6230 DEFVAR_LISP ("ns-command-modifier", &ns_command_modifier,
6231 "This variable describes the behavior of the command key.\n\
6232 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6233 ns_command_modifier = Qsuper;
6235 DEFVAR_LISP ("ns-control-modifier", &ns_control_modifier,
6236 "This variable describes the behavior of the control key.\n\
6237 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6238 ns_control_modifier = Qcontrol;
6240 DEFVAR_LISP ("ns-function-modifier", &ns_function_modifier,
6241 "This variable describes the behavior of the function key (on laptops).\n\
6242 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6243 Set to none means that the function key is not interpreted by Emacs at all,\n\
6244 allowing it to be used at a lower level for accented character entry.");
6245 ns_function_modifier = Qnone;
6247 DEFVAR_LISP ("ns-antialias-text", &ns_antialias_text,
6248 "Non-nil (the default) means to render text antialiased. Only has an effect on OS X Panther and above.");
6249 ns_antialias_text = Qt;
6251 DEFVAR_LISP ("ns-confirm-quit", &ns_confirm_quit,
6252 "Whether to confirm application quit using dialog.");
6253 ns_confirm_quit = Qnil;
6255 staticpro (&ns_display_name_list);
6256 ns_display_name_list = Qnil;
6258 staticpro (&last_mouse_motion_frame);
6259 last_mouse_motion_frame = Qnil;
6261 /* TODO: move to common code */
6262 DEFVAR_LISP ("x-toolkit-scroll-bars", &Vx_toolkit_scroll_bars,
6263 doc: /* If not nil, Emacs uses toolkit scroll bars. */);
6264 #ifdef USE_TOOLKIT_SCROLL_BARS
6265 Vx_toolkit_scroll_bars = Qt;
6267 Vx_toolkit_scroll_bars = Qnil;
6270 /* these are unsupported but we need the declarations to avoid whining
6271 messages from cus-start.el */
6272 DEFVAR_BOOL ("x-use-underline-position-properties",
6273 &x_use_underline_position_properties,
6274 doc: /* NOT SUPPORTED UNDER NS.
6275 *Non-nil means make use of UNDERLINE_POSITION font properties.
6276 A value of nil means ignore them. If you encounter fonts with bogus
6277 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
6278 to 4.1, set this to nil.
6280 NOTE: Not supported on Mac yet. */);
6281 x_use_underline_position_properties = 0;
6283 DEFVAR_BOOL ("x-underline-at-descent-line",
6284 &x_underline_at_descent_line,
6285 doc: /* NOT SUPPORTED UNDER NS.
6286 *Non-nil means to draw the underline at the same place as the descent line.
6287 A value of nil means to draw the underline according to the value of the
6288 variable `x-use-underline-position-properties', which is usually at the
6289 baseline level. The default value is nil. */);
6290 x_underline_at_descent_line = 0;
6292 /* Tell emacs about this window system. */
6293 Fprovide (intern ("ns"), Qnil);
6297 // arch-tag: 6eaa8f7d-a69b-4e1c-b43d-ab31defbe0d2