1 /* NeXT/Open/GNUstep / MacOSX communication module.
2 Copyright (C) 1989, 1993, 1994, 2005, 2006, 2008
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)
29 #include <sys/types.h>
35 #include "blockinput.h"
36 #include "sysselect.h"
39 #include "character.h"
41 #include "composite.h"
44 #include "termhooks.h"
55 int term_trace_num = 0;
56 #define NSTRACE(x) fprintf (stderr, "%s:%d: [%d] " #x "\n", \
57 __FILE__, __LINE__, ++term_trace_num)
63 /* ==========================================================================
67 ========================================================================== */
69 /* Special keycodes that we pass down the event chain */
70 #define KEY_NS_POWER_OFF ((1<<28)|(0<<16)|1)
71 #define KEY_NS_OPEN_FILE ((1<<28)|(0<<16)|2)
72 #define KEY_NS_OPEN_TEMP_FILE ((1<<28)|(0<<16)|3)
73 #define KEY_NS_DRAG_FILE ((1<<28)|(0<<16)|4)
74 #define KEY_NS_DRAG_COLOR ((1<<28)|(0<<16)|5)
75 #define KEY_NS_DRAG_TEXT ((1<<28)|(0<<16)|6)
76 #define KEY_NS_CHANGE_FONT ((1<<28)|(0<<16)|7)
77 #define KEY_NS_OPEN_FILE_LINE ((1<<28)|(0<<16)|8)
78 #define KEY_NS_INSERT_WORKING_TEXT ((1<<28)|(0<<16)|9)
79 #define KEY_NS_DELETE_WORKING_TEXT ((1<<28)|(0<<16)|10)
80 #define KEY_NS_SPI_SERVICE_CALL ((1<<28)|(0<<16)|11)
81 #define KEY_NS_NEW_FRAME ((1<<28)|(0<<16)|12)
83 /* Convert a symbol indexed with an NSxxx value to a value as defined
84 in keyboard.c (lispy_function_key). I hope this is a correct way
86 static unsigned convert_ns_to_X_keysym[] =
88 NSHomeFunctionKey, 0x50,
89 NSLeftArrowFunctionKey, 0x51,
90 NSUpArrowFunctionKey, 0x52,
91 NSRightArrowFunctionKey, 0x53,
92 NSDownArrowFunctionKey, 0x54,
93 NSPageUpFunctionKey, 0x55,
94 NSPageDownFunctionKey, 0x56,
95 NSEndFunctionKey, 0x57,
96 NSBeginFunctionKey, 0x58,
97 NSSelectFunctionKey, 0x60,
98 NSPrintFunctionKey, 0x61,
99 NSExecuteFunctionKey, 0x62,
100 NSInsertFunctionKey, 0x63,
101 NSUndoFunctionKey, 0x65,
102 NSRedoFunctionKey, 0x66,
103 NSMenuFunctionKey, 0x67,
104 NSFindFunctionKey, 0x68,
105 NSHelpFunctionKey, 0x6A,
106 NSBreakFunctionKey, 0x6B,
108 NSF1FunctionKey, 0xBE,
109 NSF2FunctionKey, 0xBF,
110 NSF3FunctionKey, 0xC0,
111 NSF4FunctionKey, 0xC1,
112 NSF5FunctionKey, 0xC2,
113 NSF6FunctionKey, 0xC3,
114 NSF7FunctionKey, 0xC4,
115 NSF8FunctionKey, 0xC5,
116 NSF9FunctionKey, 0xC6,
117 NSF10FunctionKey, 0xC7,
118 NSF11FunctionKey, 0xC8,
119 NSF12FunctionKey, 0xC9,
120 NSF13FunctionKey, 0xCA,
121 NSF14FunctionKey, 0xCB,
122 NSF15FunctionKey, 0xCC,
124 NSBackspaceCharacter, 0x08, /* 8: Not on some KBs. */
125 NSDeleteCharacter, 0xFF, /* 127: Big 'delete' key upper right. */
126 NSDeleteFunctionKey, 0x9F, /* 63272: Del forw key off main array. */
128 NSTabCharacter, 0x09,
129 0x19, 0x09, /* left tab->regular since pass shift */
130 NSCarriageReturnCharacter, 0x0D,
131 NSNewlineCharacter, 0x0D,
132 NSEnterCharacter, 0x8D,
134 0x1B, 0x1B /* escape */
138 /* Lisp communications */
139 Lisp_Object ns_input_file, ns_input_font, ns_input_fontsize, ns_input_line;
140 Lisp_Object ns_input_color, ns_input_text, ns_working_text;
141 Lisp_Object ns_input_spi_name, ns_input_spi_arg;
142 Lisp_Object Vx_toolkit_scroll_bars;
143 static Lisp_Object Qmodifier_value;
144 /* TODO: unsure why these defined in term files, anyway we need in keymap.c */
145 Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper;
146 extern Lisp_Object Qcursor_color, Qcursor_type, Qns;
149 EmacsPrefsController *prefsController;
151 /* Defaults managed through the OpenStep defaults system. These pertain to
152 the NS interface specifically. Although a customization group could be
153 created, it's more natural to manage them via defaults. */
155 /* Specifies which emacs modifier should be generated when NS receives
156 the Alternate modifer. May be Qnone or any of the modifier lisp symbols. */
157 Lisp_Object ns_alternate_modifier;
159 /* Specifies which emacs modifier should be generated when NS receives
160 the Command modifer. May be any of the modifier lisp symbols. */
161 Lisp_Object ns_command_modifier;
163 /* Specifies which emacs modifier should be generated when NS receives
164 the Control modifer. May be any of the modifier lisp symbols. */
165 Lisp_Object ns_control_modifier;
167 /* Specifies which emacs modifier should be generated when NS receives
168 the Function modifer (laptops). May be any of the modifier lisp symbols. */
169 Lisp_Object ns_function_modifier;
171 /* A floating point value specifying vertical stretch (positive) or shrink
172 (negative) of text line spacing. Zero means default spacing.
173 YES indicates 0.5, NO indicates 0.0. */
174 Lisp_Object ns_expand_space;
176 /* Control via default 'GSFontAntiAlias' on OS X and GNUstep. */
177 Lisp_Object ns_antialias_text;
179 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
180 the maximum font size to NOT antialias. On GNUstep there is currently
181 no way to control this behavior. */
182 float ns_antialias_threshold;
184 /* Controls use of an undocumented CG function to do Quickdraw-style font
185 smoothing (less heavy) instead of regular Quartz smoothing. */
186 Lisp_Object ns_use_qd_smoothing;
188 /* Used to pick up AppleHighlightColor on OS X */
189 Lisp_Object ns_use_system_highlight_color;
190 NSString *ns_selection_color;
193 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
195 /* Display variables */
196 struct ns_display_info *x_display_list; /* Chain of existing displays */
197 Lisp_Object ns_display_name_list;
198 long context_menu_value = 0;
201 NSPoint last_mouse_motion_position;
202 static NSRect last_mouse_glyph;
203 static unsigned long last_mouse_movement_time = 0;
204 static Lisp_Object last_mouse_motion_frame;
205 static EmacsScroller *last_mouse_scroll_bar = nil;
206 static struct frame *ns_updating_frame;
207 static NSView *focus_view = NULL;
208 static int ns_window_num =0;
210 static BOOL gsaved = NO;
211 BOOL ns_in_resize = NO;
212 int ns_tmp_flags; /* FIXME */
213 struct nsfont_info *ns_tmp_font; /* FIXME */
214 /*static int debug_lock = 0; */
217 /* This undocumented Quartz function controls how fonts are anti-aliased.
218 (Found from code in Mac wxWindows impl, discovered by running `nm' on
220 Mode 0 is normal anti-aliasing, mode 1 is no anti-aliasing, and mode 2 is
221 4-bit pixel-aligned anti-aliasing (the old QuickDraw standard). */
222 extern void CGContextSetFontRenderingMode (CGContextRef cg, int v);
227 static BOOL send_appdefined = YES;
228 static NSEvent *last_appdefined_event = 0;
229 static NSTimer *timed_entry = 0;
230 static NSTimer *fd_entry = nil;
231 static NSTimer *scroll_repeat_entry = nil;
232 static fd_set select_readfds, t_readfds;
233 static struct timeval select_timeout;
234 static int select_nfds;
235 static NSAutoreleasePool *outerpool;
236 static BOOL ns_shutdown_properly = NO;
237 static struct input_event *emacs_event = NULL;
238 static struct input_event *q_event_ptr = NULL;
239 static int n_emacs_events_pending = 0;
240 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
241 *ns_pending_service_args;
242 static BOOL inNsSelect = 0;
244 /* Convert modifiers in a NeXTSTEP event to emacs style modifiers. */
245 #define NS_FUNCTION_KEY_MASK 0x800000
246 #define EV_MODIFIERS(e) \
247 ((([e modifierFlags] & NSHelpKeyMask) ? \
248 hyper_modifier : 0) \
249 | (([e modifierFlags] & NSAlternateKeyMask) ? \
250 parse_solitary_modifier (ns_alternate_modifier) : 0) \
251 | (([e modifierFlags] & NSShiftKeyMask) ? \
252 shift_modifier : 0) \
253 | (([e modifierFlags] & NSControlKeyMask) ? \
254 parse_solitary_modifier (ns_control_modifier) : 0) \
255 | (([e modifierFlags] & NS_FUNCTION_KEY_MASK) ? \
256 parse_solitary_modifier (ns_function_modifier) : 0) \
257 | (([e modifierFlags] & NSCommandKeyMask) ? \
258 parse_solitary_modifier (ns_command_modifier):0))
260 #define EV_UDMODIFIERS(e) \
261 ((([e type] == NSLeftMouseDown) ? down_modifier : 0) \
262 | (([e type] == NSRightMouseDown) ? down_modifier : 0) \
263 | (([e type] == NSLeftMouseDragged) ? down_modifier : 0) \
264 | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
265 | (([e type] == NSLeftMouseUp) ? up_modifier : 0) \
266 | (([e type] == NSRightMouseUp) ? up_modifier : 0))
268 #define EV_BUTTON(e) \
269 ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 : \
270 (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : 1)
272 /* Convert the time field to a timestamp in milliseconds. */
273 #ifdef NS_IMPL_GNUSTEP
274 /* Apple says timestamp is in seconds, but GNUstep seems to be returning msec */
275 #define EV_TIMESTAMP(e) ([e timestamp])
277 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
278 #endif /* not gnustep */
280 /* This is a piece of code which is common to all the event handling
281 methods. Maybe it should even be a function. */
282 #define EV_TRAILER(e) \
284 XSETFRAME (emacs_event->frame_or_window, [NSApp isActive] ? \
285 emacsframe : SELECTED_FRAME ()); \
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 /* TODO: get rid of need for these forward declarations */
294 static void ns_condemn_scroll_bars (struct frame *f),
295 ns_judge_scroll_bars (struct frame *f);
297 /* unused variables needed for compatibility reasons */
298 int x_use_underline_position_properties, x_underline_at_descent_line;
299 /* FIXME: figure out what to do with underline_minimum_offset. */
302 /* ==========================================================================
306 ========================================================================== */
310 append2 (Lisp_Object list, Lisp_Object item)
311 /* --------------------------------------------------------------------------
312 Utility to append to a list
313 -------------------------------------------------------------------------- */
315 Lisp_Object array[2];
317 array[1] = Fcons (item, Qnil);
318 return Fnconc (2, &array[0]);
324 /* --------------------------------------------------------------------------
325 Used to allow emacs to find its resources under Emacs.app
326 Called from emacs.c at startup.
327 -------------------------------------------------------------------------- */
329 NSBundle *bundle = [NSBundle mainBundle];
330 NSString *binDir = [bundle bundlePath], *resourceDir = [bundle resourcePath];
331 NSString *resourcePath, *resourcePaths;
333 BOOL onWindows = NO; /* how do I determine this? */
334 NSString *pathSeparator = onWindows ? @";" : @":";
335 NSFileManager *fileManager = [NSFileManager defaultManager];
337 /*NSLog (@"ns_init_paths: '%@'\n%@\n", [[NSBundle mainBundle] bundlePath], [[NSBundle mainBundle] resourcePath]); */
339 /* get bindir from base */
340 range = [resourceDir rangeOfString: @"Contents"];
341 if (range.location != NSNotFound)
343 binDir = [binDir stringByAppendingPathComponent: @"Contents"];
345 binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
349 /* the following based on Andrew Choi's init_mac_osx_environment () */
350 if (!getenv ("EMACSLOADPATH"))
352 NSArray *paths = [resourceDir stringsByAppendingPaths:
353 [NSArray arrayWithObjects:
354 @"site-lisp", @"lisp", @"leim", nil]];
355 NSEnumerator *pathEnum = [paths objectEnumerator];
357 while (resourcePath = [pathEnum nextObject])
359 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
362 if ([resourcePaths length] > 0)
364 = [resourcePaths stringByAppendingString: pathSeparator];
366 = [resourcePaths stringByAppendingString: resourcePath];
369 if ([resourcePaths length] > 0)
370 setenv ("EMACSLOADPATH", [resourcePaths UTF8String], 1);
371 /*NSLog (@"loadPath: '%s'\n", resourcePaths); */
374 if (!getenv ("EMACSPATH"))
376 NSArray *paths = [binDir stringsByAppendingPaths:
377 [NSArray arrayWithObjects: @"bin",
379 NSEnumerator *pathEnum = [paths objectEnumerator];
381 while (resourcePath = [pathEnum nextObject])
383 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
386 if ([resourcePaths length] > 0)
388 = [resourcePaths stringByAppendingString: pathSeparator];
390 = [resourcePaths stringByAppendingString: resourcePath];
393 if ([resourcePaths length] > 0)
394 setenv ("EMACSPATH", [resourcePaths UTF8String], 1);
397 resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
398 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
402 if (!getenv ("EMACSDATA"))
403 setenv ("EMACSDATA", [resourcePath UTF8String], 1);
404 if (!getenv ("EMACSDOC"))
405 setenv ("EMACSDOC", [resourcePath UTF8String], 1);
409 if (!getenv ("INFOPATH"))
411 resourcePath = [resourceDir stringByAppendingPathComponent: @"info"];
412 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
414 setenv ("INFOPATH", [resourcePath UTF8String], 1);
420 timeval_subtract (struct timeval *result, struct timeval x, struct timeval y)
421 /* --------------------------------------------------------------------------
422 Subtract the `struct timeval' values X and Y, storing the result in RESULT.
423 Return 1 if the difference is negative, otherwise 0.
424 -------------------------------------------------------------------------- */
426 /* Perform the carry for the later subtraction by updating y.
427 This is safer because on some systems
428 the tv_sec member is unsigned. */
429 if (x.tv_usec < y.tv_usec)
431 int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
432 y.tv_usec -= 1000000 * nsec;
435 if (x.tv_usec - y.tv_usec > 1000000)
437 int nsec = (y.tv_usec - x.tv_usec) / 1000000;
438 y.tv_usec += 1000000 * nsec;
442 /* Compute the time remaining to wait. tv_usec is certainly positive. */
443 result->tv_sec = x.tv_sec - y.tv_sec;
444 result->tv_usec = x.tv_usec - y.tv_usec;
446 /* Return indication of whether the result should be considered negative. */
447 return x.tv_sec < y.tv_sec;
451 ns_timeout (int usecs)
452 /* --------------------------------------------------------------------------
453 Blocking timer utility used by ns_ring_bell
454 -------------------------------------------------------------------------- */
456 struct timeval wakeup;
458 EMACS_GET_TIME (wakeup);
460 /* Compute time to wait until, propagating carry from usecs. */
461 wakeup.tv_usec += usecs;
462 wakeup.tv_sec += (wakeup.tv_usec / 1000000);
463 wakeup.tv_usec %= 1000000;
465 /* Keep waiting until past the time wakeup. */
468 struct timeval timeout;
470 EMACS_GET_TIME (timeout);
472 /* In effect, timeout = wakeup - timeout.
473 Break if result would be negative. */
474 if (timeval_subtract (&timeout, wakeup, timeout))
477 /* Try to wait that long--but we might wake up sooner. */
478 select (0, NULL, NULL, NULL, &timeout);
484 ns_release_object (void *obj)
485 /* --------------------------------------------------------------------------
486 Release an object (callable from C)
487 -------------------------------------------------------------------------- */
494 ns_retain_object (void *obj)
495 /* --------------------------------------------------------------------------
496 Retain an object (callable from C)
497 -------------------------------------------------------------------------- */
504 ns_alloc_autorelease_pool ()
505 /* --------------------------------------------------------------------------
506 Allocate a pool for temporary objects (callable from C)
507 -------------------------------------------------------------------------- */
509 return [[NSAutoreleasePool alloc] init];
514 ns_release_autorelease_pool (void *pool)
515 /* --------------------------------------------------------------------------
516 Free a pool and temporary objects it refers to (callable from C)
517 -------------------------------------------------------------------------- */
519 ns_release_object (pool);
524 /* ==========================================================================
526 Focus (clipping) and screen update
528 ========================================================================== */
531 ns_resize_handle_rect (NSWindow *window)
533 NSRect r = [window frame];
534 r.origin.x = r.size.width - RESIZE_HANDLE_SIZE;
536 r.size.width = r.size.height = RESIZE_HANDLE_SIZE;
542 ns_update_begin (struct frame *f)
543 /* --------------------------------------------------------------------------
544 Prepare for a grouped sequence of drawing calls
545 23: external (RIF) call; now split w/ and called before update_window_begin
546 -------------------------------------------------------------------------- */
548 NSView *view = FRAME_NS_VIEW (f);
549 NSTRACE (ns_update_begin);
551 ns_updating_frame = f;
554 #ifdef NS_IMPL_GNUSTEP
555 uRect = NSMakeRect (0, 0, 0, 0);
561 ns_update_window_begin (struct window *w)
562 /* --------------------------------------------------------------------------
563 Prepare for a grouped sequence of drawing calls
564 23: external (RIF) call; now split with and called after update_begin
565 -------------------------------------------------------------------------- */
567 struct frame *f = XFRAME (WINDOW_FRAME (w));
568 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
569 NSTRACE (ns_update_window_begin);
572 set_output_cursor (&w->cursor);
576 if (f == dpyinfo->mouse_face_mouse_frame)
578 /* Don't do highlighting for mouse motion during the update. */
579 dpyinfo->mouse_face_defer = 1;
581 /* If the frame needs to be redrawn,
582 simply forget about any prior mouse highlighting. */
583 if (FRAME_GARBAGED_P (f))
584 dpyinfo->mouse_face_window = Qnil;
586 /* (further code for mouse faces ifdef'd out in other terms elided) */
594 ns_update_window_end (struct window *w, int cursor_on_p,
595 int mouse_face_overwritten_p)
596 /* --------------------------------------------------------------------------
597 Finished a grouped sequence of drawing calls
598 23: external (RIF) call; now split with and called before update_window_end
599 -------------------------------------------------------------------------- */
601 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (XFRAME (w->frame));
603 /* note: this fn is nearly identical in all terms */
604 if (!w->pseudo_window_p)
609 display_and_set_cursor (w, 1,
610 output_cursor.hpos, output_cursor.vpos,
611 output_cursor.x, output_cursor.y);
613 if (draw_window_fringes (w, 1))
614 x_draw_vertical_border (w);
619 /* If a row with mouse-face was overwritten, arrange for
620 frame_up_to_date to redisplay the mouse highlight. */
621 if (mouse_face_overwritten_p)
623 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
624 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
625 dpyinfo->mouse_face_window = Qnil;
628 updated_window = NULL;
629 NSTRACE (update_window_end);
634 ns_update_end (struct frame *f)
635 /* --------------------------------------------------------------------------
636 Finished a grouped sequence of drawing calls
637 23: external (RIF) call; now split with and called after update_window_end
638 -------------------------------------------------------------------------- */
640 NSView *view = FRAME_NS_VIEW (f);
642 /* if (f == FRAME_NS_DISPLAY_INFO (f)->mouse_face_mouse_frame) */
643 FRAME_NS_DISPLAY_INFO (f)->mouse_face_defer = 0;
647 #ifdef NS_IMPL_GNUSTEP
648 /* trigger flush only in the rectangle we tracked as being drawn */
649 [view unlockFocusNeedsFlush: NO];
650 /*fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", uRect.origin.x, uRect.origin.y, uRect.size.width, uRect.size.height); */
651 [view lockFocusInRect: uRect];
655 [[view window] flushWindow];
658 ns_updating_frame = NULL;
659 NSTRACE (ns_update_end);
664 ns_flush (struct frame *f)
665 /* --------------------------------------------------------------------------
666 23: external (RIF) call
667 NS impl is no-op since currently we flush in ns_update_end and elsewhere
668 -------------------------------------------------------------------------- */
675 ns_focus (struct frame *f, NSRect *r, int n)
676 /* --------------------------------------------------------------------------
677 Internal: Focus on given frame. During small local updates this is used to
678 draw, however during large updates, ns_update_begin and ns_update_end are
679 called to wrap the whole thing, in which case these calls are stubbed out.
680 Except, on GNUstep, we accumulate the rectangle being drawn into, because
681 the back end won't do this automatically, and will just end up flushing
683 -------------------------------------------------------------------------- */
685 // NSTRACE (ns_focus);
686 #ifdef NS_IMPL_GNUSTEP
689 u = NSUnionRect (r[0], r[1]);
694 fprintf (stderr, "focus: %d", c++);
695 if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
696 fprintf (stderr, "\n"); */
698 if (f != ns_updating_frame)
700 NSView *view = FRAME_NS_VIEW (f);
701 if (view != focus_view)
703 if (focus_view != NULL)
705 [focus_view unlockFocus];
706 [[focus_view window] flushWindow];
711 #ifdef NS_IMPL_GNUSTEP
712 r ? [view lockFocusInRect: u] : [view lockFocus];
717 /*if (view) debug_lock++; */
719 #ifdef NS_IMPL_GNUSTEP
722 /* more than one rect being drawn into */
725 [view unlockFocus]; /* add prev rect to redraw list */
726 [view lockFocusInRect: u]; /* focus for draw in new rect */
731 #ifdef NS_IMPL_GNUSTEP
734 /* in batch mode, but in GNUstep must still track rectangles explicitly */
735 uRect = (r ? NSUnionRect (uRect, u) : [FRAME_NS_VIEW (f) visibleRect]);
742 [[NSGraphicsContext currentContext] saveGraphicsState];
744 NSRectClipList (r, 2);
753 ns_unfocus (struct frame *f)
754 /* --------------------------------------------------------------------------
755 Internal: Remove focus on given frame
756 -------------------------------------------------------------------------- */
758 // NSTRACE (ns_unfocus);
762 [[NSGraphicsContext currentContext] restoreGraphicsState];
766 if (f != ns_updating_frame)
768 if (focus_view != NULL)
770 [focus_view unlockFocus];
771 [[focus_view window] flushWindow];
780 ns_clip_to_row (struct window *w, struct glyph_row *row, int area, BOOL gc)
781 /* --------------------------------------------------------------------------
782 23: Internal (but parallels other terms): Focus drawing on given row
783 -------------------------------------------------------------------------- */
785 struct frame *f = XFRAME (WINDOW_FRAME (w));
787 int window_x, window_y, window_width;
789 window_box (w, area, &window_x, &window_y, &window_width, 0);
791 clip_rect.origin.x = window_x - FRAME_INTERNAL_BORDER_WIDTH (f);
792 clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
793 clip_rect.origin.y = max (clip_rect.origin.y, window_y);
794 clip_rect.size.width = window_width + 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
795 clip_rect.size.height = row->visible_height;
797 /* allow a full-height row at the top when requested
798 (used to draw fringe all the way through internal border area) */
799 if (gc && clip_rect.origin.y < 5)
801 clip_rect.origin.y -= FRAME_INTERNAL_BORDER_WIDTH (f);
802 clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
805 /* likewise at bottom */
807 FRAME_PIXEL_HEIGHT (f) - (clip_rect.origin.y + clip_rect.size.height) < 5)
808 clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
810 ns_focus (f, &clip_rect, 1);
816 /* --------------------------------------------------------------------------
818 -------------------------------------------------------------------------- */
820 NSTRACE (ns_ring_bell);
823 NSAutoreleasePool *pool;
824 struct frame *frame = SELECTED_FRAME ();
828 pool = [[NSAutoreleasePool alloc] init];
830 view = FRAME_NS_VIEW (frame);
834 NSPoint dim = NSMakePoint (128, 128);
837 r.origin.x += (r.size.width - dim.x) / 2;
838 r.origin.y += (r.size.height - dim.y) / 2;
839 r.size.width = dim.x;
840 r.size.height = dim.y;
841 /* XXX: cacheImageInRect under GNUstep does not account for
842 offset in x_set_window_size, so overestimate (4 fine on Cocoa) */
843 surr = NSInsetRect (r, -10, -10);
844 ns_focus (frame, &surr, 1);
845 [[view window] cacheImageInRect: surr];
846 [ns_lookup_indexed_color (NS_FACE_FOREGROUND
847 (FRAME_DEFAULT_FACE (frame)), frame) set];
849 [[view window] flushWindow];
851 [[view window] restoreCachedImage];
852 [[view window] flushWindow];
866 ns_reset_terminal_modes (struct terminal *terminal)
867 /* Externally called as hook */
869 NSTRACE (ns_reset_terminal_modes);
873 ns_set_terminal_modes (struct terminal *terminal)
874 /* Externally called as hook */
876 NSTRACE (ns_set_terminal_modes);
881 /* ==========================================================================
883 Frame / window manager related functions
885 ========================================================================== */
889 ns_raise_frame (struct frame *f)
890 /* --------------------------------------------------------------------------
891 Bring window to foreground and make it active
892 -------------------------------------------------------------------------- */
894 NSView *view = FRAME_NS_VIEW (f);
897 [[view window] makeKeyAndOrderFront: NSApp];
903 ns_lower_frame (struct frame *f)
904 /* --------------------------------------------------------------------------
906 -------------------------------------------------------------------------- */
908 NSView *view = FRAME_NS_VIEW (f);
911 [[view window] orderBack: NSApp];
917 ns_frame_raise_lower (struct frame *f, int raise)
918 /* --------------------------------------------------------------------------
920 -------------------------------------------------------------------------- */
922 NSTRACE (ns_frame_raise_lower);
932 ns_frame_rehighlight (struct frame *frame)
933 /* --------------------------------------------------------------------------
934 External (hook): called on things like window switching within frame
935 -------------------------------------------------------------------------- */
937 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
938 struct frame *old_highlight = dpyinfo->x_highlight_frame;
940 NSTRACE (ns_frame_rehighlight);
941 if (dpyinfo->x_focus_frame)
943 dpyinfo->x_highlight_frame
944 = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
945 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
946 : dpyinfo->x_focus_frame);
947 if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
949 FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
950 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
954 dpyinfo->x_highlight_frame = 0;
956 if (dpyinfo->x_highlight_frame &&
957 dpyinfo->x_highlight_frame != old_highlight)
960 x_update_cursor (old_highlight, 1);
961 if (dpyinfo->x_highlight_frame)
962 x_update_cursor (dpyinfo->x_highlight_frame, 1);
968 x_make_frame_visible (struct frame *f)
969 /* --------------------------------------------------------------------------
970 External: Show the window (X11 semantics)
971 -------------------------------------------------------------------------- */
973 NSTRACE (x_make_frame_visible);
974 /* XXX: at some points in past this was not needed, as the only place that
975 called this (frame.c:Fraise_frame ()) also called raise_lower;
976 if this ends up the case again, comment this out again. */
977 if (!FRAME_VISIBLE_P (f))
983 x_make_frame_invisible (struct frame *f)
984 /* --------------------------------------------------------------------------
985 External: Hide the window (X11 semantics)
986 -------------------------------------------------------------------------- */
988 NSView * view = FRAME_NS_VIEW (f);
989 NSTRACE (x_make_frame_invisible);
991 [[view window] orderOut: NSApp];
996 x_iconify_frame (struct frame *f)
997 /* --------------------------------------------------------------------------
998 External: Iconify window
999 -------------------------------------------------------------------------- */
1001 NSView * view = FRAME_NS_VIEW (f);
1002 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1003 NSTRACE (x_iconify_frame);
1006 if (dpyinfo->x_highlight_frame == f)
1007 dpyinfo->x_highlight_frame = 0;
1009 if ([[view window] windowNumber] <= 0)
1011 /* the window is still deferred. Make it very small, bring it
1012 on screen and order it out. */
1013 NSRect s = { { 100, 100}, {0, 0} };
1015 t = [[view window] frame];
1016 [[view window] setFrame: s display: NO];
1017 [[view window] orderBack: NSApp];
1018 [[view window] orderOut: NSApp];
1019 [[view window] setFrame: t display: NO];
1021 [[view window] miniaturize: NSApp];
1026 x_destroy_window (struct frame *f)
1027 /* --------------------------------------------------------------------------
1028 External: Delete the window
1029 -------------------------------------------------------------------------- */
1031 NSView *view = FRAME_NS_VIEW (f);
1032 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1033 NSTRACE (x_destroy_window);
1036 [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1040 free_frame_menubar (f);
1042 if (FRAME_FACE_CACHE (f))
1043 free_frame_faces (f);
1045 if (f == dpyinfo->x_focus_frame)
1046 dpyinfo->x_focus_frame = 0;
1047 if (f == dpyinfo->x_highlight_frame)
1048 dpyinfo->x_highlight_frame = 0;
1049 if (f == dpyinfo->mouse_face_mouse_frame)
1051 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
1052 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
1053 dpyinfo->mouse_face_window = Qnil;
1054 dpyinfo->mouse_face_deferred_gc = 0;
1055 dpyinfo->mouse_face_mouse_frame = 0;
1058 xfree (f->output_data.ns);
1060 [[view window] close];
1069 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1070 /* --------------------------------------------------------------------------
1071 External: Position the window
1072 -------------------------------------------------------------------------- */
1075 NSView *view = FRAME_NS_VIEW (f);
1077 NSTRACE (x_set_offset);
1083 #ifdef NS_IMPL_GNUSTEP
1085 f->left_pos = 100; /* don't overlap menu */
1087 if (view != nil && (screen = [[view window] screen]))
1088 [[view window] setFrameTopLeftPoint:
1089 NSMakePoint (SCREENMAXBOUND (f->left_pos),
1090 SCREENMAXBOUND ([screen frame].size.height
1091 - NS_TOP_POS (f)))];
1097 x_set_window_size (struct frame *f, int change_grav, int cols, int rows)
1098 /* --------------------------------------------------------------------------
1099 Adjust window pixel size based on given character grid size
1100 Impl is a bit more complex than other terms, need to do some
1101 internal clipping and also pay attention to screen constraints.
1102 -------------------------------------------------------------------------- */
1104 EmacsView *view = FRAME_NS_VIEW (f);
1105 EmacsToolbar *toolbar = [view toolbar];
1106 NSWindow *window = [view window];
1107 NSScreen *screen = [window screen];
1108 NSRect wr = [window frame];
1109 int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1110 int pixelwidth, pixelheight;
1111 static int oldRows, oldCols, oldFontWidth, oldFontHeight;
1113 static struct frame *oldF;
1115 NSTRACE (x_set_window_size);
1119 && rows == oldRows && cols == oldCols
1120 && oldFontWidth == FRAME_COLUMN_WIDTH (f)
1121 && oldFontHeight == FRAME_LINE_HEIGHT (f)
1125 /*fprintf (stderr, "\tsetWindowSize: %d x %d, font size %d x %d\n", cols, rows, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f)); */
1129 check_frame_size (f, &rows, &cols);
1133 oldFontWidth = FRAME_COLUMN_WIDTH (f);
1134 oldFontHeight = FRAME_LINE_HEIGHT (f);
1137 f->scroll_bar_actual_width = NS_SCROLL_BAR_WIDTH (f);
1138 compute_fringe_widths (f, 0);
1140 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols);
1141 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
1143 /* If we have a change in toolbar display, calculate height */
1145 /* XXX: GNUstep has not yet implemented the first method below, added
1146 in Panther, however the second is incorrect under Cocoa. */
1147 #ifdef NS_IMPL_GNUSTEP
1148 FRAME_NS_TOOLBAR_HEIGHT (f)
1149 = NSHeight ([NSWindow frameRectForContentRect: NSMakeRect (0, 0, 0, 0)
1150 styleMask: [window styleMask]])
1151 - FRAME_NS_TITLEBAR_HEIGHT (f);
1153 FRAME_NS_TOOLBAR_HEIGHT (f) = 32;
1154 /* actually get wrong result here if toolbar not yet displayed
1155 NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1156 - FRAME_NS_TITLEBAR_HEIGHT (f); */
1159 FRAME_NS_TOOLBAR_HEIGHT (f) = 0;
1161 wr.size.width = pixelwidth + f->border_width;
1162 wr.size.height = pixelheight + FRAME_NS_TITLEBAR_HEIGHT (f)
1163 + FRAME_NS_TOOLBAR_HEIGHT (f);
1165 /* constrain to screen if we can */
1168 NSSize sz = [screen visibleFrame].size;
1169 NSSize ez = { wr.size.width - sz.width, wr.size.height - sz.height };
1172 int cr = ez.width / FRAME_COLUMN_WIDTH (f) + 1;
1175 wr.size.width -= cr * FRAME_COLUMN_WIDTH (f);
1176 pixelwidth -= cr * FRAME_COLUMN_WIDTH (f);
1180 int rr = ez.height / FRAME_LINE_HEIGHT (f) + 1;
1183 wr.size.height -= rr * FRAME_LINE_HEIGHT (f);
1184 pixelheight -= rr * FRAME_LINE_HEIGHT (f);
1186 wr.origin.x = f->left_pos;
1187 wr.origin.y = [screen frame].size.height - NS_TOP_POS (f)
1191 [view setRows: rows andColumns: cols];
1192 [window setFrame: wr display: YES];
1194 /*fprintf (stderr, "\tx_set_window_size %d, %d\t%d, %d\n", cols, rows, pixelwidth, pixelheight); */
1196 /* This is a trick to compensate for Emacs' managing the scrollbar area
1197 as a fixed number of standard character columns. Instead of leaving
1198 blank space for the extra, we chopped it off above. Now for
1199 left-hand scrollbars, we shift all rendering to the left by the
1200 difference between the real width and Emacs' imagined one. For
1201 right-hand bars, don't worry about it since the extra is never used.
1202 (Obviously doesn't work for vertically split windows tho..) */
1203 NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1204 ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1205 - NS_SCROLL_BAR_WIDTH (f), 0)
1206 : NSMakePoint (0, 0);
1207 [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1208 [view setBoundsOrigin: origin];
1210 change_frame_size (f, rows, cols, 0, 1, 0); /* pretend, delay, safe */
1211 FRAME_PIXEL_WIDTH (f) = pixelwidth;
1212 FRAME_PIXEL_HEIGHT (f) = pixelheight;
1213 /* SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */
1215 mark_window_cursors_off (XWINDOW (f->root_window));
1216 cancel_mouse_face (f);
1223 /* ==========================================================================
1227 ========================================================================== */
1231 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1233 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1234 return color_table->colors[idx];
1239 ns_index_color (NSColor *color, struct frame *f)
1241 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1245 if (!color_table->colors)
1247 color_table->size = NS_COLOR_CAPACITY;
1248 color_table->avail = 1; /* skip idx=0 as marker */
1250 = (NSColor **)xmalloc (color_table->size * sizeof (NSColor *));
1251 color_table->empty_indices = [[NSMutableSet alloc] init];
1254 /* do we already have this color ? */
1257 for (i = 1; i < color_table->avail; i++)
1259 if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1261 [color_table->colors[i] retain];
1267 if ([color_table->empty_indices count] > 0)
1269 index = [color_table->empty_indices anyObject];
1270 [color_table->empty_indices removeObject: index];
1271 idx = [index unsignedIntValue];
1275 if (color_table->avail == color_table->size)
1277 color_table->size += NS_COLOR_CAPACITY;
1279 = (NSColor **)xrealloc (color_table->colors,
1280 color_table->size * sizeof (NSColor *));
1282 idx = color_table->avail++;
1283 index = [NSNumber numberWithUnsignedInt: idx];
1286 color_table->colors[idx] = color;
1288 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1294 ns_free_indexed_color (unsigned long idx, struct frame *f)
1296 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1300 color = color_table->colors[idx];
1302 color_table->colors[idx] = nil;
1303 [color_table->empty_indices addObject: [NSNumber numberWithUnsignedInt: idx]];
1304 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1309 ns_get_color (const char *name, NSColor **col)
1310 /* --------------------------------------------------------------------------
1312 /* --------------------------------------------------------------------------
1313 /* On *Step, we recognize several color formats, in addition to a catalog
1314 of colors found in the file Emacs.clr. Color formats include:
1315 - #rrggbb or RGBrrggbb where rr, gg, bb specify red, green and blue in hex
1316 - ARGBaarrggbb is similar, with aa being the alpha channel (FF = opaque)
1317 - HSVhhssvv and AHSVaahhssvv (or HSB/AHSB) are similar for hue, saturation,
1319 - CMYKccmmyykk is similar for cyan, magenta, yellow, black. */
1321 NSColor * new = nil;
1322 const char *hex = NULL;
1323 enum { rgb, argb, hsv, ahsv, cmyk, gray } color_space;
1324 NSString *nsname = [NSString stringWithUTF8String: name];
1326 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1329 if ([nsname isEqualToString: @"ns_selection_color"])
1331 nsname = ns_selection_color;
1332 name = [ns_selection_color UTF8String];
1335 if (name[0] == '0' || name[0] == '1' || name[0] == '.')
1338 NSScanner *scanner = [NSScanner scannerWithString: nsname];
1340 [scanner scanFloat: &r];
1341 [scanner scanFloat: &g];
1342 [scanner scanFloat: &b];
1343 *col = [NSColor colorWithCalibratedRed: r green: g blue: b alpha: 1.0];
1348 /* 23: FIXME: emacs seems to downcase everything before passing it here,
1349 which we can work around, except for GRAY, since gray##, where ## is
1350 decimal between 0 and 99, is also an X11 colorname. */
1351 if (name[0] == '#') /* X11 format */
1356 else if (!memcmp (name, "RGB", 3) || !memcmp (name, "rgb", 3))
1361 else if (!memcmp (name, "ARGB", 4) || !memcmp (name, "argb", 4))
1366 else if (!memcmp (name, "HSV", 3) || !memcmp (name, "hsv", 3) ||
1367 !memcmp (name, "HSB", 3) || !memcmp (name, "hsb", 3))
1372 else if (!memcmp (name, "AHSV", 4) || !memcmp (name, "ahsv", 4) ||
1373 !memcmp (name, "AHSB", 4) || !memcmp (name, "ahsb", 4))
1378 else if (!memcmp (name, "CMYK", 4) || !memcmp (name, "cmyk", 4))
1383 else if (!memcmp (name, "GRAY", 4) /*|| !memcmp (name, "gray", 4)*/)
1389 /* Direct colors (hex values) */
1392 unsigned int color = 0;
1393 if (sscanf (hex, "%x", &color))
1395 float f1 = ((color >> 24) & 0xff) / 255.0;
1396 float f2 = ((color >> 16) & 0xff) / 255.0;
1397 float f3 = ((color >> 8) & 0xff) / 255.0;
1398 float f4 = ((color ) & 0xff) / 255.0;
1400 switch (color_space)
1403 *col = [NSColor colorWithCalibratedRed: f2
1409 *col = [NSColor colorWithCalibratedRed: f2
1415 *col = [NSColor colorWithCalibratedHue: f2
1421 *col = [NSColor colorWithCalibratedHue: f2
1427 *col = [NSColor colorWithCalibratedWhite: f3 alpha: f4];
1430 *col = [NSColor colorWithDeviceCyan: f1
1437 *col = [*col colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1443 /* Otherwise, color is expected to be from a list */
1445 NSEnumerator *lenum, *cenum;
1449 #ifdef NS_IMPL_GNUSTEP
1450 /* XXX: who is wrong, the requestor or the implementation? */
1451 if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1453 nsname = @"highlightColor";
1456 lenum = [[NSColorList availableColorLists] objectEnumerator];
1457 while ( (clist = [lenum nextObject]) && new == nil)
1459 cenum = [[clist allKeys] objectEnumerator];
1460 while ( (name = [cenum nextObject]) && new == nil )
1462 if ([name compare: nsname
1463 options: NSCaseInsensitiveSearch] == NSOrderedSame )
1464 new = [clist colorWithKey: name];
1470 *col = [new colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1472 NSLog (@"Failed to find color '%@'", nsname); */
1479 ns_get_color_default (const char *name, NSColor *dflt)
1480 /* --------------------------------------------------------------------------
1481 Parse a color or use a default value
1482 -------------------------------------------------------------------------- */
1486 if (ns_get_color (name, &col))
1494 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1495 /* --------------------------------------------------------------------------
1496 Convert a Lisp string object to a NS color
1497 -------------------------------------------------------------------------- */
1499 NSTRACE (ns_lisp_to_color);
1500 if (STRINGP (color))
1501 return ns_get_color (SDATA (color), col);
1502 else if (SYMBOLP (color))
1503 return ns_get_color (SDATA (SYMBOL_NAME (color)), col);
1509 ns_color_to_lisp (NSColor *col)
1510 /* --------------------------------------------------------------------------
1511 Convert a color to a lisp string with the RGB equivalent
1512 -------------------------------------------------------------------------- */
1514 float red, green, blue, alpha, gray;
1517 NSTRACE (ns_color_to_lisp);
1520 if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1522 if ((str =[[col colorNameComponent] UTF8String]))
1525 return build_string ((char *)str);
1528 [[col colorUsingColorSpaceName: NSCalibratedRGBColorSpace]
1529 getRed: &red green: &green blue: &blue alpha: &alpha];
1530 if (red ==green && red ==blue)
1532 [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1533 getWhite: &gray alpha: &alpha];
1534 snprintf (buf, sizeof (buf), "GRAY%02.2lx%02.2lx",
1535 lrint (gray * 0xff), lrint (alpha * 0xff));
1537 return build_string (buf);
1540 snprintf (buf, sizeof (buf), "ARGB%02.2lx%02.2lx%02.2lx%02.2lx",
1542 lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1545 return build_string (buf);
1550 ns_defined_color (struct frame *f, char *name, XColor *color_def, int alloc,
1552 /* --------------------------------------------------------------------------
1553 23: Return 1 if named color found, and set color_def rgb accordingly.
1554 If makeIndex and alloc are nonzero put the color in the color_table,
1555 and set color_def pixel to the resulting index.
1556 If makeIndex is zero, set color_def pixel to ARGB.
1557 Return 0 if not found
1558 -------------------------------------------------------------------------- */
1562 int notFound = ns_get_color (name, &temp);
1564 NSTRACE (ns_defined_color);
1569 if (makeIndex && alloc)
1570 color_def->pixel = ns_index_color(temp, f); /* [temp retain]; */
1572 [temp getRed: &r green: &g blue: &b alpha: &a];
1573 color_def->red = r * 256;
1574 color_def->green = g * 256;
1575 color_def->blue = b * 256;
1579 = ARGB_TO_ULONG((int)(a*256),
1580 color_def->red, color_def->green, color_def->blue);
1587 ns_get_rgb_color (struct frame *f, float r, float g, float b, float a)
1588 /* --------------------------------------------------------------------------
1589 return an autoreleased RGB color
1590 -------------------------------------------------------------------------- */
1592 /*static int c = 1; fprintf (stderr, "color request %d\n", c++); */
1593 if (r < 0.0) r = 0.0;
1594 else if (r > 1.0) r = 1.0;
1595 if (g < 0.0) g = 0.0;
1596 else if (g > 1.0) g = 1.0;
1597 if (b < 0.0) b = 0.0;
1598 else if (b > 1.0) b = 1.0;
1599 if (a < 0.0) a = 0.0;
1600 else if (a > 1.0) a = 1.0;
1601 return (unsigned long) ns_index_color(
1602 [NSColor colorWithCalibratedRed: r green: g blue: b alpha: a], f);
1607 /* ==========================================================================
1611 ========================================================================== */
1615 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1616 /* --------------------------------------------------------------------------
1617 Programmatically reposition mouse pointer in pixel coordinates
1618 -------------------------------------------------------------------------- */
1620 NSTRACE (x_set_mouse_pixel_position);
1623 /* FIXME: this does not work, and what about GNUstep? */
1624 #ifdef NS_IMPL_COCOA
1625 [FRAME_NS_VIEW (f) lockFocus];
1626 PSsetmouse ((float)pix_x, (float)pix_y);
1627 [FRAME_NS_VIEW (f) unlockFocus];
1634 x_set_mouse_position (struct frame *f, int h, int v)
1635 /* --------------------------------------------------------------------------
1636 Programmatically reposition mouse pointer in character coordinates
1637 -------------------------------------------------------------------------- */
1641 pix_x = FRAME_COL_TO_PIXEL_X (f, h) + FRAME_COLUMN_WIDTH (f) / 2;
1642 pix_y = FRAME_LINE_TO_PIXEL_Y (f, v) + FRAME_LINE_HEIGHT (f) / 2;
1644 if (pix_x < 0) pix_x = 0;
1645 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
1647 if (pix_y < 0) pix_y = 0;
1648 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
1650 x_set_mouse_pixel_position (f, pix_x, pix_y);
1655 note_mouse_movement (struct frame *frame, float x, float y)
1656 /* ------------------------------------------------------------------------
1657 Called by EmacsView on mouseMovement events. Passes on
1658 to emacs mainstream code if we moved off of a rect of interest
1659 known as last_mouse_glyph.
1660 ------------------------------------------------------------------------ */
1662 // NSTRACE (note_mouse_movement);
1664 XSETFRAME (last_mouse_motion_frame, frame);
1666 /* Note, this doesn't get called for enter/leave, since we don't have a
1667 position. Those are taken care of in the corresponding NSView methods. */
1669 /* has movement gone beyond last rect we were tracking? */
1670 if (x < last_mouse_glyph.origin.x ||
1671 x >= (last_mouse_glyph.origin.x + last_mouse_glyph.size.width) ||
1672 y < last_mouse_glyph.origin.y ||
1673 y >= (last_mouse_glyph.origin.y + last_mouse_glyph.size.height))
1675 frame->mouse_moved = 1;
1676 note_mouse_highlight (frame, x, y);
1677 remember_mouse_glyph (frame, x, y, &last_mouse_glyph);
1686 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1687 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1688 unsigned long *time)
1689 /* --------------------------------------------------------------------------
1690 External (hook): inform emacs about mouse position and hit parts.
1691 If a scrollbar is being dragged, set bar_window, part, x, y, time.
1692 x & y should be position in the scrollbar (the whole bar, not the handle)
1693 and length of scrollbar respectively
1694 -------------------------------------------------------------------------- */
1699 Lisp_Object frame, tail;
1701 struct ns_display_info *dpyinfo;
1703 NSTRACE (ns_mouse_position);
1707 fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1711 dpyinfo = FRAME_NS_DISPLAY_INFO (*fp);
1715 if (last_mouse_scroll_bar != nil && insist == 0)
1717 /* TODO: we do not use this path at the moment because drag events will
1718 go directly to the EmacsScroller. Leaving code in for now. */
1719 [last_mouse_scroll_bar getMouseMotionPart: (int *)part window: bar_window
1721 if (time) *time = last_mouse_movement_time;
1722 last_mouse_scroll_bar = nil;
1726 /* Clear the mouse-moved flag for every frame on this display. */
1727 FOR_EACH_FRAME (tail, frame)
1728 if (FRAME_NS_P (XFRAME (frame))
1729 && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1730 XFRAME (frame)->mouse_moved = 0;
1732 last_mouse_scroll_bar = nil;
1733 if (last_mouse_frame && FRAME_LIVE_P (last_mouse_frame))
1734 f = last_mouse_frame;
1736 f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame
1737 : SELECTED_FRAME ();
1739 if (f && f->output_data.ns) /* TODO: 2nd check no longer needed? */
1741 view = FRAME_NS_VIEW (*fp);
1743 position = [[view window] mouseLocationOutsideOfEventStream];
1744 position = [view convertPoint: position fromView: nil];
1745 remember_mouse_glyph (f, position.x, position.y, &last_mouse_glyph);
1746 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1748 if (bar_window) *bar_window = Qnil;
1749 if (part) *part = 0; /*scroll_bar_handle; */
1751 if (x) XSETINT (*x, lrint (position.x));
1752 if (y) XSETINT (*y, lrint (position.y));
1753 if (time) *time = last_mouse_movement_time;
1763 ns_frame_up_to_date (struct frame *f)
1764 /* --------------------------------------------------------------------------
1765 External (hook): Fix up mouse highlighting right after a full update.
1766 Some highlighting was deferred if GC was happening during
1767 note_mouse_highlight (), while other highlighting was deferred for update.
1768 -------------------------------------------------------------------------- */
1770 NSTRACE (ns_frame_up_to_date);
1774 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1775 if ((dpyinfo->mouse_face_deferred_gc||f ==dpyinfo->mouse_face_mouse_frame)
1776 /*&& dpyinfo->mouse_face_mouse_frame*/)
1779 if (dpyinfo->mouse_face_mouse_frame)
1780 note_mouse_highlight (dpyinfo->mouse_face_mouse_frame,
1781 dpyinfo->mouse_face_mouse_x,
1782 dpyinfo->mouse_face_mouse_y);
1783 dpyinfo->mouse_face_deferred_gc = 0;
1791 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1792 /* --------------------------------------------------------------------------
1793 External (RIF): set frame mouse pointer type.
1794 -------------------------------------------------------------------------- */
1796 NSTRACE (ns_define_frame_cursor);
1797 if (FRAME_POINTER_TYPE (f) != cursor)
1799 EmacsView *view = FRAME_NS_VIEW (f);
1800 FRAME_POINTER_TYPE (f) = cursor;
1801 [[view window] invalidateCursorRectsForView: view];
1807 /* ==========================================================================
1811 ========================================================================== */
1815 ns_convert_key (unsigned code)
1816 /* --------------------------------------------------------------------------
1817 Internal call used by NSView-keyDown.
1818 -------------------------------------------------------------------------- */
1820 const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym)
1821 / sizeof (convert_ns_to_X_keysym[0]));
1823 /* An array would be faster, but less easy to read. */
1824 for (keysym = 0; keysym < last_keysym; keysym += 2)
1825 if (code == convert_ns_to_X_keysym[keysym])
1826 return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
1828 /* if decide to use keyCode and Carbon table, use this line:
1829 return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
1834 x_get_keysym_name (int keysym)
1835 /* --------------------------------------------------------------------------
1836 Called by keyboard.c. Not sure if the return val is important, except
1838 -------------------------------------------------------------------------- */
1840 static char value[16];
1841 NSTRACE (x_get_keysym_name);
1842 sprintf (value, "%d", keysym);
1848 /* ==========================================================================
1850 Block drawing operations
1852 ========================================================================== */
1856 ns_redraw_scroll_bars (struct frame *f)
1860 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
1861 NSTRACE (ns_judge_scroll_bars);
1862 for (i =[subviews count]-1; i >= 0; i--)
1864 view = [subviews objectAtIndex: i];
1865 if (![view isKindOfClass: [EmacsScroller class]]) continue;
1872 ns_clear_frame (struct frame *f)
1873 /* --------------------------------------------------------------------------
1874 External (hook): Erase the entire frame
1875 -------------------------------------------------------------------------- */
1877 NSView *view = FRAME_NS_VIEW (f);
1880 NSTRACE (ns_clear_frame);
1884 /* comes on initial frame because we have
1885 after-make-frame-functions = select-frame */
1886 if (!FRAME_DEFAULT_FACE (f))
1889 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
1891 output_cursor.hpos = output_cursor.vpos = 0;
1892 output_cursor.x = -1;
1897 ns_focus (f, &r, 1);
1898 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
1902 #ifdef NS_IMPL_COCOA
1903 [[view window] display]; /* redraw resize handle */
1906 /* as of 2006/11 or so this is now needed */
1907 ns_redraw_scroll_bars (f);
1913 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
1914 /* --------------------------------------------------------------------------
1915 23: External (RIF): Clear section of frame
1916 -------------------------------------------------------------------------- */
1918 NSRect r = NSMakeRect (x, y, width, height);
1919 NSView *view = FRAME_NS_VIEW (f);
1920 struct face *face = FRAME_DEFAULT_FACE (f);
1925 NSTRACE (ns_clear_frame_area);
1927 r = NSIntersectionRect (r, [view frame]);
1928 ns_focus (f, &r, 1);
1929 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
1931 #ifdef NS_IMPL_COCOA
1933 /* clip out the resize handle */
1934 NSWindow *window = [FRAME_NS_VIEW (f) window];
1936 = [view convertRect: ns_resize_handle_rect (window) fromView: nil];
1938 ir = NSIntersectionRect (r, ir);
1939 if (NSIsEmptyRect (ir))
1945 #ifdef NS_IMPL_COCOA
1949 NSRect r1 = r, r2 = r; /* upper and lower non-intersecting */
1950 r1.size.height -= ir.size.height;
1951 r2.origin.y += r1.size.height;
1952 r2.size.width -= ir.size.width;
1953 r2.size.height = ir.size.height;
1966 ns_scroll_run (struct window *w, struct run *run)
1967 /* --------------------------------------------------------------------------
1968 23: External (RIF): Insert or delete n lines at line vpos
1969 -------------------------------------------------------------------------- */
1971 struct frame *f = XFRAME (w->frame);
1972 int x, y, width, height, from_y, to_y, bottom_y;
1974 NSTRACE (ns_scroll_run);
1976 /* begin copy from other terms */
1977 /* Get frame-relative bounding box of the text display area of W,
1978 without mode lines. Include in this box the left and right
1980 window_box (w, -1, &x, &y, &width, &height);
1982 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
1983 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
1984 bottom_y = y + height;
1988 /* Scrolling up. Make sure we don't copy part of the mode
1989 line at the bottom. */
1990 if (from_y + run->height > bottom_y)
1991 height = bottom_y - from_y;
1993 height = run->height;
1997 /* Scolling down. Make sure we don't copy over the mode line.
1999 if (to_y + run->height > bottom_y)
2000 height = bottom_y - to_y;
2002 height = run->height;
2004 /* end copy from other terms */
2015 NSRect srcRect = NSMakeRect (x, from_y, width, height);
2016 NSRect dstRect = NSMakeRect (x, to_y, width, height);
2017 NSPoint dstOrigin = NSMakePoint (x, to_y);
2019 ns_focus (f, &dstRect, 1);
2020 NSCopyBits (0, srcRect , dstOrigin);
2029 ns_after_update_window_line (struct glyph_row *desired_row)
2030 /* --------------------------------------------------------------------------
2031 23: External (RIF): preparatory to fringe update after text was updated
2032 -------------------------------------------------------------------------- */
2034 struct window *w = updated_window;
2038 NSTRACE (ns_after_update_window_line);
2040 /* begin copy from other terms */
2043 if (!desired_row->mode_line_p && !w->pseudo_window_p)
2044 desired_row->redraw_fringe_bitmaps_p = 1;
2046 /* When a window has disappeared, make sure that no rest of
2047 full-width rows stays visible in the internal border.
2048 Under NS this is drawn inside the fringes. */
2049 if (windows_or_buffers_changed
2050 && (f = XFRAME (w->frame),
2051 width = FRAME_INTERNAL_BORDER_WIDTH (f),
2053 && (height = desired_row->visible_height,
2056 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2058 /* Internal border is drawn below the tool bar. */
2059 if (WINDOWP (f->tool_bar_window)
2060 && w == XWINDOW (f->tool_bar_window))
2062 /* end copy from other terms */
2065 if (!desired_row->full_width_p)
2067 int x1 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2068 + WINDOW_LEFT_FRINGE_WIDTH (w);
2069 int x2 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2070 + FRAME_PIXEL_WIDTH (f) - NS_SCROLL_BAR_WIDTH (f)
2071 - WINDOW_RIGHT_FRINGE_WIDTH (w)
2072 - FRAME_INTERNAL_BORDER_WIDTH (f);
2073 ns_clear_frame_area (f, x1, y, width, height);
2074 ns_clear_frame_area (f, x2, y, width, height);
2082 ns_shift_glyphs_for_insert (struct frame *f,
2083 int x, int y, int width, int height,
2085 /* --------------------------------------------------------------------------
2086 23: External (RIF): copy an area horizontally, don't worry about clearing src
2087 -------------------------------------------------------------------------- */
2089 NSRect srcRect = NSMakeRect (x, y, width, height);
2090 NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2091 NSPoint dstOrigin = dstRect.origin;
2093 NSTRACE (ns_shift_glyphs_for_insert);
2095 ns_focus (f, &dstRect, 1);
2096 NSCopyBits (0, srcRect, dstOrigin);
2102 /* ==========================================================================
2104 Character encoding and metrics
2106 ========================================================================== */
2110 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2111 /* --------------------------------------------------------------------------
2112 23: External (RIF); compute left/right overhang of whole string and set in s
2113 -------------------------------------------------------------------------- */
2115 struct face *face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2116 struct font *font = s->font; /*face->font; */
2120 struct font_metrics metrics;
2121 unsigned int codes[2];
2122 codes[0] = *(s->char2b);
2123 codes[1] = *(s->char2b + s->nchars - 1);
2125 font->driver->text_extents (font, codes, 2, &metrics);
2126 s->left_overhang = -metrics.lbearing;
2128 = metrics.rbearing > metrics.width
2129 ? metrics.rbearing - metrics.width : 0;
2133 s->left_overhang = 0;
2134 s->right_overhang = ((struct nsfont_info *)font)->ital ?
2135 FONT_HEIGHT (font) * 0.2 : 0;
2141 /* ==========================================================================
2143 Fringe and cursor drawing
2145 ========================================================================== */
2148 extern int max_used_fringe_bitmap;
2150 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2151 struct draw_fringe_bitmap_params *p)
2152 /* --------------------------------------------------------------------------
2153 23: External (RIF); fringe-related
2154 -------------------------------------------------------------------------- */
2156 struct frame *f = XFRAME (WINDOW_FRAME (w));
2157 struct face *face = p->face;
2159 static EmacsImage **bimgs = NULL;
2160 static int nBimgs = 0;
2161 /* NS-specific: move internal border inside fringe */
2162 int x = p->bx < 0 ? p->x : p->bx;
2163 int wd = p->bx < 0 ? p->wd : p->nx;
2164 BOOL fringeOnVeryLeft
2165 = x - WINDOW_LEFT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w)
2166 - FRAME_INTERNAL_BORDER_WIDTH (f) < 10;
2167 BOOL fringeOnVeryRight
2168 = FRAME_PIXEL_WIDTH (f) - x - wd - FRAME_INTERNAL_BORDER_WIDTH (f)
2169 - WINDOW_RIGHT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w) < 10;
2170 int xAdjust = FRAME_INTERNAL_BORDER_WIDTH (f) *
2171 (fringeOnVeryLeft ? -1 : (fringeOnVeryRight ? 1 : 0));
2173 /* grow bimgs if needed */
2174 if (nBimgs < max_used_fringe_bitmap)
2176 EmacsImage **newBimgs
2177 = xmalloc (max_used_fringe_bitmap * sizeof (EmacsImage *));
2178 bzero (newBimgs, max_used_fringe_bitmap * sizeof (EmacsImage *));
2182 bcopy (bimgs, newBimgs, nBimgs * sizeof (EmacsImage *));
2187 nBimgs = max_used_fringe_bitmap;
2190 /* Must clip because of partially visible lines. */
2191 rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
2194 /* Adjust position of "bottom aligned" bitmap on partially
2195 visible last row. */
2197 int oldVH = row->visible_height;
2198 row->visible_height = p->h;
2199 row->y -= rowY - p->y;
2200 ns_clip_to_row (w, row, -1, NO);
2202 row->visible_height = oldVH;
2205 ns_clip_to_row (w, row, -1, YES);
2207 if (p->bx >= 0 && !p->overlay_p)
2209 int yAdjust = rowY - FRAME_INTERNAL_BORDER_WIDTH (f) < 5 ?
2210 -FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2211 int yIncr = FRAME_PIXEL_HEIGHT (f) - (p->by+yAdjust + p->ny) < 5 ?
2212 FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2214 yIncr += FRAME_INTERNAL_BORDER_WIDTH (f);
2215 NSRect r = NSMakeRect (p->bx+xAdjust, p->by+yAdjust, p->nx, p->ny+yIncr);
2217 [ns_lookup_indexed_color(face->background, f) set];
2223 NSRect r = NSMakeRect (p->x+xAdjust, p->y, p->wd, p->h);
2224 NSPoint pt = r.origin;
2225 EmacsImage *img = bimgs[p->which - 1];
2229 unsigned short *bits = p->bits + p->dh;
2230 int len = 8 * p->h/8;
2232 unsigned char *cbits = xmalloc (len);
2234 for (i =0; i<len; i++)
2235 cbits[i] = ~(bits[i] & 0xff);
2236 img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2238 bimgs[p->which - 1] = img;
2243 /* Since we composite the bitmap instead of just blitting it, we need
2244 to erase the whole background. */
2245 [ns_lookup_indexed_color(face->background, f) set];
2248 [img setXBMColor: ns_lookup_indexed_color(face->foreground, f)];
2249 [img compositeToPoint: pt operation: NSCompositeSourceOver];
2256 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2257 int x, int y, int cursor_type, int cursor_width,
2258 int on_p, int active_p)
2259 /* --------------------------------------------------------------------------
2260 External call (RIF): draw cursor
2261 (modeled after x_draw_window_cursor
2262 FIXME: cursor_width is effectively bogus -- it sometimes gets set
2263 in xdisp.c set_frame_cursor_types, sometimes left uninitialized;
2264 DON'T USE IT (no other terms do)
2265 -------------------------------------------------------------------------- */
2269 struct frame *f = WINDOW_XFRAME (w);
2270 struct glyph *phys_cursor_glyph;
2271 int overspill, cursorToDraw;
2273 NSTRACE (dumpcursor);
2274 //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);
2279 w->phys_cursor_type = cursor_type;
2280 w->phys_cursor_on_p = on_p;
2282 if (cursor_type == NO_CURSOR)
2284 w->phys_cursor_width = 0;
2288 if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2290 if (glyph_row->exact_window_width_line_p
2291 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2293 glyph_row->cursor_in_fringe_p = 1;
2294 draw_fringe_bitmap (w, glyph_row, 0);
2299 get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2301 r.origin.x = fx, r.origin.y = fy;
2303 r.size.width = w->phys_cursor_width;
2305 /* FIXME: if we overwrite the internal border area, it does not get erased;
2306 fix by truncating cursor, but better would be to erase properly */
2307 overspill = r.origin.x + r.size.width -
2308 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, WINDOW_BOX_RIGHT_EDGE_X (w)
2309 - WINDOW_TOTAL_FRINGE_WIDTH (w) - FRAME_INTERNAL_BORDER_WIDTH (f));
2311 r.size.width -= overspill;
2313 /* TODO: only needed in rare cases with last-resort font in HELLO..
2314 should we do this more efficiently? */
2315 ns_clip_to_row (w, glyph_row, -1, NO); /* do ns_focus(f, &r, 1); if remove */
2316 [FRAME_CURSOR_COLOR (f) set];
2318 #ifdef NS_IMPL_COCOA
2319 /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2320 atomic. Cleaner ways of doing this should be investigated.
2321 One way would be to set a global variable DRAWING_CURSOR
2322 when making the call to draw_phys..(), don't focus in that
2323 case, then move the ns_unfocus() here after that call. */
2324 NSDisableScreenUpdates ();
2327 cursorToDraw = active_p ? cursor_type : HOLLOW_BOX_CURSOR;
2328 switch (cursorToDraw)
2332 case FILLED_BOX_CURSOR:
2335 case HOLLOW_BOX_CURSOR:
2337 [FRAME_BACKGROUND_COLOR (f) set];
2338 NSRectFill (NSInsetRect (r, 1, 1));
2339 [FRAME_CURSOR_COLOR (f) set];
2343 s.origin.y += lrint (0.75 * s.size.height);
2344 s.size.height = lrint (s.size.height * 0.25);
2349 s.size.width = min (cursor_width, 2); //FIXME(see above)
2355 /* draw the character under the cursor */
2356 if (cursorToDraw != NO_CURSOR)
2357 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2359 #ifdef NS_IMPL_COCOA
2360 NSEnableScreenUpdates ();
2367 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2368 /* --------------------------------------------------------------------------
2369 External (RIF): Draw a vertical line.
2370 -------------------------------------------------------------------------- */
2372 struct frame *f = XFRAME (WINDOW_FRAME (w));
2374 NSRect r = NSMakeRect (x, y0, 2, y1-y0);
2376 NSTRACE (ns_draw_vertical_window_border);
2378 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2380 [ns_lookup_indexed_color(face->foreground, f) set];
2382 ns_focus (f, &r, 1);
2383 NSDrawGroove (r, r);
2389 show_hourglass (struct atimer *timer)
2391 if (hourglass_shown_p)
2396 /* TODO: add NSProgressIndicator to selected frame (see macfns.c) */
2398 hourglass_shown_p = 1;
2406 if (!hourglass_shown_p)
2411 /* TODO: remove NSProgressIndicator from all frames */
2413 hourglass_shown_p = 0;
2419 /* ==========================================================================
2421 Glyph drawing operations
2423 ========================================================================== */
2426 static inline NSRect
2427 ns_fix_rect_ibw (NSRect r, int fibw, int frame_pixel_width)
2428 /* --------------------------------------------------------------------------
2429 Under NS we draw internal borders inside fringes, and want full-width
2430 rendering to go all the way to edge. This function makes that correction.
2431 -------------------------------------------------------------------------- */
2433 if (r.origin.y <= fibw+1)
2435 r.size.height += r.origin.y;
2438 if (r.origin.x <= fibw+1)
2440 r.size.width += r.origin.x;
2443 if (frame_pixel_width - (r.origin.x+r.size.width) <= fibw+1)
2444 r.size.width += fibw;
2451 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2452 /* --------------------------------------------------------------------------
2453 Wrapper utility to account for internal border width on full-width lines,
2454 and allow top full-width rows to hit the frame top. nr should be pointer
2455 to two successive NSRects. Number of rects actually used is returned.
2456 -------------------------------------------------------------------------- */
2458 int n = get_glyph_string_clip_rects (s, nr, 2);
2459 if (s->row->full_width_p)
2461 *nr = ns_fix_rect_ibw (*nr, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2462 FRAME_PIXEL_WIDTH (s->f));
2464 *nr = ns_fix_rect_ibw (*(nr+1), FRAME_INTERNAL_BORDER_WIDTH (s->f),
2465 FRAME_PIXEL_WIDTH (s->f));
2472 ns_draw_box (NSRect r, float thickness, NSColor *col, char left_p, char right_p)
2473 /* --------------------------------------------------------------------------
2474 Draw an unfilled rect inside r, optionally leaving left and/or right open.
2475 Note we can't just use an NSDrawRect command, because of the possibility
2476 of some sides not being drawn, and because the rect will be filled.
2477 -------------------------------------------------------------------------- */
2483 s.size.height = thickness;
2485 s.origin.y += r.size.height - thickness;
2488 s.size.height = r.size.height;
2489 s.origin.y = r.origin.y;
2491 /* left, right (optional) */
2492 s.size.width = thickness;
2497 s.origin.x += r.size.width - thickness;
2504 ns_draw_relief (NSRect r, int thickness, char raised_p,
2505 char top_p, char bottom_p, char left_p, char right_p,
2506 struct glyph_string *s)
2507 /* --------------------------------------------------------------------------
2508 Draw a relief rect inside r, optionally leaving some sides open.
2509 Note we can't just use an NSDrawBezel command, because of the possibility
2510 of some sides not being drawn, and because the rect will be filled.
2511 -------------------------------------------------------------------------- */
2513 static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2514 NSColor *newBaseCol = nil;
2517 NSTRACE (ns_draw_relief);
2521 if (s->face->use_box_color_for_shadows_p)
2523 newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2525 /* else if (s->first_glyph->type == IMAGE_GLYPH
2527 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2529 newBaseCol = IMAGE_BACKGROUND (s->img, s->f, 0);
2533 newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2536 if (newBaseCol == nil)
2537 newBaseCol = [NSColor grayColor];
2539 if (newBaseCol != baseCol) /* TODO: better check */
2542 baseCol = [newBaseCol retain];
2544 lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2546 darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2549 [(raised_p ? lightCol : darkCol) set];
2551 /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2554 sr.size.height = thickness;
2555 if (top_p) NSRectFill (sr);
2558 sr.size.height = r.size.height;
2559 sr.size.width = thickness;
2560 if (left_p) NSRectFill (sr);
2562 [(raised_p ? darkCol : lightCol) set];
2565 sr.size.width = r.size.width;
2566 sr.size.height = thickness;
2567 sr.origin.y += r.size.height - thickness;
2568 if (bottom_p) NSRectFill (sr);
2571 sr.size.height = r.size.height;
2572 sr.origin.y = r.origin.y;
2573 sr.size.width = thickness;
2574 sr.origin.x += r.size.width - thickness;
2575 if (right_p) NSRectFill (sr);
2580 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2581 /* --------------------------------------------------------------------------
2582 Function modeled after x_draw_glyph_string_box ().
2583 Sets up parameters for drawing.
2584 -------------------------------------------------------------------------- */
2586 int right_x, last_x;
2587 char left_p, right_p;
2588 struct glyph *last_glyph;
2593 if (s->hl == DRAW_MOUSE_FACE)
2596 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2598 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2603 thickness = face->box_line_width;
2605 NSTRACE (ns_dumpglyphs_box_or_relief);
2607 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2608 ? WINDOW_RIGHT_EDGE_X (s->w)
2609 : window_box_right (s->w, s->area));
2610 last_glyph = (s->cmp || s->img
2611 ? s->first_glyph : s->first_glyph + s->nchars-1);
2613 right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2614 ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2616 left_p = (s->first_glyph->left_box_line_p
2617 || (s->hl == DRAW_MOUSE_FACE
2618 && (s->prev == NULL || s->prev->hl != s->hl)));
2619 right_p = (last_glyph->right_box_line_p
2620 || (s->hl == DRAW_MOUSE_FACE
2621 && (s->next == NULL || s->next->hl != s->hl)));
2623 r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2625 /* expand full-width row over internal borders */
2626 if (s->row->full_width_p)
2627 r = ns_fix_rect_ibw (r, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2628 FRAME_PIXEL_WIDTH (s->f));
2630 if (s->face->box == FACE_SIMPLE_BOX)
2632 xassert (s->face->box_color != nil);
2633 ns_draw_box (r, abs (thickness),
2634 ns_lookup_indexed_color (face->box_color, s->f),
2639 ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2640 1, 1, left_p, right_p, s);
2646 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2647 /* --------------------------------------------------------------------------
2648 Modeled after x_draw_glyph_string_background, which draws BG in
2649 certain cases. Others are left to the text rendering routine.
2650 -------------------------------------------------------------------------- */
2652 NSTRACE (ns_maybe_dumpglyphs_background);
2654 if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2656 int box_line_width = max (s->face->box_line_width, 0);
2657 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2658 || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2661 if (s->hl == DRAW_MOUSE_FACE)
2664 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2666 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2669 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2671 [(NS_FACE_BACKGROUND (face) != 0
2672 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2673 : FRAME_BACKGROUND_COLOR (s->f)) set];
2676 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (s->f);
2677 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2680 if (s->hl != DRAW_CURSOR)
2682 NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2683 s->background_width,
2684 s->height-2*box_line_width);
2686 /* expand full-width row over internal borders */
2687 if (s->row->full_width_p)
2689 int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2690 if (r.origin.y <= fibw+1 + box_line_width)
2692 r.size.height += r.origin.y;
2695 if (r.origin.x <= fibw+1)
2697 r.size.width += 2*r.origin.x;
2700 if (FRAME_PIXEL_WIDTH (s->f) - (r.origin.x + r.size.width)
2702 r.size.width += fibw;
2708 s->background_filled_p = 1;
2715 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2716 /* --------------------------------------------------------------------------
2717 Renders an image and associated borders.
2718 -------------------------------------------------------------------------- */
2720 EmacsImage *img = s->img->pixmap;
2721 int box_line_vwidth = max (s->face->box_line_width, 0);
2722 int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2723 int bg_x, bg_y, bg_height;
2728 NSTRACE (ns_dumpglyphs_image);
2730 if (s->face->box != FACE_NO_BOX
2731 && s->first_glyph->left_box_line_p && s->slice.x == 0)
2732 x += abs (s->face->box_line_width);
2735 bg_y = s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2736 bg_height = s->height;
2737 /* other terms have this, but was causing problems w/tabbar mode */
2738 /* - 2 * box_line_vwidth; */
2740 if (s->slice.x == 0) x += s->img->hmargin;
2741 if (s->slice.y == 0) y += s->img->vmargin;
2743 /* Draw BG: if we need larger area than image itself cleared, do that,
2744 otherwise, since we composite the image under NS (instead of mucking
2745 with its background color), we must clear just the image area. */
2746 [ns_lookup_indexed_color (NS_FACE_BACKGROUND
2747 (FACE_FROM_ID (s->f, s->first_glyph->face_id)), s->f) set];
2749 if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
2750 || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
2752 br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
2753 s->background_filled_p = 1;
2757 br = NSMakeRect (x, y, s->slice.width, s->slice.height);
2760 /* expand full-width row over internal borders */
2761 if (s->row->full_width_p)
2763 int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2764 if (br.origin.y <= fibw+1 + box_line_vwidth)
2766 br.size.height += br.origin.y;
2769 if (br.origin.x <= fibw+1 + box_line_vwidth)
2771 br.size.width += br.origin.x;
2774 if (FRAME_PIXEL_WIDTH (s->f) - (br.origin.x + br.size.width) <= fibw+1)
2775 br.size.width += fibw;
2780 /* Draw the image.. do we need to draw placeholder if img ==nil? */
2782 [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
2783 operation: NSCompositeSourceOver];
2785 /* Draw relief, if requested */
2786 if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
2788 if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
2790 th = tool_bar_button_relief >= 0 ?
2791 tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2792 raised_p = (s->hl == DRAW_IMAGE_RAISED);
2796 th = abs (s->img->relief);
2797 raised_p = (s->img->relief > 0);
2800 r.origin.x = x - th;
2801 r.origin.y = y - th;
2802 r.size.width = s->slice.width + 2*th-1;
2803 r.size.height = s->slice.height + 2*th-1;
2804 ns_draw_relief (r, th, raised_p,
2806 s->slice.y + s->slice.height == s->img->height,
2808 s->slice.x + s->slice.width == s->img->width, s);
2814 ns_draw_glyph_string (struct glyph_string *s)
2815 /* --------------------------------------------------------------------------
2816 External (RIF): Main draw-text call.
2817 -------------------------------------------------------------------------- */
2819 /* TODO (optimize): focus for box and contents draw */
2822 char box_drawn_p = 0;
2824 NSTRACE (ns_draw_glyph_string);
2826 if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
2829 struct glyph_string *next;
2831 for (width = 0, next = s->next; next;
2832 width += next->width, next = next->next)
2833 if (next->first_glyph->type != IMAGE_GLYPH)
2835 n = ns_get_glyph_string_clip_rect (s->next, r);
2836 ns_focus (s->f, r, n);
2837 ns_maybe_dumpglyphs_background (s->next, 1);
2839 next->num_clips = 0;
2843 if (!s->for_overlaps && s->face->box != FACE_NO_BOX
2844 && (s->first_glyph->type == CHAR_GLYPH
2845 || s->first_glyph->type == COMPOSITE_GLYPH))
2847 n = ns_get_glyph_string_clip_rect (s, r);
2848 ns_focus (s->f, r, n);
2849 ns_maybe_dumpglyphs_background (s, 1);
2850 ns_dumpglyphs_box_or_relief (s);
2855 switch (s->first_glyph->type)
2859 n = ns_get_glyph_string_clip_rect (s, r);
2860 ns_focus (s->f, r, n);
2861 ns_dumpglyphs_image (s, r[0]);
2866 if (!s->background_filled_p)
2868 *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
2870 if (!s->row->full_width_p)
2872 /* truncate to avoid overwriting fringe and/or scrollbar */
2873 int overrun = max (0, (s->x + s->background_width)
2874 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
2875 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
2876 r[0].size.width -= overrun;
2878 /* XXX: Try to work between problem where a stretch glyph on
2879 a partially-visible bottom row will clear part of the
2880 modeline, and another where list-buffers headers and similar
2881 rows erroneously have visible_height set to 0. Not sure
2882 where this is coming from as other terms seem not to show. */
2883 r[0].size.height = min (s->height, s->row->visible_height);
2886 /* expand full-width rows over internal borders */
2889 r[0] = ns_fix_rect_ibw (r[0], FRAME_INTERNAL_BORDER_WIDTH (s->f),
2890 FRAME_PIXEL_WIDTH (s->f));
2893 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
2894 overwriting cursor (usually when cursor on a tab) */
2895 if (s->hl == DRAW_CURSOR)
2897 r[0].origin.x += s->width;
2898 r[0].size.width -= s->width;
2901 ns_focus (s->f, r, 1);
2902 [ns_lookup_indexed_color (NS_FACE_BACKGROUND
2903 (FACE_FROM_ID (s->f, s->first_glyph->face_id)), s->f) set];
2906 s->background_filled_p = 1;
2911 case COMPOSITE_GLYPH:
2912 n = ns_get_glyph_string_clip_rect (s, r);
2913 ns_focus (s->f, r, n);
2915 if (s->for_overlaps || (s->cmp_from > 0
2916 && ! s->first_glyph->u.cmp.automatic))
2917 s->background_filled_p = 1;
2919 ns_maybe_dumpglyphs_background
2920 (s, s->first_glyph->type == COMPOSITE_GLYPH);
2922 ns_tmp_flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
2923 (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
2924 (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
2925 NS_DUMPGLYPH_NORMAL));
2926 ns_tmp_font = (struct nsfont_info *)s->face->font;
2927 if (ns_tmp_font == NULL)
2928 ns_tmp_font = (struct nsfont_info *)FRAME_FONT (s->f);
2930 ns_tmp_font->font.driver->draw
2931 (s, 0, s->nchars, s->x, s->y,
2932 (ns_tmp_flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
2933 || ns_tmp_flags == NS_DUMPGLYPH_MOUSEFACE);
2942 /* Draw box if not done already. */
2943 if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
2945 n = ns_get_glyph_string_clip_rect (s, r);
2946 ns_focus (s->f, r, n);
2947 ns_dumpglyphs_box_or_relief (s);
2956 /* ==========================================================================
2960 ========================================================================== */
2964 ns_send_appdefined (int value)
2965 /* --------------------------------------------------------------------------
2966 Internal: post an appdefined event which EmacsApp-sendEvent will
2967 recognize and take as a command to halt the event loop.
2968 -------------------------------------------------------------------------- */
2970 /*NSTRACE (ns_send_appdefined); */
2972 /* Only post this event if we haven't already posted one. This will end
2973 the [NXApp run] main loop after having processed all events queued at
2975 if (send_appdefined)
2979 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
2980 send_appdefined = NO;
2982 /* Don't need wakeup timer any more */
2985 [timed_entry invalidate];
2986 [timed_entry release];
2990 /* Ditto for file descriptor poller */
2993 [fd_entry invalidate];
2998 nxev = [NSEvent otherEventWithType: NSApplicationDefined
2999 location: NSMakePoint (0, 0)
3002 windowNumber: [[NSApp mainWindow] windowNumber]
3003 context: [NSApp context]
3008 /* Post an application defined event on the event queue. When this is
3009 received the [NXApp run] will return, thus having processed all
3010 events which are currently queued. */
3011 [NSApp postEvent: nxev atStart: NO];
3017 ns_read_socket (struct terminal *terminal, int expected,
3018 struct input_event *hold_quit)
3019 /* --------------------------------------------------------------------------
3020 External (hook): Post an event to ourself and keep reading events until
3021 we read it back again. In effect process all events which were waiting.
3022 23: Now we have to manage the event buffer ourselves.
3023 -------------------------------------------------------------------------- */
3025 struct input_event ev;
3027 static NSDate *lastCheck = nil;
3028 /* NSTRACE (ns_read_socket); */
3030 if (interrupt_input_blocked)
3032 interrupt_input_pending = 1;
3036 interrupt_input_pending = 0;
3039 #ifdef COCOA_EXPERIMENTAL_CTRL_G
3040 /* causes Feval to abort; unclear on why this isn't in calling code */
3044 n_emacs_events_pending = 0;
3047 q_event_ptr = hold_quit;
3049 /* we manage autorelease pools by allocate/reallocate each time around
3050 the loop; strict nesting is occasionally violated but seems not to
3051 matter.. earlier methods using full nesting caused major memory leaks */
3052 [outerpool release];
3053 outerpool = [[NSAutoreleasePool alloc] init];
3055 /* If have pending open-file requests, attend to the next one of those. */
3056 if (ns_pending_files && [ns_pending_files count] != 0
3057 && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3059 [ns_pending_files removeObjectAtIndex: 0];
3061 /* Deal with pending service requests. */
3062 else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3064 NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3065 withArg: [ns_pending_service_args objectAtIndex: 0]])
3067 [ns_pending_service_names removeObjectAtIndex: 0];
3068 [ns_pending_service_args removeObjectAtIndex: 0];
3072 /* Run and wait for events. We must always send one NX_APPDEFINED event
3073 to ourself, otherwise [NXApp run] will never exit. */
3074 send_appdefined = YES;
3076 /* TODO: from termhooks.h: */
3077 /* XXX Please note that a non-zero value of EXPECTED only means that
3078 there is available input on at least one of the currently opened
3079 terminal devices -- but not necessarily on this device.
3080 Therefore, in most cases EXPECTED should be simply ignored. */
3081 /* However, if in ns_select, this is called from gobble_input, which
3082 appears to set it correctly for our purposes, and always assuming
3083 !expected causes 100% CPU usage. */
3084 if (!inNsSelect || !expected)
3086 /* Post an application defined event on the event queue. When this is
3087 received the [NXApp run] will return, thus having processed all
3088 events which are currently queued, if any. */
3089 ns_send_appdefined (-1);
3095 nevents = n_emacs_events_pending;
3096 n_emacs_events_pending = 0;
3097 emacs_event = q_event_ptr = NULL;
3099 #ifdef COCOA_EXPERIMENTAL_CTRL_G
3108 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3109 fd_set *exceptfds, struct timeval *timeout)
3110 /* --------------------------------------------------------------------------
3111 Replacement for select, checking for events
3112 -------------------------------------------------------------------------- */
3117 /* NSTRACE (ns_select); */
3119 if (NSApp == nil /* || ([NSApp isActive] == NO &&
3120 [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
3121 inMode:NSDefaultRunLoopMode dequeue:NO] == nil) */)
3122 return select (nfds, readfds, writefds, exceptfds, timeout);
3124 /* Save file descriptor set, which gets overwritten in calls to select ()
3125 Note, this is called from process.c, and only readfds is ever set */
3128 memcpy (&select_readfds, readfds, sizeof (fd_set));
3134 /* Try an initial select for pending data on input files */
3135 select_timeout.tv_sec = select_timeout.tv_usec = 0;
3136 result = select (nfds, readfds, writefds, exceptfds, &select_timeout);
3140 /* if (!timeout || timed_entry || fd_entry)
3141 fprintf (stderr, "assertion failed: timeout null or timed_entry/fd_entry non-null in ns_select\n"); */
3143 /* set a timeout and run the main AppKit event loop while continuing
3144 to monitor the files */
3145 time = ((double) timeout->tv_sec) + ((double) timeout->tv_usec)/1000000.0;
3146 timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3148 selector: @selector (timeout_handler:)
3150 repeats: YES] /* for safe removal */
3153 /* set a periodic task to try the select () again */
3154 fd_entry = [[NSTimer scheduledTimerWithTimeInterval: 0.1
3156 selector: @selector (fd_handler:)
3161 /* Let Application dispatch events until it receives an event of the type
3162 NX_APPDEFINED, which should only be sent by timeout_handler. */
3164 gobble_input (timeout ? 1 : 0);
3165 ev = last_appdefined_event;
3171 if ([ev type] != NSApplicationDefined)
3175 last_appdefined_event = 0;
3179 /* The NX_APPDEFINED event we received was a timeout. */
3184 /* The NX_APPDEFINED event we received was the result of
3185 at least one real input event arriving. */
3191 /* Received back from select () in fd_handler; copy the results */
3193 memcpy (readfds, &select_readfds, sizeof (fd_set));
3197 /* never reached, shut compiler up */
3203 /* ==========================================================================
3207 ========================================================================== */
3211 ns_set_vertical_scroll_bar (struct window *window,
3212 int portion, int whole, int position)
3213 /* --------------------------------------------------------------------------
3214 External (hook): Update or add scrollbar
3215 -------------------------------------------------------------------------- */
3219 struct frame *f = XFRAME (WINDOW_FRAME (window));
3220 EmacsView *view = FRAME_NS_VIEW (f);
3221 int window_y, window_height;
3222 BOOL barOnVeryLeft, barOnVeryRight;
3223 int top, left, height, width, sb_width, sb_left;
3225 static int count = 0;
3227 /* optimization; display engine sends WAY too many of these.. */
3228 if (!NILP (window->vertical_scroll_bar))
3230 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3231 if ([bar checkSamePosition: position portion: portion whole: whole])
3233 if (view->scrollbarsNeedingUpdate == 0)
3235 if (!windows_or_buffers_changed)
3239 view->scrollbarsNeedingUpdate--;
3243 NSTRACE (ns_set_vertical_scroll_bar);
3245 /* Get dimensions. */
3246 window_box (window, -1, 0, &window_y, 0, &window_height);
3248 height = window_height;
3249 width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3250 left = WINDOW_SCROLL_BAR_AREA_X (window);
3252 if (top < 5) /* top scrollbar adjustment */
3254 top -= FRAME_INTERNAL_BORDER_WIDTH (f);
3255 height += FRAME_INTERNAL_BORDER_WIDTH (f);
3258 /* allow for displaying a skinnier scrollbar than char area allotted */
3259 sb_width = (WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) > 0) ?
3260 WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) : width;
3262 barOnVeryLeft = left < 5;
3263 barOnVeryRight = FRAME_PIXEL_WIDTH (f) - left - width < 5;
3264 sb_left = left + FRAME_INTERNAL_BORDER_WIDTH (f)
3265 * (barOnVeryLeft ? -1 : (barOnVeryRight ? 1 : 0));
3267 r = NSMakeRect (sb_left, top, sb_width, height);
3268 /* the parent view is flipped, so we need to flip y value */
3270 r.origin.y = (v.size.height - r.size.height - r.origin.y);
3272 XSETWINDOW (win, window);
3275 /* we want at least 5 lines to display a scrollbar */
3276 if (WINDOW_TOTAL_LINES (window) < 5)
3278 if (!NILP (window->vertical_scroll_bar))
3280 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3281 [bar removeFromSuperview];
3282 window->vertical_scroll_bar = Qnil;
3284 ns_clear_frame_area (f, sb_left, top, width, height);
3289 if (NILP (window->vertical_scroll_bar))
3291 ns_clear_frame_area (f, sb_left, top, width, height);
3292 bar = [[EmacsScroller alloc] initFrame: r window: win];
3293 window->vertical_scroll_bar = make_save_value (bar, 0);
3298 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3299 oldRect = [bar frame];
3300 r.size.width = oldRect.size.width;
3301 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3303 if (oldRect.origin.x != r.origin.x)
3304 ns_clear_frame_area (f, sb_left, top, width, height);
3309 [bar setPosition: position portion: portion whole: whole];
3315 ns_condemn_scroll_bars (struct frame *f)
3316 /* --------------------------------------------------------------------------
3317 External (hook): arrange for all frame's scrollbars to be removed
3318 at next call to judge_scroll_bars, except for those redeemed.
3319 -------------------------------------------------------------------------- */
3323 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3325 NSTRACE (ns_condemn_scroll_bars);
3327 for (i =[subviews count]-1; i >= 0; i--)
3329 view = [subviews objectAtIndex: i];
3330 if ([view isKindOfClass: [EmacsScroller class]])
3337 ns_redeem_scroll_bar (struct window *window)
3338 /* --------------------------------------------------------------------------
3339 External (hook): arrange to spare this window's scrollbar
3340 at next call to judge_scroll_bars.
3341 -------------------------------------------------------------------------- */
3344 NSTRACE (ns_redeem_scroll_bar);
3345 if (!NILP (window->vertical_scroll_bar))
3347 bar =XNS_SCROLL_BAR (window->vertical_scroll_bar);
3354 ns_judge_scroll_bars (struct frame *f)
3355 /* --------------------------------------------------------------------------
3356 External (hook): destroy all scrollbars on frame that weren't
3357 redeemed after call to condemn_scroll_bars.
3358 -------------------------------------------------------------------------- */
3362 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3363 NSTRACE (ns_judge_scroll_bars);
3364 for (i =[subviews count]-1; i >= 0; i--)
3366 view = [subviews objectAtIndex: i];
3367 if (![view isKindOfClass: [EmacsScroller class]]) continue;
3374 /* ==========================================================================
3376 Miscellaneous, mainly stubbed-out functions added in 23
3378 ========================================================================== */
3382 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
3388 /* ==========================================================================
3392 ========================================================================== */
3395 x_display_pixel_height (dpyinfo)
3396 struct ns_display_info *dpyinfo;
3398 NSScreen *screen = [NSScreen mainScreen];
3399 return [screen frame].size.height;
3403 x_display_pixel_width (dpyinfo)
3404 struct ns_display_info *dpyinfo;
3406 NSScreen *screen = [NSScreen mainScreen];
3407 return [screen frame].size.width;
3411 static Lisp_Object ns_string_to_lispmod (const char *s)
3412 /* --------------------------------------------------------------------------
3413 Convert modifier name to lisp symbol
3414 -------------------------------------------------------------------------- */
3416 if (!strncmp (SDATA (SYMBOL_NAME (Qmeta)), s, 10))
3418 else if (!strncmp (SDATA (SYMBOL_NAME (Qsuper)), s, 10))
3420 else if (!strncmp (SDATA (SYMBOL_NAME (Qcontrol)), s, 10))
3422 else if (!strncmp (SDATA (SYMBOL_NAME (Qalt)), s, 10))
3424 else if (!strncmp (SDATA (SYMBOL_NAME (Qhyper)), s, 10))
3426 else if (!strncmp (SDATA (SYMBOL_NAME (Qnone)), s, 10))
3433 static Lisp_Object ns_mod_to_lisp (int m)
3434 /* --------------------------------------------------------------------------
3435 Convert modifier code (see lisp.h) to lisp symbol
3436 -------------------------------------------------------------------------- */
3440 else if (m == CHAR_SUPER)
3442 else if (m == CHAR_CTL)
3444 else if (m == CHAR_ALT)
3446 else if (m == CHAR_HYPER)
3448 else /* if (m == 0) */
3454 ns_set_default_prefs ()
3455 /* --------------------------------------------------------------------------
3456 Initialize preference variables to defaults
3457 -------------------------------------------------------------------------- */
3459 ns_alternate_modifier = Qmeta;
3460 ns_command_modifier = Qsuper;
3461 ns_control_modifier = Qcontrol;
3462 ns_function_modifier = Qnone;
3463 ns_expand_space = make_float (0.0);
3464 ns_antialias_text = Qt;
3465 ns_antialias_threshold = 10.0; /* not exposed to lisp side */
3466 ns_use_qd_smoothing = Qnil;
3467 ns_use_system_highlight_color = Qt;
3472 ns_default (const char *parameter, Lisp_Object *result,
3473 Lisp_Object yesval, Lisp_Object noval,
3474 BOOL is_float, BOOL is_modstring)
3475 /* --------------------------------------------------------------------------
3476 Check a parameter value in user's preferences
3477 -------------------------------------------------------------------------- */
3481 if ( (value =[[[NSUserDefaults standardUserDefaults]
3482 stringForKey: [NSString stringWithUTF8String: parameter]]
3487 if (strcasecmp (value, "YES") == 0)
3489 else if (strcasecmp (value, "NO") == 0)
3491 else if (is_float && (f = strtod (value, &pos), pos != value))
3492 *result = make_float (f);
3493 else if (is_modstring && value)
3494 *result = ns_string_to_lispmod (value);
3495 else fprintf (stderr,
3496 "Bad value for default \"%s\": \"%s\"\n", parameter, value);
3502 ns_initialize_display_info (struct ns_display_info *dpyinfo)
3503 /* --------------------------------------------------------------------------
3504 Initialize global info and storage for display.
3505 -------------------------------------------------------------------------- */
3507 NSScreen *screen = [NSScreen mainScreen];
3508 NSWindowDepth depth = [screen depth];
3510 dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
3511 dpyinfo->resy = 72.27;
3512 dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
3513 NSColorSpaceFromDepth (depth)]
3514 && ![NSCalibratedWhiteColorSpace isEqualToString:
3515 NSColorSpaceFromDepth (depth)];
3516 dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
3517 dpyinfo->image_cache = make_image_cache ();
3518 dpyinfo->color_table
3519 = (struct ns_color_table *)xmalloc (sizeof (struct ns_color_table));
3520 dpyinfo->color_table->colors = NULL;
3521 dpyinfo->root_window = 42; /* a placeholder.. */
3523 dpyinfo->mouse_face_mouse_frame = NULL;
3524 dpyinfo->mouse_face_deferred_gc = 0;
3525 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
3526 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
3527 dpyinfo->mouse_face_face_id = DEFAULT_FACE_ID;
3528 dpyinfo->mouse_face_window = dpyinfo->mouse_face_overlay = Qnil;
3529 dpyinfo->mouse_face_hidden = 0;
3531 dpyinfo->mouse_face_mouse_x = dpyinfo->mouse_face_mouse_y = 0;
3532 dpyinfo->mouse_face_defer = 0;
3534 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
3536 dpyinfo->n_fonts = 0;
3537 dpyinfo->smallest_font_height = 1;
3538 dpyinfo->smallest_char_width = 1;
3542 /* 23: Needed as new part of display engine; this and next define public
3543 functions in this file (well, many of them, anyway). */
3544 /* x_... are generic versions in xdisp.c that we, and other terms, get away
3545 with using despite presence in the "system dependent" redisplay
3546 interface. In addition, many of the ns_ methods have code that is
3547 shared with all terms, indicating need for further refactoring. */
3548 extern frame_parm_handler ns_frame_parm_handlers[];
3549 static struct redisplay_interface ns_redisplay_interface =
3551 ns_frame_parm_handlers,
3552 x_produce_glyphs, /*generic OK */
3553 x_write_glyphs, /*generic OK */
3554 x_insert_glyphs, /*generic OK */
3555 x_clear_end_of_line, /*generic OK */
3556 ns_scroll_run, /*23 */
3557 ns_after_update_window_line, /*23: added */
3558 ns_update_window_begin, /*23: split from update_begin */
3559 ns_update_window_end, /*23: split from update_end */
3560 x_cursor_to, /*generic OK */
3562 0, /* flush_display_optional */
3563 x_clear_window_mouse_face, /*generic OK */
3564 x_get_glyph_overhangs, /*23: generic OK */
3565 x_fix_overlapping_area, /*generic OK */
3566 ns_draw_fringe_bitmap, /*23 */
3567 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
3568 0, /* destroy_fringe_bitmap */
3569 ns_compute_glyph_string_overhangs, /*23 */
3570 ns_draw_glyph_string, /*23: interface to nsfont.m */
3571 ns_define_frame_cursor, /*23 */
3572 ns_clear_frame_area, /*23 */
3573 ns_draw_window_cursor, /*23: revamped ns_dumpcursor */
3574 ns_draw_vertical_window_border,
3575 ns_shift_glyphs_for_insert
3580 ns_delete_display (struct ns_display_info *dpyinfo)
3586 /* This function is called when the last frame on a display is deleted. */
3588 ns_delete_terminal (struct terminal *terminal)
3590 struct ns_display_info *dpyinfo = terminal->display_info.ns;
3593 /* Protect against recursive calls. Fdelete_frame in
3594 delete_terminal calls us back when it deletes our last frame. */
3595 if (!terminal->name)
3600 x_destroy_all_bitmaps (dpyinfo);
3601 ns_delete_display (dpyinfo);
3606 static struct terminal *
3607 ns_create_terminal (struct ns_display_info *dpyinfo)
3608 /* --------------------------------------------------------------------------
3609 Set up use of NS before we make the first connection.
3610 -------------------------------------------------------------------------- */
3612 struct terminal *terminal;
3614 NSTRACE (ns_create_terminal);
3616 terminal = create_terminal ();
3618 terminal->type = output_ns;
3619 terminal->display_info.ns = dpyinfo;
3620 dpyinfo->terminal = terminal;
3622 terminal->rif = &ns_redisplay_interface;
3624 terminal->clear_frame_hook = ns_clear_frame;
3625 terminal->ins_del_lines_hook = 0; /* 23: vestigial? */
3626 terminal->delete_glyphs_hook = 0; /* 23: vestigial? */
3627 terminal->ring_bell_hook = ns_ring_bell;
3628 terminal->reset_terminal_modes_hook = ns_reset_terminal_modes;
3629 terminal->set_terminal_modes_hook = ns_set_terminal_modes;
3630 terminal->update_begin_hook = ns_update_begin;
3631 terminal->update_end_hook = ns_update_end;
3632 terminal->set_terminal_window_hook = NULL; /* 23: vestigial? */
3633 terminal->read_socket_hook = ns_read_socket;
3634 terminal->frame_up_to_date_hook = ns_frame_up_to_date;
3635 terminal->mouse_position_hook = ns_mouse_position;
3636 terminal->frame_rehighlight_hook = ns_frame_rehighlight;
3637 terminal->frame_raise_lower_hook = ns_frame_raise_lower;
3639 terminal->fullscreen_hook = 0; /*XTfullscreen_hook;//23.50 */
3641 terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
3642 terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
3643 terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
3644 terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
3646 terminal->delete_frame_hook = x_destroy_window;
3647 terminal->delete_terminal_hook = ns_delete_terminal;
3649 terminal->scroll_region_ok = 1;
3650 terminal->char_ins_del_ok = 1;
3651 terminal->line_ins_del_ok = 1;
3652 terminal->fast_clear_end_of_line = 1;
3653 terminal->memory_below_frame = 0;
3661 /* --------------------------------------------------------------------------
3662 Mainly vestigial under NS now that ns_create_terminal () does most things.
3663 -------------------------------------------------------------------------- */
3666 Fset_input_interrupt_mode (Qt);
3670 struct ns_display_info *
3671 ns_term_init (Lisp_Object display_name)
3672 /* --------------------------------------------------------------------------
3673 Start the Application and get things rolling.
3674 -------------------------------------------------------------------------- */
3676 extern Lisp_Object Fset_input_mode (Lisp_Object, Lisp_Object,
3677 Lisp_Object, Lisp_Object);
3678 struct terminal *terminal;
3679 struct ns_display_info *dpyinfo;
3680 static int ns_initialized = 0;
3683 NSTRACE (ns_term_init);
3685 /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
3686 /*GSDebugAllocationActive (YES); */
3688 handling_signal = 0;
3690 if (!ns_initialized)
3696 ns_pending_files = [[NSMutableArray alloc] init];
3697 ns_pending_service_names = [[NSMutableArray alloc] init];
3698 ns_pending_service_args = [[NSMutableArray alloc] init];
3700 /* Start app and create the main menu, window, view.
3701 Needs to be here because ns_initialize_display_info () uses AppKit classes.
3702 The view will then ask the NSApp to stop and return to Emacs. */
3703 [EmacsApp sharedApplication];
3706 [NSApp setDelegate: NSApp];
3708 /* debugging: log all notifications */
3709 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
3710 selector: @selector (logNotification:)
3711 name: nil object: nil]; */
3713 dpyinfo = (struct ns_display_info *)xmalloc (sizeof (struct ns_display_info));
3714 bzero (dpyinfo, sizeof (struct ns_display_info));
3716 ns_initialize_display_info (dpyinfo);
3717 terminal = ns_create_terminal (dpyinfo);
3719 terminal->kboard = (KBOARD *) xmalloc (sizeof (KBOARD));
3720 init_kboard (terminal->kboard);
3721 terminal->kboard->Vwindow_system = Qns;
3722 terminal->kboard->next_kboard = all_kboards;
3723 all_kboards = terminal->kboard;
3724 /* Don't let the initial kboard remain current longer than necessary.
3725 That would cause problems if a file loaded on startup tries to
3726 prompt in the mini-buffer. */
3727 if (current_kboard == initial_kboard)
3728 current_kboard = terminal->kboard;
3729 terminal->kboard->reference_count++;
3731 dpyinfo->next = x_display_list;
3732 x_display_list = dpyinfo;
3734 /* Put it on ns_display_name_list */
3735 ns_display_name_list = Fcons (Fcons (display_name, Qnil),
3736 ns_display_name_list);
3737 /* ns_display_name_list = Fcons (Fcons (display_name,
3738 Fcons (Qnil, dpyinfo->xrdb)),
3739 ns_display_name_list); */
3740 dpyinfo->name_list_element = XCAR (ns_display_name_list);
3742 /* Set the name of the terminal. */
3743 terminal->name = (char *) xmalloc (SBYTES (display_name) + 1);
3744 strncpy (terminal->name, SDATA (display_name), SBYTES (display_name));
3745 terminal->name[SBYTES (display_name)] = 0;
3749 /* Read various user defaults. */
3750 ns_set_default_prefs ();
3751 ns_default ("AlternateModifier", &ns_alternate_modifier,
3752 Qnil, Qnil, NO, YES);
3753 if (NILP (ns_alternate_modifier))
3754 ns_alternate_modifier = Qmeta;
3755 ns_default ("CommandModifier", &ns_command_modifier,
3756 Qnil, Qnil, NO, YES);
3757 if (NILP (ns_command_modifier))
3758 ns_command_modifier = Qsuper;
3759 ns_default ("ControlModifier", &ns_control_modifier,
3760 Qnil, Qnil, NO, YES);
3761 if (NILP (ns_control_modifier))
3762 ns_control_modifier = Qcontrol;
3763 ns_default ("FunctionModifier", &ns_function_modifier,
3764 Qnil, Qnil, NO, YES);
3765 if (NILP (ns_function_modifier))
3766 ns_function_modifier = Qnone;
3767 ns_default ("ExpandSpace", &ns_expand_space,
3768 make_float (0.5), make_float (0.0), YES, NO);
3769 ns_default ("GSFontAntiAlias", &ns_antialias_text,
3772 ns_default ("AppleAntiAliasingThreshold", &tmp,
3773 make_float (10.0), make_float (6.0), YES, NO);
3774 ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
3775 ns_default ("UseQuickdrawSmoothing", &ns_use_qd_smoothing,
3777 ns_default ("UseSystemHighlightColor", &ns_use_system_highlight_color,
3779 if (EQ (ns_use_system_highlight_color, Qt))
3781 ns_selection_color = [[NSUserDefaults standardUserDefaults]
3782 stringForKey: @"AppleHighlightColor"];
3783 if (ns_selection_color == nil)
3784 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
3787 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
3790 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
3794 Lisp_Object color_file, color_map, color;
3799 color_file = Fexpand_file_name (build_string ("rgb.txt"),
3800 Fsymbol_value (intern ("data-directory")));
3801 if (NILP (Ffile_readable_p (color_file)))
3802 fatal ("Could not find %s.\n", SDATA (color_file));
3804 color_map = Fx_load_color_file (color_file);
3805 if (NILP (color_map))
3806 fatal ("Could not read %s.\n", SDATA (color_file));
3808 cl = [[NSColorList alloc] initWithName: @"Emacs"];
3809 for ( ; CONSP (color_map); color_map = XCDR (color_map))
3811 color = XCAR (color_map);
3812 name = SDATA (XCAR (color));
3813 c = XINT (XCDR (color));
3815 [NSColor colorWithCalibratedRed: RED_FROM_ULONG (c) / 255.0
3816 green: GREEN_FROM_ULONG (c) / 255.0
3817 blue: BLUE_FROM_ULONG (c) / 255.0
3819 forKey: [NSString stringWithUTF8String: name]];
3821 [cl writeToFile: nil];
3827 #ifdef NS_IMPL_GNUSTEP
3828 strncpy (c, gnustep_base_version, sizeof (c));
3830 /*PSnextrelease (128, c); */
3831 snprintf (c, sizeof (c), "%g", NSAppKitVersionNumber);
3833 Vwindow_system_version = build_string (c);
3836 delete_keyboard_wait_descriptor (0);
3838 /* Set up OS X app menu */
3839 #ifdef NS_IMPL_COCOA
3843 /* set up the application menu */
3844 svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
3845 [svcsMenu setAutoenablesItems: NO];
3846 appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
3847 [appMenu setAutoenablesItems: NO];
3848 mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
3849 dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
3851 [appMenu insertItemWithTitle: @"About Emacs"
3852 action: @selector (orderFrontStandardAboutPanel:)
3855 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
3856 [appMenu insertItemWithTitle: @"Preferences..."
3857 action: @selector (showPreferencesWindow:)
3860 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
3861 item = [appMenu insertItemWithTitle: @"Services"
3862 action: @selector (menuDown:)
3865 [appMenu setSubmenu: svcsMenu forItem: item];
3866 /* [svcsMenu setSupercell: item]; */
3867 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
3868 [appMenu insertItemWithTitle: @"Hide Emacs"
3869 action: @selector (hide:)
3872 item = [appMenu insertItemWithTitle: @"Hide Others"
3873 action: @selector (hideOtherApplications:)
3876 [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
3877 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
3878 [appMenu insertItemWithTitle: @"Quit Emacs"
3879 action: @selector (terminate:)
3883 item = [mainMenu insertItemWithTitle: @"Emacs"
3884 action: @selector (menuDown:)
3887 [mainMenu setSubmenu: appMenu forItem: item];
3888 [dockMenu insertItemWithTitle: @"New Frame"
3889 action: @selector (newFrame:)
3893 [NSApp setMainMenu: mainMenu];
3894 [NSApp setAppleMenu: appMenu];
3895 [NSApp setServicesMenu: svcsMenu];
3896 /* Needed at least on Cocoa, to get dock menu to show windows */
3897 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
3899 #endif /* MAC OS X menu setup */
3907 extern Lisp_Object Vauto_save_list_file_name;
3909 ns_term_shutdown (int sig)
3911 /* code not reached in emacs.c after this is called by shut_down_emacs: */
3912 if (STRINGP (Vauto_save_list_file_name))
3913 unlink (SDATA (Vauto_save_list_file_name));
3915 ns_shutdown_properly = YES;
3916 [NSApp terminate: NSApp];
3920 /* ==========================================================================
3922 EmacsApp implementation
3924 ========================================================================== */
3927 @implementation EmacsApp
3929 - (void)logNotification: (NSNotification *)notification
3931 const char *name = [[notification name] UTF8String];
3932 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
3933 && !strstr (name, "WindowNumber"))
3934 NSLog (@"notification: '%@'", [notification name]);
3938 - (void)sendEvent: (NSEvent *)theEvent
3939 /* --------------------------------------------------------------------------
3940 Events posted by ns_send_appdefined interrupt the run loop here
3941 -------------------------------------------------------------------------- */
3943 int type = [theEvent type];
3944 NSWindow *window = [theEvent window];
3945 /* NSTRACE (sendEvent); */
3946 /*fprintf (stderr, "received event of type %d\n", [theEvent type]); */
3948 if (type == NSCursorUpdate && window == nil)
3950 fprintf (stderr, "Dropping external cursor update event.\n");
3954 #ifdef NS_IMPL_COCOA
3955 /* pass mouse down in resize handle and subsequent drags directly to
3956 EmacsWindow so we can generate continuous redisplays */
3959 if (type == NSLeftMouseDragged)
3961 [window mouseDragged: theEvent];
3964 else if (type == NSLeftMouseUp)
3966 [window mouseUp: theEvent];
3970 else if (type == NSLeftMouseDown)
3972 NSRect r = ns_resize_handle_rect (window);
3973 if (NSPointInRect ([theEvent locationInWindow], r))
3976 [window mouseDown: theEvent];
3982 if (type == NSApplicationDefined)
3984 last_appdefined_event = theEvent;
3988 [super sendEvent: theEvent];
3992 - (void)showPreferencesWindow: (id)sender
3994 if (prefsController == nil)
3995 prefsController = [[EmacsPrefsController alloc] init];
3996 [prefsController showForFrame: SELECTED_FRAME ()];
4000 - (void)newFrame: (id)sender
4002 struct frame *emacsframe = SELECTED_FRAME ();
4003 NSEvent *theEvent = [NSApp currentEvent];
4007 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4008 emacs_event->code = KEY_NS_NEW_FRAME;
4009 emacs_event->modifiers = 0;
4010 EV_TRAILER (theEvent);
4014 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4015 - (BOOL) openFile: (NSString *)fileName
4017 struct frame *emacsframe = SELECTED_FRAME ();
4018 NSEvent *theEvent = [NSApp currentEvent];
4023 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4024 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4025 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4026 ns_input_line = Qnil; /* can be start or cons start,end */
4027 emacs_event->modifiers =0;
4028 EV_TRAILER (theEvent);
4034 /* **************************************************************************
4036 EmacsApp delegate implementation
4038 ************************************************************************** */
4040 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4041 /* --------------------------------------------------------------------------
4042 When application is loaded, terminate event loop in ns_term_init
4043 -------------------------------------------------------------------------- */
4045 NSTRACE (applicationDidFinishLaunching);
4046 [NSApp setServicesProvider: NSApp];
4047 ns_send_appdefined (-2);
4051 - (void) terminate: (id)sender
4054 if (ns_shutdown_properly)
4055 [super terminate: sender];
4058 /* Fkill_emacs (Qnil); */
4059 ns_shutdown_properly = YES;
4060 Feval (Fcons (intern ("save-buffers-kill-emacs"), Qnil));
4066 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4068 if (ns_shutdown_properly)
4069 return NSTerminateNow;
4071 Lisp_Object contents = list3 (build_string ("Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?"),
4072 Fcons (build_string ("Cancel"), Qnil),
4073 Fcons (build_string ("Save and Exit"), Qt));
4074 Lisp_Object res = ns_popup_dialog (Qt, contents, Qnil);
4075 fprintf (stderr, "res = %d\n", EQ (res, Qt)); /* FIXME */
4078 Feval (Fcons (intern ("save-buffers-kill-emacs"), Qnil));
4079 return NSTerminateNow;
4081 return NSTerminateCancel;
4085 /* Notification from the Workspace to open a file */
4086 - (BOOL)application: sender openFile: (NSString *)file
4088 [ns_pending_files addObject: file];
4093 /* Open a file as a temporary file */
4094 - (BOOL)application: sender openTempFile: (NSString *)file
4096 [ns_pending_files addObject: file];
4101 /* Notification from the Workspace to open a file noninteractively (?) */
4102 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4104 [ns_pending_files addObject: file];
4109 /* Notification from the Workspace to open multiple files */
4110 - (void)application: sender openFiles: (NSArray *)fileList
4112 NSEnumerator *files = [fileList objectEnumerator];
4114 while ((file = [files nextObject]) != nil)
4115 [ns_pending_files addObject: file];
4117 /* TODO: when GNUstep implements this (and we require that version of
4118 GNUstep), remove. */
4119 #ifndef NS_IMPL_GNUSTEP
4120 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4121 #endif /* !NS_IMPL_GNUSTEP */
4126 /* Handle dock menu requests. */
4127 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4133 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4134 - (void)applicationDidBecomeActive: (NSNotification *)notification
4137 - (void)applicationDidResignActive: (NSNotification *)notification
4139 ns_send_appdefined (-1);
4144 /* ==========================================================================
4146 EmacsApp aux handlers for managing event loop
4148 ========================================================================== */
4151 - (void)timeout_handler: (NSTimer *)timedEntry
4152 /* --------------------------------------------------------------------------
4153 The timeout specified to ns_select has passed.
4154 -------------------------------------------------------------------------- */
4156 /*NSTRACE (timeout_handler); */
4157 ns_send_appdefined (-2);
4160 extern void update_window_cursor (struct window *w, int on);
4162 - (void)fd_handler: (NSTimer *) fdEntry
4163 /* --------------------------------------------------------------------------
4164 Check data waiting on file descriptors and terminate if so
4165 -------------------------------------------------------------------------- */
4168 /* NSTRACE (fd_handler); */
4170 if (select_nfds == 0)
4173 memcpy (&t_readfds, &select_readfds, sizeof (fd_set));
4175 select_timeout.tv_sec = select_timeout.tv_usec = 0;
4176 result = select (select_nfds, &t_readfds, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
4180 memcpy (&select_readfds, &t_readfds, sizeof (fd_set));
4181 ns_send_appdefined (result);
4187 /* ==========================================================================
4191 ========================================================================== */
4193 /* called from system: queue for next pass through event loop */
4194 - (void)requestService: (NSPasteboard *)pboard
4195 userData: (NSString *)userData
4196 error: (NSString **)error
4198 [ns_pending_service_names addObject: userData];
4199 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
4200 SDATA (ns_string_from_pasteboard (pboard))]];
4204 /* called from ns_read_socket to clear queue */
4205 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
4207 struct frame *emacsframe = SELECTED_FRAME ();
4208 NSEvent *theEvent = [NSApp currentEvent];
4213 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4214 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
4215 ns_input_spi_name = build_string ([name UTF8String]);
4216 ns_input_spi_arg = build_string ([arg UTF8String]);
4217 emacs_event->modifiers = EV_MODIFIERS (theEvent);
4218 EV_TRAILER (theEvent);
4228 /* ==========================================================================
4230 EmacsView implementation
4232 ========================================================================== */
4235 @implementation EmacsView
4237 /* needed to inform when window closed from LISP */
4238 - (void) setWindowClosing: (BOOL)closing
4240 windowClosing = closing;
4246 NSTRACE (EmacsView_dealloc);
4252 /* called on font panel selection */
4253 - (void)changeFont: (id)sender
4255 NSEvent *e =[[self window] currentEvent];
4256 struct face *face =FRAME_DEFAULT_FACE (emacsframe);
4260 NSTRACE (changeFont);
4264 if (newFont = [sender convertFont:
4265 ((struct nsfont_info *)face->font)->nsfont])
4267 SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
4269 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4270 emacs_event->modifiers = 0;
4271 emacs_event->code = KEY_NS_CHANGE_FONT;
4273 size = [newFont pointSize];
4274 ns_input_fontsize = make_number (lrint (size));
4275 ns_input_font = build_string ([[newFont familyName] UTF8String]);
4281 - (BOOL)acceptsFirstResponder
4283 NSTRACE (acceptsFirstResponder);
4288 - (void)resetCursorRects
4290 NSRect visible = [self visibleRect];
4291 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
4292 NSTRACE (resetCursorRects);
4294 if (currentCursor == nil)
4295 currentCursor = [NSCursor arrowCursor];
4297 if (!NSIsEmptyRect (visible))
4298 [self addCursorRect: visible cursor: currentCursor];
4299 [currentCursor setOnMouseEntered: YES];
4303 /*****************************************************************************/
4304 /* Keyboard handling. */
4307 - (void)keyDown: (NSEvent *)theEvent
4309 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4311 unsigned fnKeysym = 0;
4313 static NSMutableArray *nsEvArray;
4314 static BOOL firstTime = YES;
4318 /* Rhapsody and OS X give up and down events for the arrow keys */
4319 if ([theEvent type] != NSKeyDown)
4325 if (![[self window] isKeyWindow])
4327 /* XXX: Using NO_SOCK_SIGIO like Carbon causes a condition in which,
4328 when Emacs display updates a different frame from the current one,
4329 and temporarily selects it, then processes some interrupt-driven
4330 input (dispnew.c:3878), OS will send the event to the correct NSWindow,
4331 but for some reason that window has its first responder set to the
4332 NSView most recently updated (I guess), which is not the correct one.
4333 UPDATE: After multi-TTY merge this happens even w/o NO_SOCK_SIGIO */
4334 if ([[theEvent window] isKindOfClass: [EmacsWindow class]])
4335 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
4339 if (nsEvArray == nil)
4340 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
4342 [NSCursor setHiddenUntilMouseMoves: YES];
4344 if (dpyinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
4346 clear_mouse_face (dpyinfo);
4347 dpyinfo->mouse_face_hidden = 1;
4350 if (!processingCompose)
4352 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
4353 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
4354 /* (Carbon way: [theEvent keyCode]) */
4356 /* is it a "function key"? */
4357 fnKeysym = ns_convert_key (code);
4360 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
4361 because Emacs treats Delete and KP-Delete same (in simple.el). */
4362 if (fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
4363 code = 0xFF08; /* backspace */
4368 /* are there modifiers? */
4369 emacs_event->modifiers = 0;
4370 flags = [theEvent modifierFlags];
4372 if (flags & NSHelpKeyMask)
4373 emacs_event->modifiers |= hyper_modifier;
4375 if (flags & NSShiftKeyMask)
4376 emacs_event->modifiers |= shift_modifier;
4378 if (flags & NSCommandKeyMask)
4380 emacs_event->modifiers |= parse_solitary_modifier (ns_command_modifier);
4381 /* if super (default), take input manager's word so things like
4382 dvorak / qwerty layout work */
4383 if (EQ (ns_command_modifier, Qsuper)
4385 && [[theEvent characters] length] != 0)
4387 /* XXX: the code we get will be unshifted, so if we have
4388 a shift modifier, must convert ourselves */
4389 if (!(flags & NSShiftKeyMask))
4390 code = [[theEvent characters] characterAtIndex: 0];
4392 /* this is ugly and also requires linking w/Carbon framework
4393 (for LMGetKbdType) so for now leave this rare (?) case
4394 undealt with.. in future look into CGEvent methods */
4397 long smv = GetScriptManagerVariable (smKeyScript);
4398 Handle uchrHandle = GetResource
4399 ('uchr', GetScriptVariable (smv, smScriptKeys));
4401 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
4402 [[theEvent characters] characterAtIndex: 0],
4403 kUCKeyActionDisplay,
4404 (flags & ~NSCommandKeyMask) >> 8,
4405 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
4406 &dummy, 1, &dummy, &code);
4413 if (flags & NSControlKeyMask)
4414 emacs_event->modifiers |= parse_solitary_modifier (ns_control_modifier);
4416 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
4417 emacs_event->modifiers |= parse_solitary_modifier (ns_function_modifier);
4419 if (flags & NSAlternateKeyMask) /* default = meta */
4421 if (EQ (ns_alternate_modifier, Qnone) && !fnKeysym)
4422 { /* accept pre-interp alt comb */
4423 if ([[theEvent characters] length] > 0)
4424 code = [[theEvent characters] characterAtIndex: 0];
4425 /*HACK: clear lone shift modifier to stop next if from firing */
4426 if (emacs_event->modifiers == shift_modifier)
4427 emacs_event->modifiers = 0;
4430 emacs_event->modifiers |= parse_solitary_modifier (ns_alternate_modifier);
4433 /*fprintf (stderr,"code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",code,fnKeysym,flags,emacs_event->modifiers); */
4435 /* if it was a function key or had modifiers, pass it directly to emacs */
4436 if (fnKeysym || (emacs_event->modifiers
4437 && [[theEvent charactersIgnoringModifiers] length] > 0))
4438 /*[[theEvent characters] length] */
4440 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4442 code |= (1<<28)|(3<<16);
4443 else if (code == 0x7f)
4444 code |= (1<<28)|(3<<16);
4446 emacs_event->kind = code > 0xFF
4447 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4449 emacs_event->code = code;
4450 EV_TRAILER (theEvent);
4455 /* if we get here we should send the key for input manager processing */
4456 if (firstTime && [[NSInputManager currentInputManager]
4457 wantsToDelayTextChangeNotifications] == NO)
4459 "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
4462 if (NS_KEYLOG && !processingCompose)
4463 fprintf (stderr, "Begin compose sequence.\n");
4465 processingCompose = YES;
4466 [nsEvArray addObject: theEvent];
4467 [self interpretKeyEvents: nsEvArray];
4468 [nsEvArray removeObject: theEvent];
4472 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
4475 /* <NSTextInput>: called through when done composing */
4476 - (void)insertText: (id)aString
4479 int len = [(NSString *)aString length];
4482 if (NS_KEYLOG) NSLog (@"insertText '%@'\tlen = %d", aString, len);
4483 processingCompose = NO;
4488 /* first, clear any working text */
4489 if (workingText != nil)
4490 [self deleteWorkingText];
4492 /* now insert the string as keystrokes */
4493 for (i =0; i<len; i++)
4495 code = [aString characterAtIndex: i];
4496 /* TODO: still need this? */
4498 code = '~'; /* 0x7E */
4499 emacs_event->modifiers = 0;
4501 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4502 emacs_event->code = code;
4503 EV_TRAILER ((id)nil);
4508 /* <NSTextInput>: inserts display of composing characters */
4509 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
4511 NSString *str = [aString respondsToSelector: @selector (string)] ?
4512 [aString string] : aString;
4514 NSLog (@"setMarkedText '%@' len =%d range %d from %d", str, [str length],
4515 selRange.length, selRange.location);
4517 if (workingText != nil)
4518 [self deleteWorkingText];
4519 if ([str length] == 0)
4525 processingCompose = YES;
4526 workingText = [str copy];
4527 ns_working_text = build_string ([workingText UTF8String]);
4529 /* if in "echo area", not true minibuffer, can't show chars in interactive
4530 mode, so call using eval; otherwise we send a key event, which was the
4531 original way this was done */
4532 if (!EQ (Feval (Fcons (intern ("ns-in-echo-area"), Qnil)), Qnil))
4534 Feval (Fcons (intern ("ns-echo-working-text"), Qnil));
4535 ns_send_appdefined (-1);
4539 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4540 emacs_event->code = KEY_NS_INSERT_WORKING_TEXT;
4541 EV_TRAILER ((id)nil);
4546 /* delete display of composing characters [not in <NSTextInput>] */
4547 - (void)deleteWorkingText
4549 if (workingText == nil)
4552 fprintf (stderr, "deleteWorkingText len =%d\n", [workingText length]);
4553 [workingText release];
4555 processingCompose = NO;
4560 if (!EQ (Feval (Fcons (intern ("ns-in-echo-area"), Qnil)), Qnil))
4562 Feval (Fcons (intern ("ns-unecho-working-text"), Qnil));
4563 ns_send_appdefined (-1);
4567 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4568 emacs_event->code = KEY_NS_DELETE_WORKING_TEXT;
4569 EV_TRAILER ((id)nil);
4574 - (BOOL)hasMarkedText
4576 return workingText != nil;
4579 - (NSRange)markedRange
4581 NSRange rng = workingText != nil
4582 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
4583 if (NS_KEYLOG) NSLog (@"markedRange request");
4589 if (NS_KEYLOG) NSLog (@"unmark (accept) text");
4590 [self deleteWorkingText];
4591 processingCompose = NO;
4594 /* used to position char selection windows, etc. */
4595 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
4599 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
4600 if (NS_KEYLOG) NSLog (@"firstRectForCharRange request");
4602 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
4603 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
4604 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
4605 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
4606 +FRAME_LINE_HEIGHT (emacsframe));
4608 pt = [self convertPoint: pt toView: nil];
4609 pt = [[self window] convertBaseToScreen: pt];
4614 - (NSInteger)conversationIdentifier
4616 return (NSInteger)self;
4619 /* TODO: below here not yet implemented correctly, but may not be needed */
4621 - (void)doCommandBySelector: (SEL)aSelector
4623 if (NS_KEYLOG) NSLog (@"Do command by selector: %@",
4624 NSStringFromSelector (aSelector));
4626 if (aSelector == @selector (deleteBackward:))
4628 /* happens when user backspaces over an ongoing composition:
4629 throw a 'delete' into the event queue */
4632 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4633 emacs_event->code = 0xFF08;
4634 EV_TRAILER ((id)nil);
4638 - (NSArray *)validAttributesForMarkedText
4640 static NSArray *arr = nil;
4641 if (arr == nil) arr = [NSArray new];
4642 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
4646 - (NSRange)selectedRange
4648 if (NS_KEYLOG) NSLog (@"selectedRange request");
4649 return NSMakeRange (NSNotFound, 0);
4652 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
4654 if (NS_KEYLOG) NSLog (@"characterIndexForPoint request");
4658 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
4660 static NSAttributedString *str = nil;
4661 if (str == nil) str = [NSAttributedString new];
4662 if (NS_KEYLOG) NSLog (@"attributedSubstringFromRange request");
4666 /* End <NSTextInput> impl. */
4667 /*****************************************************************************/
4670 /* This is what happens when the user presses a mouse button. */
4671 - (void)mouseDown: (NSEvent *)theEvent
4673 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
4676 NSTRACE (mouseDown);
4678 [self deleteWorkingText];
4683 last_mouse_frame = emacsframe;
4684 /* appears to be needed to prevent spurious movement events generated on
4686 last_mouse_frame->mouse_moved = 0;
4688 if ([theEvent type] == NSScrollWheel)
4690 float delta = [theEvent deltaY];
4691 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
4694 emacs_event->kind = WHEEL_EVENT;
4695 emacs_event->code = 0;
4696 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
4697 ((delta > 0) ? up_modifier : down_modifier);
4701 emacs_event->kind = MOUSE_CLICK_EVENT;
4702 emacs_event->code = EV_BUTTON (theEvent);
4703 emacs_event->modifiers = EV_MODIFIERS (theEvent)
4704 | EV_UDMODIFIERS (theEvent);
4706 XSETINT (emacs_event->x, lrint (p.x));
4707 XSETINT (emacs_event->y, lrint (p.y));
4708 EV_TRAILER (theEvent);
4712 - (void)mouseUp: (NSEvent *)theEvent
4715 [self mouseDown: theEvent];
4719 - (void)rightMouseDown: (NSEvent *)theEvent
4721 NSTRACE (rightMouseDown);
4722 [self mouseDown: theEvent];
4726 - (void)rightMouseUp: (NSEvent *)theEvent
4728 NSTRACE (rightMouseUp);
4729 [self mouseDown: theEvent];
4733 - (void) scrollWheel: (NSEvent *)theEvent
4735 NSTRACE (scrollWheel);
4736 [self mouseDown: theEvent];
4740 /* Tell emacs the mouse has moved. */
4741 - (void)mouseMoved: (NSEvent *)e
4743 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4746 // NSTRACE (mouseMoved);
4748 last_mouse_movement_time = EV_TIMESTAMP (e);
4749 last_mouse_motion_position
4750 = [self convertPoint: [e locationInWindow] fromView: nil];
4752 /* update any mouse face */
4753 if (dpyinfo->mouse_face_hidden)
4755 dpyinfo->mouse_face_hidden = 0;
4756 clear_mouse_face (dpyinfo);
4759 /* tooltip handling */
4760 previous_help_echo_string = help_echo_string;
4761 help_echo_string = Qnil;
4763 if (!note_mouse_movement (emacsframe, last_mouse_motion_position.x,
4764 last_mouse_motion_position.y))
4765 help_echo_string = previous_help_echo_string;
4767 XSETFRAME (frame, emacsframe);
4768 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
4770 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
4771 (note_mouse_highlight), which is called through the
4772 note_mouse_movement () call above */
4773 gen_help_event (help_echo_string, frame, help_echo_window,
4774 help_echo_object, help_echo_pos);
4778 help_echo_string = Qnil;
4779 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
4782 if (emacsframe->mouse_moved && send_appdefined)
4783 ns_send_appdefined (-1);
4787 - (void)mouseDragged: (NSEvent *)e
4789 NSTRACE (mouseDragged);
4790 [self mouseMoved: e];
4794 - (void)rightMouseDragged: (NSEvent *)e
4796 NSTRACE (rightMouseDragged);
4797 [self mouseMoved: e];
4801 - (BOOL)windowShouldClose: (id)sender
4803 NSEvent *e =[[self window] currentEvent];
4805 NSTRACE (windowShouldClose);
4806 windowClosing = YES;
4809 emacs_event->kind = DELETE_WINDOW_EVENT;
4810 emacs_event->modifiers = 0;
4811 emacs_event->code = 0;
4813 /* Don't close this window, let this be done from lisp code. */
4818 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
4819 /* normalize frame to gridded text size */
4821 NSTRACE (windowWillResize);
4822 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
4824 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe,
4825 #ifdef NS_IMPL_GNUSTEP
4826 frameSize.width + 3);
4830 if (cols < MINWIDTH)
4832 frameSize.width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (emacsframe, cols);
4834 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, frameSize.height
4835 #ifdef NS_IMPL_GNUSTEP
4836 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe) + 3
4837 - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
4839 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
4840 - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
4842 if (rows < MINHEIGHT)
4844 frameSize.height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows)
4845 + FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
4846 + FRAME_NS_TOOLBAR_HEIGHT (emacsframe);
4847 #ifdef NS_IMPL_COCOA
4849 /* this sets window title to have size in it; the wm does this under GS */
4850 NSRect r = [[self window] frame];
4851 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
4862 NSWindow *window = [self window];
4865 const char *t = [[[self window] title] UTF8String];
4866 char *pos = strstr (t, " — ");
4869 old_title = (char *) xmalloc (strlen (t) + 1);
4870 strcpy (old_title, t);
4872 size_title = xmalloc (strlen (old_title) + 40);
4873 sprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
4874 [window setTitle: [NSString stringWithUTF8String: size_title]];
4879 #endif /* NS_IMPL_COCOA */
4880 /*fprintf (stderr," ...size became %.0f x %.0f (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
4886 - (void)windowDidResize: (NSNotification *)notification
4888 NSWindow *theWindow = [notification object];
4890 #ifdef NS_IMPL_GNUSTEP
4891 /* in GNUstep, at least currently, it's possible to get a didResize
4892 without getting a willResize.. therefore we need to act as if we got
4893 the willResize now */
4894 NSSize sz = [theWindow frame].size;
4895 sz = [self windowWillResize: theWindow toSize: sz];
4896 #endif /* NS_IMPL_GNUSTEP */
4898 NSTRACE (windowDidResize);
4899 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
4901 #ifdef NS_IMPL_COCOA
4907 #endif /* NS_IMPL_COCOA */
4909 if (cols > 0 && rows > 0)
4910 x_set_window_size (emacsframe, 0, cols, rows);
4912 ns_send_appdefined (-1);
4914 /* The following line causes a crash on GNUstep. Adrian Robert
4915 says he doesn't remember why he added this line, but removing it
4916 doesn't seem to cause problems on OSX, either. */
4923 - (void)windowDidBecomeKey: (NSNotification *)notification
4924 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
4926 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4927 struct frame *old_focus = dpyinfo->x_focus_frame;
4929 NSTRACE (windowDidBecomeKey);
4931 if (emacsframe != old_focus)
4932 dpyinfo->x_focus_frame = emacsframe;
4934 ns_frame_rehighlight (emacsframe);
4938 emacs_event->kind = FOCUS_IN_EVENT;
4939 EV_TRAILER ((id)nil);
4944 - (void)windowDidResignKey: (NSNotification *)notification
4945 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
4947 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4948 NSTRACE (windowDidResignKey);
4950 if (dpyinfo->x_focus_frame == emacsframe)
4951 dpyinfo->x_focus_frame = 0;
4953 ns_frame_rehighlight (emacsframe);
4955 /* FIXME: for some reason needed on second and subsequent clicks away
4956 from sole-frame Emacs to get hollow box to show */
4957 if (!windowClosing && [[self window] isVisible] == YES)
4958 x_update_cursor (emacsframe, 1);
4962 [self deleteWorkingText];
4963 emacs_event->kind = FOCUS_IN_EVENT;
4964 EV_TRAILER ((id)nil);
4969 - (void)windowWillMiniaturize: sender
4971 NSTRACE (windowWillMiniaturize);
4987 - initFrameFromEmacs: (struct frame *)f
4992 NSButton *toggleButton;
4993 int vbextra = NS_SCROLL_BAR_WIDTH (f);
4998 NSTRACE (initFrameFromEmacs);
5001 processingCompose = NO;
5002 scrollbarsNeedingUpdate = 0;
5004 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
5006 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
5007 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
5008 [self initWithFrame: r];
5010 FRAME_NS_VIEW (f) = self;
5014 win = [[EmacsWindow alloc]
5015 initWithContentRect: r
5016 styleMask: (NSResizableWindowMask |
5017 NSMiniaturizableWindowMask |
5018 NSClosableWindowMask)
5019 backing: NSBackingStoreBuffered
5023 f->border_width = wr.size.width - r.size.width;
5024 FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
5026 [win setAcceptsMouseMovedEvents: YES];
5027 [win setDelegate: self];
5028 [win useOptimizedDrawing: YES];
5030 sz.width = FRAME_COLUMN_WIDTH (f);
5031 sz.height = FRAME_LINE_HEIGHT (f);
5032 [win setResizeIncrements: sz];
5034 [[win contentView] addSubview: self];
5037 [self registerForDraggedTypes: ns_drag_types];
5040 name = [NSString stringWithUTF8String:
5041 NILP (tem) ? (unsigned char *)"Emacs" : SDATA (tem)];
5042 [win setTitle: name];
5044 /* toolbar support */
5045 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
5046 [NSString stringWithFormat: @"Emacs Frame %d",
5048 [win setToolbar: toolbar];
5049 [toolbar setVisible: NO];
5050 #ifdef NS_IMPL_COCOA
5051 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
5052 [toggleButton setTarget: self];
5053 [toggleButton setAction: @selector (toggleToolbar: )];
5055 FRAME_NS_TOOLBAR_HEIGHT (f) = 0;
5059 [win setMiniwindowTitle:
5060 [NSString stringWithUTF8String: SDATA (tem)]];
5063 NSScreen *screen = [win screen];
5066 [win setFrameTopLeftPoint: NSMakePoint
5067 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
5068 IN_BOUND (-SCREENMAX,
5069 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
5072 [win makeFirstResponder: self];
5074 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5075 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
5076 [win setBackgroundColor: col];
5077 if ([col alphaComponent] != 1.0)
5078 [win setOpaque: NO];
5080 [self allocateGState];
5087 - (void)windowDidMove: sender
5089 NSWindow *win = [self window];
5090 NSRect r = [win frame];
5091 NSScreen *screen = [win screen];
5092 NSRect sr = [screen frame];
5094 NSTRACE (windowDidMove);
5096 if (!emacsframe->output_data.ns)
5100 emacsframe->left_pos = r.origin.x; /* - sr.origin.x; */
5101 emacsframe->top_pos = sr.size.height -
5102 (r.origin.y + r.size.height); /* + sr.origin.y; */
5106 #ifdef NS_IMPL_COCOA
5107 /* if we don't do this manually, the window will resize but not move */
5108 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
5110 [[self window] setFrame: newFrame display: NO];
5115 /* Implement this to control size of frame on zoom.
5116 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
5117 defaultFrame:(NSRect)defaultFrame; */
5120 - (void)windowDidDeminiaturize: sender
5122 NSTRACE (windowDidDeminiaturize);
5123 if (!emacsframe->output_data.ns)
5125 emacsframe->async_visible = 1;
5126 emacsframe->async_iconified = 0;
5127 windows_or_buffers_changed++;
5131 emacs_event->kind = ICONIFY_EVENT;
5132 EV_TRAILER ((id)nil);
5137 - (void)windowDidExpose: sender
5139 NSTRACE (windowDidExpose);
5140 if (!emacsframe->output_data.ns)
5142 emacsframe->async_visible = 1;
5143 SET_FRAME_GARBAGED (emacsframe);
5145 if (send_appdefined)
5146 ns_send_appdefined (-1);
5150 - (void)windowDidMiniaturize: sender
5152 NSTRACE (windowDidMiniaturize);
5153 if (!emacsframe->output_data.ns)
5156 emacsframe->async_iconified = 1;
5160 emacs_event->kind = ICONIFY_EVENT;
5161 EV_TRAILER ((id)nil);
5166 - (void)mouseEntered: (NSEvent *)theEvent
5168 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5169 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5170 NSTRACE (mouseEntered);
5172 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5176 - (void)mouseExited: (NSEvent *)theEvent
5178 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5180 struct ns_display_info *dpyinfo
5181 = emacsframe ? FRAME_NS_DISPLAY_INFO (emacsframe) : NULL;
5183 NSTRACE (mouseExited);
5185 if (dpyinfo || !emacsframe)
5188 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5190 if (emacsframe == dpyinfo->mouse_face_mouse_frame)
5192 clear_mouse_face (dpyinfo);
5193 dpyinfo->mouse_face_mouse_frame = 0;
5201 if (context_menu_value == -1)
5202 context_menu_value = [sender tag];
5204 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
5205 emacsframe->menu_bar_vector,
5206 (void *)[sender tag]);
5207 ns_send_appdefined (-1);
5212 - (EmacsToolbar *)toolbar
5218 /* this gets called on toolbar button click */
5219 - toolbarClicked: (id)item
5222 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
5224 NSTRACE (toolbarClicked);
5229 /* send first event (for some reason two needed) */
5230 theEvent =[[self window] currentEvent];
5231 emacs_event->kind = TOOL_BAR_EVENT;
5232 XSETFRAME (emacs_event->arg, emacsframe);
5233 EV_TRAILER (theEvent);
5235 emacs_event->kind = TOOL_BAR_EVENT;
5236 /* XSETINT (emacs_event->code, 0); */
5237 emacs_event->arg = AREF (emacsframe->tool_bar_items,
5238 idx + TOOL_BAR_ITEM_KEY);
5239 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5240 EV_TRAILER (theEvent);
5245 - toggleToolbar: (id)sender
5247 Lisp_Object lispFrame;
5248 XSETFRAME (lispFrame, emacsframe);
5249 Feval (Fcons (intern ("ns-toggle-toolbar"), Fcons (lispFrame, Qnil)));
5250 SET_FRAME_GARBAGED (emacsframe);
5251 ns_send_appdefined (-1);
5255 - (void)drawRect: (NSRect)rect
5257 int x = NSMinX (rect), y = NSMinY (rect);
5258 int width = NSWidth (rect), height = NSHeight (rect);
5262 if (!emacsframe || !emacsframe->output_data.ns)
5266 ns_clear_frame_area (emacsframe, x, y, width, height);
5267 expose_frame (emacsframe, x, y, width, height);
5269 emacsframe->async_visible = 1;
5270 emacsframe->async_iconified = 0;
5272 /* SET_FRAME_GARBAGED (emacsframe);
5273 ns_send_appdefined (-1); */
5277 /* NSDraggingDestination protocol methods. Actually this is not really a
5278 protocol, but a category of Object. O well... */
5280 -(unsigned int) draggingEntered: (id <NSDraggingInfo>) sender
5282 NSTRACE (draggingEntered);
5283 return NSDragOperationGeneric;
5287 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
5293 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
5298 NSEvent *theEvent = [[self window] currentEvent];
5301 NSTRACE (performDragOperation);
5306 position = [self convertPoint: [sender draggingLocation] fromView: nil];
5307 x = lrint (position.x); y = lrint (position.y);
5309 pb = [sender draggingPasteboard];
5310 type = [pb availableTypeFromArray: ns_drag_types];
5315 else if ([type isEqualToString: NSFilenamesPboardType])
5318 NSEnumerator *fenum;
5321 if (!(files = [pb propertyListForType: type]))
5324 fenum = [files objectEnumerator];
5325 while ( (file = [fenum nextObject]) )
5327 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5328 emacs_event->code = KEY_NS_DRAG_FILE;
5329 XSETINT (emacs_event->x, x);
5330 XSETINT (emacs_event->y, y);
5331 ns_input_file = append2 (ns_input_file,
5332 build_string ([file UTF8String]));
5333 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5334 EV_TRAILER (theEvent);
5338 else if ([type isEqualToString: NSURLPboardType])
5343 if (!(fileURL = [NSURL URLFromPasteboard: pb]) ||
5344 [fileURL isFileURL] == NO)
5347 file = [fileURL path];
5348 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5349 emacs_event->code = KEY_NS_DRAG_FILE;
5350 XSETINT (emacs_event->x, x);
5351 XSETINT (emacs_event->y, y);
5352 ns_input_file = append2 (ns_input_file, build_string ([file UTF8String]));
5353 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5354 EV_TRAILER (theEvent);
5357 else if ([type isEqualToString: NSStringPboardType]
5358 || [type isEqualToString: NSTabularTextPboardType])
5362 if (! (data = [pb stringForType: type]))
5365 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5366 emacs_event->code = KEY_NS_DRAG_TEXT;
5367 XSETINT (emacs_event->x, x);
5368 XSETINT (emacs_event->y, y);
5369 ns_input_text = build_string ([data UTF8String]);
5370 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5371 EV_TRAILER (theEvent);
5374 else if ([type isEqualToString: NSColorPboardType])
5376 NSColor *c = [NSColor colorFromPasteboard: pb];
5377 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5378 emacs_event->code = KEY_NS_DRAG_COLOR;
5379 XSETINT (emacs_event->x, x);
5380 XSETINT (emacs_event->y, y);
5381 ns_input_color = ns_color_to_lisp (c);
5382 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5383 EV_TRAILER (theEvent);
5386 else if ([type isEqualToString: NSFontPboardType])
5388 /* impl based on GNUstep NSTextView.m */
5389 NSData *data = [pb dataForType: NSFontPboardType];
5390 NSDictionary *dict = [NSUnarchiver unarchiveObjectWithData: data];
5391 NSFont *font = [dict objectForKey: NSFontAttributeName];
5397 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5398 emacs_event->code = KEY_NS_CHANGE_FONT;
5399 XSETINT (emacs_event->x, x);
5400 XSETINT (emacs_event->y, y);
5401 ns_input_font = build_string ([[font fontName] UTF8String]);
5402 snprintf (fontSize, 10, "%f", [font pointSize]);
5403 ns_input_fontsize = build_string (fontSize);
5404 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5405 EV_TRAILER (theEvent);
5410 error ("Invalid data type in dragging pasteboard.");
5416 - validRequestorForSendType: (NSString *)typeSent
5417 returnType: (NSString *)typeReturned
5419 NSTRACE (validRequestorForSendType);
5420 if ([ns_send_types indexOfObjectIdenticalTo: typeSent] != NSNotFound &&
5421 [ns_return_types indexOfObjectIdenticalTo: typeSent] != NSNotFound)
5424 return [super validRequestorForSendType: typeSent
5425 returnType: typeReturned];
5429 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
5430 (gives a miniaturized version of the window); currently we use the latter for
5431 frames whose active buffer doesn't correspond to any file
5432 (e.g., '*scratch*') */
5433 - setMiniwindowImage: (BOOL) setMini
5435 id image = [[self window] miniwindowImage];
5436 NSTRACE (setMiniwindowImage);
5438 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
5439 about "AppleDockIconEnabled" notwithstanding, however the set message
5440 below has its effect nonetheless. */
5441 if (image != emacsframe->output_data.ns->miniimage)
5443 if (image && [image isKindOfClass: [EmacsImage class]])
5445 [[self window] setMiniwindowImage:
5446 setMini ? emacsframe->output_data.ns->miniimage : nil];
5453 - (void) setRows: (int) r andColumns: (int) c
5459 @end /* EmacsView */
5463 /* ==========================================================================
5465 EmacsWindow implementation
5467 ========================================================================== */
5469 @implementation EmacsWindow
5471 /* called only on resize clicks by special case in EmacsApp-sendEvent */
5472 - (void)mouseDown: (NSEvent *)theEvent
5476 NSSize size = [[theEvent window] frame].size;
5477 grabOffset = [theEvent locationInWindow];
5478 grabOffset.x = size.width - grabOffset.x;
5481 [super mouseDown: theEvent];
5486 - (void)mouseUp: (NSEvent *)theEvent
5490 struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
5492 ns_set_name_as_filename (f);
5494 ns_send_appdefined (-1);
5497 [super mouseUp: theEvent];
5501 /* send resize events */
5502 - (void)mouseDragged: (NSEvent *)theEvent
5506 NSPoint p = [theEvent locationInWindow];
5507 NSSize size, vettedSize, origSize = [self frame].size;
5509 size.width = p.x + grabOffset.x;
5510 size.height = origSize.height - p.y + grabOffset.y;
5512 if (size.width == origSize.width && size.height == origSize.height)
5515 vettedSize = [[self delegate] windowWillResize: self toSize: size];
5516 if (vettedSize.width != size.width || vettedSize.height != size.height)
5518 [[NSNotificationCenter defaultCenter]
5519 postNotificationName: NSWindowDidResizeNotification
5524 [super mouseDragged: theEvent];
5527 @end /* EmacsWindow */
5530 /* ==========================================================================
5532 EmacsScroller implementation
5534 ========================================================================== */
5537 @implementation EmacsScroller
5539 /* for repeat button push */
5540 #define SCROLL_BAR_FIRST_DELAY 0.5
5541 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
5543 + (float) scrollerWidth
5545 /* TODO: if we want to allow variable widths, this is the place to do it,
5546 however neither GNUstep nor Cocoa support it very well */
5547 return [NSScroller scrollerWidth];
5551 - initFrame: (NSRect )r window: (Lisp_Object)nwin
5553 NSTRACE (EmacsScroller_initFrame);
5555 r.size.width = [EmacsScroller scrollerWidth];
5556 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
5557 [self setContinuous: YES];
5558 [self setEnabled: YES];
5560 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
5561 locked against the right, top and bottom edges. */
5562 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
5566 pixel_height = NSHeight (r);
5567 min_portion = 20 / pixel_height;
5569 frame = XFRAME (XWINDOW (win)->frame);
5570 if (FRAME_LIVE_P (frame))
5573 EmacsView *view = FRAME_NS_VIEW (frame);
5574 NSView *sview = [[view window] contentView];
5575 NSArray *subs = [sview subviews];
5577 /* disable optimization stopping redraw of other scrollbars */
5578 view->scrollbarsNeedingUpdate = 0;
5579 for (i =[subs count]-1; i >= 0; i--)
5580 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
5581 view->scrollbarsNeedingUpdate++;
5582 [sview addSubview: self];
5585 /* [self setFrame: r]; */
5591 - (void)setFrame: (NSRect)newRect
5593 NSTRACE (EmacsScroller_setFrame);
5595 pixel_height = NSHeight (newRect);
5596 min_portion = 20 / pixel_height;
5597 [super setFrame: newRect];
5599 /* UNBLOCK_INPUT; */
5605 NSTRACE (EmacsScroller_dealloc);
5607 XWINDOW (win)->vertical_scroll_bar = Qnil;
5634 /* ensure other scrollbar updates after deletion */
5635 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
5637 view->scrollbarsNeedingUpdate++;
5638 [self removeFromSuperview];
5646 - (void)resetCursorRects
5648 NSRect visible = [self visibleRect];
5649 NSTRACE (resetCursorRects);
5651 if (!NSIsEmptyRect (visible))
5652 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
5653 [[NSCursor arrowCursor] setOnMouseEntered: YES];
5657 - (int) checkSamePosition: (int) position portion: (int) portion
5660 return em_position ==position && em_portion ==portion && em_whole ==whole
5661 && portion != whole; /* needed for resize empty buf */
5665 - setPosition: (int)position portion: (int)portion whole: (int)whole
5667 NSTRACE (setPosition);
5669 em_position = position;
5670 em_portion = portion;
5673 if (portion >= whole)
5674 [self setFloatValue: 0.0 knobProportion: 1.0];
5678 portion = max ((float)whole*min_portion/pixel_height, portion);
5679 pos = (float)position / (whole - portion);
5680 por = (float)portion/whole;
5681 [self setFloatValue: pos knobProportion: por];
5683 #ifdef NS_IMPL_GNUSTEP
5689 /* FIXME: unused at moment (see ns_mouse_position) at the moment because
5690 drag events will go directly to the EmacsScroller. Leaving in for now. */
5691 -(void)getMouseMotionPart: (int *)part window: (Lisp_Object *)window
5692 x: (Lisp_Object *)x y: ( Lisp_Object *)y
5694 *part = last_hit_part;
5696 XSETINT (*y, pixel_height);
5697 if ([self floatValue] > 0.999)
5698 XSETINT (*x, pixel_height);
5700 XSETINT (*x, pixel_height * [self floatValue]);
5704 /* set up emacs_event */
5705 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
5710 emacs_event->part = last_hit_part;
5711 emacs_event->code = 0;
5712 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
5713 emacs_event->frame_or_window = win;
5714 emacs_event->timestamp = EV_TIMESTAMP (e);
5715 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
5716 emacs_event->arg = Qnil;
5717 XSETINT (emacs_event->x, loc * pixel_height);
5718 XSETINT (emacs_event->y, pixel_height-20);
5720 n_emacs_events_pending++;
5721 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
5722 EVENT_INIT (*emacs_event);
5723 ns_send_appdefined (-1);
5727 /* called manually thru timer to implement repeated button action w/hold-down */
5728 - repeatScroll: (NSTimer *)scrollEntry
5730 NSEvent *e = [[self window] currentEvent];
5731 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
5732 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
5734 /* clear timer if need be */
5735 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
5737 [scroll_repeat_entry invalidate];
5738 [scroll_repeat_entry release];
5739 scroll_repeat_entry = nil;
5745 = [[NSTimer scheduledTimerWithTimeInterval:
5746 SCROLL_BAR_CONTINUOUS_DELAY
5748 selector: @selector (repeatScroll:)
5754 [self sendScrollEventAtLoc: 0 fromEvent: e];
5759 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
5760 mouseDragged events without going into a modal loop. */
5761 - (void)mouseDown: (NSEvent *)e
5764 /* hitPart is only updated AFTER event is passed on */
5765 NSScrollerPart part = [self testPart: [e locationInWindow]];
5766 double inc = 0.0, loc, kloc, pos;
5769 NSTRACE (EmacsScroller_mouseDown);
5773 case NSScrollerDecrementPage:
5774 last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
5775 case NSScrollerIncrementPage:
5776 last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
5777 case NSScrollerDecrementLine:
5778 last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
5779 case NSScrollerIncrementLine:
5780 last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
5781 case NSScrollerKnob:
5782 last_hit_part = scroll_bar_handle; break;
5783 case NSScrollerKnobSlot: /* GNUstep-only */
5784 last_hit_part = scroll_bar_move_ratio; break;
5785 default: /* NSScrollerNoPart? */
5786 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %d\n", part);
5792 pos = 0; /* ignored */
5794 /* set a timer to repeat, as we can't let superclass do this modally */
5796 = [[NSTimer scheduledTimerWithTimeInterval: 0.5
5798 selector: @selector (repeatScroll:)
5805 /* handle, or on GNUstep possibly slot */
5806 NSEvent *fake_event;
5808 /* compute float loc in slot and mouse offset on knob */
5809 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
5811 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
5817 else if (loc >= NSHeight (sr))
5819 loc = NSHeight (sr);
5827 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
5829 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
5831 last_mouse_offset = kloc;
5833 /* if knob, tell emacs a location offset by knob pos
5834 (to indicate top of handle) */
5835 if (part == NSScrollerKnob)
5836 pos = (loc - last_mouse_offset) / NSHeight (sr);
5838 /* else this is a slot click on GNUstep: go straight there */
5839 pos = loc / NSHeight (sr);
5841 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
5842 fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
5843 location: [e locationInWindow]
5844 modifierFlags: [e modifierFlags]
5845 timestamp: [e timestamp]
5846 windowNumber: [e windowNumber]
5847 context: [e context]
5848 eventNumber: [e eventNumber]
5849 clickCount: [e clickCount]
5850 pressure: [e pressure]];
5851 [super mouseUp: fake_event];
5854 if (part != NSScrollerKnob)
5855 [self sendScrollEventAtLoc: pos fromEvent: e];
5859 /* Called as we manually track scroller drags, rather than superclass. */
5860 - (void)mouseDragged: (NSEvent *)e
5866 NSTRACE (EmacsScroller_mouseDragged);
5868 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
5870 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
5877 else if (loc >= NSHeight (sr) + last_mouse_offset)
5879 loc = NSHeight (sr) + last_mouse_offset;
5883 pos = /*(edge ? loc :*/ (loc - last_mouse_offset) / NSHeight (sr);
5884 [self sendScrollEventAtLoc: pos fromEvent: e];
5888 - (void)mouseUp: (NSEvent *)e
5890 if (scroll_repeat_entry)
5892 [scroll_repeat_entry invalidate];
5893 [scroll_repeat_entry release];
5894 scroll_repeat_entry = nil;
5900 /* treat scrollwheel events in the bar as though they were in the main window */
5901 - (void) scrollWheel: (NSEvent *)theEvent
5903 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
5904 [view mouseDown: theEvent];
5907 @end /* EmacsScroller */
5911 /* ==========================================================================
5913 EmacsPrefsController implementation
5915 ========================================================================== */
5918 @implementation EmacsPrefsController
5920 /* in Tiger+, can just do [popup selectItemWithTag: tag]; */
5921 static void selectItemWithTag (NSPopUpButton *popup, int tag)
5923 NSEnumerator *items = [[popup itemArray] objectEnumerator];
5925 while (item = [items nextObject])
5927 if ([item tag] == tag)
5929 [popup selectItem: item];
5937 [NSBundle loadNibNamed: @"preferences" owner: self];
5942 - (void) showForFrame: (struct frame *)f
5945 [self setPanelFromValues];
5946 [prefsWindow makeKeyAndOrderFront: self];
5947 [prefsWindow display];
5951 - (void) setPanelFromValues
5954 = ns_lisp_to_cursor_type (get_frame_param (frame, Qcursor_type));
5955 prevExpandSpace = XFLOATINT (ns_expand_space);
5957 #ifdef NS_IMPL_COCOA
5958 prevUseHighlightColor = ns_use_system_highlight_color;
5961 [expandSpaceSlider setFloatValue: prevExpandSpace];
5962 [cursorTypeMatrix selectCellWithTag: (cursorType == FILLED_BOX_CURSOR ? 1 :
5963 (cursorType == BAR_CURSOR ? 2 :
5964 (cursorType == HBAR_CURSOR ? 3 : 4)))];
5965 selectItemWithTag (alternateModMenu,
5966 parse_solitary_modifier (ns_alternate_modifier));
5967 selectItemWithTag (commandModMenu,
5968 parse_solitary_modifier (ns_command_modifier));
5969 #ifdef NS_IMPL_COCOA
5970 selectItemWithTag (controlModMenu,
5971 parse_solitary_modifier (ns_control_modifier));
5972 selectItemWithTag (functionModMenu,
5973 parse_solitary_modifier (ns_function_modifier));
5974 [smoothFontsCheck setState: (NILP (ns_antialias_text) ? NO : YES)];
5975 [useQuickdrawCheck setState: (NILP (ns_use_qd_smoothing) ? NO : YES)];
5976 [useSysHiliteCheck setState: (NILP (prevUseHighlightColor) ? NO : YES)];
5981 - (void) setValuesFromPanel
5983 int altTag = [[alternateModMenu selectedItem] tag];
5984 int cmdTag = [[commandModMenu selectedItem] tag];
5985 #ifdef NS_IMPL_COCOA
5986 int ctrlTag = [[controlModMenu selectedItem] tag];
5987 int fnTag = [[functionModMenu selectedItem] tag];
5989 float expandSpace = [expandSpaceSlider floatValue];
5990 int cursorTag = [[cursorTypeMatrix selectedCell] tag];
5991 Lisp_Object cursor_type = ns_cursor_type_to_lisp
5992 ( cursorTag == 1 ? FILLED_BOX_CURSOR
5993 : cursorTag == 2 ? BAR_CURSOR
5994 : cursorTag == 3 ? HBAR_CURSOR : HOLLOW_BOX_CURSOR);
5996 if (expandSpace != prevExpandSpace)
5998 ns_expand_space = make_float (expandSpace);
5999 /* TODO: more needed: store needed metrics in nsfont_info, update
6000 frame default font max_bounds and fontp, recompute faces */
6001 /* FRAME_LINE_HEIGHT (frame) *= (expandSpace / prevExpandSpace);
6002 x_set_window_size (frame, 0, frame->text_cols, frame->text_lines); */
6003 prevExpandSpace = expandSpace;
6006 store_frame_param (frame, Qcursor_type, cursor_type);
6007 ns_set_cursor_type(frame, cursor_type, Qnil); /* FIXME: do only if changed */
6009 ns_alternate_modifier = ns_mod_to_lisp (altTag);
6010 ns_command_modifier = ns_mod_to_lisp (cmdTag);
6011 #ifdef NS_IMPL_COCOA
6012 ns_control_modifier = ns_mod_to_lisp (ctrlTag);
6013 ns_function_modifier = ns_mod_to_lisp (fnTag);
6014 ns_antialias_text = [smoothFontsCheck state] ? Qt : Qnil;
6015 ns_use_qd_smoothing = [useQuickdrawCheck state] ? Qt : Qnil;
6016 ns_use_system_highlight_color = [useSysHiliteCheck state] ? Qt : Qnil;
6017 if (! EQ (ns_use_system_highlight_color, prevUseHighlightColor))
6019 prevUseHighlightColor = ns_use_system_highlight_color;
6020 if (EQ (ns_use_system_highlight_color, Qt))
6022 ns_selection_color = [[NSUserDefaults standardUserDefaults]
6023 stringForKey: @"AppleHighlightColor"];
6024 if (ns_selection_color == nil)
6025 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
6028 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
6030 #endif /* NS_IMPL_COCOA */
6031 Fcall_interactively (intern ("ns-save-preferences"), Qnil, Qnil);
6036 - (IBAction)cancel: (id)sender
6038 [prefsWindow close];
6042 - (IBAction)ok: (id)sender
6044 [self setValuesFromPanel];
6045 [prefsWindow close];
6049 - (IBAction)resetToDefaults: (id)sender
6051 ns_set_default_prefs ();
6052 [self setPanelFromValues];
6056 - (IBAction)runHelp: (id)sender
6058 Feval (Fcons (intern ("info"),
6059 Fcons (build_string ("(ns-emacs)Preferences Panel"), Qnil)));
6060 SET_FRAME_GARBAGED (frame);
6061 ns_send_appdefined (-1);
6065 - (IBAction)setColors: (id)sender
6067 Lisp_Object lispFrame;
6068 XSETFRAME (lispFrame, frame);
6069 Fns_popup_color_panel (lispFrame);
6073 - (IBAction)setDefaultFont: (id)sender
6075 Lisp_Object lispFrame;
6076 XSETFRAME (lispFrame, frame);
6077 Fns_popup_font_panel (lispFrame);
6080 @end /* EmacsPrefsController */
6085 /* ==========================================================================
6087 Font-related functions; these used to be in nsfaces.m
6088 The XLFD functions (115 lines) are an abomination that should be removed.
6090 ========================================================================== */
6094 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
6096 struct font *font = XFONT_OBJECT (font_object);
6099 fontset = fontset_from_font (font_object);
6100 FRAME_FONTSET (f) = fontset;
6102 if (FRAME_FONT (f) == font)
6103 /* This font is already set in frame F. There's nothing more to
6107 FRAME_FONT (f) = font;
6109 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
6110 FRAME_COLUMN_WIDTH (f) = font->average_width;
6111 FRAME_SPACE_WIDTH (f) = font->space_width;
6112 FRAME_LINE_HEIGHT (f) = font->height;
6114 compute_fringe_widths (f, 1);
6116 /* Compute the scroll bar width in character columns. */
6117 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
6119 int wid = FRAME_COLUMN_WIDTH (f);
6120 FRAME_CONFIG_SCROLL_BAR_COLS (f)
6121 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
6125 int wid = FRAME_COLUMN_WIDTH (f);
6126 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
6129 /* Now make the frame display the given font. */
6130 if (FRAME_NS_WINDOW (f) != 0)
6131 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
6137 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
6140 ns_font_to_xlfd (NSFont *nsfont)
6141 /* --------------------------------------------------------------------------
6142 Convert an NS font name to an X font name (XLFD).
6143 The string returned is temporarily allocated.
6144 -------------------------------------------------------------------------- */
6146 NSFontManager *mgr = [NSFontManager sharedFontManager];
6147 NSString *sname = [nsfont /*familyName*/fontName];
6148 char *famName = (char *)[sname UTF8String];
6149 char *weightStr = [mgr fontNamed: sname hasTraits: NSBoldFontMask] ?
6151 char *slantStr = [mgr fontNamed: sname hasTraits: NSItalicFontMask] ?
6153 int size = [nsfont pointSize];
6154 int aWidth = lrint (10.0 * [nsfont widthOfString: @"a"]);
6158 /* change '-' to '$' to avoid messing w/XLFD separator */
6159 for (len = strlen (famName), i =0; i<len; i++)
6160 if (famName[i] == '-')
6166 xlfd = [[NSString stringWithFormat:
6167 @"-apple-%s-%s-%s-normal--%d-%d-75-75-m-%d-iso10646-1",
6168 famName, weightStr, slantStr, size, 10*size, aWidth]
6170 /*fprintf (stderr, "converted '%s' to '%s'\n",name,xlfd); */
6175 ns_fontname_to_xlfd (const char *name)
6176 /* --------------------------------------------------------------------------
6177 Convert an NS font name to an X font name (XLFD).
6179 The string returned is temporarily allocated.
6180 -------------------------------------------------------------------------- */
6183 char *weightStr = strcasestr (name, "bold") ? "bold" : "medium";
6184 char *slantStr = strcasestr (name, "italic") || strcasestr (name, "oblique")
6185 || strcasestr (name, "synthital") ? "i" : "r";
6189 /* change '-' to '$' to avoid messing w/XLFD separator, and ' ' to '_' */
6190 bzero (famName, 180);
6191 bcopy (name, famName, max (strlen (name), 179));
6192 for (len =strlen (famName), i =0; i<len; i++)
6194 if (famName[i] == '-')
6196 else if (famName[i] == ' ')
6200 xlfd = [[NSString stringWithFormat:
6201 @"-apple-%s-%s-%s-normal--0-0-75-75-m-0-iso10646-1",
6202 famName, weightStr, slantStr]
6204 /*fprintf (stderr, "converted '%s' to '%s'\n",name,xlfd); */
6210 ns_xlfd_to_fontname (const char *xlfd)
6211 /* --------------------------------------------------------------------------
6212 Convert an X font name (XLFD) to an NS font name.
6213 Only family is used.
6214 The string returned is temporarily allocated.
6215 -------------------------------------------------------------------------- */
6217 char *name = xmalloc (180);
6221 if (!strncmp (xlfd, "--", 2))
6222 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
6224 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
6226 /* stopgap for malformed XLFD input */
6227 if (strlen (name) == 0)
6228 strcpy (name, "Monaco");
6230 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
6231 also uppercase after '-' or ' ' */
6232 name[0] = toupper (name[0]);
6233 for (len =strlen (name), i =0; i<len; i++)
6239 name[i+1] = toupper (name[i+1]);
6241 else if (name[i] == '_')
6245 name[i+1] = toupper (name[i+1]);
6248 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
6249 ret = [[NSString stringWithUTF8String: name] UTF8String];
6258 NSTRACE (syms_of_nsterm);
6259 DEFVAR_LISP ("ns-input-file", &ns_input_file,
6260 "The file specified in the last NS event.");
6261 ns_input_file =Qnil;
6263 DEFVAR_LISP ("ns-input-text", &ns_input_text,
6264 "The data received in the last NS text drag event.");
6265 ns_input_text =Qnil;
6267 DEFVAR_LISP ("ns-working-text", &ns_working_text,
6268 "String for visualizing working composition sequence.");
6269 ns_working_text =Qnil;
6271 DEFVAR_LISP ("ns-input-font", &ns_input_font,
6272 "The font specified in the last NS event.");
6273 ns_input_font =Qnil;
6275 DEFVAR_LISP ("ns-input-fontsize", &ns_input_fontsize,
6276 "The fontsize specified in the last NS event.");
6277 ns_input_fontsize =Qnil;
6279 DEFVAR_LISP ("ns-input-line", &ns_input_line,
6280 "The line specified in the last NS event.");
6281 ns_input_line =Qnil;
6283 DEFVAR_LISP ("ns-input-color", &ns_input_color,
6284 "The color specified in the last NS event.");
6285 ns_input_color =Qnil;
6287 DEFVAR_LISP ("ns-input-spi-name", &ns_input_spi_name,
6288 "The service name specified in the last NS event.");
6289 ns_input_spi_name =Qnil;
6291 DEFVAR_LISP ("ns-input-spi-arg", &ns_input_spi_arg,
6292 "The service argument specified in the last NS event.");
6293 ns_input_spi_arg =Qnil;
6295 DEFVAR_LISP ("ns-alternate-modifier", &ns_alternate_modifier,
6296 "This variable describes the behavior of the alternate or option key.\n\
6297 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6298 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6299 at all, allowing it to be used at a lower level for accented character entry.");
6301 DEFVAR_LISP ("ns-command-modifier", &ns_command_modifier,
6302 "This variable describes the behavior of the command key.\n\
6303 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6305 DEFVAR_LISP ("ns-control-modifier", &ns_control_modifier,
6306 "This variable describes the behavior of the control key.\n\
6307 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6309 DEFVAR_LISP ("ns-function-modifier", &ns_function_modifier,
6310 "This variable describes the behavior of the function key (on laptops).\n\
6311 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6312 Set to none means that the function key is not interpreted by Emacs at all,\n\
6313 allowing it to be used at a lower level for accented character entry.");
6315 DEFVAR_LISP ("ns-expand-space", &ns_expand_space,
6316 "Amount by which spacing between lines is expanded (positive)\n\
6317 or shrunk (negative). Zero (the default) means standard line height.\n\
6318 (This variable should only be read, never set.)");
6320 DEFVAR_LISP ("ns-antialias-text", &ns_antialias_text,
6321 "Non-nil (the default) means to render text antialiased. Only has an effect on OS X Panther and above.");
6323 DEFVAR_LISP ("ns-use-qd-smoothing", &ns_use_qd_smoothing,
6324 "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).");
6326 DEFVAR_LISP ("ns-use-system-highlight-color",
6327 &ns_use_system_highlight_color,
6328 "Whether to use the system default (on OS X only) for the highlight color. Nil means to use standard emacs (prior to version 21) 'grey'.");
6330 staticpro (&ns_display_name_list);
6331 ns_display_name_list = Qnil;
6333 staticpro (&last_mouse_motion_frame);
6334 last_mouse_motion_frame = Qnil;
6336 /*23: now apparently we need to tell emacs what modifiers there are.. */
6337 Qmodifier_value = intern ("modifier-value");
6338 Qalt = intern ("alt");
6339 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
6340 Qhyper = intern ("hyper");
6341 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
6342 Qmeta = intern ("meta");
6343 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
6344 Qsuper = intern ("super");
6345 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
6346 Qcontrol = intern ("control");
6347 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
6349 /* TODO: move to common code */
6350 DEFVAR_LISP ("x-toolkit-scroll-bars", &Vx_toolkit_scroll_bars,
6351 doc: /* If not nil, Emacs uses toolkit scroll bars. */);
6352 #ifdef USE_TOOLKIT_SCROLL_BARS
6353 Vx_toolkit_scroll_bars = Qt;
6355 Vx_toolkit_scroll_bars = Qnil;
6358 /* these are unsupported but we need the declarations to avoid whining
6359 messages from cus-start.el */
6360 DEFVAR_BOOL ("x-use-underline-position-properties",
6361 &x_use_underline_position_properties,
6362 doc: /* NOT SUPPORTED UNDER NS.
6363 *Non-nil means make use of UNDERLINE_POSITION font properties.
6364 A value of nil means ignore them. If you encounter fonts with bogus
6365 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
6366 to 4.1, set this to nil.
6368 NOTE: Not supported on Mac yet. */);
6369 x_use_underline_position_properties = 0;
6371 DEFVAR_BOOL ("x-underline-at-descent-line",
6372 &x_underline_at_descent_line,
6373 doc: /* NOT SUPPORTED UNDER NS.
6374 *Non-nil means to draw the underline at the same place as the descent line.
6375 A value of nil means to draw the underline according to the value of the
6376 variable `x-use-underline-position-properties', which is usually at the
6377 baseline level. The default value is nil. */);
6378 x_underline_at_descent_line = 0;
6380 /* Tell emacs about this window system. */
6381 Fprovide (intern ("ns"), Qnil);
6382 /* TODO: try to move this back into lisp, ns-win.el loaded too late
6385 Lisp_Object args[3] = { intern ("ns-version-string"), build_string ("9.0"),
6386 build_string ("NS Window system port version number.") };
6387 Fdefconst (Flist (3, args));
6392 // arch-tag: 6eaa8f7d-a69b-4e1c-b43d-ab31defbe0d2