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