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