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