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;
148 /* Some preferences equivalent to those set by X resources under X are
149 managed through the OpenStep defaults system. We depart from X
150 behavior and refuse to read defaults when started under these
153 /* Set in emacs.c. */
156 /* Specifies which emacs modifier should be generated when NS receives
157 the Alternate modifer. May be Qnone or any of the modifier lisp symbols. */
158 Lisp_Object ns_alternate_modifier;
160 /* Specifies which emacs modifier should be generated when NS receives
161 the Command modifer. May be any of the modifier lisp symbols. */
162 Lisp_Object ns_command_modifier;
164 /* Specifies which emacs modifier should be generated when NS receives
165 the Control modifer. May be any of the modifier lisp symbols. */
166 Lisp_Object ns_control_modifier;
168 /* Specifies which emacs modifier should be generated when NS receives
169 the Function modifer (laptops). May be any of the modifier lisp symbols. */
170 Lisp_Object ns_function_modifier;
172 /* Control via default 'GSFontAntiAlias' on OS X and GNUstep. */
173 Lisp_Object ns_antialias_text;
175 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
176 the maximum font size to NOT antialias. On GNUstep there is currently
177 no way to control this behavior. */
178 float ns_antialias_threshold;
180 /* Controls use of an undocumented CG function to do Quickdraw-style font
181 smoothing (less heavy) instead of regular Quartz smoothing. */
182 Lisp_Object ns_use_qd_smoothing;
184 /* Used to pick up AppleHighlightColor on OS X */
185 NSString *ns_selection_color;
187 /* Confirm on exit. */
188 Lisp_Object ns_confirm_quit;
190 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
192 /* Display variables */
193 struct ns_display_info *x_display_list; /* Chain of existing displays */
194 Lisp_Object ns_display_name_list;
195 long context_menu_value = 0;
198 NSPoint last_mouse_motion_position;
199 static NSRect last_mouse_glyph;
200 static unsigned long last_mouse_movement_time = 0;
201 static Lisp_Object last_mouse_motion_frame;
202 static EmacsScroller *last_mouse_scroll_bar = nil;
203 static struct frame *ns_updating_frame;
204 static NSView *focus_view = NULL;
205 static int ns_window_num =0;
207 static BOOL gsaved = NO;
208 BOOL ns_in_resize = NO;
209 static BOOL ns_fake_keydown = NO;
210 int ns_tmp_flags; /* FIXME */
211 struct nsfont_info *ns_tmp_font; /* FIXME */
212 /*static int debug_lock = 0; */
215 /* This undocumented Quartz function controls how fonts are anti-aliased.
216 (Found from code in Mac wxWindows impl, discovered by running `nm' on
218 Mode 0 is normal anti-aliasing, mode 1 is no anti-aliasing, and mode 2 is
219 4-bit pixel-aligned anti-aliasing (the old QuickDraw standard). */
220 extern void CGContextSetFontRenderingMode (CGContextRef cg, int v);
225 static BOOL send_appdefined = YES;
226 static NSEvent *last_appdefined_event = 0;
227 static NSTimer *timed_entry = 0;
228 static NSTimer *fd_entry = nil;
229 static NSTimer *scroll_repeat_entry = nil;
230 static fd_set select_readfds, t_readfds;
231 static struct timeval select_timeout;
232 static int select_nfds;
233 static NSAutoreleasePool *outerpool;
234 static struct input_event *emacs_event = NULL;
235 static struct input_event *q_event_ptr = NULL;
236 static int n_emacs_events_pending = 0;
237 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
238 *ns_pending_service_args;
239 static BOOL inNsSelect = 0;
241 /* Convert modifiers in a NeXTSTEP event to emacs style modifiers. */
242 #define NS_FUNCTION_KEY_MASK 0x800000
243 #define EV_MODIFIERS(e) \
244 ((([e modifierFlags] & NSHelpKeyMask) ? \
245 hyper_modifier : 0) \
246 | (([e modifierFlags] & NSAlternateKeyMask) ? \
247 parse_solitary_modifier (ns_alternate_modifier) : 0) \
248 | (([e modifierFlags] & NSShiftKeyMask) ? \
249 shift_modifier : 0) \
250 | (([e modifierFlags] & NSControlKeyMask) ? \
251 parse_solitary_modifier (ns_control_modifier) : 0) \
252 | (([e modifierFlags] & NS_FUNCTION_KEY_MASK) ? \
253 parse_solitary_modifier (ns_function_modifier) : 0) \
254 | (([e modifierFlags] & NSCommandKeyMask) ? \
255 parse_solitary_modifier (ns_command_modifier):0))
257 #define EV_UDMODIFIERS(e) \
258 ((([e type] == NSLeftMouseDown) ? down_modifier : 0) \
259 | (([e type] == NSRightMouseDown) ? down_modifier : 0) \
260 | (([e type] == NSOtherMouseDown) ? down_modifier : 0) \
261 | (([e type] == NSLeftMouseDragged) ? down_modifier : 0) \
262 | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
263 | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
264 | (([e type] == NSLeftMouseUp) ? up_modifier : 0) \
265 | (([e type] == NSRightMouseUp) ? up_modifier : 0) \
266 | (([e type] == NSOtherMouseUp) ? up_modifier : 0))
268 #define EV_BUTTON(e) \
269 ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 : \
270 (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
271 [e buttonNumber] - 1)
273 /* Convert the time field to a timestamp in milliseconds. */
274 #ifdef NS_IMPL_GNUSTEP
275 /* Apple says timestamp is in seconds, but GNUstep seems to be returning msec */
276 #define EV_TIMESTAMP(e) ([e timestamp])
278 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
279 #endif /* not gnustep */
281 /* This is a piece of code which is common to all the event handling
282 methods. Maybe it should even be a function. */
283 #define EV_TRAILER(e) \
285 XSETFRAME (emacs_event->frame_or_window, emacsframe); \
286 if (e) emacs_event->timestamp = EV_TIMESTAMP (e); \
287 n_emacs_events_pending++; \
288 kbd_buffer_store_event_hold (emacs_event, q_event_ptr); \
289 EVENT_INIT (*emacs_event); \
290 ns_send_appdefined (-1); \
293 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
295 /* TODO: get rid of need for these forward declarations */
296 static void ns_condemn_scroll_bars (struct frame *f);
297 static void ns_judge_scroll_bars (struct frame *f);
298 void x_set_frame_alpha (struct frame *f);
300 /* unused variables needed for compatibility reasons */
301 int x_use_underline_position_properties, x_underline_at_descent_line;
302 /* FIXME: figure out what to do with underline_minimum_offset. */
305 /* ==========================================================================
309 ========================================================================== */
313 append2 (Lisp_Object list, Lisp_Object item)
314 /* --------------------------------------------------------------------------
315 Utility to append to a list
316 -------------------------------------------------------------------------- */
318 Lisp_Object array[2];
320 array[1] = Fcons (item, Qnil);
321 return Fnconc (2, &array[0]);
327 /* --------------------------------------------------------------------------
328 Used to allow emacs to find its resources under Emacs.app
329 Called from emacs.c at startup.
330 -------------------------------------------------------------------------- */
332 NSBundle *bundle = [NSBundle mainBundle];
333 NSString *binDir = [bundle bundlePath], *resourceDir = [bundle resourcePath];
334 NSString *resourcePath, *resourcePaths;
336 BOOL onWindows = NO; /* how do I determine this? */
337 NSString *pathSeparator = onWindows ? @";" : @":";
338 NSFileManager *fileManager = [NSFileManager defaultManager];
340 /*NSLog (@"ns_init_paths: '%@'\n%@\n", [[NSBundle mainBundle] bundlePath], [[NSBundle mainBundle] resourcePath]); */
342 /* get bindir from base */
343 range = [resourceDir rangeOfString: @"Contents"];
344 if (range.location != NSNotFound)
346 binDir = [binDir stringByAppendingPathComponent: @"Contents"];
348 binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
352 /* the following based on Andrew Choi's init_mac_osx_environment () */
353 if (!getenv ("EMACSLOADPATH"))
355 NSArray *paths = [resourceDir stringsByAppendingPaths:
356 [NSArray arrayWithObjects:
357 @"site-lisp", @"lisp", @"leim", nil]];
358 NSEnumerator *pathEnum = [paths objectEnumerator];
360 while (resourcePath = [pathEnum nextObject])
362 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
365 if ([resourcePaths length] > 0)
367 = [resourcePaths stringByAppendingString: pathSeparator];
369 = [resourcePaths stringByAppendingString: resourcePath];
372 if ([resourcePaths length] > 0)
373 setenv ("EMACSLOADPATH", [resourcePaths UTF8String], 1);
374 /*NSLog (@"loadPath: '%s'\n", resourcePaths); */
377 if (!getenv ("EMACSPATH"))
379 NSArray *paths = [binDir stringsByAppendingPaths:
380 [NSArray arrayWithObjects: @"bin",
382 NSEnumerator *pathEnum = [paths objectEnumerator];
384 while (resourcePath = [pathEnum nextObject])
386 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
389 if ([resourcePaths length] > 0)
391 = [resourcePaths stringByAppendingString: pathSeparator];
393 = [resourcePaths stringByAppendingString: resourcePath];
396 if ([resourcePaths length] > 0)
397 setenv ("EMACSPATH", [resourcePaths UTF8String], 1);
400 resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
401 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
405 if (!getenv ("EMACSDATA"))
406 setenv ("EMACSDATA", [resourcePath UTF8String], 1);
407 if (!getenv ("EMACSDOC"))
408 setenv ("EMACSDOC", [resourcePath UTF8String], 1);
412 if (!getenv ("INFOPATH"))
414 resourcePath = [resourceDir stringByAppendingPathComponent: @"info"];
415 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
417 setenv ("INFOPATH", [[resourcePath stringByAppendingString: @":"]
419 /* Note, extra colon needed to cause merge w/later user additions. */
425 timeval_subtract (struct timeval *result, struct timeval x, struct timeval y)
426 /* --------------------------------------------------------------------------
427 Subtract the `struct timeval' values X and Y, storing the result in RESULT.
428 Return 1 if the difference is negative, otherwise 0.
429 -------------------------------------------------------------------------- */
431 /* Perform the carry for the later subtraction by updating y.
432 This is safer because on some systems
433 the tv_sec member is unsigned. */
434 if (x.tv_usec < y.tv_usec)
436 int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
437 y.tv_usec -= 1000000 * nsec;
440 if (x.tv_usec - y.tv_usec > 1000000)
442 int nsec = (y.tv_usec - x.tv_usec) / 1000000;
443 y.tv_usec += 1000000 * nsec;
447 /* Compute the time remaining to wait. tv_usec is certainly positive. */
448 result->tv_sec = x.tv_sec - y.tv_sec;
449 result->tv_usec = x.tv_usec - y.tv_usec;
451 /* Return indication of whether the result should be considered negative. */
452 return x.tv_sec < y.tv_sec;
456 ns_timeout (int usecs)
457 /* --------------------------------------------------------------------------
458 Blocking timer utility used by ns_ring_bell
459 -------------------------------------------------------------------------- */
461 struct timeval wakeup;
463 EMACS_GET_TIME (wakeup);
465 /* Compute time to wait until, propagating carry from usecs. */
466 wakeup.tv_usec += usecs;
467 wakeup.tv_sec += (wakeup.tv_usec / 1000000);
468 wakeup.tv_usec %= 1000000;
470 /* Keep waiting until past the time wakeup. */
473 struct timeval timeout;
475 EMACS_GET_TIME (timeout);
477 /* In effect, timeout = wakeup - timeout.
478 Break if result would be negative. */
479 if (timeval_subtract (&timeout, wakeup, timeout))
482 /* Try to wait that long--but we might wake up sooner. */
483 select (0, NULL, NULL, NULL, &timeout);
489 ns_release_object (void *obj)
490 /* --------------------------------------------------------------------------
491 Release an object (callable from C)
492 -------------------------------------------------------------------------- */
499 ns_retain_object (void *obj)
500 /* --------------------------------------------------------------------------
501 Retain an object (callable from C)
502 -------------------------------------------------------------------------- */
509 ns_alloc_autorelease_pool ()
510 /* --------------------------------------------------------------------------
511 Allocate a pool for temporary objects (callable from C)
512 -------------------------------------------------------------------------- */
514 return [[NSAutoreleasePool alloc] init];
519 ns_release_autorelease_pool (void *pool)
520 /* --------------------------------------------------------------------------
521 Free a pool and temporary objects it refers to (callable from C)
522 -------------------------------------------------------------------------- */
524 ns_release_object (pool);
529 /* ==========================================================================
531 Focus (clipping) and screen update
533 ========================================================================== */
536 ns_resize_handle_rect (NSWindow *window)
538 NSRect r = [window frame];
539 r.origin.x = r.size.width - RESIZE_HANDLE_SIZE;
541 r.size.width = r.size.height = RESIZE_HANDLE_SIZE;
547 ns_update_begin (struct frame *f)
548 /* --------------------------------------------------------------------------
549 Prepare for a grouped sequence of drawing calls
550 external (RIF) call; whole frame, called before update_window_begin
551 -------------------------------------------------------------------------- */
553 NSView *view = FRAME_NS_VIEW (f);
554 NSTRACE (ns_update_begin);
556 ns_updating_frame = f;
559 #ifdef NS_IMPL_GNUSTEP
560 uRect = NSMakeRect (0, 0, 0, 0);
566 ns_update_window_begin (struct window *w)
567 /* --------------------------------------------------------------------------
568 Prepare for a grouped sequence of drawing calls
569 external (RIF) call; for one window, called after update_begin
570 -------------------------------------------------------------------------- */
572 struct frame *f = XFRAME (WINDOW_FRAME (w));
573 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
574 NSTRACE (ns_update_window_begin);
577 set_output_cursor (&w->cursor);
581 if (f == dpyinfo->mouse_face_mouse_frame)
583 /* Don't do highlighting for mouse motion during the update. */
584 dpyinfo->mouse_face_defer = 1;
586 /* If the frame needs to be redrawn,
587 simply forget about any prior mouse highlighting. */
588 if (FRAME_GARBAGED_P (f))
589 dpyinfo->mouse_face_window = Qnil;
591 /* (further code for mouse faces ifdef'd out in other terms elided) */
599 ns_update_window_end (struct window *w, int cursor_on_p,
600 int mouse_face_overwritten_p)
601 /* --------------------------------------------------------------------------
602 Finished a grouped sequence of drawing calls
603 external (RIF) call; for one window called before update_end
604 -------------------------------------------------------------------------- */
606 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (XFRAME (w->frame));
608 /* note: this fn is nearly identical in all terms */
609 if (!w->pseudo_window_p)
614 display_and_set_cursor (w, 1,
615 output_cursor.hpos, output_cursor.vpos,
616 output_cursor.x, output_cursor.y);
618 if (draw_window_fringes (w, 1))
619 x_draw_vertical_border (w);
624 /* If a row with mouse-face was overwritten, arrange for
625 frame_up_to_date to redisplay the mouse highlight. */
626 if (mouse_face_overwritten_p)
628 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
629 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
630 dpyinfo->mouse_face_window = Qnil;
633 updated_window = NULL;
634 NSTRACE (update_window_end);
639 ns_update_end (struct frame *f)
640 /* --------------------------------------------------------------------------
641 Finished a grouped sequence of drawing calls
642 external (RIF) call; for whole frame, called after update_window_end
643 -------------------------------------------------------------------------- */
645 NSView *view = FRAME_NS_VIEW (f);
647 /* if (f == FRAME_NS_DISPLAY_INFO (f)->mouse_face_mouse_frame) */
648 FRAME_NS_DISPLAY_INFO (f)->mouse_face_defer = 0;
652 #ifdef NS_IMPL_GNUSTEP
653 /* trigger flush only in the rectangle we tracked as being drawn */
654 [view unlockFocusNeedsFlush: NO];
655 /*fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", uRect.origin.x, uRect.origin.y, uRect.size.width, uRect.size.height); */
656 [view lockFocusInRect: uRect];
660 [[view window] flushWindow];
663 ns_updating_frame = NULL;
664 NSTRACE (ns_update_end);
669 ns_flush (struct frame *f)
670 /* --------------------------------------------------------------------------
672 NS impl is no-op since currently we flush in ns_update_end and elsewhere
673 -------------------------------------------------------------------------- */
680 ns_focus (struct frame *f, NSRect *r, int n)
681 /* --------------------------------------------------------------------------
682 Internal: Focus on given frame. During small local updates this is used to
683 draw, however during large updates, ns_update_begin and ns_update_end are
684 called to wrap the whole thing, in which case these calls are stubbed out.
685 Except, on GNUstep, we accumulate the rectangle being drawn into, because
686 the back end won't do this automatically, and will just end up flushing
688 -------------------------------------------------------------------------- */
690 // NSTRACE (ns_focus);
691 #ifdef NS_IMPL_GNUSTEP
694 u = NSUnionRect (r[0], r[1]);
699 fprintf (stderr, "focus: %d", c++);
700 if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
701 fprintf (stderr, "\n"); */
703 if (f != ns_updating_frame)
705 NSView *view = FRAME_NS_VIEW (f);
706 if (view != focus_view)
708 if (focus_view != NULL)
710 [focus_view unlockFocus];
711 [[focus_view window] flushWindow];
716 #ifdef NS_IMPL_GNUSTEP
717 r ? [view lockFocusInRect: u] : [view lockFocus];
722 /*if (view) debug_lock++; */
724 #ifdef NS_IMPL_GNUSTEP
727 /* more than one rect being drawn into */
730 [view unlockFocus]; /* add prev rect to redraw list */
731 [view lockFocusInRect: u]; /* focus for draw in new rect */
736 #ifdef NS_IMPL_GNUSTEP
739 /* in batch mode, but in GNUstep must still track rectangles explicitly */
740 uRect = (r ? NSUnionRect (uRect, u) : [FRAME_NS_VIEW (f) visibleRect]);
747 [[NSGraphicsContext currentContext] saveGraphicsState];
749 NSRectClipList (r, 2);
758 ns_unfocus (struct frame *f)
759 /* --------------------------------------------------------------------------
760 Internal: Remove focus on given frame
761 -------------------------------------------------------------------------- */
763 // NSTRACE (ns_unfocus);
767 [[NSGraphicsContext currentContext] restoreGraphicsState];
771 if (f != ns_updating_frame)
773 if (focus_view != NULL)
775 [focus_view unlockFocus];
776 [[focus_view window] flushWindow];
785 ns_clip_to_row (struct window *w, struct glyph_row *row, int area, BOOL gc)
786 /* --------------------------------------------------------------------------
787 Internal (but parallels other terms): Focus drawing on given row
788 -------------------------------------------------------------------------- */
790 struct frame *f = XFRAME (WINDOW_FRAME (w));
792 int window_x, window_y, window_width;
794 window_box (w, area, &window_x, &window_y, &window_width, 0);
796 clip_rect.origin.x = window_x - FRAME_INTERNAL_BORDER_WIDTH (f);
797 clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
798 clip_rect.origin.y = max (clip_rect.origin.y, window_y);
799 clip_rect.size.width = window_width + 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
800 clip_rect.size.height = row->visible_height;
802 /* allow a full-height row at the top when requested
803 (used to draw fringe all the way through internal border area) */
804 if (gc && clip_rect.origin.y < 5)
806 clip_rect.origin.y -= FRAME_INTERNAL_BORDER_WIDTH (f);
807 clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
810 /* likewise at bottom */
812 FRAME_PIXEL_HEIGHT (f) - (clip_rect.origin.y + clip_rect.size.height) < 5)
813 clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
815 ns_focus (f, &clip_rect, 1);
821 /* --------------------------------------------------------------------------
823 -------------------------------------------------------------------------- */
825 NSTRACE (ns_ring_bell);
828 NSAutoreleasePool *pool;
829 struct frame *frame = SELECTED_FRAME ();
833 pool = [[NSAutoreleasePool alloc] init];
835 view = FRAME_NS_VIEW (frame);
839 NSPoint dim = NSMakePoint (128, 128);
842 r.origin.x += (r.size.width - dim.x) / 2;
843 r.origin.y += (r.size.height - dim.y) / 2;
844 r.size.width = dim.x;
845 r.size.height = dim.y;
846 surr = NSInsetRect (r, -2, -2);
847 ns_focus (frame, &surr, 1);
848 [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
849 [ns_lookup_indexed_color (NS_FACE_FOREGROUND
850 (FRAME_DEFAULT_FACE (frame)), frame) set];
852 [[view window] flushWindow];
854 [[view window] restoreCachedImage];
855 [[view window] flushWindow];
869 ns_reset_terminal_modes (struct terminal *terminal)
870 /* Externally called as hook */
872 NSTRACE (ns_reset_terminal_modes);
876 ns_set_terminal_modes (struct terminal *terminal)
877 /* Externally called as hook */
879 NSTRACE (ns_set_terminal_modes);
884 /* ==========================================================================
886 Frame / window manager related functions
888 ========================================================================== */
892 ns_raise_frame (struct frame *f)
893 /* --------------------------------------------------------------------------
894 Bring window to foreground and make it active
895 -------------------------------------------------------------------------- */
897 NSView *view = FRAME_NS_VIEW (f);
900 FRAME_SAMPLE_VISIBILITY (f);
901 if (FRAME_VISIBLE_P (f))
903 [[view window] makeKeyAndOrderFront: NSApp];
910 ns_lower_frame (struct frame *f)
911 /* --------------------------------------------------------------------------
913 -------------------------------------------------------------------------- */
915 NSView *view = FRAME_NS_VIEW (f);
918 [[view window] orderBack: NSApp];
924 ns_frame_raise_lower (struct frame *f, int raise)
925 /* --------------------------------------------------------------------------
927 -------------------------------------------------------------------------- */
929 NSTRACE (ns_frame_raise_lower);
939 ns_frame_rehighlight (struct frame *frame)
940 /* --------------------------------------------------------------------------
941 External (hook): called on things like window switching within frame
942 -------------------------------------------------------------------------- */
944 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
945 struct frame *old_highlight = dpyinfo->x_highlight_frame;
947 NSTRACE (ns_frame_rehighlight);
948 if (dpyinfo->x_focus_frame)
950 dpyinfo->x_highlight_frame
951 = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
952 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
953 : dpyinfo->x_focus_frame);
954 if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
956 FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
957 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
961 dpyinfo->x_highlight_frame = 0;
963 if (dpyinfo->x_highlight_frame &&
964 dpyinfo->x_highlight_frame != old_highlight)
968 x_update_cursor (old_highlight, 1);
969 x_set_frame_alpha (old_highlight);
971 if (dpyinfo->x_highlight_frame)
973 x_update_cursor (dpyinfo->x_highlight_frame, 1);
974 x_set_frame_alpha (dpyinfo->x_highlight_frame);
981 x_make_frame_visible (struct frame *f)
982 /* --------------------------------------------------------------------------
983 External: Show the window (X11 semantics)
984 -------------------------------------------------------------------------- */
986 NSTRACE (x_make_frame_visible);
987 /* XXX: at some points in past this was not needed, as the only place that
988 called this (frame.c:Fraise_frame ()) also called raise_lower;
989 if this ends up the case again, comment this out again. */
990 if (!FRAME_VISIBLE_P (f))
992 f->async_visible = 1;
999 x_make_frame_invisible (struct frame *f)
1000 /* --------------------------------------------------------------------------
1001 External: Hide the window (X11 semantics)
1002 -------------------------------------------------------------------------- */
1004 NSView * view = FRAME_NS_VIEW (f);
1005 NSTRACE (x_make_frame_invisible);
1007 [[view window] orderOut: NSApp];
1008 f->async_visible = 0;
1009 f->async_iconified = 0;
1014 x_iconify_frame (struct frame *f)
1015 /* --------------------------------------------------------------------------
1016 External: Iconify window
1017 -------------------------------------------------------------------------- */
1019 NSView * view = FRAME_NS_VIEW (f);
1020 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1021 NSTRACE (x_iconify_frame);
1024 if (dpyinfo->x_highlight_frame == f)
1025 dpyinfo->x_highlight_frame = 0;
1027 if ([[view window] windowNumber] <= 0)
1029 /* the window is still deferred. Make it very small, bring it
1030 on screen and order it out. */
1031 NSRect s = { { 100, 100}, {0, 0} };
1033 t = [[view window] frame];
1034 [[view window] setFrame: s display: NO];
1035 [[view window] orderBack: NSApp];
1036 [[view window] orderOut: NSApp];
1037 [[view window] setFrame: t display: NO];
1039 [[view window] miniaturize: NSApp];
1044 x_destroy_window (struct frame *f)
1045 /* --------------------------------------------------------------------------
1046 External: Delete the window
1047 -------------------------------------------------------------------------- */
1049 NSView *view = FRAME_NS_VIEW (f);
1050 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1051 NSTRACE (x_destroy_window);
1054 [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1058 free_frame_menubar (f);
1060 if (FRAME_FACE_CACHE (f))
1061 free_frame_faces (f);
1063 if (f == dpyinfo->x_focus_frame)
1064 dpyinfo->x_focus_frame = 0;
1065 if (f == dpyinfo->x_highlight_frame)
1066 dpyinfo->x_highlight_frame = 0;
1067 if (f == dpyinfo->mouse_face_mouse_frame)
1069 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
1070 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
1071 dpyinfo->mouse_face_window = Qnil;
1072 dpyinfo->mouse_face_deferred_gc = 0;
1073 dpyinfo->mouse_face_mouse_frame = 0;
1076 xfree (f->output_data.ns);
1078 [[view window] close];
1087 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1088 /* --------------------------------------------------------------------------
1089 External: Position the window
1090 -------------------------------------------------------------------------- */
1093 NSView *view = FRAME_NS_VIEW (f);
1095 NSTRACE (x_set_offset);
1101 #ifdef NS_IMPL_GNUSTEP
1103 f->left_pos = 100; /* don't overlap menu */
1105 if (view != nil && (screen = [[view window] screen]))
1106 [[view window] setFrameTopLeftPoint:
1107 NSMakePoint (SCREENMAXBOUND (f->left_pos),
1108 SCREENMAXBOUND ([screen frame].size.height
1109 - NS_TOP_POS (f)))];
1115 x_set_window_size (struct frame *f, int change_grav, int cols, int rows)
1116 /* --------------------------------------------------------------------------
1117 Adjust window pixel size based on given character grid size
1118 Impl is a bit more complex than other terms, need to do some
1119 internal clipping and also pay attention to screen constraints.
1120 -------------------------------------------------------------------------- */
1122 EmacsView *view = FRAME_NS_VIEW (f);
1123 EmacsToolbar *toolbar = [view toolbar];
1124 NSWindow *window = [view window];
1125 NSScreen *screen = [window screen];
1126 NSRect wr = [window frame];
1127 int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1128 int pixelwidth, pixelheight;
1129 static int oldRows, oldCols, oldFontWidth, oldFontHeight;
1131 static struct frame *oldF;
1133 NSTRACE (x_set_window_size);
1137 && rows == oldRows && cols == oldCols
1138 && oldFontWidth == FRAME_COLUMN_WIDTH (f)
1139 && oldFontHeight == FRAME_LINE_HEIGHT (f)
1143 /*fprintf (stderr, "\tsetWindowSize: %d x %d, font size %d x %d\n", cols, rows, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f)); */
1147 check_frame_size (f, &rows, &cols);
1151 oldFontWidth = FRAME_COLUMN_WIDTH (f);
1152 oldFontHeight = FRAME_LINE_HEIGHT (f);
1155 f->scroll_bar_actual_width = NS_SCROLL_BAR_WIDTH (f);
1156 compute_fringe_widths (f, 0);
1158 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols);
1159 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
1161 /* If we have a toolbar, take its height into account. */
1163 FRAME_NS_TOOLBAR_HEIGHT (f) =
1164 /* XXX: GNUstep has not yet implemented the first method below, added
1165 in Panther, however the second is incorrect under Cocoa. */
1166 #ifdef NS_IMPL_COCOA
1167 NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1168 /* NOTE: previously this would generate wrong result if toolbar not
1169 yet displayed and fixing toolbar_height=32 helped, but
1170 now (200903) seems no longer needed */
1172 NSHeight ([NSWindow frameRectForContentRect: NSMakeRect (0, 0, 0, 0)
1173 styleMask: [window styleMask]])
1175 - FRAME_NS_TITLEBAR_HEIGHT (f);
1177 FRAME_NS_TOOLBAR_HEIGHT (f) = 0;
1179 wr.size.width = pixelwidth + f->border_width;
1180 wr.size.height = pixelheight + FRAME_NS_TITLEBAR_HEIGHT (f)
1181 + FRAME_NS_TOOLBAR_HEIGHT (f);
1183 /* constrain to screen if we can */
1186 NSSize sz = [screen visibleFrame].size;
1187 NSSize ez = { wr.size.width - sz.width, wr.size.height - sz.height };
1190 int cr = ez.width / FRAME_COLUMN_WIDTH (f) + 1;
1193 wr.size.width -= cr * FRAME_COLUMN_WIDTH (f);
1194 pixelwidth -= cr * FRAME_COLUMN_WIDTH (f);
1198 int rr = ez.height / FRAME_LINE_HEIGHT (f) + 1;
1201 wr.size.height -= rr * FRAME_LINE_HEIGHT (f);
1202 pixelheight -= rr * FRAME_LINE_HEIGHT (f);
1204 wr.origin.x = f->left_pos;
1205 wr.origin.y = [screen frame].size.height - NS_TOP_POS (f)
1209 [view setRows: rows andColumns: cols];
1210 [window setFrame: wr display: YES];
1212 /*fprintf (stderr, "\tx_set_window_size %d, %d\t%d, %d\n", cols, rows, pixelwidth, pixelheight); */
1214 /* This is a trick to compensate for Emacs' managing the scrollbar area
1215 as a fixed number of standard character columns. Instead of leaving
1216 blank space for the extra, we chopped it off above. Now for
1217 left-hand scrollbars, we shift all rendering to the left by the
1218 difference between the real width and Emacs' imagined one. For
1219 right-hand bars, don't worry about it since the extra is never used.
1220 (Obviously doesn't work for vertically split windows tho..) */
1221 NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1222 ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1223 - NS_SCROLL_BAR_WIDTH (f), 0)
1224 : NSMakePoint (0, 0);
1225 [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1226 [view setBoundsOrigin: origin];
1228 change_frame_size (f, rows, cols, 0, 1, 0); /* pretend, delay, safe */
1229 FRAME_PIXEL_WIDTH (f) = pixelwidth;
1230 FRAME_PIXEL_HEIGHT (f) = pixelheight;
1231 /* SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */
1233 mark_window_cursors_off (XWINDOW (f->root_window));
1234 cancel_mouse_face (f);
1241 /* ==========================================================================
1245 ========================================================================== */
1249 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1251 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1252 return color_table->colors[idx];
1257 ns_index_color (NSColor *color, struct frame *f)
1259 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1263 if (!color_table->colors)
1265 color_table->size = NS_COLOR_CAPACITY;
1266 color_table->avail = 1; /* skip idx=0 as marker */
1268 = (NSColor **)xmalloc (color_table->size * sizeof (NSColor *));
1269 color_table->empty_indices = [[NSMutableSet alloc] init];
1272 /* do we already have this color ? */
1275 for (i = 1; i < color_table->avail; i++)
1277 if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1279 [color_table->colors[i] retain];
1285 if ([color_table->empty_indices count] > 0)
1287 index = [color_table->empty_indices anyObject];
1288 [color_table->empty_indices removeObject: index];
1289 idx = [index unsignedIntValue];
1293 if (color_table->avail == color_table->size)
1295 color_table->size += NS_COLOR_CAPACITY;
1297 = (NSColor **)xrealloc (color_table->colors,
1298 color_table->size * sizeof (NSColor *));
1300 idx = color_table->avail++;
1303 color_table->colors[idx] = color;
1305 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1311 ns_free_indexed_color (unsigned long idx, struct frame *f)
1313 struct ns_color_table *color_table;
1320 color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1322 if (idx <= 0 || idx >= color_table->size) {
1323 message1("ns_free_indexed_color: Color index out of range.\n");
1327 index = [NSNumber numberWithUnsignedInt: idx];
1328 if ([color_table->empty_indices containsObject: index]) {
1329 message1("ns_free_indexed_color: attempt to free already freed color.\n");
1333 color = color_table->colors[idx];
1335 color_table->colors[idx] = nil;
1336 [color_table->empty_indices addObject: [NSNumber numberWithUnsignedInt: idx]];
1337 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1342 ns_get_color (const char *name, NSColor **col)
1343 /* --------------------------------------------------------------------------
1345 /* --------------------------------------------------------------------------
1346 /* On *Step, we recognize several color formats, in addition to a catalog
1347 of colors found in the file Emacs.clr. Color formats include:
1348 - #rrggbb where rr, gg, bb specify red, green and blue in hex. */
1350 NSColor * new = nil;
1351 const char *hex = NULL;
1352 enum { rgb } color_space;
1353 NSString *nsname = [NSString stringWithUTF8String: name];
1355 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1358 if ([nsname isEqualToString: @"ns_selection_color"])
1360 nsname = ns_selection_color;
1361 name = [ns_selection_color UTF8String];
1364 if (name[0] == '0' || name[0] == '1' || name[0] == '.')
1367 NSScanner *scanner = [NSScanner scannerWithString: nsname];
1369 [scanner scanFloat: &r];
1370 [scanner scanFloat: &g];
1371 [scanner scanFloat: &b];
1372 *col = [NSColor colorWithCalibratedRed: r green: g blue: b alpha: 1.0];
1377 if (name[0] == '#') /* X11 format */
1383 /* Direct colors (hex values) */
1386 unsigned long long color = 0;
1387 if (sscanf (hex, "%x", &color))
1389 float f1, f2, f3, f4;
1390 /* Assume it's either 1 byte or 2 per channel... */
1391 if (strlen(hex) > 8) {
1392 f1 = ((color >> 48) & 0xffff) / 65535.0;
1393 f2 = ((color >> 32) & 0xffff) / 65535.0;
1394 f3 = ((color >> 16) & 0xffff) / 65535.0;
1395 f4 = ((color ) & 0xffff) / 65535.0;
1397 f1 = ((color >> 24) & 0xff) / 255.0;
1398 f2 = ((color >> 16) & 0xff) / 255.0;
1399 f3 = ((color >> 8) & 0xff) / 255.0;
1400 f4 = ((color ) & 0xff) / 255.0;
1403 switch (color_space)
1406 *col = [NSColor colorWithCalibratedRed: f2
1412 *col = [*col colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1418 /* Otherwise, color is expected to be from a list */
1420 NSEnumerator *lenum, *cenum;
1424 #ifdef NS_IMPL_GNUSTEP
1425 /* XXX: who is wrong, the requestor or the implementation? */
1426 if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1428 nsname = @"highlightColor";
1431 lenum = [[NSColorList availableColorLists] objectEnumerator];
1432 while ( (clist = [lenum nextObject]) && new == nil)
1434 cenum = [[clist allKeys] objectEnumerator];
1435 while ( (name = [cenum nextObject]) && new == nil )
1437 if ([name compare: nsname
1438 options: NSCaseInsensitiveSearch] == NSOrderedSame )
1439 new = [clist colorWithKey: name];
1445 *col = [new colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1447 NSLog (@"Failed to find color '%@'", nsname); */
1454 ns_get_color_default (const char *name, NSColor *dflt)
1455 /* --------------------------------------------------------------------------
1456 Parse a color or use a default value
1457 -------------------------------------------------------------------------- */
1461 if (ns_get_color (name, &col))
1469 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1470 /* --------------------------------------------------------------------------
1471 Convert a Lisp string object to a NS color
1472 -------------------------------------------------------------------------- */
1474 NSTRACE (ns_lisp_to_color);
1475 if (STRINGP (color))
1476 return ns_get_color (SDATA (color), col);
1477 else if (SYMBOLP (color))
1478 return ns_get_color (SDATA (SYMBOL_NAME (color)), col);
1484 ns_color_to_lisp (NSColor *col)
1485 /* --------------------------------------------------------------------------
1486 Convert a color to a lisp string with the RGB equivalent
1487 -------------------------------------------------------------------------- */
1489 float red, green, blue, alpha, gray;
1492 NSTRACE (ns_color_to_lisp);
1495 if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1497 if ((str =[[col colorNameComponent] UTF8String]))
1500 return build_string ((char *)str);
1503 [[col colorUsingColorSpaceName: NSCalibratedRGBColorSpace]
1504 getRed: &red green: &green blue: &blue alpha: &alpha];
1505 if (red ==green && red ==blue)
1507 [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1508 getWhite: &gray alpha: &alpha];
1509 snprintf (buf, sizeof (buf), "#%02.2lx%02.2lx%02.2lx",
1510 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1512 return build_string (buf);
1515 snprintf (buf, sizeof (buf), "#%02.2lx%02.2lx%02.2lx",
1516 lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1519 return build_string (buf);
1524 ns_query_color(void *col, XColor *color_def, int setPixel)
1525 /* --------------------------------------------------------------------------
1526 Get ARGB values out of NSColor col and put them into color_def.
1527 If setPixel, set the pixel to a concatenated version.
1528 and set color_def pixel to the resulting index.
1529 -------------------------------------------------------------------------- */
1533 [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1534 color_def->red = r * 65535;
1535 color_def->green = g * 65535;
1536 color_def->blue = b * 65535;
1538 if (setPixel == YES)
1540 = ARGB_TO_ULONG((int)(a*255),
1541 (int)(r*255), (int)(g*255), (int)(b*255));
1546 ns_defined_color (struct frame *f, char *name, XColor *color_def, int alloc,
1548 /* --------------------------------------------------------------------------
1549 Return 1 if named color found, and set color_def rgb accordingly.
1550 If makeIndex and alloc are nonzero put the color in the color_table,
1551 and set color_def pixel to the resulting index.
1552 If makeIndex is zero, set color_def pixel to ARGB.
1553 Return 0 if not found
1554 -------------------------------------------------------------------------- */
1557 int notFound = ns_get_color (name, &temp);
1559 NSTRACE (ns_defined_color);
1564 if (makeIndex && alloc)
1565 color_def->pixel = ns_index_color(temp, f); /* [temp retain]; */
1567 ns_query_color (temp, color_def, !makeIndex);
1574 ns_get_rgb_color (struct frame *f, float r, float g, float b, float a)
1575 /* --------------------------------------------------------------------------
1576 return an autoreleased RGB color
1577 -------------------------------------------------------------------------- */
1579 /*static int c = 1; fprintf (stderr, "color request %d\n", c++); */
1580 if (r < 0.0) r = 0.0;
1581 else if (r > 1.0) r = 1.0;
1582 if (g < 0.0) g = 0.0;
1583 else if (g > 1.0) g = 1.0;
1584 if (b < 0.0) b = 0.0;
1585 else if (b > 1.0) b = 1.0;
1586 if (a < 0.0) a = 0.0;
1587 else if (a > 1.0) a = 1.0;
1588 return (unsigned long) ns_index_color(
1589 [NSColor colorWithCalibratedRed: r green: g blue: b alpha: a], f);
1594 x_set_frame_alpha (struct frame *f)
1595 /* --------------------------------------------------------------------------
1596 change the entire-frame transparency
1597 -------------------------------------------------------------------------- */
1599 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1600 EmacsView *view = FRAME_NS_VIEW (f);
1602 double alpha_min = 1.0;
1604 if (dpyinfo->x_highlight_frame == f)
1605 alpha = f->alpha[0];
1607 alpha = f->alpha[1];
1609 if (FLOATP (Vframe_alpha_lower_limit))
1610 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1611 else if (INTEGERP (Vframe_alpha_lower_limit))
1612 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1616 else if (1.0 < alpha)
1618 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1621 #ifdef NS_IMPL_COCOA
1622 [[view window] setAlphaValue: alpha];
1627 /* ==========================================================================
1631 ========================================================================== */
1635 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1636 /* --------------------------------------------------------------------------
1637 Programmatically reposition mouse pointer in pixel coordinates
1638 -------------------------------------------------------------------------- */
1640 NSTRACE (x_set_mouse_pixel_position);
1643 /* FIXME: this does not work, and what about GNUstep? */
1644 #ifdef NS_IMPL_COCOA
1645 [FRAME_NS_VIEW (f) lockFocus];
1646 PSsetmouse ((float)pix_x, (float)pix_y);
1647 [FRAME_NS_VIEW (f) unlockFocus];
1654 x_set_mouse_position (struct frame *f, int h, int v)
1655 /* --------------------------------------------------------------------------
1656 Programmatically reposition mouse pointer in character coordinates
1657 -------------------------------------------------------------------------- */
1661 pix_x = FRAME_COL_TO_PIXEL_X (f, h) + FRAME_COLUMN_WIDTH (f) / 2;
1662 pix_y = FRAME_LINE_TO_PIXEL_Y (f, v) + FRAME_LINE_HEIGHT (f) / 2;
1664 if (pix_x < 0) pix_x = 0;
1665 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
1667 if (pix_y < 0) pix_y = 0;
1668 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
1670 x_set_mouse_pixel_position (f, pix_x, pix_y);
1675 note_mouse_movement (struct frame *frame, float x, float y)
1676 /* ------------------------------------------------------------------------
1677 Called by EmacsView on mouseMovement events. Passes on
1678 to emacs mainstream code if we moved off of a rect of interest
1679 known as last_mouse_glyph.
1680 ------------------------------------------------------------------------ */
1682 // NSTRACE (note_mouse_movement);
1684 XSETFRAME (last_mouse_motion_frame, frame);
1686 /* Note, this doesn't get called for enter/leave, since we don't have a
1687 position. Those are taken care of in the corresponding NSView methods. */
1689 /* has movement gone beyond last rect we were tracking? */
1690 if (x < last_mouse_glyph.origin.x ||
1691 x >= (last_mouse_glyph.origin.x + last_mouse_glyph.size.width) ||
1692 y < last_mouse_glyph.origin.y ||
1693 y >= (last_mouse_glyph.origin.y + last_mouse_glyph.size.height))
1695 ns_update_begin(frame);
1696 frame->mouse_moved = 1;
1697 note_mouse_highlight (frame, x, y);
1698 remember_mouse_glyph (frame, x, y, &last_mouse_glyph);
1699 ns_update_end(frame);
1708 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1709 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1710 unsigned long *time)
1711 /* --------------------------------------------------------------------------
1712 External (hook): inform emacs about mouse position and hit parts.
1713 If a scrollbar is being dragged, set bar_window, part, x, y, time.
1714 x & y should be position in the scrollbar (the whole bar, not the handle)
1715 and length of scrollbar respectively
1716 -------------------------------------------------------------------------- */
1721 Lisp_Object frame, tail;
1723 struct ns_display_info *dpyinfo;
1725 NSTRACE (ns_mouse_position);
1729 fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1733 dpyinfo = FRAME_NS_DISPLAY_INFO (*fp);
1737 if (last_mouse_scroll_bar != nil && insist == 0)
1739 /* TODO: we do not use this path at the moment because drag events will
1740 go directly to the EmacsScroller. Leaving code in for now. */
1741 [last_mouse_scroll_bar getMouseMotionPart: (int *)part window: bar_window
1743 if (time) *time = last_mouse_movement_time;
1744 last_mouse_scroll_bar = nil;
1748 /* Clear the mouse-moved flag for every frame on this display. */
1749 FOR_EACH_FRAME (tail, frame)
1750 if (FRAME_NS_P (XFRAME (frame))
1751 && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1752 XFRAME (frame)->mouse_moved = 0;
1754 last_mouse_scroll_bar = nil;
1755 if (last_mouse_frame && FRAME_LIVE_P (last_mouse_frame))
1756 f = last_mouse_frame;
1758 f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame
1759 : SELECTED_FRAME ();
1761 if (f && f->output_data.ns) /* TODO: 2nd check no longer needed? */
1763 view = FRAME_NS_VIEW (*fp);
1765 position = [[view window] mouseLocationOutsideOfEventStream];
1766 position = [view convertPoint: position fromView: nil];
1767 remember_mouse_glyph (f, position.x, position.y, &last_mouse_glyph);
1768 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1770 if (bar_window) *bar_window = Qnil;
1771 if (part) *part = 0; /*scroll_bar_handle; */
1773 if (x) XSETINT (*x, lrint (position.x));
1774 if (y) XSETINT (*y, lrint (position.y));
1775 if (time) *time = last_mouse_movement_time;
1785 ns_frame_up_to_date (struct frame *f)
1786 /* --------------------------------------------------------------------------
1787 External (hook): Fix up mouse highlighting right after a full update.
1788 Some highlighting was deferred if GC was happening during
1789 note_mouse_highlight (), while other highlighting was deferred for update.
1790 -------------------------------------------------------------------------- */
1792 NSTRACE (ns_frame_up_to_date);
1796 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1797 if ((dpyinfo->mouse_face_deferred_gc||f ==dpyinfo->mouse_face_mouse_frame)
1798 /*&& dpyinfo->mouse_face_mouse_frame*/)
1802 if (dpyinfo->mouse_face_mouse_frame)
1803 note_mouse_highlight (dpyinfo->mouse_face_mouse_frame,
1804 dpyinfo->mouse_face_mouse_x,
1805 dpyinfo->mouse_face_mouse_y);
1806 dpyinfo->mouse_face_deferred_gc = 0;
1815 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1816 /* --------------------------------------------------------------------------
1817 External (RIF): set frame mouse pointer type.
1818 -------------------------------------------------------------------------- */
1820 NSTRACE (ns_define_frame_cursor);
1821 if (FRAME_POINTER_TYPE (f) != cursor)
1823 EmacsView *view = FRAME_NS_VIEW (f);
1824 FRAME_POINTER_TYPE (f) = cursor;
1825 [[view window] invalidateCursorRectsForView: view];
1831 /* ==========================================================================
1835 ========================================================================== */
1839 ns_convert_key (unsigned code)
1840 /* --------------------------------------------------------------------------
1841 Internal call used by NSView-keyDown.
1842 -------------------------------------------------------------------------- */
1844 const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym)
1845 / sizeof (convert_ns_to_X_keysym[0]));
1847 /* An array would be faster, but less easy to read. */
1848 for (keysym = 0; keysym < last_keysym; keysym += 2)
1849 if (code == convert_ns_to_X_keysym[keysym])
1850 return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
1852 /* if decide to use keyCode and Carbon table, use this line:
1853 return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
1858 x_get_keysym_name (int keysym)
1859 /* --------------------------------------------------------------------------
1860 Called by keyboard.c. Not sure if the return val is important, except
1862 -------------------------------------------------------------------------- */
1864 static char value[16];
1865 NSTRACE (x_get_keysym_name);
1866 sprintf (value, "%d", keysym);
1872 /* ==========================================================================
1874 Block drawing operations
1876 ========================================================================== */
1880 ns_redraw_scroll_bars (struct frame *f)
1884 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
1885 NSTRACE (ns_judge_scroll_bars);
1886 for (i =[subviews count]-1; i >= 0; i--)
1888 view = [subviews objectAtIndex: i];
1889 if (![view isKindOfClass: [EmacsScroller class]]) continue;
1896 ns_clear_frame (struct frame *f)
1897 /* --------------------------------------------------------------------------
1898 External (hook): Erase the entire frame
1899 -------------------------------------------------------------------------- */
1901 NSView *view = FRAME_NS_VIEW (f);
1904 NSTRACE (ns_clear_frame);
1908 /* comes on initial frame because we have
1909 after-make-frame-functions = select-frame */
1910 if (!FRAME_DEFAULT_FACE (f))
1913 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
1915 output_cursor.hpos = output_cursor.vpos = 0;
1916 output_cursor.x = -1;
1921 ns_focus (f, &r, 1);
1922 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
1926 #ifdef NS_IMPL_COCOA
1927 [[view window] display]; /* redraw resize handle */
1930 /* as of 2006/11 or so this is now needed */
1931 ns_redraw_scroll_bars (f);
1937 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
1938 /* --------------------------------------------------------------------------
1939 External (RIF): Clear section of frame
1940 -------------------------------------------------------------------------- */
1942 NSRect r = NSMakeRect (x, y, width, height);
1943 NSView *view = FRAME_NS_VIEW (f);
1944 struct face *face = FRAME_DEFAULT_FACE (f);
1949 NSTRACE (ns_clear_frame_area);
1951 r = NSIntersectionRect (r, [view frame]);
1952 ns_focus (f, &r, 1);
1953 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
1955 #ifdef NS_IMPL_COCOA
1957 /* clip out the resize handle */
1958 NSWindow *window = [FRAME_NS_VIEW (f) window];
1960 = [view convertRect: ns_resize_handle_rect (window) fromView: nil];
1962 ir = NSIntersectionRect (r, ir);
1963 if (NSIsEmptyRect (ir))
1969 #ifdef NS_IMPL_COCOA
1973 NSRect r1 = r, r2 = r; /* upper and lower non-intersecting */
1974 r1.size.height -= ir.size.height;
1975 r2.origin.y += r1.size.height;
1976 r2.size.width -= ir.size.width;
1977 r2.size.height = ir.size.height;
1990 ns_scroll_run (struct window *w, struct run *run)
1991 /* --------------------------------------------------------------------------
1992 External (RIF): Insert or delete n lines at line vpos
1993 -------------------------------------------------------------------------- */
1995 struct frame *f = XFRAME (w->frame);
1996 int x, y, width, height, from_y, to_y, bottom_y;
1998 NSTRACE (ns_scroll_run);
2000 /* begin copy from other terms */
2001 /* Get frame-relative bounding box of the text display area of W,
2002 without mode lines. Include in this box the left and right
2004 window_box (w, -1, &x, &y, &width, &height);
2006 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2007 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2008 bottom_y = y + height;
2012 /* Scrolling up. Make sure we don't copy part of the mode
2013 line at the bottom. */
2014 if (from_y + run->height > bottom_y)
2015 height = bottom_y - from_y;
2017 height = run->height;
2021 /* Scolling down. Make sure we don't copy over the mode line.
2023 if (to_y + run->height > bottom_y)
2024 height = bottom_y - to_y;
2026 height = run->height;
2028 /* end copy from other terms */
2039 NSRect srcRect = NSMakeRect (x, from_y, width, height);
2040 NSRect dstRect = NSMakeRect (x, to_y, width, height);
2041 NSPoint dstOrigin = NSMakePoint (x, to_y);
2043 ns_focus (f, &dstRect, 1);
2044 NSCopyBits (0, srcRect , dstOrigin);
2053 ns_after_update_window_line (struct glyph_row *desired_row)
2054 /* --------------------------------------------------------------------------
2055 External (RIF): preparatory to fringe update after text was updated
2056 -------------------------------------------------------------------------- */
2058 struct window *w = updated_window;
2062 NSTRACE (ns_after_update_window_line);
2064 /* begin copy from other terms */
2067 if (!desired_row->mode_line_p && !w->pseudo_window_p)
2068 desired_row->redraw_fringe_bitmaps_p = 1;
2070 /* When a window has disappeared, make sure that no rest of
2071 full-width rows stays visible in the internal border.
2072 Under NS this is drawn inside the fringes. */
2073 if (windows_or_buffers_changed
2074 && (f = XFRAME (w->frame),
2075 width = FRAME_INTERNAL_BORDER_WIDTH (f),
2077 && (height = desired_row->visible_height,
2080 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2082 /* Internal border is drawn below the tool bar. */
2083 if (WINDOWP (f->tool_bar_window)
2084 && w == XWINDOW (f->tool_bar_window))
2086 /* end copy from other terms */
2089 if (!desired_row->full_width_p)
2091 int x1 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2092 + WINDOW_LEFT_FRINGE_WIDTH (w);
2093 int x2 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2094 + FRAME_PIXEL_WIDTH (f) - NS_SCROLL_BAR_WIDTH (f)
2095 - WINDOW_RIGHT_FRINGE_WIDTH (w)
2096 - FRAME_INTERNAL_BORDER_WIDTH (f);
2097 ns_clear_frame_area (f, x1, y, width, height);
2098 ns_clear_frame_area (f, x2, y, width, height);
2106 ns_shift_glyphs_for_insert (struct frame *f,
2107 int x, int y, int width, int height,
2109 /* --------------------------------------------------------------------------
2110 External (RIF): copy an area horizontally, don't worry about clearing src
2111 -------------------------------------------------------------------------- */
2113 NSRect srcRect = NSMakeRect (x, y, width, height);
2114 NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2115 NSPoint dstOrigin = dstRect.origin;
2117 NSTRACE (ns_shift_glyphs_for_insert);
2119 ns_focus (f, &dstRect, 1);
2120 NSCopyBits (0, srcRect, dstOrigin);
2126 /* ==========================================================================
2128 Character encoding and metrics
2130 ========================================================================== */
2134 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2135 /* --------------------------------------------------------------------------
2136 External (RIF); compute left/right overhang of whole string and set in s
2137 -------------------------------------------------------------------------- */
2139 struct face *face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2140 struct font *font = s->font; /*face->font; */
2144 struct font_metrics metrics;
2145 unsigned int codes[2];
2146 codes[0] = *(s->char2b);
2147 codes[1] = *(s->char2b + s->nchars - 1);
2149 font->driver->text_extents (font, codes, 2, &metrics);
2150 s->left_overhang = -metrics.lbearing;
2152 = metrics.rbearing > metrics.width
2153 ? metrics.rbearing - metrics.width : 0;
2157 s->left_overhang = 0;
2158 s->right_overhang = ((struct nsfont_info *)font)->ital ?
2159 FONT_HEIGHT (font) * 0.2 : 0;
2165 /* ==========================================================================
2167 Fringe and cursor drawing
2169 ========================================================================== */
2172 extern int max_used_fringe_bitmap;
2174 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2175 struct draw_fringe_bitmap_params *p)
2176 /* --------------------------------------------------------------------------
2177 External (RIF); fringe-related
2178 -------------------------------------------------------------------------- */
2180 struct frame *f = XFRAME (WINDOW_FRAME (w));
2181 struct face *face = p->face;
2183 static EmacsImage **bimgs = NULL;
2184 static int nBimgs = 0;
2185 /* NS-specific: move internal border inside fringe */
2186 int x = p->bx < 0 ? p->x : p->bx;
2187 int wd = p->bx < 0 ? p->wd : p->nx;
2188 BOOL fringeOnVeryLeft
2189 = x - WINDOW_LEFT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w)
2190 - FRAME_INTERNAL_BORDER_WIDTH (f) < 10;
2191 BOOL fringeOnVeryRight
2192 = FRAME_PIXEL_WIDTH (f) - x - wd - FRAME_INTERNAL_BORDER_WIDTH (f)
2193 - WINDOW_RIGHT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w) < 10;
2194 int xAdjust = FRAME_INTERNAL_BORDER_WIDTH (f) *
2195 (fringeOnVeryLeft ? -1 : (fringeOnVeryRight ? 1 : 0));
2197 /* grow bimgs if needed */
2198 if (nBimgs < max_used_fringe_bitmap)
2200 EmacsImage **newBimgs
2201 = xmalloc (max_used_fringe_bitmap * sizeof (EmacsImage *));
2202 bzero (newBimgs, max_used_fringe_bitmap * sizeof (EmacsImage *));
2206 bcopy (bimgs, newBimgs, nBimgs * sizeof (EmacsImage *));
2211 nBimgs = max_used_fringe_bitmap;
2214 /* Must clip because of partially visible lines. */
2215 rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
2218 /* Adjust position of "bottom aligned" bitmap on partially
2219 visible last row. */
2221 int oldVH = row->visible_height;
2222 row->visible_height = p->h;
2223 row->y -= rowY - p->y;
2224 ns_clip_to_row (w, row, -1, NO);
2226 row->visible_height = oldVH;
2229 ns_clip_to_row (w, row, -1, YES);
2231 if (p->bx >= 0 && !p->overlay_p)
2233 int yAdjust = rowY - FRAME_INTERNAL_BORDER_WIDTH (f) < 5 ?
2234 -FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2235 int yIncr = FRAME_PIXEL_HEIGHT (f) - (p->by+yAdjust + p->ny) < 5 ?
2236 FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2238 yIncr += FRAME_INTERNAL_BORDER_WIDTH (f);
2239 NSRect r = NSMakeRect (p->bx+xAdjust, p->by+yAdjust, p->nx, p->ny+yIncr);
2241 [ns_lookup_indexed_color(face->background, f) set];
2247 NSRect r = NSMakeRect (p->x+xAdjust, p->y, p->wd, p->h);
2248 NSPoint pt = r.origin;
2249 EmacsImage *img = bimgs[p->which - 1];
2253 unsigned short *bits = p->bits + p->dh;
2254 int len = 8 * p->h/8;
2256 unsigned char *cbits = xmalloc (len);
2258 for (i =0; i<len; i++)
2259 cbits[i] = ~(bits[i] & 0xff);
2260 img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2262 bimgs[p->which - 1] = img;
2267 /* Since we composite the bitmap instead of just blitting it, we need
2268 to erase the whole background. */
2269 [ns_lookup_indexed_color(face->background, f) set];
2272 [img setXBMColor: ns_lookup_indexed_color(face->foreground, f)];
2273 [img compositeToPoint: pt operation: NSCompositeSourceOver];
2280 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2281 int x, int y, int cursor_type, int cursor_width,
2282 int on_p, int active_p)
2283 /* --------------------------------------------------------------------------
2284 External call (RIF): draw cursor
2285 (modeled after x_draw_window_cursor
2286 FIXME: cursor_width is effectively bogus -- it sometimes gets set
2287 in xdisp.c set_frame_cursor_types, sometimes left uninitialized;
2288 DON'T USE IT (no other terms do)
2289 -------------------------------------------------------------------------- */
2293 struct frame *f = WINDOW_XFRAME (w);
2294 struct glyph *phys_cursor_glyph;
2297 NSTRACE (dumpcursor);
2298 //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);
2303 w->phys_cursor_type = cursor_type;
2304 w->phys_cursor_on_p = on_p;
2306 if (cursor_type == NO_CURSOR)
2308 w->phys_cursor_width = 0;
2312 if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2314 if (glyph_row->exact_window_width_line_p
2315 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2317 glyph_row->cursor_in_fringe_p = 1;
2318 draw_fringe_bitmap (w, glyph_row, 0);
2323 get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2325 r.origin.x = fx, r.origin.y = fy;
2327 r.size.width = w->phys_cursor_width;
2329 /* FIXME: if we overwrite the internal border area, it does not get erased;
2330 fix by truncating cursor, but better would be to erase properly */
2331 overspill = r.origin.x + r.size.width -
2332 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, WINDOW_BOX_RIGHT_EDGE_X (w)
2333 - WINDOW_TOTAL_FRINGE_WIDTH (w) - FRAME_INTERNAL_BORDER_WIDTH (f));
2335 r.size.width -= overspill;
2337 /* TODO: only needed in rare cases with last-resort font in HELLO..
2338 should we do this more efficiently? */
2339 ns_clip_to_row (w, glyph_row, -1, NO); /* do ns_focus(f, &r, 1); if remove */
2340 [FRAME_CURSOR_COLOR (f) set];
2342 #ifdef NS_IMPL_COCOA
2343 /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2344 atomic. Cleaner ways of doing this should be investigated.
2345 One way would be to set a global variable DRAWING_CURSOR
2346 when making the call to draw_phys..(), don't focus in that
2347 case, then move the ns_unfocus() here after that call. */
2348 NSDisableScreenUpdates ();
2351 switch (cursor_type)
2355 case FILLED_BOX_CURSOR:
2358 case HOLLOW_BOX_CURSOR:
2360 [FRAME_BACKGROUND_COLOR (f) set];
2361 NSRectFill (NSInsetRect (r, 1, 1));
2362 [FRAME_CURSOR_COLOR (f) set];
2366 s.origin.y += lrint (0.75 * s.size.height);
2367 s.size.height = lrint (s.size.height * 0.25);
2372 s.size.width = min (cursor_width, 2); //FIXME(see above)
2378 /* draw the character under the cursor */
2379 if (cursor_type != NO_CURSOR)
2380 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2382 #ifdef NS_IMPL_COCOA
2383 NSEnableScreenUpdates ();
2390 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2391 /* --------------------------------------------------------------------------
2392 External (RIF): Draw a vertical line.
2393 -------------------------------------------------------------------------- */
2395 struct frame *f = XFRAME (WINDOW_FRAME (w));
2397 NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2399 NSTRACE (ns_draw_vertical_window_border);
2401 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2403 [ns_lookup_indexed_color(face->foreground, f) set];
2405 ns_focus (f, &r, 1);
2412 show_hourglass (struct atimer *timer)
2414 if (hourglass_shown_p)
2419 /* TODO: add NSProgressIndicator to selected frame (see macfns.c) */
2421 hourglass_shown_p = 1;
2429 if (!hourglass_shown_p)
2434 /* TODO: remove NSProgressIndicator from all frames */
2436 hourglass_shown_p = 0;
2442 /* ==========================================================================
2444 Glyph drawing operations
2446 ========================================================================== */
2449 static inline NSRect
2450 ns_fix_rect_ibw (NSRect r, int fibw, int frame_pixel_width)
2451 /* --------------------------------------------------------------------------
2452 Under NS we draw internal borders inside fringes, and want full-width
2453 rendering to go all the way to edge. This function makes that correction.
2454 -------------------------------------------------------------------------- */
2456 if (r.origin.y <= fibw+1)
2458 r.size.height += r.origin.y;
2461 if (r.origin.x <= fibw+1)
2463 r.size.width += r.origin.x;
2466 if (frame_pixel_width - (r.origin.x+r.size.width) <= fibw+1)
2467 r.size.width += fibw;
2474 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2475 /* --------------------------------------------------------------------------
2476 Wrapper utility to account for internal border width on full-width lines,
2477 and allow top full-width rows to hit the frame top. nr should be pointer
2478 to two successive NSRects. Number of rects actually used is returned.
2479 -------------------------------------------------------------------------- */
2481 int n = get_glyph_string_clip_rects (s, nr, 2);
2482 if (s->row->full_width_p)
2484 *nr = ns_fix_rect_ibw (*nr, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2485 FRAME_PIXEL_WIDTH (s->f));
2487 *nr = ns_fix_rect_ibw (*(nr+1), FRAME_INTERNAL_BORDER_WIDTH (s->f),
2488 FRAME_PIXEL_WIDTH (s->f));
2495 ns_draw_box (NSRect r, float thickness, NSColor *col, char left_p, char right_p)
2496 /* --------------------------------------------------------------------------
2497 Draw an unfilled rect inside r, optionally leaving left and/or right open.
2498 Note we can't just use an NSDrawRect command, because of the possibility
2499 of some sides not being drawn, and because the rect will be filled.
2500 -------------------------------------------------------------------------- */
2506 s.size.height = thickness;
2508 s.origin.y += r.size.height - thickness;
2511 s.size.height = r.size.height;
2512 s.origin.y = r.origin.y;
2514 /* left, right (optional) */
2515 s.size.width = thickness;
2520 s.origin.x += r.size.width - thickness;
2527 ns_draw_relief (NSRect r, int thickness, char raised_p,
2528 char top_p, char bottom_p, char left_p, char right_p,
2529 struct glyph_string *s)
2530 /* --------------------------------------------------------------------------
2531 Draw a relief rect inside r, optionally leaving some sides open.
2532 Note we can't just use an NSDrawBezel command, because of the possibility
2533 of some sides not being drawn, and because the rect will be filled.
2534 -------------------------------------------------------------------------- */
2536 static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2537 NSColor *newBaseCol = nil;
2540 NSTRACE (ns_draw_relief);
2544 if (s->face->use_box_color_for_shadows_p)
2546 newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2548 /* else if (s->first_glyph->type == IMAGE_GLYPH
2550 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2552 newBaseCol = IMAGE_BACKGROUND (s->img, s->f, 0);
2556 newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2559 if (newBaseCol == nil)
2560 newBaseCol = [NSColor grayColor];
2562 if (newBaseCol != baseCol) /* TODO: better check */
2565 baseCol = [newBaseCol retain];
2567 lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2569 darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2572 [(raised_p ? lightCol : darkCol) set];
2574 /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2577 sr.size.height = thickness;
2578 if (top_p) NSRectFill (sr);
2581 sr.size.height = r.size.height;
2582 sr.size.width = thickness;
2583 if (left_p) NSRectFill (sr);
2585 [(raised_p ? darkCol : lightCol) set];
2588 sr.size.width = r.size.width;
2589 sr.size.height = thickness;
2590 sr.origin.y += r.size.height - thickness;
2591 if (bottom_p) NSRectFill (sr);
2594 sr.size.height = r.size.height;
2595 sr.origin.y = r.origin.y;
2596 sr.size.width = thickness;
2597 sr.origin.x += r.size.width - thickness;
2598 if (right_p) NSRectFill (sr);
2603 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2604 /* --------------------------------------------------------------------------
2605 Function modeled after x_draw_glyph_string_box ().
2606 Sets up parameters for drawing.
2607 -------------------------------------------------------------------------- */
2609 int right_x, last_x;
2610 char left_p, right_p;
2611 struct glyph *last_glyph;
2616 if (s->hl == DRAW_MOUSE_FACE)
2619 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2621 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2626 thickness = face->box_line_width;
2628 NSTRACE (ns_dumpglyphs_box_or_relief);
2630 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2631 ? WINDOW_RIGHT_EDGE_X (s->w)
2632 : window_box_right (s->w, s->area));
2633 last_glyph = (s->cmp || s->img
2634 ? s->first_glyph : s->first_glyph + s->nchars-1);
2636 right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2637 ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2639 left_p = (s->first_glyph->left_box_line_p
2640 || (s->hl == DRAW_MOUSE_FACE
2641 && (s->prev == NULL || s->prev->hl != s->hl)));
2642 right_p = (last_glyph->right_box_line_p
2643 || (s->hl == DRAW_MOUSE_FACE
2644 && (s->next == NULL || s->next->hl != s->hl)));
2646 r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2648 /* expand full-width row over internal borders */
2649 if (s->row->full_width_p)
2650 r = ns_fix_rect_ibw (r, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2651 FRAME_PIXEL_WIDTH (s->f));
2653 if (s->face->box == FACE_SIMPLE_BOX)
2655 xassert (s->face->box_color != nil);
2656 ns_draw_box (r, abs (thickness),
2657 ns_lookup_indexed_color (face->box_color, s->f),
2662 ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2663 1, 1, left_p, right_p, s);
2669 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2670 /* --------------------------------------------------------------------------
2671 Modeled after x_draw_glyph_string_background, which draws BG in
2672 certain cases. Others are left to the text rendering routine.
2673 -------------------------------------------------------------------------- */
2675 NSTRACE (ns_maybe_dumpglyphs_background);
2677 if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2679 int box_line_width = max (s->face->box_line_width, 0);
2680 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2681 || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2684 if (s->hl == DRAW_MOUSE_FACE)
2687 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2689 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2692 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2696 [(NS_FACE_BACKGROUND (face) != 0
2697 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2698 : FRAME_BACKGROUND_COLOR (s->f)) set];
2699 #if 0 /* This is tiling, not stippling. */
2702 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (s->f);
2703 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2707 if (s->hl != DRAW_CURSOR)
2709 NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2710 s->background_width,
2711 s->height-2*box_line_width);
2713 /* expand full-width row over internal borders */
2714 if (s->row->full_width_p)
2716 int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2717 if (r.origin.y <= fibw+1 + box_line_width)
2719 r.size.height += r.origin.y;
2722 if (r.origin.x <= fibw+1)
2724 r.size.width += 2*r.origin.x;
2727 if (FRAME_PIXEL_WIDTH (s->f) - (r.origin.x + r.size.width)
2729 r.size.width += fibw;
2735 s->background_filled_p = 1;
2742 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2743 /* --------------------------------------------------------------------------
2744 Renders an image and associated borders.
2745 -------------------------------------------------------------------------- */
2747 EmacsImage *img = s->img->pixmap;
2748 int box_line_vwidth = max (s->face->box_line_width, 0);
2749 int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2750 int bg_x, bg_y, bg_height;
2756 NSTRACE (ns_dumpglyphs_image);
2758 if (s->face->box != FACE_NO_BOX
2759 && s->first_glyph->left_box_line_p && s->slice.x == 0)
2760 x += abs (s->face->box_line_width);
2763 bg_y = s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2764 bg_height = s->height;
2765 /* other terms have this, but was causing problems w/tabbar mode */
2766 /* - 2 * box_line_vwidth; */
2768 if (s->slice.x == 0) x += s->img->hmargin;
2769 if (s->slice.y == 0) y += s->img->vmargin;
2771 /* Draw BG: if we need larger area than image itself cleared, do that,
2772 otherwise, since we composite the image under NS (instead of mucking
2773 with its background color), we must clear just the image area. */
2774 if (s->hl == DRAW_MOUSE_FACE)
2777 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2779 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2782 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2784 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
2786 if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
2787 || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
2789 br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
2790 s->background_filled_p = 1;
2794 br = NSMakeRect (x, y, s->slice.width, s->slice.height);
2797 /* expand full-width row over internal borders */
2798 if (s->row->full_width_p)
2800 int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2801 if (br.origin.y <= fibw+1 + box_line_vwidth)
2803 br.size.height += br.origin.y;
2806 if (br.origin.x <= fibw+1 + box_line_vwidth)
2808 br.size.width += br.origin.x;
2811 if (FRAME_PIXEL_WIDTH (s->f) - (br.origin.x + br.size.width) <= fibw+1)
2812 br.size.width += fibw;
2817 /* Draw the image.. do we need to draw placeholder if img ==nil? */
2819 [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
2820 operation: NSCompositeSourceOver];
2822 /* Draw relief, if requested */
2823 if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
2825 if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
2827 th = tool_bar_button_relief >= 0 ?
2828 tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2829 raised_p = (s->hl == DRAW_IMAGE_RAISED);
2833 th = abs (s->img->relief);
2834 raised_p = (s->img->relief > 0);
2837 r.origin.x = x - th;
2838 r.origin.y = y - th;
2839 r.size.width = s->slice.width + 2*th-1;
2840 r.size.height = s->slice.height + 2*th-1;
2841 ns_draw_relief (r, th, raised_p,
2843 s->slice.y + s->slice.height == s->img->height,
2845 s->slice.x + s->slice.width == s->img->width, s);
2851 ns_dumpglyphs_stretch (struct glyph_string *s)
2857 if (!s->background_filled_p)
2859 n = ns_get_glyph_string_clip_rect (s, r);
2860 *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
2864 if (!s->row->full_width_p)
2866 /* truncate to avoid overwriting fringe and/or scrollbar */
2867 int overrun = max (0, (s->x + s->background_width)
2868 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
2869 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
2870 r[i].size.width -= overrun;
2872 /* XXX: Try to work between problem where a stretch glyph on
2873 a partially-visible bottom row will clear part of the
2874 modeline, and another where list-buffers headers and similar
2875 rows erroneously have visible_height set to 0. Not sure
2876 where this is coming from as other terms seem not to show. */
2877 r[i].size.height = min (s->height, s->row->visible_height);
2880 /* expand full-width rows over internal borders */
2883 r[i] = ns_fix_rect_ibw (r[i], FRAME_INTERNAL_BORDER_WIDTH (s->f),
2884 FRAME_PIXEL_WIDTH (s->f));
2887 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
2888 overwriting cursor (usually when cursor on a tab) */
2889 if (s->hl == DRAW_CURSOR)
2891 r[i].origin.x += s->width;
2892 r[i].size.width -= s->width;
2896 ns_focus (s->f, r, n);
2898 if (s->hl == DRAW_MOUSE_FACE)
2901 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2903 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2906 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2908 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
2913 s->background_filled_p = 1;
2919 ns_draw_glyph_string (struct glyph_string *s)
2920 /* --------------------------------------------------------------------------
2921 External (RIF): Main draw-text call.
2922 -------------------------------------------------------------------------- */
2924 /* TODO (optimize): focus for box and contents draw */
2927 char box_drawn_p = 0;
2929 NSTRACE (ns_draw_glyph_string);
2931 if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
2934 struct glyph_string *next;
2936 for (width = 0, next = s->next;
2937 next && width < s->right_overhang;
2938 width += next->width, next = next->next)
2939 if (next->first_glyph->type != IMAGE_GLYPH)
2941 if (next->first_glyph->type != STRETCH_GLYPH)
2943 n = ns_get_glyph_string_clip_rect (s->next, r);
2944 ns_focus (s->f, r, n);
2945 ns_maybe_dumpglyphs_background (s->next, 1);
2950 ns_dumpglyphs_stretch (s->next);
2952 next->num_clips = 0;
2956 if (!s->for_overlaps && s->face->box != FACE_NO_BOX
2957 && (s->first_glyph->type == CHAR_GLYPH
2958 || s->first_glyph->type == COMPOSITE_GLYPH))
2960 n = ns_get_glyph_string_clip_rect (s, r);
2961 ns_focus (s->f, r, n);
2962 ns_maybe_dumpglyphs_background (s, 1);
2963 ns_dumpglyphs_box_or_relief (s);
2968 switch (s->first_glyph->type)
2972 n = ns_get_glyph_string_clip_rect (s, r);
2973 ns_focus (s->f, r, n);
2974 ns_dumpglyphs_image (s, r[0]);
2979 ns_dumpglyphs_stretch (s);
2983 case COMPOSITE_GLYPH:
2984 n = ns_get_glyph_string_clip_rect (s, r);
2985 ns_focus (s->f, r, n);
2987 if (s->for_overlaps || (s->cmp_from > 0
2988 && ! s->first_glyph->u.cmp.automatic))
2989 s->background_filled_p = 1;
2991 ns_maybe_dumpglyphs_background
2992 (s, s->first_glyph->type == COMPOSITE_GLYPH);
2994 ns_tmp_flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
2995 (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
2996 (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
2997 NS_DUMPGLYPH_NORMAL));
2998 ns_tmp_font = (struct nsfont_info *)s->face->font;
2999 if (ns_tmp_font == NULL)
3000 ns_tmp_font = (struct nsfont_info *)FRAME_FONT (s->f);
3002 ns_tmp_font->font.driver->draw
3003 (s, 0, s->nchars, s->x, s->y,
3004 (ns_tmp_flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3005 || ns_tmp_flags == NS_DUMPGLYPH_MOUSEFACE);
3014 /* Draw box if not done already. */
3015 if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3017 n = ns_get_glyph_string_clip_rect (s, r);
3018 ns_focus (s->f, r, n);
3019 ns_dumpglyphs_box_or_relief (s);
3028 /* ==========================================================================
3032 ========================================================================== */
3036 ns_send_appdefined (int value)
3037 /* --------------------------------------------------------------------------
3038 Internal: post an appdefined event which EmacsApp-sendEvent will
3039 recognize and take as a command to halt the event loop.
3040 -------------------------------------------------------------------------- */
3042 /*NSTRACE (ns_send_appdefined); */
3044 /* Only post this event if we haven't already posted one. This will end
3045 the [NXApp run] main loop after having processed all events queued at
3047 if (send_appdefined)
3051 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
3052 send_appdefined = NO;
3054 /* Don't need wakeup timer any more */
3057 [timed_entry invalidate];
3058 [timed_entry release];
3062 /* Ditto for file descriptor poller */
3065 [fd_entry invalidate];
3070 nxev = [NSEvent otherEventWithType: NSApplicationDefined
3071 location: NSMakePoint (0, 0)
3074 windowNumber: [[NSApp mainWindow] windowNumber]
3075 context: [NSApp context]
3080 /* Post an application defined event on the event queue. When this is
3081 received the [NXApp run] will return, thus having processed all
3082 events which are currently queued. */
3083 [NSApp postEvent: nxev atStart: NO];
3089 ns_read_socket (struct terminal *terminal, int expected,
3090 struct input_event *hold_quit)
3091 /* --------------------------------------------------------------------------
3092 External (hook): Post an event to ourself and keep reading events until
3093 we read it back again. In effect process all events which were waiting.
3094 From 21+ we have to manage the event buffer ourselves.
3095 -------------------------------------------------------------------------- */
3097 struct input_event ev;
3100 /* NSTRACE (ns_read_socket); */
3102 if (interrupt_input_blocked)
3104 interrupt_input_pending = 1;
3106 pending_signals = 1;
3111 interrupt_input_pending = 0;
3113 pending_signals = pending_atimers;
3117 n_emacs_events_pending = 0;
3120 q_event_ptr = hold_quit;
3122 /* we manage autorelease pools by allocate/reallocate each time around
3123 the loop; strict nesting is occasionally violated but seems not to
3124 matter.. earlier methods using full nesting caused major memory leaks */
3125 [outerpool release];
3126 outerpool = [[NSAutoreleasePool alloc] init];
3128 /* If have pending open-file requests, attend to the next one of those. */
3129 if (ns_pending_files && [ns_pending_files count] != 0
3130 && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3132 [ns_pending_files removeObjectAtIndex: 0];
3134 /* Deal with pending service requests. */
3135 else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3137 NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3138 withArg: [ns_pending_service_args objectAtIndex: 0]])
3140 [ns_pending_service_names removeObjectAtIndex: 0];
3141 [ns_pending_service_args removeObjectAtIndex: 0];
3145 /* Run and wait for events. We must always send one NX_APPDEFINED event
3146 to ourself, otherwise [NXApp run] will never exit. */
3147 send_appdefined = YES;
3149 /* If called via ns_select, this is called once with expected=1,
3150 because we expect either the timeout or file descriptor activity.
3151 In this case the first event through will either be real input or
3152 one of these. read_avail_input() then calls once more with expected=0
3153 and in that case we need to return quickly if there is nothing.
3154 If we're being called outside of that, it's also OK to return quickly
3155 after one iteration through the event loop, since other terms do
3156 this and emacs expects it. */
3157 if (!(inNsSelect && expected)) // (!inNsSelect || !expected)
3159 /* Post an application defined event on the event queue. When this is
3160 received the [NXApp run] will return, thus having processed all
3161 events which are currently queued, if any. */
3162 ns_send_appdefined (-1);
3168 nevents = n_emacs_events_pending;
3169 n_emacs_events_pending = 0;
3170 emacs_event = q_event_ptr = NULL;
3178 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3179 fd_set *exceptfds, struct timeval *timeout)
3180 /* --------------------------------------------------------------------------
3181 Replacement for select, checking for events
3182 -------------------------------------------------------------------------- */
3187 /* NSTRACE (ns_select); */
3189 if (NSApp == nil || inNsSelect == 1 /* || ([NSApp isActive] == NO &&
3190 [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
3191 inMode:NSDefaultRunLoopMode dequeue:NO] == nil) */)
3192 return select (nfds, readfds, writefds, exceptfds, timeout);
3194 /* Save file descriptor set, which gets overwritten in calls to select ()
3195 Note, this is called from process.c, and only readfds is ever set */
3198 memcpy (&select_readfds, readfds, sizeof (fd_set));
3204 /* Try an initial select for pending data on input files */
3205 select_timeout.tv_sec = select_timeout.tv_usec = 0;
3206 result = select (nfds, readfds, writefds, exceptfds, &select_timeout);
3210 /* if (!timeout || timed_entry || fd_entry)
3211 fprintf (stderr, "assertion failed: timeout null or timed_entry/fd_entry non-null in ns_select\n"); */
3213 /* set a timeout and run the main AppKit event loop while continuing
3214 to monitor the files */
3215 time = ((double) timeout->tv_sec) + ((double) timeout->tv_usec)/1000000.0;
3216 timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3218 selector: @selector (timeout_handler:)
3220 repeats: YES] /* for safe removal */
3223 /* set a periodic task to try the select () again */
3224 fd_entry = [[NSTimer scheduledTimerWithTimeInterval: 0.1
3226 selector: @selector (fd_handler:)
3231 /* Let Application dispatch events until it receives an event of the type
3232 NX_APPDEFINED, which should only be sent by timeout_handler.
3233 We tell read_avail_input() that input is "expected" because we do expect
3234 either the timeout or fd handler to fire, and if they don't, the original
3235 call from process.c that got us here expects us to wait until some input
3239 ev = last_appdefined_event;
3245 if ([ev type] != NSApplicationDefined)
3249 last_appdefined_event = 0;
3253 /* The NX_APPDEFINED event we received was a timeout. */
3258 /* The NX_APPDEFINED event we received was the result of
3259 at least one real input event arriving. */
3265 /* Received back from select () in fd_handler; copy the results */
3267 memcpy (readfds, &select_readfds, sizeof (fd_set));
3271 /* never reached, shut compiler up */
3277 /* ==========================================================================
3281 ========================================================================== */
3285 ns_set_vertical_scroll_bar (struct window *window,
3286 int portion, int whole, int position)
3287 /* --------------------------------------------------------------------------
3288 External (hook): Update or add scrollbar
3289 -------------------------------------------------------------------------- */
3293 struct frame *f = XFRAME (WINDOW_FRAME (window));
3294 EmacsView *view = FRAME_NS_VIEW (f);
3295 int window_y, window_height;
3296 BOOL barOnVeryLeft, barOnVeryRight;
3297 int top, left, height, width, sb_width, sb_left;
3299 static int count = 0;
3301 /* optimization; display engine sends WAY too many of these.. */
3302 if (!NILP (window->vertical_scroll_bar))
3304 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3305 if ([bar checkSamePosition: position portion: portion whole: whole])
3307 if (view->scrollbarsNeedingUpdate == 0)
3309 if (!windows_or_buffers_changed)
3313 view->scrollbarsNeedingUpdate--;
3317 NSTRACE (ns_set_vertical_scroll_bar);
3319 /* Get dimensions. */
3320 window_box (window, -1, 0, &window_y, 0, &window_height);
3322 height = window_height;
3323 width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3324 left = WINDOW_SCROLL_BAR_AREA_X (window);
3326 if (top < 5) /* top scrollbar adjustment */
3328 top -= FRAME_INTERNAL_BORDER_WIDTH (f);
3329 height += FRAME_INTERNAL_BORDER_WIDTH (f);
3332 /* allow for displaying a skinnier scrollbar than char area allotted */
3333 sb_width = (WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) > 0) ?
3334 WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) : width;
3336 barOnVeryLeft = left < 5;
3337 barOnVeryRight = FRAME_PIXEL_WIDTH (f) - left - width < 5;
3338 sb_left = left + FRAME_INTERNAL_BORDER_WIDTH (f)
3339 * (barOnVeryLeft ? -1 : (barOnVeryRight ? 1 : 0));
3341 r = NSMakeRect (sb_left, top, sb_width, height);
3342 /* the parent view is flipped, so we need to flip y value */
3344 r.origin.y = (v.size.height - r.size.height - r.origin.y);
3346 XSETWINDOW (win, window);
3349 /* we want at least 5 lines to display a scrollbar */
3350 if (WINDOW_TOTAL_LINES (window) < 5)
3352 if (!NILP (window->vertical_scroll_bar))
3354 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3355 [bar removeFromSuperview];
3356 window->vertical_scroll_bar = Qnil;
3358 ns_clear_frame_area (f, sb_left, top, width, height);
3363 if (NILP (window->vertical_scroll_bar))
3365 ns_clear_frame_area (f, sb_left, top, width, height);
3366 bar = [[EmacsScroller alloc] initFrame: r window: win];
3367 window->vertical_scroll_bar = make_save_value (bar, 0);
3372 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3373 oldRect = [bar frame];
3374 r.size.width = oldRect.size.width;
3375 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3377 if (oldRect.origin.x != r.origin.x)
3378 ns_clear_frame_area (f, sb_left, top, width, height);
3383 [bar setPosition: position portion: portion whole: whole];
3389 ns_condemn_scroll_bars (struct frame *f)
3390 /* --------------------------------------------------------------------------
3391 External (hook): arrange for all frame's scrollbars to be removed
3392 at next call to judge_scroll_bars, except for those redeemed.
3393 -------------------------------------------------------------------------- */
3397 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3399 NSTRACE (ns_condemn_scroll_bars);
3401 for (i =[subviews count]-1; i >= 0; i--)
3403 view = [subviews objectAtIndex: i];
3404 if ([view isKindOfClass: [EmacsScroller class]])
3411 ns_redeem_scroll_bar (struct window *window)
3412 /* --------------------------------------------------------------------------
3413 External (hook): arrange to spare this window's scrollbar
3414 at next call to judge_scroll_bars.
3415 -------------------------------------------------------------------------- */
3418 NSTRACE (ns_redeem_scroll_bar);
3419 if (!NILP (window->vertical_scroll_bar))
3421 bar =XNS_SCROLL_BAR (window->vertical_scroll_bar);
3428 ns_judge_scroll_bars (struct frame *f)
3429 /* --------------------------------------------------------------------------
3430 External (hook): destroy all scrollbars on frame that weren't
3431 redeemed after call to condemn_scroll_bars.
3432 -------------------------------------------------------------------------- */
3436 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3437 NSTRACE (ns_judge_scroll_bars);
3438 for (i =[subviews count]-1; i >= 0; i--)
3440 view = [subviews objectAtIndex: i];
3441 if (![view isKindOfClass: [EmacsScroller class]]) continue;
3448 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
3450 /* XXX irrelevant under NS */
3455 /* ==========================================================================
3459 ========================================================================== */
3462 x_display_pixel_height (dpyinfo)
3463 struct ns_display_info *dpyinfo;
3465 NSScreen *screen = [NSScreen mainScreen];
3466 return [screen frame].size.height;
3470 x_display_pixel_width (dpyinfo)
3471 struct ns_display_info *dpyinfo;
3473 NSScreen *screen = [NSScreen mainScreen];
3474 return [screen frame].size.width;
3478 static Lisp_Object ns_string_to_lispmod (const char *s)
3479 /* --------------------------------------------------------------------------
3480 Convert modifier name to lisp symbol
3481 -------------------------------------------------------------------------- */
3483 if (!strncmp (SDATA (SYMBOL_NAME (Qmeta)), s, 10))
3485 else if (!strncmp (SDATA (SYMBOL_NAME (Qsuper)), s, 10))
3487 else if (!strncmp (SDATA (SYMBOL_NAME (Qcontrol)), s, 10))
3489 else if (!strncmp (SDATA (SYMBOL_NAME (Qalt)), s, 10))
3491 else if (!strncmp (SDATA (SYMBOL_NAME (Qhyper)), s, 10))
3493 else if (!strncmp (SDATA (SYMBOL_NAME (Qnone)), s, 10))
3500 static Lisp_Object ns_mod_to_lisp (int m)
3501 /* --------------------------------------------------------------------------
3502 Convert modifier code (see lisp.h) to lisp symbol
3503 -------------------------------------------------------------------------- */
3507 else if (m == CHAR_SUPER)
3509 else if (m == CHAR_CTL)
3511 else if (m == CHAR_ALT)
3513 else if (m == CHAR_HYPER)
3515 else /* if (m == 0) */
3521 ns_set_default_prefs ()
3522 /* --------------------------------------------------------------------------
3523 Initialize preference variables to defaults
3524 -------------------------------------------------------------------------- */
3526 ns_alternate_modifier = Qmeta;
3527 ns_command_modifier = Qsuper;
3528 ns_control_modifier = Qcontrol;
3529 ns_function_modifier = Qnone;
3530 ns_antialias_text = Qt;
3531 ns_antialias_threshold = 10.0; /* not exposed to lisp side */
3532 ns_use_qd_smoothing = Qnil;
3533 ns_confirm_quit = Qnil;
3538 ns_default (const char *parameter, Lisp_Object *result,
3539 Lisp_Object yesval, Lisp_Object noval,
3540 BOOL is_float, BOOL is_modstring)
3541 /* --------------------------------------------------------------------------
3542 Check a parameter value in user's preferences
3543 -------------------------------------------------------------------------- */
3547 if ( (value =[[[NSUserDefaults standardUserDefaults]
3548 stringForKey: [NSString stringWithUTF8String: parameter]]
3553 if (strcasecmp (value, "YES") == 0)
3555 else if (strcasecmp (value, "NO") == 0)
3557 else if (is_float && (f = strtod (value, &pos), pos != value))
3558 *result = make_float (f);
3559 else if (is_modstring && value)
3560 *result = ns_string_to_lispmod (value);
3561 else fprintf (stderr,
3562 "Bad value for default \"%s\": \"%s\"\n", parameter, value);
3568 ns_initialize_display_info (struct ns_display_info *dpyinfo)
3569 /* --------------------------------------------------------------------------
3570 Initialize global info and storage for display.
3571 -------------------------------------------------------------------------- */
3573 NSScreen *screen = [NSScreen mainScreen];
3574 NSWindowDepth depth = [screen depth];
3576 dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
3577 dpyinfo->resy = 72.27;
3578 dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
3579 NSColorSpaceFromDepth (depth)]
3580 && ![NSCalibratedWhiteColorSpace isEqualToString:
3581 NSColorSpaceFromDepth (depth)];
3582 dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
3583 dpyinfo->image_cache = make_image_cache ();
3584 dpyinfo->color_table
3585 = (struct ns_color_table *)xmalloc (sizeof (struct ns_color_table));
3586 dpyinfo->color_table->colors = NULL;
3587 dpyinfo->root_window = 42; /* a placeholder.. */
3589 dpyinfo->mouse_face_mouse_frame = NULL;
3590 dpyinfo->mouse_face_deferred_gc = 0;
3591 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
3592 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
3593 dpyinfo->mouse_face_face_id = DEFAULT_FACE_ID;
3594 dpyinfo->mouse_face_window = dpyinfo->mouse_face_overlay = Qnil;
3595 dpyinfo->mouse_face_hidden = 0;
3597 dpyinfo->mouse_face_mouse_x = dpyinfo->mouse_face_mouse_y = 0;
3598 dpyinfo->mouse_face_defer = 0;
3600 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
3602 dpyinfo->n_fonts = 0;
3603 dpyinfo->smallest_font_height = 1;
3604 dpyinfo->smallest_char_width = 1;
3608 /* This and next define (many of the) public functions in this file. */
3609 /* x_... are generic versions in xdisp.c that we, and other terms, get away
3610 with using despite presence in the "system dependent" redisplay
3611 interface. In addition, many of the ns_ methods have code that is
3612 shared with all terms, indicating need for further refactoring. */
3613 extern frame_parm_handler ns_frame_parm_handlers[];
3614 static struct redisplay_interface ns_redisplay_interface =
3616 ns_frame_parm_handlers,
3620 x_clear_end_of_line,
3622 ns_after_update_window_line,
3623 ns_update_window_begin,
3624 ns_update_window_end,
3627 0, /* flush_display_optional */
3628 x_clear_window_mouse_face,
3629 x_get_glyph_overhangs,
3630 x_fix_overlapping_area,
3631 ns_draw_fringe_bitmap,
3632 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
3633 0, /* destroy_fringe_bitmap */
3634 ns_compute_glyph_string_overhangs,
3635 ns_draw_glyph_string, /* interface to nsfont.m */
3636 ns_define_frame_cursor,
3637 ns_clear_frame_area,
3638 ns_draw_window_cursor,
3639 ns_draw_vertical_window_border,
3640 ns_shift_glyphs_for_insert
3645 ns_delete_display (struct ns_display_info *dpyinfo)
3651 /* This function is called when the last frame on a display is deleted. */
3653 ns_delete_terminal (struct terminal *terminal)
3655 struct ns_display_info *dpyinfo = terminal->display_info.ns;
3658 /* Protect against recursive calls. delete_frame in
3659 delete_terminal calls us back when it deletes our last frame. */
3660 if (!terminal->name)
3665 x_destroy_all_bitmaps (dpyinfo);
3666 ns_delete_display (dpyinfo);
3671 static struct terminal *
3672 ns_create_terminal (struct ns_display_info *dpyinfo)
3673 /* --------------------------------------------------------------------------
3674 Set up use of NS before we make the first connection.
3675 -------------------------------------------------------------------------- */
3677 struct terminal *terminal;
3679 NSTRACE (ns_create_terminal);
3681 terminal = create_terminal ();
3683 terminal->type = output_ns;
3684 terminal->display_info.ns = dpyinfo;
3685 dpyinfo->terminal = terminal;
3687 terminal->rif = &ns_redisplay_interface;
3689 terminal->clear_frame_hook = ns_clear_frame;
3690 terminal->ins_del_lines_hook = 0; /* XXX vestigial? */
3691 terminal->delete_glyphs_hook = 0; /* XXX vestigial? */
3692 terminal->ring_bell_hook = ns_ring_bell;
3693 terminal->reset_terminal_modes_hook = ns_reset_terminal_modes;
3694 terminal->set_terminal_modes_hook = ns_set_terminal_modes;
3695 terminal->update_begin_hook = ns_update_begin;
3696 terminal->update_end_hook = ns_update_end;
3697 terminal->set_terminal_window_hook = NULL; /* XXX vestigial? */
3698 terminal->read_socket_hook = ns_read_socket;
3699 terminal->frame_up_to_date_hook = ns_frame_up_to_date;
3700 terminal->mouse_position_hook = ns_mouse_position;
3701 terminal->frame_rehighlight_hook = ns_frame_rehighlight;
3702 terminal->frame_raise_lower_hook = ns_frame_raise_lower;
3704 terminal->fullscreen_hook = 0; /* see XTfullscreen_hook */
3706 terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
3707 terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
3708 terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
3709 terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
3711 terminal->delete_frame_hook = x_destroy_window;
3712 terminal->delete_terminal_hook = ns_delete_terminal;
3714 terminal->scroll_region_ok = 1;
3715 terminal->char_ins_del_ok = 1;
3716 terminal->line_ins_del_ok = 1;
3717 terminal->fast_clear_end_of_line = 1;
3718 terminal->memory_below_frame = 0;
3724 struct ns_display_info *
3725 ns_term_init (Lisp_Object display_name)
3726 /* --------------------------------------------------------------------------
3727 Start the Application and get things rolling.
3728 -------------------------------------------------------------------------- */
3730 struct terminal *terminal;
3731 struct ns_display_info *dpyinfo;
3732 static int ns_initialized = 0;
3735 NSTRACE (ns_term_init);
3737 /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
3738 /*GSDebugAllocationActive (YES); */
3740 handling_signal = 0;
3742 if (!ns_initialized)
3745 Fset_input_interrupt_mode (Qnil);
3749 ns_pending_files = [[NSMutableArray alloc] init];
3750 ns_pending_service_names = [[NSMutableArray alloc] init];
3751 ns_pending_service_args = [[NSMutableArray alloc] init];
3753 /* Start app and create the main menu, window, view.
3754 Needs to be here because ns_initialize_display_info () uses AppKit classes.
3755 The view will then ask the NSApp to stop and return to Emacs. */
3756 [EmacsApp sharedApplication];
3759 [NSApp setDelegate: NSApp];
3761 /* debugging: log all notifications */
3762 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
3763 selector: @selector (logNotification:)
3764 name: nil object: nil]; */
3766 dpyinfo = (struct ns_display_info *)xmalloc (sizeof (struct ns_display_info));
3767 bzero (dpyinfo, sizeof (struct ns_display_info));
3769 ns_initialize_display_info (dpyinfo);
3770 terminal = ns_create_terminal (dpyinfo);
3772 terminal->kboard = (KBOARD *) xmalloc (sizeof (KBOARD));
3773 init_kboard (terminal->kboard);
3774 terminal->kboard->Vwindow_system = Qns;
3775 terminal->kboard->next_kboard = all_kboards;
3776 all_kboards = terminal->kboard;
3777 /* Don't let the initial kboard remain current longer than necessary.
3778 That would cause problems if a file loaded on startup tries to
3779 prompt in the mini-buffer. */
3780 if (current_kboard == initial_kboard)
3781 current_kboard = terminal->kboard;
3782 terminal->kboard->reference_count++;
3784 dpyinfo->next = x_display_list;
3785 x_display_list = dpyinfo;
3787 /* Put it on ns_display_name_list */
3788 ns_display_name_list = Fcons (Fcons (display_name, Qnil),
3789 ns_display_name_list);
3790 dpyinfo->name_list_element = XCAR (ns_display_name_list);
3792 /* Set the name of the terminal. */
3793 terminal->name = (char *) xmalloc (SBYTES (display_name) + 1);
3794 strncpy (terminal->name, SDATA (display_name), SBYTES (display_name));
3795 terminal->name[SBYTES (display_name)] = 0;
3799 /* Read various user defaults. */
3800 ns_set_default_prefs ();
3801 if (!ns_no_defaults)
3803 ns_default ("GSFontAntiAlias", &ns_antialias_text,
3806 /* this is a standard variable */
3807 ns_default ("AppleAntiAliasingThreshold", &tmp,
3808 make_float (10.0), make_float (6.0), YES, NO);
3809 ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
3812 ns_selection_color = [[NSUserDefaults standardUserDefaults]
3813 stringForKey: @"AppleHighlightColor"];
3814 if (ns_selection_color == nil)
3815 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
3818 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
3822 Lisp_Object color_file, color_map, color;
3827 color_file = Fexpand_file_name (build_string ("rgb.txt"),
3828 Fsymbol_value (intern ("data-directory")));
3829 if (NILP (Ffile_readable_p (color_file)))
3830 fatal ("Could not find %s.\n", SDATA (color_file));
3832 color_map = Fx_load_color_file (color_file);
3833 if (NILP (color_map))
3834 fatal ("Could not read %s.\n", SDATA (color_file));
3836 cl = [[NSColorList alloc] initWithName: @"Emacs"];
3837 for ( ; CONSP (color_map); color_map = XCDR (color_map))
3839 color = XCAR (color_map);
3840 name = SDATA (XCAR (color));
3841 c = XINT (XCDR (color));
3843 [NSColor colorWithCalibratedRed: RED_FROM_ULONG (c) / 255.0
3844 green: GREEN_FROM_ULONG (c) / 255.0
3845 blue: BLUE_FROM_ULONG (c) / 255.0
3847 forKey: [NSString stringWithUTF8String: name]];
3849 [cl writeToFile: nil];
3855 #ifdef NS_IMPL_GNUSTEP
3856 strncpy (c, gnustep_base_version, sizeof (c));
3858 /*PSnextrelease (128, c); */
3859 snprintf (c, sizeof (c), "%g", NSAppKitVersionNumber);
3861 Vwindow_system_version = build_string (c);
3864 delete_keyboard_wait_descriptor (0);
3866 /* Set up OS X app menu */
3867 #ifdef NS_IMPL_COCOA
3871 /* set up the application menu */
3872 svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
3873 [svcsMenu setAutoenablesItems: NO];
3874 appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
3875 [appMenu setAutoenablesItems: NO];
3876 mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
3877 dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
3879 [appMenu insertItemWithTitle: @"About Emacs"
3880 action: @selector (orderFrontStandardAboutPanel:)
3883 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
3884 [appMenu insertItemWithTitle: @"Preferences..."
3885 action: @selector (showPreferencesWindow:)
3888 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
3889 item = [appMenu insertItemWithTitle: @"Services"
3890 action: @selector (menuDown:)
3893 [appMenu setSubmenu: svcsMenu forItem: item];
3894 /* [svcsMenu setSupercell: item]; */
3895 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
3896 [appMenu insertItemWithTitle: @"Hide Emacs"
3897 action: @selector (hide:)
3900 item = [appMenu insertItemWithTitle: @"Hide Others"
3901 action: @selector (hideOtherApplications:)
3904 [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
3905 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
3906 [appMenu insertItemWithTitle: @"Quit Emacs"
3907 action: @selector (terminate:)
3911 item = [mainMenu insertItemWithTitle: @"Emacs"
3912 action: @selector (menuDown:)
3915 [mainMenu setSubmenu: appMenu forItem: item];
3916 [dockMenu insertItemWithTitle: @"New Frame"
3917 action: @selector (newFrame:)
3921 [NSApp setMainMenu: mainMenu];
3922 [NSApp setAppleMenu: appMenu];
3923 [NSApp setServicesMenu: svcsMenu];
3924 /* Needed at least on Cocoa, to get dock menu to show windows */
3925 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
3927 #endif /* MAC OS X menu setup */
3935 extern Lisp_Object Vauto_save_list_file_name;
3937 ns_term_shutdown (int sig)
3939 /* code not reached in emacs.c after this is called by shut_down_emacs: */
3940 if (STRINGP (Vauto_save_list_file_name))
3941 unlink (SDATA (Vauto_save_list_file_name));
3943 if (sig == 0 || sig == SIGTERM)
3945 [NSApp terminate: NSApp];
3947 else // force a stack trace to happen
3954 /* ==========================================================================
3956 EmacsApp implementation
3958 ========================================================================== */
3961 @implementation EmacsApp
3963 - (void)logNotification: (NSNotification *)notification
3965 const char *name = [[notification name] UTF8String];
3966 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
3967 && !strstr (name, "WindowNumber"))
3968 NSLog (@"notification: '%@'", [notification name]);
3972 - (void)sendEvent: (NSEvent *)theEvent
3973 /* --------------------------------------------------------------------------
3974 Called when NSApp is running for each event received. Used to stop
3975 the loop when we choose, since there's no way to just run one iteration.
3976 -------------------------------------------------------------------------- */
3978 int type = [theEvent type];
3979 NSWindow *window = [theEvent window];
3980 /* NSTRACE (sendEvent); */
3981 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
3983 if (type == NSCursorUpdate && window == nil)
3985 fprintf (stderr, "Dropping external cursor update event.\n");
3989 #ifdef NS_IMPL_COCOA
3990 /* pass mouse down in resize handle and subsequent drags directly to
3991 EmacsWindow so we can generate continuous redisplays */
3994 if (type == NSLeftMouseDragged)
3996 [window mouseDragged: theEvent];
3999 else if (type == NSLeftMouseUp)
4001 [window mouseUp: theEvent];
4005 else if (type == NSLeftMouseDown)
4007 NSRect r = ns_resize_handle_rect (window);
4008 if (NSPointInRect ([theEvent locationInWindow], r))
4011 [window mouseDown: theEvent];
4017 if (type == NSApplicationDefined)
4019 /* Events posted by ns_send_appdefined interrupt the run loop here.
4020 But, if a modal window is up, an appdefined can still come through,
4021 (e.g., from a makeKeyWindow event) but stopping self also stops the
4022 modal loop. Just defer it until later. */
4023 if ([NSApp modalWindow] == nil)
4025 last_appdefined_event = theEvent;
4030 send_appdefined = YES;
4034 [super sendEvent: theEvent];
4038 - (void)showPreferencesWindow: (id)sender
4040 struct frame *emacsframe = SELECTED_FRAME ();
4041 NSEvent *theEvent = [NSApp currentEvent];
4045 emacs_event->kind = NS_NONKEY_EVENT;
4046 emacs_event->code = KEY_NS_SHOW_PREFS;
4047 emacs_event->modifiers = 0;
4048 EV_TRAILER (theEvent);
4052 - (void)newFrame: (id)sender
4054 struct frame *emacsframe = SELECTED_FRAME ();
4055 NSEvent *theEvent = [NSApp currentEvent];
4059 emacs_event->kind = NS_NONKEY_EVENT;
4060 emacs_event->code = KEY_NS_NEW_FRAME;
4061 emacs_event->modifiers = 0;
4062 EV_TRAILER (theEvent);
4066 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4067 - (BOOL) openFile: (NSString *)fileName
4069 struct frame *emacsframe = SELECTED_FRAME ();
4070 NSEvent *theEvent = [NSApp currentEvent];
4075 emacs_event->kind = NS_NONKEY_EVENT;
4076 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4077 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4078 ns_input_line = Qnil; /* can be start or cons start,end */
4079 emacs_event->modifiers =0;
4080 EV_TRAILER (theEvent);
4086 /* **************************************************************************
4088 EmacsApp delegate implementation
4090 ************************************************************************** */
4092 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4093 /* --------------------------------------------------------------------------
4094 When application is loaded, terminate event loop in ns_term_init
4095 -------------------------------------------------------------------------- */
4097 NSTRACE (applicationDidFinishLaunching);
4098 [NSApp setServicesProvider: NSApp];
4099 ns_send_appdefined (-2);
4103 /* Termination sequences:
4106 MenuBar | File | Exit:
4107 Select Quit from App menubar:
4109 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4112 Select Quit from Dock menu:
4115 Cancel -> Nothing else
4119 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4124 - (void) terminate: (id)sender
4126 struct frame *emacsframe = SELECTED_FRAME ();
4131 emacs_event->kind = NS_NONKEY_EVENT;
4132 emacs_event->code = KEY_NS_POWER_OFF;
4133 emacs_event->arg = Qt; /* mark as non-key event */
4134 EV_TRAILER ((id)nil);
4138 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4142 if (NILP (ns_confirm_quit)) // || ns_shutdown_properly --> TO DO
4143 return NSTerminateNow;
4145 ret = NSRunAlertPanel([[NSProcessInfo processInfo] processName],
4146 [NSString stringWithUTF8String:"Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?"],
4147 @"Save Buffers and Exit", @"Cancel", nil);
4149 if (ret == NSAlertDefaultReturn)
4150 return NSTerminateNow;
4151 else if (ret == NSAlertAlternateReturn)
4152 return NSTerminateCancel;
4153 return NSTerminateNow; /* just in case */
4157 /* Notification from the Workspace to open a file */
4158 - (BOOL)application: sender openFile: (NSString *)file
4160 [ns_pending_files addObject: file];
4165 /* Open a file as a temporary file */
4166 - (BOOL)application: sender openTempFile: (NSString *)file
4168 [ns_pending_files addObject: file];
4173 /* Notification from the Workspace to open a file noninteractively (?) */
4174 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4176 [ns_pending_files addObject: file];
4181 /* Notification from the Workspace to open multiple files */
4182 - (void)application: sender openFiles: (NSArray *)fileList
4184 NSEnumerator *files = [fileList objectEnumerator];
4186 while ((file = [files nextObject]) != nil)
4187 [ns_pending_files addObject: file];
4189 /* TODO: when GNUstep implements this (and we require that version of
4190 GNUstep), remove. */
4191 #ifndef NS_IMPL_GNUSTEP
4192 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4193 #endif /* !NS_IMPL_GNUSTEP */
4198 /* Handle dock menu requests. */
4199 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4205 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4206 - (void)applicationWillBecomeActive: (NSNotification *)notification
4208 //ns_app_active=YES;
4210 - (void)applicationDidBecomeActive: (NSNotification *)notification
4212 //ns_app_active=YES;
4214 - (void)applicationDidResignActive: (NSNotification *)notification
4217 ns_send_appdefined (-1);
4222 /* ==========================================================================
4224 EmacsApp aux handlers for managing event loop
4226 ========================================================================== */
4229 - (void)timeout_handler: (NSTimer *)timedEntry
4230 /* --------------------------------------------------------------------------
4231 The timeout specified to ns_select has passed.
4232 -------------------------------------------------------------------------- */
4234 /*NSTRACE (timeout_handler); */
4235 ns_send_appdefined (-2);
4238 extern void update_window_cursor (struct window *w, int on);
4240 - (void)fd_handler: (NSTimer *) fdEntry
4241 /* --------------------------------------------------------------------------
4242 Check data waiting on file descriptors and terminate if so
4243 -------------------------------------------------------------------------- */
4246 /* NSTRACE (fd_handler); */
4248 if (select_nfds == 0)
4251 memcpy (&t_readfds, &select_readfds, sizeof (fd_set));
4253 select_timeout.tv_sec = select_timeout.tv_usec = 0;
4254 result = select (select_nfds, &t_readfds, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
4258 memcpy (&select_readfds, &t_readfds, sizeof (fd_set));
4259 ns_send_appdefined (result);
4265 /* ==========================================================================
4269 ========================================================================== */
4271 /* called from system: queue for next pass through event loop */
4272 - (void)requestService: (NSPasteboard *)pboard
4273 userData: (NSString *)userData
4274 error: (NSString **)error
4276 [ns_pending_service_names addObject: userData];
4277 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
4278 SDATA (ns_string_from_pasteboard (pboard))]];
4282 /* called from ns_read_socket to clear queue */
4283 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
4285 struct frame *emacsframe = SELECTED_FRAME ();
4286 NSEvent *theEvent = [NSApp currentEvent];
4291 emacs_event->kind = NS_NONKEY_EVENT;
4292 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
4293 ns_input_spi_name = build_string ([name UTF8String]);
4294 ns_input_spi_arg = build_string ([arg UTF8String]);
4295 emacs_event->modifiers = EV_MODIFIERS (theEvent);
4296 EV_TRAILER (theEvent);
4306 /* ==========================================================================
4308 EmacsView implementation
4310 ========================================================================== */
4313 @implementation EmacsView
4315 /* needed to inform when window closed from LISP */
4316 - (void) setWindowClosing: (BOOL)closing
4318 windowClosing = closing;
4324 NSTRACE (EmacsView_dealloc);
4330 /* called on font panel selection */
4331 - (void)changeFont: (id)sender
4333 NSEvent *e =[[self window] currentEvent];
4334 struct face *face =FRAME_DEFAULT_FACE (emacsframe);
4338 NSTRACE (changeFont);
4342 if (newFont = [sender convertFont:
4343 ((struct nsfont_info *)face->font)->nsfont])
4345 SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
4347 emacs_event->kind = NS_NONKEY_EVENT;
4348 emacs_event->modifiers = 0;
4349 emacs_event->code = KEY_NS_CHANGE_FONT;
4351 size = [newFont pointSize];
4352 ns_input_fontsize = make_number (lrint (size));
4353 ns_input_font = build_string ([[newFont familyName] UTF8String]);
4359 - (BOOL)acceptsFirstResponder
4361 NSTRACE (acceptsFirstResponder);
4366 - (void)resetCursorRects
4368 NSRect visible = [self visibleRect];
4369 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
4370 NSTRACE (resetCursorRects);
4372 if (currentCursor == nil)
4373 currentCursor = [NSCursor arrowCursor];
4375 if (!NSIsEmptyRect (visible))
4376 [self addCursorRect: visible cursor: currentCursor];
4377 [currentCursor setOnMouseEntered: YES];
4382 /*****************************************************************************/
4383 /* Keyboard handling. */
4386 - (void)keyDown: (NSEvent *)theEvent
4388 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4390 unsigned fnKeysym = 0;
4392 static NSMutableArray *nsEvArray;
4393 static BOOL firstTime = YES;
4397 /* Rhapsody and OS X give up and down events for the arrow keys */
4398 if (ns_fake_keydown == YES)
4399 ns_fake_keydown = NO;
4400 else if ([theEvent type] != NSKeyDown)
4406 if (![[self window] isKeyWindow]
4407 && [[theEvent window] isKindOfClass: [EmacsWindow class]]
4408 /* we must avoid an infinite loop here. */
4409 && (EmacsView *)[[theEvent window] delegate] != self)
4411 /* XXX: There is an occasional condition in which, when Emacs display
4412 updates a different frame from the current one, and temporarily
4413 selects it, then processes some interrupt-driven input
4414 (dispnew.c:3878), OS will send the event to the correct NSWindow, but
4415 for some reason that window has its first responder set to the NSView
4416 most recently updated (I guess), which is not the correct one. */
4417 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
4421 if (nsEvArray == nil)
4422 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
4424 [NSCursor setHiddenUntilMouseMoves: YES];
4426 if (dpyinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
4428 clear_mouse_face (dpyinfo);
4429 dpyinfo->mouse_face_hidden = 1;
4432 if (!processingCompose)
4434 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
4435 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
4436 /* (Carbon way: [theEvent keyCode]) */
4438 /* is it a "function key"? */
4439 fnKeysym = ns_convert_key (code);
4442 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
4443 because Emacs treats Delete and KP-Delete same (in simple.el). */
4444 if (fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
4445 code = 0xFF08; /* backspace */
4450 /* are there modifiers? */
4451 emacs_event->modifiers = 0;
4452 flags = [theEvent modifierFlags];
4454 if (flags & NSHelpKeyMask)
4455 emacs_event->modifiers |= hyper_modifier;
4457 if (flags & NSShiftKeyMask)
4458 emacs_event->modifiers |= shift_modifier;
4460 if (flags & NSCommandKeyMask)
4462 emacs_event->modifiers |= parse_solitary_modifier (ns_command_modifier);
4463 /* if super (default), take input manager's word so things like
4464 dvorak / qwerty layout work */
4465 if (EQ (ns_command_modifier, Qsuper)
4467 && [[theEvent characters] length] != 0)
4469 /* XXX: the code we get will be unshifted, so if we have
4470 a shift modifier, must convert ourselves */
4471 if (!(flags & NSShiftKeyMask))
4472 code = [[theEvent characters] characterAtIndex: 0];
4474 /* this is ugly and also requires linking w/Carbon framework
4475 (for LMGetKbdType) so for now leave this rare (?) case
4476 undealt with.. in future look into CGEvent methods */
4479 long smv = GetScriptManagerVariable (smKeyScript);
4480 Handle uchrHandle = GetResource
4481 ('uchr', GetScriptVariable (smv, smScriptKeys));
4483 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
4484 [[theEvent characters] characterAtIndex: 0],
4485 kUCKeyActionDisplay,
4486 (flags & ~NSCommandKeyMask) >> 8,
4487 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
4488 &dummy, 1, &dummy, &code);
4495 if (flags & NSControlKeyMask)
4496 emacs_event->modifiers |=
4497 parse_solitary_modifier (ns_control_modifier);
4499 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
4500 emacs_event->modifiers |=
4501 parse_solitary_modifier (ns_function_modifier);
4503 if (flags & NSAlternateKeyMask) /* default = meta */
4505 if ((NILP (ns_alternate_modifier) || EQ (ns_alternate_modifier, Qnone))
4507 { /* accept pre-interp alt comb */
4508 if ([[theEvent characters] length] > 0)
4509 code = [[theEvent characters] characterAtIndex: 0];
4510 /*HACK: clear lone shift modifier to stop next if from firing */
4511 if (emacs_event->modifiers == shift_modifier)
4512 emacs_event->modifiers = 0;
4515 emacs_event->modifiers |=
4516 parse_solitary_modifier (ns_alternate_modifier);
4520 fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
4521 code, fnKeysym, flags, emacs_event->modifiers);
4523 /* if it was a function key or had modifiers, pass it directly to emacs */
4524 if (fnKeysym || (emacs_event->modifiers
4525 && [[theEvent charactersIgnoringModifiers] length] > 0))
4526 /*[[theEvent characters] length] */
4528 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4530 code |= (1<<28)|(3<<16);
4531 else if (code == 0x7f)
4532 code |= (1<<28)|(3<<16);
4534 emacs_event->kind = code > 0xFF
4535 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4537 emacs_event->code = code;
4538 EV_TRAILER (theEvent);
4543 /* if we get here we should send the key for input manager processing */
4544 if (firstTime && [[NSInputManager currentInputManager]
4545 wantsToDelayTextChangeNotifications] == NO)
4547 "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
4550 if (NS_KEYLOG && !processingCompose)
4551 fprintf (stderr, "keyDown: Begin compose sequence.\n");
4553 processingCompose = YES;
4554 [nsEvArray addObject: theEvent];
4555 [self interpretKeyEvents: nsEvArray];
4556 [nsEvArray removeObject: theEvent];
4560 #ifdef NS_IMPL_COCOA
4561 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
4562 decided not to send key-down for.
4563 See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
4564 If it matches one of these, send it on to keyDown. */
4565 -(void)keyUp: (NSEvent *)theEvent
4567 int flags = [theEvent modifierFlags];
4568 int code = [theEvent keyCode];
4569 if (code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
4572 fprintf (stderr, "keyUp: passed test");
4573 ns_fake_keydown = YES;
4574 [self keyDown: theEvent];
4580 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
4583 /* <NSTextInput>: called when done composing;
4584 NOTE: also called when we delete over working text, followed immed.
4585 by doCommandBySelector: deleteBackward: */
4586 - (void)insertText: (id)aString
4589 int len = [(NSString *)aString length];
4593 NSLog (@"insertText '%@'\tlen = %d", aString, len);
4594 processingCompose = NO;
4599 /* first, clear any working text */
4600 if (workingText != nil)
4601 [self deleteWorkingText];
4603 /* now insert the string as keystrokes */
4604 for (i =0; i<len; i++)
4606 code = [aString characterAtIndex: i];
4607 /* TODO: still need this? */
4609 code = '~'; /* 0x7E */
4610 emacs_event->modifiers = 0;
4612 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4613 emacs_event->code = code;
4614 EV_TRAILER ((id)nil);
4619 /* <NSTextInput>: inserts display of composing characters */
4620 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
4622 NSString *str = [aString respondsToSelector: @selector (string)] ?
4623 [aString string] : aString;
4625 NSLog (@"setMarkedText '%@' len =%d range %d from %d", str, [str length],
4626 selRange.length, selRange.location);
4628 if (workingText != nil)
4629 [self deleteWorkingText];
4630 if ([str length] == 0)
4636 processingCompose = YES;
4637 workingText = [str copy];
4638 ns_working_text = build_string ([workingText UTF8String]);
4640 emacs_event->kind = NS_TEXT_EVENT;
4641 emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
4642 EV_TRAILER ((id)nil);
4646 /* delete display of composing characters [not in <NSTextInput>] */
4647 - (void)deleteWorkingText
4649 if (workingText == nil)
4652 NSLog(@"deleteWorkingText len =%d\n", [workingText length]);
4653 [workingText release];
4655 processingCompose = NO;
4660 emacs_event->kind = NS_TEXT_EVENT;
4661 emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
4662 EV_TRAILER ((id)nil);
4666 - (BOOL)hasMarkedText
4668 return workingText != nil;
4672 - (NSRange)markedRange
4674 NSRange rng = workingText != nil
4675 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
4677 NSLog (@"markedRange request");
4685 NSLog (@"unmark (accept) text");
4686 [self deleteWorkingText];
4687 processingCompose = NO;
4691 /* used to position char selection windows, etc. */
4692 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
4696 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
4698 NSLog (@"firstRectForCharRange request");
4700 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
4701 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
4702 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
4703 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
4704 +FRAME_LINE_HEIGHT (emacsframe));
4706 pt = [self convertPoint: pt toView: nil];
4707 pt = [[self window] convertBaseToScreen: pt];
4713 - (NSInteger)conversationIdentifier
4715 return (NSInteger)self;
4719 - (void)doCommandBySelector: (SEL)aSelector
4722 NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
4724 if (aSelector == @selector (deleteBackward:))
4726 /* happens when user backspaces over an ongoing composition:
4727 throw a 'delete' into the event queue */
4730 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4731 emacs_event->code = 0xFF08;
4732 EV_TRAILER ((id)nil);
4736 - (NSArray *)validAttributesForMarkedText
4738 static NSArray *arr = nil;
4739 if (arr == nil) arr = [NSArray new];
4740 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
4744 - (NSRange)selectedRange
4747 NSLog (@"selectedRange request");
4748 return NSMakeRange (NSNotFound, 0);
4751 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
4754 NSLog (@"characterIndexForPoint request");
4758 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
4760 static NSAttributedString *str = nil;
4761 if (str == nil) str = [NSAttributedString new];
4763 NSLog (@"attributedSubstringFromRange request");
4767 /* End <NSTextInput> impl. */
4768 /*****************************************************************************/
4771 /* This is what happens when the user presses a mouse button. */
4772 - (void)mouseDown: (NSEvent *)theEvent
4774 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
4777 NSTRACE (mouseDown);
4779 [self deleteWorkingText];
4784 last_mouse_frame = emacsframe;
4785 /* appears to be needed to prevent spurious movement events generated on
4787 last_mouse_frame->mouse_moved = 0;
4789 if ([theEvent type] == NSScrollWheel)
4791 float delta = [theEvent deltaY];
4792 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
4795 emacs_event->kind = WHEEL_EVENT;
4796 emacs_event->code = 0;
4797 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
4798 ((delta > 0) ? up_modifier : down_modifier);
4802 emacs_event->kind = MOUSE_CLICK_EVENT;
4803 emacs_event->code = EV_BUTTON (theEvent);
4804 emacs_event->modifiers = EV_MODIFIERS (theEvent)
4805 | EV_UDMODIFIERS (theEvent);
4807 XSETINT (emacs_event->x, lrint (p.x));
4808 XSETINT (emacs_event->y, lrint (p.y));
4809 EV_TRAILER (theEvent);
4813 - (void)rightMouseDown: (NSEvent *)theEvent
4815 NSTRACE (rightMouseDown);
4816 [self mouseDown: theEvent];
4820 - (void)otherMouseDown: (NSEvent *)theEvent
4822 NSTRACE (otherMouseDown);
4823 [self mouseDown: theEvent];
4827 - (void)mouseUp: (NSEvent *)theEvent
4830 [self mouseDown: theEvent];
4834 - (void)rightMouseUp: (NSEvent *)theEvent
4836 NSTRACE (rightMouseUp);
4837 [self mouseDown: theEvent];
4841 - (void)otherMouseUp: (NSEvent *)theEvent
4843 NSTRACE (otherMouseUp);
4844 [self mouseDown: theEvent];
4848 - (void) scrollWheel: (NSEvent *)theEvent
4850 NSTRACE (scrollWheel);
4851 [self mouseDown: theEvent];
4855 /* Tell emacs the mouse has moved. */
4856 - (void)mouseMoved: (NSEvent *)e
4858 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4861 // NSTRACE (mouseMoved);
4863 last_mouse_movement_time = EV_TIMESTAMP (e);
4864 last_mouse_motion_position
4865 = [self convertPoint: [e locationInWindow] fromView: nil];
4867 /* update any mouse face */
4868 if (dpyinfo->mouse_face_hidden)
4870 dpyinfo->mouse_face_hidden = 0;
4871 clear_mouse_face (dpyinfo);
4874 /* tooltip handling */
4875 previous_help_echo_string = help_echo_string;
4876 help_echo_string = Qnil;
4878 if (!note_mouse_movement (emacsframe, last_mouse_motion_position.x,
4879 last_mouse_motion_position.y))
4880 help_echo_string = previous_help_echo_string;
4882 XSETFRAME (frame, emacsframe);
4883 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
4885 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
4886 (note_mouse_highlight), which is called through the
4887 note_mouse_movement () call above */
4888 gen_help_event (help_echo_string, frame, help_echo_window,
4889 help_echo_object, help_echo_pos);
4893 help_echo_string = Qnil;
4894 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
4897 if (emacsframe->mouse_moved && send_appdefined)
4898 ns_send_appdefined (-1);
4902 - (void)mouseDragged: (NSEvent *)e
4904 NSTRACE (mouseDragged);
4905 [self mouseMoved: e];
4909 - (void)rightMouseDragged: (NSEvent *)e
4911 NSTRACE (rightMouseDragged);
4912 [self mouseMoved: e];
4916 - (void)otherMouseDragged: (NSEvent *)e
4918 NSTRACE (otherMouseDragged);
4919 [self mouseMoved: e];
4923 - (BOOL)windowShouldClose: (id)sender
4925 NSEvent *e =[[self window] currentEvent];
4927 NSTRACE (windowShouldClose);
4928 windowClosing = YES;
4931 emacs_event->kind = DELETE_WINDOW_EVENT;
4932 emacs_event->modifiers = 0;
4933 emacs_event->code = 0;
4935 /* Don't close this window, let this be done from lisp code. */
4940 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
4941 /* normalize frame to gridded text size */
4943 NSTRACE (windowWillResize);
4944 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
4946 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe,
4947 #ifdef NS_IMPL_GNUSTEP
4948 frameSize.width + 3);
4952 if (cols < MINWIDTH)
4954 frameSize.width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (emacsframe, cols);
4956 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, frameSize.height
4957 #ifdef NS_IMPL_GNUSTEP
4958 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe) + 3
4959 - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
4961 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
4962 - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
4964 if (rows < MINHEIGHT)
4966 frameSize.height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows)
4967 + FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
4968 + FRAME_NS_TOOLBAR_HEIGHT (emacsframe);
4969 #ifdef NS_IMPL_COCOA
4971 /* this sets window title to have size in it; the wm does this under GS */
4972 NSRect r = [[self window] frame];
4973 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
4984 NSWindow *window = [self window];
4987 const char *t = [[[self window] title] UTF8String];
4988 char *pos = strstr (t, " — ");
4991 old_title = (char *) xmalloc (strlen (t) + 1);
4992 strcpy (old_title, t);
4994 size_title = xmalloc (strlen (old_title) + 40);
4995 sprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
4996 [window setTitle: [NSString stringWithUTF8String: size_title]];
5001 #endif /* NS_IMPL_COCOA */
5002 /*fprintf (stderr," ...size became %.0f x %.0f (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
5008 - (void)windowDidResize: (NSNotification *)notification
5010 NSWindow *theWindow = [notification object];
5012 #ifdef NS_IMPL_GNUSTEP
5013 /* in GNUstep, at least currently, it's possible to get a didResize
5014 without getting a willResize.. therefore we need to act as if we got
5015 the willResize now */
5016 NSSize sz = [theWindow frame].size;
5017 sz = [self windowWillResize: theWindow toSize: sz];
5018 #endif /* NS_IMPL_GNUSTEP */
5020 NSTRACE (windowDidResize);
5021 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
5023 #ifdef NS_IMPL_COCOA
5029 #endif /* NS_IMPL_COCOA */
5031 // Calling x_set_window_size tends to get us into inf-loops
5032 // (x_set_window_size causes a resize which causes
5033 // a "windowDidResize" which calls x_set_window_size).
5034 // At least with GNUStep, don't know about MacOSX. --Stef
5035 #ifndef NS_IMPL_GNUSTEP
5036 if (cols > 0 && rows > 0)
5037 x_set_window_size (emacsframe, 0, cols, rows);
5040 ns_send_appdefined (-1);
5044 - (void)windowDidBecomeKey: (NSNotification *)notification
5045 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5047 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5048 struct frame *old_focus = dpyinfo->x_focus_frame;
5050 NSTRACE (windowDidBecomeKey);
5052 if (emacsframe != old_focus)
5053 dpyinfo->x_focus_frame = emacsframe;
5055 ns_frame_rehighlight (emacsframe);
5059 emacs_event->kind = FOCUS_IN_EVENT;
5060 EV_TRAILER ((id)nil);
5065 - (void)windowDidResignKey: (NSNotification *)notification
5066 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5068 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5069 NSTRACE (windowDidResignKey);
5071 if (dpyinfo->x_focus_frame == emacsframe)
5072 dpyinfo->x_focus_frame = 0;
5074 ns_frame_rehighlight (emacsframe);
5076 /* FIXME: for some reason needed on second and subsequent clicks away
5077 from sole-frame Emacs to get hollow box to show */
5078 if (!windowClosing && [[self window] isVisible] == YES)
5080 x_update_cursor (emacsframe, 1);
5081 x_set_frame_alpha (emacsframe);
5086 [self deleteWorkingText];
5087 emacs_event->kind = FOCUS_IN_EVENT;
5088 EV_TRAILER ((id)nil);
5093 - (void)windowWillMiniaturize: sender
5095 NSTRACE (windowWillMiniaturize);
5111 - initFrameFromEmacs: (struct frame *)f
5116 NSButton *toggleButton;
5117 int vbextra = NS_SCROLL_BAR_WIDTH (f);
5122 NSTRACE (initFrameFromEmacs);
5125 processingCompose = NO;
5126 scrollbarsNeedingUpdate = 0;
5128 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
5130 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
5131 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
5132 [self initWithFrame: r];
5134 FRAME_NS_VIEW (f) = self;
5138 win = [[EmacsWindow alloc]
5139 initWithContentRect: r
5140 styleMask: (NSResizableWindowMask |
5141 NSMiniaturizableWindowMask |
5142 NSClosableWindowMask)
5143 backing: NSBackingStoreBuffered
5147 f->border_width = wr.size.width - r.size.width;
5148 FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
5150 [win setAcceptsMouseMovedEvents: YES];
5151 [win setDelegate: self];
5152 [win useOptimizedDrawing: YES];
5154 sz.width = FRAME_COLUMN_WIDTH (f);
5155 sz.height = FRAME_LINE_HEIGHT (f);
5156 [win setResizeIncrements: sz];
5158 [[win contentView] addSubview: self];
5161 [self registerForDraggedTypes: ns_drag_types];
5164 name = [NSString stringWithUTF8String:
5165 NILP (tem) ? (unsigned char *)"Emacs" : SDATA (tem)];
5166 [win setTitle: name];
5168 /* toolbar support */
5169 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
5170 [NSString stringWithFormat: @"Emacs Frame %d",
5172 [win setToolbar: toolbar];
5173 [toolbar setVisible: NO];
5174 #ifdef NS_IMPL_COCOA
5175 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
5176 [toggleButton setTarget: self];
5177 [toggleButton setAction: @selector (toggleToolbar: )];
5179 FRAME_NS_TOOLBAR_HEIGHT (f) = 0;
5183 [win setMiniwindowTitle:
5184 [NSString stringWithUTF8String: SDATA (tem)]];
5187 NSScreen *screen = [win screen];
5190 [win setFrameTopLeftPoint: NSMakePoint
5191 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
5192 IN_BOUND (-SCREENMAX,
5193 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
5196 [win makeFirstResponder: self];
5198 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5199 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
5200 [win setBackgroundColor: col];
5201 if ([col alphaComponent] != 1.0)
5202 [win setOpaque: NO];
5204 [self allocateGState];
5211 - (void)windowDidMove: sender
5213 NSWindow *win = [self window];
5214 NSRect r = [win frame];
5215 NSScreen *screen = [win screen];
5216 NSRect sr = [screen frame];
5218 NSTRACE (windowDidMove);
5220 if (!emacsframe->output_data.ns)
5224 emacsframe->left_pos = r.origin.x; /* - sr.origin.x; */
5225 emacsframe->top_pos = sr.size.height -
5226 (r.origin.y + r.size.height); /* + sr.origin.y; */
5230 #ifdef NS_IMPL_COCOA
5231 /* if we don't do this manually, the window will resize but not move */
5232 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
5234 NSTRACE (windowShouldZoom);
5235 [[self window] setFrame: newFrame display: NO];
5241 /* Override to do something slightly nonstandard, but nice. First click on
5242 zoom button will zoom vertically. Second will zoom completely. Third
5243 returns to original. */
5244 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
5245 defaultFrame:(NSRect)defaultFrame
5247 NSRect result = [sender frame];
5248 NSTRACE (windowWillUseStandardFrame);
5250 if (result.size.height == defaultFrame.size.height) {
5251 result = defaultFrame;
5253 result.size.height = defaultFrame.size.height;
5254 result.origin.y = defaultFrame.origin.y;
5257 /* A windowWillResize does not get generated at least on Tiger. */
5258 [self windowWillResize: sender toSize: result.size];
5263 - (void)windowDidDeminiaturize: sender
5265 NSTRACE (windowDidDeminiaturize);
5266 if (!emacsframe->output_data.ns)
5268 emacsframe->async_iconified = 0;
5269 emacsframe->async_visible = 1;
5270 windows_or_buffers_changed++;
5274 emacs_event->kind = ICONIFY_EVENT;
5275 EV_TRAILER ((id)nil);
5280 - (void)windowDidExpose: sender
5282 NSTRACE (windowDidExpose);
5283 if (!emacsframe->output_data.ns)
5285 emacsframe->async_visible = 1;
5286 SET_FRAME_GARBAGED (emacsframe);
5288 if (send_appdefined)
5289 ns_send_appdefined (-1);
5293 - (void)windowDidMiniaturize: sender
5295 NSTRACE (windowDidMiniaturize);
5296 if (!emacsframe->output_data.ns)
5299 emacsframe->async_iconified = 1;
5300 emacsframe->async_visible = 0;
5304 emacs_event->kind = ICONIFY_EVENT;
5305 EV_TRAILER ((id)nil);
5310 - (void)mouseEntered: (NSEvent *)theEvent
5312 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5313 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5314 NSTRACE (mouseEntered);
5316 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5320 - (void)mouseExited: (NSEvent *)theEvent
5322 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5324 struct ns_display_info *dpyinfo
5325 = emacsframe ? FRAME_NS_DISPLAY_INFO (emacsframe) : NULL;
5327 NSTRACE (mouseExited);
5329 if (dpyinfo || !emacsframe)
5332 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5334 if (emacsframe == dpyinfo->mouse_face_mouse_frame)
5336 clear_mouse_face (dpyinfo);
5337 dpyinfo->mouse_face_mouse_frame = 0;
5345 if (context_menu_value == -1)
5346 context_menu_value = [sender tag];
5348 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
5349 emacsframe->menu_bar_vector,
5350 (void *)[sender tag]);
5351 ns_send_appdefined (-1);
5356 - (EmacsToolbar *)toolbar
5362 /* this gets called on toolbar button click */
5363 - toolbarClicked: (id)item
5366 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
5368 NSTRACE (toolbarClicked);
5373 /* send first event (for some reason two needed) */
5374 theEvent = [[self window] currentEvent];
5375 emacs_event->kind = TOOL_BAR_EVENT;
5376 XSETFRAME (emacs_event->arg, emacsframe);
5377 EV_TRAILER (theEvent);
5379 emacs_event->kind = TOOL_BAR_EVENT;
5380 /* XSETINT (emacs_event->code, 0); */
5381 emacs_event->arg = AREF (emacsframe->tool_bar_items,
5382 idx + TOOL_BAR_ITEM_KEY);
5383 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5384 EV_TRAILER (theEvent);
5389 - toggleToolbar: (id)sender
5394 emacs_event->kind = NS_NONKEY_EVENT;
5395 emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
5396 EV_TRAILER ((id)nil);
5401 - (void)drawRect: (NSRect)rect
5403 int x = NSMinX (rect), y = NSMinY (rect);
5404 int width = NSWidth (rect), height = NSHeight (rect);
5408 if (!emacsframe || !emacsframe->output_data.ns || ns_in_resize)
5411 ns_clear_frame_area (emacsframe, x, y, width, height);
5412 expose_frame (emacsframe, x, y, width, height);
5415 drawRect: may be called (at least in OS X 10.5) for invisible
5416 views as well for some reason. Thus, do not infer visibility
5419 emacsframe->async_visible = 1;
5420 emacsframe->async_iconified = 0;
5425 /* NSDraggingDestination protocol methods. Actually this is not really a
5426 protocol, but a category of Object. O well... */
5428 -(unsigned int) draggingEntered: (id <NSDraggingInfo>) sender
5430 NSTRACE (draggingEntered);
5431 return NSDragOperationGeneric;
5435 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
5441 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
5446 NSEvent *theEvent = [[self window] currentEvent];
5449 NSTRACE (performDragOperation);
5454 position = [self convertPoint: [sender draggingLocation] fromView: nil];
5455 x = lrint (position.x); y = lrint (position.y);
5457 pb = [sender draggingPasteboard];
5458 type = [pb availableTypeFromArray: ns_drag_types];
5463 else if ([type isEqualToString: NSFilenamesPboardType])
5466 NSEnumerator *fenum;
5469 if (!(files = [pb propertyListForType: type]))
5472 fenum = [files objectEnumerator];
5473 while ( (file = [fenum nextObject]) )
5475 emacs_event->kind = NS_NONKEY_EVENT;
5476 emacs_event->code = KEY_NS_DRAG_FILE;
5477 XSETINT (emacs_event->x, x);
5478 XSETINT (emacs_event->y, y);
5479 ns_input_file = append2 (ns_input_file,
5480 build_string ([file UTF8String]));
5481 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5482 EV_TRAILER (theEvent);
5486 else if ([type isEqualToString: NSURLPboardType])
5491 if (!(fileURL = [NSURL URLFromPasteboard: pb]) ||
5492 [fileURL isFileURL] == NO)
5495 file = [fileURL path];
5496 emacs_event->kind = NS_NONKEY_EVENT;
5497 emacs_event->code = KEY_NS_DRAG_FILE;
5498 XSETINT (emacs_event->x, x);
5499 XSETINT (emacs_event->y, y);
5500 ns_input_file = append2 (ns_input_file, build_string ([file UTF8String]));
5501 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5502 EV_TRAILER (theEvent);
5505 else if ([type isEqualToString: NSStringPboardType]
5506 || [type isEqualToString: NSTabularTextPboardType])
5510 if (! (data = [pb stringForType: type]))
5513 emacs_event->kind = NS_NONKEY_EVENT;
5514 emacs_event->code = KEY_NS_DRAG_TEXT;
5515 XSETINT (emacs_event->x, x);
5516 XSETINT (emacs_event->y, y);
5517 ns_input_text = build_string ([data UTF8String]);
5518 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5519 EV_TRAILER (theEvent);
5522 else if ([type isEqualToString: NSColorPboardType])
5524 NSColor *c = [NSColor colorFromPasteboard: pb];
5525 emacs_event->kind = NS_NONKEY_EVENT;
5526 emacs_event->code = KEY_NS_DRAG_COLOR;
5527 XSETINT (emacs_event->x, x);
5528 XSETINT (emacs_event->y, y);
5529 ns_input_color = ns_color_to_lisp (c);
5530 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5531 EV_TRAILER (theEvent);
5534 else if ([type isEqualToString: NSFontPboardType])
5536 /* impl based on GNUstep NSTextView.m */
5537 NSData *data = [pb dataForType: NSFontPboardType];
5538 NSDictionary *dict = [NSUnarchiver unarchiveObjectWithData: data];
5539 NSFont *font = [dict objectForKey: NSFontAttributeName];
5545 emacs_event->kind = NS_NONKEY_EVENT;
5546 emacs_event->code = KEY_NS_CHANGE_FONT;
5547 XSETINT (emacs_event->x, x);
5548 XSETINT (emacs_event->y, y);
5549 ns_input_font = build_string ([[font fontName] UTF8String]);
5550 snprintf (fontSize, 10, "%f", [font pointSize]);
5551 ns_input_fontsize = build_string (fontSize);
5552 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5553 EV_TRAILER (theEvent);
5558 error ("Invalid data type in dragging pasteboard.");
5564 - validRequestorForSendType: (NSString *)typeSent
5565 returnType: (NSString *)typeReturned
5567 NSTRACE (validRequestorForSendType);
5568 if ([ns_send_types indexOfObjectIdenticalTo: typeSent] != NSNotFound &&
5569 [ns_return_types indexOfObjectIdenticalTo: typeSent] != NSNotFound)
5572 return [super validRequestorForSendType: typeSent
5573 returnType: typeReturned];
5577 /* The next two methods are part of NSServicesRequests informal protocol,
5578 supposedly called when a services menu item is chosen from this app.
5579 But this should not happen because we override the services menu with our
5580 own entries which call ns-perform-service.
5581 Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
5582 So let's at least stub them out until further investigation can be done. */
5584 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
5586 /* we could call ns_string_from_pasteboard(pboard) here but then it should
5587 be written into the buffer in place of the existing selection..
5588 ordinary service calls go through functions defined in ns-win.el */
5592 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
5594 /* supposed to write for as many of types as we are able */
5599 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
5600 (gives a miniaturized version of the window); currently we use the latter for
5601 frames whose active buffer doesn't correspond to any file
5602 (e.g., '*scratch*') */
5603 - setMiniwindowImage: (BOOL) setMini
5605 id image = [[self window] miniwindowImage];
5606 NSTRACE (setMiniwindowImage);
5608 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
5609 about "AppleDockIconEnabled" notwithstanding, however the set message
5610 below has its effect nonetheless. */
5611 if (image != emacsframe->output_data.ns->miniimage)
5613 if (image && [image isKindOfClass: [EmacsImage class]])
5615 [[self window] setMiniwindowImage:
5616 setMini ? emacsframe->output_data.ns->miniimage : nil];
5623 - (void) setRows: (int) r andColumns: (int) c
5629 @end /* EmacsView */
5633 /* ==========================================================================
5635 EmacsWindow implementation
5637 ========================================================================== */
5639 @implementation EmacsWindow
5641 /* called only on resize clicks by special case in EmacsApp-sendEvent */
5642 - (void)mouseDown: (NSEvent *)theEvent
5646 NSSize size = [[theEvent window] frame].size;
5647 grabOffset = [theEvent locationInWindow];
5648 grabOffset.x = size.width - grabOffset.x;
5651 [super mouseDown: theEvent];
5656 - (void)mouseUp: (NSEvent *)theEvent
5660 struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
5662 ns_set_name_as_filename (f);
5664 ns_send_appdefined (-1);
5667 [super mouseUp: theEvent];
5671 /* send resize events */
5672 - (void)mouseDragged: (NSEvent *)theEvent
5676 NSPoint p = [theEvent locationInWindow];
5677 NSSize size, vettedSize, origSize = [self frame].size;
5679 size.width = p.x + grabOffset.x;
5680 size.height = origSize.height - p.y + grabOffset.y;
5682 if (size.width == origSize.width && size.height == origSize.height)
5685 vettedSize = [[self delegate] windowWillResize: self toSize: size];
5686 if (vettedSize.width != size.width || vettedSize.height != size.height)
5688 [[NSNotificationCenter defaultCenter]
5689 postNotificationName: NSWindowDidResizeNotification
5694 [super mouseDragged: theEvent];
5697 @end /* EmacsWindow */
5700 /* ==========================================================================
5702 EmacsScroller implementation
5704 ========================================================================== */
5707 @implementation EmacsScroller
5709 /* for repeat button push */
5710 #define SCROLL_BAR_FIRST_DELAY 0.5
5711 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
5713 + (float) scrollerWidth
5715 /* TODO: if we want to allow variable widths, this is the place to do it,
5716 however neither GNUstep nor Cocoa support it very well */
5717 return [NSScroller scrollerWidth];
5721 - initFrame: (NSRect )r window: (Lisp_Object)nwin
5723 NSTRACE (EmacsScroller_initFrame);
5725 r.size.width = [EmacsScroller scrollerWidth];
5726 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
5727 [self setContinuous: YES];
5728 [self setEnabled: YES];
5730 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
5731 locked against the right, top and bottom edges. */
5732 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
5736 pixel_height = NSHeight (r);
5737 min_portion = 20 / pixel_height;
5739 frame = XFRAME (XWINDOW (win)->frame);
5740 if (FRAME_LIVE_P (frame))
5743 EmacsView *view = FRAME_NS_VIEW (frame);
5744 NSView *sview = [[view window] contentView];
5745 NSArray *subs = [sview subviews];
5747 /* disable optimization stopping redraw of other scrollbars */
5748 view->scrollbarsNeedingUpdate = 0;
5749 for (i =[subs count]-1; i >= 0; i--)
5750 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
5751 view->scrollbarsNeedingUpdate++;
5752 [sview addSubview: self];
5755 /* [self setFrame: r]; */
5761 - (void)setFrame: (NSRect)newRect
5763 NSTRACE (EmacsScroller_setFrame);
5765 pixel_height = NSHeight (newRect);
5766 min_portion = 20 / pixel_height;
5767 [super setFrame: newRect];
5769 /* UNBLOCK_INPUT; */
5775 NSTRACE (EmacsScroller_dealloc);
5777 XWINDOW (win)->vertical_scroll_bar = Qnil;
5804 /* ensure other scrollbar updates after deletion */
5805 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
5807 view->scrollbarsNeedingUpdate++;
5808 [self removeFromSuperview];
5816 - (void)resetCursorRects
5818 NSRect visible = [self visibleRect];
5819 NSTRACE (resetCursorRects);
5821 if (!NSIsEmptyRect (visible))
5822 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
5823 [[NSCursor arrowCursor] setOnMouseEntered: YES];
5827 - (int) checkSamePosition: (int) position portion: (int) portion
5830 return em_position ==position && em_portion ==portion && em_whole ==whole
5831 && portion != whole; /* needed for resize empty buf */
5835 - setPosition: (int)position portion: (int)portion whole: (int)whole
5837 NSTRACE (setPosition);
5839 em_position = position;
5840 em_portion = portion;
5843 if (portion >= whole)
5844 [self setFloatValue: 0.0 knobProportion: 1.0];
5848 portion = max ((float)whole*min_portion/pixel_height, portion);
5849 pos = (float)position / (whole - portion);
5850 por = (float)portion/whole;
5851 [self setFloatValue: pos knobProportion: por];
5853 #ifdef NS_IMPL_GNUSTEP
5859 /* FIXME: unused at moment (see ns_mouse_position) at the moment because
5860 drag events will go directly to the EmacsScroller. Leaving in for now. */
5861 -(void)getMouseMotionPart: (int *)part window: (Lisp_Object *)window
5862 x: (Lisp_Object *)x y: ( Lisp_Object *)y
5864 *part = last_hit_part;
5866 XSETINT (*y, pixel_height);
5867 if ([self floatValue] > 0.999)
5868 XSETINT (*x, pixel_height);
5870 XSETINT (*x, pixel_height * [self floatValue]);
5874 /* set up emacs_event */
5875 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
5880 emacs_event->part = last_hit_part;
5881 emacs_event->code = 0;
5882 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
5883 emacs_event->frame_or_window = win;
5884 emacs_event->timestamp = EV_TIMESTAMP (e);
5885 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
5886 emacs_event->arg = Qnil;
5887 XSETINT (emacs_event->x, loc * pixel_height);
5888 XSETINT (emacs_event->y, pixel_height-20);
5890 n_emacs_events_pending++;
5891 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
5892 EVENT_INIT (*emacs_event);
5893 ns_send_appdefined (-1);
5897 /* called manually thru timer to implement repeated button action w/hold-down */
5898 - repeatScroll: (NSTimer *)scrollEntry
5900 NSEvent *e = [[self window] currentEvent];
5901 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
5902 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
5904 /* clear timer if need be */
5905 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
5907 [scroll_repeat_entry invalidate];
5908 [scroll_repeat_entry release];
5909 scroll_repeat_entry = nil;
5915 = [[NSTimer scheduledTimerWithTimeInterval:
5916 SCROLL_BAR_CONTINUOUS_DELAY
5918 selector: @selector (repeatScroll:)
5924 [self sendScrollEventAtLoc: 0 fromEvent: e];
5929 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
5930 mouseDragged events without going into a modal loop. */
5931 - (void)mouseDown: (NSEvent *)e
5934 /* hitPart is only updated AFTER event is passed on */
5935 NSScrollerPart part = [self testPart: [e locationInWindow]];
5936 double inc = 0.0, loc, kloc, pos;
5939 NSTRACE (EmacsScroller_mouseDown);
5943 case NSScrollerDecrementPage:
5944 last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
5945 case NSScrollerIncrementPage:
5946 last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
5947 case NSScrollerDecrementLine:
5948 last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
5949 case NSScrollerIncrementLine:
5950 last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
5951 case NSScrollerKnob:
5952 last_hit_part = scroll_bar_handle; break;
5953 case NSScrollerKnobSlot: /* GNUstep-only */
5954 last_hit_part = scroll_bar_move_ratio; break;
5955 default: /* NSScrollerNoPart? */
5956 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %d\n", part);
5962 pos = 0; /* ignored */
5964 /* set a timer to repeat, as we can't let superclass do this modally */
5966 = [[NSTimer scheduledTimerWithTimeInterval: 0.5
5968 selector: @selector (repeatScroll:)
5975 /* handle, or on GNUstep possibly slot */
5976 NSEvent *fake_event;
5978 /* compute float loc in slot and mouse offset on knob */
5979 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
5981 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
5987 else if (loc >= NSHeight (sr))
5989 loc = NSHeight (sr);
5997 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
5999 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
6001 last_mouse_offset = kloc;
6003 /* if knob, tell emacs a location offset by knob pos
6004 (to indicate top of handle) */
6005 if (part == NSScrollerKnob)
6006 pos = (loc - last_mouse_offset) / NSHeight (sr);
6008 /* else this is a slot click on GNUstep: go straight there */
6009 pos = loc / NSHeight (sr);
6011 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
6012 fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
6013 location: [e locationInWindow]
6014 modifierFlags: [e modifierFlags]
6015 timestamp: [e timestamp]
6016 windowNumber: [e windowNumber]
6017 context: [e context]
6018 eventNumber: [e eventNumber]
6019 clickCount: [e clickCount]
6020 pressure: [e pressure]];
6021 [super mouseUp: fake_event];
6024 if (part != NSScrollerKnob)
6025 [self sendScrollEventAtLoc: pos fromEvent: e];
6029 /* Called as we manually track scroller drags, rather than superclass. */
6030 - (void)mouseDragged: (NSEvent *)e
6036 NSTRACE (EmacsScroller_mouseDragged);
6038 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6040 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6047 else if (loc >= NSHeight (sr) + last_mouse_offset)
6049 loc = NSHeight (sr) + last_mouse_offset;
6053 pos = /*(edge ? loc :*/ (loc - last_mouse_offset) / NSHeight (sr);
6054 [self sendScrollEventAtLoc: pos fromEvent: e];
6058 - (void)mouseUp: (NSEvent *)e
6060 if (scroll_repeat_entry)
6062 [scroll_repeat_entry invalidate];
6063 [scroll_repeat_entry release];
6064 scroll_repeat_entry = nil;
6070 /* treat scrollwheel events in the bar as though they were in the main window */
6071 - (void) scrollWheel: (NSEvent *)theEvent
6073 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
6074 [view mouseDown: theEvent];
6077 @end /* EmacsScroller */
6082 /* ==========================================================================
6084 Font-related functions; these used to be in nsfaces.m
6086 ========================================================================== */
6090 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
6092 struct font *font = XFONT_OBJECT (font_object);
6095 fontset = fontset_from_font (font_object);
6096 FRAME_FONTSET (f) = fontset;
6098 if (FRAME_FONT (f) == font)
6099 /* This font is already set in frame F. There's nothing more to
6103 FRAME_FONT (f) = font;
6105 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
6106 FRAME_COLUMN_WIDTH (f) = font->average_width;
6107 FRAME_SPACE_WIDTH (f) = font->space_width;
6108 FRAME_LINE_HEIGHT (f) = font->height;
6110 compute_fringe_widths (f, 1);
6112 /* Compute the scroll bar width in character columns. */
6113 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
6115 int wid = FRAME_COLUMN_WIDTH (f);
6116 FRAME_CONFIG_SCROLL_BAR_COLS (f)
6117 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
6121 int wid = FRAME_COLUMN_WIDTH (f);
6122 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
6125 /* Now make the frame display the given font. */
6126 if (FRAME_NS_WINDOW (f) != 0)
6127 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
6133 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
6134 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
6138 ns_xlfd_to_fontname (const char *xlfd)
6139 /* --------------------------------------------------------------------------
6140 Convert an X font name (XLFD) to an NS font name.
6141 Only family is used.
6142 The string returned is temporarily allocated.
6143 -------------------------------------------------------------------------- */
6145 char *name = xmalloc (180);
6149 if (!strncmp (xlfd, "--", 2))
6150 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
6152 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
6154 /* stopgap for malformed XLFD input */
6155 if (strlen (name) == 0)
6156 strcpy (name, "Monaco");
6158 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
6159 also uppercase after '-' or ' ' */
6160 name[0] = toupper (name[0]);
6161 for (len =strlen (name), i =0; i<len; i++)
6167 name[i+1] = toupper (name[i+1]);
6169 else if (name[i] == '_')
6173 name[i+1] = toupper (name[i+1]);
6176 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
6177 ret = [[NSString stringWithUTF8String: name] UTF8String];
6186 NSTRACE (syms_of_nsterm);
6187 DEFVAR_LISP ("ns-input-file", &ns_input_file,
6188 "The file specified in the last NS event.");
6189 ns_input_file =Qnil;
6191 DEFVAR_LISP ("ns-input-text", &ns_input_text,
6192 "The data received in the last NS text drag event.");
6193 ns_input_text =Qnil;
6195 DEFVAR_LISP ("ns-working-text", &ns_working_text,
6196 "String for visualizing working composition sequence.");
6197 ns_working_text =Qnil;
6199 DEFVAR_LISP ("ns-input-font", &ns_input_font,
6200 "The font specified in the last NS event.");
6201 ns_input_font =Qnil;
6203 DEFVAR_LISP ("ns-input-fontsize", &ns_input_fontsize,
6204 "The fontsize specified in the last NS event.");
6205 ns_input_fontsize =Qnil;
6207 DEFVAR_LISP ("ns-input-line", &ns_input_line,
6208 "The line specified in the last NS event.");
6209 ns_input_line =Qnil;
6211 DEFVAR_LISP ("ns-input-color", &ns_input_color,
6212 "The color specified in the last NS event.");
6213 ns_input_color =Qnil;
6215 DEFVAR_LISP ("ns-input-spi-name", &ns_input_spi_name,
6216 "The service name specified in the last NS event.");
6217 ns_input_spi_name =Qnil;
6219 DEFVAR_LISP ("ns-input-spi-arg", &ns_input_spi_arg,
6220 "The service argument specified in the last NS event.");
6221 ns_input_spi_arg =Qnil;
6223 DEFVAR_LISP ("ns-alternate-modifier", &ns_alternate_modifier,
6224 "This variable describes the behavior of the alternate or option key.\n\
6225 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6226 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6227 at all, allowing it to be used at a lower level for accented character entry.");
6229 DEFVAR_LISP ("ns-command-modifier", &ns_command_modifier,
6230 "This variable describes the behavior of the command key.\n\
6231 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6233 DEFVAR_LISP ("ns-control-modifier", &ns_control_modifier,
6234 "This variable describes the behavior of the control key.\n\
6235 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6237 DEFVAR_LISP ("ns-function-modifier", &ns_function_modifier,
6238 "This variable describes the behavior of the function key (on laptops).\n\
6239 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6240 Set to none means that the function key is not interpreted by Emacs at all,\n\
6241 allowing it to be used at a lower level for accented character entry.");
6243 DEFVAR_LISP ("ns-antialias-text", &ns_antialias_text,
6244 "Non-nil (the default) means to render text antialiased. Only has an effect on OS X Panther and above.");
6246 DEFVAR_LISP ("ns-use-qd-smoothing", &ns_use_qd_smoothing,
6247 "Whether to render text using QuickDraw (less heavy) antialiasing. Only has an effect on OS X Panther and above. Default is nil (use Quartz smoothing).");
6249 DEFVAR_LISP ("ns-confirm-quit", &ns_confirm_quit,
6250 "Whether to confirm application quit using dialog.");
6252 staticpro (&ns_display_name_list);
6253 ns_display_name_list = Qnil;
6255 staticpro (&last_mouse_motion_frame);
6256 last_mouse_motion_frame = Qnil;
6258 /* from 23+ we need to tell emacs what modifiers there are.. */
6259 Qmodifier_value = intern ("modifier-value");
6260 Qalt = intern ("alt");
6261 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
6262 Qhyper = intern ("hyper");
6263 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
6264 Qmeta = intern ("meta");
6265 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
6266 Qsuper = intern ("super");
6267 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
6268 Qcontrol = intern ("control");
6269 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
6271 /* TODO: move to common code */
6272 DEFVAR_LISP ("x-toolkit-scroll-bars", &Vx_toolkit_scroll_bars,
6273 doc: /* If not nil, Emacs uses toolkit scroll bars. */);
6274 #ifdef USE_TOOLKIT_SCROLL_BARS
6275 Vx_toolkit_scroll_bars = Qt;
6277 Vx_toolkit_scroll_bars = Qnil;
6280 /* these are unsupported but we need the declarations to avoid whining
6281 messages from cus-start.el */
6282 DEFVAR_BOOL ("x-use-underline-position-properties",
6283 &x_use_underline_position_properties,
6284 doc: /* NOT SUPPORTED UNDER NS.
6285 *Non-nil means make use of UNDERLINE_POSITION font properties.
6286 A value of nil means ignore them. If you encounter fonts with bogus
6287 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
6288 to 4.1, set this to nil.
6290 NOTE: Not supported on Mac yet. */);
6291 x_use_underline_position_properties = 0;
6293 DEFVAR_BOOL ("x-underline-at-descent-line",
6294 &x_underline_at_descent_line,
6295 doc: /* NOT SUPPORTED UNDER NS.
6296 *Non-nil means to draw the underline at the same place as the descent line.
6297 A value of nil means to draw the underline according to the value of the
6298 variable `x-use-underline-position-properties', which is usually at the
6299 baseline level. The default value is nil. */);
6300 x_underline_at_descent_line = 0;
6302 /* Tell emacs about this window system. */
6303 Fprovide (intern ("ns"), Qnil);
6307 // arch-tag: 6eaa8f7d-a69b-4e1c-b43d-ab31defbe0d2