1 /* NeXT/Open/GNUstep / MacOSX communication module.
2 Copyright (C) 1989, 1993, 1994, 2005, 2006, 2008, 2009
3 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 Originally by Carl Edman
22 Updated by Christian Limpach (chris@nice.ch)
23 OpenStep/Rhapsody port by Scott Bender (sbender@harmony-ds.com)
24 MacOSX/Aqua port by Christophe de Dinechin (descubes@earthlink.net)
25 GNUstep port and post-20 update by Adrian Robert (arobert@cogsci.ucsd.edu)
28 /* This should be the first include, as it may set up #defines affecting
29 interpretation of even the system includes. */
33 #include <sys/types.h>
39 #include "blockinput.h"
40 #include "sysselect.h"
43 #include "character.h"
45 #include "composite.h"
48 #include "termhooks.h"
59 int term_trace_num = 0;
60 #define NSTRACE(x) fprintf (stderr, "%s:%d: [%d] " #x "\n", \
61 __FILE__, __LINE__, ++term_trace_num)
67 /* ==========================================================================
71 ========================================================================== */
73 /* Convert a symbol indexed with an NSxxx value to a value as defined
74 in keyboard.c (lispy_function_key). I hope this is a correct way
76 static unsigned convert_ns_to_X_keysym[] =
78 NSHomeFunctionKey, 0x50,
79 NSLeftArrowFunctionKey, 0x51,
80 NSUpArrowFunctionKey, 0x52,
81 NSRightArrowFunctionKey, 0x53,
82 NSDownArrowFunctionKey, 0x54,
83 NSPageUpFunctionKey, 0x55,
84 NSPageDownFunctionKey, 0x56,
85 NSEndFunctionKey, 0x57,
86 NSBeginFunctionKey, 0x58,
87 NSSelectFunctionKey, 0x60,
88 NSPrintFunctionKey, 0x61,
89 NSExecuteFunctionKey, 0x62,
90 NSInsertFunctionKey, 0x63,
91 NSUndoFunctionKey, 0x65,
92 NSRedoFunctionKey, 0x66,
93 NSMenuFunctionKey, 0x67,
94 NSFindFunctionKey, 0x68,
95 NSHelpFunctionKey, 0x6A,
96 NSBreakFunctionKey, 0x6B,
98 NSF1FunctionKey, 0xBE,
99 NSF2FunctionKey, 0xBF,
100 NSF3FunctionKey, 0xC0,
101 NSF4FunctionKey, 0xC1,
102 NSF5FunctionKey, 0xC2,
103 NSF6FunctionKey, 0xC3,
104 NSF7FunctionKey, 0xC4,
105 NSF8FunctionKey, 0xC5,
106 NSF9FunctionKey, 0xC6,
107 NSF10FunctionKey, 0xC7,
108 NSF11FunctionKey, 0xC8,
109 NSF12FunctionKey, 0xC9,
110 NSF13FunctionKey, 0xCA,
111 NSF14FunctionKey, 0xCB,
112 NSF15FunctionKey, 0xCC,
113 NSF16FunctionKey, 0xCD,
114 NSF17FunctionKey, 0xCE,
115 NSF18FunctionKey, 0xCF,
116 NSF19FunctionKey, 0xD0,
117 NSF20FunctionKey, 0xD1,
118 NSF21FunctionKey, 0xD2,
119 NSF22FunctionKey, 0xD3,
120 NSF23FunctionKey, 0xD4,
121 NSF24FunctionKey, 0xD5,
123 NSBackspaceCharacter, 0x08, /* 8: Not on some KBs. */
124 NSDeleteCharacter, 0xFF, /* 127: Big 'delete' key upper right. */
125 NSDeleteFunctionKey, 0x9F, /* 63272: Del forw key off main array. */
127 NSTabCharacter, 0x09,
128 0x19, 0x09, /* left tab->regular since pass shift */
129 NSCarriageReturnCharacter, 0x0D,
130 NSNewlineCharacter, 0x0D,
131 NSEnterCharacter, 0x8D,
133 0x1B, 0x1B /* escape */
137 /* Lisp communications */
138 Lisp_Object ns_input_file, ns_input_font, ns_input_fontsize, ns_input_line;
139 Lisp_Object ns_input_color, ns_input_text, ns_working_text;
140 Lisp_Object ns_input_spi_name, ns_input_spi_arg;
141 Lisp_Object Vx_toolkit_scroll_bars;
142 static Lisp_Object Qmodifier_value;
143 /* TODO: unsure why these defined in term files, anyway we need in keymap.c */
144 Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper;
145 extern Lisp_Object Qcursor_color, Qcursor_type, Qns;
147 /* Specifies which emacs modifier should be generated when NS receives
148 the Alternate modifer. May be Qnone or any of the modifier lisp symbols. */
149 Lisp_Object ns_alternate_modifier;
151 /* Specifies which emacs modifier should be generated when NS receives
152 the Command modifer. May be any of the modifier lisp symbols. */
153 Lisp_Object ns_command_modifier;
155 /* Specifies which emacs modifier should be generated when NS receives
156 the Control modifer. May be any of the modifier lisp symbols. */
157 Lisp_Object ns_control_modifier;
159 /* Specifies which emacs modifier should be generated when NS receives
160 the Function modifer (laptops). May be any of the modifier lisp symbols. */
161 Lisp_Object ns_function_modifier;
163 /* Control via default 'GSFontAntiAlias' on OS X and GNUstep. */
164 Lisp_Object ns_antialias_text;
166 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
167 the maximum font size to NOT antialias. On GNUstep there is currently
168 no way to control this behavior. */
169 float ns_antialias_threshold;
171 /* Used to pick up AppleHighlightColor on OS X */
172 NSString *ns_selection_color;
174 /* Confirm on exit. */
175 Lisp_Object ns_confirm_quit;
177 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
179 /* Display variables */
180 struct ns_display_info *x_display_list; /* Chain of existing displays */
181 Lisp_Object ns_display_name_list;
182 long context_menu_value = 0;
185 NSPoint last_mouse_motion_position;
186 static NSRect last_mouse_glyph;
187 static unsigned long last_mouse_movement_time = 0;
188 static Lisp_Object last_mouse_motion_frame;
189 static EmacsScroller *last_mouse_scroll_bar = nil;
190 static struct frame *ns_updating_frame;
191 static NSView *focus_view = NULL;
192 static int ns_window_num =0;
194 static BOOL gsaved = NO;
195 BOOL ns_in_resize = NO;
196 static BOOL ns_fake_keydown = NO;
197 int ns_tmp_flags; /* FIXME */
198 struct nsfont_info *ns_tmp_font; /* FIXME */
199 /*static int debug_lock = 0; */
202 static BOOL send_appdefined = YES;
203 static NSEvent *last_appdefined_event = 0;
204 static NSTimer *timed_entry = 0;
205 static NSTimer *fd_entry = nil;
206 static NSTimer *scroll_repeat_entry = nil;
207 static fd_set select_readfds, t_readfds;
208 static struct timeval select_timeout;
209 static int select_nfds;
210 static NSAutoreleasePool *outerpool;
211 static struct input_event *emacs_event = NULL;
212 static struct input_event *q_event_ptr = NULL;
213 static int n_emacs_events_pending = 0;
214 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
215 *ns_pending_service_args;
216 static BOOL inNsSelect = 0;
218 /* Convert modifiers in a NeXTSTEP event to emacs style modifiers. */
219 #define NS_FUNCTION_KEY_MASK 0x800000
220 #define EV_MODIFIERS(e) \
221 ((([e modifierFlags] & NSHelpKeyMask) ? \
222 hyper_modifier : 0) \
223 | (([e modifierFlags] & NSAlternateKeyMask) ? \
224 parse_solitary_modifier (ns_alternate_modifier) : 0) \
225 | (([e modifierFlags] & NSShiftKeyMask) ? \
226 shift_modifier : 0) \
227 | (([e modifierFlags] & NSControlKeyMask) ? \
228 parse_solitary_modifier (ns_control_modifier) : 0) \
229 | (([e modifierFlags] & NS_FUNCTION_KEY_MASK) ? \
230 parse_solitary_modifier (ns_function_modifier) : 0) \
231 | (([e modifierFlags] & NSCommandKeyMask) ? \
232 parse_solitary_modifier (ns_command_modifier):0))
234 #define EV_UDMODIFIERS(e) \
235 ((([e type] == NSLeftMouseDown) ? down_modifier : 0) \
236 | (([e type] == NSRightMouseDown) ? down_modifier : 0) \
237 | (([e type] == NSOtherMouseDown) ? down_modifier : 0) \
238 | (([e type] == NSLeftMouseDragged) ? down_modifier : 0) \
239 | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
240 | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
241 | (([e type] == NSLeftMouseUp) ? up_modifier : 0) \
242 | (([e type] == NSRightMouseUp) ? up_modifier : 0) \
243 | (([e type] == NSOtherMouseUp) ? up_modifier : 0))
245 #define EV_BUTTON(e) \
246 ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 : \
247 (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
248 [e buttonNumber] - 1)
250 /* Convert the time field to a timestamp in milliseconds. */
251 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
253 /* This is a piece of code which is common to all the event handling
254 methods. Maybe it should even be a function. */
255 #define EV_TRAILER(e) \
257 XSETFRAME (emacs_event->frame_or_window, emacsframe); \
258 if (e) emacs_event->timestamp = EV_TIMESTAMP (e); \
259 n_emacs_events_pending++; \
260 kbd_buffer_store_event_hold (emacs_event, q_event_ptr); \
261 EVENT_INIT (*emacs_event); \
262 ns_send_appdefined (-1); \
265 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
267 /* TODO: get rid of need for these forward declarations */
268 static void ns_condemn_scroll_bars (struct frame *f);
269 static void ns_judge_scroll_bars (struct frame *f);
270 void x_set_frame_alpha (struct frame *f);
272 /* unused variables needed for compatibility reasons */
273 int x_use_underline_position_properties, x_underline_at_descent_line;
274 /* FIXME: figure out what to do with underline_minimum_offset. */
277 /* ==========================================================================
281 ========================================================================== */
285 append2 (Lisp_Object list, Lisp_Object item)
286 /* --------------------------------------------------------------------------
287 Utility to append to a list
288 -------------------------------------------------------------------------- */
290 Lisp_Object array[2];
292 array[1] = Fcons (item, Qnil);
293 return Fnconc (2, &array[0]);
299 /* --------------------------------------------------------------------------
300 Used to allow emacs to find its resources under Emacs.app
301 Called from emacs.c at startup.
302 -------------------------------------------------------------------------- */
304 NSBundle *bundle = [NSBundle mainBundle];
305 NSString *binDir = [bundle bundlePath], *resourceDir = [bundle resourcePath];
306 NSString *resourcePath, *resourcePaths;
308 BOOL onWindows = NO; /* how do I determine this? */
309 NSString *pathSeparator = onWindows ? @";" : @":";
310 NSFileManager *fileManager = [NSFileManager defaultManager];
312 /*NSLog (@"ns_init_paths: '%@'\n%@\n", [[NSBundle mainBundle] bundlePath], [[NSBundle mainBundle] resourcePath]); */
314 /* get bindir from base */
315 range = [resourceDir rangeOfString: @"Contents"];
316 if (range.location != NSNotFound)
318 binDir = [binDir stringByAppendingPathComponent: @"Contents"];
320 binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
324 /* the following based on Andrew Choi's init_mac_osx_environment () */
325 if (!getenv ("EMACSLOADPATH"))
327 NSArray *paths = [resourceDir stringsByAppendingPaths:
328 [NSArray arrayWithObjects:
329 @"site-lisp", @"lisp", @"leim", nil]];
330 NSEnumerator *pathEnum = [paths objectEnumerator];
332 while (resourcePath = [pathEnum nextObject])
334 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
337 if ([resourcePaths length] > 0)
339 = [resourcePaths stringByAppendingString: pathSeparator];
341 = [resourcePaths stringByAppendingString: resourcePath];
344 if ([resourcePaths length] > 0)
345 setenv ("EMACSLOADPATH", [resourcePaths UTF8String], 1);
346 /*NSLog (@"loadPath: '%@'\n", resourcePaths); */
349 if (!getenv ("EMACSPATH"))
351 NSArray *paths = [binDir stringsByAppendingPaths:
352 [NSArray arrayWithObjects: @"bin",
354 NSEnumerator *pathEnum = [paths objectEnumerator];
356 while (resourcePath = [pathEnum nextObject])
358 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
361 if ([resourcePaths length] > 0)
363 = [resourcePaths stringByAppendingString: pathSeparator];
365 = [resourcePaths stringByAppendingString: resourcePath];
368 if ([resourcePaths length] > 0)
369 setenv ("EMACSPATH", [resourcePaths UTF8String], 1);
372 resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
373 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
377 if (!getenv ("EMACSDATA"))
378 setenv ("EMACSDATA", [resourcePath UTF8String], 1);
379 if (!getenv ("EMACSDOC"))
380 setenv ("EMACSDOC", [resourcePath UTF8String], 1);
384 if (!getenv ("INFOPATH"))
386 resourcePath = [resourceDir stringByAppendingPathComponent: @"info"];
387 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
389 setenv ("INFOPATH", [[resourcePath stringByAppendingString: @":"]
391 /* Note, extra colon needed to cause merge w/later user additions. */
397 timeval_subtract (struct timeval *result, struct timeval x, struct timeval y)
398 /* --------------------------------------------------------------------------
399 Subtract the `struct timeval' values X and Y, storing the result in RESULT.
400 Return 1 if the difference is negative, otherwise 0.
401 -------------------------------------------------------------------------- */
403 /* Perform the carry for the later subtraction by updating y.
404 This is safer because on some systems
405 the tv_sec member is unsigned. */
406 if (x.tv_usec < y.tv_usec)
408 int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
409 y.tv_usec -= 1000000 * nsec;
412 if (x.tv_usec - y.tv_usec > 1000000)
414 int nsec = (y.tv_usec - x.tv_usec) / 1000000;
415 y.tv_usec += 1000000 * nsec;
419 /* Compute the time remaining to wait. tv_usec is certainly positive. */
420 result->tv_sec = x.tv_sec - y.tv_sec;
421 result->tv_usec = x.tv_usec - y.tv_usec;
423 /* Return indication of whether the result should be considered negative. */
424 return x.tv_sec < y.tv_sec;
428 ns_timeout (int usecs)
429 /* --------------------------------------------------------------------------
430 Blocking timer utility used by ns_ring_bell
431 -------------------------------------------------------------------------- */
433 struct timeval wakeup;
435 EMACS_GET_TIME (wakeup);
437 /* Compute time to wait until, propagating carry from usecs. */
438 wakeup.tv_usec += usecs;
439 wakeup.tv_sec += (wakeup.tv_usec / 1000000);
440 wakeup.tv_usec %= 1000000;
442 /* Keep waiting until past the time wakeup. */
445 struct timeval timeout;
447 EMACS_GET_TIME (timeout);
449 /* In effect, timeout = wakeup - timeout.
450 Break if result would be negative. */
451 if (timeval_subtract (&timeout, wakeup, timeout))
454 /* Try to wait that long--but we might wake up sooner. */
455 select (0, NULL, NULL, NULL, &timeout);
461 ns_release_object (void *obj)
462 /* --------------------------------------------------------------------------
463 Release an object (callable from C)
464 -------------------------------------------------------------------------- */
471 ns_retain_object (void *obj)
472 /* --------------------------------------------------------------------------
473 Retain an object (callable from C)
474 -------------------------------------------------------------------------- */
481 ns_alloc_autorelease_pool ()
482 /* --------------------------------------------------------------------------
483 Allocate a pool for temporary objects (callable from C)
484 -------------------------------------------------------------------------- */
486 return [[NSAutoreleasePool alloc] init];
491 ns_release_autorelease_pool (void *pool)
492 /* --------------------------------------------------------------------------
493 Free a pool and temporary objects it refers to (callable from C)
494 -------------------------------------------------------------------------- */
496 ns_release_object (pool);
501 /* ==========================================================================
503 Focus (clipping) and screen update
505 ========================================================================== */
508 ns_resize_handle_rect (NSWindow *window)
510 NSRect r = [window frame];
511 r.origin.x = r.size.width - RESIZE_HANDLE_SIZE;
513 r.size.width = r.size.height = RESIZE_HANDLE_SIZE;
519 ns_update_begin (struct frame *f)
520 /* --------------------------------------------------------------------------
521 Prepare for a grouped sequence of drawing calls
522 external (RIF) call; whole frame, called before update_window_begin
523 -------------------------------------------------------------------------- */
525 NSView *view = FRAME_NS_VIEW (f);
526 NSTRACE (ns_update_begin);
528 ns_updating_frame = f;
531 #ifdef NS_IMPL_GNUSTEP
532 uRect = NSMakeRect (0, 0, 0, 0);
538 ns_update_window_begin (struct window *w)
539 /* --------------------------------------------------------------------------
540 Prepare for a grouped sequence of drawing calls
541 external (RIF) call; for one window, called after update_begin
542 -------------------------------------------------------------------------- */
544 struct frame *f = XFRAME (WINDOW_FRAME (w));
545 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
546 NSTRACE (ns_update_window_begin);
549 set_output_cursor (&w->cursor);
553 if (f == dpyinfo->mouse_face_mouse_frame)
555 /* Don't do highlighting for mouse motion during the update. */
556 dpyinfo->mouse_face_defer = 1;
558 /* If the frame needs to be redrawn,
559 simply forget about any prior mouse highlighting. */
560 if (FRAME_GARBAGED_P (f))
561 dpyinfo->mouse_face_window = Qnil;
563 /* (further code for mouse faces ifdef'd out in other terms elided) */
571 ns_update_window_end (struct window *w, int cursor_on_p,
572 int mouse_face_overwritten_p)
573 /* --------------------------------------------------------------------------
574 Finished a grouped sequence of drawing calls
575 external (RIF) call; for one window called before update_end
576 -------------------------------------------------------------------------- */
578 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (XFRAME (w->frame));
580 /* note: this fn is nearly identical in all terms */
581 if (!w->pseudo_window_p)
586 display_and_set_cursor (w, 1,
587 output_cursor.hpos, output_cursor.vpos,
588 output_cursor.x, output_cursor.y);
590 if (draw_window_fringes (w, 1))
591 x_draw_vertical_border (w);
596 /* If a row with mouse-face was overwritten, arrange for
597 frame_up_to_date to redisplay the mouse highlight. */
598 if (mouse_face_overwritten_p)
600 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
601 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
602 dpyinfo->mouse_face_window = Qnil;
605 updated_window = NULL;
606 NSTRACE (update_window_end);
611 ns_update_end (struct frame *f)
612 /* --------------------------------------------------------------------------
613 Finished a grouped sequence of drawing calls
614 external (RIF) call; for whole frame, called after update_window_end
615 -------------------------------------------------------------------------- */
617 NSView *view = FRAME_NS_VIEW (f);
619 /* if (f == FRAME_NS_DISPLAY_INFO (f)->mouse_face_mouse_frame) */
620 FRAME_NS_DISPLAY_INFO (f)->mouse_face_defer = 0;
624 #ifdef NS_IMPL_GNUSTEP
625 /* trigger flush only in the rectangle we tracked as being drawn */
626 [view unlockFocusNeedsFlush: NO];
627 /*fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", uRect.origin.x, uRect.origin.y, uRect.size.width, uRect.size.height); */
628 [view lockFocusInRect: uRect];
632 [[view window] flushWindow];
635 ns_updating_frame = NULL;
636 NSTRACE (ns_update_end);
641 ns_flush (struct frame *f)
642 /* --------------------------------------------------------------------------
644 NS impl is no-op since currently we flush in ns_update_end and elsewhere
645 -------------------------------------------------------------------------- */
652 ns_focus (struct frame *f, NSRect *r, int n)
653 /* --------------------------------------------------------------------------
654 Internal: Focus on given frame. During small local updates this is used to
655 draw, however during large updates, ns_update_begin and ns_update_end are
656 called to wrap the whole thing, in which case these calls are stubbed out.
657 Except, on GNUstep, we accumulate the rectangle being drawn into, because
658 the back end won't do this automatically, and will just end up flushing
660 -------------------------------------------------------------------------- */
662 // NSTRACE (ns_focus);
663 #ifdef NS_IMPL_GNUSTEP
666 u = NSUnionRect (r[0], r[1]);
671 fprintf (stderr, "focus: %d", c++);
672 if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
673 fprintf (stderr, "\n"); */
675 if (f != ns_updating_frame)
677 NSView *view = FRAME_NS_VIEW (f);
678 if (view != focus_view)
680 if (focus_view != NULL)
682 [focus_view unlockFocus];
683 [[focus_view window] flushWindow];
688 #ifdef NS_IMPL_GNUSTEP
689 r ? [view lockFocusInRect: u] : [view lockFocus];
694 /*if (view) debug_lock++; */
696 #ifdef NS_IMPL_GNUSTEP
699 /* more than one rect being drawn into */
702 [view unlockFocus]; /* add prev rect to redraw list */
703 [view lockFocusInRect: u]; /* focus for draw in new rect */
708 #ifdef NS_IMPL_GNUSTEP
711 /* in batch mode, but in GNUstep must still track rectangles explicitly */
712 uRect = (r ? NSUnionRect (uRect, u) : [FRAME_NS_VIEW (f) visibleRect]);
719 [[NSGraphicsContext currentContext] saveGraphicsState];
721 NSRectClipList (r, 2);
730 ns_unfocus (struct frame *f)
731 /* --------------------------------------------------------------------------
732 Internal: Remove focus on given frame
733 -------------------------------------------------------------------------- */
735 // NSTRACE (ns_unfocus);
739 [[NSGraphicsContext currentContext] restoreGraphicsState];
743 if (f != ns_updating_frame)
745 if (focus_view != NULL)
747 [focus_view unlockFocus];
748 [[focus_view window] flushWindow];
757 ns_clip_to_row (struct window *w, struct glyph_row *row, int area, BOOL gc)
758 /* --------------------------------------------------------------------------
759 Internal (but parallels other terms): Focus drawing on given row
760 -------------------------------------------------------------------------- */
762 struct frame *f = XFRAME (WINDOW_FRAME (w));
764 int window_x, window_y, window_width;
766 window_box (w, area, &window_x, &window_y, &window_width, 0);
768 clip_rect.origin.x = window_x - FRAME_INTERNAL_BORDER_WIDTH (f);
769 clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
770 clip_rect.origin.y = max (clip_rect.origin.y, window_y);
771 clip_rect.size.width = window_width + 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
772 clip_rect.size.height = row->visible_height;
774 /* allow a full-height row at the top when requested
775 (used to draw fringe all the way through internal border area) */
776 if (gc && clip_rect.origin.y < 5)
778 clip_rect.origin.y -= FRAME_INTERNAL_BORDER_WIDTH (f);
779 clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
782 /* likewise at bottom */
784 FRAME_PIXEL_HEIGHT (f) - (clip_rect.origin.y + clip_rect.size.height) < 5)
785 clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
787 ns_focus (f, &clip_rect, 1);
793 /* --------------------------------------------------------------------------
795 -------------------------------------------------------------------------- */
797 NSTRACE (ns_ring_bell);
800 NSAutoreleasePool *pool;
801 struct frame *frame = SELECTED_FRAME ();
805 pool = [[NSAutoreleasePool alloc] init];
807 view = FRAME_NS_VIEW (frame);
811 NSPoint dim = NSMakePoint (128, 128);
814 r.origin.x += (r.size.width - dim.x) / 2;
815 r.origin.y += (r.size.height - dim.y) / 2;
816 r.size.width = dim.x;
817 r.size.height = dim.y;
818 surr = NSInsetRect (r, -2, -2);
819 ns_focus (frame, &surr, 1);
820 [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
821 [ns_lookup_indexed_color (NS_FACE_FOREGROUND
822 (FRAME_DEFAULT_FACE (frame)), frame) set];
824 [[view window] flushWindow];
826 [[view window] restoreCachedImage];
827 [[view window] flushWindow];
841 ns_reset_terminal_modes (struct terminal *terminal)
842 /* Externally called as hook */
844 NSTRACE (ns_reset_terminal_modes);
849 ns_set_terminal_modes (struct terminal *terminal)
850 /* Externally called as hook */
852 NSTRACE (ns_set_terminal_modes);
857 /* ==========================================================================
859 Frame / window manager related functions
861 ========================================================================== */
865 ns_raise_frame (struct frame *f)
866 /* --------------------------------------------------------------------------
867 Bring window to foreground and make it active
868 -------------------------------------------------------------------------- */
870 NSView *view = FRAME_NS_VIEW (f);
873 FRAME_SAMPLE_VISIBILITY (f);
874 if (FRAME_VISIBLE_P (f))
876 [[view window] makeKeyAndOrderFront: NSApp];
883 ns_lower_frame (struct frame *f)
884 /* --------------------------------------------------------------------------
886 -------------------------------------------------------------------------- */
888 NSView *view = FRAME_NS_VIEW (f);
891 [[view window] orderBack: NSApp];
897 ns_frame_raise_lower (struct frame *f, int raise)
898 /* --------------------------------------------------------------------------
900 -------------------------------------------------------------------------- */
902 NSTRACE (ns_frame_raise_lower);
912 ns_frame_rehighlight (struct frame *frame)
913 /* --------------------------------------------------------------------------
914 External (hook): called on things like window switching within frame
915 -------------------------------------------------------------------------- */
917 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
918 struct frame *old_highlight = dpyinfo->x_highlight_frame;
920 NSTRACE (ns_frame_rehighlight);
921 if (dpyinfo->x_focus_frame)
923 dpyinfo->x_highlight_frame
924 = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
925 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
926 : dpyinfo->x_focus_frame);
927 if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
929 FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
930 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
934 dpyinfo->x_highlight_frame = 0;
936 if (dpyinfo->x_highlight_frame &&
937 dpyinfo->x_highlight_frame != old_highlight)
941 x_update_cursor (old_highlight, 1);
942 x_set_frame_alpha (old_highlight);
944 if (dpyinfo->x_highlight_frame)
946 x_update_cursor (dpyinfo->x_highlight_frame, 1);
947 x_set_frame_alpha (dpyinfo->x_highlight_frame);
954 x_make_frame_visible (struct frame *f)
955 /* --------------------------------------------------------------------------
956 External: Show the window (X11 semantics)
957 -------------------------------------------------------------------------- */
959 NSTRACE (x_make_frame_visible);
960 /* XXX: at some points in past this was not needed, as the only place that
961 called this (frame.c:Fraise_frame ()) also called raise_lower;
962 if this ends up the case again, comment this out again. */
963 if (!FRAME_VISIBLE_P (f))
965 f->async_visible = 1;
972 x_make_frame_invisible (struct frame *f)
973 /* --------------------------------------------------------------------------
974 External: Hide the window (X11 semantics)
975 -------------------------------------------------------------------------- */
977 NSView * view = FRAME_NS_VIEW (f);
978 NSTRACE (x_make_frame_invisible);
980 [[view window] orderOut: NSApp];
981 f->async_visible = 0;
982 f->async_iconified = 0;
987 x_iconify_frame (struct frame *f)
988 /* --------------------------------------------------------------------------
989 External: Iconify window
990 -------------------------------------------------------------------------- */
992 NSView * view = FRAME_NS_VIEW (f);
993 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
994 NSTRACE (x_iconify_frame);
997 if (dpyinfo->x_highlight_frame == f)
998 dpyinfo->x_highlight_frame = 0;
1000 if ([[view window] windowNumber] <= 0)
1002 /* the window is still deferred. Make it very small, bring it
1003 on screen and order it out. */
1004 NSRect s = { { 100, 100}, {0, 0} };
1006 t = [[view window] frame];
1007 [[view window] setFrame: s display: NO];
1008 [[view window] orderBack: NSApp];
1009 [[view window] orderOut: NSApp];
1010 [[view window] setFrame: t display: NO];
1012 [[view window] miniaturize: NSApp];
1017 x_destroy_window (struct frame *f)
1018 /* --------------------------------------------------------------------------
1019 External: Delete the window
1020 -------------------------------------------------------------------------- */
1022 NSView *view = FRAME_NS_VIEW (f);
1023 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1024 NSTRACE (x_destroy_window);
1027 [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1031 free_frame_menubar (f);
1033 if (FRAME_FACE_CACHE (f))
1034 free_frame_faces (f);
1036 if (f == dpyinfo->x_focus_frame)
1037 dpyinfo->x_focus_frame = 0;
1038 if (f == dpyinfo->x_highlight_frame)
1039 dpyinfo->x_highlight_frame = 0;
1040 if (f == dpyinfo->mouse_face_mouse_frame)
1042 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
1043 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
1044 dpyinfo->mouse_face_window = Qnil;
1045 dpyinfo->mouse_face_deferred_gc = 0;
1046 dpyinfo->mouse_face_mouse_frame = 0;
1049 xfree (f->output_data.ns);
1051 [[view window] close];
1060 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1061 /* --------------------------------------------------------------------------
1062 External: Position the window
1063 -------------------------------------------------------------------------- */
1066 NSView *view = FRAME_NS_VIEW (f);
1068 NSTRACE (x_set_offset);
1074 #ifdef NS_IMPL_GNUSTEP
1076 f->left_pos = 100; /* don't overlap menu */
1079 if (view != nil && (screen = [[view window] screen]))
1080 [[view window] setFrameTopLeftPoint:
1081 NSMakePoint (SCREENMAXBOUND (f->left_pos),
1082 SCREENMAXBOUND ([screen frame].size.height
1083 - NS_TOP_POS (f)))];
1089 x_set_window_size (struct frame *f, int change_grav, int cols, int rows)
1090 /* --------------------------------------------------------------------------
1091 Adjust window pixel size based on given character grid size
1092 Impl is a bit more complex than other terms, need to do some
1093 internal clipping and also pay attention to screen constraints.
1094 -------------------------------------------------------------------------- */
1096 EmacsView *view = FRAME_NS_VIEW (f);
1097 EmacsToolbar *toolbar = [view toolbar];
1098 NSWindow *window = [view window];
1099 NSScreen *screen = [window screen];
1100 NSRect wr = [window frame];
1101 int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1102 int pixelwidth, pixelheight;
1103 static int oldRows, oldCols, oldFontWidth, oldFontHeight;
1105 static struct frame *oldF;
1107 NSTRACE (x_set_window_size);
1111 && rows == oldRows && cols == oldCols
1112 && oldFontWidth == FRAME_COLUMN_WIDTH (f)
1113 && oldFontHeight == FRAME_LINE_HEIGHT (f)
1117 /*fprintf (stderr, "\tsetWindowSize: %d x %d, font size %d x %d\n", cols, rows, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f)); */
1121 check_frame_size (f, &rows, &cols);
1125 oldFontWidth = FRAME_COLUMN_WIDTH (f);
1126 oldFontHeight = FRAME_LINE_HEIGHT (f);
1129 f->scroll_bar_actual_width = NS_SCROLL_BAR_WIDTH (f);
1130 compute_fringe_widths (f, 0);
1132 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols);
1133 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
1135 /* If we have a toolbar, take its height into account. */
1137 /* NOTE: previously this would generate wrong result if toolbar not
1138 yet displayed and fixing toolbar_height=32 helped, but
1139 now (200903) seems no longer needed */
1140 FRAME_NS_TOOLBAR_HEIGHT (f) =
1141 NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1142 - FRAME_NS_TITLEBAR_HEIGHT (f);
1144 FRAME_NS_TOOLBAR_HEIGHT (f) = 0;
1146 wr.size.width = pixelwidth + f->border_width;
1147 wr.size.height = pixelheight + FRAME_NS_TITLEBAR_HEIGHT (f)
1148 + FRAME_NS_TOOLBAR_HEIGHT (f);
1150 /* constrain to screen if we can */
1153 NSSize sz = [screen visibleFrame].size;
1154 NSSize ez = { wr.size.width - sz.width, wr.size.height - sz.height };
1157 int cr = ez.width / FRAME_COLUMN_WIDTH (f) + 1;
1160 wr.size.width -= cr * FRAME_COLUMN_WIDTH (f);
1161 pixelwidth -= cr * FRAME_COLUMN_WIDTH (f);
1165 int rr = ez.height / FRAME_LINE_HEIGHT (f) + 1;
1168 wr.size.height -= rr * FRAME_LINE_HEIGHT (f);
1169 pixelheight -= rr * FRAME_LINE_HEIGHT (f);
1171 wr.origin.x = f->left_pos;
1172 wr.origin.y = [screen frame].size.height - NS_TOP_POS (f)
1176 [view setRows: rows andColumns: cols];
1177 [window setFrame: wr display: YES];
1179 /*fprintf (stderr, "\tx_set_window_size %d, %d\t%d, %d\n", cols, rows, pixelwidth, pixelheight); */
1181 /* This is a trick to compensate for Emacs' managing the scrollbar area
1182 as a fixed number of standard character columns. Instead of leaving
1183 blank space for the extra, we chopped it off above. Now for
1184 left-hand scrollbars, we shift all rendering to the left by the
1185 difference between the real width and Emacs' imagined one. For
1186 right-hand bars, don't worry about it since the extra is never used.
1187 (Obviously doesn't work for vertically split windows tho..) */
1188 NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1189 ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1190 - NS_SCROLL_BAR_WIDTH (f), 0)
1191 : NSMakePoint (0, 0);
1192 [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1193 [view setBoundsOrigin: origin];
1195 change_frame_size (f, rows, cols, 0, 1, 0); /* pretend, delay, safe */
1196 FRAME_PIXEL_WIDTH (f) = pixelwidth;
1197 FRAME_PIXEL_HEIGHT (f) = pixelheight;
1198 /* SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */
1200 mark_window_cursors_off (XWINDOW (f->root_window));
1201 cancel_mouse_face (f);
1208 /* ==========================================================================
1212 ========================================================================== */
1216 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1218 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1219 if (idx < 1 || idx >= color_table->avail)
1221 return color_table->colors[idx];
1226 ns_index_color (NSColor *color, struct frame *f)
1228 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1232 if (!color_table->colors)
1234 color_table->size = NS_COLOR_CAPACITY;
1235 color_table->avail = 1; /* skip idx=0 as marker */
1237 = (NSColor **)xmalloc (color_table->size * sizeof (NSColor *));
1238 color_table->colors[0] = nil;
1239 color_table->empty_indices = [[NSMutableSet alloc] init];
1242 /* do we already have this color ? */
1245 for (i = 1; i < color_table->avail; i++)
1247 if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1249 [color_table->colors[i] retain];
1255 if ([color_table->empty_indices count] > 0)
1257 index = [color_table->empty_indices anyObject];
1258 [color_table->empty_indices removeObject: index];
1259 idx = [index unsignedIntValue];
1263 if (color_table->avail == color_table->size)
1265 color_table->size += NS_COLOR_CAPACITY;
1267 = (NSColor **)xrealloc (color_table->colors,
1268 color_table->size * sizeof (NSColor *));
1270 idx = color_table->avail++;
1273 color_table->colors[idx] = color;
1275 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1281 ns_free_indexed_color (unsigned long idx, struct frame *f)
1283 struct ns_color_table *color_table;
1290 color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1292 if (idx <= 0 || idx >= color_table->size) {
1293 message1("ns_free_indexed_color: Color index out of range.\n");
1297 index = [NSNumber numberWithUnsignedInt: idx];
1298 if ([color_table->empty_indices containsObject: index]) {
1299 message1("ns_free_indexed_color: attempt to free already freed color.\n");
1303 color = color_table->colors[idx];
1305 color_table->colors[idx] = nil;
1306 [color_table->empty_indices addObject: [NSNumber numberWithUnsignedInt: idx]];
1307 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1312 ns_get_color (const char *name, NSColor **col)
1313 /* --------------------------------------------------------------------------
1315 -------------------------------------------------------------------------- */
1316 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1317 X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1318 See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1321 static char hex[20];
1323 float r = -1.0, g, b;
1324 NSString *nsname = [NSString stringWithUTF8String: name];
1326 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1329 if ([nsname isEqualToString: @"ns_selection_color"])
1331 nsname = ns_selection_color;
1332 name = [ns_selection_color UTF8String];
1335 /* First, check for some sort of numeric specification. */
1338 if (name[0] == '0' || name[0] == '1' || name[0] == '.') /* RGB decimal */
1340 NSScanner *scanner = [NSScanner scannerWithString: nsname];
1341 [scanner scanFloat: &r];
1342 [scanner scanFloat: &g];
1343 [scanner scanFloat: &b];
1345 else if (!strncmp(name, "rgb:", 4)) /* A newer X11 format -- rgb:r/g/b */
1347 strcpy(hex, name + 4);
1348 scaling = (strlen(hex) - 2) / 3;
1350 else if (name[0] == '#') /* An old X11 format; convert to newer */
1352 int len = (strlen(name) - 1);
1353 int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1355 scaling = strlen(name+start) / 3;
1356 for (i=0; i<3; i++) {
1357 strncpy(hex + i * (scaling + 1), name + start + i * scaling, scaling);
1358 hex[(i+1) * (scaling + 1) - 1] = '/';
1360 hex[3 * (scaling + 1) - 1] = '\0';
1366 float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1367 if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1377 *col = [NSColor colorWithCalibratedRed: r green: g blue: b alpha: 1.0];
1382 /* Otherwise, color is expected to be from a list */
1384 NSEnumerator *lenum, *cenum;
1388 #ifdef NS_IMPL_GNUSTEP
1389 /* XXX: who is wrong, the requestor or the implementation? */
1390 if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1392 nsname = @"highlightColor";
1395 lenum = [[NSColorList availableColorLists] objectEnumerator];
1396 while ( (clist = [lenum nextObject]) && new == nil)
1398 cenum = [[clist allKeys] objectEnumerator];
1399 while ( (name = [cenum nextObject]) && new == nil )
1401 if ([name compare: nsname
1402 options: NSCaseInsensitiveSearch] == NSOrderedSame )
1403 new = [clist colorWithKey: name];
1409 *col = [new colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1416 ns_get_color_default (const char *name, NSColor *dflt)
1417 /* --------------------------------------------------------------------------
1418 Parse a color or use a default value
1419 -------------------------------------------------------------------------- */
1423 if (ns_get_color (name, &col))
1431 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1432 /* --------------------------------------------------------------------------
1433 Convert a Lisp string object to a NS color
1434 -------------------------------------------------------------------------- */
1436 NSTRACE (ns_lisp_to_color);
1437 if (STRINGP (color))
1438 return ns_get_color (SDATA (color), col);
1439 else if (SYMBOLP (color))
1440 return ns_get_color (SDATA (SYMBOL_NAME (color)), col);
1446 ns_color_to_lisp (NSColor *col)
1447 /* --------------------------------------------------------------------------
1448 Convert a color to a lisp string with the RGB equivalent
1449 -------------------------------------------------------------------------- */
1451 float red, green, blue, alpha, gray;
1454 NSTRACE (ns_color_to_lisp);
1457 if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1459 if ((str =[[col colorNameComponent] UTF8String]))
1462 return build_string ((char *)str);
1465 [[col colorUsingColorSpaceName: NSCalibratedRGBColorSpace]
1466 getRed: &red green: &green blue: &blue alpha: &alpha];
1467 if (red ==green && red ==blue)
1469 [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1470 getWhite: &gray alpha: &alpha];
1471 snprintf (buf, sizeof (buf), "#%02.2lx%02.2lx%02.2lx",
1472 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1474 return build_string (buf);
1477 snprintf (buf, sizeof (buf), "#%02.2lx%02.2lx%02.2lx",
1478 lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1481 return build_string (buf);
1486 ns_query_color(void *col, XColor *color_def, int setPixel)
1487 /* --------------------------------------------------------------------------
1488 Get ARGB values out of NSColor col and put them into color_def.
1489 If setPixel, set the pixel to a concatenated version.
1490 and set color_def pixel to the resulting index.
1491 -------------------------------------------------------------------------- */
1495 [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1496 color_def->red = r * 65535;
1497 color_def->green = g * 65535;
1498 color_def->blue = b * 65535;
1500 if (setPixel == YES)
1502 = ARGB_TO_ULONG((int)(a*255),
1503 (int)(r*255), (int)(g*255), (int)(b*255));
1508 ns_defined_color (struct frame *f, char *name, XColor *color_def, int alloc,
1510 /* --------------------------------------------------------------------------
1511 Return 1 if named color found, and set color_def rgb accordingly.
1512 If makeIndex and alloc are nonzero put the color in the color_table,
1513 and set color_def pixel to the resulting index.
1514 If makeIndex is zero, set color_def pixel to ARGB.
1515 Return 0 if not found
1516 -------------------------------------------------------------------------- */
1519 int notFound = ns_get_color (name, &temp);
1521 NSTRACE (ns_defined_color);
1526 if (makeIndex && alloc)
1527 color_def->pixel = ns_index_color(temp, f); /* [temp retain]; */
1529 ns_query_color (temp, color_def, !makeIndex);
1536 ns_get_rgb_color (struct frame *f, float r, float g, float b, float a)
1537 /* --------------------------------------------------------------------------
1538 return an autoreleased RGB color
1539 -------------------------------------------------------------------------- */
1541 /*static int c = 1; fprintf (stderr, "color request %d\n", c++); */
1542 if (r < 0.0) r = 0.0;
1543 else if (r > 1.0) r = 1.0;
1544 if (g < 0.0) g = 0.0;
1545 else if (g > 1.0) g = 1.0;
1546 if (b < 0.0) b = 0.0;
1547 else if (b > 1.0) b = 1.0;
1548 if (a < 0.0) a = 0.0;
1549 else if (a > 1.0) a = 1.0;
1550 return (unsigned long) ns_index_color(
1551 [NSColor colorWithCalibratedRed: r green: g blue: b alpha: a], f);
1556 x_set_frame_alpha (struct frame *f)
1557 /* --------------------------------------------------------------------------
1558 change the entire-frame transparency
1559 -------------------------------------------------------------------------- */
1561 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1562 EmacsView *view = FRAME_NS_VIEW (f);
1564 double alpha_min = 1.0;
1566 if (dpyinfo->x_highlight_frame == f)
1567 alpha = f->alpha[0];
1569 alpha = f->alpha[1];
1571 if (FLOATP (Vframe_alpha_lower_limit))
1572 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1573 else if (INTEGERP (Vframe_alpha_lower_limit))
1574 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1578 else if (1.0 < alpha)
1580 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1583 #ifdef NS_IMPL_COCOA
1584 [[view window] setAlphaValue: alpha];
1589 /* ==========================================================================
1593 ========================================================================== */
1597 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1598 /* --------------------------------------------------------------------------
1599 Programmatically reposition mouse pointer in pixel coordinates
1600 -------------------------------------------------------------------------- */
1602 NSTRACE (x_set_mouse_pixel_position);
1605 /* FIXME: this does not work, and what about GNUstep? */
1606 #ifdef NS_IMPL_COCOA
1607 [FRAME_NS_VIEW (f) lockFocus];
1608 PSsetmouse ((float)pix_x, (float)pix_y);
1609 [FRAME_NS_VIEW (f) unlockFocus];
1616 x_set_mouse_position (struct frame *f, int h, int v)
1617 /* --------------------------------------------------------------------------
1618 Programmatically reposition mouse pointer in character coordinates
1619 -------------------------------------------------------------------------- */
1623 pix_x = FRAME_COL_TO_PIXEL_X (f, h) + FRAME_COLUMN_WIDTH (f) / 2;
1624 pix_y = FRAME_LINE_TO_PIXEL_Y (f, v) + FRAME_LINE_HEIGHT (f) / 2;
1626 if (pix_x < 0) pix_x = 0;
1627 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
1629 if (pix_y < 0) pix_y = 0;
1630 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
1632 x_set_mouse_pixel_position (f, pix_x, pix_y);
1637 note_mouse_movement (struct frame *frame, float x, float y)
1638 /* ------------------------------------------------------------------------
1639 Called by EmacsView on mouseMovement events. Passes on
1640 to emacs mainstream code if we moved off of a rect of interest
1641 known as last_mouse_glyph.
1642 ------------------------------------------------------------------------ */
1644 // NSTRACE (note_mouse_movement);
1646 XSETFRAME (last_mouse_motion_frame, frame);
1648 /* Note, this doesn't get called for enter/leave, since we don't have a
1649 position. Those are taken care of in the corresponding NSView methods. */
1651 /* has movement gone beyond last rect we were tracking? */
1652 if (x < last_mouse_glyph.origin.x ||
1653 x >= (last_mouse_glyph.origin.x + last_mouse_glyph.size.width) ||
1654 y < last_mouse_glyph.origin.y ||
1655 y >= (last_mouse_glyph.origin.y + last_mouse_glyph.size.height))
1657 ns_update_begin(frame);
1658 frame->mouse_moved = 1;
1659 note_mouse_highlight (frame, x, y);
1660 remember_mouse_glyph (frame, x, y, &last_mouse_glyph);
1661 ns_update_end(frame);
1670 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1671 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1672 unsigned long *time)
1673 /* --------------------------------------------------------------------------
1674 External (hook): inform emacs about mouse position and hit parts.
1675 If a scrollbar is being dragged, set bar_window, part, x, y, time.
1676 x & y should be position in the scrollbar (the whole bar, not the handle)
1677 and length of scrollbar respectively
1678 -------------------------------------------------------------------------- */
1683 Lisp_Object frame, tail;
1685 struct ns_display_info *dpyinfo;
1687 NSTRACE (ns_mouse_position);
1691 fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1695 dpyinfo = FRAME_NS_DISPLAY_INFO (*fp);
1699 if (last_mouse_scroll_bar != nil && insist == 0)
1701 /* TODO: we do not use this path at the moment because drag events will
1702 go directly to the EmacsScroller. Leaving code in for now. */
1703 [last_mouse_scroll_bar getMouseMotionPart: (int *)part window: bar_window
1705 if (time) *time = last_mouse_movement_time;
1706 last_mouse_scroll_bar = nil;
1710 /* Clear the mouse-moved flag for every frame on this display. */
1711 FOR_EACH_FRAME (tail, frame)
1712 if (FRAME_NS_P (XFRAME (frame))
1713 && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1714 XFRAME (frame)->mouse_moved = 0;
1716 last_mouse_scroll_bar = nil;
1717 if (last_mouse_frame && FRAME_LIVE_P (last_mouse_frame))
1718 f = last_mouse_frame;
1720 f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame
1721 : SELECTED_FRAME ();
1723 if (f && f->output_data.ns) /* TODO: 2nd check no longer needed? */
1725 view = FRAME_NS_VIEW (*fp);
1727 position = [[view window] mouseLocationOutsideOfEventStream];
1728 position = [view convertPoint: position fromView: nil];
1729 remember_mouse_glyph (f, position.x, position.y, &last_mouse_glyph);
1730 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1732 if (bar_window) *bar_window = Qnil;
1733 if (part) *part = 0; /*scroll_bar_handle; */
1735 if (x) XSETINT (*x, lrint (position.x));
1736 if (y) XSETINT (*y, lrint (position.y));
1737 if (time) *time = last_mouse_movement_time;
1747 ns_frame_up_to_date (struct frame *f)
1748 /* --------------------------------------------------------------------------
1749 External (hook): Fix up mouse highlighting right after a full update.
1750 Some highlighting was deferred if GC was happening during
1751 note_mouse_highlight (), while other highlighting was deferred for update.
1752 -------------------------------------------------------------------------- */
1754 NSTRACE (ns_frame_up_to_date);
1758 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1759 if ((dpyinfo->mouse_face_deferred_gc||f ==dpyinfo->mouse_face_mouse_frame)
1760 /*&& dpyinfo->mouse_face_mouse_frame*/)
1764 if (dpyinfo->mouse_face_mouse_frame)
1765 note_mouse_highlight (dpyinfo->mouse_face_mouse_frame,
1766 dpyinfo->mouse_face_mouse_x,
1767 dpyinfo->mouse_face_mouse_y);
1768 dpyinfo->mouse_face_deferred_gc = 0;
1777 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1778 /* --------------------------------------------------------------------------
1779 External (RIF): set frame mouse pointer type.
1780 -------------------------------------------------------------------------- */
1782 NSTRACE (ns_define_frame_cursor);
1783 if (FRAME_POINTER_TYPE (f) != cursor)
1785 EmacsView *view = FRAME_NS_VIEW (f);
1786 FRAME_POINTER_TYPE (f) = cursor;
1787 [[view window] invalidateCursorRectsForView: view];
1793 /* ==========================================================================
1797 ========================================================================== */
1801 ns_convert_key (unsigned code)
1802 /* --------------------------------------------------------------------------
1803 Internal call used by NSView-keyDown.
1804 -------------------------------------------------------------------------- */
1806 const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym)
1807 / sizeof (convert_ns_to_X_keysym[0]));
1809 /* An array would be faster, but less easy to read. */
1810 for (keysym = 0; keysym < last_keysym; keysym += 2)
1811 if (code == convert_ns_to_X_keysym[keysym])
1812 return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
1814 /* if decide to use keyCode and Carbon table, use this line:
1815 return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
1820 x_get_keysym_name (int keysym)
1821 /* --------------------------------------------------------------------------
1822 Called by keyboard.c. Not sure if the return val is important, except
1824 -------------------------------------------------------------------------- */
1826 static char value[16];
1827 NSTRACE (x_get_keysym_name);
1828 sprintf (value, "%d", keysym);
1834 /* ==========================================================================
1836 Block drawing operations
1838 ========================================================================== */
1842 ns_redraw_scroll_bars (struct frame *f)
1846 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
1847 NSTRACE (ns_judge_scroll_bars);
1848 for (i =[subviews count]-1; i >= 0; i--)
1850 view = [subviews objectAtIndex: i];
1851 if (![view isKindOfClass: [EmacsScroller class]]) continue;
1858 ns_clear_frame (struct frame *f)
1859 /* --------------------------------------------------------------------------
1860 External (hook): Erase the entire frame
1861 -------------------------------------------------------------------------- */
1863 NSView *view = FRAME_NS_VIEW (f);
1866 NSTRACE (ns_clear_frame);
1870 /* comes on initial frame because we have
1871 after-make-frame-functions = select-frame */
1872 if (!FRAME_DEFAULT_FACE (f))
1875 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
1877 output_cursor.hpos = output_cursor.vpos = 0;
1878 output_cursor.x = -1;
1883 ns_focus (f, &r, 1);
1884 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
1888 #ifdef NS_IMPL_COCOA
1889 [[view window] display]; /* redraw resize handle */
1892 /* as of 2006/11 or so this is now needed */
1893 ns_redraw_scroll_bars (f);
1899 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
1900 /* --------------------------------------------------------------------------
1901 External (RIF): Clear section of frame
1902 -------------------------------------------------------------------------- */
1904 NSRect r = NSMakeRect (x, y, width, height);
1905 NSView *view = FRAME_NS_VIEW (f);
1906 struct face *face = FRAME_DEFAULT_FACE (f);
1911 NSTRACE (ns_clear_frame_area);
1913 r = NSIntersectionRect (r, [view frame]);
1914 ns_focus (f, &r, 1);
1915 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
1917 #ifdef NS_IMPL_COCOA
1919 /* clip out the resize handle */
1920 NSWindow *window = [FRAME_NS_VIEW (f) window];
1922 = [view convertRect: ns_resize_handle_rect (window) fromView: nil];
1924 ir = NSIntersectionRect (r, ir);
1925 if (NSIsEmptyRect (ir))
1931 #ifdef NS_IMPL_COCOA
1935 NSRect r1 = r, r2 = r; /* upper and lower non-intersecting */
1936 r1.size.height -= ir.size.height;
1937 r2.origin.y += r1.size.height;
1938 r2.size.width -= ir.size.width;
1939 r2.size.height = ir.size.height;
1952 ns_scroll_run (struct window *w, struct run *run)
1953 /* --------------------------------------------------------------------------
1954 External (RIF): Insert or delete n lines at line vpos
1955 -------------------------------------------------------------------------- */
1957 struct frame *f = XFRAME (w->frame);
1958 int x, y, width, height, from_y, to_y, bottom_y;
1960 NSTRACE (ns_scroll_run);
1962 /* begin copy from other terms */
1963 /* Get frame-relative bounding box of the text display area of W,
1964 without mode lines. Include in this box the left and right
1966 window_box (w, -1, &x, &y, &width, &height);
1968 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
1969 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
1970 bottom_y = y + height;
1974 /* Scrolling up. Make sure we don't copy part of the mode
1975 line at the bottom. */
1976 if (from_y + run->height > bottom_y)
1977 height = bottom_y - from_y;
1979 height = run->height;
1983 /* Scolling down. Make sure we don't copy over the mode line.
1985 if (to_y + run->height > bottom_y)
1986 height = bottom_y - to_y;
1988 height = run->height;
1990 /* end copy from other terms */
2001 NSRect srcRect = NSMakeRect (x, from_y, width, height);
2002 NSRect dstRect = NSMakeRect (x, to_y, width, height);
2003 NSPoint dstOrigin = NSMakePoint (x, to_y);
2005 ns_focus (f, &dstRect, 1);
2006 NSCopyBits (0, srcRect , dstOrigin);
2015 ns_after_update_window_line (struct glyph_row *desired_row)
2016 /* --------------------------------------------------------------------------
2017 External (RIF): preparatory to fringe update after text was updated
2018 -------------------------------------------------------------------------- */
2020 struct window *w = updated_window;
2024 NSTRACE (ns_after_update_window_line);
2026 /* begin copy from other terms */
2029 if (!desired_row->mode_line_p && !w->pseudo_window_p)
2030 desired_row->redraw_fringe_bitmaps_p = 1;
2032 /* When a window has disappeared, make sure that no rest of
2033 full-width rows stays visible in the internal border.
2034 Under NS this is drawn inside the fringes. */
2035 if (windows_or_buffers_changed
2036 && (f = XFRAME (w->frame),
2037 width = FRAME_INTERNAL_BORDER_WIDTH (f),
2039 && (height = desired_row->visible_height,
2042 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2044 /* Internal border is drawn below the tool bar. */
2045 if (WINDOWP (f->tool_bar_window)
2046 && w == XWINDOW (f->tool_bar_window))
2048 /* end copy from other terms */
2051 if (!desired_row->full_width_p)
2053 int x1 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2054 + WINDOW_LEFT_FRINGE_WIDTH (w);
2055 int x2 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2056 + FRAME_PIXEL_WIDTH (f) - NS_SCROLL_BAR_WIDTH (f)
2057 - WINDOW_RIGHT_FRINGE_WIDTH (w)
2058 - FRAME_INTERNAL_BORDER_WIDTH (f);
2059 ns_clear_frame_area (f, x1, y, width, height);
2060 ns_clear_frame_area (f, x2, y, width, height);
2068 ns_shift_glyphs_for_insert (struct frame *f,
2069 int x, int y, int width, int height,
2071 /* --------------------------------------------------------------------------
2072 External (RIF): copy an area horizontally, don't worry about clearing src
2073 -------------------------------------------------------------------------- */
2075 NSRect srcRect = NSMakeRect (x, y, width, height);
2076 NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2077 NSPoint dstOrigin = dstRect.origin;
2079 NSTRACE (ns_shift_glyphs_for_insert);
2081 ns_focus (f, &dstRect, 1);
2082 NSCopyBits (0, srcRect, dstOrigin);
2088 /* ==========================================================================
2090 Character encoding and metrics
2092 ========================================================================== */
2096 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2097 /* --------------------------------------------------------------------------
2098 External (RIF); compute left/right overhang of whole string and set in s
2099 -------------------------------------------------------------------------- */
2101 struct face *face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2102 struct font *font = s->font; /*face->font; */
2106 struct font_metrics metrics;
2107 unsigned int codes[2];
2108 codes[0] = *(s->char2b);
2109 codes[1] = *(s->char2b + s->nchars - 1);
2111 font->driver->text_extents (font, codes, 2, &metrics);
2112 s->left_overhang = -metrics.lbearing;
2114 = metrics.rbearing > metrics.width
2115 ? metrics.rbearing - metrics.width : 0;
2119 s->left_overhang = 0;
2120 s->right_overhang = ((struct nsfont_info *)font)->ital ?
2121 FONT_HEIGHT (font) * 0.2 : 0;
2127 /* ==========================================================================
2129 Fringe and cursor drawing
2131 ========================================================================== */
2134 extern int max_used_fringe_bitmap;
2136 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2137 struct draw_fringe_bitmap_params *p)
2138 /* --------------------------------------------------------------------------
2139 External (RIF); fringe-related
2140 -------------------------------------------------------------------------- */
2142 struct frame *f = XFRAME (WINDOW_FRAME (w));
2143 struct face *face = p->face;
2145 static EmacsImage **bimgs = NULL;
2146 static int nBimgs = 0;
2147 /* NS-specific: move internal border inside fringe */
2148 int x = p->bx < 0 ? p->x : p->bx;
2149 int wd = p->bx < 0 ? p->wd : p->nx;
2150 BOOL fringeOnVeryLeft
2151 = x - WINDOW_LEFT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w)
2152 - FRAME_INTERNAL_BORDER_WIDTH (f) < 10;
2153 BOOL fringeOnVeryRight
2154 = FRAME_PIXEL_WIDTH (f) - x - wd - FRAME_INTERNAL_BORDER_WIDTH (f)
2155 - WINDOW_RIGHT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w) < 10;
2156 int xAdjust = FRAME_INTERNAL_BORDER_WIDTH (f) *
2157 (fringeOnVeryLeft ? -1 : (fringeOnVeryRight ? 1 : 0));
2159 /* grow bimgs if needed */
2160 if (nBimgs < max_used_fringe_bitmap)
2162 EmacsImage **newBimgs
2163 = xmalloc (max_used_fringe_bitmap * sizeof (EmacsImage *));
2164 bzero (newBimgs, max_used_fringe_bitmap * sizeof (EmacsImage *));
2168 bcopy (bimgs, newBimgs, nBimgs * sizeof (EmacsImage *));
2173 nBimgs = max_used_fringe_bitmap;
2176 /* Must clip because of partially visible lines. */
2177 rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
2180 /* Adjust position of "bottom aligned" bitmap on partially
2181 visible last row. */
2183 int oldVH = row->visible_height;
2184 row->visible_height = p->h;
2185 row->y -= rowY - p->y;
2186 ns_clip_to_row (w, row, -1, NO);
2188 row->visible_height = oldVH;
2191 ns_clip_to_row (w, row, -1, YES);
2193 if (p->bx >= 0 && !p->overlay_p)
2195 int yAdjust = rowY - FRAME_INTERNAL_BORDER_WIDTH (f) < 5 ?
2196 -FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2197 int yIncr = FRAME_PIXEL_HEIGHT (f) - (p->by+yAdjust + p->ny) < 5 ?
2198 FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2200 yIncr += FRAME_INTERNAL_BORDER_WIDTH (f);
2201 NSRect r = NSMakeRect (p->bx+xAdjust, p->by+yAdjust, p->nx, p->ny+yIncr);
2203 [ns_lookup_indexed_color(face->background, f) set];
2209 NSRect r = NSMakeRect (p->x+xAdjust, p->y, p->wd, p->h);
2210 NSPoint pt = r.origin;
2211 EmacsImage *img = bimgs[p->which - 1];
2215 unsigned short *bits = p->bits + p->dh;
2216 int len = 8 * p->h/8;
2218 unsigned char *cbits = xmalloc (len);
2220 for (i =0; i<len; i++)
2221 cbits[i] = ~(bits[i] & 0xff);
2222 img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2224 bimgs[p->which - 1] = img;
2229 /* Since we composite the bitmap instead of just blitting it, we need
2230 to erase the whole background. */
2231 [ns_lookup_indexed_color(face->background, f) set];
2234 [img setXBMColor: ns_lookup_indexed_color(face->foreground, f)];
2235 [img compositeToPoint: pt operation: NSCompositeSourceOver];
2242 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2243 int x, int y, int cursor_type, int cursor_width,
2244 int on_p, int active_p)
2245 /* --------------------------------------------------------------------------
2246 External call (RIF): draw cursor
2247 (modeled after x_draw_window_cursor
2248 FIXME: cursor_width is effectively bogus -- it sometimes gets set
2249 in xdisp.c set_frame_cursor_types, sometimes left uninitialized;
2250 DON'T USE IT (no other terms do)
2251 -------------------------------------------------------------------------- */
2255 struct frame *f = WINDOW_XFRAME (w);
2256 struct glyph *phys_cursor_glyph;
2259 NSTRACE (dumpcursor);
2260 //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);
2265 w->phys_cursor_type = cursor_type;
2266 w->phys_cursor_on_p = on_p;
2268 if (cursor_type == NO_CURSOR)
2270 w->phys_cursor_width = 0;
2274 if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2276 if (glyph_row->exact_window_width_line_p
2277 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2279 glyph_row->cursor_in_fringe_p = 1;
2280 draw_fringe_bitmap (w, glyph_row, 0);
2285 get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2287 r.origin.x = fx, r.origin.y = fy;
2289 r.size.width = w->phys_cursor_width;
2291 /* FIXME: if we overwrite the internal border area, it does not get erased;
2292 fix by truncating cursor, but better would be to erase properly */
2293 overspill = r.origin.x + r.size.width -
2294 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, WINDOW_BOX_RIGHT_EDGE_X (w)
2295 - WINDOW_TOTAL_FRINGE_WIDTH (w) - FRAME_INTERNAL_BORDER_WIDTH (f));
2297 r.size.width -= overspill;
2299 /* TODO: only needed in rare cases with last-resort font in HELLO..
2300 should we do this more efficiently? */
2301 ns_clip_to_row (w, glyph_row, -1, NO); /* do ns_focus(f, &r, 1); if remove */
2302 [FRAME_CURSOR_COLOR (f) set];
2304 #ifdef NS_IMPL_COCOA
2305 /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2306 atomic. Cleaner ways of doing this should be investigated.
2307 One way would be to set a global variable DRAWING_CURSOR
2308 when making the call to draw_phys..(), don't focus in that
2309 case, then move the ns_unfocus() here after that call. */
2310 NSDisableScreenUpdates ();
2313 switch (cursor_type)
2317 case FILLED_BOX_CURSOR:
2320 case HOLLOW_BOX_CURSOR:
2322 [FRAME_BACKGROUND_COLOR (f) set];
2323 NSRectFill (NSInsetRect (r, 1, 1));
2324 [FRAME_CURSOR_COLOR (f) set];
2328 s.origin.y += lrint (0.75 * s.size.height);
2329 s.size.height = lrint (s.size.height * 0.25);
2334 s.size.width = min (cursor_width, 2); //FIXME(see above)
2340 /* draw the character under the cursor */
2341 if (cursor_type != NO_CURSOR)
2342 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2344 #ifdef NS_IMPL_COCOA
2345 NSEnableScreenUpdates ();
2352 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2353 /* --------------------------------------------------------------------------
2354 External (RIF): Draw a vertical line.
2355 -------------------------------------------------------------------------- */
2357 struct frame *f = XFRAME (WINDOW_FRAME (w));
2359 NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2361 NSTRACE (ns_draw_vertical_window_border);
2363 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2365 [ns_lookup_indexed_color(face->foreground, f) set];
2367 ns_focus (f, &r, 1);
2374 show_hourglass (struct atimer *timer)
2376 if (hourglass_shown_p)
2381 /* TODO: add NSProgressIndicator to selected frame (see macfns.c) */
2383 hourglass_shown_p = 1;
2391 if (!hourglass_shown_p)
2396 /* TODO: remove NSProgressIndicator from all frames */
2398 hourglass_shown_p = 0;
2404 /* ==========================================================================
2406 Glyph drawing operations
2408 ========================================================================== */
2411 static inline NSRect
2412 ns_fix_rect_ibw (NSRect r, int fibw, int frame_pixel_width)
2413 /* --------------------------------------------------------------------------
2414 Under NS we draw internal borders inside fringes, and want full-width
2415 rendering to go all the way to edge. This function makes that correction.
2416 -------------------------------------------------------------------------- */
2418 if (r.origin.y <= fibw+1)
2420 r.size.height += r.origin.y;
2423 if (r.origin.x <= fibw+1)
2425 r.size.width += r.origin.x;
2428 if (frame_pixel_width - (r.origin.x+r.size.width) <= fibw+1)
2429 r.size.width += fibw;
2436 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2437 /* --------------------------------------------------------------------------
2438 Wrapper utility to account for internal border width on full-width lines,
2439 and allow top full-width rows to hit the frame top. nr should be pointer
2440 to two successive NSRects. Number of rects actually used is returned.
2441 -------------------------------------------------------------------------- */
2443 int n = get_glyph_string_clip_rects (s, nr, 2);
2444 if (s->row->full_width_p)
2446 *nr = ns_fix_rect_ibw (*nr, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2447 FRAME_PIXEL_WIDTH (s->f));
2449 *nr = ns_fix_rect_ibw (*(nr+1), FRAME_INTERNAL_BORDER_WIDTH (s->f),
2450 FRAME_PIXEL_WIDTH (s->f));
2457 ns_draw_box (NSRect r, float thickness, NSColor *col, char left_p, char right_p)
2458 /* --------------------------------------------------------------------------
2459 Draw an unfilled rect inside r, optionally leaving left and/or right open.
2460 Note we can't just use an NSDrawRect command, because of the possibility
2461 of some sides not being drawn, and because the rect will be filled.
2462 -------------------------------------------------------------------------- */
2468 s.size.height = thickness;
2470 s.origin.y += r.size.height - thickness;
2473 s.size.height = r.size.height;
2474 s.origin.y = r.origin.y;
2476 /* left, right (optional) */
2477 s.size.width = thickness;
2482 s.origin.x += r.size.width - thickness;
2489 ns_draw_relief (NSRect r, int thickness, char raised_p,
2490 char top_p, char bottom_p, char left_p, char right_p,
2491 struct glyph_string *s)
2492 /* --------------------------------------------------------------------------
2493 Draw a relief rect inside r, optionally leaving some sides open.
2494 Note we can't just use an NSDrawBezel command, because of the possibility
2495 of some sides not being drawn, and because the rect will be filled.
2496 -------------------------------------------------------------------------- */
2498 static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2499 NSColor *newBaseCol = nil;
2502 NSTRACE (ns_draw_relief);
2506 if (s->face->use_box_color_for_shadows_p)
2508 newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2510 /* else if (s->first_glyph->type == IMAGE_GLYPH
2512 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2514 newBaseCol = IMAGE_BACKGROUND (s->img, s->f, 0);
2518 newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2521 if (newBaseCol == nil)
2522 newBaseCol = [NSColor grayColor];
2524 if (newBaseCol != baseCol) /* TODO: better check */
2527 baseCol = [newBaseCol retain];
2529 lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2531 darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2534 [(raised_p ? lightCol : darkCol) set];
2536 /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2539 sr.size.height = thickness;
2540 if (top_p) NSRectFill (sr);
2543 sr.size.height = r.size.height;
2544 sr.size.width = thickness;
2545 if (left_p) NSRectFill (sr);
2547 [(raised_p ? darkCol : lightCol) set];
2550 sr.size.width = r.size.width;
2551 sr.size.height = thickness;
2552 sr.origin.y += r.size.height - thickness;
2553 if (bottom_p) NSRectFill (sr);
2556 sr.size.height = r.size.height;
2557 sr.origin.y = r.origin.y;
2558 sr.size.width = thickness;
2559 sr.origin.x += r.size.width - thickness;
2560 if (right_p) NSRectFill (sr);
2565 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2566 /* --------------------------------------------------------------------------
2567 Function modeled after x_draw_glyph_string_box ().
2568 Sets up parameters for drawing.
2569 -------------------------------------------------------------------------- */
2571 int right_x, last_x;
2572 char left_p, right_p;
2573 struct glyph *last_glyph;
2578 if (s->hl == DRAW_MOUSE_FACE)
2581 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2583 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2588 thickness = face->box_line_width;
2590 NSTRACE (ns_dumpglyphs_box_or_relief);
2592 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2593 ? WINDOW_RIGHT_EDGE_X (s->w)
2594 : window_box_right (s->w, s->area));
2595 last_glyph = (s->cmp || s->img
2596 ? s->first_glyph : s->first_glyph + s->nchars-1);
2598 right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2599 ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2601 left_p = (s->first_glyph->left_box_line_p
2602 || (s->hl == DRAW_MOUSE_FACE
2603 && (s->prev == NULL || s->prev->hl != s->hl)));
2604 right_p = (last_glyph->right_box_line_p
2605 || (s->hl == DRAW_MOUSE_FACE
2606 && (s->next == NULL || s->next->hl != s->hl)));
2608 r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2610 /* expand full-width row over internal borders */
2611 if (s->row->full_width_p)
2612 r = ns_fix_rect_ibw (r, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2613 FRAME_PIXEL_WIDTH (s->f));
2615 /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
2616 if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
2618 ns_draw_box (r, abs (thickness),
2619 ns_lookup_indexed_color (face->box_color, s->f),
2624 ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2625 1, 1, left_p, right_p, s);
2631 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2632 /* --------------------------------------------------------------------------
2633 Modeled after x_draw_glyph_string_background, which draws BG in
2634 certain cases. Others are left to the text rendering routine.
2635 -------------------------------------------------------------------------- */
2637 NSTRACE (ns_maybe_dumpglyphs_background);
2639 if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2641 int box_line_width = max (s->face->box_line_width, 0);
2642 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2643 || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2646 if (s->hl == DRAW_MOUSE_FACE)
2649 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2651 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2654 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2656 [(NS_FACE_BACKGROUND (face) != 0
2657 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2658 : FRAME_BACKGROUND_COLOR (s->f)) set];
2661 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (s->f);
2662 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2665 if (s->hl != DRAW_CURSOR)
2667 NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2668 s->background_width,
2669 s->height-2*box_line_width);
2671 /* expand full-width row over internal borders */
2672 if (s->row->full_width_p)
2674 int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2675 if (r.origin.y <= fibw+1 + box_line_width)
2677 r.size.height += r.origin.y;
2680 if (r.origin.x <= fibw+1)
2682 r.size.width += 2*r.origin.x;
2685 if (FRAME_PIXEL_WIDTH (s->f) - (r.origin.x + r.size.width)
2687 r.size.width += fibw;
2693 s->background_filled_p = 1;
2700 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2701 /* --------------------------------------------------------------------------
2702 Renders an image and associated borders.
2703 -------------------------------------------------------------------------- */
2705 EmacsImage *img = s->img->pixmap;
2706 int box_line_vwidth = max (s->face->box_line_width, 0);
2707 int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2708 int bg_x, bg_y, bg_height;
2714 NSTRACE (ns_dumpglyphs_image);
2716 if (s->face->box != FACE_NO_BOX
2717 && s->first_glyph->left_box_line_p && s->slice.x == 0)
2718 x += abs (s->face->box_line_width);
2721 bg_y = s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2722 bg_height = s->height;
2723 /* other terms have this, but was causing problems w/tabbar mode */
2724 /* - 2 * box_line_vwidth; */
2726 if (s->slice.x == 0) x += s->img->hmargin;
2727 if (s->slice.y == 0) y += s->img->vmargin;
2729 /* Draw BG: if we need larger area than image itself cleared, do that,
2730 otherwise, since we composite the image under NS (instead of mucking
2731 with its background color), we must clear just the image area. */
2732 if (s->hl == DRAW_MOUSE_FACE)
2735 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2737 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2740 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2742 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
2744 if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
2745 || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
2747 br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
2748 s->background_filled_p = 1;
2752 br = NSMakeRect (x, y, s->slice.width, s->slice.height);
2755 /* expand full-width row over internal borders */
2756 if (s->row->full_width_p)
2758 int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2759 if (br.origin.y <= fibw+1 + box_line_vwidth)
2761 br.size.height += br.origin.y;
2764 if (br.origin.x <= fibw+1 + box_line_vwidth)
2766 br.size.width += br.origin.x;
2769 if (FRAME_PIXEL_WIDTH (s->f) - (br.origin.x + br.size.width) <= fibw+1)
2770 br.size.width += fibw;
2775 /* Draw the image.. do we need to draw placeholder if img ==nil? */
2777 [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
2778 operation: NSCompositeSourceOver];
2780 /* Draw relief, if requested */
2781 if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
2783 if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
2785 th = tool_bar_button_relief >= 0 ?
2786 tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2787 raised_p = (s->hl == DRAW_IMAGE_RAISED);
2791 th = abs (s->img->relief);
2792 raised_p = (s->img->relief > 0);
2795 r.origin.x = x - th;
2796 r.origin.y = y - th;
2797 r.size.width = s->slice.width + 2*th-1;
2798 r.size.height = s->slice.height + 2*th-1;
2799 ns_draw_relief (r, th, raised_p,
2801 s->slice.y + s->slice.height == s->img->height,
2803 s->slice.x + s->slice.width == s->img->width, s);
2809 ns_dumpglyphs_stretch (struct glyph_string *s)
2815 if (!s->background_filled_p)
2817 n = ns_get_glyph_string_clip_rect (s, r);
2818 *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
2822 if (!s->row->full_width_p)
2824 /* truncate to avoid overwriting fringe and/or scrollbar */
2825 int overrun = max (0, (s->x + s->background_width)
2826 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
2827 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
2828 r[i].size.width -= overrun;
2830 /* XXX: Try to work between problem where a stretch glyph on
2831 a partially-visible bottom row will clear part of the
2832 modeline, and another where list-buffers headers and similar
2833 rows erroneously have visible_height set to 0. Not sure
2834 where this is coming from as other terms seem not to show. */
2835 r[i].size.height = min (s->height, s->row->visible_height);
2838 /* expand full-width rows over internal borders */
2841 r[i] = ns_fix_rect_ibw (r[i], FRAME_INTERNAL_BORDER_WIDTH (s->f),
2842 FRAME_PIXEL_WIDTH (s->f));
2845 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
2846 overwriting cursor (usually when cursor on a tab) */
2847 if (s->hl == DRAW_CURSOR)
2849 r[i].origin.x += s->width;
2850 r[i].size.width -= s->width;
2854 ns_focus (s->f, r, n);
2856 if (s->hl == DRAW_MOUSE_FACE)
2859 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2861 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2864 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2866 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
2871 s->background_filled_p = 1;
2877 ns_draw_glyph_string (struct glyph_string *s)
2878 /* --------------------------------------------------------------------------
2879 External (RIF): Main draw-text call.
2880 -------------------------------------------------------------------------- */
2882 /* TODO (optimize): focus for box and contents draw */
2885 char box_drawn_p = 0;
2887 NSTRACE (ns_draw_glyph_string);
2889 if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
2892 struct glyph_string *next;
2894 for (width = 0, next = s->next;
2895 next && width < s->right_overhang;
2896 width += next->width, next = next->next)
2897 if (next->first_glyph->type != IMAGE_GLYPH)
2899 if (next->first_glyph->type != STRETCH_GLYPH)
2901 n = ns_get_glyph_string_clip_rect (s->next, r);
2902 ns_focus (s->f, r, n);
2903 ns_maybe_dumpglyphs_background (s->next, 1);
2908 ns_dumpglyphs_stretch (s->next);
2910 next->num_clips = 0;
2914 if (!s->for_overlaps && s->face->box != FACE_NO_BOX
2915 && (s->first_glyph->type == CHAR_GLYPH
2916 || s->first_glyph->type == COMPOSITE_GLYPH))
2918 n = ns_get_glyph_string_clip_rect (s, r);
2919 ns_focus (s->f, r, n);
2920 ns_maybe_dumpglyphs_background (s, 1);
2921 ns_dumpglyphs_box_or_relief (s);
2926 switch (s->first_glyph->type)
2930 n = ns_get_glyph_string_clip_rect (s, r);
2931 ns_focus (s->f, r, n);
2932 ns_dumpglyphs_image (s, r[0]);
2937 ns_dumpglyphs_stretch (s);
2941 case COMPOSITE_GLYPH:
2942 n = ns_get_glyph_string_clip_rect (s, r);
2943 ns_focus (s->f, r, n);
2945 if (s->for_overlaps || (s->cmp_from > 0
2946 && ! s->first_glyph->u.cmp.automatic))
2947 s->background_filled_p = 1;
2949 ns_maybe_dumpglyphs_background
2950 (s, s->first_glyph->type == COMPOSITE_GLYPH);
2952 ns_tmp_flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
2953 (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
2954 (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
2955 NS_DUMPGLYPH_NORMAL));
2956 ns_tmp_font = (struct nsfont_info *)s->face->font;
2957 if (ns_tmp_font == NULL)
2958 ns_tmp_font = (struct nsfont_info *)FRAME_FONT (s->f);
2960 ns_tmp_font->font.driver->draw
2961 (s, 0, s->nchars, s->x, s->y,
2962 (ns_tmp_flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
2963 || ns_tmp_flags == NS_DUMPGLYPH_MOUSEFACE);
2972 /* Draw box if not done already. */
2973 if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
2975 n = ns_get_glyph_string_clip_rect (s, r);
2976 ns_focus (s->f, r, n);
2977 ns_dumpglyphs_box_or_relief (s);
2986 /* ==========================================================================
2990 ========================================================================== */
2994 ns_send_appdefined (int value)
2995 /* --------------------------------------------------------------------------
2996 Internal: post an appdefined event which EmacsApp-sendEvent will
2997 recognize and take as a command to halt the event loop.
2998 -------------------------------------------------------------------------- */
3000 /*NSTRACE (ns_send_appdefined); */
3002 /* Only post this event if we haven't already posted one. This will end
3003 the [NXApp run] main loop after having processed all events queued at
3005 if (send_appdefined)
3009 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
3010 send_appdefined = NO;
3012 /* Don't need wakeup timer any more */
3015 [timed_entry invalidate];
3016 [timed_entry release];
3020 /* Ditto for file descriptor poller */
3023 [fd_entry invalidate];
3028 nxev = [NSEvent otherEventWithType: NSApplicationDefined
3029 location: NSMakePoint (0, 0)
3032 windowNumber: [[NSApp mainWindow] windowNumber]
3033 context: [NSApp context]
3038 /* Post an application defined event on the event queue. When this is
3039 received the [NXApp run] will return, thus having processed all
3040 events which are currently queued. */
3041 [NSApp postEvent: nxev atStart: NO];
3047 ns_read_socket (struct terminal *terminal, int expected,
3048 struct input_event *hold_quit)
3049 /* --------------------------------------------------------------------------
3050 External (hook): Post an event to ourself and keep reading events until
3051 we read it back again. In effect process all events which were waiting.
3052 From 21+ we have to manage the event buffer ourselves.
3053 -------------------------------------------------------------------------- */
3055 struct input_event ev;
3058 /* NSTRACE (ns_read_socket); */
3060 if (interrupt_input_blocked)
3062 interrupt_input_pending = 1;
3064 pending_signals = 1;
3069 interrupt_input_pending = 0;
3071 pending_signals = pending_atimers;
3075 n_emacs_events_pending = 0;
3078 q_event_ptr = hold_quit;
3080 /* we manage autorelease pools by allocate/reallocate each time around
3081 the loop; strict nesting is occasionally violated but seems not to
3082 matter.. earlier methods using full nesting caused major memory leaks */
3083 [outerpool release];
3084 outerpool = [[NSAutoreleasePool alloc] init];
3086 /* If have pending open-file requests, attend to the next one of those. */
3087 if (ns_pending_files && [ns_pending_files count] != 0
3088 && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3090 [ns_pending_files removeObjectAtIndex: 0];
3092 /* Deal with pending service requests. */
3093 else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3095 NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3096 withArg: [ns_pending_service_args objectAtIndex: 0]])
3098 [ns_pending_service_names removeObjectAtIndex: 0];
3099 [ns_pending_service_args removeObjectAtIndex: 0];
3103 /* Run and wait for events. We must always send one NX_APPDEFINED event
3104 to ourself, otherwise [NXApp run] will never exit. */
3105 send_appdefined = YES;
3107 /* If called via ns_select, this is called once with expected=1,
3108 because we expect either the timeout or file descriptor activity.
3109 In this case the first event through will either be real input or
3110 one of these. read_avail_input() then calls once more with expected=0
3111 and in that case we need to return quickly if there is nothing.
3112 If we're being called outside of that, it's also OK to return quickly
3113 after one iteration through the event loop, since other terms do
3114 this and emacs expects it. */
3115 if (!(inNsSelect && expected))
3117 /* Post an application defined event on the event queue. When this is
3118 received the [NXApp run] will return, thus having processed all
3119 events which are currently queued, if any. */
3120 ns_send_appdefined (-1);
3126 nevents = n_emacs_events_pending;
3127 n_emacs_events_pending = 0;
3128 emacs_event = q_event_ptr = NULL;
3136 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3137 fd_set *exceptfds, struct timeval *timeout)
3138 /* --------------------------------------------------------------------------
3139 Replacement for select, checking for events
3140 -------------------------------------------------------------------------- */
3145 /* NSTRACE (ns_select); */
3147 if (NSApp == nil || inNsSelect == 1 /* || ([NSApp isActive] == NO &&
3148 [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
3149 inMode:NSDefaultRunLoopMode dequeue:NO] == nil) */)
3150 return select (nfds, readfds, writefds, exceptfds, timeout);
3152 /* Save file descriptor set, which gets overwritten in calls to select ()
3153 Note, this is called from process.c, and only readfds is ever set */
3156 memcpy (&select_readfds, readfds, sizeof (fd_set));
3162 /* Try an initial select for pending data on input files */
3163 select_timeout.tv_sec = select_timeout.tv_usec = 0;
3164 result = select (nfds, readfds, writefds, exceptfds, &select_timeout);
3168 /* if (!timeout || timed_entry || fd_entry)
3169 fprintf (stderr, "assertion failed: timeout null or timed_entry/fd_entry non-null in ns_select\n"); */
3171 /* set a timeout and run the main AppKit event loop while continuing
3172 to monitor the files */
3173 time = ((double) timeout->tv_sec) + ((double) timeout->tv_usec)/1000000.0;
3174 timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3176 selector: @selector (timeout_handler:)
3178 repeats: YES] /* for safe removal */
3181 /* set a periodic task to try the select () again */
3182 fd_entry = [[NSTimer scheduledTimerWithTimeInterval: 0.1
3184 selector: @selector (fd_handler:)
3189 /* Let Application dispatch events until it receives an event of the type
3190 NX_APPDEFINED, which should only be sent by timeout_handler.
3191 We tell read_avail_input() that input is "expected" because we do expect
3192 either the timeout or fd handler to fire, and if they don't, the original
3193 call from process.c that got us here expects us to wait until some input
3197 ev = last_appdefined_event;
3203 if ([ev type] != NSApplicationDefined)
3207 last_appdefined_event = 0;
3211 /* The NX_APPDEFINED event we received was a timeout. */
3216 /* The NX_APPDEFINED event we received was the result of
3217 at least one real input event arriving. */
3223 /* Received back from select () in fd_handler; copy the results */
3225 memcpy (readfds, &select_readfds, sizeof (fd_set));
3229 /* never reached, shut compiler up */
3235 /* ==========================================================================
3239 ========================================================================== */
3243 ns_set_vertical_scroll_bar (struct window *window,
3244 int portion, int whole, int position)
3245 /* --------------------------------------------------------------------------
3246 External (hook): Update or add scrollbar
3247 -------------------------------------------------------------------------- */
3251 struct frame *f = XFRAME (WINDOW_FRAME (window));
3252 EmacsView *view = FRAME_NS_VIEW (f);
3253 int window_y, window_height;
3254 BOOL barOnVeryLeft, barOnVeryRight;
3255 int top, left, height, width, sb_width, sb_left;
3257 static int count = 0;
3259 /* optimization; display engine sends WAY too many of these.. */
3260 if (!NILP (window->vertical_scroll_bar))
3262 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3263 if ([bar checkSamePosition: position portion: portion whole: whole])
3265 if (view->scrollbarsNeedingUpdate == 0)
3267 if (!windows_or_buffers_changed)
3271 view->scrollbarsNeedingUpdate--;
3275 NSTRACE (ns_set_vertical_scroll_bar);
3277 /* Get dimensions. */
3278 window_box (window, -1, 0, &window_y, 0, &window_height);
3280 height = window_height;
3281 width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3282 left = WINDOW_SCROLL_BAR_AREA_X (window);
3284 if (top < 5) /* top scrollbar adjustment */
3286 top -= FRAME_INTERNAL_BORDER_WIDTH (f);
3287 height += FRAME_INTERNAL_BORDER_WIDTH (f);
3290 /* allow for displaying a skinnier scrollbar than char area allotted */
3291 sb_width = (WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) > 0) ?
3292 WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) : width;
3294 barOnVeryLeft = left < 5;
3295 barOnVeryRight = FRAME_PIXEL_WIDTH (f) - left - width < 5;
3296 sb_left = left + FRAME_INTERNAL_BORDER_WIDTH (f)
3297 * (barOnVeryLeft ? -1 : (barOnVeryRight ? 1 : 0));
3299 r = NSMakeRect (sb_left, top, sb_width, height);
3300 /* the parent view is flipped, so we need to flip y value */
3302 r.origin.y = (v.size.height - r.size.height - r.origin.y);
3304 XSETWINDOW (win, window);
3307 /* we want at least 5 lines to display a scrollbar */
3308 if (WINDOW_TOTAL_LINES (window) < 5)
3310 if (!NILP (window->vertical_scroll_bar))
3312 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3313 [bar removeFromSuperview];
3314 window->vertical_scroll_bar = Qnil;
3316 ns_clear_frame_area (f, sb_left, top, width, height);
3321 if (NILP (window->vertical_scroll_bar))
3323 ns_clear_frame_area (f, sb_left, top, width, height);
3324 bar = [[EmacsScroller alloc] initFrame: r window: win];
3325 window->vertical_scroll_bar = make_save_value (bar, 0);
3330 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3331 oldRect = [bar frame];
3332 r.size.width = oldRect.size.width;
3333 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3335 if (oldRect.origin.x != r.origin.x)
3336 ns_clear_frame_area (f, sb_left, top, width, height);
3341 [bar setPosition: position portion: portion whole: whole];
3347 ns_condemn_scroll_bars (struct frame *f)
3348 /* --------------------------------------------------------------------------
3349 External (hook): arrange for all frame's scrollbars to be removed
3350 at next call to judge_scroll_bars, except for those redeemed.
3351 -------------------------------------------------------------------------- */
3355 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3357 NSTRACE (ns_condemn_scroll_bars);
3359 for (i =[subviews count]-1; i >= 0; i--)
3361 view = [subviews objectAtIndex: i];
3362 if ([view isKindOfClass: [EmacsScroller class]])
3369 ns_redeem_scroll_bar (struct window *window)
3370 /* --------------------------------------------------------------------------
3371 External (hook): arrange to spare this window's scrollbar
3372 at next call to judge_scroll_bars.
3373 -------------------------------------------------------------------------- */
3376 NSTRACE (ns_redeem_scroll_bar);
3377 if (!NILP (window->vertical_scroll_bar))
3379 bar =XNS_SCROLL_BAR (window->vertical_scroll_bar);
3386 ns_judge_scroll_bars (struct frame *f)
3387 /* --------------------------------------------------------------------------
3388 External (hook): destroy all scrollbars on frame that weren't
3389 redeemed after call to condemn_scroll_bars.
3390 -------------------------------------------------------------------------- */
3394 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3395 NSTRACE (ns_judge_scroll_bars);
3396 for (i =[subviews count]-1; i >= 0; i--)
3398 view = [subviews objectAtIndex: i];
3399 if (![view isKindOfClass: [EmacsScroller class]]) continue;
3406 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
3408 /* XXX irrelevant under NS */
3413 /* ==========================================================================
3417 ========================================================================== */
3420 x_display_pixel_height (dpyinfo)
3421 struct ns_display_info *dpyinfo;
3423 NSScreen *screen = [NSScreen mainScreen];
3424 return [screen frame].size.height;
3428 x_display_pixel_width (dpyinfo)
3429 struct ns_display_info *dpyinfo;
3431 NSScreen *screen = [NSScreen mainScreen];
3432 return [screen frame].size.width;
3436 static Lisp_Object ns_string_to_lispmod (const char *s)
3437 /* --------------------------------------------------------------------------
3438 Convert modifier name to lisp symbol
3439 -------------------------------------------------------------------------- */
3441 if (!strncmp (SDATA (SYMBOL_NAME (Qmeta)), s, 10))
3443 else if (!strncmp (SDATA (SYMBOL_NAME (Qsuper)), s, 10))
3445 else if (!strncmp (SDATA (SYMBOL_NAME (Qcontrol)), s, 10))
3447 else if (!strncmp (SDATA (SYMBOL_NAME (Qalt)), s, 10))
3449 else if (!strncmp (SDATA (SYMBOL_NAME (Qhyper)), s, 10))
3451 else if (!strncmp (SDATA (SYMBOL_NAME (Qnone)), s, 10))
3458 static Lisp_Object ns_mod_to_lisp (int m)
3459 /* --------------------------------------------------------------------------
3460 Convert modifier code (see lisp.h) to lisp symbol
3461 -------------------------------------------------------------------------- */
3465 else if (m == CHAR_SUPER)
3467 else if (m == CHAR_CTL)
3469 else if (m == CHAR_ALT)
3471 else if (m == CHAR_HYPER)
3473 else /* if (m == 0) */
3479 ns_set_default_prefs ()
3480 /* --------------------------------------------------------------------------
3481 Initialize preference variables to defaults
3482 -------------------------------------------------------------------------- */
3484 ns_alternate_modifier = Qmeta;
3485 ns_command_modifier = Qsuper;
3486 ns_control_modifier = Qcontrol;
3487 ns_function_modifier = Qnone;
3488 ns_antialias_text = Qt;
3489 ns_antialias_threshold = 10.0; /* not exposed to lisp side */
3490 ns_confirm_quit = Qnil;
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 bzero (dpyinfo, 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 /* Read various user defaults. */
3757 ns_set_default_prefs ();
3758 if (!inhibit_x_resources)
3760 ns_default ("GSFontAntiAlias", &ns_antialias_text,
3763 /* this is a standard variable */
3764 ns_default ("AppleAntiAliasingThreshold", &tmp,
3765 make_float (10.0), make_float (6.0), YES, NO);
3766 ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
3769 ns_selection_color = [[NSUserDefaults standardUserDefaults]
3770 stringForKey: @"AppleHighlightColor"];
3771 if (ns_selection_color == nil)
3772 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
3775 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
3779 Lisp_Object color_file, color_map, color;
3784 color_file = Fexpand_file_name (build_string ("rgb.txt"),
3785 Fsymbol_value (intern ("data-directory")));
3786 if (NILP (Ffile_readable_p (color_file)))
3787 fatal ("Could not find %s.\n", SDATA (color_file));
3789 color_map = Fx_load_color_file (color_file);
3790 if (NILP (color_map))
3791 fatal ("Could not read %s.\n", SDATA (color_file));
3793 cl = [[NSColorList alloc] initWithName: @"Emacs"];
3794 for ( ; CONSP (color_map); color_map = XCDR (color_map))
3796 color = XCAR (color_map);
3797 name = SDATA (XCAR (color));
3798 c = XINT (XCDR (color));
3800 [NSColor colorWithCalibratedRed: RED_FROM_ULONG (c) / 255.0
3801 green: GREEN_FROM_ULONG (c) / 255.0
3802 blue: BLUE_FROM_ULONG (c) / 255.0
3804 forKey: [NSString stringWithUTF8String: name]];
3806 [cl writeToFile: nil];
3812 #ifdef NS_IMPL_GNUSTEP
3813 strncpy (c, gnustep_base_version, sizeof (c));
3815 /*PSnextrelease (128, c); */
3816 snprintf (c, sizeof (c), "%g", NSAppKitVersionNumber);
3818 Vwindow_system_version = build_string (c);
3821 delete_keyboard_wait_descriptor (0);
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 /* [svcsMenu setSupercell: item]; */
3852 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
3853 [appMenu insertItemWithTitle: @"Hide Emacs"
3854 action: @selector (hide:)
3857 item = [appMenu insertItemWithTitle: @"Hide Others"
3858 action: @selector (hideOtherApplications:)
3861 [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
3862 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
3863 [appMenu insertItemWithTitle: @"Quit Emacs"
3864 action: @selector (terminate:)
3868 item = [mainMenu insertItemWithTitle: @"Emacs"
3869 action: @selector (menuDown:)
3872 [mainMenu setSubmenu: appMenu forItem: item];
3873 [dockMenu insertItemWithTitle: @"New Frame"
3874 action: @selector (newFrame:)
3878 [NSApp setMainMenu: mainMenu];
3879 [NSApp setAppleMenu: appMenu];
3880 [NSApp setServicesMenu: svcsMenu];
3881 /* Needed at least on Cocoa, to get dock menu to show windows */
3882 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
3884 #endif /* MAC OS X menu setup */
3892 extern Lisp_Object Vauto_save_list_file_name;
3894 ns_term_shutdown (int sig)
3896 /* code not reached in emacs.c after this is called by shut_down_emacs: */
3897 if (STRINGP (Vauto_save_list_file_name))
3898 unlink (SDATA (Vauto_save_list_file_name));
3900 if (sig == 0 || sig == SIGTERM)
3902 [NSApp terminate: NSApp];
3904 else // force a stack trace to happen
3911 /* ==========================================================================
3913 EmacsApp implementation
3915 ========================================================================== */
3918 @implementation EmacsApp
3920 - (void)logNotification: (NSNotification *)notification
3922 const char *name = [[notification name] UTF8String];
3923 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
3924 && !strstr (name, "WindowNumber"))
3925 NSLog (@"notification: '%@'", [notification name]);
3929 - (void)sendEvent: (NSEvent *)theEvent
3930 /* --------------------------------------------------------------------------
3931 Called when NSApp is running for each event received. Used to stop
3932 the loop when we choose, since there's no way to just run one iteration.
3933 -------------------------------------------------------------------------- */
3935 int type = [theEvent type];
3936 NSWindow *window = [theEvent window];
3937 /* NSTRACE (sendEvent); */
3938 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
3940 if (type == NSCursorUpdate && window == nil)
3942 fprintf (stderr, "Dropping external cursor update event.\n");
3946 #ifdef NS_IMPL_COCOA
3947 /* pass mouse down in resize handle and subsequent drags directly to
3948 EmacsWindow so we can generate continuous redisplays */
3951 if (type == NSLeftMouseDragged)
3953 [window mouseDragged: theEvent];
3956 else if (type == NSLeftMouseUp)
3958 [window mouseUp: theEvent];
3962 else if (type == NSLeftMouseDown)
3964 NSRect r = ns_resize_handle_rect (window);
3965 if (NSPointInRect ([theEvent locationInWindow], r))
3968 [window mouseDown: theEvent];
3974 if (type == NSApplicationDefined)
3976 /* Events posted by ns_send_appdefined interrupt the run loop here.
3977 But, if a modal window is up, an appdefined can still come through,
3978 (e.g., from a makeKeyWindow event) but stopping self also stops the
3979 modal loop. Just defer it until later. */
3980 if ([NSApp modalWindow] == nil)
3982 last_appdefined_event = theEvent;
3987 send_appdefined = YES;
3991 [super sendEvent: theEvent];
3995 - (void)showPreferencesWindow: (id)sender
3997 struct frame *emacsframe = SELECTED_FRAME ();
3998 NSEvent *theEvent = [NSApp currentEvent];
4002 emacs_event->kind = NS_NONKEY_EVENT;
4003 emacs_event->code = KEY_NS_SHOW_PREFS;
4004 emacs_event->modifiers = 0;
4005 EV_TRAILER (theEvent);
4009 - (void)newFrame: (id)sender
4011 struct frame *emacsframe = SELECTED_FRAME ();
4012 NSEvent *theEvent = [NSApp currentEvent];
4016 emacs_event->kind = NS_NONKEY_EVENT;
4017 emacs_event->code = KEY_NS_NEW_FRAME;
4018 emacs_event->modifiers = 0;
4019 EV_TRAILER (theEvent);
4023 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4024 - (BOOL) openFile: (NSString *)fileName
4026 struct frame *emacsframe = SELECTED_FRAME ();
4027 NSEvent *theEvent = [NSApp currentEvent];
4032 emacs_event->kind = NS_NONKEY_EVENT;
4033 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4034 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4035 ns_input_line = Qnil; /* can be start or cons start,end */
4036 emacs_event->modifiers =0;
4037 EV_TRAILER (theEvent);
4043 /* **************************************************************************
4045 EmacsApp delegate implementation
4047 ************************************************************************** */
4049 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4050 /* --------------------------------------------------------------------------
4051 When application is loaded, terminate event loop in ns_term_init
4052 -------------------------------------------------------------------------- */
4054 NSTRACE (applicationDidFinishLaunching);
4055 [NSApp setServicesProvider: NSApp];
4056 ns_send_appdefined (-2);
4060 /* Termination sequences:
4063 MenuBar | File | Exit:
4064 Select Quit from App menubar:
4066 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4069 Select Quit from Dock menu:
4072 Cancel -> Nothing else
4076 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4081 - (void) terminate: (id)sender
4083 struct frame *emacsframe = SELECTED_FRAME ();
4088 emacs_event->kind = NS_NONKEY_EVENT;
4089 emacs_event->code = KEY_NS_POWER_OFF;
4090 emacs_event->arg = Qt; /* mark as non-key event */
4091 EV_TRAILER ((id)nil);
4095 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4099 if (NILP (ns_confirm_quit)) // || ns_shutdown_properly --> TO DO
4100 return NSTerminateNow;
4102 ret = NSRunAlertPanel([[NSProcessInfo processInfo] processName],
4103 [NSString stringWithUTF8String:"Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?"],
4104 @"Save Buffers and Exit", @"Cancel", nil);
4106 if (ret == NSAlertDefaultReturn)
4107 return NSTerminateNow;
4108 else if (ret == NSAlertAlternateReturn)
4109 return NSTerminateCancel;
4110 return NSTerminateNow; /* just in case */
4114 /* Notification from the Workspace to open a file */
4115 - (BOOL)application: sender openFile: (NSString *)file
4117 [ns_pending_files addObject: file];
4122 /* Open a file as a temporary file */
4123 - (BOOL)application: sender openTempFile: (NSString *)file
4125 [ns_pending_files addObject: file];
4130 /* Notification from the Workspace to open a file noninteractively (?) */
4131 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4133 [ns_pending_files addObject: file];
4138 /* Notification from the Workspace to open multiple files */
4139 - (void)application: sender openFiles: (NSArray *)fileList
4141 NSEnumerator *files = [fileList objectEnumerator];
4143 while ((file = [files nextObject]) != nil)
4144 [ns_pending_files addObject: file];
4146 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4151 /* Handle dock menu requests. */
4152 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4158 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4159 - (void)applicationWillBecomeActive: (NSNotification *)notification
4161 //ns_app_active=YES;
4163 - (void)applicationDidBecomeActive: (NSNotification *)notification
4165 //ns_app_active=YES;
4167 - (void)applicationDidResignActive: (NSNotification *)notification
4170 ns_send_appdefined (-1);
4175 /* ==========================================================================
4177 EmacsApp aux handlers for managing event loop
4179 ========================================================================== */
4182 - (void)timeout_handler: (NSTimer *)timedEntry
4183 /* --------------------------------------------------------------------------
4184 The timeout specified to ns_select has passed.
4185 -------------------------------------------------------------------------- */
4187 /*NSTRACE (timeout_handler); */
4188 ns_send_appdefined (-2);
4191 extern void update_window_cursor (struct window *w, int on);
4193 - (void)fd_handler: (NSTimer *) fdEntry
4194 /* --------------------------------------------------------------------------
4195 Check data waiting on file descriptors and terminate if so
4196 -------------------------------------------------------------------------- */
4199 /* NSTRACE (fd_handler); */
4201 if (select_nfds == 0)
4204 memcpy (&t_readfds, &select_readfds, sizeof (fd_set));
4206 select_timeout.tv_sec = select_timeout.tv_usec = 0;
4207 result = select (select_nfds, &t_readfds, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
4211 memcpy (&select_readfds, &t_readfds, sizeof (fd_set));
4212 ns_send_appdefined (result);
4218 /* ==========================================================================
4222 ========================================================================== */
4224 /* called from system: queue for next pass through event loop */
4225 - (void)requestService: (NSPasteboard *)pboard
4226 userData: (NSString *)userData
4227 error: (NSString **)error
4229 [ns_pending_service_names addObject: userData];
4230 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
4231 SDATA (ns_string_from_pasteboard (pboard))]];
4235 /* called from ns_read_socket to clear queue */
4236 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
4238 struct frame *emacsframe = SELECTED_FRAME ();
4239 NSEvent *theEvent = [NSApp currentEvent];
4244 emacs_event->kind = NS_NONKEY_EVENT;
4245 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
4246 ns_input_spi_name = build_string ([name UTF8String]);
4247 ns_input_spi_arg = build_string ([arg UTF8String]);
4248 emacs_event->modifiers = EV_MODIFIERS (theEvent);
4249 EV_TRAILER (theEvent);
4259 /* ==========================================================================
4261 EmacsView implementation
4263 ========================================================================== */
4266 @implementation EmacsView
4268 /* needed to inform when window closed from LISP */
4269 - (void) setWindowClosing: (BOOL)closing
4271 windowClosing = closing;
4277 NSTRACE (EmacsView_dealloc);
4283 /* called on font panel selection */
4284 - (void)changeFont: (id)sender
4286 NSEvent *e =[[self window] currentEvent];
4287 struct face *face =FRAME_DEFAULT_FACE (emacsframe);
4291 NSTRACE (changeFont);
4295 if (newFont = [sender convertFont:
4296 ((struct nsfont_info *)face->font)->nsfont])
4298 SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
4300 emacs_event->kind = NS_NONKEY_EVENT;
4301 emacs_event->modifiers = 0;
4302 emacs_event->code = KEY_NS_CHANGE_FONT;
4304 size = [newFont pointSize];
4305 ns_input_fontsize = make_number (lrint (size));
4306 ns_input_font = build_string ([[newFont familyName] UTF8String]);
4312 - (BOOL)acceptsFirstResponder
4314 NSTRACE (acceptsFirstResponder);
4319 - (void)resetCursorRects
4321 NSRect visible = [self visibleRect];
4322 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
4323 NSTRACE (resetCursorRects);
4325 if (currentCursor == nil)
4326 currentCursor = [NSCursor arrowCursor];
4328 if (!NSIsEmptyRect (visible))
4329 [self addCursorRect: visible cursor: currentCursor];
4330 [currentCursor setOnMouseEntered: YES];
4335 /*****************************************************************************/
4336 /* Keyboard handling. */
4339 - (void)keyDown: (NSEvent *)theEvent
4341 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4343 unsigned fnKeysym = 0;
4345 static NSMutableArray *nsEvArray;
4346 static BOOL firstTime = YES;
4350 /* Rhapsody and OS X give up and down events for the arrow keys */
4351 if (ns_fake_keydown == YES)
4352 ns_fake_keydown = NO;
4353 else if ([theEvent type] != NSKeyDown)
4359 if (![[self window] isKeyWindow]
4360 && [[theEvent window] isKindOfClass: [EmacsWindow class]]
4361 /* we must avoid an infinite loop here. */
4362 && (EmacsView *)[[theEvent window] delegate] != self)
4364 /* XXX: There is an occasional condition in which, when Emacs display
4365 updates a different frame from the current one, and temporarily
4366 selects it, then processes some interrupt-driven input
4367 (dispnew.c:3878), OS will send the event to the correct NSWindow, but
4368 for some reason that window has its first responder set to the NSView
4369 most recently updated (I guess), which is not the correct one. */
4370 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
4374 if (nsEvArray == nil)
4375 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
4377 [NSCursor setHiddenUntilMouseMoves: YES];
4379 if (dpyinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
4381 clear_mouse_face (dpyinfo);
4382 dpyinfo->mouse_face_hidden = 1;
4385 if (!processingCompose)
4387 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
4388 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
4389 /* (Carbon way: [theEvent keyCode]) */
4391 /* is it a "function key"? */
4392 fnKeysym = ns_convert_key (code);
4395 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
4396 because Emacs treats Delete and KP-Delete same (in simple.el). */
4397 if (fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
4398 code = 0xFF08; /* backspace */
4403 /* are there modifiers? */
4404 emacs_event->modifiers = 0;
4405 flags = [theEvent modifierFlags];
4407 if (flags & NSHelpKeyMask)
4408 emacs_event->modifiers |= hyper_modifier;
4410 if (flags & NSShiftKeyMask)
4411 emacs_event->modifiers |= shift_modifier;
4413 if (flags & NSCommandKeyMask)
4415 emacs_event->modifiers |= parse_solitary_modifier (ns_command_modifier);
4416 /* if super (default), take input manager's word so things like
4417 dvorak / qwerty layout work */
4418 if (EQ (ns_command_modifier, Qsuper)
4420 && [[theEvent characters] length] != 0)
4422 /* XXX: the code we get will be unshifted, so if we have
4423 a shift modifier, must convert ourselves */
4424 if (!(flags & NSShiftKeyMask))
4425 code = [[theEvent characters] characterAtIndex: 0];
4427 /* this is ugly and also requires linking w/Carbon framework
4428 (for LMGetKbdType) so for now leave this rare (?) case
4429 undealt with.. in future look into CGEvent methods */
4432 long smv = GetScriptManagerVariable (smKeyScript);
4433 Handle uchrHandle = GetResource
4434 ('uchr', GetScriptVariable (smv, smScriptKeys));
4436 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
4437 [[theEvent characters] characterAtIndex: 0],
4438 kUCKeyActionDisplay,
4439 (flags & ~NSCommandKeyMask) >> 8,
4440 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
4441 &dummy, 1, &dummy, &code);
4448 if (flags & NSControlKeyMask)
4449 emacs_event->modifiers |=
4450 parse_solitary_modifier (ns_control_modifier);
4452 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
4453 emacs_event->modifiers |=
4454 parse_solitary_modifier (ns_function_modifier);
4456 if (flags & NSAlternateKeyMask) /* default = meta */
4458 if ((NILP (ns_alternate_modifier) || EQ (ns_alternate_modifier, Qnone))
4460 { /* accept pre-interp alt comb */
4461 if ([[theEvent characters] length] > 0)
4462 code = [[theEvent characters] characterAtIndex: 0];
4463 /*HACK: clear lone shift modifier to stop next if from firing */
4464 if (emacs_event->modifiers == shift_modifier)
4465 emacs_event->modifiers = 0;
4468 emacs_event->modifiers |=
4469 parse_solitary_modifier (ns_alternate_modifier);
4473 fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
4474 code, fnKeysym, flags, emacs_event->modifiers);
4476 /* if it was a function key or had modifiers, pass it directly to emacs */
4477 if (fnKeysym || (emacs_event->modifiers
4478 && [[theEvent charactersIgnoringModifiers] length] > 0))
4479 /*[[theEvent characters] length] */
4481 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4483 code |= (1<<28)|(3<<16);
4484 else if (code == 0x7f)
4485 code |= (1<<28)|(3<<16);
4487 emacs_event->kind = code > 0xFF
4488 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4490 emacs_event->code = code;
4491 EV_TRAILER (theEvent);
4496 /* if we get here we should send the key for input manager processing */
4497 if (firstTime && [[NSInputManager currentInputManager]
4498 wantsToDelayTextChangeNotifications] == NO)
4500 "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
4503 if (NS_KEYLOG && !processingCompose)
4504 fprintf (stderr, "keyDown: Begin compose sequence.\n");
4506 processingCompose = YES;
4507 [nsEvArray addObject: theEvent];
4508 [self interpretKeyEvents: nsEvArray];
4509 [nsEvArray removeObject: theEvent];
4513 #ifdef NS_IMPL_COCOA
4514 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
4515 decided not to send key-down for.
4516 See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
4517 This only applies on Tiger and earlier.
4518 If it matches one of these, send it on to keyDown. */
4519 -(void)keyUp: (NSEvent *)theEvent
4521 int flags = [theEvent modifierFlags];
4522 int code = [theEvent keyCode];
4523 if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
4524 code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
4527 fprintf (stderr, "keyUp: passed test");
4528 ns_fake_keydown = YES;
4529 [self keyDown: theEvent];
4535 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
4538 /* <NSTextInput>: called when done composing;
4539 NOTE: also called when we delete over working text, followed immed.
4540 by doCommandBySelector: deleteBackward: */
4541 - (void)insertText: (id)aString
4544 int len = [(NSString *)aString length];
4548 NSLog (@"insertText '%@'\tlen = %d", aString, len);
4549 processingCompose = NO;
4554 /* first, clear any working text */
4555 if (workingText != nil)
4556 [self deleteWorkingText];
4558 /* now insert the string as keystrokes */
4559 for (i =0; i<len; i++)
4561 code = [aString characterAtIndex: i];
4562 /* TODO: still need this? */
4564 code = '~'; /* 0x7E */
4565 emacs_event->modifiers = 0;
4567 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4568 emacs_event->code = code;
4569 EV_TRAILER ((id)nil);
4574 /* <NSTextInput>: inserts display of composing characters */
4575 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
4577 NSString *str = [aString respondsToSelector: @selector (string)] ?
4578 [aString string] : aString;
4580 NSLog (@"setMarkedText '%@' len =%d range %d from %d", str, [str length],
4581 selRange.length, selRange.location);
4583 if (workingText != nil)
4584 [self deleteWorkingText];
4585 if ([str length] == 0)
4591 processingCompose = YES;
4592 workingText = [str copy];
4593 ns_working_text = build_string ([workingText UTF8String]);
4595 emacs_event->kind = NS_TEXT_EVENT;
4596 emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
4597 EV_TRAILER ((id)nil);
4601 /* delete display of composing characters [not in <NSTextInput>] */
4602 - (void)deleteWorkingText
4604 if (workingText == nil)
4607 NSLog(@"deleteWorkingText len =%d\n", [workingText length]);
4608 [workingText release];
4610 processingCompose = NO;
4615 emacs_event->kind = NS_TEXT_EVENT;
4616 emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
4617 EV_TRAILER ((id)nil);
4621 - (BOOL)hasMarkedText
4623 return workingText != nil;
4627 - (NSRange)markedRange
4629 NSRange rng = workingText != nil
4630 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
4632 NSLog (@"markedRange request");
4640 NSLog (@"unmark (accept) text");
4641 [self deleteWorkingText];
4642 processingCompose = NO;
4646 /* used to position char selection windows, etc. */
4647 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
4651 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
4653 NSLog (@"firstRectForCharRange request");
4655 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
4656 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
4657 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
4658 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
4659 +FRAME_LINE_HEIGHT (emacsframe));
4661 pt = [self convertPoint: pt toView: nil];
4662 pt = [[self window] convertBaseToScreen: pt];
4668 - (NSInteger)conversationIdentifier
4670 return (NSInteger)self;
4674 - (void)doCommandBySelector: (SEL)aSelector
4677 NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
4679 if (aSelector == @selector (deleteBackward:))
4681 /* happens when user backspaces over an ongoing composition:
4682 throw a 'delete' into the event queue */
4685 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4686 emacs_event->code = 0xFF08;
4687 EV_TRAILER ((id)nil);
4691 - (NSArray *)validAttributesForMarkedText
4693 static NSArray *arr = nil;
4694 if (arr == nil) arr = [NSArray new];
4695 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
4699 - (NSRange)selectedRange
4702 NSLog (@"selectedRange request");
4703 return NSMakeRange (NSNotFound, 0);
4706 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
4709 NSLog (@"characterIndexForPoint request");
4713 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
4715 static NSAttributedString *str = nil;
4716 if (str == nil) str = [NSAttributedString new];
4718 NSLog (@"attributedSubstringFromRange request");
4722 /* End <NSTextInput> impl. */
4723 /*****************************************************************************/
4726 /* This is what happens when the user presses a mouse button. */
4727 - (void)mouseDown: (NSEvent *)theEvent
4729 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
4732 NSTRACE (mouseDown);
4734 [self deleteWorkingText];
4739 last_mouse_frame = emacsframe;
4740 /* appears to be needed to prevent spurious movement events generated on
4742 last_mouse_frame->mouse_moved = 0;
4744 if ([theEvent type] == NSScrollWheel)
4746 float delta = [theEvent deltaY];
4747 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
4750 emacs_event->kind = WHEEL_EVENT;
4751 emacs_event->code = 0;
4752 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
4753 ((delta > 0) ? up_modifier : down_modifier);
4757 emacs_event->kind = MOUSE_CLICK_EVENT;
4758 emacs_event->code = EV_BUTTON (theEvent);
4759 emacs_event->modifiers = EV_MODIFIERS (theEvent)
4760 | EV_UDMODIFIERS (theEvent);
4762 XSETINT (emacs_event->x, lrint (p.x));
4763 XSETINT (emacs_event->y, lrint (p.y));
4764 EV_TRAILER (theEvent);
4768 - (void)rightMouseDown: (NSEvent *)theEvent
4770 NSTRACE (rightMouseDown);
4771 [self mouseDown: theEvent];
4775 - (void)otherMouseDown: (NSEvent *)theEvent
4777 NSTRACE (otherMouseDown);
4778 [self mouseDown: theEvent];
4782 - (void)mouseUp: (NSEvent *)theEvent
4785 [self mouseDown: theEvent];
4789 - (void)rightMouseUp: (NSEvent *)theEvent
4791 NSTRACE (rightMouseUp);
4792 [self mouseDown: theEvent];
4796 - (void)otherMouseUp: (NSEvent *)theEvent
4798 NSTRACE (otherMouseUp);
4799 [self mouseDown: theEvent];
4803 - (void) scrollWheel: (NSEvent *)theEvent
4805 NSTRACE (scrollWheel);
4806 [self mouseDown: theEvent];
4810 /* Tell emacs the mouse has moved. */
4811 - (void)mouseMoved: (NSEvent *)e
4813 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4816 // NSTRACE (mouseMoved);
4818 last_mouse_movement_time = EV_TIMESTAMP (e);
4819 last_mouse_motion_position
4820 = [self convertPoint: [e locationInWindow] fromView: nil];
4822 /* update any mouse face */
4823 if (dpyinfo->mouse_face_hidden)
4825 dpyinfo->mouse_face_hidden = 0;
4826 clear_mouse_face (dpyinfo);
4829 /* tooltip handling */
4830 previous_help_echo_string = help_echo_string;
4831 help_echo_string = Qnil;
4833 if (!note_mouse_movement (emacsframe, last_mouse_motion_position.x,
4834 last_mouse_motion_position.y))
4835 help_echo_string = previous_help_echo_string;
4837 XSETFRAME (frame, emacsframe);
4838 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
4840 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
4841 (note_mouse_highlight), which is called through the
4842 note_mouse_movement () call above */
4843 gen_help_event (help_echo_string, frame, help_echo_window,
4844 help_echo_object, help_echo_pos);
4848 help_echo_string = Qnil;
4849 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
4852 if (emacsframe->mouse_moved && send_appdefined)
4853 ns_send_appdefined (-1);
4857 - (void)mouseDragged: (NSEvent *)e
4859 NSTRACE (mouseDragged);
4860 [self mouseMoved: e];
4864 - (void)rightMouseDragged: (NSEvent *)e
4866 NSTRACE (rightMouseDragged);
4867 [self mouseMoved: e];
4871 - (void)otherMouseDragged: (NSEvent *)e
4873 NSTRACE (otherMouseDragged);
4874 [self mouseMoved: e];
4878 - (BOOL)windowShouldClose: (id)sender
4880 NSEvent *e =[[self window] currentEvent];
4882 NSTRACE (windowShouldClose);
4883 windowClosing = YES;
4886 emacs_event->kind = DELETE_WINDOW_EVENT;
4887 emacs_event->modifiers = 0;
4888 emacs_event->code = 0;
4890 /* Don't close this window, let this be done from lisp code. */
4895 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
4896 /* normalize frame to gridded text size */
4898 NSTRACE (windowWillResize);
4899 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
4901 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe,
4902 #ifdef NS_IMPL_GNUSTEP
4903 frameSize.width + 3);
4907 if (cols < MINWIDTH)
4909 frameSize.width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (emacsframe, cols);
4911 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, frameSize.height
4912 #ifdef NS_IMPL_GNUSTEP
4913 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe) + 3
4914 - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
4916 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
4917 - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
4919 if (rows < MINHEIGHT)
4921 frameSize.height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows)
4922 + FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
4923 + FRAME_NS_TOOLBAR_HEIGHT (emacsframe);
4924 #ifdef NS_IMPL_COCOA
4926 /* this sets window title to have size in it; the wm does this under GS */
4927 NSRect r = [[self window] frame];
4928 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
4939 NSWindow *window = [self window];
4942 const char *t = [[[self window] title] UTF8String];
4943 char *pos = strstr (t, " — ");
4946 old_title = (char *) xmalloc (strlen (t) + 1);
4947 strcpy (old_title, t);
4949 size_title = xmalloc (strlen (old_title) + 40);
4950 sprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
4951 [window setTitle: [NSString stringWithUTF8String: size_title]];
4956 #endif /* NS_IMPL_COCOA */
4957 /*fprintf (stderr," ...size became %.0f x %.0f (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
4963 - (void)windowDidResize: (NSNotification *)notification
4965 NSWindow *theWindow = [notification object];
4967 #ifdef NS_IMPL_GNUSTEP
4968 /* in GNUstep, at least currently, it's possible to get a didResize
4969 without getting a willResize.. therefore we need to act as if we got
4970 the willResize now */
4971 NSSize sz = [theWindow frame].size;
4972 sz = [self windowWillResize: theWindow toSize: sz];
4973 #endif /* NS_IMPL_GNUSTEP */
4975 NSTRACE (windowDidResize);
4976 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
4978 #ifdef NS_IMPL_COCOA
4984 #endif /* NS_IMPL_COCOA */
4986 /* Avoid loop under GNUstep due to call at beginning of this function.
4987 (x_set_window_size causes a resize which causes
4988 a "windowDidResize" which calls x_set_window_size). */
4989 #ifndef NS_IMPL_GNUSTEP
4990 if (cols > 0 && rows > 0)
4991 x_set_window_size (emacsframe, 0, cols, rows);
4994 ns_send_appdefined (-1);
4998 - (void)windowDidBecomeKey: (NSNotification *)notification
4999 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5001 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5002 struct frame *old_focus = dpyinfo->x_focus_frame;
5004 NSTRACE (windowDidBecomeKey);
5006 if (emacsframe != old_focus)
5007 dpyinfo->x_focus_frame = emacsframe;
5009 ns_frame_rehighlight (emacsframe);
5013 emacs_event->kind = FOCUS_IN_EVENT;
5014 EV_TRAILER ((id)nil);
5019 - (void)windowDidResignKey: (NSNotification *)notification
5020 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5022 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5023 NSTRACE (windowDidResignKey);
5025 if (dpyinfo->x_focus_frame == emacsframe)
5026 dpyinfo->x_focus_frame = 0;
5028 ns_frame_rehighlight (emacsframe);
5030 /* FIXME: for some reason needed on second and subsequent clicks away
5031 from sole-frame Emacs to get hollow box to show */
5032 if (!windowClosing && [[self window] isVisible] == YES)
5034 x_update_cursor (emacsframe, 1);
5035 x_set_frame_alpha (emacsframe);
5040 [self deleteWorkingText];
5041 emacs_event->kind = FOCUS_IN_EVENT;
5042 EV_TRAILER ((id)nil);
5047 - (void)windowWillMiniaturize: sender
5049 NSTRACE (windowWillMiniaturize);
5065 - initFrameFromEmacs: (struct frame *)f
5070 NSButton *toggleButton;
5071 int vbextra = NS_SCROLL_BAR_WIDTH (f);
5076 NSTRACE (initFrameFromEmacs);
5079 processingCompose = NO;
5080 scrollbarsNeedingUpdate = 0;
5082 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
5084 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
5085 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
5086 [self initWithFrame: r];
5087 [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
5089 FRAME_NS_VIEW (f) = self;
5093 win = [[EmacsWindow alloc]
5094 initWithContentRect: r
5095 styleMask: (NSResizableWindowMask |
5096 NSMiniaturizableWindowMask |
5097 NSClosableWindowMask)
5098 backing: NSBackingStoreBuffered
5102 f->border_width = wr.size.width - r.size.width;
5103 FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
5105 [win setAcceptsMouseMovedEvents: YES];
5106 [win setDelegate: self];
5107 [win useOptimizedDrawing: YES];
5109 sz.width = FRAME_COLUMN_WIDTH (f);
5110 sz.height = FRAME_LINE_HEIGHT (f);
5111 [win setResizeIncrements: sz];
5113 [[win contentView] addSubview: self];
5116 [self registerForDraggedTypes: ns_drag_types];
5119 name = [NSString stringWithUTF8String:
5120 NILP (tem) ? (unsigned char *)"Emacs" : SDATA (tem)];
5121 [win setTitle: name];
5123 /* toolbar support */
5124 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
5125 [NSString stringWithFormat: @"Emacs Frame %d",
5127 [win setToolbar: toolbar];
5128 [toolbar setVisible: NO];
5129 #ifdef NS_IMPL_COCOA
5130 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
5131 [toggleButton setTarget: self];
5132 [toggleButton setAction: @selector (toggleToolbar: )];
5134 FRAME_NS_TOOLBAR_HEIGHT (f) = 0;
5138 [win setMiniwindowTitle:
5139 [NSString stringWithUTF8String: SDATA (tem)]];
5142 NSScreen *screen = [win screen];
5145 [win setFrameTopLeftPoint: NSMakePoint
5146 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
5147 IN_BOUND (-SCREENMAX,
5148 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
5151 [win makeFirstResponder: self];
5153 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5154 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
5155 [win setBackgroundColor: col];
5156 if ([col alphaComponent] != 1.0)
5157 [win setOpaque: NO];
5159 [self allocateGState];
5166 - (void)windowDidMove: sender
5168 NSWindow *win = [self window];
5169 NSRect r = [win frame];
5170 NSScreen *screen = [win screen];
5172 NSTRACE (windowDidMove);
5174 if (!emacsframe->output_data.ns)
5178 emacsframe->left_pos = r.origin.x;
5179 emacsframe->top_pos =
5180 [screen frame].size.height - (r.origin.y + r.size.height);
5185 /* Called AFTER method below, but before our windowWillResize call there leads
5186 to windowDidResize -> x_set_window_size. Update emacs' notion of frame
5187 location so set_window_size moves the frame. */
5188 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
5190 NSTRACE (windowShouldZoom);
5191 emacsframe->left_pos = (int)newFrame.origin.x;
5192 emacsframe->top_pos = [[sender screen] frame].size.height
5193 - (newFrame.origin.y+newFrame.size.height);
5198 /* Override to do something slightly nonstandard, but nice. First click on
5199 zoom button will zoom vertically. Second will zoom completely. Third
5200 returns to original. */
5201 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
5202 defaultFrame:(NSRect)defaultFrame
5204 NSRect result = [sender frame];
5205 static NSRect ns_userRect = { 0, 0, 0, 0 };
5207 NSTRACE (windowWillUseStandardFrame);
5209 if (abs (defaultFrame.size.height - result.size.height)
5210 > FRAME_LINE_HEIGHT (emacsframe))
5213 ns_userRect = result;
5214 result.size.height = defaultFrame.size.height;
5215 result.origin.y = defaultFrame.origin.y;
5219 if (abs (defaultFrame.size.width - result.size.width)
5220 > FRAME_COLUMN_WIDTH (emacsframe))
5221 result = defaultFrame; /* second click */
5223 result = ns_userRect.size.height ? ns_userRect : result; /* restore */
5226 [self windowWillResize: sender toSize: result.size];
5231 - (void)windowDidDeminiaturize: sender
5233 NSTRACE (windowDidDeminiaturize);
5234 if (!emacsframe->output_data.ns)
5236 emacsframe->async_iconified = 0;
5237 emacsframe->async_visible = 1;
5238 windows_or_buffers_changed++;
5242 emacs_event->kind = ICONIFY_EVENT;
5243 EV_TRAILER ((id)nil);
5248 - (void)windowDidExpose: sender
5250 NSTRACE (windowDidExpose);
5251 if (!emacsframe->output_data.ns)
5253 emacsframe->async_visible = 1;
5254 SET_FRAME_GARBAGED (emacsframe);
5256 if (send_appdefined)
5257 ns_send_appdefined (-1);
5261 - (void)windowDidMiniaturize: sender
5263 NSTRACE (windowDidMiniaturize);
5264 if (!emacsframe->output_data.ns)
5267 emacsframe->async_iconified = 1;
5268 emacsframe->async_visible = 0;
5272 emacs_event->kind = ICONIFY_EVENT;
5273 EV_TRAILER ((id)nil);
5278 - (void)mouseEntered: (NSEvent *)theEvent
5280 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5281 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5282 NSTRACE (mouseEntered);
5284 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5288 - (void)mouseExited: (NSEvent *)theEvent
5290 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5292 struct ns_display_info *dpyinfo
5293 = emacsframe ? FRAME_NS_DISPLAY_INFO (emacsframe) : NULL;
5295 NSTRACE (mouseExited);
5297 if (dpyinfo || !emacsframe)
5300 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5302 if (emacsframe == dpyinfo->mouse_face_mouse_frame)
5304 clear_mouse_face (dpyinfo);
5305 dpyinfo->mouse_face_mouse_frame = 0;
5313 if (context_menu_value == -1)
5314 context_menu_value = [sender tag];
5316 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
5317 emacsframe->menu_bar_vector,
5318 (void *)[sender tag]);
5319 ns_send_appdefined (-1);
5324 - (EmacsToolbar *)toolbar
5330 /* this gets called on toolbar button click */
5331 - toolbarClicked: (id)item
5334 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
5336 NSTRACE (toolbarClicked);
5341 /* send first event (for some reason two needed) */
5342 theEvent = [[self window] currentEvent];
5343 emacs_event->kind = TOOL_BAR_EVENT;
5344 XSETFRAME (emacs_event->arg, emacsframe);
5345 EV_TRAILER (theEvent);
5347 emacs_event->kind = TOOL_BAR_EVENT;
5348 /* XSETINT (emacs_event->code, 0); */
5349 emacs_event->arg = AREF (emacsframe->tool_bar_items,
5350 idx + TOOL_BAR_ITEM_KEY);
5351 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5352 EV_TRAILER (theEvent);
5357 - toggleToolbar: (id)sender
5362 emacs_event->kind = NS_NONKEY_EVENT;
5363 emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
5364 EV_TRAILER ((id)nil);
5369 - (void)drawRect: (NSRect)rect
5371 int x = NSMinX (rect), y = NSMinY (rect);
5372 int width = NSWidth (rect), height = NSHeight (rect);
5376 if (!emacsframe || !emacsframe->output_data.ns || ns_in_resize)
5379 ns_clear_frame_area (emacsframe, x, y, width, height);
5380 expose_frame (emacsframe, x, y, width, height);
5383 drawRect: may be called (at least in OS X 10.5) for invisible
5384 views as well for some reason. Thus, do not infer visibility
5387 emacsframe->async_visible = 1;
5388 emacsframe->async_iconified = 0;
5393 /* NSDraggingDestination protocol methods. Actually this is not really a
5394 protocol, but a category of Object. O well... */
5396 -(unsigned int) draggingEntered: (id <NSDraggingInfo>) sender
5398 NSTRACE (draggingEntered);
5399 return NSDragOperationGeneric;
5403 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
5409 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
5414 NSEvent *theEvent = [[self window] currentEvent];
5417 NSTRACE (performDragOperation);
5422 position = [self convertPoint: [sender draggingLocation] fromView: nil];
5423 x = lrint (position.x); y = lrint (position.y);
5425 pb = [sender draggingPasteboard];
5426 type = [pb availableTypeFromArray: ns_drag_types];
5431 else if ([type isEqualToString: NSFilenamesPboardType])
5434 NSEnumerator *fenum;
5437 if (!(files = [pb propertyListForType: type]))
5440 fenum = [files objectEnumerator];
5441 while ( (file = [fenum nextObject]) )
5443 emacs_event->kind = NS_NONKEY_EVENT;
5444 emacs_event->code = KEY_NS_DRAG_FILE;
5445 XSETINT (emacs_event->x, x);
5446 XSETINT (emacs_event->y, y);
5447 ns_input_file = append2 (ns_input_file,
5448 build_string ([file UTF8String]));
5449 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5450 EV_TRAILER (theEvent);
5454 else if ([type isEqualToString: NSURLPboardType])
5459 if (!(fileURL = [NSURL URLFromPasteboard: pb]) ||
5460 [fileURL isFileURL] == NO)
5463 file = [fileURL path];
5464 emacs_event->kind = NS_NONKEY_EVENT;
5465 emacs_event->code = KEY_NS_DRAG_FILE;
5466 XSETINT (emacs_event->x, x);
5467 XSETINT (emacs_event->y, y);
5468 ns_input_file = append2 (ns_input_file, build_string ([file UTF8String]));
5469 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5470 EV_TRAILER (theEvent);
5473 else if ([type isEqualToString: NSStringPboardType]
5474 || [type isEqualToString: NSTabularTextPboardType])
5478 if (! (data = [pb stringForType: type]))
5481 emacs_event->kind = NS_NONKEY_EVENT;
5482 emacs_event->code = KEY_NS_DRAG_TEXT;
5483 XSETINT (emacs_event->x, x);
5484 XSETINT (emacs_event->y, y);
5485 ns_input_text = build_string ([data UTF8String]);
5486 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5487 EV_TRAILER (theEvent);
5490 else if ([type isEqualToString: NSColorPboardType])
5492 NSColor *c = [NSColor colorFromPasteboard: pb];
5493 emacs_event->kind = NS_NONKEY_EVENT;
5494 emacs_event->code = KEY_NS_DRAG_COLOR;
5495 XSETINT (emacs_event->x, x);
5496 XSETINT (emacs_event->y, y);
5497 ns_input_color = ns_color_to_lisp (c);
5498 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5499 EV_TRAILER (theEvent);
5502 else if ([type isEqualToString: NSFontPboardType])
5504 /* impl based on GNUstep NSTextView.m */
5505 NSData *data = [pb dataForType: NSFontPboardType];
5506 NSDictionary *dict = [NSUnarchiver unarchiveObjectWithData: data];
5507 NSFont *font = [dict objectForKey: NSFontAttributeName];
5513 emacs_event->kind = NS_NONKEY_EVENT;
5514 emacs_event->code = KEY_NS_CHANGE_FONT;
5515 XSETINT (emacs_event->x, x);
5516 XSETINT (emacs_event->y, y);
5517 ns_input_font = build_string ([[font fontName] UTF8String]);
5518 snprintf (fontSize, 10, "%f", [font pointSize]);
5519 ns_input_fontsize = build_string (fontSize);
5520 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5521 EV_TRAILER (theEvent);
5526 error ("Invalid data type in dragging pasteboard.");
5532 - validRequestorForSendType: (NSString *)typeSent
5533 returnType: (NSString *)typeReturned
5535 NSTRACE (validRequestorForSendType);
5536 if ([ns_send_types indexOfObjectIdenticalTo: typeSent] != NSNotFound &&
5537 [ns_return_types indexOfObjectIdenticalTo: typeSent] != NSNotFound)
5540 return [super validRequestorForSendType: typeSent
5541 returnType: typeReturned];
5545 /* The next two methods are part of NSServicesRequests informal protocol,
5546 supposedly called when a services menu item is chosen from this app.
5547 But this should not happen because we override the services menu with our
5548 own entries which call ns-perform-service.
5549 Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
5550 So let's at least stub them out until further investigation can be done. */
5552 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
5554 /* we could call ns_string_from_pasteboard(pboard) here but then it should
5555 be written into the buffer in place of the existing selection..
5556 ordinary service calls go through functions defined in ns-win.el */
5560 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
5562 /* supposed to write for as many of types as we are able */
5567 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
5568 (gives a miniaturized version of the window); currently we use the latter for
5569 frames whose active buffer doesn't correspond to any file
5570 (e.g., '*scratch*') */
5571 - setMiniwindowImage: (BOOL) setMini
5573 id image = [[self window] miniwindowImage];
5574 NSTRACE (setMiniwindowImage);
5576 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
5577 about "AppleDockIconEnabled" notwithstanding, however the set message
5578 below has its effect nonetheless. */
5579 if (image != emacsframe->output_data.ns->miniimage)
5581 if (image && [image isKindOfClass: [EmacsImage class]])
5583 [[self window] setMiniwindowImage:
5584 setMini ? emacsframe->output_data.ns->miniimage : nil];
5591 - (void) setRows: (int) r andColumns: (int) c
5597 @end /* EmacsView */
5601 /* ==========================================================================
5603 EmacsWindow implementation
5605 ========================================================================== */
5607 @implementation EmacsWindow
5609 /* called only on resize clicks by special case in EmacsApp-sendEvent */
5610 - (void)mouseDown: (NSEvent *)theEvent
5614 NSSize size = [[theEvent window] frame].size;
5615 grabOffset = [theEvent locationInWindow];
5616 grabOffset.x = size.width - grabOffset.x;
5619 [super mouseDown: theEvent];
5624 - (void)mouseUp: (NSEvent *)theEvent
5628 struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
5630 ns_set_name_as_filename (f);
5632 ns_send_appdefined (-1);
5635 [super mouseUp: theEvent];
5639 /* send resize events */
5640 - (void)mouseDragged: (NSEvent *)theEvent
5644 NSPoint p = [theEvent locationInWindow];
5645 NSSize size, vettedSize, origSize = [self frame].size;
5647 size.width = p.x + grabOffset.x;
5648 size.height = origSize.height - p.y + grabOffset.y;
5650 if (size.width == origSize.width && size.height == origSize.height)
5653 vettedSize = [[self delegate] windowWillResize: self toSize: size];
5654 if (vettedSize.width != size.width || vettedSize.height != size.height)
5656 [[NSNotificationCenter defaultCenter]
5657 postNotificationName: NSWindowDidResizeNotification
5662 [super mouseDragged: theEvent];
5665 @end /* EmacsWindow */
5668 /* ==========================================================================
5670 EmacsScroller implementation
5672 ========================================================================== */
5675 @implementation EmacsScroller
5677 /* for repeat button push */
5678 #define SCROLL_BAR_FIRST_DELAY 0.5
5679 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
5681 + (float) scrollerWidth
5683 /* TODO: if we want to allow variable widths, this is the place to do it,
5684 however neither GNUstep nor Cocoa support it very well */
5685 return [NSScroller scrollerWidth];
5689 - initFrame: (NSRect )r window: (Lisp_Object)nwin
5691 NSTRACE (EmacsScroller_initFrame);
5693 r.size.width = [EmacsScroller scrollerWidth];
5694 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
5695 [self setContinuous: YES];
5696 [self setEnabled: YES];
5698 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
5699 locked against the top and bottom edges, and right edge on OS X, where
5700 scrollers are on right. */
5701 #ifdef NS_IMPL_GNUSTEP
5702 [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
5704 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
5709 pixel_height = NSHeight (r);
5710 min_portion = 20 / pixel_height;
5712 frame = XFRAME (XWINDOW (win)->frame);
5713 if (FRAME_LIVE_P (frame))
5716 EmacsView *view = FRAME_NS_VIEW (frame);
5717 NSView *sview = [[view window] contentView];
5718 NSArray *subs = [sview subviews];
5720 /* disable optimization stopping redraw of other scrollbars */
5721 view->scrollbarsNeedingUpdate = 0;
5722 for (i =[subs count]-1; i >= 0; i--)
5723 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
5724 view->scrollbarsNeedingUpdate++;
5725 [sview addSubview: self];
5728 /* [self setFrame: r]; */
5734 - (void)setFrame: (NSRect)newRect
5736 NSTRACE (EmacsScroller_setFrame);
5738 pixel_height = NSHeight (newRect);
5739 min_portion = 20 / pixel_height;
5740 [super setFrame: newRect];
5742 /* UNBLOCK_INPUT; */
5748 NSTRACE (EmacsScroller_dealloc);
5750 XWINDOW (win)->vertical_scroll_bar = Qnil;
5777 /* ensure other scrollbar updates after deletion */
5778 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
5780 view->scrollbarsNeedingUpdate++;
5781 [self removeFromSuperview];
5789 - (void)resetCursorRects
5791 NSRect visible = [self visibleRect];
5792 NSTRACE (resetCursorRects);
5794 if (!NSIsEmptyRect (visible))
5795 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
5796 [[NSCursor arrowCursor] setOnMouseEntered: YES];
5800 - (int) checkSamePosition: (int) position portion: (int) portion
5803 return em_position ==position && em_portion ==portion && em_whole ==whole
5804 && portion != whole; /* needed for resize empty buf */
5808 - setPosition: (int)position portion: (int)portion whole: (int)whole
5810 NSTRACE (setPosition);
5812 em_position = position;
5813 em_portion = portion;
5816 if (portion >= whole)
5817 [self setFloatValue: 0.0 knobProportion: 1.0];
5821 portion = max ((float)whole*min_portion/pixel_height, portion);
5822 pos = (float)position / (whole - portion);
5823 por = (float)portion/whole;
5824 [self setFloatValue: pos knobProportion: por];
5829 /* FIXME: unused at moment (see ns_mouse_position) at the moment because
5830 drag events will go directly to the EmacsScroller. Leaving in for now. */
5831 -(void)getMouseMotionPart: (int *)part window: (Lisp_Object *)window
5832 x: (Lisp_Object *)x y: ( Lisp_Object *)y
5834 *part = last_hit_part;
5836 XSETINT (*y, pixel_height);
5837 if ([self floatValue] > 0.999)
5838 XSETINT (*x, pixel_height);
5840 XSETINT (*x, pixel_height * [self floatValue]);
5844 /* set up emacs_event */
5845 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
5850 emacs_event->part = last_hit_part;
5851 emacs_event->code = 0;
5852 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
5853 emacs_event->frame_or_window = win;
5854 emacs_event->timestamp = EV_TIMESTAMP (e);
5855 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
5856 emacs_event->arg = Qnil;
5857 XSETINT (emacs_event->x, loc * pixel_height);
5858 XSETINT (emacs_event->y, pixel_height-20);
5860 n_emacs_events_pending++;
5861 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
5862 EVENT_INIT (*emacs_event);
5863 ns_send_appdefined (-1);
5867 /* called manually thru timer to implement repeated button action w/hold-down */
5868 - repeatScroll: (NSTimer *)scrollEntry
5870 NSEvent *e = [[self window] currentEvent];
5871 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
5872 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
5874 /* clear timer if need be */
5875 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
5877 [scroll_repeat_entry invalidate];
5878 [scroll_repeat_entry release];
5879 scroll_repeat_entry = nil;
5885 = [[NSTimer scheduledTimerWithTimeInterval:
5886 SCROLL_BAR_CONTINUOUS_DELAY
5888 selector: @selector (repeatScroll:)
5894 [self sendScrollEventAtLoc: 0 fromEvent: e];
5899 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
5900 mouseDragged events without going into a modal loop. */
5901 - (void)mouseDown: (NSEvent *)e
5904 /* hitPart is only updated AFTER event is passed on */
5905 NSScrollerPart part = [self testPart: [e locationInWindow]];
5906 double inc = 0.0, loc, kloc, pos;
5909 NSTRACE (EmacsScroller_mouseDown);
5913 case NSScrollerDecrementPage:
5914 last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
5915 case NSScrollerIncrementPage:
5916 last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
5917 case NSScrollerDecrementLine:
5918 last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
5919 case NSScrollerIncrementLine:
5920 last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
5921 case NSScrollerKnob:
5922 last_hit_part = scroll_bar_handle; break;
5923 case NSScrollerKnobSlot: /* GNUstep-only */
5924 last_hit_part = scroll_bar_move_ratio; break;
5925 default: /* NSScrollerNoPart? */
5926 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %d\n", part);
5932 pos = 0; /* ignored */
5934 /* set a timer to repeat, as we can't let superclass do this modally */
5936 = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
5938 selector: @selector (repeatScroll:)
5945 /* handle, or on GNUstep possibly slot */
5946 NSEvent *fake_event;
5948 /* compute float loc in slot and mouse offset on knob */
5949 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
5951 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
5957 else if (loc >= NSHeight (sr))
5959 loc = NSHeight (sr);
5967 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
5969 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
5971 last_mouse_offset = kloc;
5973 /* if knob, tell emacs a location offset by knob pos
5974 (to indicate top of handle) */
5975 if (part == NSScrollerKnob)
5976 pos = (loc - last_mouse_offset) / NSHeight (sr);
5978 /* else this is a slot click on GNUstep: go straight there */
5979 pos = loc / NSHeight (sr);
5981 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
5982 fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
5983 location: [e locationInWindow]
5984 modifierFlags: [e modifierFlags]
5985 timestamp: [e timestamp]
5986 windowNumber: [e windowNumber]
5987 context: [e context]
5988 eventNumber: [e eventNumber]
5989 clickCount: [e clickCount]
5990 pressure: [e pressure]];
5991 [super mouseUp: fake_event];
5994 if (part != NSScrollerKnob)
5995 [self sendScrollEventAtLoc: pos fromEvent: e];
5999 /* Called as we manually track scroller drags, rather than superclass. */
6000 - (void)mouseDragged: (NSEvent *)e
6006 NSTRACE (EmacsScroller_mouseDragged);
6008 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6010 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6017 else if (loc >= NSHeight (sr) + last_mouse_offset)
6019 loc = NSHeight (sr) + last_mouse_offset;
6023 pos = /*(edge ? loc :*/ (loc - last_mouse_offset) / NSHeight (sr);
6024 [self sendScrollEventAtLoc: pos fromEvent: e];
6028 - (void)mouseUp: (NSEvent *)e
6030 if (scroll_repeat_entry)
6032 [scroll_repeat_entry invalidate];
6033 [scroll_repeat_entry release];
6034 scroll_repeat_entry = nil;
6040 /* treat scrollwheel events in the bar as though they were in the main window */
6041 - (void) scrollWheel: (NSEvent *)theEvent
6043 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
6044 [view mouseDown: theEvent];
6047 @end /* EmacsScroller */
6052 /* ==========================================================================
6054 Font-related functions; these used to be in nsfaces.m
6056 ========================================================================== */
6060 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
6062 struct font *font = XFONT_OBJECT (font_object);
6065 fontset = fontset_from_font (font_object);
6066 FRAME_FONTSET (f) = fontset;
6068 if (FRAME_FONT (f) == font)
6069 /* This font is already set in frame F. There's nothing more to
6073 FRAME_FONT (f) = font;
6075 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
6076 FRAME_COLUMN_WIDTH (f) = font->average_width;
6077 FRAME_SPACE_WIDTH (f) = font->space_width;
6078 FRAME_LINE_HEIGHT (f) = font->height;
6080 compute_fringe_widths (f, 1);
6082 /* Compute the scroll bar width in character columns. */
6083 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
6085 int wid = FRAME_COLUMN_WIDTH (f);
6086 FRAME_CONFIG_SCROLL_BAR_COLS (f)
6087 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
6091 int wid = FRAME_COLUMN_WIDTH (f);
6092 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
6095 /* Now make the frame display the given font. */
6096 if (FRAME_NS_WINDOW (f) != 0)
6097 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
6103 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
6104 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
6108 ns_xlfd_to_fontname (const char *xlfd)
6109 /* --------------------------------------------------------------------------
6110 Convert an X font name (XLFD) to an NS font name.
6111 Only family is used.
6112 The string returned is temporarily allocated.
6113 -------------------------------------------------------------------------- */
6115 char *name = xmalloc (180);
6119 if (!strncmp (xlfd, "--", 2))
6120 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
6122 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
6124 /* stopgap for malformed XLFD input */
6125 if (strlen (name) == 0)
6126 strcpy (name, "Monaco");
6128 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
6129 also uppercase after '-' or ' ' */
6130 name[0] = toupper (name[0]);
6131 for (len =strlen (name), i =0; i<len; i++)
6137 name[i+1] = toupper (name[i+1]);
6139 else if (name[i] == '_')
6143 name[i+1] = toupper (name[i+1]);
6146 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
6147 ret = [[NSString stringWithUTF8String: name] UTF8String];
6156 NSTRACE (syms_of_nsterm);
6157 DEFVAR_LISP ("ns-input-file", &ns_input_file,
6158 "The file specified in the last NS event.");
6159 ns_input_file =Qnil;
6161 DEFVAR_LISP ("ns-input-text", &ns_input_text,
6162 "The data received in the last NS text drag event.");
6163 ns_input_text =Qnil;
6165 DEFVAR_LISP ("ns-working-text", &ns_working_text,
6166 "String for visualizing working composition sequence.");
6167 ns_working_text =Qnil;
6169 DEFVAR_LISP ("ns-input-font", &ns_input_font,
6170 "The font specified in the last NS event.");
6171 ns_input_font =Qnil;
6173 DEFVAR_LISP ("ns-input-fontsize", &ns_input_fontsize,
6174 "The fontsize specified in the last NS event.");
6175 ns_input_fontsize =Qnil;
6177 DEFVAR_LISP ("ns-input-line", &ns_input_line,
6178 "The line specified in the last NS event.");
6179 ns_input_line =Qnil;
6181 DEFVAR_LISP ("ns-input-color", &ns_input_color,
6182 "The color specified in the last NS event.");
6183 ns_input_color =Qnil;
6185 DEFVAR_LISP ("ns-input-spi-name", &ns_input_spi_name,
6186 "The service name specified in the last NS event.");
6187 ns_input_spi_name =Qnil;
6189 DEFVAR_LISP ("ns-input-spi-arg", &ns_input_spi_arg,
6190 "The service argument specified in the last NS event.");
6191 ns_input_spi_arg =Qnil;
6193 DEFVAR_LISP ("ns-alternate-modifier", &ns_alternate_modifier,
6194 "This variable describes the behavior of the alternate or option key.\n\
6195 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6196 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6197 at all, allowing it to be used at a lower level for accented character entry.");
6199 DEFVAR_LISP ("ns-command-modifier", &ns_command_modifier,
6200 "This variable describes the behavior of the command key.\n\
6201 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6203 DEFVAR_LISP ("ns-control-modifier", &ns_control_modifier,
6204 "This variable describes the behavior of the control key.\n\
6205 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6207 DEFVAR_LISP ("ns-function-modifier", &ns_function_modifier,
6208 "This variable describes the behavior of the function key (on laptops).\n\
6209 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6210 Set to none means that the function key is not interpreted by Emacs at all,\n\
6211 allowing it to be used at a lower level for accented character entry.");
6213 DEFVAR_LISP ("ns-antialias-text", &ns_antialias_text,
6214 "Non-nil (the default) means to render text antialiased. Only has an effect on OS X Panther and above.");
6216 DEFVAR_LISP ("ns-confirm-quit", &ns_confirm_quit,
6217 "Whether to confirm application quit using dialog.");
6219 staticpro (&ns_display_name_list);
6220 ns_display_name_list = Qnil;
6222 staticpro (&last_mouse_motion_frame);
6223 last_mouse_motion_frame = Qnil;
6225 /* from 23+ we need to tell emacs what modifiers there are.. */
6226 Qmodifier_value = intern ("modifier-value");
6227 Qalt = intern ("alt");
6228 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
6229 Qhyper = intern ("hyper");
6230 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
6231 Qmeta = intern ("meta");
6232 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
6233 Qsuper = intern ("super");
6234 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
6235 Qcontrol = intern ("control");
6236 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
6238 /* TODO: move to common code */
6239 DEFVAR_LISP ("x-toolkit-scroll-bars", &Vx_toolkit_scroll_bars,
6240 doc: /* If not nil, Emacs uses toolkit scroll bars. */);
6241 #ifdef USE_TOOLKIT_SCROLL_BARS
6242 Vx_toolkit_scroll_bars = Qt;
6244 Vx_toolkit_scroll_bars = Qnil;
6247 /* these are unsupported but we need the declarations to avoid whining
6248 messages from cus-start.el */
6249 DEFVAR_BOOL ("x-use-underline-position-properties",
6250 &x_use_underline_position_properties,
6251 doc: /* NOT SUPPORTED UNDER NS.
6252 *Non-nil means make use of UNDERLINE_POSITION font properties.
6253 A value of nil means ignore them. If you encounter fonts with bogus
6254 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
6255 to 4.1, set this to nil.
6257 NOTE: Not supported on Mac yet. */);
6258 x_use_underline_position_properties = 0;
6260 DEFVAR_BOOL ("x-underline-at-descent-line",
6261 &x_underline_at_descent_line,
6262 doc: /* NOT SUPPORTED UNDER NS.
6263 *Non-nil means to draw the underline at the same place as the descent line.
6264 A value of nil means to draw the underline according to the value of the
6265 variable `x-use-underline-position-properties', which is usually at the
6266 baseline level. The default value is nil. */);
6267 x_underline_at_descent_line = 0;
6269 /* Tell emacs about this window system. */
6270 Fprovide (intern ("ns"), Qnil);
6274 // arch-tag: 6eaa8f7d-a69b-4e1c-b43d-ab31defbe0d2