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