Make a self-contained ns build able to find its own libexec directory
[bpt/emacs.git] / src / nsterm.m
1 /* NeXT/Open/GNUstep / MacOSX communication module.
2
3 Copyright (C) 1989, 1993-1994, 2005-2006, 2008-2012
4 Free Software Foundation, Inc.
5
6 This file is part of GNU Emacs.
7
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20
21 /*
22 Originally by Carl Edman
23 Updated by Christian Limpach (chris@nice.ch)
24 OpenStep/Rhapsody port by Scott Bender (sbender@harmony-ds.com)
25 MacOSX/Aqua port by Christophe de Dinechin (descubes@earthlink.net)
26 GNUstep port and post-20 update by Adrian Robert (arobert@cogsci.ucsd.edu)
27 */
28
29 /* This should be the first include, as it may set up #defines affecting
30 interpretation of even the system includes. */
31 #include <config.h>
32
33 #include <math.h>
34 #include <sys/types.h>
35 #include <time.h>
36 #include <signal.h>
37 #include <unistd.h>
38 #include <setjmp.h>
39
40 #include "lisp.h"
41 #include "blockinput.h"
42 #include "sysselect.h"
43 #include "nsterm.h"
44 #include "systime.h"
45 #include "character.h"
46 #include "fontset.h"
47 #include "composite.h"
48 #include "ccl.h"
49
50 #include "termhooks.h"
51 #include "termopts.h"
52 #include "termchar.h"
53
54 #include "window.h"
55 #include "keyboard.h"
56
57 #include "font.h"
58
59 /* call tracing */
60 #if 0
61 int term_trace_num = 0;
62 #define NSTRACE(x) fprintf (stderr, "%s:%d: [%d] " #x "\n", \
63 __FILE__, __LINE__, ++term_trace_num)
64 #else
65 #define NSTRACE(x)
66 #endif
67
68 extern NSString *NSMenuDidBeginTrackingNotification;
69
70 /* ==========================================================================
71
72 Local declarations
73
74 ========================================================================== */
75
76 /* Convert a symbol indexed with an NSxxx value to a value as defined
77 in keyboard.c (lispy_function_key). I hope this is a correct way
78 of doing things... */
79 static unsigned convert_ns_to_X_keysym[] =
80 {
81 NSHomeFunctionKey, 0x50,
82 NSLeftArrowFunctionKey, 0x51,
83 NSUpArrowFunctionKey, 0x52,
84 NSRightArrowFunctionKey, 0x53,
85 NSDownArrowFunctionKey, 0x54,
86 NSPageUpFunctionKey, 0x55,
87 NSPageDownFunctionKey, 0x56,
88 NSEndFunctionKey, 0x57,
89 NSBeginFunctionKey, 0x58,
90 NSSelectFunctionKey, 0x60,
91 NSPrintFunctionKey, 0x61,
92 NSExecuteFunctionKey, 0x62,
93 NSInsertFunctionKey, 0x63,
94 NSUndoFunctionKey, 0x65,
95 NSRedoFunctionKey, 0x66,
96 NSMenuFunctionKey, 0x67,
97 NSFindFunctionKey, 0x68,
98 NSHelpFunctionKey, 0x6A,
99 NSBreakFunctionKey, 0x6B,
100
101 NSF1FunctionKey, 0xBE,
102 NSF2FunctionKey, 0xBF,
103 NSF3FunctionKey, 0xC0,
104 NSF4FunctionKey, 0xC1,
105 NSF5FunctionKey, 0xC2,
106 NSF6FunctionKey, 0xC3,
107 NSF7FunctionKey, 0xC4,
108 NSF8FunctionKey, 0xC5,
109 NSF9FunctionKey, 0xC6,
110 NSF10FunctionKey, 0xC7,
111 NSF11FunctionKey, 0xC8,
112 NSF12FunctionKey, 0xC9,
113 NSF13FunctionKey, 0xCA,
114 NSF14FunctionKey, 0xCB,
115 NSF15FunctionKey, 0xCC,
116 NSF16FunctionKey, 0xCD,
117 NSF17FunctionKey, 0xCE,
118 NSF18FunctionKey, 0xCF,
119 NSF19FunctionKey, 0xD0,
120 NSF20FunctionKey, 0xD1,
121 NSF21FunctionKey, 0xD2,
122 NSF22FunctionKey, 0xD3,
123 NSF23FunctionKey, 0xD4,
124 NSF24FunctionKey, 0xD5,
125
126 NSBackspaceCharacter, 0x08, /* 8: Not on some KBs. */
127 NSDeleteCharacter, 0xFF, /* 127: Big 'delete' key upper right. */
128 NSDeleteFunctionKey, 0x9F, /* 63272: Del forw key off main array. */
129
130 NSTabCharacter, 0x09,
131 0x19, 0x09, /* left tab->regular since pass shift */
132 NSCarriageReturnCharacter, 0x0D,
133 NSNewlineCharacter, 0x0D,
134 NSEnterCharacter, 0x8D,
135
136 0x1B, 0x1B /* escape */
137 };
138
139 static Lisp_Object Qmodifier_value;
140 Lisp_Object Qalt, Qcontrol, Qhyper, Qmeta, Qsuper, Qnone;
141 extern Lisp_Object Qcursor_color, Qcursor_type, Qns, Qleft;
142
143 static Lisp_Object QUTF8_STRING;
144
145 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
146 the maximum font size to NOT antialias. On GNUstep there is currently
147 no way to control this behavior. */
148 float ns_antialias_threshold;
149
150 /* Used to pick up AppleHighlightColor on OS X */
151 NSString *ns_selection_color;
152
153 NSArray *ns_send_types =0, *ns_return_types =0, *ns_drag_types =0;
154 NSString *ns_app_name = @"Emacs"; /* default changed later */
155
156 /* Display variables */
157 struct ns_display_info *x_display_list; /* Chain of existing displays */
158 Lisp_Object ns_display_name_list;
159 long context_menu_value = 0;
160
161 /* display update */
162 NSPoint last_mouse_motion_position;
163 static NSRect last_mouse_glyph;
164 static Time last_mouse_movement_time = 0;
165 static Lisp_Object last_mouse_motion_frame;
166 static EmacsScroller *last_mouse_scroll_bar = nil;
167 static struct frame *ns_updating_frame;
168 static NSView *focus_view = NULL;
169 static int ns_window_num = 0;
170 static NSRect uRect;
171 static BOOL gsaved = NO;
172 BOOL ns_in_resize = NO;
173 static BOOL ns_fake_keydown = NO;
174 int ns_tmp_flags; /* FIXME */
175 struct nsfont_info *ns_tmp_font; /* FIXME */
176 static BOOL ns_menu_bar_is_hidden = NO;
177 /*static int debug_lock = 0; */
178
179 /* event loop */
180 static BOOL send_appdefined = YES;
181 static NSEvent *last_appdefined_event = 0;
182 static NSTimer *timed_entry = 0;
183 static NSTimer *fd_entry = nil;
184 static NSTimer *scroll_repeat_entry = nil;
185 static fd_set select_readfds, t_readfds;
186 static struct timeval select_timeout;
187 static int select_nfds;
188 static NSAutoreleasePool *outerpool;
189 static struct input_event *emacs_event = NULL;
190 static struct input_event *q_event_ptr = NULL;
191 static int n_emacs_events_pending = 0;
192 static NSMutableArray *ns_pending_files, *ns_pending_service_names,
193 *ns_pending_service_args;
194 static BOOL inNsSelect = 0;
195
196 /* Convert modifiers in a NeXTstep event to emacs style modifiers. */
197 #define NS_FUNCTION_KEY_MASK 0x800000
198 #define NSLeftControlKeyMask (0x000001 | NSControlKeyMask)
199 #define NSRightControlKeyMask (0x002000 | NSControlKeyMask)
200 #define NSLeftCommandKeyMask (0x000008 | NSCommandKeyMask)
201 #define NSRightCommandKeyMask (0x000010 | NSCommandKeyMask)
202 #define NSLeftAlternateKeyMask (0x000020 | NSAlternateKeyMask)
203 #define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
204 #define EV_MODIFIERS(e) \
205 ((([e modifierFlags] & NSHelpKeyMask) ? \
206 hyper_modifier : 0) \
207 | (!EQ (ns_right_alternate_modifier, Qleft) && \
208 (([e modifierFlags] & NSRightAlternateKeyMask) \
209 == NSRightAlternateKeyMask) ? \
210 parse_solitary_modifier (ns_right_alternate_modifier) : 0) \
211 | (([e modifierFlags] & NSAlternateKeyMask) ? \
212 parse_solitary_modifier (ns_alternate_modifier) : 0) \
213 | (([e modifierFlags] & NSShiftKeyMask) ? \
214 shift_modifier : 0) \
215 | (!EQ (ns_right_control_modifier, Qleft) && \
216 (([e modifierFlags] & NSRightControlKeyMask) \
217 == NSRightControlKeyMask) ? \
218 parse_solitary_modifier (ns_right_control_modifier) : 0) \
219 | (([e modifierFlags] & NSControlKeyMask) ? \
220 parse_solitary_modifier (ns_control_modifier) : 0) \
221 | (([e modifierFlags] & NS_FUNCTION_KEY_MASK) ? \
222 parse_solitary_modifier (ns_function_modifier) : 0) \
223 | (!EQ (ns_right_command_modifier, Qleft) && \
224 (([e modifierFlags] & NSRightCommandKeyMask) \
225 == NSRightCommandKeyMask) ? \
226 parse_solitary_modifier (ns_right_command_modifier) : 0) \
227 | (([e modifierFlags] & NSCommandKeyMask) ? \
228 parse_solitary_modifier (ns_command_modifier):0))
229
230 #define EV_UDMODIFIERS(e) \
231 ((([e type] == NSLeftMouseDown) ? down_modifier : 0) \
232 | (([e type] == NSRightMouseDown) ? down_modifier : 0) \
233 | (([e type] == NSOtherMouseDown) ? down_modifier : 0) \
234 | (([e type] == NSLeftMouseDragged) ? down_modifier : 0) \
235 | (([e type] == NSRightMouseDragged) ? down_modifier : 0) \
236 | (([e type] == NSOtherMouseDragged) ? down_modifier : 0) \
237 | (([e type] == NSLeftMouseUp) ? up_modifier : 0) \
238 | (([e type] == NSRightMouseUp) ? up_modifier : 0) \
239 | (([e type] == NSOtherMouseUp) ? up_modifier : 0))
240
241 #define EV_BUTTON(e) \
242 ((([e type] == NSLeftMouseDown) || ([e type] == NSLeftMouseUp)) ? 0 : \
243 (([e type] == NSRightMouseDown) || ([e type] == NSRightMouseUp)) ? 2 : \
244 [e buttonNumber] - 1)
245
246 /* Convert the time field to a timestamp in milliseconds. */
247 #define EV_TIMESTAMP(e) ([e timestamp] * 1000)
248
249 /* This is a piece of code which is common to all the event handling
250 methods. Maybe it should even be a function. */
251 #define EV_TRAILER(e) \
252 { \
253 XSETFRAME (emacs_event->frame_or_window, emacsframe); \
254 if (e) emacs_event->timestamp = EV_TIMESTAMP (e); \
255 n_emacs_events_pending++; \
256 kbd_buffer_store_event_hold (emacs_event, q_event_ptr); \
257 EVENT_INIT (*emacs_event); \
258 ns_send_appdefined (-1); \
259 }
260
261 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
262
263 /* TODO: get rid of need for these forward declarations */
264 static void ns_condemn_scroll_bars (struct frame *f);
265 static void ns_judge_scroll_bars (struct frame *f);
266 void x_set_frame_alpha (struct frame *f);
267
268
269 /* ==========================================================================
270
271 Utilities
272
273 ========================================================================== */
274
275
276 static Lisp_Object
277 append2 (Lisp_Object list, Lisp_Object item)
278 /* --------------------------------------------------------------------------
279 Utility to append to a list
280 -------------------------------------------------------------------------- */
281 {
282 Lisp_Object array[2];
283 array[0] = list;
284 array[1] = Fcons (item, Qnil);
285 return Fnconc (2, &array[0]);
286 }
287
288
289 void
290 ns_init_paths (void)
291 /* --------------------------------------------------------------------------
292 Used to allow emacs to find its resources under Emacs.app
293 Called from emacs.c at startup.
294 -------------------------------------------------------------------------- */
295 {
296 NSBundle *bundle = [NSBundle mainBundle];
297 NSString *binDir = [bundle bundlePath], *resourceDir = [bundle resourcePath];
298 NSString *resourcePath, *resourcePaths;
299 NSRange range;
300 BOOL onWindows = NO; /* how do I determine this? */
301 NSString *pathSeparator = onWindows ? @";" : @":";
302 NSFileManager *fileManager = [NSFileManager defaultManager];
303 BOOL isDir;
304 /*NSLog (@"ns_init_paths: '%@'\n%@\n", [[NSBundle mainBundle] bundlePath], [[NSBundle mainBundle] resourcePath]); */
305
306 /* get bindir from base */
307 range = [resourceDir rangeOfString: @"Contents"];
308 if (range.location != NSNotFound)
309 {
310 binDir = [binDir stringByAppendingPathComponent: @"Contents"];
311 #ifdef NS_IMPL_COCOA
312 binDir = [binDir stringByAppendingPathComponent: @"MacOS"];
313 #endif
314 }
315
316 /* the following based on Andrew Choi's init_mac_osx_environment () */
317 if (!getenv ("EMACSLOADPATH"))
318 {
319 NSArray *paths = [resourceDir stringsByAppendingPaths:
320 [NSArray arrayWithObjects:
321 @"site-lisp", @"lisp", @"leim", nil]];
322 NSEnumerator *pathEnum = [paths objectEnumerator];
323 resourcePaths = @"";
324 while (resourcePath = [pathEnum nextObject])
325 {
326 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
327 if (isDir)
328 {
329 if ([resourcePaths length] > 0)
330 resourcePaths
331 = [resourcePaths stringByAppendingString: pathSeparator];
332 resourcePaths
333 = [resourcePaths stringByAppendingString: resourcePath];
334 }
335 }
336 if ([resourcePaths length] > 0)
337 setenv ("EMACSLOADPATH", [resourcePaths UTF8String], 1);
338 /*NSLog (@"loadPath: '%@'\n", resourcePaths); */
339 }
340
341 /* Normally, Emacs does not add its own bin/ directory to the PATH.
342 However, a self-contained NS build has a different layout, with
343 bin/ and libexec/ subdirectories in the directory that contains
344 Emacs.app itself.
345 We put libexec first, because init_callproc_1 uses the first
346 element to initialize exec-directory. An alternative would be
347 for init_callproc to check for invocation-directory/libexec. */
348 if (!getenv ("EMACSPATH"))
349 {
350 NSArray *paths = [binDir stringsByAppendingPaths:
351 [NSArray arrayWithObjects: @"libexec",
352 @"bin", nil]];
353 NSEnumerator *pathEnum = [paths objectEnumerator];
354 resourcePaths = @"";
355 while (resourcePath = [pathEnum nextObject])
356 {
357 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
358 if (isDir)
359 {
360 if ([resourcePaths length] > 0)
361 resourcePaths
362 = [resourcePaths stringByAppendingString: pathSeparator];
363 resourcePaths
364 = [resourcePaths stringByAppendingString: resourcePath];
365 }
366 }
367 if ([resourcePaths length] > 0)
368 setenv ("EMACSPATH", [resourcePaths UTF8String], 1);
369 }
370
371 resourcePath = [resourceDir stringByAppendingPathComponent: @"etc"];
372 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
373 {
374 if (isDir)
375 {
376 if (!getenv ("EMACSDATA"))
377 setenv ("EMACSDATA", [resourcePath UTF8String], 1);
378 if (!getenv ("EMACSDOC"))
379 setenv ("EMACSDOC", [resourcePath UTF8String], 1);
380 }
381 }
382
383 if (!getenv ("INFOPATH"))
384 {
385 resourcePath = [resourceDir stringByAppendingPathComponent: @"info"];
386 if ([fileManager fileExistsAtPath: resourcePath isDirectory: &isDir])
387 if (isDir)
388 setenv ("INFOPATH", [[resourcePath stringByAppendingString: @":"]
389 UTF8String], 1);
390 /* Note, extra colon needed to cause merge w/later user additions. */
391 }
392 }
393
394
395 static int
396 timeval_subtract (struct timeval *result, struct timeval x, struct timeval y)
397 /* --------------------------------------------------------------------------
398 Subtract the `struct timeval' values X and Y, storing the result in RESULT.
399 Return 1 if the difference is negative, otherwise 0.
400 -------------------------------------------------------------------------- */
401 {
402 /* Perform the carry for the later subtraction by updating y.
403 This is safer because on some systems
404 the tv_sec member is unsigned. */
405 if (x.tv_usec < y.tv_usec)
406 {
407 int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
408 y.tv_usec -= 1000000 * nsec;
409 y.tv_sec += nsec;
410 }
411 if (x.tv_usec - y.tv_usec > 1000000)
412 {
413 int nsec = (y.tv_usec - x.tv_usec) / 1000000;
414 y.tv_usec += 1000000 * nsec;
415 y.tv_sec -= nsec;
416 }
417
418 /* Compute the time remaining to wait. tv_usec is certainly positive. */
419 result->tv_sec = x.tv_sec - y.tv_sec;
420 result->tv_usec = x.tv_usec - y.tv_usec;
421
422 /* Return indication of whether the result should be considered negative. */
423 return x.tv_sec < y.tv_sec;
424 }
425
426 static void
427 ns_timeout (int usecs)
428 /* --------------------------------------------------------------------------
429 Blocking timer utility used by ns_ring_bell
430 -------------------------------------------------------------------------- */
431 {
432 struct timeval wakeup;
433
434 EMACS_GET_TIME (wakeup);
435
436 /* Compute time to wait until, propagating carry from usecs. */
437 wakeup.tv_usec += usecs;
438 wakeup.tv_sec += (wakeup.tv_usec / 1000000);
439 wakeup.tv_usec %= 1000000;
440
441 /* Keep waiting until past the time wakeup. */
442 while (1)
443 {
444 struct timeval timeout;
445
446 EMACS_GET_TIME (timeout);
447
448 /* In effect, timeout = wakeup - timeout.
449 Break if result would be negative. */
450 if (timeval_subtract (&timeout, wakeup, timeout))
451 break;
452
453 /* Try to wait that long--but we might wake up sooner. */
454 select (0, NULL, NULL, NULL, &timeout);
455 }
456 }
457
458
459 void
460 ns_release_object (void *obj)
461 /* --------------------------------------------------------------------------
462 Release an object (callable from C)
463 -------------------------------------------------------------------------- */
464 {
465 [(id)obj release];
466 }
467
468
469 void
470 ns_retain_object (void *obj)
471 /* --------------------------------------------------------------------------
472 Retain an object (callable from C)
473 -------------------------------------------------------------------------- */
474 {
475 [(id)obj retain];
476 }
477
478
479 void *
480 ns_alloc_autorelease_pool (void)
481 /* --------------------------------------------------------------------------
482 Allocate a pool for temporary objects (callable from C)
483 -------------------------------------------------------------------------- */
484 {
485 return [[NSAutoreleasePool alloc] init];
486 }
487
488
489 void
490 ns_release_autorelease_pool (void *pool)
491 /* --------------------------------------------------------------------------
492 Free a pool and temporary objects it refers to (callable from C)
493 -------------------------------------------------------------------------- */
494 {
495 ns_release_object (pool);
496 }
497
498
499
500 /* ==========================================================================
501
502 Focus (clipping) and screen update
503
504 ========================================================================== */
505
506 static NSRect
507 ns_resize_handle_rect (NSWindow *window)
508 {
509 NSRect r = [window frame];
510 r.origin.x = r.size.width - RESIZE_HANDLE_SIZE;
511 r.origin.y = 0;
512 r.size.width = r.size.height = RESIZE_HANDLE_SIZE;
513 return r;
514 }
515
516
517 //
518 // Window constraining
519 // -------------------
520 //
521 // To ensure that the windows are not placed under the menu bar, they
522 // are typically moved by the call-back constrainFrameRect. However,
523 // by overriding it, it's possible to inhibit this, leaving the window
524 // in it's original position.
525 //
526 // It's possible to hide the menu bar. However, technically, it's only
527 // possible to hide it when the application is active. To ensure that
528 // this work properly, the menu bar and window constraining are
529 // deferred until the application becomes active.
530 //
531 // Even though it's not possible to manually move a window above the
532 // top of the screen, it is allowed if it's done programmatically,
533 // when the menu is hidden. This allows the editable area to cover the
534 // full screen height.
535 //
536 // Test cases
537 // ----------
538 //
539 // Use the following extra files:
540 //
541 // init.el:
542 // ;; Hide menu and place frame slightly above the top of the screen.
543 // (setq ns-auto-hide-menu-bar t)
544 // (set-frame-position (selected-frame) 0 -20)
545 //
546 // Test 1:
547 //
548 // emacs -Q -l init.el
549 //
550 // Result: No menu bar, and the title bar should be above the screen.
551 //
552 // Test 2:
553 //
554 // emacs -Q
555 //
556 // Result: Menu bar visible, frame placed immediately below the menu.
557 //
558
559 static void
560 ns_constrain_all_frames (void)
561 {
562 Lisp_Object tail, frame;
563
564 FOR_EACH_FRAME (tail, frame)
565 {
566 struct frame *f = XFRAME (frame);
567 if (FRAME_NS_P (f))
568 {
569 NSView *view = FRAME_NS_VIEW (f);
570 /* This no-op will trigger the default window placing
571 * constraint system. */
572 f->output_data.ns->dont_constrain = 0;
573 [[view window] setFrameOrigin:[[view window] frame].origin];
574 }
575 }
576 }
577
578
579 /* True, if the menu bar should be hidden. */
580
581 static BOOL
582 ns_menu_bar_should_be_hidden (void)
583 {
584 return !NILP (ns_auto_hide_menu_bar)
585 && [NSApp respondsToSelector:@selector(setPresentationOptions:)];
586 }
587
588
589 /* Show or hide the menu bar, based on user setting. */
590
591 static void
592 ns_update_auto_hide_menu_bar (void)
593 {
594 #ifndef MAC_OS_X_VERSION_10_6
595 #define MAC_OS_X_VERSION_10_6 1060
596 #endif
597 #ifdef NS_IMPL_COCOA
598 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
599 BLOCK_INPUT;
600
601 NSTRACE (ns_update_auto_hide_menu_bar);
602
603 if (NSApp != nil
604 && [NSApp isActive]
605 && [NSApp respondsToSelector:@selector(setPresentationOptions:)])
606 {
607 // Note, "setPresentationOptions" triggers an error unless the
608 // application is active.
609 BOOL menu_bar_should_be_hidden = ns_menu_bar_should_be_hidden ();
610
611 if (menu_bar_should_be_hidden != ns_menu_bar_is_hidden)
612 {
613 NSApplicationPresentationOptions options
614 = NSApplicationPresentationAutoHideDock;
615
616 if (menu_bar_should_be_hidden)
617 options |= NSApplicationPresentationAutoHideMenuBar;
618
619 [NSApp setPresentationOptions: options];
620
621 ns_menu_bar_is_hidden = menu_bar_should_be_hidden;
622
623 if (!ns_menu_bar_is_hidden)
624 {
625 ns_constrain_all_frames ();
626 }
627 }
628 }
629
630 UNBLOCK_INPUT;
631 #endif
632 #endif
633 }
634
635
636 static void
637 ns_update_begin (struct frame *f)
638 /* --------------------------------------------------------------------------
639 Prepare for a grouped sequence of drawing calls
640 external (RIF) call; whole frame, called before update_window_begin
641 -------------------------------------------------------------------------- */
642 {
643 NSView *view = FRAME_NS_VIEW (f);
644 NSTRACE (ns_update_begin);
645
646 ns_update_auto_hide_menu_bar ();
647
648 ns_updating_frame = f;
649 [view lockFocus];
650
651 #ifdef NS_IMPL_GNUSTEP
652 uRect = NSMakeRect (0, 0, 0, 0);
653 #endif
654 }
655
656
657 static void
658 ns_update_window_begin (struct window *w)
659 /* --------------------------------------------------------------------------
660 Prepare for a grouped sequence of drawing calls
661 external (RIF) call; for one window, called after update_begin
662 -------------------------------------------------------------------------- */
663 {
664 struct frame *f = XFRAME (WINDOW_FRAME (w));
665 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
666 NSTRACE (ns_update_window_begin);
667
668 updated_window = w;
669 set_output_cursor (&w->cursor);
670
671 BLOCK_INPUT;
672
673 if (f == hlinfo->mouse_face_mouse_frame)
674 {
675 /* Don't do highlighting for mouse motion during the update. */
676 hlinfo->mouse_face_defer = 1;
677
678 /* If the frame needs to be redrawn,
679 simply forget about any prior mouse highlighting. */
680 if (FRAME_GARBAGED_P (f))
681 hlinfo->mouse_face_window = Qnil;
682
683 /* (further code for mouse faces ifdef'd out in other terms elided) */
684 }
685
686 UNBLOCK_INPUT;
687 }
688
689
690 static void
691 ns_update_window_end (struct window *w, int cursor_on_p,
692 int mouse_face_overwritten_p)
693 /* --------------------------------------------------------------------------
694 Finished a grouped sequence of drawing calls
695 external (RIF) call; for one window called before update_end
696 -------------------------------------------------------------------------- */
697 {
698 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (XFRAME (w->frame));
699
700 /* note: this fn is nearly identical in all terms */
701 if (!w->pseudo_window_p)
702 {
703 BLOCK_INPUT;
704
705 if (cursor_on_p)
706 display_and_set_cursor (w, 1,
707 output_cursor.hpos, output_cursor.vpos,
708 output_cursor.x, output_cursor.y);
709
710 if (draw_window_fringes (w, 1))
711 x_draw_vertical_border (w);
712
713 UNBLOCK_INPUT;
714 }
715
716 /* If a row with mouse-face was overwritten, arrange for
717 frame_up_to_date to redisplay the mouse highlight. */
718 if (mouse_face_overwritten_p)
719 {
720 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
721 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
722 hlinfo->mouse_face_window = Qnil;
723 }
724
725 updated_window = NULL;
726 NSTRACE (update_window_end);
727 }
728
729
730 static void
731 ns_update_end (struct frame *f)
732 /* --------------------------------------------------------------------------
733 Finished a grouped sequence of drawing calls
734 external (RIF) call; for whole frame, called after update_window_end
735 -------------------------------------------------------------------------- */
736 {
737 NSView *view = FRAME_NS_VIEW (f);
738
739 /* if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
740 MOUSE_HL_INFO (f)->mouse_face_defer = 0;
741
742 BLOCK_INPUT;
743
744 #ifdef NS_IMPL_GNUSTEP
745 /* trigger flush only in the rectangle we tracked as being drawn */
746 [view unlockFocusNeedsFlush: NO];
747 /*fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", uRect.origin.x, uRect.origin.y, uRect.size.width, uRect.size.height); */
748 [view lockFocusInRect: uRect];
749 #endif
750
751 [view unlockFocus];
752 [[view window] flushWindow];
753
754 UNBLOCK_INPUT;
755 ns_updating_frame = NULL;
756 NSTRACE (ns_update_end);
757 }
758
759
760 static void
761 ns_flush (struct frame *f)
762 /* --------------------------------------------------------------------------
763 external (RIF) call
764 NS impl is no-op since currently we flush in ns_update_end and elsewhere
765 -------------------------------------------------------------------------- */
766 {
767 NSTRACE (ns_flush);
768 }
769
770
771 static void
772 ns_focus (struct frame *f, NSRect *r, int n)
773 /* --------------------------------------------------------------------------
774 Internal: Focus on given frame. During small local updates this is used to
775 draw, however during large updates, ns_update_begin and ns_update_end are
776 called to wrap the whole thing, in which case these calls are stubbed out.
777 Except, on GNUstep, we accumulate the rectangle being drawn into, because
778 the back end won't do this automatically, and will just end up flushing
779 the entire window.
780 -------------------------------------------------------------------------- */
781 {
782 // NSTRACE (ns_focus);
783 #ifdef NS_IMPL_GNUSTEP
784 NSRect u;
785 if (n == 2)
786 u = NSUnionRect (r[0], r[1]);
787 else if (r)
788 u = *r;
789 #endif
790 /* static int c =0;
791 fprintf (stderr, "focus: %d", c++);
792 if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
793 fprintf (stderr, "\n"); */
794
795 if (f != ns_updating_frame)
796 {
797 NSView *view = FRAME_NS_VIEW (f);
798 if (view != focus_view)
799 {
800 if (focus_view != NULL)
801 {
802 [focus_view unlockFocus];
803 [[focus_view window] flushWindow];
804 /*debug_lock--; */
805 }
806
807 if (view)
808 #ifdef NS_IMPL_GNUSTEP
809 r ? [view lockFocusInRect: u] : [view lockFocus];
810 #else
811 [view lockFocus];
812 #endif
813 focus_view = view;
814 /*if (view) debug_lock++; */
815 }
816 #ifdef NS_IMPL_GNUSTEP
817 else
818 {
819 /* more than one rect being drawn into */
820 if (view && r)
821 {
822 [view unlockFocus]; /* add prev rect to redraw list */
823 [view lockFocusInRect: u]; /* focus for draw in new rect */
824 }
825 }
826 #endif
827 }
828 #ifdef NS_IMPL_GNUSTEP
829 else
830 {
831 /* in batch mode, but in GNUstep must still track rectangles explicitly */
832 uRect = (r ? NSUnionRect (uRect, u) : [FRAME_NS_VIEW (f) visibleRect]);
833 }
834 #endif
835
836 /* clipping */
837 if (r)
838 {
839 [[NSGraphicsContext currentContext] saveGraphicsState];
840 if (n == 2)
841 NSRectClipList (r, 2);
842 else
843 NSRectClip (*r);
844 gsaved = YES;
845 }
846 }
847
848
849 static void
850 ns_unfocus (struct frame *f)
851 /* --------------------------------------------------------------------------
852 Internal: Remove focus on given frame
853 -------------------------------------------------------------------------- */
854 {
855 // NSTRACE (ns_unfocus);
856
857 if (gsaved)
858 {
859 [[NSGraphicsContext currentContext] restoreGraphicsState];
860 gsaved = NO;
861 }
862
863 if (f != ns_updating_frame)
864 {
865 if (focus_view != NULL)
866 {
867 [focus_view unlockFocus];
868 [[focus_view window] flushWindow];
869 focus_view = NULL;
870 /*debug_lock--; */
871 }
872 }
873 }
874
875
876 static void
877 ns_clip_to_row (struct window *w, struct glyph_row *row, int area, BOOL gc)
878 /* --------------------------------------------------------------------------
879 Internal (but parallels other terms): Focus drawing on given row
880 -------------------------------------------------------------------------- */
881 {
882 struct frame *f = XFRAME (WINDOW_FRAME (w));
883 NSRect clip_rect;
884 int window_x, window_y, window_width;
885
886 window_box (w, area, &window_x, &window_y, &window_width, 0);
887
888 clip_rect.origin.x = window_x - FRAME_INTERNAL_BORDER_WIDTH (f);
889 clip_rect.origin.y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, row->y));
890 clip_rect.origin.y = max (clip_rect.origin.y, window_y);
891 clip_rect.size.width = window_width + 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
892 clip_rect.size.height = row->visible_height;
893
894 /* allow a full-height row at the top when requested
895 (used to draw fringe all the way through internal border area) */
896 if (gc && clip_rect.origin.y < 5)
897 {
898 clip_rect.origin.y -= FRAME_INTERNAL_BORDER_WIDTH (f);
899 clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
900 }
901
902 /* likewise at bottom */
903 if (gc &&
904 FRAME_PIXEL_HEIGHT (f) - (clip_rect.origin.y + clip_rect.size.height) < 5)
905 clip_rect.size.height += FRAME_INTERNAL_BORDER_WIDTH (f);
906
907 ns_focus (f, &clip_rect, 1);
908 }
909
910
911 static void
912 ns_ring_bell (struct frame *f)
913 /* --------------------------------------------------------------------------
914 "Beep" routine
915 -------------------------------------------------------------------------- */
916 {
917 NSTRACE (ns_ring_bell);
918 if (visible_bell)
919 {
920 NSAutoreleasePool *pool;
921 struct frame *frame = SELECTED_FRAME ();
922 NSView *view;
923
924 BLOCK_INPUT;
925 pool = [[NSAutoreleasePool alloc] init];
926
927 view = FRAME_NS_VIEW (frame);
928 if (view != nil)
929 {
930 NSRect r, surr;
931 NSPoint dim = NSMakePoint (128, 128);
932
933 r = [view bounds];
934 r.origin.x += (r.size.width - dim.x) / 2;
935 r.origin.y += (r.size.height - dim.y) / 2;
936 r.size.width = dim.x;
937 r.size.height = dim.y;
938 surr = NSInsetRect (r, -2, -2);
939 ns_focus (frame, &surr, 1);
940 [[view window] cacheImageInRect: [view convertRect: surr toView:nil]];
941 [ns_lookup_indexed_color (NS_FACE_FOREGROUND
942 (FRAME_DEFAULT_FACE (frame)), frame) set];
943 NSRectFill (r);
944 [[view window] flushWindow];
945 ns_timeout (150000);
946 [[view window] restoreCachedImage];
947 [[view window] flushWindow];
948 ns_unfocus (frame);
949 }
950 [pool release];
951 UNBLOCK_INPUT;
952 }
953 else
954 {
955 NSBeep ();
956 }
957 }
958
959
960 static void
961 ns_reset_terminal_modes (struct terminal *terminal)
962 /* Externally called as hook */
963 {
964 NSTRACE (ns_reset_terminal_modes);
965 }
966
967
968 static void
969 ns_set_terminal_modes (struct terminal *terminal)
970 /* Externally called as hook */
971 {
972 NSTRACE (ns_set_terminal_modes);
973 }
974
975
976
977 /* ==========================================================================
978
979 Frame / window manager related functions
980
981 ========================================================================== */
982
983
984 static void
985 ns_raise_frame (struct frame *f)
986 /* --------------------------------------------------------------------------
987 Bring window to foreground and make it active
988 -------------------------------------------------------------------------- */
989 {
990 NSView *view = FRAME_NS_VIEW (f);
991 check_ns ();
992 BLOCK_INPUT;
993 FRAME_SAMPLE_VISIBILITY (f);
994 if (FRAME_VISIBLE_P (f))
995 {
996 [[view window] makeKeyAndOrderFront: NSApp];
997 }
998 UNBLOCK_INPUT;
999 }
1000
1001
1002 static void
1003 ns_lower_frame (struct frame *f)
1004 /* --------------------------------------------------------------------------
1005 Send window to back
1006 -------------------------------------------------------------------------- */
1007 {
1008 NSView *view = FRAME_NS_VIEW (f);
1009 check_ns ();
1010 BLOCK_INPUT;
1011 [[view window] orderBack: NSApp];
1012 UNBLOCK_INPUT;
1013 }
1014
1015
1016 static void
1017 ns_frame_raise_lower (struct frame *f, int raise)
1018 /* --------------------------------------------------------------------------
1019 External (hook)
1020 -------------------------------------------------------------------------- */
1021 {
1022 NSTRACE (ns_frame_raise_lower);
1023
1024 if (raise)
1025 ns_raise_frame (f);
1026 else
1027 ns_lower_frame (f);
1028 }
1029
1030
1031 static void
1032 ns_frame_rehighlight (struct frame *frame)
1033 /* --------------------------------------------------------------------------
1034 External (hook): called on things like window switching within frame
1035 -------------------------------------------------------------------------- */
1036 {
1037 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
1038 struct frame *old_highlight = dpyinfo->x_highlight_frame;
1039
1040 NSTRACE (ns_frame_rehighlight);
1041 if (dpyinfo->x_focus_frame)
1042 {
1043 dpyinfo->x_highlight_frame
1044 = (FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1045 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
1046 : dpyinfo->x_focus_frame);
1047 if (!FRAME_LIVE_P (dpyinfo->x_highlight_frame))
1048 {
1049 FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
1050 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
1051 }
1052 }
1053 else
1054 dpyinfo->x_highlight_frame = 0;
1055
1056 if (dpyinfo->x_highlight_frame &&
1057 dpyinfo->x_highlight_frame != old_highlight)
1058 {
1059 if (old_highlight)
1060 {
1061 x_update_cursor (old_highlight, 1);
1062 x_set_frame_alpha (old_highlight);
1063 }
1064 if (dpyinfo->x_highlight_frame)
1065 {
1066 x_update_cursor (dpyinfo->x_highlight_frame, 1);
1067 x_set_frame_alpha (dpyinfo->x_highlight_frame);
1068 }
1069 }
1070 }
1071
1072
1073 void
1074 x_make_frame_visible (struct frame *f)
1075 /* --------------------------------------------------------------------------
1076 External: Show the window (X11 semantics)
1077 -------------------------------------------------------------------------- */
1078 {
1079 NSTRACE (x_make_frame_visible);
1080 /* XXX: at some points in past this was not needed, as the only place that
1081 called this (frame.c:Fraise_frame ()) also called raise_lower;
1082 if this ends up the case again, comment this out again. */
1083 if (!FRAME_VISIBLE_P (f))
1084 {
1085 f->async_visible = 1;
1086 ns_raise_frame (f);
1087 }
1088 }
1089
1090
1091 void
1092 x_make_frame_invisible (struct frame *f)
1093 /* --------------------------------------------------------------------------
1094 External: Hide the window (X11 semantics)
1095 -------------------------------------------------------------------------- */
1096 {
1097 NSView * view = FRAME_NS_VIEW (f);
1098 NSTRACE (x_make_frame_invisible);
1099 check_ns ();
1100 [[view window] orderOut: NSApp];
1101 f->async_visible = 0;
1102 f->async_iconified = 0;
1103 }
1104
1105
1106 void
1107 x_iconify_frame (struct frame *f)
1108 /* --------------------------------------------------------------------------
1109 External: Iconify window
1110 -------------------------------------------------------------------------- */
1111 {
1112 NSView * view = FRAME_NS_VIEW (f);
1113 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1114 NSTRACE (x_iconify_frame);
1115 check_ns ();
1116
1117 if (dpyinfo->x_highlight_frame == f)
1118 dpyinfo->x_highlight_frame = 0;
1119
1120 if ([[view window] windowNumber] <= 0)
1121 {
1122 /* the window is still deferred. Make it very small, bring it
1123 on screen and order it out. */
1124 NSRect s = { { 100, 100}, {0, 0} };
1125 NSRect t;
1126 t = [[view window] frame];
1127 [[view window] setFrame: s display: NO];
1128 [[view window] orderBack: NSApp];
1129 [[view window] orderOut: NSApp];
1130 [[view window] setFrame: t display: NO];
1131 }
1132 [[view window] miniaturize: NSApp];
1133 }
1134
1135 /* Free X resources of frame F. */
1136
1137 void
1138 x_free_frame_resources (struct frame *f)
1139 {
1140 NSView *view = FRAME_NS_VIEW (f);
1141 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1142 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1143 NSTRACE (x_destroy_window);
1144 check_ns ();
1145
1146 [(EmacsView *)view setWindowClosing: YES]; /* may not have been informed */
1147
1148 BLOCK_INPUT;
1149
1150 free_frame_menubar (f);
1151
1152 if (FRAME_FACE_CACHE (f))
1153 free_frame_faces (f);
1154
1155 if (f == dpyinfo->x_focus_frame)
1156 dpyinfo->x_focus_frame = 0;
1157 if (f == dpyinfo->x_highlight_frame)
1158 dpyinfo->x_highlight_frame = 0;
1159 if (f == hlinfo->mouse_face_mouse_frame)
1160 {
1161 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
1162 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
1163 hlinfo->mouse_face_window = Qnil;
1164 hlinfo->mouse_face_deferred_gc = 0;
1165 hlinfo->mouse_face_mouse_frame = 0;
1166 }
1167
1168 xfree (f->output_data.ns);
1169
1170 if (f->output_data.ns->miniimage != nil)
1171 [f->output_data.ns->miniimage release];
1172
1173 [[view window] close];
1174 [view release];
1175
1176 UNBLOCK_INPUT;
1177 }
1178
1179 void
1180 x_destroy_window (struct frame *f)
1181 /* --------------------------------------------------------------------------
1182 External: Delete the window
1183 -------------------------------------------------------------------------- */
1184 {
1185 NSTRACE (x_destroy_window);
1186 check_ns ();
1187 x_free_frame_resources (f);
1188 ns_window_num--;
1189 }
1190
1191
1192 void
1193 x_set_offset (struct frame *f, int xoff, int yoff, int change_grav)
1194 /* --------------------------------------------------------------------------
1195 External: Position the window
1196 -------------------------------------------------------------------------- */
1197 {
1198 NSView *view = FRAME_NS_VIEW (f);
1199 NSArray *screens = [NSScreen screens];
1200 NSScreen *fscreen = [screens objectAtIndex: 0];
1201 NSScreen *screen = [[view window] screen];
1202
1203 NSTRACE (x_set_offset);
1204
1205 BLOCK_INPUT;
1206
1207 f->left_pos = xoff;
1208 f->top_pos = yoff;
1209
1210 if (view != nil && screen && fscreen)
1211 {
1212 f->left_pos = f->size_hint_flags & XNegative
1213 ? [screen visibleFrame].size.width + f->left_pos - FRAME_PIXEL_WIDTH (f)
1214 : f->left_pos;
1215 /* We use visibleFrame here to take menu bar into account.
1216 Ideally we should also adjust left/top with visibleFrame.origin. */
1217
1218 f->top_pos = f->size_hint_flags & YNegative
1219 ? ([screen visibleFrame].size.height + f->top_pos
1220 - FRAME_PIXEL_HEIGHT (f) - FRAME_NS_TITLEBAR_HEIGHT (f)
1221 - FRAME_TOOLBAR_HEIGHT (f))
1222 : f->top_pos;
1223 #ifdef NS_IMPL_GNUSTEP
1224 if (f->left_pos < 100)
1225 f->left_pos = 100; /* don't overlap menu */
1226 #endif
1227 /* Constrain the setFrameTopLeftPoint so we don't move behind the
1228 menu bar. */
1229 f->output_data.ns->dont_constrain = 0;
1230 [[view window] setFrameTopLeftPoint:
1231 NSMakePoint (SCREENMAXBOUND (f->left_pos),
1232 SCREENMAXBOUND ([fscreen frame].size.height
1233 - NS_TOP_POS (f)))];
1234 f->size_hint_flags &= ~(XNegative|YNegative);
1235 }
1236
1237 UNBLOCK_INPUT;
1238 }
1239
1240
1241 void
1242 x_set_window_size (struct frame *f, int change_grav, int cols, int rows)
1243 /* --------------------------------------------------------------------------
1244 Adjust window pixel size based on given character grid size
1245 Impl is a bit more complex than other terms, need to do some
1246 internal clipping.
1247 -------------------------------------------------------------------------- */
1248 {
1249 EmacsView *view = FRAME_NS_VIEW (f);
1250 EmacsToolbar *toolbar = [view toolbar];
1251 NSWindow *window = [view window];
1252 NSRect wr = [window frame];
1253 int tb = FRAME_EXTERNAL_TOOL_BAR (f);
1254 int pixelwidth, pixelheight;
1255 static int oldRows, oldCols, oldFontWidth, oldFontHeight;
1256 static int oldTB;
1257 static struct frame *oldF;
1258
1259 NSTRACE (x_set_window_size);
1260
1261 if (view == nil ||
1262 (f == oldF
1263 && rows == oldRows && cols == oldCols
1264 && oldFontWidth == FRAME_COLUMN_WIDTH (f)
1265 && oldFontHeight == FRAME_LINE_HEIGHT (f)
1266 && oldTB == tb))
1267 return;
1268
1269 /*fprintf (stderr, "\tsetWindowSize: %d x %d, font size %d x %d\n", cols, rows, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f)); */
1270
1271 BLOCK_INPUT;
1272
1273 check_frame_size (f, &rows, &cols);
1274 oldF = f;
1275 oldRows = rows;
1276 oldCols = cols;
1277 oldFontWidth = FRAME_COLUMN_WIDTH (f);
1278 oldFontHeight = FRAME_LINE_HEIGHT (f);
1279 oldTB = tb;
1280
1281 f->scroll_bar_actual_width = NS_SCROLL_BAR_WIDTH (f);
1282 compute_fringe_widths (f, 0);
1283
1284 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols);
1285 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
1286
1287 /* If we have a toolbar, take its height into account. */
1288 if (tb)
1289 /* NOTE: previously this would generate wrong result if toolbar not
1290 yet displayed and fixing toolbar_height=32 helped, but
1291 now (200903) seems no longer needed */
1292 FRAME_TOOLBAR_HEIGHT (f) =
1293 NSHeight ([window frameRectForContentRect: NSMakeRect (0, 0, 0, 0)])
1294 - FRAME_NS_TITLEBAR_HEIGHT (f);
1295 else
1296 FRAME_TOOLBAR_HEIGHT (f) = 0;
1297
1298 wr.size.width = pixelwidth + f->border_width;
1299 wr.size.height = pixelheight + FRAME_NS_TITLEBAR_HEIGHT (f)
1300 + FRAME_TOOLBAR_HEIGHT (f);
1301
1302 /* Do not try to constrain to this screen. We may have multiple
1303 screens, and want Emacs to span those. Constraining to screen
1304 prevents that, and that is not nice to the user. */
1305 if (f->output_data.ns->zooming)
1306 f->output_data.ns->zooming = 0;
1307 else
1308 wr.origin.y += FRAME_PIXEL_HEIGHT (f) - pixelheight;
1309
1310 [view setRows: rows andColumns: cols];
1311 [window setFrame: wr display: YES];
1312
1313 /*fprintf (stderr, "\tx_set_window_size %d, %d\t%d, %d\n", cols, rows, pixelwidth, pixelheight); */
1314
1315 /* This is a trick to compensate for Emacs' managing the scrollbar area
1316 as a fixed number of standard character columns. Instead of leaving
1317 blank space for the extra, we chopped it off above. Now for
1318 left-hand scrollbars, we shift all rendering to the left by the
1319 difference between the real width and Emacs' imagined one. For
1320 right-hand bars, don't worry about it since the extra is never used.
1321 (Obviously doesn't work for vertically split windows tho..) */
1322 {
1323 NSPoint origin = FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f)
1324 ? NSMakePoint (FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f)
1325 - NS_SCROLL_BAR_WIDTH (f), 0)
1326 : NSMakePoint (0, 0);
1327 [view setFrame: NSMakeRect (0, 0, pixelwidth, pixelheight)];
1328 [view setBoundsOrigin: origin];
1329 }
1330
1331 change_frame_size (f, rows, cols, 0, 1, 0); /* pretend, delay, safe */
1332 FRAME_PIXEL_WIDTH (f) = pixelwidth;
1333 FRAME_PIXEL_HEIGHT (f) = pixelheight;
1334 /* SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */
1335
1336 mark_window_cursors_off (XWINDOW (f->root_window));
1337 cancel_mouse_face (f);
1338
1339 UNBLOCK_INPUT;
1340 }
1341
1342
1343
1344 /* ==========================================================================
1345
1346 Color management
1347
1348 ========================================================================== */
1349
1350
1351 NSColor *
1352 ns_lookup_indexed_color (unsigned long idx, struct frame *f)
1353 {
1354 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1355 if (idx < 1 || idx >= color_table->avail)
1356 return nil;
1357 return color_table->colors[idx];
1358 }
1359
1360
1361 unsigned long
1362 ns_index_color (NSColor *color, struct frame *f)
1363 {
1364 struct ns_color_table *color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1365 ptrdiff_t idx;
1366 ptrdiff_t i;
1367
1368 if (!color_table->colors)
1369 {
1370 color_table->size = NS_COLOR_CAPACITY;
1371 color_table->avail = 1; /* skip idx=0 as marker */
1372 color_table->colors
1373 = (NSColor **)xmalloc (color_table->size * sizeof (NSColor *));
1374 color_table->colors[0] = nil;
1375 color_table->empty_indices = [[NSMutableSet alloc] init];
1376 }
1377
1378 /* do we already have this color ? */
1379 for (i = 1; i < color_table->avail; i++)
1380 if (color_table->colors[i] && [color_table->colors[i] isEqual: color])
1381 return i;
1382
1383 if ([color_table->empty_indices count] > 0)
1384 {
1385 NSNumber *index = [color_table->empty_indices anyObject];
1386 [color_table->empty_indices removeObject: index];
1387 idx = [index unsignedLongValue];
1388 }
1389 else
1390 {
1391 if (color_table->avail == color_table->size)
1392 color_table->colors =
1393 xpalloc (color_table->colors, &color_table->size, 1,
1394 min (ULONG_MAX, PTRDIFF_MAX), sizeof *color_table->colors);
1395 idx = color_table->avail++;
1396 }
1397
1398 color_table->colors[idx] = color;
1399 [color retain];
1400 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1401 return idx;
1402 }
1403
1404
1405 void
1406 ns_free_indexed_color (unsigned long idx, struct frame *f)
1407 {
1408 struct ns_color_table *color_table;
1409 NSColor *color;
1410 NSNumber *index;
1411
1412 if (!f)
1413 return;
1414
1415 color_table = FRAME_NS_DISPLAY_INFO (f)->color_table;
1416
1417 if (idx <= 0 || idx >= color_table->size) {
1418 message1 ("ns_free_indexed_color: Color index out of range.\n");
1419 return;
1420 }
1421
1422 index = [NSNumber numberWithUnsignedInt: idx];
1423 if ([color_table->empty_indices containsObject: index]) {
1424 message1 ("ns_free_indexed_color: attempt to free already freed color.\n");
1425 return;
1426 }
1427
1428 color = color_table->colors[idx];
1429 [color release];
1430 color_table->colors[idx] = nil;
1431 [color_table->empty_indices addObject: index];
1432 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1433 }
1434
1435
1436 static int
1437 ns_get_color (const char *name, NSColor **col)
1438 /* --------------------------------------------------------------------------
1439 Parse a color name
1440 -------------------------------------------------------------------------- */
1441 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1442 X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1443 See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1444 {
1445 NSColor *new = nil;
1446 static char hex[20];
1447 int scaling;
1448 float r = -1.0, g, b;
1449 NSString *nsname = [NSString stringWithUTF8String: name];
1450
1451 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1452 BLOCK_INPUT;
1453
1454 if ([nsname isEqualToString: @"ns_selection_color"])
1455 {
1456 nsname = ns_selection_color;
1457 name = [ns_selection_color UTF8String];
1458 }
1459
1460 /* First, check for some sort of numeric specification. */
1461 hex[0] = '\0';
1462
1463 if (name[0] == '0' || name[0] == '1' || name[0] == '.') /* RGB decimal */
1464 {
1465 NSScanner *scanner = [NSScanner scannerWithString: nsname];
1466 [scanner scanFloat: &r];
1467 [scanner scanFloat: &g];
1468 [scanner scanFloat: &b];
1469 }
1470 else if (!strncmp(name, "rgb:", 4)) /* A newer X11 format -- rgb:r/g/b */
1471 {
1472 strncpy (hex, name + 4, 19);
1473 hex[19] = '\0';
1474 scaling = (strlen(hex) - 2) / 3;
1475 }
1476 else if (name[0] == '#') /* An old X11 format; convert to newer */
1477 {
1478 int len = (strlen(name) - 1);
1479 int start = (len % 3 == 0) ? 1 : len / 4 + 1;
1480 int i;
1481 scaling = strlen(name+start) / 3;
1482 for (i=0; i<3; i++) {
1483 strncpy(hex + i * (scaling + 1), name + start + i * scaling, scaling);
1484 hex[(i+1) * (scaling + 1) - 1] = '/';
1485 }
1486 hex[3 * (scaling + 1) - 1] = '\0';
1487 }
1488
1489 if (hex[0])
1490 {
1491 int rr, gg, bb;
1492 float fscale = scaling == 4 ? 65535.0 : (scaling == 2 ? 255.0 : 15.0);
1493 if (sscanf (hex, "%x/%x/%x", &rr, &gg, &bb))
1494 {
1495 r = rr / fscale;
1496 g = gg / fscale;
1497 b = bb / fscale;
1498 }
1499 }
1500
1501 if (r >= 0.0)
1502 {
1503 *col = [NSColor colorWithCalibratedRed: r green: g blue: b alpha: 1.0];
1504 UNBLOCK_INPUT;
1505 return 0;
1506 }
1507
1508 /* Otherwise, color is expected to be from a list */
1509 {
1510 NSEnumerator *lenum, *cenum;
1511 NSString *name;
1512 NSColorList *clist;
1513
1514 #ifdef NS_IMPL_GNUSTEP
1515 /* XXX: who is wrong, the requestor or the implementation? */
1516 if ([nsname compare: @"Highlight" options: NSCaseInsensitiveSearch]
1517 == NSOrderedSame)
1518 nsname = @"highlightColor";
1519 #endif
1520
1521 lenum = [[NSColorList availableColorLists] objectEnumerator];
1522 while ( (clist = [lenum nextObject]) && new == nil)
1523 {
1524 cenum = [[clist allKeys] objectEnumerator];
1525 while ( (name = [cenum nextObject]) && new == nil )
1526 {
1527 if ([name compare: nsname
1528 options: NSCaseInsensitiveSearch] == NSOrderedSame )
1529 new = [clist colorWithKey: name];
1530 }
1531 }
1532 }
1533
1534 if (new)
1535 *col = [new colorUsingColorSpaceName: NSCalibratedRGBColorSpace];
1536 UNBLOCK_INPUT;
1537 return new ? 0 : 1;
1538 }
1539
1540
1541 static NSColor *
1542 ns_get_color_default (const char *name, NSColor *dflt)
1543 /* --------------------------------------------------------------------------
1544 Parse a color or use a default value
1545 -------------------------------------------------------------------------- */
1546 {
1547 NSColor * col;
1548
1549 if (ns_get_color (name, &col))
1550 return dflt;
1551 else
1552 return col;
1553 }
1554
1555
1556 int
1557 ns_lisp_to_color (Lisp_Object color, NSColor **col)
1558 /* --------------------------------------------------------------------------
1559 Convert a Lisp string object to a NS color
1560 -------------------------------------------------------------------------- */
1561 {
1562 NSTRACE (ns_lisp_to_color);
1563 if (STRINGP (color))
1564 return ns_get_color (SDATA (color), col);
1565 else if (SYMBOLP (color))
1566 return ns_get_color (SDATA (SYMBOL_NAME (color)), col);
1567 return 1;
1568 }
1569
1570
1571 Lisp_Object
1572 ns_color_to_lisp (NSColor *col)
1573 /* --------------------------------------------------------------------------
1574 Convert a color to a lisp string with the RGB equivalent
1575 -------------------------------------------------------------------------- */
1576 {
1577 CGFloat red, green, blue, alpha, gray;
1578 char buf[1024];
1579 const char *str;
1580 NSTRACE (ns_color_to_lisp);
1581
1582 BLOCK_INPUT;
1583 if ([[col colorSpaceName] isEqualToString: NSNamedColorSpace])
1584
1585 if ((str =[[col colorNameComponent] UTF8String]))
1586 {
1587 UNBLOCK_INPUT;
1588 return build_string ((char *)str);
1589 }
1590
1591 [[col colorUsingColorSpaceName: NSCalibratedRGBColorSpace]
1592 getRed: &red green: &green blue: &blue alpha: &alpha];
1593 if (red ==green && red ==blue)
1594 {
1595 [[col colorUsingColorSpaceName: NSCalibratedWhiteColorSpace]
1596 getWhite: &gray alpha: &alpha];
1597 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1598 lrint (gray * 0xff), lrint (gray * 0xff), lrint (gray * 0xff));
1599 UNBLOCK_INPUT;
1600 return build_string (buf);
1601 }
1602
1603 snprintf (buf, sizeof (buf), "#%2.2lx%2.2lx%2.2lx",
1604 lrint (red*0xff), lrint (green*0xff), lrint (blue*0xff));
1605
1606 UNBLOCK_INPUT;
1607 return build_string (buf);
1608 }
1609
1610
1611 void
1612 ns_query_color(void *col, XColor *color_def, int setPixel)
1613 /* --------------------------------------------------------------------------
1614 Get ARGB values out of NSColor col and put them into color_def.
1615 If setPixel, set the pixel to a concatenated version.
1616 and set color_def pixel to the resulting index.
1617 -------------------------------------------------------------------------- */
1618 {
1619 CGFloat r, g, b, a;
1620
1621 [((NSColor *)col) getRed: &r green: &g blue: &b alpha: &a];
1622 color_def->red = r * 65535;
1623 color_def->green = g * 65535;
1624 color_def->blue = b * 65535;
1625
1626 if (setPixel == YES)
1627 color_def->pixel
1628 = ARGB_TO_ULONG((int)(a*255),
1629 (int)(r*255), (int)(g*255), (int)(b*255));
1630 }
1631
1632
1633 int
1634 ns_defined_color (struct frame *f,
1635 const char *name,
1636 XColor *color_def,
1637 int alloc,
1638 char makeIndex)
1639 /* --------------------------------------------------------------------------
1640 Return 1 if named color found, and set color_def rgb accordingly.
1641 If makeIndex and alloc are nonzero put the color in the color_table,
1642 and set color_def pixel to the resulting index.
1643 If makeIndex is zero, set color_def pixel to ARGB.
1644 Return 0 if not found
1645 -------------------------------------------------------------------------- */
1646 {
1647 NSColor *col;
1648 NSTRACE (ns_defined_color);
1649
1650 BLOCK_INPUT;
1651 if (ns_get_color (name, &col) != 0) /* Color not found */
1652 {
1653 UNBLOCK_INPUT;
1654 return 0;
1655 }
1656 if (makeIndex && alloc)
1657 color_def->pixel = ns_index_color (col, f);
1658 ns_query_color (col, color_def, !makeIndex);
1659 UNBLOCK_INPUT;
1660 return 1;
1661 }
1662
1663
1664 unsigned long
1665 ns_get_rgb_color (struct frame *f, float r, float g, float b, float a)
1666 /* --------------------------------------------------------------------------
1667 return an autoreleased RGB color
1668 -------------------------------------------------------------------------- */
1669 {
1670 /*static int c = 1; fprintf (stderr, "color request %d\n", c++); */
1671 if (r < 0.0) r = 0.0;
1672 else if (r > 1.0) r = 1.0;
1673 if (g < 0.0) g = 0.0;
1674 else if (g > 1.0) g = 1.0;
1675 if (b < 0.0) b = 0.0;
1676 else if (b > 1.0) b = 1.0;
1677 if (a < 0.0) a = 0.0;
1678 else if (a > 1.0) a = 1.0;
1679 return (unsigned long) ns_index_color(
1680 [NSColor colorWithCalibratedRed: r green: g blue: b alpha: a], f);
1681 }
1682
1683
1684 void
1685 x_set_frame_alpha (struct frame *f)
1686 /* --------------------------------------------------------------------------
1687 change the entire-frame transparency
1688 -------------------------------------------------------------------------- */
1689 {
1690 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1691 EmacsView *view = FRAME_NS_VIEW (f);
1692 double alpha = 1.0;
1693 double alpha_min = 1.0;
1694
1695 if (dpyinfo->x_highlight_frame == f)
1696 alpha = f->alpha[0];
1697 else
1698 alpha = f->alpha[1];
1699
1700 if (FLOATP (Vframe_alpha_lower_limit))
1701 alpha_min = XFLOAT_DATA (Vframe_alpha_lower_limit);
1702 else if (INTEGERP (Vframe_alpha_lower_limit))
1703 alpha_min = (XINT (Vframe_alpha_lower_limit)) / 100.0;
1704
1705 if (alpha < 0.0)
1706 return;
1707 else if (1.0 < alpha)
1708 alpha = 1.0;
1709 else if (0.0 <= alpha && alpha < alpha_min && alpha_min <= 1.0)
1710 alpha = alpha_min;
1711
1712 #ifdef NS_IMPL_COCOA
1713 [[view window] setAlphaValue: alpha];
1714 #endif
1715 }
1716
1717
1718 /* ==========================================================================
1719
1720 Mouse handling
1721
1722 ========================================================================== */
1723
1724
1725 void
1726 x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y)
1727 /* --------------------------------------------------------------------------
1728 Programmatically reposition mouse pointer in pixel coordinates
1729 -------------------------------------------------------------------------- */
1730 {
1731 NSTRACE (x_set_mouse_pixel_position);
1732 ns_raise_frame (f);
1733 #if 0
1734 /* FIXME: this does not work, and what about GNUstep? */
1735 #ifdef NS_IMPL_COCOA
1736 [FRAME_NS_VIEW (f) lockFocus];
1737 PSsetmouse ((float)pix_x, (float)pix_y);
1738 [FRAME_NS_VIEW (f) unlockFocus];
1739 #endif
1740 #endif
1741 }
1742
1743
1744 void
1745 x_set_mouse_position (struct frame *f, int h, int v)
1746 /* --------------------------------------------------------------------------
1747 Programmatically reposition mouse pointer in character coordinates
1748 -------------------------------------------------------------------------- */
1749 {
1750 int pix_x, pix_y;
1751
1752 pix_x = FRAME_COL_TO_PIXEL_X (f, h) + FRAME_COLUMN_WIDTH (f) / 2;
1753 pix_y = FRAME_LINE_TO_PIXEL_Y (f, v) + FRAME_LINE_HEIGHT (f) / 2;
1754
1755 if (pix_x < 0) pix_x = 0;
1756 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
1757
1758 if (pix_y < 0) pix_y = 0;
1759 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
1760
1761 x_set_mouse_pixel_position (f, pix_x, pix_y);
1762 }
1763
1764
1765 static int
1766 note_mouse_movement (struct frame *frame, float x, float y)
1767 /* ------------------------------------------------------------------------
1768 Called by EmacsView on mouseMovement events. Passes on
1769 to emacs mainstream code if we moved off of a rect of interest
1770 known as last_mouse_glyph.
1771 ------------------------------------------------------------------------ */
1772 {
1773 // NSTRACE (note_mouse_movement);
1774
1775 XSETFRAME (last_mouse_motion_frame, frame);
1776
1777 /* Note, this doesn't get called for enter/leave, since we don't have a
1778 position. Those are taken care of in the corresponding NSView methods. */
1779
1780 /* has movement gone beyond last rect we were tracking? */
1781 if (x < last_mouse_glyph.origin.x ||
1782 x >= (last_mouse_glyph.origin.x + last_mouse_glyph.size.width) ||
1783 y < last_mouse_glyph.origin.y ||
1784 y >= (last_mouse_glyph.origin.y + last_mouse_glyph.size.height))
1785 {
1786 ns_update_begin(frame);
1787 frame->mouse_moved = 1;
1788 note_mouse_highlight (frame, x, y);
1789 remember_mouse_glyph (frame, x, y, &last_mouse_glyph);
1790 ns_update_end(frame);
1791 return 1;
1792 }
1793
1794 return 0;
1795 }
1796
1797
1798 static void
1799 ns_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
1800 enum scroll_bar_part *part, Lisp_Object *x, Lisp_Object *y,
1801 Time *time)
1802 /* --------------------------------------------------------------------------
1803 External (hook): inform emacs about mouse position and hit parts.
1804 If a scrollbar is being dragged, set bar_window, part, x, y, time.
1805 x & y should be position in the scrollbar (the whole bar, not the handle)
1806 and length of scrollbar respectively
1807 -------------------------------------------------------------------------- */
1808 {
1809 id view;
1810 NSPoint position;
1811 int xchar, ychar;
1812 Lisp_Object frame, tail;
1813 struct frame *f;
1814 struct ns_display_info *dpyinfo;
1815
1816 NSTRACE (ns_mouse_position);
1817
1818 if (*fp == NULL)
1819 {
1820 fprintf (stderr, "Warning: ns_mouse_position () called with null *fp.\n");
1821 return;
1822 }
1823
1824 dpyinfo = FRAME_NS_DISPLAY_INFO (*fp);
1825
1826 BLOCK_INPUT;
1827
1828 if (last_mouse_scroll_bar != nil && insist == 0)
1829 {
1830 /* TODO: we do not use this path at the moment because drag events will
1831 go directly to the EmacsScroller. Leaving code in for now. */
1832 [last_mouse_scroll_bar getMouseMotionPart: (int *)part window: bar_window
1833 x: x y: y];
1834 if (time) *time = last_mouse_movement_time;
1835 last_mouse_scroll_bar = nil;
1836 }
1837 else
1838 {
1839 /* Clear the mouse-moved flag for every frame on this display. */
1840 FOR_EACH_FRAME (tail, frame)
1841 if (FRAME_NS_P (XFRAME (frame))
1842 && FRAME_NS_DISPLAY (XFRAME (frame)) == FRAME_NS_DISPLAY (*fp))
1843 XFRAME (frame)->mouse_moved = 0;
1844
1845 last_mouse_scroll_bar = nil;
1846 if (last_mouse_frame && FRAME_LIVE_P (last_mouse_frame))
1847 f = last_mouse_frame;
1848 else
1849 f = dpyinfo->x_focus_frame ? dpyinfo->x_focus_frame
1850 : SELECTED_FRAME ();
1851
1852 if (f && f->output_data.ns) /* TODO: 2nd check no longer needed? */
1853 {
1854 view = FRAME_NS_VIEW (*fp);
1855
1856 position = [[view window] mouseLocationOutsideOfEventStream];
1857 position = [view convertPoint: position fromView: nil];
1858 remember_mouse_glyph (f, position.x, position.y, &last_mouse_glyph);
1859 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1860
1861 if (bar_window) *bar_window = Qnil;
1862 if (part) *part = 0; /*scroll_bar_handle; */
1863
1864 if (x) XSETINT (*x, lrint (position.x));
1865 if (y) XSETINT (*y, lrint (position.y));
1866 if (time) *time = last_mouse_movement_time;
1867 *fp = f;
1868 }
1869 }
1870
1871 UNBLOCK_INPUT;
1872 }
1873
1874
1875 static void
1876 ns_frame_up_to_date (struct frame *f)
1877 /* --------------------------------------------------------------------------
1878 External (hook): Fix up mouse highlighting right after a full update.
1879 Some highlighting was deferred if GC was happening during
1880 note_mouse_highlight (), while other highlighting was deferred for update.
1881 -------------------------------------------------------------------------- */
1882 {
1883 NSTRACE (ns_frame_up_to_date);
1884
1885 if (FRAME_NS_P (f))
1886 {
1887 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
1888 if ((hlinfo->mouse_face_deferred_gc || f ==hlinfo->mouse_face_mouse_frame)
1889 /*&& hlinfo->mouse_face_mouse_frame*/)
1890 {
1891 BLOCK_INPUT;
1892 ns_update_begin(f);
1893 if (hlinfo->mouse_face_mouse_frame)
1894 note_mouse_highlight (hlinfo->mouse_face_mouse_frame,
1895 hlinfo->mouse_face_mouse_x,
1896 hlinfo->mouse_face_mouse_y);
1897 hlinfo->mouse_face_deferred_gc = 0;
1898 ns_update_end(f);
1899 UNBLOCK_INPUT;
1900 }
1901 }
1902 }
1903
1904
1905 void
1906 ns_define_frame_cursor (struct frame *f, Cursor cursor)
1907 /* --------------------------------------------------------------------------
1908 External (RIF): set frame mouse pointer type.
1909 -------------------------------------------------------------------------- */
1910 {
1911 NSTRACE (ns_define_frame_cursor);
1912 if (FRAME_POINTER_TYPE (f) != cursor)
1913 {
1914 EmacsView *view = FRAME_NS_VIEW (f);
1915 FRAME_POINTER_TYPE (f) = cursor;
1916 [[view window] invalidateCursorRectsForView: view];
1917 /* Redisplay assumes this function also draws the changed frame
1918 cursor, but this function doesn't, so do it explicitly. */
1919 x_update_cursor (f, 1);
1920 }
1921 }
1922
1923
1924
1925 /* ==========================================================================
1926
1927 Keyboard handling
1928
1929 ========================================================================== */
1930
1931
1932 static unsigned
1933 ns_convert_key (unsigned code)
1934 /* --------------------------------------------------------------------------
1935 Internal call used by NSView-keyDown.
1936 -------------------------------------------------------------------------- */
1937 {
1938 const unsigned last_keysym = (sizeof (convert_ns_to_X_keysym)
1939 / sizeof (convert_ns_to_X_keysym[0]));
1940 unsigned keysym;
1941 /* An array would be faster, but less easy to read. */
1942 for (keysym = 0; keysym < last_keysym; keysym += 2)
1943 if (code == convert_ns_to_X_keysym[keysym])
1944 return 0xFF00 | convert_ns_to_X_keysym[keysym+1];
1945 return 0;
1946 /* if decide to use keyCode and Carbon table, use this line:
1947 return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
1948 }
1949
1950
1951 char *
1952 x_get_keysym_name (int keysym)
1953 /* --------------------------------------------------------------------------
1954 Called by keyboard.c. Not sure if the return val is important, except
1955 that it be unique.
1956 -------------------------------------------------------------------------- */
1957 {
1958 static char value[16];
1959 NSTRACE (x_get_keysym_name);
1960 sprintf (value, "%d", keysym);
1961 return value;
1962 }
1963
1964
1965
1966 /* ==========================================================================
1967
1968 Block drawing operations
1969
1970 ========================================================================== */
1971
1972
1973 static void
1974 ns_redraw_scroll_bars (struct frame *f)
1975 {
1976 int i;
1977 id view;
1978 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
1979 NSTRACE (ns_judge_scroll_bars);
1980 for (i =[subviews count]-1; i >= 0; i--)
1981 {
1982 view = [subviews objectAtIndex: i];
1983 if (![view isKindOfClass: [EmacsScroller class]]) continue;
1984 [view display];
1985 }
1986 }
1987
1988
1989 void
1990 ns_clear_frame (struct frame *f)
1991 /* --------------------------------------------------------------------------
1992 External (hook): Erase the entire frame
1993 -------------------------------------------------------------------------- */
1994 {
1995 NSView *view = FRAME_NS_VIEW (f);
1996 NSRect r;
1997
1998 NSTRACE (ns_clear_frame);
1999 if (ns_in_resize)
2000 return;
2001
2002 /* comes on initial frame because we have
2003 after-make-frame-functions = select-frame */
2004 if (!FRAME_DEFAULT_FACE (f))
2005 return;
2006
2007 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
2008
2009 output_cursor.hpos = output_cursor.vpos = 0;
2010 output_cursor.x = -1;
2011
2012 r = [view bounds];
2013
2014 BLOCK_INPUT;
2015 ns_focus (f, &r, 1);
2016 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (FRAME_DEFAULT_FACE (f)), f) set];
2017 NSRectFill (r);
2018 ns_unfocus (f);
2019
2020 #ifdef NS_IMPL_COCOA
2021 [[view window] display]; /* redraw resize handle */
2022 #endif
2023
2024 /* as of 2006/11 or so this is now needed */
2025 ns_redraw_scroll_bars (f);
2026 UNBLOCK_INPUT;
2027 }
2028
2029
2030 void
2031 ns_clear_frame_area (struct frame *f, int x, int y, int width, int height)
2032 /* --------------------------------------------------------------------------
2033 External (RIF): Clear section of frame
2034 -------------------------------------------------------------------------- */
2035 {
2036 NSRect r = NSMakeRect (x, y, width, height);
2037 NSView *view = FRAME_NS_VIEW (f);
2038 struct face *face = FRAME_DEFAULT_FACE (f);
2039
2040 if (!view || !face)
2041 return;
2042
2043 NSTRACE (ns_clear_frame_area);
2044
2045 r = NSIntersectionRect (r, [view frame]);
2046 ns_focus (f, &r, 1);
2047 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f) set];
2048
2049 #ifdef NS_IMPL_COCOA
2050 {
2051 /* clip out the resize handle */
2052 NSWindow *window = [FRAME_NS_VIEW (f) window];
2053 NSRect ir
2054 = [view convertRect: ns_resize_handle_rect (window) fromView: nil];
2055
2056 ir = NSIntersectionRect (r, ir);
2057 if (NSIsEmptyRect (ir))
2058 {
2059 #endif
2060
2061 NSRectFill (r);
2062
2063 #ifdef NS_IMPL_COCOA
2064 }
2065 else
2066 {
2067 NSRect r1 = r, r2 = r; /* upper and lower non-intersecting */
2068 r1.size.height -= ir.size.height;
2069 r2.origin.y += r1.size.height;
2070 r2.size.width -= ir.size.width;
2071 r2.size.height = ir.size.height;
2072 NSRectFill (r1);
2073 NSRectFill (r2);
2074 }
2075 }
2076 #endif
2077
2078 ns_unfocus (f);
2079 return;
2080 }
2081
2082
2083 static void
2084 ns_scroll_run (struct window *w, struct run *run)
2085 /* --------------------------------------------------------------------------
2086 External (RIF): Insert or delete n lines at line vpos
2087 -------------------------------------------------------------------------- */
2088 {
2089 struct frame *f = XFRAME (w->frame);
2090 int x, y, width, height, from_y, to_y, bottom_y;
2091
2092 NSTRACE (ns_scroll_run);
2093
2094 /* begin copy from other terms */
2095 /* Get frame-relative bounding box of the text display area of W,
2096 without mode lines. Include in this box the left and right
2097 fringe of W. */
2098 window_box (w, -1, &x, &y, &width, &height);
2099
2100 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2101 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2102 bottom_y = y + height;
2103
2104 if (to_y < from_y)
2105 {
2106 /* Scrolling up. Make sure we don't copy part of the mode
2107 line at the bottom. */
2108 if (from_y + run->height > bottom_y)
2109 height = bottom_y - from_y;
2110 else
2111 height = run->height;
2112 }
2113 else
2114 {
2115 /* Scrolling down. Make sure we don't copy over the mode line.
2116 at the bottom. */
2117 if (to_y + run->height > bottom_y)
2118 height = bottom_y - to_y;
2119 else
2120 height = run->height;
2121 }
2122 /* end copy from other terms */
2123
2124 if (height == 0)
2125 return;
2126
2127 BLOCK_INPUT;
2128
2129 updated_window = w;
2130 x_clear_cursor (w);
2131
2132 {
2133 NSRect srcRect = NSMakeRect (x, from_y, width, height);
2134 NSRect dstRect = NSMakeRect (x, to_y, width, height);
2135 NSPoint dstOrigin = NSMakePoint (x, to_y);
2136
2137 ns_focus (f, &dstRect, 1);
2138 NSCopyBits (0, srcRect , dstOrigin);
2139 ns_unfocus (f);
2140 }
2141
2142 UNBLOCK_INPUT;
2143 }
2144
2145
2146 static void
2147 ns_after_update_window_line (struct glyph_row *desired_row)
2148 /* --------------------------------------------------------------------------
2149 External (RIF): preparatory to fringe update after text was updated
2150 -------------------------------------------------------------------------- */
2151 {
2152 struct window *w = updated_window;
2153 struct frame *f;
2154 int width, height;
2155
2156 NSTRACE (ns_after_update_window_line);
2157
2158 /* begin copy from other terms */
2159 xassert (w);
2160
2161 if (!desired_row->mode_line_p && !w->pseudo_window_p)
2162 desired_row->redraw_fringe_bitmaps_p = 1;
2163
2164 /* When a window has disappeared, make sure that no rest of
2165 full-width rows stays visible in the internal border.
2166 Under NS this is drawn inside the fringes. */
2167 if (windows_or_buffers_changed
2168 && (f = XFRAME (w->frame),
2169 width = FRAME_INTERNAL_BORDER_WIDTH (f),
2170 width != 0)
2171 && (height = desired_row->visible_height,
2172 height > 0))
2173 {
2174 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2175
2176 /* Internal border is drawn below the tool bar. */
2177 if (WINDOWP (f->tool_bar_window)
2178 && w == XWINDOW (f->tool_bar_window))
2179 y -= width;
2180 /* end copy from other terms */
2181
2182 BLOCK_INPUT;
2183 if (!desired_row->full_width_p)
2184 {
2185 int x1 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2186 + WINDOW_LEFT_FRINGE_WIDTH (w);
2187 int x2 = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
2188 + FRAME_PIXEL_WIDTH (f) - NS_SCROLL_BAR_WIDTH (f)
2189 - WINDOW_RIGHT_FRINGE_WIDTH (w)
2190 - FRAME_INTERNAL_BORDER_WIDTH (f);
2191 ns_clear_frame_area (f, x1, y, width, height);
2192 ns_clear_frame_area (f, x2, y, width, height);
2193 }
2194 UNBLOCK_INPUT;
2195 }
2196 }
2197
2198
2199 static void
2200 ns_shift_glyphs_for_insert (struct frame *f,
2201 int x, int y, int width, int height,
2202 int shift_by)
2203 /* --------------------------------------------------------------------------
2204 External (RIF): copy an area horizontally, don't worry about clearing src
2205 -------------------------------------------------------------------------- */
2206 {
2207 NSRect srcRect = NSMakeRect (x, y, width, height);
2208 NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2209 NSPoint dstOrigin = dstRect.origin;
2210
2211 NSTRACE (ns_shift_glyphs_for_insert);
2212
2213 ns_focus (f, &dstRect, 1);
2214 NSCopyBits (0, srcRect, dstOrigin);
2215 ns_unfocus (f);
2216 }
2217
2218
2219
2220 /* ==========================================================================
2221
2222 Character encoding and metrics
2223
2224 ========================================================================== */
2225
2226
2227 static inline void
2228 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2229 /* --------------------------------------------------------------------------
2230 External (RIF); compute left/right overhang of whole string and set in s
2231 -------------------------------------------------------------------------- */
2232 {
2233 struct face *face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2234 struct font *font = s->font; /*face->font; */
2235
2236 if (s->char2b)
2237 {
2238 struct font_metrics metrics;
2239 unsigned int codes[2];
2240 codes[0] = *(s->char2b);
2241 codes[1] = *(s->char2b + s->nchars - 1);
2242
2243 font->driver->text_extents (font, codes, 2, &metrics);
2244 s->left_overhang = -metrics.lbearing;
2245 s->right_overhang
2246 = metrics.rbearing > metrics.width
2247 ? metrics.rbearing - metrics.width : 0;
2248 }
2249 else
2250 {
2251 s->left_overhang = 0;
2252 s->right_overhang = ((struct nsfont_info *)font)->ital ?
2253 FONT_HEIGHT (font) * 0.2 : 0;
2254 }
2255 }
2256
2257
2258
2259 /* ==========================================================================
2260
2261 Fringe and cursor drawing
2262
2263 ========================================================================== */
2264
2265
2266 extern int max_used_fringe_bitmap;
2267 static void
2268 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2269 struct draw_fringe_bitmap_params *p)
2270 /* --------------------------------------------------------------------------
2271 External (RIF); fringe-related
2272 -------------------------------------------------------------------------- */
2273 {
2274 struct frame *f = XFRAME (WINDOW_FRAME (w));
2275 struct face *face = p->face;
2276 int rowY;
2277 static EmacsImage **bimgs = NULL;
2278 static int nBimgs = 0;
2279 /* NS-specific: move internal border inside fringe */
2280 int x = p->bx < 0 ? p->x : p->bx;
2281 int wd = p->bx < 0 ? p->wd : p->nx;
2282 BOOL fringeOnVeryLeft
2283 = x - WINDOW_LEFT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w)
2284 - FRAME_INTERNAL_BORDER_WIDTH (f) < 10;
2285 BOOL fringeOnVeryRight
2286 = FRAME_PIXEL_WIDTH (f) - x - wd - FRAME_INTERNAL_BORDER_WIDTH (f)
2287 - WINDOW_RIGHT_SCROLL_BAR_COLS (w) * WINDOW_FRAME_COLUMN_WIDTH (w) < 10;
2288 int xAdjust = FRAME_INTERNAL_BORDER_WIDTH (f) *
2289 (fringeOnVeryLeft ? -1 : (fringeOnVeryRight ? 1 : 0));
2290
2291 /* grow bimgs if needed */
2292 if (nBimgs < max_used_fringe_bitmap)
2293 {
2294 EmacsImage **newBimgs
2295 = xmalloc (max_used_fringe_bitmap * sizeof (EmacsImage *));
2296 memset (newBimgs, 0, max_used_fringe_bitmap * sizeof (EmacsImage *));
2297
2298 if (nBimgs)
2299 {
2300 memcpy (newBimgs, bimgs, nBimgs * sizeof (EmacsImage *));
2301 xfree (bimgs);
2302 }
2303
2304 bimgs = newBimgs;
2305 nBimgs = max_used_fringe_bitmap;
2306 }
2307
2308 /* Must clip because of partially visible lines. */
2309 rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
2310 ns_clip_to_row (w, row, -1, YES);
2311
2312 if (p->bx >= 0 && !p->overlay_p)
2313 {
2314 int yAdjust = rowY - FRAME_INTERNAL_BORDER_WIDTH (f) < 5 ?
2315 -FRAME_INTERNAL_BORDER_WIDTH (f) : 0;
2316 int yIncr = FRAME_PIXEL_HEIGHT (f) - (p->by+yAdjust + p->ny) < 5 ?
2317 FRAME_INTERNAL_BORDER_WIDTH (f) : 0
2318 + (yAdjust ? FRAME_INTERNAL_BORDER_WIDTH (f) : 0);
2319 NSRect r = NSMakeRect (p->bx+xAdjust, p->by+yAdjust, p->nx, p->ny+yIncr);
2320 NSRectClip (r);
2321 [ns_lookup_indexed_color(face->background, f) set];
2322 NSRectFill (r);
2323 }
2324
2325 if (p->which)
2326 {
2327 NSRect r = NSMakeRect (p->x+xAdjust, p->y, p->wd, p->h);
2328 NSPoint pt = r.origin;
2329 EmacsImage *img = bimgs[p->which - 1];
2330
2331 if (!img)
2332 {
2333 unsigned short *bits = p->bits + p->dh;
2334 int len = p->h;
2335 int i;
2336 unsigned char *cbits = xmalloc (len);
2337
2338 for (i =0; i<len; i++)
2339 cbits[i] = ~(bits[i] & 0xff);
2340 img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2341 flip: NO];
2342 bimgs[p->which - 1] = img;
2343 xfree (cbits);
2344 }
2345
2346 NSRectClip (r);
2347 /* Since we composite the bitmap instead of just blitting it, we need
2348 to erase the whole background. */
2349 [ns_lookup_indexed_color(face->background, f) set];
2350 NSRectFill (r);
2351 pt.y += p->h;
2352 [img setXBMColor: ns_lookup_indexed_color(face->foreground, f)];
2353 [img compositeToPoint: pt operation: NSCompositeSourceOver];
2354 }
2355 ns_unfocus (f);
2356 }
2357
2358
2359 void
2360 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2361 int x, int y, int cursor_type, int cursor_width,
2362 int on_p, int active_p)
2363 /* --------------------------------------------------------------------------
2364 External call (RIF): draw cursor.
2365 Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2366 -------------------------------------------------------------------------- */
2367 {
2368 NSRect r, s;
2369 int fx, fy, h, cursor_height;
2370 struct frame *f = WINDOW_XFRAME (w);
2371 struct glyph *phys_cursor_glyph;
2372 int overspill;
2373 struct glyph *cursor_glyph;
2374 struct face *face;
2375 NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2376
2377 /* If cursor is out of bounds, don't draw garbage. This can happen
2378 in mini-buffer windows when switching between echo area glyphs
2379 and mini-buffer. */
2380
2381 NSTRACE (dumpcursor);
2382
2383 if (!on_p)
2384 return;
2385
2386 w->phys_cursor_type = cursor_type;
2387 w->phys_cursor_on_p = on_p;
2388
2389 if (cursor_type == NO_CURSOR)
2390 {
2391 w->phys_cursor_width = 0;
2392 return;
2393 }
2394
2395 if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2396 {
2397 if (glyph_row->exact_window_width_line_p
2398 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2399 {
2400 glyph_row->cursor_in_fringe_p = 1;
2401 draw_fringe_bitmap (w, glyph_row, 0);
2402 }
2403 return;
2404 }
2405
2406 /* We draw the cursor (with NSRectFill), then draw the glyph on top
2407 (other terminals do it the other way round). We must set
2408 w->phys_cursor_width to the cursor width. For bar cursors, that
2409 is CURSOR_WIDTH; for box cursors, it is the glyph width. */
2410 get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2411
2412 /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2413 to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2414 if (cursor_type == BAR_CURSOR)
2415 {
2416 if (cursor_width < 1)
2417 cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2418 w->phys_cursor_width = cursor_width;
2419 }
2420 /* If we have an HBAR, "cursor_width" MAY specify height. */
2421 else if (cursor_type == HBAR_CURSOR)
2422 {
2423 cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2424 fy += h - cursor_height;
2425 h = cursor_height;
2426 }
2427
2428 r.origin.x = fx, r.origin.y = fy;
2429 r.size.height = h;
2430 r.size.width = w->phys_cursor_width;
2431
2432 /* FIXME: if we overwrite the internal border area, it does not get erased;
2433 fix by truncating cursor, but better would be to erase properly */
2434 overspill = r.origin.x + r.size.width -
2435 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, WINDOW_BOX_RIGHT_EDGE_X (w)
2436 - WINDOW_TOTAL_FRINGE_WIDTH (w) - FRAME_INTERNAL_BORDER_WIDTH (f));
2437 if (overspill > 0)
2438 r.size.width -= overspill;
2439
2440 /* TODO: only needed in rare cases with last-resort font in HELLO..
2441 should we do this more efficiently? */
2442 ns_clip_to_row (w, glyph_row, -1, NO); /* do ns_focus(f, &r, 1); if remove */
2443
2444
2445 face = FACE_FROM_ID (f, phys_cursor_glyph->face_id);
2446 if (face && NS_FACE_BACKGROUND (face)
2447 == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2448 {
2449 [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2450 hollow_color = FRAME_CURSOR_COLOR (f);
2451 }
2452 else
2453 [FRAME_CURSOR_COLOR (f) set];
2454
2455 #ifdef NS_IMPL_COCOA
2456 /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2457 atomic. Cleaner ways of doing this should be investigated.
2458 One way would be to set a global variable DRAWING_CURSOR
2459 when making the call to draw_phys..(), don't focus in that
2460 case, then move the ns_unfocus() here after that call. */
2461 NSDisableScreenUpdates ();
2462 #endif
2463
2464 switch (cursor_type)
2465 {
2466 case NO_CURSOR:
2467 break;
2468 case FILLED_BOX_CURSOR:
2469 NSRectFill (r);
2470 break;
2471 case HOLLOW_BOX_CURSOR:
2472 NSRectFill (r);
2473 [hollow_color set];
2474 NSRectFill (NSInsetRect (r, 1, 1));
2475 [FRAME_CURSOR_COLOR (f) set];
2476 break;
2477 case HBAR_CURSOR:
2478 NSRectFill (r);
2479 break;
2480 case BAR_CURSOR:
2481 s = r;
2482 /* If the character under cursor is R2L, draw the bar cursor
2483 on the right of its glyph, rather than on the left. */
2484 cursor_glyph = get_phys_cursor_glyph (w);
2485 if ((cursor_glyph->resolved_level & 1) != 0)
2486 s.origin.x += cursor_glyph->pixel_width - s.size.width;
2487
2488 NSRectFill (s);
2489 break;
2490 }
2491 ns_unfocus (f);
2492
2493 /* draw the character under the cursor */
2494 if (cursor_type != NO_CURSOR)
2495 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2496
2497 #ifdef NS_IMPL_COCOA
2498 NSEnableScreenUpdates ();
2499 #endif
2500
2501 }
2502
2503
2504 static void
2505 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2506 /* --------------------------------------------------------------------------
2507 External (RIF): Draw a vertical line.
2508 -------------------------------------------------------------------------- */
2509 {
2510 struct frame *f = XFRAME (WINDOW_FRAME (w));
2511 struct face *face;
2512 NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2513
2514 NSTRACE (ns_draw_vertical_window_border);
2515
2516 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2517 if (face)
2518 [ns_lookup_indexed_color(face->foreground, f) set];
2519
2520 ns_focus (f, &r, 1);
2521 NSRectFill(r);
2522 ns_unfocus (f);
2523 }
2524
2525
2526 void
2527 show_hourglass (struct atimer *timer)
2528 {
2529 if (hourglass_shown_p)
2530 return;
2531
2532 BLOCK_INPUT;
2533
2534 /* TODO: add NSProgressIndicator to selected frame (see macfns.c) */
2535
2536 hourglass_shown_p = 1;
2537 UNBLOCK_INPUT;
2538 }
2539
2540
2541 void
2542 hide_hourglass (void)
2543 {
2544 if (!hourglass_shown_p)
2545 return;
2546
2547 BLOCK_INPUT;
2548
2549 /* TODO: remove NSProgressIndicator from all frames */
2550
2551 hourglass_shown_p = 0;
2552 UNBLOCK_INPUT;
2553 }
2554
2555
2556
2557 /* ==========================================================================
2558
2559 Glyph drawing operations
2560
2561 ========================================================================== */
2562
2563
2564 static inline NSRect
2565 ns_fix_rect_ibw (NSRect r, int fibw, int frame_pixel_width)
2566 /* --------------------------------------------------------------------------
2567 Under NS we draw internal borders inside fringes, and want full-width
2568 rendering to go all the way to edge. This function makes that correction.
2569 -------------------------------------------------------------------------- */
2570 {
2571 if (r.origin.y <= fibw+1)
2572 {
2573 r.size.height += r.origin.y;
2574 r.origin.y = 0;
2575 }
2576 if (r.origin.x <= fibw+1)
2577 {
2578 r.size.width += r.origin.x;
2579 r.origin.x = 0;
2580 }
2581 if (frame_pixel_width - (r.origin.x+r.size.width) <= fibw+1)
2582 r.size.width += fibw;
2583
2584 return r;
2585 }
2586
2587
2588 static int
2589 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2590 /* --------------------------------------------------------------------------
2591 Wrapper utility to account for internal border width on full-width lines,
2592 and allow top full-width rows to hit the frame top. nr should be pointer
2593 to two successive NSRects. Number of rects actually used is returned.
2594 -------------------------------------------------------------------------- */
2595 {
2596 int n = get_glyph_string_clip_rects (s, nr, 2);
2597 if (s->row->full_width_p)
2598 {
2599 *nr = ns_fix_rect_ibw (*nr, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2600 FRAME_PIXEL_WIDTH (s->f));
2601 if (n == 2)
2602 *nr = ns_fix_rect_ibw (*(nr+1), FRAME_INTERNAL_BORDER_WIDTH (s->f),
2603 FRAME_PIXEL_WIDTH (s->f));
2604 }
2605 return n;
2606 }
2607
2608 void
2609 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
2610 NSColor *defaultCol, CGFloat width, CGFloat x)
2611 /* --------------------------------------------------------------------------
2612 Draw underline, overline, and strike-through on glyph string s.
2613 -------------------------------------------------------------------------- */
2614 {
2615 if (s->for_overlaps)
2616 return;
2617
2618 /* Do underline. */
2619 if (face->underline_p)
2620 {
2621 NSRect r;
2622 unsigned long thickness, position;
2623
2624 /* If the prev was underlined, match its appearance. */
2625 if (s->prev && s->prev->face->underline_p
2626 && s->prev->underline_thickness > 0)
2627 {
2628 thickness = s->prev->underline_thickness;
2629 position = s->prev->underline_position;
2630 }
2631 else
2632 {
2633 struct font *font;
2634 unsigned long descent;
2635
2636 font=s->font;
2637 descent = s->y + s->height - s->ybase;
2638
2639 /* Use underline thickness of font, defaulting to 1. */
2640 thickness = (font && font->underline_thickness > 0)
2641 ? font->underline_thickness : 1;
2642
2643 /* Determine the offset of underlining from the baseline. */
2644 if (x_underline_at_descent_line)
2645 position = descent - thickness;
2646 else if (x_use_underline_position_properties
2647 && font && font->underline_position >= 0)
2648 position = font->underline_position;
2649 else if (font)
2650 position = lround (font->descent / 2);
2651 else
2652 position = underline_minimum_offset;
2653
2654 position = max (position, underline_minimum_offset);
2655
2656 /* Ensure underlining is not cropped. */
2657 if (descent <= position)
2658 {
2659 position = descent - 1;
2660 thickness = 1;
2661 }
2662 else if (descent < position + thickness)
2663 thickness = 1;
2664 }
2665
2666 s->underline_thickness = thickness;
2667 s->underline_position = position;
2668
2669 r = NSMakeRect (x, s->ybase + position, width, thickness);
2670
2671 if (face->underline_defaulted_p)
2672 [defaultCol set];
2673 else
2674 [ns_lookup_indexed_color (face->underline_color, s->f) set];
2675 NSRectFill (r);
2676 }
2677
2678 /* Do overline. We follow other terms in using a thickness of 1
2679 and ignoring overline_margin. */
2680 if (face->overline_p)
2681 {
2682 NSRect r;
2683 r = NSMakeRect (x, s->y, width, 1);
2684
2685 if (face->overline_color_defaulted_p)
2686 [defaultCol set];
2687 else
2688 [ns_lookup_indexed_color (face->overline_color, s->f) set];
2689 NSRectFill (r);
2690 }
2691
2692 /* Do strike-through. We follow other terms for thickness and
2693 vertical position.*/
2694 if (face->strike_through_p)
2695 {
2696 NSRect r;
2697 unsigned long dy;
2698
2699 dy = lrint ((s->height - 1) / 2);
2700 r = NSMakeRect (x, s->y + dy, width, 1);
2701
2702 if (face->strike_through_color_defaulted_p)
2703 [defaultCol set];
2704 else
2705 [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
2706 NSRectFill (r);
2707 }
2708 }
2709
2710 static void
2711 ns_draw_box (NSRect r, float thickness, NSColor *col, char left_p, char right_p)
2712 /* --------------------------------------------------------------------------
2713 Draw an unfilled rect inside r, optionally leaving left and/or right open.
2714 Note we can't just use an NSDrawRect command, because of the possibility
2715 of some sides not being drawn, and because the rect will be filled.
2716 -------------------------------------------------------------------------- */
2717 {
2718 NSRect s = r;
2719 [col set];
2720
2721 /* top, bottom */
2722 s.size.height = thickness;
2723 NSRectFill (s);
2724 s.origin.y += r.size.height - thickness;
2725 NSRectFill (s);
2726
2727 s.size.height = r.size.height;
2728 s.origin.y = r.origin.y;
2729
2730 /* left, right (optional) */
2731 s.size.width = thickness;
2732 if (left_p)
2733 NSRectFill (s);
2734 if (right_p)
2735 {
2736 s.origin.x += r.size.width - thickness;
2737 NSRectFill (s);
2738 }
2739 }
2740
2741
2742 static void
2743 ns_draw_relief (NSRect r, int thickness, char raised_p,
2744 char top_p, char bottom_p, char left_p, char right_p,
2745 struct glyph_string *s)
2746 /* --------------------------------------------------------------------------
2747 Draw a relief rect inside r, optionally leaving some sides open.
2748 Note we can't just use an NSDrawBezel command, because of the possibility
2749 of some sides not being drawn, and because the rect will be filled.
2750 -------------------------------------------------------------------------- */
2751 {
2752 static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2753 NSColor *newBaseCol = nil;
2754 NSRect sr = r;
2755
2756 NSTRACE (ns_draw_relief);
2757
2758 /* set up colors */
2759
2760 if (s->face->use_box_color_for_shadows_p)
2761 {
2762 newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2763 }
2764 /* else if (s->first_glyph->type == IMAGE_GLYPH
2765 && s->img->pixmap
2766 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2767 {
2768 newBaseCol = IMAGE_BACKGROUND (s->img, s->f, 0);
2769 } */
2770 else
2771 {
2772 newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2773 }
2774
2775 if (newBaseCol == nil)
2776 newBaseCol = [NSColor grayColor];
2777
2778 if (newBaseCol != baseCol) /* TODO: better check */
2779 {
2780 [baseCol release];
2781 baseCol = [newBaseCol retain];
2782 [lightCol release];
2783 lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2784 [darkCol release];
2785 darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2786 }
2787
2788 [(raised_p ? lightCol : darkCol) set];
2789
2790 /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2791
2792 /* top */
2793 sr.size.height = thickness;
2794 if (top_p) NSRectFill (sr);
2795
2796 /* left */
2797 sr.size.height = r.size.height;
2798 sr.size.width = thickness;
2799 if (left_p) NSRectFill (sr);
2800
2801 [(raised_p ? darkCol : lightCol) set];
2802
2803 /* bottom */
2804 sr.size.width = r.size.width;
2805 sr.size.height = thickness;
2806 sr.origin.y += r.size.height - thickness;
2807 if (bottom_p) NSRectFill (sr);
2808
2809 /* right */
2810 sr.size.height = r.size.height;
2811 sr.origin.y = r.origin.y;
2812 sr.size.width = thickness;
2813 sr.origin.x += r.size.width - thickness;
2814 if (right_p) NSRectFill (sr);
2815 }
2816
2817
2818 static void
2819 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2820 /* --------------------------------------------------------------------------
2821 Function modeled after x_draw_glyph_string_box ().
2822 Sets up parameters for drawing.
2823 -------------------------------------------------------------------------- */
2824 {
2825 int right_x, last_x;
2826 char left_p, right_p;
2827 struct glyph *last_glyph;
2828 NSRect r;
2829 int thickness;
2830 struct face *face;
2831
2832 if (s->hl == DRAW_MOUSE_FACE)
2833 {
2834 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2835 if (!face)
2836 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2837 }
2838 else
2839 face = s->face;
2840
2841 thickness = face->box_line_width;
2842
2843 NSTRACE (ns_dumpglyphs_box_or_relief);
2844
2845 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2846 ? WINDOW_RIGHT_EDGE_X (s->w)
2847 : window_box_right (s->w, s->area));
2848 last_glyph = (s->cmp || s->img
2849 ? s->first_glyph : s->first_glyph + s->nchars-1);
2850
2851 right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2852 ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2853
2854 left_p = (s->first_glyph->left_box_line_p
2855 || (s->hl == DRAW_MOUSE_FACE
2856 && (s->prev == NULL || s->prev->hl != s->hl)));
2857 right_p = (last_glyph->right_box_line_p
2858 || (s->hl == DRAW_MOUSE_FACE
2859 && (s->next == NULL || s->next->hl != s->hl)));
2860
2861 r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2862
2863 /* expand full-width row over internal borders */
2864 if (s->row->full_width_p)
2865 r = ns_fix_rect_ibw (r, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2866 FRAME_PIXEL_WIDTH (s->f));
2867
2868 /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
2869 if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
2870 {
2871 ns_draw_box (r, abs (thickness),
2872 ns_lookup_indexed_color (face->box_color, s->f),
2873 left_p, right_p);
2874 }
2875 else
2876 {
2877 ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2878 1, 1, left_p, right_p, s);
2879 }
2880 }
2881
2882
2883 static void
2884 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2885 /* --------------------------------------------------------------------------
2886 Modeled after x_draw_glyph_string_background, which draws BG in
2887 certain cases. Others are left to the text rendering routine.
2888 -------------------------------------------------------------------------- */
2889 {
2890 NSTRACE (ns_maybe_dumpglyphs_background);
2891
2892 if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2893 {
2894 int box_line_width = max (s->face->box_line_width, 0);
2895 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2896 || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2897 {
2898 struct face *face;
2899 if (s->hl == DRAW_MOUSE_FACE)
2900 {
2901 face = FACE_FROM_ID (s->f,
2902 MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2903 if (!face)
2904 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2905 }
2906 else
2907 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2908 if (!face->stipple)
2909 [(NS_FACE_BACKGROUND (face) != 0
2910 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2911 : FRAME_BACKGROUND_COLOR (s->f)) set];
2912 else
2913 {
2914 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (s->f);
2915 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2916 }
2917
2918 if (s->hl != DRAW_CURSOR)
2919 {
2920 NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2921 s->background_width,
2922 s->height-2*box_line_width);
2923
2924 /* expand full-width row over internal borders */
2925 if (s->row->full_width_p)
2926 {
2927 int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2928 if (r.origin.y <= fibw+1 + box_line_width)
2929 {
2930 r.size.height += r.origin.y;
2931 r.origin.y = 0;
2932 }
2933 if (r.origin.x <= fibw+1)
2934 {
2935 r.size.width += 2*r.origin.x;
2936 r.origin.x = 0;
2937 }
2938 if (FRAME_PIXEL_WIDTH (s->f) - (r.origin.x + r.size.width)
2939 <= fibw+1)
2940 r.size.width += fibw;
2941 }
2942
2943 NSRectFill (r);
2944 }
2945
2946 s->background_filled_p = 1;
2947 }
2948 }
2949 }
2950
2951
2952 static void
2953 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2954 /* --------------------------------------------------------------------------
2955 Renders an image and associated borders.
2956 -------------------------------------------------------------------------- */
2957 {
2958 EmacsImage *img = s->img->pixmap;
2959 int box_line_vwidth = max (s->face->box_line_width, 0);
2960 int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2961 int bg_x, bg_y, bg_height;
2962 int th;
2963 char raised_p;
2964 NSRect br;
2965 struct face *face;
2966 NSColor *tdCol;
2967
2968 NSTRACE (ns_dumpglyphs_image);
2969
2970 if (s->face->box != FACE_NO_BOX
2971 && s->first_glyph->left_box_line_p && s->slice.x == 0)
2972 x += abs (s->face->box_line_width);
2973
2974 bg_x = x;
2975 bg_y = s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2976 bg_height = s->height;
2977 /* other terms have this, but was causing problems w/tabbar mode */
2978 /* - 2 * box_line_vwidth; */
2979
2980 if (s->slice.x == 0) x += s->img->hmargin;
2981 if (s->slice.y == 0) y += s->img->vmargin;
2982
2983 /* Draw BG: if we need larger area than image itself cleared, do that,
2984 otherwise, since we composite the image under NS (instead of mucking
2985 with its background color), we must clear just the image area. */
2986 if (s->hl == DRAW_MOUSE_FACE)
2987 {
2988 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2989 if (!face)
2990 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2991 }
2992 else
2993 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2994
2995 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
2996
2997 if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
2998 || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
2999 {
3000 br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
3001 s->background_filled_p = 1;
3002 }
3003 else
3004 {
3005 br = NSMakeRect (x, y, s->slice.width, s->slice.height);
3006 }
3007
3008 /* expand full-width row over internal borders */
3009 if (s->row->full_width_p)
3010 {
3011 int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
3012 if (br.origin.y <= fibw+1 + box_line_vwidth)
3013 {
3014 br.size.height += br.origin.y;
3015 br.origin.y = 0;
3016 }
3017 if (br.origin.x <= fibw+1 + box_line_vwidth)
3018 {
3019 br.size.width += br.origin.x;
3020 br.origin.x = 0;
3021 }
3022 if (FRAME_PIXEL_WIDTH (s->f) - (br.origin.x + br.size.width) <= fibw+1)
3023 br.size.width += fibw;
3024 }
3025
3026 NSRectFill (br);
3027
3028 /* Draw the image.. do we need to draw placeholder if img ==nil? */
3029 if (img != nil)
3030 [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3031 operation: NSCompositeSourceOver];
3032
3033 if (s->hl == DRAW_CURSOR)
3034 {
3035 [FRAME_CURSOR_COLOR (s->f) set];
3036 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3037 tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3038 else
3039 /* Currently on NS img->mask is always 0. Since
3040 get_window_cursor_type specifies a hollow box cursor when on
3041 a non-masked image we never reach this clause. But we put it
3042 in in anticipation of better support for image masks on
3043 NS. */
3044 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3045 }
3046 else
3047 {
3048 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3049 }
3050
3051 /* Draw underline, overline, strike-through. */
3052 ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3053
3054 /* Draw relief, if requested */
3055 if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3056 {
3057 if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3058 {
3059 th = tool_bar_button_relief >= 0 ?
3060 tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3061 raised_p = (s->hl == DRAW_IMAGE_RAISED);
3062 }
3063 else
3064 {
3065 th = abs (s->img->relief);
3066 raised_p = (s->img->relief > 0);
3067 }
3068
3069 r.origin.x = x - th;
3070 r.origin.y = y - th;
3071 r.size.width = s->slice.width + 2*th-1;
3072 r.size.height = s->slice.height + 2*th-1;
3073 ns_draw_relief (r, th, raised_p,
3074 s->slice.y == 0,
3075 s->slice.y + s->slice.height == s->img->height,
3076 s->slice.x == 0,
3077 s->slice.x + s->slice.width == s->img->width, s);
3078 }
3079
3080 /* If there is no mask, the background won't be seen,
3081 so draw a rectangle on the image for the cursor.
3082 Do this for all images, getting transparency right is not reliable. */
3083 if (s->hl == DRAW_CURSOR)
3084 {
3085 int thickness = abs (s->img->relief);
3086 if (thickness == 0) thickness = 1;
3087 ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3088 }
3089 }
3090
3091
3092 static void
3093 ns_dumpglyphs_stretch (struct glyph_string *s)
3094 {
3095 NSRect r[2];
3096 int n, i;
3097 struct face *face;
3098 NSColor *fgCol, *bgCol;
3099
3100 if (!s->background_filled_p)
3101 {
3102 n = ns_get_glyph_string_clip_rect (s, r);
3103 *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3104
3105 ns_focus (s->f, r, n);
3106
3107 if (s->hl == DRAW_MOUSE_FACE)
3108 {
3109 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3110 if (!face)
3111 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3112 }
3113 else
3114 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3115
3116 bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3117 fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3118
3119 for (i=0; i<n; i++)
3120 {
3121 if (!s->row->full_width_p)
3122 {
3123 int overrun, leftoverrun;
3124
3125 /* truncate to avoid overwriting fringe and/or scrollbar */
3126 overrun = max (0, (s->x + s->background_width)
3127 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3128 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3129 r[i].size.width -= overrun;
3130
3131 /* truncate to avoid overwriting to left of the window box */
3132 leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3133 + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3134
3135 if (leftoverrun > 0)
3136 {
3137 r[i].origin.x += leftoverrun;
3138 r[i].size.width -= leftoverrun;
3139 }
3140
3141 /* XXX: Try to work between problem where a stretch glyph on
3142 a partially-visible bottom row will clear part of the
3143 modeline, and another where list-buffers headers and similar
3144 rows erroneously have visible_height set to 0. Not sure
3145 where this is coming from as other terms seem not to show. */
3146 r[i].size.height = min (s->height, s->row->visible_height);
3147 }
3148
3149 /* expand full-width rows over internal borders */
3150 else
3151 {
3152 r[i] = ns_fix_rect_ibw (r[i], FRAME_INTERNAL_BORDER_WIDTH (s->f),
3153 FRAME_PIXEL_WIDTH (s->f));
3154 }
3155
3156 [bgCol set];
3157
3158 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3159 overwriting cursor (usually when cursor on a tab) */
3160 if (s->hl == DRAW_CURSOR)
3161 {
3162 CGFloat x, width;
3163
3164 x = r[i].origin.x;
3165 width = s->w->phys_cursor_width;
3166 r[i].size.width -= width;
3167 r[i].origin.x += width;
3168
3169 NSRectFill (r[i]);
3170
3171 /* Draw overlining, etc. on the cursor. */
3172 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3173 ns_draw_text_decoration (s, face, bgCol, width, x);
3174 else
3175 ns_draw_text_decoration (s, face, fgCol, width, x);
3176 }
3177 else
3178 {
3179 NSRectFill (r[i]);
3180 }
3181
3182 /* Draw overlining, etc. on the stretch glyph (or the part
3183 of the stretch glyph after the cursor). */
3184 ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3185 r[i].origin.x);
3186 }
3187 ns_unfocus (s->f);
3188 s->background_filled_p = 1;
3189 }
3190 }
3191
3192
3193 static void
3194 ns_draw_glyph_string (struct glyph_string *s)
3195 /* --------------------------------------------------------------------------
3196 External (RIF): Main draw-text call.
3197 -------------------------------------------------------------------------- */
3198 {
3199 /* TODO (optimize): focus for box and contents draw */
3200 NSRect r[2];
3201 int n;
3202 char box_drawn_p = 0;
3203
3204 NSTRACE (ns_draw_glyph_string);
3205
3206 if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3207 {
3208 int width;
3209 struct glyph_string *next;
3210
3211 for (width = 0, next = s->next;
3212 next && width < s->right_overhang;
3213 width += next->width, next = next->next)
3214 if (next->first_glyph->type != IMAGE_GLYPH)
3215 {
3216 if (next->first_glyph->type != STRETCH_GLYPH)
3217 {
3218 n = ns_get_glyph_string_clip_rect (s->next, r);
3219 ns_focus (s->f, r, n);
3220 ns_maybe_dumpglyphs_background (s->next, 1);
3221 ns_unfocus (s->f);
3222 }
3223 else
3224 {
3225 ns_dumpglyphs_stretch (s->next);
3226 }
3227 next->num_clips = 0;
3228 }
3229 }
3230
3231 if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3232 && (s->first_glyph->type == CHAR_GLYPH
3233 || s->first_glyph->type == COMPOSITE_GLYPH))
3234 {
3235 n = ns_get_glyph_string_clip_rect (s, r);
3236 ns_focus (s->f, r, n);
3237 ns_maybe_dumpglyphs_background (s, 1);
3238 ns_dumpglyphs_box_or_relief (s);
3239 ns_unfocus (s->f);
3240 box_drawn_p = 1;
3241 }
3242
3243 switch (s->first_glyph->type)
3244 {
3245
3246 case IMAGE_GLYPH:
3247 n = ns_get_glyph_string_clip_rect (s, r);
3248 ns_focus (s->f, r, n);
3249 ns_dumpglyphs_image (s, r[0]);
3250 ns_unfocus (s->f);
3251 break;
3252
3253 case STRETCH_GLYPH:
3254 ns_dumpglyphs_stretch (s);
3255 break;
3256
3257 case CHAR_GLYPH:
3258 case COMPOSITE_GLYPH:
3259 n = ns_get_glyph_string_clip_rect (s, r);
3260 ns_focus (s->f, r, n);
3261
3262 if (s->for_overlaps || (s->cmp_from > 0
3263 && ! s->first_glyph->u.cmp.automatic))
3264 s->background_filled_p = 1;
3265 else
3266 ns_maybe_dumpglyphs_background
3267 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3268
3269 ns_tmp_flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3270 (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3271 (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3272 NS_DUMPGLYPH_NORMAL));
3273 ns_tmp_font = (struct nsfont_info *)s->face->font;
3274 if (ns_tmp_font == NULL)
3275 ns_tmp_font = (struct nsfont_info *)FRAME_FONT (s->f);
3276
3277 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3278 {
3279 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3280 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3281 NS_FACE_FOREGROUND (s->face) = tmp;
3282 }
3283
3284 ns_tmp_font->font.driver->draw
3285 (s, 0, s->nchars, s->x, s->y,
3286 (ns_tmp_flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3287 || ns_tmp_flags == NS_DUMPGLYPH_MOUSEFACE);
3288
3289 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3290 {
3291 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3292 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3293 NS_FACE_FOREGROUND (s->face) = tmp;
3294 }
3295
3296 ns_unfocus (s->f);
3297 break;
3298
3299 case GLYPHLESS_GLYPH:
3300 n = ns_get_glyph_string_clip_rect (s, r);
3301 ns_focus (s->f, r, n);
3302
3303 if (s->for_overlaps || (s->cmp_from > 0
3304 && ! s->first_glyph->u.cmp.automatic))
3305 s->background_filled_p = 1;
3306 else
3307 ns_maybe_dumpglyphs_background
3308 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3309 /* ... */
3310 /* Not yet implemented. */
3311 /* ... */
3312 ns_unfocus (s->f);
3313 break;
3314
3315 default:
3316 abort ();
3317 }
3318
3319 /* Draw box if not done already. */
3320 if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3321 {
3322 n = ns_get_glyph_string_clip_rect (s, r);
3323 ns_focus (s->f, r, n);
3324 ns_dumpglyphs_box_or_relief (s);
3325 ns_unfocus (s->f);
3326 }
3327
3328 s->num_clips = 0;
3329 }
3330
3331
3332
3333 /* ==========================================================================
3334
3335 Event loop
3336
3337 ========================================================================== */
3338
3339
3340 static void
3341 ns_send_appdefined (int value)
3342 /* --------------------------------------------------------------------------
3343 Internal: post an appdefined event which EmacsApp-sendEvent will
3344 recognize and take as a command to halt the event loop.
3345 -------------------------------------------------------------------------- */
3346 {
3347 /*NSTRACE (ns_send_appdefined); */
3348
3349 /* Only post this event if we haven't already posted one. This will end
3350 the [NXApp run] main loop after having processed all events queued at
3351 this moment. */
3352 if (send_appdefined)
3353 {
3354 NSEvent *nxev;
3355
3356 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
3357 send_appdefined = NO;
3358
3359 /* Don't need wakeup timer any more */
3360 if (timed_entry)
3361 {
3362 [timed_entry invalidate];
3363 [timed_entry release];
3364 timed_entry = nil;
3365 }
3366
3367 /* Ditto for file descriptor poller */
3368 if (fd_entry)
3369 {
3370 [fd_entry invalidate];
3371 [fd_entry release];
3372 fd_entry = nil;
3373 }
3374
3375 nxev = [NSEvent otherEventWithType: NSApplicationDefined
3376 location: NSMakePoint (0, 0)
3377 modifierFlags: 0
3378 timestamp: 0
3379 windowNumber: [[NSApp mainWindow] windowNumber]
3380 context: [NSApp context]
3381 subtype: 0
3382 data1: value
3383 data2: 0];
3384
3385 /* Post an application defined event on the event queue. When this is
3386 received the [NXApp run] will return, thus having processed all
3387 events which are currently queued. */
3388 [NSApp postEvent: nxev atStart: NO];
3389 }
3390 }
3391
3392
3393 static int
3394 ns_read_socket (struct terminal *terminal, int expected,
3395 struct input_event *hold_quit)
3396 /* --------------------------------------------------------------------------
3397 External (hook): Post an event to ourself and keep reading events until
3398 we read it back again. In effect process all events which were waiting.
3399 From 21+ we have to manage the event buffer ourselves.
3400 -------------------------------------------------------------------------- */
3401 {
3402 struct input_event ev;
3403 int nevents;
3404
3405 /* NSTRACE (ns_read_socket); */
3406
3407 if (interrupt_input_blocked)
3408 {
3409 interrupt_input_pending = 1;
3410 #ifdef SYNC_INPUT
3411 pending_signals = 1;
3412 #endif
3413 return -1;
3414 }
3415
3416 interrupt_input_pending = 0;
3417 #ifdef SYNC_INPUT
3418 pending_signals = pending_atimers;
3419 #endif
3420
3421 BLOCK_INPUT;
3422 n_emacs_events_pending = 0;
3423 EVENT_INIT (ev);
3424 emacs_event = &ev;
3425 q_event_ptr = hold_quit;
3426
3427 /* we manage autorelease pools by allocate/reallocate each time around
3428 the loop; strict nesting is occasionally violated but seems not to
3429 matter.. earlier methods using full nesting caused major memory leaks */
3430 [outerpool release];
3431 outerpool = [[NSAutoreleasePool alloc] init];
3432
3433 /* If have pending open-file requests, attend to the next one of those. */
3434 if (ns_pending_files && [ns_pending_files count] != 0
3435 && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3436 {
3437 [ns_pending_files removeObjectAtIndex: 0];
3438 }
3439 /* Deal with pending service requests. */
3440 else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3441 && [(EmacsApp *)
3442 NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3443 withArg: [ns_pending_service_args objectAtIndex: 0]])
3444 {
3445 [ns_pending_service_names removeObjectAtIndex: 0];
3446 [ns_pending_service_args removeObjectAtIndex: 0];
3447 }
3448 else
3449 {
3450 /* Run and wait for events. We must always send one NX_APPDEFINED event
3451 to ourself, otherwise [NXApp run] will never exit. */
3452 send_appdefined = YES;
3453
3454 /* If called via ns_select, this is called once with expected=1,
3455 because we expect either the timeout or file descriptor activity.
3456 In this case the first event through will either be real input or
3457 one of these. read_avail_input() then calls once more with expected=0
3458 and in that case we need to return quickly if there is nothing.
3459 If we're being called outside of that, it's also OK to return quickly
3460 after one iteration through the event loop, since other terms do
3461 this and emacs expects it. */
3462 if (!(inNsSelect && expected))
3463 {
3464 /* Post an application defined event on the event queue. When this is
3465 received the [NXApp run] will return, thus having processed all
3466 events which are currently queued, if any. */
3467 ns_send_appdefined (-1);
3468 }
3469
3470 [NSApp run];
3471 }
3472
3473 nevents = n_emacs_events_pending;
3474 n_emacs_events_pending = 0;
3475 emacs_event = q_event_ptr = NULL;
3476 UNBLOCK_INPUT;
3477
3478 return nevents;
3479 }
3480
3481
3482 int
3483 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3484 fd_set *exceptfds, struct timeval *timeout)
3485 /* --------------------------------------------------------------------------
3486 Replacement for select, checking for events
3487 -------------------------------------------------------------------------- */
3488 {
3489 int result;
3490 double time;
3491 NSEvent *ev;
3492 /* NSTRACE (ns_select); */
3493
3494 if (NSApp == nil || inNsSelect == 1 /* || ([NSApp isActive] == NO &&
3495 [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
3496 inMode:NSDefaultRunLoopMode dequeue:NO] == nil) */)
3497 return select (nfds, readfds, writefds, exceptfds, timeout);
3498
3499 /* Save file descriptor set, which gets overwritten in calls to select ()
3500 Note, this is called from process.c, and only readfds is ever set */
3501 if (readfds)
3502 {
3503 memcpy (&select_readfds, readfds, sizeof (fd_set));
3504 select_nfds = nfds;
3505 }
3506 else
3507 select_nfds = 0;
3508
3509 /* Try an initial select for pending data on input files */
3510 select_timeout.tv_sec = select_timeout.tv_usec = 0;
3511 result = select (nfds, readfds, writefds, exceptfds, &select_timeout);
3512 if (result)
3513 return result;
3514
3515 /* if (!timeout || timed_entry || fd_entry)
3516 fprintf (stderr, "assertion failed: timeout null or timed_entry/fd_entry non-null in ns_select\n"); */
3517
3518 /* set a timeout and run the main AppKit event loop while continuing
3519 to monitor the files */
3520 time = ((double) timeout->tv_sec) + ((double) timeout->tv_usec)/1000000.0;
3521 timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3522 target: NSApp
3523 selector: @selector (timeout_handler:)
3524 userInfo: 0
3525 repeats: YES] /* for safe removal */
3526 retain];
3527
3528 /* set a periodic task to try the select () again */
3529 fd_entry = [[NSTimer scheduledTimerWithTimeInterval: 0.1
3530 target: NSApp
3531 selector: @selector (fd_handler:)
3532 userInfo: 0
3533 repeats: YES]
3534 retain];
3535
3536 /* Let Application dispatch events until it receives an event of the type
3537 NX_APPDEFINED, which should only be sent by timeout_handler.
3538 We tell read_avail_input() that input is "expected" because we do expect
3539 either the timeout or fd handler to fire, and if they don't, the original
3540 call from process.c that got us here expects us to wait until some input
3541 comes. */
3542 inNsSelect = 1;
3543 gobble_input (1);
3544 ev = last_appdefined_event;
3545 inNsSelect = 0;
3546
3547 if (ev)
3548 {
3549 int t;
3550 if ([ev type] != NSApplicationDefined)
3551 abort ();
3552
3553 t = [ev data1];
3554 last_appdefined_event = 0;
3555
3556 if (t == -2)
3557 {
3558 /* The NX_APPDEFINED event we received was a timeout. */
3559 return 0;
3560 }
3561 else if (t == -1)
3562 {
3563 /* The NX_APPDEFINED event we received was the result of
3564 at least one real input event arriving. */
3565 errno = EINTR;
3566 return -1;
3567 }
3568 else
3569 {
3570 /* Received back from select () in fd_handler; copy the results */
3571 if (readfds)
3572 memcpy (readfds, &select_readfds, sizeof (fd_set));
3573 return t;
3574 }
3575 }
3576 /* never reached, shut compiler up */
3577 return 0;
3578 }
3579
3580
3581
3582 /* ==========================================================================
3583
3584 Scrollbar handling
3585
3586 ========================================================================== */
3587
3588
3589 static void
3590 ns_set_vertical_scroll_bar (struct window *window,
3591 int portion, int whole, int position)
3592 /* --------------------------------------------------------------------------
3593 External (hook): Update or add scrollbar
3594 -------------------------------------------------------------------------- */
3595 {
3596 Lisp_Object win;
3597 NSRect r, v;
3598 struct frame *f = XFRAME (WINDOW_FRAME (window));
3599 EmacsView *view = FRAME_NS_VIEW (f);
3600 int window_y, window_height;
3601 BOOL barOnVeryLeft, barOnVeryRight;
3602 int top, left, height, width, sb_width, sb_left;
3603 EmacsScroller *bar;
3604 static int count = 0;
3605
3606 /* optimization; display engine sends WAY too many of these.. */
3607 if (!NILP (window->vertical_scroll_bar))
3608 {
3609 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3610 if ([bar checkSamePosition: position portion: portion whole: whole])
3611 {
3612 if (view->scrollbarsNeedingUpdate == 0)
3613 {
3614 if (!windows_or_buffers_changed)
3615 return;
3616 }
3617 else
3618 view->scrollbarsNeedingUpdate--;
3619 }
3620 }
3621
3622 NSTRACE (ns_set_vertical_scroll_bar);
3623
3624 /* Get dimensions. */
3625 window_box (window, -1, 0, &window_y, 0, &window_height);
3626 top = window_y;
3627 height = window_height;
3628 width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3629 left = WINDOW_SCROLL_BAR_AREA_X (window);
3630
3631 if (top < 5) /* top scrollbar adjustment */
3632 {
3633 top -= FRAME_INTERNAL_BORDER_WIDTH (f);
3634 height += FRAME_INTERNAL_BORDER_WIDTH (f);
3635 }
3636
3637 /* allow for displaying a skinnier scrollbar than char area allotted */
3638 sb_width = (WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) > 0) ?
3639 WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) : width;
3640
3641 barOnVeryLeft = left < 5;
3642 barOnVeryRight = FRAME_PIXEL_WIDTH (f) - left - width < 5;
3643 sb_left = left + FRAME_INTERNAL_BORDER_WIDTH (f)
3644 * (barOnVeryLeft ? -1 : (barOnVeryRight ? 1 : 0));
3645
3646 r = NSMakeRect (sb_left, top, sb_width, height);
3647 /* the parent view is flipped, so we need to flip y value */
3648 v = [view frame];
3649 r.origin.y = (v.size.height - r.size.height - r.origin.y);
3650
3651 XSETWINDOW (win, window);
3652 BLOCK_INPUT;
3653
3654 /* we want at least 5 lines to display a scrollbar */
3655 if (WINDOW_TOTAL_LINES (window) < 5)
3656 {
3657 if (!NILP (window->vertical_scroll_bar))
3658 {
3659 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3660 [bar removeFromSuperview];
3661 window->vertical_scroll_bar = Qnil;
3662 }
3663 ns_clear_frame_area (f, sb_left, top, width, height);
3664 UNBLOCK_INPUT;
3665 return;
3666 }
3667
3668 if (NILP (window->vertical_scroll_bar))
3669 {
3670 ns_clear_frame_area (f, sb_left, top, width, height);
3671 bar = [[EmacsScroller alloc] initFrame: r window: win];
3672 window->vertical_scroll_bar = make_save_value (bar, 0);
3673 }
3674 else
3675 {
3676 NSRect oldRect;
3677 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3678 oldRect = [bar frame];
3679 r.size.width = oldRect.size.width;
3680 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3681 {
3682 if (oldRect.origin.x != r.origin.x)
3683 ns_clear_frame_area (f, sb_left, top, width, height);
3684 [bar setFrame: r];
3685 }
3686 }
3687
3688 [bar setPosition: position portion: portion whole: whole];
3689 UNBLOCK_INPUT;
3690 }
3691
3692
3693 static void
3694 ns_condemn_scroll_bars (struct frame *f)
3695 /* --------------------------------------------------------------------------
3696 External (hook): arrange for all frame's scrollbars to be removed
3697 at next call to judge_scroll_bars, except for those redeemed.
3698 -------------------------------------------------------------------------- */
3699 {
3700 int i;
3701 id view;
3702 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3703
3704 NSTRACE (ns_condemn_scroll_bars);
3705
3706 for (i =[subviews count]-1; i >= 0; i--)
3707 {
3708 view = [subviews objectAtIndex: i];
3709 if ([view isKindOfClass: [EmacsScroller class]])
3710 [view condemn];
3711 }
3712 }
3713
3714
3715 static void
3716 ns_redeem_scroll_bar (struct window *window)
3717 /* --------------------------------------------------------------------------
3718 External (hook): arrange to spare this window's scrollbar
3719 at next call to judge_scroll_bars.
3720 -------------------------------------------------------------------------- */
3721 {
3722 id bar;
3723 NSTRACE (ns_redeem_scroll_bar);
3724 if (!NILP (window->vertical_scroll_bar))
3725 {
3726 bar =XNS_SCROLL_BAR (window->vertical_scroll_bar);
3727 [bar reprieve];
3728 }
3729 }
3730
3731
3732 static void
3733 ns_judge_scroll_bars (struct frame *f)
3734 /* --------------------------------------------------------------------------
3735 External (hook): destroy all scrollbars on frame that weren't
3736 redeemed after call to condemn_scroll_bars.
3737 -------------------------------------------------------------------------- */
3738 {
3739 int i;
3740 id view;
3741 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3742 NSTRACE (ns_judge_scroll_bars);
3743 for (i =[subviews count]-1; i >= 0; i--)
3744 {
3745 view = [subviews objectAtIndex: i];
3746 if (![view isKindOfClass: [EmacsScroller class]]) continue;
3747 [view judge];
3748 }
3749 }
3750
3751
3752 void
3753 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
3754 {
3755 /* XXX irrelevant under NS */
3756 }
3757
3758
3759
3760 /* ==========================================================================
3761
3762 Initialization
3763
3764 ========================================================================== */
3765
3766 int
3767 x_display_pixel_height (struct ns_display_info *dpyinfo)
3768 {
3769 NSScreen *screen = [NSScreen mainScreen];
3770 return [screen frame].size.height;
3771 }
3772
3773 int
3774 x_display_pixel_width (struct ns_display_info *dpyinfo)
3775 {
3776 NSScreen *screen = [NSScreen mainScreen];
3777 return [screen frame].size.width;
3778 }
3779
3780
3781 static Lisp_Object ns_string_to_lispmod (const char *s)
3782 /* --------------------------------------------------------------------------
3783 Convert modifier name to lisp symbol
3784 -------------------------------------------------------------------------- */
3785 {
3786 if (!strncmp (SDATA (SYMBOL_NAME (Qmeta)), s, 10))
3787 return Qmeta;
3788 else if (!strncmp (SDATA (SYMBOL_NAME (Qsuper)), s, 10))
3789 return Qsuper;
3790 else if (!strncmp (SDATA (SYMBOL_NAME (Qcontrol)), s, 10))
3791 return Qcontrol;
3792 else if (!strncmp (SDATA (SYMBOL_NAME (Qalt)), s, 10))
3793 return Qalt;
3794 else if (!strncmp (SDATA (SYMBOL_NAME (Qhyper)), s, 10))
3795 return Qhyper;
3796 else if (!strncmp (SDATA (SYMBOL_NAME (Qnone)), s, 10))
3797 return Qnone;
3798 else
3799 return Qnil;
3800 }
3801
3802
3803 static Lisp_Object ns_mod_to_lisp (int m)
3804 /* --------------------------------------------------------------------------
3805 Convert modifier code (see lisp.h) to lisp symbol
3806 -------------------------------------------------------------------------- */
3807 {
3808 if (m == CHAR_META)
3809 return Qmeta;
3810 else if (m == CHAR_SUPER)
3811 return Qsuper;
3812 else if (m == CHAR_CTL)
3813 return Qcontrol;
3814 else if (m == CHAR_ALT)
3815 return Qalt;
3816 else if (m == CHAR_HYPER)
3817 return Qhyper;
3818 else /* if (m == 0) */
3819 return Qnone;
3820 }
3821
3822
3823 static void
3824 ns_default (const char *parameter, Lisp_Object *result,
3825 Lisp_Object yesval, Lisp_Object noval,
3826 BOOL is_float, BOOL is_modstring)
3827 /* --------------------------------------------------------------------------
3828 Check a parameter value in user's preferences
3829 -------------------------------------------------------------------------- */
3830 {
3831 const char *value = ns_get_defaults_value (parameter);
3832
3833 if (value)
3834 {
3835 double f;
3836 char *pos;
3837 if (strcasecmp (value, "YES") == 0)
3838 *result = yesval;
3839 else if (strcasecmp (value, "NO") == 0)
3840 *result = noval;
3841 else if (is_float && (f = strtod (value, &pos), pos != value))
3842 *result = make_float (f);
3843 else if (is_modstring && value)
3844 *result = ns_string_to_lispmod (value);
3845 else fprintf (stderr,
3846 "Bad value for default \"%s\": \"%s\"\n", parameter, value);
3847 }
3848 }
3849
3850
3851 void
3852 ns_initialize_display_info (struct ns_display_info *dpyinfo)
3853 /* --------------------------------------------------------------------------
3854 Initialize global info and storage for display.
3855 -------------------------------------------------------------------------- */
3856 {
3857 NSScreen *screen = [NSScreen mainScreen];
3858 NSWindowDepth depth = [screen depth];
3859 Mouse_HLInfo *hlinfo = &dpyinfo->mouse_highlight;
3860
3861 dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
3862 dpyinfo->resy = 72.27;
3863 dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
3864 NSColorSpaceFromDepth (depth)]
3865 && ![NSCalibratedWhiteColorSpace isEqualToString:
3866 NSColorSpaceFromDepth (depth)];
3867 dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
3868 dpyinfo->image_cache = make_image_cache ();
3869 dpyinfo->color_table
3870 = (struct ns_color_table *)xmalloc (sizeof (struct ns_color_table));
3871 dpyinfo->color_table->colors = NULL;
3872 dpyinfo->root_window = 42; /* a placeholder.. */
3873
3874 hlinfo->mouse_face_mouse_frame = NULL;
3875 hlinfo->mouse_face_deferred_gc = 0;
3876 hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
3877 hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
3878 hlinfo->mouse_face_face_id = DEFAULT_FACE_ID;
3879 hlinfo->mouse_face_window = hlinfo->mouse_face_overlay = Qnil;
3880 hlinfo->mouse_face_hidden = 0;
3881
3882 hlinfo->mouse_face_mouse_x = hlinfo->mouse_face_mouse_y = 0;
3883 hlinfo->mouse_face_defer = 0;
3884
3885 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
3886
3887 dpyinfo->n_fonts = 0;
3888 dpyinfo->smallest_font_height = 1;
3889 dpyinfo->smallest_char_width = 1;
3890 }
3891
3892
3893 /* This and next define (many of the) public functions in this file. */
3894 /* x_... are generic versions in xdisp.c that we, and other terms, get away
3895 with using despite presence in the "system dependent" redisplay
3896 interface. In addition, many of the ns_ methods have code that is
3897 shared with all terms, indicating need for further refactoring. */
3898 extern frame_parm_handler ns_frame_parm_handlers[];
3899 static struct redisplay_interface ns_redisplay_interface =
3900 {
3901 ns_frame_parm_handlers,
3902 x_produce_glyphs,
3903 x_write_glyphs,
3904 x_insert_glyphs,
3905 x_clear_end_of_line,
3906 ns_scroll_run,
3907 ns_after_update_window_line,
3908 ns_update_window_begin,
3909 ns_update_window_end,
3910 x_cursor_to,
3911 ns_flush,
3912 0, /* flush_display_optional */
3913 x_clear_window_mouse_face,
3914 x_get_glyph_overhangs,
3915 x_fix_overlapping_area,
3916 ns_draw_fringe_bitmap,
3917 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
3918 0, /* destroy_fringe_bitmap */
3919 ns_compute_glyph_string_overhangs,
3920 ns_draw_glyph_string, /* interface to nsfont.m */
3921 ns_define_frame_cursor,
3922 ns_clear_frame_area,
3923 ns_draw_window_cursor,
3924 ns_draw_vertical_window_border,
3925 ns_shift_glyphs_for_insert
3926 };
3927
3928
3929 static void
3930 ns_delete_display (struct ns_display_info *dpyinfo)
3931 {
3932 /* TODO... */
3933 }
3934
3935
3936 /* This function is called when the last frame on a display is deleted. */
3937 static void
3938 ns_delete_terminal (struct terminal *terminal)
3939 {
3940 struct ns_display_info *dpyinfo = terminal->display_info.ns;
3941 int i;
3942
3943 /* Protect against recursive calls. delete_frame in
3944 delete_terminal calls us back when it deletes our last frame. */
3945 if (!terminal->name)
3946 return;
3947
3948 BLOCK_INPUT;
3949
3950 x_destroy_all_bitmaps (dpyinfo);
3951 ns_delete_display (dpyinfo);
3952 UNBLOCK_INPUT;
3953 }
3954
3955
3956 static struct terminal *
3957 ns_create_terminal (struct ns_display_info *dpyinfo)
3958 /* --------------------------------------------------------------------------
3959 Set up use of NS before we make the first connection.
3960 -------------------------------------------------------------------------- */
3961 {
3962 struct terminal *terminal;
3963
3964 NSTRACE (ns_create_terminal);
3965
3966 terminal = create_terminal ();
3967
3968 terminal->type = output_ns;
3969 terminal->display_info.ns = dpyinfo;
3970 dpyinfo->terminal = terminal;
3971
3972 terminal->rif = &ns_redisplay_interface;
3973
3974 terminal->clear_frame_hook = ns_clear_frame;
3975 terminal->ins_del_lines_hook = 0; /* XXX vestigial? */
3976 terminal->delete_glyphs_hook = 0; /* XXX vestigial? */
3977 terminal->ring_bell_hook = ns_ring_bell;
3978 terminal->reset_terminal_modes_hook = ns_reset_terminal_modes;
3979 terminal->set_terminal_modes_hook = ns_set_terminal_modes;
3980 terminal->update_begin_hook = ns_update_begin;
3981 terminal->update_end_hook = ns_update_end;
3982 terminal->set_terminal_window_hook = NULL; /* XXX vestigial? */
3983 terminal->read_socket_hook = ns_read_socket;
3984 terminal->frame_up_to_date_hook = ns_frame_up_to_date;
3985 terminal->mouse_position_hook = ns_mouse_position;
3986 terminal->frame_rehighlight_hook = ns_frame_rehighlight;
3987 terminal->frame_raise_lower_hook = ns_frame_raise_lower;
3988
3989 terminal->fullscreen_hook = 0; /* see XTfullscreen_hook */
3990
3991 terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
3992 terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
3993 terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
3994 terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
3995
3996 terminal->delete_frame_hook = x_destroy_window;
3997 terminal->delete_terminal_hook = ns_delete_terminal;
3998
3999 terminal->scroll_region_ok = 1;
4000 terminal->char_ins_del_ok = 1;
4001 terminal->line_ins_del_ok = 1;
4002 terminal->fast_clear_end_of_line = 1;
4003 terminal->memory_below_frame = 0;
4004
4005 return terminal;
4006 }
4007
4008
4009 struct ns_display_info *
4010 ns_term_init (Lisp_Object display_name)
4011 /* --------------------------------------------------------------------------
4012 Start the Application and get things rolling.
4013 -------------------------------------------------------------------------- */
4014 {
4015 struct terminal *terminal;
4016 struct ns_display_info *dpyinfo;
4017 static int ns_initialized = 0;
4018 Lisp_Object tmp;
4019
4020 NSTRACE (ns_term_init);
4021
4022 /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4023 /*GSDebugAllocationActive (YES); */
4024 BLOCK_INPUT;
4025 handling_signal = 0;
4026
4027 if (!ns_initialized)
4028 {
4029 baud_rate = 38400;
4030 Fset_input_interrupt_mode (Qnil);
4031 ns_initialized = 1;
4032 }
4033
4034 ns_pending_files = [[NSMutableArray alloc] init];
4035 ns_pending_service_names = [[NSMutableArray alloc] init];
4036 ns_pending_service_args = [[NSMutableArray alloc] init];
4037
4038 /* Start app and create the main menu, window, view.
4039 Needs to be here because ns_initialize_display_info () uses AppKit classes.
4040 The view will then ask the NSApp to stop and return to Emacs. */
4041 [EmacsApp sharedApplication];
4042 if (NSApp == nil)
4043 return NULL;
4044 [NSApp setDelegate: NSApp];
4045
4046 /* debugging: log all notifications */
4047 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
4048 selector: @selector (logNotification:)
4049 name: nil object: nil]; */
4050
4051 dpyinfo = (struct ns_display_info *)xmalloc (sizeof (struct ns_display_info));
4052 memset (dpyinfo, 0, sizeof (struct ns_display_info));
4053
4054 ns_initialize_display_info (dpyinfo);
4055 terminal = ns_create_terminal (dpyinfo);
4056
4057 terminal->kboard = (KBOARD *) xmalloc (sizeof (KBOARD));
4058 init_kboard (terminal->kboard);
4059 KVAR (terminal->kboard, Vwindow_system) = Qns;
4060 terminal->kboard->next_kboard = all_kboards;
4061 all_kboards = terminal->kboard;
4062 /* Don't let the initial kboard remain current longer than necessary.
4063 That would cause problems if a file loaded on startup tries to
4064 prompt in the mini-buffer. */
4065 if (current_kboard == initial_kboard)
4066 current_kboard = terminal->kboard;
4067 terminal->kboard->reference_count++;
4068
4069 dpyinfo->next = x_display_list;
4070 x_display_list = dpyinfo;
4071
4072 /* Put it on ns_display_name_list */
4073 ns_display_name_list = Fcons (Fcons (display_name, Qnil),
4074 ns_display_name_list);
4075 dpyinfo->name_list_element = XCAR (ns_display_name_list);
4076
4077 /* Set the name of the terminal. */
4078 terminal->name = (char *) xmalloc (SBYTES (display_name) + 1);
4079 strncpy (terminal->name, SDATA (display_name), SBYTES (display_name));
4080 terminal->name[SBYTES (display_name)] = 0;
4081
4082 UNBLOCK_INPUT;
4083
4084 if (!inhibit_x_resources)
4085 {
4086 ns_default ("GSFontAntiAlias", &ns_antialias_text,
4087 Qt, Qnil, NO, NO);
4088 tmp = Qnil;
4089 /* this is a standard variable */
4090 ns_default ("AppleAntiAliasingThreshold", &tmp,
4091 make_float (10.0), make_float (6.0), YES, NO);
4092 ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4093 }
4094
4095 ns_selection_color = [[NSUserDefaults standardUserDefaults]
4096 stringForKey: @"AppleHighlightColor"];
4097 if (ns_selection_color == nil)
4098 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
4099
4100 {
4101 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4102
4103 if ( cl == nil )
4104 {
4105 Lisp_Object color_file, color_map, color;
4106 int r,g,b;
4107 unsigned long c;
4108 char *name;
4109
4110 color_file = Fexpand_file_name (build_string ("rgb.txt"),
4111 Fsymbol_value (intern ("data-directory")));
4112 if (NILP (Ffile_readable_p (color_file)))
4113 fatal ("Could not find %s.\n", SDATA (color_file));
4114
4115 color_map = Fx_load_color_file (color_file);
4116 if (NILP (color_map))
4117 fatal ("Could not read %s.\n", SDATA (color_file));
4118
4119 cl = [[NSColorList alloc] initWithName: @"Emacs"];
4120 for ( ; CONSP (color_map); color_map = XCDR (color_map))
4121 {
4122 color = XCAR (color_map);
4123 name = SDATA (XCAR (color));
4124 c = XINT (XCDR (color));
4125 [cl setColor:
4126 [NSColor colorWithCalibratedRed: RED_FROM_ULONG (c) / 255.0
4127 green: GREEN_FROM_ULONG (c) / 255.0
4128 blue: BLUE_FROM_ULONG (c) / 255.0
4129 alpha: 1.0]
4130 forKey: [NSString stringWithUTF8String: name]];
4131 }
4132 [cl writeToFile: nil];
4133 }
4134 }
4135
4136 {
4137 char c[128];
4138 #ifdef NS_IMPL_GNUSTEP
4139 strncpy (c, gnustep_base_version, sizeof (c));
4140 #else
4141 /*PSnextrelease (128, c); */
4142 snprintf (c, sizeof (c), "%g", NSAppKitVersionNumber);
4143 #endif
4144 Vwindow_system_version = build_string (c);
4145 }
4146
4147 delete_keyboard_wait_descriptor (0);
4148
4149 ns_app_name = [[NSProcessInfo processInfo] processName];
4150
4151 /* Set up OS X app menu */
4152 #ifdef NS_IMPL_COCOA
4153 {
4154 NSMenu *appMenu;
4155 NSMenuItem *item;
4156 /* set up the application menu */
4157 svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4158 [svcsMenu setAutoenablesItems: NO];
4159 appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4160 [appMenu setAutoenablesItems: NO];
4161 mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4162 dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4163
4164 [appMenu insertItemWithTitle: @"About Emacs"
4165 action: @selector (orderFrontStandardAboutPanel:)
4166 keyEquivalent: @""
4167 atIndex: 0];
4168 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4169 [appMenu insertItemWithTitle: @"Preferences..."
4170 action: @selector (showPreferencesWindow:)
4171 keyEquivalent: @","
4172 atIndex: 2];
4173 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4174 item = [appMenu insertItemWithTitle: @"Services"
4175 action: @selector (menuDown:)
4176 keyEquivalent: @""
4177 atIndex: 4];
4178 [appMenu setSubmenu: svcsMenu forItem: item];
4179 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4180 [appMenu insertItemWithTitle: @"Hide Emacs"
4181 action: @selector (hide:)
4182 keyEquivalent: @"h"
4183 atIndex: 6];
4184 item = [appMenu insertItemWithTitle: @"Hide Others"
4185 action: @selector (hideOtherApplications:)
4186 keyEquivalent: @"h"
4187 atIndex: 7];
4188 [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4189 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4190 [appMenu insertItemWithTitle: @"Quit Emacs"
4191 action: @selector (terminate:)
4192 keyEquivalent: @"q"
4193 atIndex: 9];
4194
4195 item = [mainMenu insertItemWithTitle: ns_app_name
4196 action: @selector (menuDown:)
4197 keyEquivalent: @""
4198 atIndex: 0];
4199 [mainMenu setSubmenu: appMenu forItem: item];
4200 [dockMenu insertItemWithTitle: @"New Frame"
4201 action: @selector (newFrame:)
4202 keyEquivalent: @""
4203 atIndex: 0];
4204
4205 [NSApp setMainMenu: mainMenu];
4206 [NSApp setAppleMenu: appMenu];
4207 [NSApp setServicesMenu: svcsMenu];
4208 /* Needed at least on Cocoa, to get dock menu to show windows */
4209 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4210
4211 [[NSNotificationCenter defaultCenter]
4212 addObserver: mainMenu
4213 selector: @selector (trackingNotification:)
4214 name: NSMenuDidBeginTrackingNotification object: mainMenu];
4215 [[NSNotificationCenter defaultCenter]
4216 addObserver: mainMenu
4217 selector: @selector (trackingNotification:)
4218 name: NSMenuDidEndTrackingNotification object: mainMenu];
4219 }
4220 #endif /* MAC OS X menu setup */
4221
4222 [NSApp run];
4223
4224 return dpyinfo;
4225 }
4226
4227
4228 void
4229 ns_term_shutdown (int sig)
4230 {
4231 [[NSUserDefaults standardUserDefaults] synchronize];
4232
4233 /* code not reached in emacs.c after this is called by shut_down_emacs: */
4234 if (STRINGP (Vauto_save_list_file_name))
4235 unlink (SDATA (Vauto_save_list_file_name));
4236
4237 if (sig == 0 || sig == SIGTERM)
4238 {
4239 [NSApp terminate: NSApp];
4240 }
4241 else // force a stack trace to happen
4242 {
4243 abort();
4244 }
4245 }
4246
4247
4248 /* ==========================================================================
4249
4250 EmacsApp implementation
4251
4252 ========================================================================== */
4253
4254
4255 @implementation EmacsApp
4256
4257 - (void)logNotification: (NSNotification *)notification
4258 {
4259 const char *name = [[notification name] UTF8String];
4260 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4261 && !strstr (name, "WindowNumber"))
4262 NSLog (@"notification: '%@'", [notification name]);
4263 }
4264
4265
4266 - (void)sendEvent: (NSEvent *)theEvent
4267 /* --------------------------------------------------------------------------
4268 Called when NSApp is running for each event received. Used to stop
4269 the loop when we choose, since there's no way to just run one iteration.
4270 -------------------------------------------------------------------------- */
4271 {
4272 int type = [theEvent type];
4273 NSWindow *window = [theEvent window];
4274 /* NSTRACE (sendEvent); */
4275 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4276
4277 #ifdef NS_IMPL_COCOA
4278 if (type == NSApplicationDefined
4279 && [theEvent data2] == NSAPP_DATA2_RUNASSCRIPT)
4280 {
4281 ns_run_ascript ();
4282 [self stop: self];
4283 return;
4284 }
4285 #endif
4286
4287 if (type == NSCursorUpdate && window == nil)
4288 {
4289 fprintf (stderr, "Dropping external cursor update event.\n");
4290 return;
4291 }
4292
4293 #ifdef NS_IMPL_COCOA
4294 /* pass mouse down in resize handle and subsequent drags directly to
4295 EmacsWindow so we can generate continuous redisplays */
4296 if (ns_in_resize)
4297 {
4298 if (type == NSLeftMouseDragged)
4299 {
4300 [window mouseDragged: theEvent];
4301 return;
4302 }
4303 else if (type == NSLeftMouseUp)
4304 {
4305 [window mouseUp: theEvent];
4306 return;
4307 }
4308 }
4309 else if (type == NSLeftMouseDown)
4310 {
4311 NSRect r = ns_resize_handle_rect (window);
4312 if (NSPointInRect ([theEvent locationInWindow], r))
4313 {
4314 ns_in_resize = YES;
4315 [window mouseDown: theEvent];
4316 return;
4317 }
4318 }
4319 #endif
4320
4321 if (type == NSApplicationDefined)
4322 {
4323 /* Events posted by ns_send_appdefined interrupt the run loop here.
4324 But, if a modal window is up, an appdefined can still come through,
4325 (e.g., from a makeKeyWindow event) but stopping self also stops the
4326 modal loop. Just defer it until later. */
4327 if ([NSApp modalWindow] == nil)
4328 {
4329 last_appdefined_event = theEvent;
4330 [self stop: self];
4331 }
4332 else
4333 {
4334 send_appdefined = YES;
4335 }
4336 }
4337
4338 [super sendEvent: theEvent];
4339 }
4340
4341
4342 - (void)showPreferencesWindow: (id)sender
4343 {
4344 struct frame *emacsframe = SELECTED_FRAME ();
4345 NSEvent *theEvent = [NSApp currentEvent];
4346
4347 if (!emacs_event)
4348 return;
4349 emacs_event->kind = NS_NONKEY_EVENT;
4350 emacs_event->code = KEY_NS_SHOW_PREFS;
4351 emacs_event->modifiers = 0;
4352 EV_TRAILER (theEvent);
4353 }
4354
4355
4356 - (void)newFrame: (id)sender
4357 {
4358 struct frame *emacsframe = SELECTED_FRAME ();
4359 NSEvent *theEvent = [NSApp currentEvent];
4360
4361 if (!emacs_event)
4362 return;
4363 emacs_event->kind = NS_NONKEY_EVENT;
4364 emacs_event->code = KEY_NS_NEW_FRAME;
4365 emacs_event->modifiers = 0;
4366 EV_TRAILER (theEvent);
4367 }
4368
4369
4370 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4371 - (BOOL) openFile: (NSString *)fileName
4372 {
4373 struct frame *emacsframe = SELECTED_FRAME ();
4374 NSEvent *theEvent = [NSApp currentEvent];
4375
4376 if (!emacs_event)
4377 return NO;
4378
4379 emacs_event->kind = NS_NONKEY_EVENT;
4380 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4381 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4382 ns_input_line = Qnil; /* can be start or cons start,end */
4383 emacs_event->modifiers =0;
4384 EV_TRAILER (theEvent);
4385
4386 return YES;
4387 }
4388
4389
4390 /* **************************************************************************
4391
4392 EmacsApp delegate implementation
4393
4394 ************************************************************************** */
4395
4396 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4397 /* --------------------------------------------------------------------------
4398 When application is loaded, terminate event loop in ns_term_init
4399 -------------------------------------------------------------------------- */
4400 {
4401 NSTRACE (applicationDidFinishLaunching);
4402 [NSApp setServicesProvider: NSApp];
4403 ns_send_appdefined (-2);
4404 }
4405
4406
4407 /* Termination sequences:
4408 C-x C-c:
4409 Cmd-Q:
4410 MenuBar | File | Exit:
4411 Select Quit from App menubar:
4412 -terminate
4413 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4414 ns_term_shutdown()
4415
4416 Select Quit from Dock menu:
4417 Logout attempt:
4418 -appShouldTerminate
4419 Cancel -> Nothing else
4420 Accept ->
4421
4422 -terminate
4423 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4424 ns_term_shutdown()
4425
4426 */
4427
4428 - (void) terminate: (id)sender
4429 {
4430 struct frame *emacsframe = SELECTED_FRAME ();
4431
4432 if (!emacs_event)
4433 return;
4434
4435 emacs_event->kind = NS_NONKEY_EVENT;
4436 emacs_event->code = KEY_NS_POWER_OFF;
4437 emacs_event->arg = Qt; /* mark as non-key event */
4438 EV_TRAILER ((id)nil);
4439 }
4440
4441
4442 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4443 {
4444 int ret;
4445
4446 if (NILP (ns_confirm_quit)) // || ns_shutdown_properly --> TO DO
4447 return NSTerminateNow;
4448
4449 ret = NSRunAlertPanel(ns_app_name,
4450 [NSString stringWithUTF8String:"Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?"],
4451 @"Save Buffers and Exit", @"Cancel", nil);
4452
4453 if (ret == NSAlertDefaultReturn)
4454 return NSTerminateNow;
4455 else if (ret == NSAlertAlternateReturn)
4456 return NSTerminateCancel;
4457 return NSTerminateNow; /* just in case */
4458 }
4459
4460
4461 /* Notification from the Workspace to open a file */
4462 - (BOOL)application: sender openFile: (NSString *)file
4463 {
4464 [ns_pending_files addObject: file];
4465 return YES;
4466 }
4467
4468
4469 /* Open a file as a temporary file */
4470 - (BOOL)application: sender openTempFile: (NSString *)file
4471 {
4472 [ns_pending_files addObject: file];
4473 return YES;
4474 }
4475
4476
4477 /* Notification from the Workspace to open a file noninteractively (?) */
4478 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4479 {
4480 [ns_pending_files addObject: file];
4481 return YES;
4482 }
4483
4484
4485 /* Notification from the Workspace to open multiple files */
4486 - (void)application: sender openFiles: (NSArray *)fileList
4487 {
4488 NSEnumerator *files = [fileList objectEnumerator];
4489 NSString *file;
4490 while ((file = [files nextObject]) != nil)
4491 [ns_pending_files addObject: file];
4492
4493 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4494
4495 }
4496
4497
4498 /* Handle dock menu requests. */
4499 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4500 {
4501 return dockMenu;
4502 }
4503
4504
4505 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4506 - (void)applicationWillBecomeActive: (NSNotification *)notification
4507 {
4508 //ns_app_active=YES;
4509 }
4510 - (void)applicationDidBecomeActive: (NSNotification *)notification
4511 {
4512 NSTRACE (applicationDidBecomeActive);
4513
4514 //ns_app_active=YES;
4515
4516 ns_update_auto_hide_menu_bar ();
4517 // No constraining takes place when the application is not active.
4518 ns_constrain_all_frames ();
4519 }
4520 - (void)applicationDidResignActive: (NSNotification *)notification
4521 {
4522 //ns_app_active=NO;
4523 ns_send_appdefined (-1);
4524 }
4525
4526
4527
4528 /* ==========================================================================
4529
4530 EmacsApp aux handlers for managing event loop
4531
4532 ========================================================================== */
4533
4534
4535 - (void)timeout_handler: (NSTimer *)timedEntry
4536 /* --------------------------------------------------------------------------
4537 The timeout specified to ns_select has passed.
4538 -------------------------------------------------------------------------- */
4539 {
4540 /*NSTRACE (timeout_handler); */
4541 ns_send_appdefined (-2);
4542 }
4543
4544 - (void)fd_handler: (NSTimer *) fdEntry
4545 /* --------------------------------------------------------------------------
4546 Check data waiting on file descriptors and terminate if so
4547 -------------------------------------------------------------------------- */
4548 {
4549 int result;
4550 /* NSTRACE (fd_handler); */
4551
4552 if (select_nfds == 0)
4553 return;
4554
4555 memcpy (&t_readfds, &select_readfds, sizeof (fd_set));
4556
4557 select_timeout.tv_sec = select_timeout.tv_usec = 0;
4558 result = select (select_nfds, &t_readfds, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
4559 &select_timeout);
4560 if (result)
4561 {
4562 memcpy (&select_readfds, &t_readfds, sizeof (fd_set));
4563 ns_send_appdefined (result);
4564 }
4565 }
4566
4567
4568
4569 /* ==========================================================================
4570
4571 Service provision
4572
4573 ========================================================================== */
4574
4575 /* called from system: queue for next pass through event loop */
4576 - (void)requestService: (NSPasteboard *)pboard
4577 userData: (NSString *)userData
4578 error: (NSString **)error
4579 {
4580 [ns_pending_service_names addObject: userData];
4581 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
4582 SDATA (ns_string_from_pasteboard (pboard))]];
4583 }
4584
4585
4586 /* called from ns_read_socket to clear queue */
4587 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
4588 {
4589 struct frame *emacsframe = SELECTED_FRAME ();
4590 NSEvent *theEvent = [NSApp currentEvent];
4591
4592 if (!emacs_event)
4593 return NO;
4594
4595 emacs_event->kind = NS_NONKEY_EVENT;
4596 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
4597 ns_input_spi_name = build_string ([name UTF8String]);
4598 ns_input_spi_arg = build_string ([arg UTF8String]);
4599 emacs_event->modifiers = EV_MODIFIERS (theEvent);
4600 EV_TRAILER (theEvent);
4601
4602 return YES;
4603 }
4604
4605
4606 @end /* EmacsApp */
4607
4608
4609
4610 /* ==========================================================================
4611
4612 EmacsView implementation
4613
4614 ========================================================================== */
4615
4616
4617 @implementation EmacsView
4618
4619 /* needed to inform when window closed from LISP */
4620 - (void) setWindowClosing: (BOOL)closing
4621 {
4622 windowClosing = closing;
4623 }
4624
4625
4626 - (void)dealloc
4627 {
4628 NSTRACE (EmacsView_dealloc);
4629 [toolbar release];
4630 [super dealloc];
4631 }
4632
4633
4634 /* called on font panel selection */
4635 - (void)changeFont: (id)sender
4636 {
4637 NSEvent *e =[[self window] currentEvent];
4638 struct face *face =FRAME_DEFAULT_FACE (emacsframe);
4639 id newFont;
4640 float size;
4641
4642 NSTRACE (changeFont);
4643 if (!emacs_event)
4644 return;
4645
4646 if (newFont = [sender convertFont:
4647 ((struct nsfont_info *)face->font)->nsfont])
4648 {
4649 SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
4650
4651 emacs_event->kind = NS_NONKEY_EVENT;
4652 emacs_event->modifiers = 0;
4653 emacs_event->code = KEY_NS_CHANGE_FONT;
4654
4655 size = [newFont pointSize];
4656 ns_input_fontsize = make_number (lrint (size));
4657 ns_input_font = build_string ([[newFont familyName] UTF8String]);
4658 EV_TRAILER (e);
4659 }
4660 }
4661
4662
4663 - (BOOL)acceptsFirstResponder
4664 {
4665 NSTRACE (acceptsFirstResponder);
4666 return YES;
4667 }
4668
4669
4670 - (void)resetCursorRects
4671 {
4672 NSRect visible = [self visibleRect];
4673 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
4674 NSTRACE (resetCursorRects);
4675
4676 if (currentCursor == nil)
4677 currentCursor = [NSCursor arrowCursor];
4678
4679 if (!NSIsEmptyRect (visible))
4680 [self addCursorRect: visible cursor: currentCursor];
4681 [currentCursor setOnMouseEntered: YES];
4682 }
4683
4684
4685
4686 /*****************************************************************************/
4687 /* Keyboard handling. */
4688 #define NS_KEYLOG 0
4689
4690 - (void)keyDown: (NSEvent *)theEvent
4691 {
4692 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
4693 int code;
4694 unsigned fnKeysym = 0;
4695 int flags;
4696 static NSMutableArray *nsEvArray;
4697 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
4698 static BOOL firstTime = YES;
4699 #endif
4700 int left_is_none;
4701
4702 NSTRACE (keyDown);
4703
4704 /* Rhapsody and OS X give up and down events for the arrow keys */
4705 if (ns_fake_keydown == YES)
4706 ns_fake_keydown = NO;
4707 else if ([theEvent type] != NSKeyDown)
4708 return;
4709
4710 if (!emacs_event)
4711 return;
4712
4713 if (![[self window] isKeyWindow]
4714 && [[theEvent window] isKindOfClass: [EmacsWindow class]]
4715 /* we must avoid an infinite loop here. */
4716 && (EmacsView *)[[theEvent window] delegate] != self)
4717 {
4718 /* XXX: There is an occasional condition in which, when Emacs display
4719 updates a different frame from the current one, and temporarily
4720 selects it, then processes some interrupt-driven input
4721 (dispnew.c:3878), OS will send the event to the correct NSWindow, but
4722 for some reason that window has its first responder set to the NSView
4723 most recently updated (I guess), which is not the correct one. */
4724 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
4725 return;
4726 }
4727
4728 if (nsEvArray == nil)
4729 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
4730
4731 [NSCursor setHiddenUntilMouseMoves: YES];
4732
4733 if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
4734 {
4735 clear_mouse_face (hlinfo);
4736 hlinfo->mouse_face_hidden = 1;
4737 }
4738
4739 if (!processingCompose)
4740 {
4741 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
4742 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
4743 /* (Carbon way: [theEvent keyCode]) */
4744
4745 /* is it a "function key"? */
4746 fnKeysym = ns_convert_key (code);
4747 if (fnKeysym)
4748 {
4749 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
4750 because Emacs treats Delete and KP-Delete same (in simple.el). */
4751 if (fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
4752 code = 0xFF08; /* backspace */
4753 else
4754 code = fnKeysym;
4755 }
4756
4757 /* are there modifiers? */
4758 emacs_event->modifiers = 0;
4759 flags = [theEvent modifierFlags];
4760
4761 if (flags & NSHelpKeyMask)
4762 emacs_event->modifiers |= hyper_modifier;
4763
4764 if (flags & NSShiftKeyMask)
4765 emacs_event->modifiers |= shift_modifier;
4766
4767 if ((flags & NSRightCommandKeyMask) == NSRightCommandKeyMask)
4768 emacs_event->modifiers |= parse_solitary_modifier
4769 (EQ (ns_right_command_modifier, Qleft)
4770 ? ns_command_modifier
4771 : ns_right_command_modifier);
4772
4773 if ((flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask)
4774 {
4775 emacs_event->modifiers |= parse_solitary_modifier
4776 (ns_command_modifier);
4777
4778 /* if super (default), take input manager's word so things like
4779 dvorak / qwerty layout work */
4780 if (EQ (ns_command_modifier, Qsuper)
4781 && !fnKeysym
4782 && [[theEvent characters] length] != 0)
4783 {
4784 /* XXX: the code we get will be unshifted, so if we have
4785 a shift modifier, must convert ourselves */
4786 if (!(flags & NSShiftKeyMask))
4787 code = [[theEvent characters] characterAtIndex: 0];
4788 #if 0
4789 /* this is ugly and also requires linking w/Carbon framework
4790 (for LMGetKbdType) so for now leave this rare (?) case
4791 undealt with.. in future look into CGEvent methods */
4792 else
4793 {
4794 long smv = GetScriptManagerVariable (smKeyScript);
4795 Handle uchrHandle = GetResource
4796 ('uchr', GetScriptVariable (smv, smScriptKeys));
4797 UInt32 dummy = 0;
4798 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
4799 [[theEvent characters] characterAtIndex: 0],
4800 kUCKeyActionDisplay,
4801 (flags & ~NSCommandKeyMask) >> 8,
4802 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
4803 &dummy, 1, &dummy, &code);
4804 code &= 0xFF;
4805 }
4806 #endif
4807 }
4808 }
4809
4810 if ((flags & NSRightControlKeyMask) == NSRightControlKeyMask)
4811 emacs_event->modifiers |= parse_solitary_modifier
4812 (EQ (ns_right_control_modifier, Qleft)
4813 ? ns_control_modifier
4814 : ns_right_control_modifier);
4815
4816 if ((flags & NSLeftControlKeyMask) == NSLeftControlKeyMask)
4817 emacs_event->modifiers |= parse_solitary_modifier
4818 (ns_control_modifier);
4819
4820 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
4821 emacs_event->modifiers |=
4822 parse_solitary_modifier (ns_function_modifier);
4823
4824 left_is_none = NILP (ns_alternate_modifier)
4825 || EQ (ns_alternate_modifier, Qnone);
4826
4827 if ((flags & NSRightAlternateKeyMask) == NSRightAlternateKeyMask)
4828 {
4829 if ((NILP (ns_right_alternate_modifier)
4830 || EQ (ns_right_alternate_modifier, Qnone)
4831 || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
4832 && !fnKeysym)
4833 { /* accept pre-interp alt comb */
4834 if ([[theEvent characters] length] > 0)
4835 code = [[theEvent characters] characterAtIndex: 0];
4836 /*HACK: clear lone shift modifier to stop next if from firing */
4837 if (emacs_event->modifiers == shift_modifier)
4838 emacs_event->modifiers = 0;
4839 }
4840 else
4841 emacs_event->modifiers |= parse_solitary_modifier
4842 (EQ (ns_right_alternate_modifier, Qleft)
4843 ? ns_alternate_modifier
4844 : ns_right_alternate_modifier);
4845 }
4846
4847 if ((flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask) /* default = meta */
4848 {
4849 if (left_is_none && !fnKeysym)
4850 { /* accept pre-interp alt comb */
4851 if ([[theEvent characters] length] > 0)
4852 code = [[theEvent characters] characterAtIndex: 0];
4853 /*HACK: clear lone shift modifier to stop next if from firing */
4854 if (emacs_event->modifiers == shift_modifier)
4855 emacs_event->modifiers = 0;
4856 }
4857 else
4858 emacs_event->modifiers |=
4859 parse_solitary_modifier (ns_alternate_modifier);
4860 }
4861
4862 if (NS_KEYLOG)
4863 fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
4864 code, fnKeysym, flags, emacs_event->modifiers);
4865
4866 /* if it was a function key or had modifiers, pass it directly to emacs */
4867 if (fnKeysym || (emacs_event->modifiers
4868 && (emacs_event->modifiers != shift_modifier)
4869 && [[theEvent charactersIgnoringModifiers] length] > 0))
4870 /*[[theEvent characters] length] */
4871 {
4872 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4873 if (code < 0x20)
4874 code |= (1<<28)|(3<<16);
4875 else if (code == 0x7f)
4876 code |= (1<<28)|(3<<16);
4877 else if (!fnKeysym)
4878 emacs_event->kind = code > 0xFF
4879 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4880
4881 emacs_event->code = code;
4882 EV_TRAILER (theEvent);
4883 return;
4884 }
4885 }
4886
4887
4888 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
4889 /* if we get here we should send the key for input manager processing */
4890 if (firstTime && [[NSInputManager currentInputManager]
4891 wantsToDelayTextChangeNotifications] == NO)
4892 fprintf (stderr,
4893 "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
4894 firstTime = NO;
4895 #endif
4896 if (NS_KEYLOG && !processingCompose)
4897 fprintf (stderr, "keyDown: Begin compose sequence.\n");
4898
4899 processingCompose = YES;
4900 [nsEvArray addObject: theEvent];
4901 [self interpretKeyEvents: nsEvArray];
4902 [nsEvArray removeObject: theEvent];
4903 }
4904
4905
4906 #ifdef NS_IMPL_COCOA
4907 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
4908 decided not to send key-down for.
4909 See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
4910 This only applies on Tiger and earlier.
4911 If it matches one of these, send it on to keyDown. */
4912 -(void)keyUp: (NSEvent *)theEvent
4913 {
4914 int flags = [theEvent modifierFlags];
4915 int code = [theEvent keyCode];
4916 if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
4917 code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
4918 {
4919 if (NS_KEYLOG)
4920 fprintf (stderr, "keyUp: passed test");
4921 ns_fake_keydown = YES;
4922 [self keyDown: theEvent];
4923 }
4924 }
4925 #endif
4926
4927
4928 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
4929
4930
4931 /* <NSTextInput>: called when done composing;
4932 NOTE: also called when we delete over working text, followed immed.
4933 by doCommandBySelector: deleteBackward: */
4934 - (void)insertText: (id)aString
4935 {
4936 int code;
4937 int len = [(NSString *)aString length];
4938 int i;
4939
4940 if (NS_KEYLOG)
4941 NSLog (@"insertText '%@'\tlen = %d", aString, len);
4942 processingCompose = NO;
4943
4944 if (!emacs_event)
4945 return;
4946
4947 /* first, clear any working text */
4948 if (workingText != nil)
4949 [self deleteWorkingText];
4950
4951 /* now insert the string as keystrokes */
4952 for (i =0; i<len; i++)
4953 {
4954 code = [aString characterAtIndex: i];
4955 /* TODO: still need this? */
4956 if (code == 0x2DC)
4957 code = '~'; /* 0x7E */
4958 emacs_event->modifiers = 0;
4959 emacs_event->kind
4960 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4961 emacs_event->code = code;
4962 EV_TRAILER ((id)nil);
4963 }
4964 }
4965
4966
4967 /* <NSTextInput>: inserts display of composing characters */
4968 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
4969 {
4970 NSString *str = [aString respondsToSelector: @selector (string)] ?
4971 [aString string] : aString;
4972 if (NS_KEYLOG)
4973 NSLog (@"setMarkedText '%@' len =%d range %d from %d", str, [str length],
4974 selRange.length, selRange.location);
4975
4976 if (workingText != nil)
4977 [self deleteWorkingText];
4978 if ([str length] == 0)
4979 return;
4980
4981 if (!emacs_event)
4982 return;
4983
4984 processingCompose = YES;
4985 workingText = [str copy];
4986 ns_working_text = build_string ([workingText UTF8String]);
4987
4988 emacs_event->kind = NS_TEXT_EVENT;
4989 emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
4990 EV_TRAILER ((id)nil);
4991 }
4992
4993
4994 /* delete display of composing characters [not in <NSTextInput>] */
4995 - (void)deleteWorkingText
4996 {
4997 if (workingText == nil)
4998 return;
4999 if (NS_KEYLOG)
5000 NSLog(@"deleteWorkingText len =%d\n", [workingText length]);
5001 [workingText release];
5002 workingText = nil;
5003 processingCompose = NO;
5004
5005 if (!emacs_event)
5006 return;
5007
5008 emacs_event->kind = NS_TEXT_EVENT;
5009 emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
5010 EV_TRAILER ((id)nil);
5011 }
5012
5013
5014 - (BOOL)hasMarkedText
5015 {
5016 return workingText != nil;
5017 }
5018
5019
5020 - (NSRange)markedRange
5021 {
5022 NSRange rng = workingText != nil
5023 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
5024 if (NS_KEYLOG)
5025 NSLog (@"markedRange request");
5026 return rng;
5027 }
5028
5029
5030 - (void)unmarkText
5031 {
5032 if (NS_KEYLOG)
5033 NSLog (@"unmark (accept) text");
5034 [self deleteWorkingText];
5035 processingCompose = NO;
5036 }
5037
5038
5039 /* used to position char selection windows, etc. */
5040 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
5041 {
5042 NSRect rect;
5043 NSPoint pt;
5044 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
5045 if (NS_KEYLOG)
5046 NSLog (@"firstRectForCharRange request");
5047
5048 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
5049 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
5050 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
5051 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
5052 +FRAME_LINE_HEIGHT (emacsframe));
5053
5054 pt = [self convertPoint: pt toView: nil];
5055 pt = [[self window] convertBaseToScreen: pt];
5056 rect.origin = pt;
5057 return rect;
5058 }
5059
5060
5061 - (long)conversationIdentifier
5062 {
5063 return (long)self;
5064 }
5065
5066
5067 - (void)doCommandBySelector: (SEL)aSelector
5068 {
5069 if (NS_KEYLOG)
5070 NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
5071
5072 if (aSelector == @selector (deleteBackward:))
5073 {
5074 /* happens when user backspaces over an ongoing composition:
5075 throw a 'delete' into the event queue */
5076 if (!emacs_event)
5077 return;
5078 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5079 emacs_event->code = 0xFF08;
5080 EV_TRAILER ((id)nil);
5081 }
5082 }
5083
5084 - (NSArray *)validAttributesForMarkedText
5085 {
5086 static NSArray *arr = nil;
5087 if (arr == nil) arr = [NSArray new];
5088 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
5089 return arr;
5090 }
5091
5092 - (NSRange)selectedRange
5093 {
5094 if (NS_KEYLOG)
5095 NSLog (@"selectedRange request");
5096 return NSMakeRange (NSNotFound, 0);
5097 }
5098
5099 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
5100 {
5101 if (NS_KEYLOG)
5102 NSLog (@"characterIndexForPoint request");
5103 return 0;
5104 }
5105
5106 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
5107 {
5108 static NSAttributedString *str = nil;
5109 if (str == nil) str = [NSAttributedString new];
5110 if (NS_KEYLOG)
5111 NSLog (@"attributedSubstringFromRange request");
5112 return str;
5113 }
5114
5115 /* End <NSTextInput> impl. */
5116 /*****************************************************************************/
5117
5118
5119 /* This is what happens when the user presses a mouse button. */
5120 - (void)mouseDown: (NSEvent *)theEvent
5121 {
5122 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5123 Lisp_Object window;
5124
5125 NSTRACE (mouseDown);
5126
5127 [self deleteWorkingText];
5128
5129 if (!emacs_event)
5130 return;
5131
5132 last_mouse_frame = emacsframe;
5133 /* appears to be needed to prevent spurious movement events generated on
5134 button clicks */
5135 last_mouse_frame->mouse_moved = 0;
5136
5137 if ([theEvent type] == NSScrollWheel)
5138 {
5139 float delta = [theEvent deltaY];
5140 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
5141 if (delta == 0)
5142 return;
5143 emacs_event->kind = WHEEL_EVENT;
5144 emacs_event->code = 0;
5145 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
5146 ((delta > 0) ? up_modifier : down_modifier);
5147 }
5148 else
5149 {
5150 emacs_event->kind = MOUSE_CLICK_EVENT;
5151 emacs_event->code = EV_BUTTON (theEvent);
5152 emacs_event->modifiers = EV_MODIFIERS (theEvent)
5153 | EV_UDMODIFIERS (theEvent);
5154 }
5155 XSETINT (emacs_event->x, lrint (p.x));
5156 XSETINT (emacs_event->y, lrint (p.y));
5157 EV_TRAILER (theEvent);
5158 }
5159
5160
5161 - (void)rightMouseDown: (NSEvent *)theEvent
5162 {
5163 NSTRACE (rightMouseDown);
5164 [self mouseDown: theEvent];
5165 }
5166
5167
5168 - (void)otherMouseDown: (NSEvent *)theEvent
5169 {
5170 NSTRACE (otherMouseDown);
5171 [self mouseDown: theEvent];
5172 }
5173
5174
5175 - (void)mouseUp: (NSEvent *)theEvent
5176 {
5177 NSTRACE (mouseUp);
5178 [self mouseDown: theEvent];
5179 }
5180
5181
5182 - (void)rightMouseUp: (NSEvent *)theEvent
5183 {
5184 NSTRACE (rightMouseUp);
5185 [self mouseDown: theEvent];
5186 }
5187
5188
5189 - (void)otherMouseUp: (NSEvent *)theEvent
5190 {
5191 NSTRACE (otherMouseUp);
5192 [self mouseDown: theEvent];
5193 }
5194
5195
5196 - (void) scrollWheel: (NSEvent *)theEvent
5197 {
5198 NSTRACE (scrollWheel);
5199 [self mouseDown: theEvent];
5200 }
5201
5202
5203 /* Tell emacs the mouse has moved. */
5204 - (void)mouseMoved: (NSEvent *)e
5205 {
5206 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5207 Lisp_Object frame;
5208
5209 // NSTRACE (mouseMoved);
5210
5211 last_mouse_movement_time = EV_TIMESTAMP (e);
5212 last_mouse_motion_position
5213 = [self convertPoint: [e locationInWindow] fromView: nil];
5214
5215 /* update any mouse face */
5216 if (hlinfo->mouse_face_hidden)
5217 {
5218 hlinfo->mouse_face_hidden = 0;
5219 clear_mouse_face (hlinfo);
5220 }
5221
5222 /* tooltip handling */
5223 previous_help_echo_string = help_echo_string;
5224 help_echo_string = Qnil;
5225
5226 if (!note_mouse_movement (emacsframe, last_mouse_motion_position.x,
5227 last_mouse_motion_position.y))
5228 help_echo_string = previous_help_echo_string;
5229
5230 XSETFRAME (frame, emacsframe);
5231 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
5232 {
5233 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
5234 (note_mouse_highlight), which is called through the
5235 note_mouse_movement () call above */
5236 gen_help_event (help_echo_string, frame, help_echo_window,
5237 help_echo_object, help_echo_pos);
5238 }
5239 else
5240 {
5241 help_echo_string = Qnil;
5242 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
5243 }
5244
5245 if (emacsframe->mouse_moved && send_appdefined)
5246 ns_send_appdefined (-1);
5247 }
5248
5249
5250 - (void)mouseDragged: (NSEvent *)e
5251 {
5252 NSTRACE (mouseDragged);
5253 [self mouseMoved: e];
5254 }
5255
5256
5257 - (void)rightMouseDragged: (NSEvent *)e
5258 {
5259 NSTRACE (rightMouseDragged);
5260 [self mouseMoved: e];
5261 }
5262
5263
5264 - (void)otherMouseDragged: (NSEvent *)e
5265 {
5266 NSTRACE (otherMouseDragged);
5267 [self mouseMoved: e];
5268 }
5269
5270
5271 - (BOOL)windowShouldClose: (id)sender
5272 {
5273 NSEvent *e =[[self window] currentEvent];
5274
5275 NSTRACE (windowShouldClose);
5276 windowClosing = YES;
5277 if (!emacs_event)
5278 return NO;
5279 emacs_event->kind = DELETE_WINDOW_EVENT;
5280 emacs_event->modifiers = 0;
5281 emacs_event->code = 0;
5282 EV_TRAILER (e);
5283 /* Don't close this window, let this be done from lisp code. */
5284 return NO;
5285 }
5286
5287
5288 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
5289 /* normalize frame to gridded text size */
5290 {
5291 NSTRACE (windowWillResize);
5292 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
5293
5294 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe,
5295 #ifdef NS_IMPL_GNUSTEP
5296 frameSize.width + 3);
5297 #else
5298 frameSize.width);
5299 #endif
5300 if (cols < MINWIDTH)
5301 cols = MINWIDTH;
5302
5303 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, frameSize.height
5304 #ifdef NS_IMPL_GNUSTEP
5305 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe) + 3
5306 - FRAME_TOOLBAR_HEIGHT (emacsframe));
5307 #else
5308 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5309 - FRAME_TOOLBAR_HEIGHT (emacsframe));
5310 #endif
5311 if (rows < MINHEIGHT)
5312 rows = MINHEIGHT;
5313 #ifdef NS_IMPL_COCOA
5314 {
5315 /* this sets window title to have size in it; the wm does this under GS */
5316 NSRect r = [[self window] frame];
5317 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
5318 {
5319 if (old_title != 0)
5320 {
5321 xfree (old_title);
5322 old_title = 0;
5323 }
5324 }
5325 else
5326 {
5327 char *size_title;
5328 NSWindow *window = [self window];
5329 if (old_title == 0)
5330 {
5331 const char *t = [[[self window] title] UTF8String];
5332 char *pos = strstr (t, " — ");
5333 if (pos)
5334 *pos = '\0';
5335 old_title = (char *) xmalloc (strlen (t) + 1);
5336 strcpy (old_title, t);
5337 }
5338 size_title = xmalloc (strlen (old_title) + 40);
5339 esprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
5340 [window setTitle: [NSString stringWithUTF8String: size_title]];
5341 [window display];
5342 xfree (size_title);
5343 }
5344 }
5345 #endif /* NS_IMPL_COCOA */
5346 /*fprintf (stderr," ...size became %.0f x %.0f (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
5347
5348 return frameSize;
5349 }
5350
5351
5352 - (void)windowDidResize: (NSNotification *)notification
5353 {
5354 NSWindow *theWindow = [notification object];
5355
5356 #ifdef NS_IMPL_GNUSTEP
5357 /* in GNUstep, at least currently, it's possible to get a didResize
5358 without getting a willResize.. therefore we need to act as if we got
5359 the willResize now */
5360 NSSize sz = [theWindow frame].size;
5361 sz = [self windowWillResize: theWindow toSize: sz];
5362 #endif /* NS_IMPL_GNUSTEP */
5363
5364 NSTRACE (windowDidResize);
5365 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
5366
5367 #ifdef NS_IMPL_COCOA
5368 if (old_title != 0)
5369 {
5370 xfree (old_title);
5371 old_title = 0;
5372 }
5373 #endif /* NS_IMPL_COCOA */
5374
5375 /* Avoid loop under GNUstep due to call at beginning of this function.
5376 (x_set_window_size causes a resize which causes
5377 a "windowDidResize" which calls x_set_window_size). */
5378 #ifndef NS_IMPL_GNUSTEP
5379 if (cols > 0 && rows > 0)
5380 {
5381 if (ns_in_resize)
5382 x_set_window_size (emacsframe, 0, cols, rows);
5383 else
5384 {
5385 NSWindow *window = [self window];
5386 NSRect wr = [window frame];
5387 FRAME_PIXEL_WIDTH (emacsframe) = (int)wr.size.width
5388 - emacsframe->border_width;
5389 FRAME_PIXEL_HEIGHT (emacsframe) = (int)wr.size.height
5390 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5391 - FRAME_TOOLBAR_HEIGHT (emacsframe);
5392 change_frame_size (emacsframe, rows, cols, 0, 0, 1);
5393 SET_FRAME_GARBAGED (emacsframe);
5394 cancel_mouse_face (emacsframe);
5395 }
5396 }
5397 #endif
5398
5399 ns_send_appdefined (-1);
5400 }
5401
5402
5403 - (void)windowDidBecomeKey: (NSNotification *)notification
5404 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5405 {
5406 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5407 struct frame *old_focus = dpyinfo->x_focus_frame;
5408
5409 NSTRACE (windowDidBecomeKey);
5410
5411 if (emacsframe != old_focus)
5412 dpyinfo->x_focus_frame = emacsframe;
5413
5414 ns_frame_rehighlight (emacsframe);
5415
5416 if (emacs_event)
5417 {
5418 emacs_event->kind = FOCUS_IN_EVENT;
5419 EV_TRAILER ((id)nil);
5420 }
5421 }
5422
5423
5424 - (void)windowDidResignKey: (NSNotification *)notification
5425 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5426 {
5427 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5428 NSTRACE (windowDidResignKey);
5429
5430 if (dpyinfo->x_focus_frame == emacsframe)
5431 dpyinfo->x_focus_frame = 0;
5432
5433 ns_frame_rehighlight (emacsframe);
5434
5435 /* FIXME: for some reason needed on second and subsequent clicks away
5436 from sole-frame Emacs to get hollow box to show */
5437 if (!windowClosing && [[self window] isVisible] == YES)
5438 {
5439 x_update_cursor (emacsframe, 1);
5440 x_set_frame_alpha (emacsframe);
5441 }
5442
5443 if (emacs_event)
5444 {
5445 [self deleteWorkingText];
5446 emacs_event->kind = FOCUS_IN_EVENT;
5447 EV_TRAILER ((id)nil);
5448 }
5449 }
5450
5451
5452 - (void)windowWillMiniaturize: sender
5453 {
5454 NSTRACE (windowWillMiniaturize);
5455 }
5456
5457
5458 - (BOOL)isFlipped
5459 {
5460 return YES;
5461 }
5462
5463
5464 - (BOOL)isOpaque
5465 {
5466 return NO;
5467 }
5468
5469
5470 - initFrameFromEmacs: (struct frame *)f
5471 {
5472 NSRect r, wr;
5473 Lisp_Object tem;
5474 NSWindow *win;
5475 NSButton *toggleButton;
5476 int vbextra = NS_SCROLL_BAR_WIDTH (f);
5477 NSSize sz;
5478 NSColor *col;
5479 NSString *name;
5480
5481 NSTRACE (initFrameFromEmacs);
5482
5483 windowClosing = NO;
5484 processingCompose = NO;
5485 scrollbarsNeedingUpdate = 0;
5486
5487 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
5488
5489 ns_userRect = NSMakeRect (0, 0, 0, 0);
5490 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
5491 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
5492 [self initWithFrame: r];
5493 [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
5494
5495 FRAME_NS_VIEW (f) = self;
5496 emacsframe = f;
5497 old_title = 0;
5498
5499 win = [[EmacsWindow alloc]
5500 initWithContentRect: r
5501 styleMask: (NSResizableWindowMask |
5502 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
5503 NSTitledWindowMask |
5504 #endif
5505 NSMiniaturizableWindowMask |
5506 NSClosableWindowMask)
5507 backing: NSBackingStoreBuffered
5508 defer: YES];
5509
5510 wr = [win frame];
5511 f->border_width = wr.size.width - r.size.width;
5512 FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
5513
5514 [win setAcceptsMouseMovedEvents: YES];
5515 [win setDelegate: self];
5516 [win useOptimizedDrawing: YES];
5517
5518 sz.width = FRAME_COLUMN_WIDTH (f);
5519 sz.height = FRAME_LINE_HEIGHT (f);
5520 [win setResizeIncrements: sz];
5521
5522 [[win contentView] addSubview: self];
5523
5524 if (ns_drag_types)
5525 [self registerForDraggedTypes: ns_drag_types];
5526
5527 tem = f->name;
5528 name = [NSString stringWithUTF8String:
5529 NILP (tem) ? (unsigned char *)"Emacs" : SDATA (tem)];
5530 [win setTitle: name];
5531
5532 /* toolbar support */
5533 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
5534 [NSString stringWithFormat: @"Emacs Frame %d",
5535 ns_window_num]];
5536 [win setToolbar: toolbar];
5537 [toolbar setVisible: NO];
5538 #ifdef NS_IMPL_COCOA
5539 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
5540 [toggleButton setTarget: self];
5541 [toggleButton setAction: @selector (toggleToolbar: )];
5542 #endif
5543 FRAME_TOOLBAR_HEIGHT (f) = 0;
5544
5545 tem = f->icon_name;
5546 if (!NILP (tem))
5547 [win setMiniwindowTitle:
5548 [NSString stringWithUTF8String: SDATA (tem)]];
5549
5550 {
5551 NSScreen *screen = [win screen];
5552
5553 if (screen != 0)
5554 [win setFrameTopLeftPoint: NSMakePoint
5555 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
5556 IN_BOUND (-SCREENMAX,
5557 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
5558 }
5559
5560 [win makeFirstResponder: self];
5561
5562 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5563 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
5564 [win setBackgroundColor: col];
5565 if ([col alphaComponent] != 1.0)
5566 [win setOpaque: NO];
5567
5568 [self allocateGState];
5569
5570 [NSApp registerServicesMenuSendTypes: ns_send_types
5571 returnTypes: nil];
5572
5573 ns_window_num++;
5574 return self;
5575 }
5576
5577
5578 - (void)windowDidMove: sender
5579 {
5580 NSWindow *win = [self window];
5581 NSRect r = [win frame];
5582 NSArray *screens = [NSScreen screens];
5583 NSScreen *screen = [screens objectAtIndex: 0];
5584
5585 NSTRACE (windowDidMove);
5586
5587 if (!emacsframe->output_data.ns)
5588 return;
5589 if (screen != nil)
5590 {
5591 emacsframe->left_pos = r.origin.x;
5592 emacsframe->top_pos =
5593 [screen frame].size.height - (r.origin.y + r.size.height);
5594 }
5595 }
5596
5597
5598 /* Called AFTER method below, but before our windowWillResize call there leads
5599 to windowDidResize -> x_set_window_size. Update emacs' notion of frame
5600 location so set_window_size moves the frame. */
5601 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
5602 {
5603 emacsframe->output_data.ns->zooming = 1;
5604 return YES;
5605 }
5606
5607
5608 /* Override to do something slightly nonstandard, but nice. First click on
5609 zoom button will zoom vertically. Second will zoom completely. Third
5610 returns to original. */
5611 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
5612 defaultFrame:(NSRect)defaultFrame
5613 {
5614 NSRect result = [sender frame];
5615
5616 NSTRACE (windowWillUseStandardFrame);
5617
5618 if (abs (defaultFrame.size.height - result.size.height)
5619 > FRAME_LINE_HEIGHT (emacsframe))
5620 {
5621 /* first click */
5622 ns_userRect = result;
5623 result.size.height = defaultFrame.size.height;
5624 result.origin.y = defaultFrame.origin.y;
5625 }
5626 else
5627 {
5628 if (abs (defaultFrame.size.width - result.size.width)
5629 > FRAME_COLUMN_WIDTH (emacsframe))
5630 result = defaultFrame; /* second click */
5631 else
5632 {
5633 /* restore */
5634 result = ns_userRect.size.height ? ns_userRect : result;
5635 ns_userRect = NSMakeRect (0, 0, 0, 0);
5636 }
5637 }
5638
5639 [self windowWillResize: sender toSize: result.size];
5640 return result;
5641 }
5642
5643
5644 - (void)windowDidDeminiaturize: sender
5645 {
5646 NSTRACE (windowDidDeminiaturize);
5647 if (!emacsframe->output_data.ns)
5648 return;
5649 emacsframe->async_iconified = 0;
5650 emacsframe->async_visible = 1;
5651 windows_or_buffers_changed++;
5652
5653 if (emacs_event)
5654 {
5655 emacs_event->kind = ICONIFY_EVENT;
5656 EV_TRAILER ((id)nil);
5657 }
5658 }
5659
5660
5661 - (void)windowDidExpose: sender
5662 {
5663 NSTRACE (windowDidExpose);
5664 if (!emacsframe->output_data.ns)
5665 return;
5666 emacsframe->async_visible = 1;
5667 SET_FRAME_GARBAGED (emacsframe);
5668
5669 if (send_appdefined)
5670 ns_send_appdefined (-1);
5671 }
5672
5673
5674 - (void)windowDidMiniaturize: sender
5675 {
5676 NSTRACE (windowDidMiniaturize);
5677 if (!emacsframe->output_data.ns)
5678 return;
5679
5680 emacsframe->async_iconified = 1;
5681 emacsframe->async_visible = 0;
5682
5683 if (emacs_event)
5684 {
5685 emacs_event->kind = ICONIFY_EVENT;
5686 EV_TRAILER ((id)nil);
5687 }
5688 }
5689
5690
5691 - (void)mouseEntered: (NSEvent *)theEvent
5692 {
5693 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5694 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5695 NSTRACE (mouseEntered);
5696
5697 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5698 }
5699
5700
5701 - (void)mouseExited: (NSEvent *)theEvent
5702 {
5703 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5704 NSRect r;
5705 Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
5706
5707 NSTRACE (mouseExited);
5708
5709 if (!hlinfo)
5710 return;
5711
5712 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5713
5714 if (emacsframe == hlinfo->mouse_face_mouse_frame)
5715 {
5716 clear_mouse_face (hlinfo);
5717 hlinfo->mouse_face_mouse_frame = 0;
5718 }
5719 }
5720
5721
5722 - menuDown: sender
5723 {
5724 NSTRACE (menuDown);
5725 if (context_menu_value == -1)
5726 context_menu_value = [sender tag];
5727 else
5728 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
5729 emacsframe->menu_bar_vector,
5730 (void *)[sender tag]);
5731 ns_send_appdefined (-1);
5732 return self;
5733 }
5734
5735
5736 - (EmacsToolbar *)toolbar
5737 {
5738 return toolbar;
5739 }
5740
5741
5742 /* this gets called on toolbar button click */
5743 - toolbarClicked: (id)item
5744 {
5745 NSEvent *theEvent;
5746 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
5747
5748 NSTRACE (toolbarClicked);
5749
5750 if (!emacs_event)
5751 return self;
5752
5753 /* send first event (for some reason two needed) */
5754 theEvent = [[self window] currentEvent];
5755 emacs_event->kind = TOOL_BAR_EVENT;
5756 XSETFRAME (emacs_event->arg, emacsframe);
5757 EV_TRAILER (theEvent);
5758
5759 emacs_event->kind = TOOL_BAR_EVENT;
5760 /* XSETINT (emacs_event->code, 0); */
5761 emacs_event->arg = AREF (emacsframe->tool_bar_items,
5762 idx + TOOL_BAR_ITEM_KEY);
5763 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5764 EV_TRAILER (theEvent);
5765 return self;
5766 }
5767
5768
5769 - toggleToolbar: (id)sender
5770 {
5771 if (!emacs_event)
5772 return self;
5773
5774 emacs_event->kind = NS_NONKEY_EVENT;
5775 emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
5776 EV_TRAILER ((id)nil);
5777 return self;
5778 }
5779
5780
5781 - (void)drawRect: (NSRect)rect
5782 {
5783 int x = NSMinX (rect), y = NSMinY (rect);
5784 int width = NSWidth (rect), height = NSHeight (rect);
5785
5786 NSTRACE (drawRect);
5787
5788 if (!emacsframe || !emacsframe->output_data.ns || ns_in_resize)
5789 return;
5790
5791 ns_clear_frame_area (emacsframe, x, y, width, height);
5792 expose_frame (emacsframe, x, y, width, height);
5793
5794 /*
5795 drawRect: may be called (at least in OS X 10.5) for invisible
5796 views as well for some reason. Thus, do not infer visibility
5797 here.
5798
5799 emacsframe->async_visible = 1;
5800 emacsframe->async_iconified = 0;
5801 */
5802 }
5803
5804
5805 /* NSDraggingDestination protocol methods. Actually this is not really a
5806 protocol, but a category of Object. O well... */
5807
5808 -(NSUInteger) draggingEntered: (id <NSDraggingInfo>) sender
5809 {
5810 NSTRACE (draggingEntered);
5811 return NSDragOperationGeneric;
5812 }
5813
5814
5815 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
5816 {
5817 return YES;
5818 }
5819
5820
5821 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
5822 {
5823 id pb;
5824 int x, y;
5825 NSString *type;
5826 NSEvent *theEvent = [[self window] currentEvent];
5827 NSPoint position;
5828
5829 NSTRACE (performDragOperation);
5830
5831 if (!emacs_event)
5832 return NO;
5833
5834 position = [self convertPoint: [sender draggingLocation] fromView: nil];
5835 x = lrint (position.x); y = lrint (position.y);
5836
5837 pb = [sender draggingPasteboard];
5838 type = [pb availableTypeFromArray: ns_drag_types];
5839 if (type == 0)
5840 {
5841 return NO;
5842 }
5843 else if ([type isEqualToString: NSFilenamesPboardType])
5844 {
5845 NSArray *files;
5846 NSEnumerator *fenum;
5847 NSString *file;
5848
5849 if (!(files = [pb propertyListForType: type]))
5850 return NO;
5851
5852 fenum = [files objectEnumerator];
5853 while ( (file = [fenum nextObject]) )
5854 {
5855 emacs_event->kind = NS_NONKEY_EVENT;
5856 emacs_event->code = KEY_NS_DRAG_FILE;
5857 XSETINT (emacs_event->x, x);
5858 XSETINT (emacs_event->y, y);
5859 ns_input_file = append2 (ns_input_file,
5860 build_string ([file UTF8String]));
5861 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5862 EV_TRAILER (theEvent);
5863 }
5864 return YES;
5865 }
5866 else if ([type isEqualToString: NSURLPboardType])
5867 {
5868 NSString *file;
5869 NSURL *fileURL;
5870
5871 if (!(fileURL = [NSURL URLFromPasteboard: pb]) ||
5872 [fileURL isFileURL] == NO)
5873 return NO;
5874
5875 file = [fileURL path];
5876 emacs_event->kind = NS_NONKEY_EVENT;
5877 emacs_event->code = KEY_NS_DRAG_FILE;
5878 XSETINT (emacs_event->x, x);
5879 XSETINT (emacs_event->y, y);
5880 ns_input_file = append2 (ns_input_file, build_string ([file UTF8String]));
5881 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5882 EV_TRAILER (theEvent);
5883 return YES;
5884 }
5885 else if ([type isEqualToString: NSStringPboardType]
5886 || [type isEqualToString: NSTabularTextPboardType])
5887 {
5888 NSString *data;
5889
5890 if (! (data = [pb stringForType: type]))
5891 return NO;
5892
5893 emacs_event->kind = NS_NONKEY_EVENT;
5894 emacs_event->code = KEY_NS_DRAG_TEXT;
5895 XSETINT (emacs_event->x, x);
5896 XSETINT (emacs_event->y, y);
5897 ns_input_text = build_string ([data UTF8String]);
5898 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5899 EV_TRAILER (theEvent);
5900 return YES;
5901 }
5902 else if ([type isEqualToString: NSColorPboardType])
5903 {
5904 NSColor *c = [NSColor colorFromPasteboard: pb];
5905 emacs_event->kind = NS_NONKEY_EVENT;
5906 emacs_event->code = KEY_NS_DRAG_COLOR;
5907 XSETINT (emacs_event->x, x);
5908 XSETINT (emacs_event->y, y);
5909 ns_input_color = ns_color_to_lisp (c);
5910 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5911 EV_TRAILER (theEvent);
5912 return YES;
5913 }
5914 else if ([type isEqualToString: NSFontPboardType])
5915 {
5916 /* impl based on GNUstep NSTextView.m */
5917 NSData *data = [pb dataForType: NSFontPboardType];
5918 NSDictionary *dict = [NSUnarchiver unarchiveObjectWithData: data];
5919 NSFont *font = [dict objectForKey: NSFontAttributeName];
5920 char fontSize[10];
5921
5922 if (font == nil)
5923 return NO;
5924
5925 emacs_event->kind = NS_NONKEY_EVENT;
5926 emacs_event->code = KEY_NS_CHANGE_FONT;
5927 XSETINT (emacs_event->x, x);
5928 XSETINT (emacs_event->y, y);
5929 ns_input_font = build_string ([[font fontName] UTF8String]);
5930 snprintf (fontSize, 10, "%f", [font pointSize]);
5931 ns_input_fontsize = build_string (fontSize);
5932 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5933 EV_TRAILER (theEvent);
5934 return YES;
5935 }
5936 else
5937 {
5938 error ("Invalid data type in dragging pasteboard.");
5939 return NO;
5940 }
5941 }
5942
5943
5944 - (id) validRequestorForSendType: (NSString *)typeSent
5945 returnType: (NSString *)typeReturned
5946 {
5947 NSTRACE (validRequestorForSendType);
5948 if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
5949 && typeReturned == nil)
5950 {
5951 if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
5952 return self;
5953 }
5954
5955 return [super validRequestorForSendType: typeSent
5956 returnType: typeReturned];
5957 }
5958
5959
5960 /* The next two methods are part of NSServicesRequests informal protocol,
5961 supposedly called when a services menu item is chosen from this app.
5962 But this should not happen because we override the services menu with our
5963 own entries which call ns-perform-service.
5964 Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
5965 So let's at least stub them out until further investigation can be done. */
5966
5967 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
5968 {
5969 /* we could call ns_string_from_pasteboard(pboard) here but then it should
5970 be written into the buffer in place of the existing selection..
5971 ordinary service calls go through functions defined in ns-win.el */
5972 return NO;
5973 }
5974
5975 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
5976 {
5977 NSArray *typesDeclared;
5978 Lisp_Object val;
5979
5980 /* We only support NSStringPboardType */
5981 if ([types containsObject:NSStringPboardType] == NO) {
5982 return NO;
5983 }
5984
5985 val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
5986 if (CONSP (val) && SYMBOLP (XCAR (val)))
5987 {
5988 val = XCDR (val);
5989 if (CONSP (val) && NILP (XCDR (val)))
5990 val = XCAR (val);
5991 }
5992 if (! STRINGP (val))
5993 return NO;
5994
5995 typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
5996 [pb declareTypes:typesDeclared owner:nil];
5997 ns_string_to_pasteboard (pb, val);
5998 return YES;
5999 }
6000
6001
6002 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
6003 (gives a miniaturized version of the window); currently we use the latter for
6004 frames whose active buffer doesn't correspond to any file
6005 (e.g., '*scratch*') */
6006 - setMiniwindowImage: (BOOL) setMini
6007 {
6008 id image = [[self window] miniwindowImage];
6009 NSTRACE (setMiniwindowImage);
6010
6011 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
6012 about "AppleDockIconEnabled" notwithstanding, however the set message
6013 below has its effect nonetheless. */
6014 if (image != emacsframe->output_data.ns->miniimage)
6015 {
6016 if (image && [image isKindOfClass: [EmacsImage class]])
6017 [image release];
6018 [[self window] setMiniwindowImage:
6019 setMini ? emacsframe->output_data.ns->miniimage : nil];
6020 }
6021
6022 return self;
6023 }
6024
6025
6026 - (void) setRows: (int) r andColumns: (int) c
6027 {
6028 rows = r;
6029 cols = c;
6030 }
6031
6032 @end /* EmacsView */
6033
6034
6035
6036 /* ==========================================================================
6037
6038 EmacsWindow implementation
6039
6040 ========================================================================== */
6041
6042 @implementation EmacsWindow
6043
6044 /* If we have multiple monitors, one above the other, we don't want to
6045 restrict the height to just one monitor. So we override this. */
6046 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
6047 {
6048 /* When making the frame visible for the first time or if there is just
6049 one screen, we want to constrain. Other times not. */
6050 NSUInteger nr_screens = [[NSScreen screens] count];
6051 struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
6052 NSTRACE (constrainFrameRect);
6053
6054 if (nr_screens == 1)
6055 return [super constrainFrameRect:frameRect toScreen:screen];
6056
6057 if (f->output_data.ns->dont_constrain
6058 || ns_menu_bar_should_be_hidden ())
6059 return frameRect;
6060
6061 f->output_data.ns->dont_constrain = 1;
6062 return [super constrainFrameRect:frameRect toScreen:screen];
6063 }
6064
6065
6066 /* called only on resize clicks by special case in EmacsApp-sendEvent */
6067 - (void)mouseDown: (NSEvent *)theEvent
6068 {
6069 if (ns_in_resize)
6070 {
6071 NSSize size = [[theEvent window] frame].size;
6072 grabOffset = [theEvent locationInWindow];
6073 grabOffset.x = size.width - grabOffset.x;
6074 }
6075 else
6076 [super mouseDown: theEvent];
6077 }
6078
6079
6080 /* stop resizing */
6081 - (void)mouseUp: (NSEvent *)theEvent
6082 {
6083 if (ns_in_resize)
6084 {
6085 struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
6086 ns_in_resize = NO;
6087 ns_set_name_as_filename (f);
6088 [self display];
6089 ns_send_appdefined (-1);
6090 }
6091 else
6092 [super mouseUp: theEvent];
6093 }
6094
6095
6096 /* send resize events */
6097 - (void)mouseDragged: (NSEvent *)theEvent
6098 {
6099 if (ns_in_resize)
6100 {
6101 NSPoint p = [theEvent locationInWindow];
6102 NSSize size, vettedSize, origSize = [self frame].size;
6103
6104 size.width = p.x + grabOffset.x;
6105 size.height = origSize.height - p.y + grabOffset.y;
6106
6107 if (size.width == origSize.width && size.height == origSize.height)
6108 return;
6109
6110 vettedSize = [[self delegate] windowWillResize: self toSize: size];
6111 [[NSNotificationCenter defaultCenter]
6112 postNotificationName: NSWindowDidResizeNotification
6113 object: self];
6114 }
6115 else
6116 [super mouseDragged: theEvent];
6117 }
6118
6119 @end /* EmacsWindow */
6120
6121
6122 /* ==========================================================================
6123
6124 EmacsScroller implementation
6125
6126 ========================================================================== */
6127
6128
6129 @implementation EmacsScroller
6130
6131 /* for repeat button push */
6132 #define SCROLL_BAR_FIRST_DELAY 0.5
6133 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
6134
6135 + (CGFloat) scrollerWidth
6136 {
6137 /* TODO: if we want to allow variable widths, this is the place to do it,
6138 however neither GNUstep nor Cocoa support it very well */
6139 return [NSScroller scrollerWidth];
6140 }
6141
6142
6143 - initFrame: (NSRect )r window: (Lisp_Object)nwin
6144 {
6145 NSTRACE (EmacsScroller_initFrame);
6146
6147 r.size.width = [EmacsScroller scrollerWidth];
6148 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
6149 [self setContinuous: YES];
6150 [self setEnabled: YES];
6151
6152 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
6153 locked against the top and bottom edges, and right edge on OS X, where
6154 scrollers are on right. */
6155 #ifdef NS_IMPL_GNUSTEP
6156 [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
6157 #else
6158 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
6159 #endif
6160
6161 win = nwin;
6162 condemned = NO;
6163 pixel_height = NSHeight (r);
6164 if (pixel_height == 0) pixel_height = 1;
6165 min_portion = 20 / pixel_height;
6166
6167 frame = XFRAME (XWINDOW (win)->frame);
6168 if (FRAME_LIVE_P (frame))
6169 {
6170 int i;
6171 EmacsView *view = FRAME_NS_VIEW (frame);
6172 NSView *sview = [[view window] contentView];
6173 NSArray *subs = [sview subviews];
6174
6175 /* disable optimization stopping redraw of other scrollbars */
6176 view->scrollbarsNeedingUpdate = 0;
6177 for (i =[subs count]-1; i >= 0; i--)
6178 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
6179 view->scrollbarsNeedingUpdate++;
6180 [sview addSubview: self];
6181 }
6182
6183 /* [self setFrame: r]; */
6184
6185 return self;
6186 }
6187
6188
6189 - (void)setFrame: (NSRect)newRect
6190 {
6191 NSTRACE (EmacsScroller_setFrame);
6192 /* BLOCK_INPUT; */
6193 pixel_height = NSHeight (newRect);
6194 if (pixel_height == 0) pixel_height = 1;
6195 min_portion = 20 / pixel_height;
6196 [super setFrame: newRect];
6197 [self display];
6198 /* UNBLOCK_INPUT; */
6199 }
6200
6201
6202 - (void)dealloc
6203 {
6204 NSTRACE (EmacsScroller_dealloc);
6205 if (!NILP (win))
6206 XWINDOW (win)->vertical_scroll_bar = Qnil;
6207 [super dealloc];
6208 }
6209
6210
6211 - condemn
6212 {
6213 NSTRACE (condemn);
6214 condemned =YES;
6215 return self;
6216 }
6217
6218
6219 - reprieve
6220 {
6221 NSTRACE (reprieve);
6222 condemned =NO;
6223 return self;
6224 }
6225
6226
6227 - judge
6228 {
6229 NSTRACE (judge);
6230 if (condemned)
6231 {
6232 EmacsView *view;
6233 BLOCK_INPUT;
6234 /* ensure other scrollbar updates after deletion */
6235 view = (EmacsView *)FRAME_NS_VIEW (frame);
6236 if (view != nil)
6237 view->scrollbarsNeedingUpdate++;
6238 [self removeFromSuperview];
6239 [self release];
6240 UNBLOCK_INPUT;
6241 }
6242 return self;
6243 }
6244
6245
6246 - (void)resetCursorRects
6247 {
6248 NSRect visible = [self visibleRect];
6249 NSTRACE (resetCursorRects);
6250
6251 if (!NSIsEmptyRect (visible))
6252 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
6253 [[NSCursor arrowCursor] setOnMouseEntered: YES];
6254 }
6255
6256
6257 - (int) checkSamePosition: (int) position portion: (int) portion
6258 whole: (int) whole
6259 {
6260 return em_position ==position && em_portion ==portion && em_whole ==whole
6261 && portion != whole; /* needed for resize empty buf */
6262 }
6263
6264
6265 - setPosition: (int)position portion: (int)portion whole: (int)whole
6266 {
6267 NSTRACE (setPosition);
6268
6269 em_position = position;
6270 em_portion = portion;
6271 em_whole = whole;
6272
6273 if (portion >= whole)
6274 {
6275 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
6276 [self setKnobProportion: 1.0];
6277 [self setDoubleValue: 1.0];
6278 #else
6279 [self setFloatValue: 0.0 knobProportion: 1.0];
6280 #endif
6281 }
6282 else
6283 {
6284 float pos, por;
6285 portion = max ((float)whole*min_portion/pixel_height, portion);
6286 pos = (float)position / (whole - portion);
6287 por = (float)portion/whole;
6288 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
6289 [self setKnobProportion: por];
6290 [self setDoubleValue: pos];
6291 #else
6292 [self setFloatValue: pos knobProportion: por];
6293 #endif
6294 }
6295 return self;
6296 }
6297
6298 /* FIXME: unused at moment (see ns_mouse_position) at the moment because
6299 drag events will go directly to the EmacsScroller. Leaving in for now. */
6300 -(void)getMouseMotionPart: (int *)part window: (Lisp_Object *)window
6301 x: (Lisp_Object *)x y: ( Lisp_Object *)y
6302 {
6303 *part = last_hit_part;
6304 *window = win;
6305 XSETINT (*y, pixel_height);
6306 if ([self floatValue] > 0.999)
6307 XSETINT (*x, pixel_height);
6308 else
6309 XSETINT (*x, pixel_height * [self floatValue]);
6310 }
6311
6312
6313 /* set up emacs_event */
6314 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
6315 {
6316 if (!emacs_event)
6317 return;
6318
6319 emacs_event->part = last_hit_part;
6320 emacs_event->code = 0;
6321 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
6322 emacs_event->frame_or_window = win;
6323 emacs_event->timestamp = EV_TIMESTAMP (e);
6324 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
6325 emacs_event->arg = Qnil;
6326 XSETINT (emacs_event->x, loc * pixel_height);
6327 XSETINT (emacs_event->y, pixel_height-20);
6328
6329 n_emacs_events_pending++;
6330 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
6331 EVENT_INIT (*emacs_event);
6332 ns_send_appdefined (-1);
6333 }
6334
6335
6336 /* called manually thru timer to implement repeated button action w/hold-down */
6337 - repeatScroll: (NSTimer *)scrollEntry
6338 {
6339 NSEvent *e = [[self window] currentEvent];
6340 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
6341 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
6342
6343 /* clear timer if need be */
6344 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
6345 {
6346 [scroll_repeat_entry invalidate];
6347 [scroll_repeat_entry release];
6348 scroll_repeat_entry = nil;
6349
6350 if (inKnob)
6351 return self;
6352
6353 scroll_repeat_entry
6354 = [[NSTimer scheduledTimerWithTimeInterval:
6355 SCROLL_BAR_CONTINUOUS_DELAY
6356 target: self
6357 selector: @selector (repeatScroll:)
6358 userInfo: 0
6359 repeats: YES]
6360 retain];
6361 }
6362
6363 [self sendScrollEventAtLoc: 0 fromEvent: e];
6364 return self;
6365 }
6366
6367
6368 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
6369 mouseDragged events without going into a modal loop. */
6370 - (void)mouseDown: (NSEvent *)e
6371 {
6372 NSRect sr, kr;
6373 /* hitPart is only updated AFTER event is passed on */
6374 NSScrollerPart part = [self testPart: [e locationInWindow]];
6375 double inc = 0.0, loc, kloc, pos;
6376 int edge = 0;
6377
6378 NSTRACE (EmacsScroller_mouseDown);
6379
6380 switch (part)
6381 {
6382 case NSScrollerDecrementPage:
6383 last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
6384 case NSScrollerIncrementPage:
6385 last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
6386 case NSScrollerDecrementLine:
6387 last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
6388 case NSScrollerIncrementLine:
6389 last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
6390 case NSScrollerKnob:
6391 last_hit_part = scroll_bar_handle; break;
6392 case NSScrollerKnobSlot: /* GNUstep-only */
6393 last_hit_part = scroll_bar_move_ratio; break;
6394 default: /* NSScrollerNoPart? */
6395 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
6396 (long) part);
6397 return;
6398 }
6399
6400 if (inc != 0.0)
6401 {
6402 pos = 0; /* ignored */
6403
6404 /* set a timer to repeat, as we can't let superclass do this modally */
6405 scroll_repeat_entry
6406 = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
6407 target: self
6408 selector: @selector (repeatScroll:)
6409 userInfo: 0
6410 repeats: YES]
6411 retain];
6412 }
6413 else
6414 {
6415 /* handle, or on GNUstep possibly slot */
6416 NSEvent *fake_event;
6417
6418 /* compute float loc in slot and mouse offset on knob */
6419 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6420 toView: nil];
6421 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6422 if (loc <= 0.0)
6423 {
6424 loc = 0.0;
6425 edge = -1;
6426 }
6427 else if (loc >= NSHeight (sr))
6428 {
6429 loc = NSHeight (sr);
6430 edge = 1;
6431 }
6432
6433 if (edge)
6434 kloc = 0.5 * edge;
6435 else
6436 {
6437 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
6438 toView: nil];
6439 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
6440 }
6441 last_mouse_offset = kloc;
6442
6443 /* if knob, tell emacs a location offset by knob pos
6444 (to indicate top of handle) */
6445 if (part == NSScrollerKnob)
6446 pos = (loc - last_mouse_offset) / NSHeight (sr);
6447 else
6448 /* else this is a slot click on GNUstep: go straight there */
6449 pos = loc / NSHeight (sr);
6450
6451 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
6452 fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
6453 location: [e locationInWindow]
6454 modifierFlags: [e modifierFlags]
6455 timestamp: [e timestamp]
6456 windowNumber: [e windowNumber]
6457 context: [e context]
6458 eventNumber: [e eventNumber]
6459 clickCount: [e clickCount]
6460 pressure: [e pressure]];
6461 [super mouseUp: fake_event];
6462 }
6463
6464 if (part != NSScrollerKnob)
6465 [self sendScrollEventAtLoc: pos fromEvent: e];
6466 }
6467
6468
6469 /* Called as we manually track scroller drags, rather than superclass. */
6470 - (void)mouseDragged: (NSEvent *)e
6471 {
6472 NSRect sr;
6473 double loc, pos;
6474 int edge = 0;
6475
6476 NSTRACE (EmacsScroller_mouseDragged);
6477
6478 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6479 toView: nil];
6480 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6481
6482 if (loc <= 0.0)
6483 {
6484 loc = 0.0;
6485 edge = -1;
6486 }
6487 else if (loc >= NSHeight (sr) + last_mouse_offset)
6488 {
6489 loc = NSHeight (sr) + last_mouse_offset;
6490 edge = 1;
6491 }
6492
6493 pos = /*(edge ? loc :*/ (loc - last_mouse_offset) / NSHeight (sr);
6494 [self sendScrollEventAtLoc: pos fromEvent: e];
6495 }
6496
6497
6498 - (void)mouseUp: (NSEvent *)e
6499 {
6500 if (scroll_repeat_entry)
6501 {
6502 [scroll_repeat_entry invalidate];
6503 [scroll_repeat_entry release];
6504 scroll_repeat_entry = nil;
6505 }
6506 last_hit_part = 0;
6507 }
6508
6509
6510 /* treat scrollwheel events in the bar as though they were in the main window */
6511 - (void) scrollWheel: (NSEvent *)theEvent
6512 {
6513 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
6514 [view mouseDown: theEvent];
6515 }
6516
6517 @end /* EmacsScroller */
6518
6519
6520
6521
6522 /* ==========================================================================
6523
6524 Font-related functions; these used to be in nsfaces.m
6525
6526 ========================================================================== */
6527
6528
6529 Lisp_Object
6530 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
6531 {
6532 struct font *font = XFONT_OBJECT (font_object);
6533
6534 if (fontset < 0)
6535 fontset = fontset_from_font (font_object);
6536 FRAME_FONTSET (f) = fontset;
6537
6538 if (FRAME_FONT (f) == font)
6539 /* This font is already set in frame F. There's nothing more to
6540 do. */
6541 return font_object;
6542
6543 FRAME_FONT (f) = font;
6544
6545 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
6546 FRAME_COLUMN_WIDTH (f) = font->average_width;
6547 FRAME_SPACE_WIDTH (f) = font->space_width;
6548 FRAME_LINE_HEIGHT (f) = font->height;
6549
6550 compute_fringe_widths (f, 1);
6551
6552 /* Compute the scroll bar width in character columns. */
6553 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
6554 {
6555 int wid = FRAME_COLUMN_WIDTH (f);
6556 FRAME_CONFIG_SCROLL_BAR_COLS (f)
6557 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
6558 }
6559 else
6560 {
6561 int wid = FRAME_COLUMN_WIDTH (f);
6562 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
6563 }
6564
6565 /* Now make the frame display the given font. */
6566 if (FRAME_NS_WINDOW (f) != 0)
6567 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
6568
6569 return font_object;
6570 }
6571
6572
6573 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
6574 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
6575 in 1.43. */
6576
6577 const char *
6578 ns_xlfd_to_fontname (const char *xlfd)
6579 /* --------------------------------------------------------------------------
6580 Convert an X font name (XLFD) to an NS font name.
6581 Only family is used.
6582 The string returned is temporarily allocated.
6583 -------------------------------------------------------------------------- */
6584 {
6585 char *name = xmalloc (180);
6586 int i, len;
6587 const char *ret;
6588
6589 if (!strncmp (xlfd, "--", 2))
6590 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
6591 else
6592 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
6593
6594 /* stopgap for malformed XLFD input */
6595 if (strlen (name) == 0)
6596 strcpy (name, "Monaco");
6597
6598 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
6599 also uppercase after '-' or ' ' */
6600 name[0] = toupper (name[0]);
6601 for (len =strlen (name), i =0; i<len; i++)
6602 {
6603 if (name[i] == '$')
6604 {
6605 name[i] = '-';
6606 if (i+1<len)
6607 name[i+1] = toupper (name[i+1]);
6608 }
6609 else if (name[i] == '_')
6610 {
6611 name[i] = ' ';
6612 if (i+1<len)
6613 name[i+1] = toupper (name[i+1]);
6614 }
6615 }
6616 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
6617 ret = [[NSString stringWithUTF8String: name] UTF8String];
6618 xfree (name);
6619 return ret;
6620 }
6621
6622
6623 void
6624 syms_of_nsterm (void)
6625 {
6626 NSTRACE (syms_of_nsterm);
6627
6628 ns_antialias_threshold = 10.0;
6629
6630 /* from 23+ we need to tell emacs what modifiers there are.. */
6631 DEFSYM (Qmodifier_value, "modifier-value");
6632 DEFSYM (Qalt, "alt");
6633 DEFSYM (Qhyper, "hyper");
6634 DEFSYM (Qmeta, "meta");
6635 DEFSYM (Qsuper, "super");
6636 DEFSYM (Qcontrol, "control");
6637 DEFSYM (Qnone, "none");
6638 DEFSYM (QUTF8_STRING, "UTF8_STRING");
6639
6640 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
6641 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
6642 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
6643 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
6644 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
6645
6646 DEFVAR_LISP ("ns-input-file", ns_input_file,
6647 "The file specified in the last NS event.");
6648 ns_input_file =Qnil;
6649
6650 DEFVAR_LISP ("ns-input-text", ns_input_text,
6651 "The data received in the last NS text drag event.");
6652 ns_input_text =Qnil;
6653
6654 DEFVAR_LISP ("ns-working-text", ns_working_text,
6655 "String for visualizing working composition sequence.");
6656 ns_working_text =Qnil;
6657
6658 DEFVAR_LISP ("ns-input-font", ns_input_font,
6659 "The font specified in the last NS event.");
6660 ns_input_font =Qnil;
6661
6662 DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
6663 "The fontsize specified in the last NS event.");
6664 ns_input_fontsize =Qnil;
6665
6666 DEFVAR_LISP ("ns-input-line", ns_input_line,
6667 "The line specified in the last NS event.");
6668 ns_input_line =Qnil;
6669
6670 DEFVAR_LISP ("ns-input-color", ns_input_color,
6671 "The color specified in the last NS event.");
6672 ns_input_color =Qnil;
6673
6674 DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
6675 "The service name specified in the last NS event.");
6676 ns_input_spi_name =Qnil;
6677
6678 DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
6679 "The service argument specified in the last NS event.");
6680 ns_input_spi_arg =Qnil;
6681
6682 DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
6683 "This variable describes the behavior of the alternate or option key.\n\
6684 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6685 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6686 at all, allowing it to be used at a lower level for accented character entry.");
6687 ns_alternate_modifier = Qmeta;
6688
6689 DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
6690 "This variable describes the behavior of the right alternate or option key.\n\
6691 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6692 Set to left means be the same key as `ns-alternate-modifier'.\n\
6693 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6694 at all, allowing it to be used at a lower level for accented character entry.");
6695 ns_right_alternate_modifier = Qleft;
6696
6697 DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
6698 "This variable describes the behavior of the command key.\n\
6699 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6700 ns_command_modifier = Qsuper;
6701
6702 DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
6703 "This variable describes the behavior of the right command key.\n\
6704 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6705 Set to left means be the same key as `ns-command-modifier'.\n\
6706 Set to none means that the command / option key is not interpreted by Emacs\n\
6707 at all, allowing it to be used at a lower level for accented character entry.");
6708 ns_right_command_modifier = Qleft;
6709
6710 DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
6711 "This variable describes the behavior of the control key.\n\
6712 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6713 ns_control_modifier = Qcontrol;
6714
6715 DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
6716 "This variable describes the behavior of the right control key.\n\
6717 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6718 Set to left means be the same key as `ns-control-modifier'.\n\
6719 Set to none means that the control / option key is not interpreted by Emacs\n\
6720 at all, allowing it to be used at a lower level for accented character entry.");
6721 ns_right_control_modifier = Qleft;
6722
6723 DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
6724 "This variable describes the behavior of the function key (on laptops).\n\
6725 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6726 Set to none means that the function key is not interpreted by Emacs at all,\n\
6727 allowing it to be used at a lower level for accented character entry.");
6728 ns_function_modifier = Qnone;
6729
6730 DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
6731 "Non-nil (the default) means to render text antialiased. Only has an effect on OS X Panther and above.");
6732 ns_antialias_text = Qt;
6733
6734 DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
6735 "Whether to confirm application quit using dialog.");
6736 ns_confirm_quit = Qnil;
6737
6738 staticpro (&ns_display_name_list);
6739 ns_display_name_list = Qnil;
6740
6741 staticpro (&last_mouse_motion_frame);
6742 last_mouse_motion_frame = Qnil;
6743
6744 DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
6745 doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
6746 Only works on OSX 10.6 or later. */);
6747 ns_auto_hide_menu_bar = Qnil;
6748
6749 /* TODO: move to common code */
6750 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
6751 doc: /* Which toolkit scroll bars Emacs uses, if any.
6752 A value of nil means Emacs doesn't use toolkit scroll bars.
6753 With the X Window system, the value is a symbol describing the
6754 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
6755 With MS Windows or Nextstep, the value is t. */);
6756 Vx_toolkit_scroll_bars = Qt;
6757
6758 DEFVAR_BOOL ("x-use-underline-position-properties",
6759 x_use_underline_position_properties,
6760 doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
6761 A value of nil means ignore them. If you encounter fonts with bogus
6762 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
6763 to 4.1, set this to nil. */);
6764 x_use_underline_position_properties = 0;
6765
6766 DEFVAR_BOOL ("x-underline-at-descent-line",
6767 x_underline_at_descent_line,
6768 doc: /* Non-nil means to draw the underline at the same place as the descent line.
6769 A value of nil means to draw the underline according to the value of the
6770 variable `x-use-underline-position-properties', which is usually at the
6771 baseline level. The default value is nil. */);
6772 x_underline_at_descent_line = 0;
6773
6774 /* Tell emacs about this window system. */
6775 Fprovide (intern ("ns"), Qnil);
6776 }