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