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