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