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