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