]> code.delx.au - gnu-emacs/blob - src/nsterm.m
Merge from origin/emacs-24
[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
2097 static void
2098 ns_scroll_run (struct window *w, struct run *run)
2099 /* --------------------------------------------------------------------------
2100 External (RIF): Insert or delete n lines at line vpos
2101 -------------------------------------------------------------------------- */
2102 {
2103 struct frame *f = XFRAME (w->frame);
2104 int x, y, width, height, from_y, to_y, bottom_y;
2105
2106 NSTRACE (ns_scroll_run);
2107
2108 /* begin copy from other terms */
2109 /* Get frame-relative bounding box of the text display area of W,
2110 without mode lines. Include in this box the left and right
2111 fringe of W. */
2112 window_box (w, ANY_AREA, &x, &y, &width, &height);
2113
2114 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
2115 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
2116 bottom_y = y + height;
2117
2118 if (to_y < from_y)
2119 {
2120 /* Scrolling up. Make sure we don't copy part of the mode
2121 line at the bottom. */
2122 if (from_y + run->height > bottom_y)
2123 height = bottom_y - from_y;
2124 else
2125 height = run->height;
2126 }
2127 else
2128 {
2129 /* Scrolling down. Make sure we don't copy over the mode line.
2130 at the bottom. */
2131 if (to_y + run->height > bottom_y)
2132 height = bottom_y - to_y;
2133 else
2134 height = run->height;
2135 }
2136 /* end copy from other terms */
2137
2138 if (height == 0)
2139 return;
2140
2141 block_input ();
2142
2143 x_clear_cursor (w);
2144
2145 {
2146 NSRect srcRect = NSMakeRect (x, from_y, width, height);
2147 NSRect dstRect = NSMakeRect (x, to_y, width, height);
2148 NSPoint dstOrigin = NSMakePoint (x, to_y);
2149
2150 ns_focus (f, &dstRect, 1);
2151 NSCopyBits (0, srcRect , dstOrigin);
2152 ns_unfocus (f);
2153 }
2154
2155 unblock_input ();
2156 }
2157
2158
2159 static void
2160 ns_after_update_window_line (struct window *w, struct glyph_row *desired_row)
2161 /* --------------------------------------------------------------------------
2162 External (RIF): preparatory to fringe update after text was updated
2163 -------------------------------------------------------------------------- */
2164 {
2165 struct frame *f;
2166 int width, height;
2167
2168 NSTRACE (ns_after_update_window_line);
2169
2170 /* begin copy from other terms */
2171 eassert (w);
2172
2173 if (!desired_row->mode_line_p && !w->pseudo_window_p)
2174 desired_row->redraw_fringe_bitmaps_p = 1;
2175
2176 /* When a window has disappeared, make sure that no rest of
2177 full-width rows stays visible in the internal border. */
2178 if (windows_or_buffers_changed
2179 && desired_row->full_width_p
2180 && (f = XFRAME (w->frame),
2181 width = FRAME_INTERNAL_BORDER_WIDTH (f),
2182 width != 0)
2183 && (height = desired_row->visible_height,
2184 height > 0))
2185 {
2186 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
2187
2188 block_input ();
2189 ns_clear_frame_area (f, 0, y, width, height);
2190 ns_clear_frame_area (f,
2191 FRAME_PIXEL_WIDTH (f) - width,
2192 y, width, height);
2193 unblock_input ();
2194 }
2195 }
2196
2197
2198 static void
2199 ns_shift_glyphs_for_insert (struct frame *f,
2200 int x, int y, int width, int height,
2201 int shift_by)
2202 /* --------------------------------------------------------------------------
2203 External (RIF): copy an area horizontally, don't worry about clearing src
2204 -------------------------------------------------------------------------- */
2205 {
2206 NSRect srcRect = NSMakeRect (x, y, width, height);
2207 NSRect dstRect = NSMakeRect (x+shift_by, y, width, height);
2208 NSPoint dstOrigin = dstRect.origin;
2209
2210 NSTRACE (ns_shift_glyphs_for_insert);
2211
2212 ns_focus (f, &dstRect, 1);
2213 NSCopyBits (0, srcRect, dstOrigin);
2214 ns_unfocus (f);
2215 }
2216
2217
2218
2219 /* ==========================================================================
2220
2221 Character encoding and metrics
2222
2223 ========================================================================== */
2224
2225
2226 static void
2227 ns_compute_glyph_string_overhangs (struct glyph_string *s)
2228 /* --------------------------------------------------------------------------
2229 External (RIF); compute left/right overhang of whole string and set in s
2230 -------------------------------------------------------------------------- */
2231 {
2232 struct font *font = s->font;
2233
2234 if (s->char2b)
2235 {
2236 struct font_metrics metrics;
2237 unsigned int codes[2];
2238 codes[0] = *(s->char2b);
2239 codes[1] = *(s->char2b + s->nchars - 1);
2240
2241 font->driver->text_extents (font, codes, 2, &metrics);
2242 s->left_overhang = -metrics.lbearing;
2243 s->right_overhang
2244 = metrics.rbearing > metrics.width
2245 ? metrics.rbearing - metrics.width : 0;
2246 }
2247 else
2248 {
2249 s->left_overhang = 0;
2250 if (EQ (font->driver->type, Qns))
2251 s->right_overhang = ((struct nsfont_info *)font)->ital ?
2252 FONT_HEIGHT (font) * 0.2 : 0;
2253 else
2254 s->right_overhang = 0;
2255 }
2256 }
2257
2258
2259
2260 /* ==========================================================================
2261
2262 Fringe and cursor drawing
2263
2264 ========================================================================== */
2265
2266
2267 extern int max_used_fringe_bitmap;
2268 static void
2269 ns_draw_fringe_bitmap (struct window *w, struct glyph_row *row,
2270 struct draw_fringe_bitmap_params *p)
2271 /* --------------------------------------------------------------------------
2272 External (RIF); fringe-related
2273 -------------------------------------------------------------------------- */
2274 {
2275 struct frame *f = XFRAME (WINDOW_FRAME (w));
2276 struct face *face = p->face;
2277 static EmacsImage **bimgs = NULL;
2278 static int nBimgs = 0;
2279
2280 /* grow bimgs if needed */
2281 if (nBimgs < max_used_fringe_bitmap)
2282 {
2283 bimgs = xrealloc (bimgs, max_used_fringe_bitmap * sizeof *bimgs);
2284 memset (bimgs + nBimgs, 0,
2285 (max_used_fringe_bitmap - nBimgs) * sizeof *bimgs);
2286 nBimgs = max_used_fringe_bitmap;
2287 }
2288
2289 /* Must clip because of partially visible lines. */
2290 ns_clip_to_row (w, row, ANY_AREA, YES);
2291
2292 if (!p->overlay_p)
2293 {
2294 int bx = p->bx, by = p->by, nx = p->nx, ny = p->ny;
2295
2296 if (bx >= 0 && nx > 0)
2297 {
2298 NSRect r = NSMakeRect (bx, by, nx, ny);
2299 NSRectClip (r);
2300 [ns_lookup_indexed_color (face->background, f) set];
2301 NSRectFill (r);
2302 }
2303 }
2304
2305 if (p->which)
2306 {
2307 NSRect r = NSMakeRect (p->x, p->y, p->wd, p->h);
2308 EmacsImage *img = bimgs[p->which - 1];
2309
2310 if (!img)
2311 {
2312 unsigned short *bits = p->bits + p->dh;
2313 int len = p->h;
2314 int i;
2315 unsigned char *cbits = xmalloc (len);
2316
2317 for (i = 0; i < len; i++)
2318 cbits[i] = ~(bits[i] & 0xff);
2319 img = [[EmacsImage alloc] initFromXBM: cbits width: 8 height: p->h
2320 flip: NO];
2321 bimgs[p->which - 1] = img;
2322 xfree (cbits);
2323 }
2324
2325 NSRectClip (r);
2326 /* Since we composite the bitmap instead of just blitting it, we need
2327 to erase the whole background. */
2328 [ns_lookup_indexed_color(face->background, f) set];
2329 NSRectFill (r);
2330
2331 {
2332 NSColor *bm_color;
2333 if (!p->cursor_p)
2334 bm_color = ns_lookup_indexed_color(face->foreground, f);
2335 else if (p->overlay_p)
2336 bm_color = ns_lookup_indexed_color(face->background, f);
2337 else
2338 bm_color = f->output_data.ns->cursor_color;
2339 [img setXBMColor: bm_color];
2340 }
2341
2342 #ifdef NS_IMPL_COCOA
2343 [img drawInRect: r
2344 fromRect: NSZeroRect
2345 operation: NSCompositeSourceOver
2346 fraction: 1.0
2347 respectFlipped: YES
2348 hints: nil];
2349 #else
2350 {
2351 NSPoint pt = r.origin;
2352 pt.y += p->h;
2353 [img compositeToPoint: pt operation: NSCompositeSourceOver];
2354 }
2355 #endif
2356 }
2357 ns_unfocus (f);
2358 }
2359
2360
2361 static void
2362 ns_draw_window_cursor (struct window *w, struct glyph_row *glyph_row,
2363 int x, int y, enum text_cursor_kinds cursor_type,
2364 int cursor_width, bool on_p, bool active_p)
2365 /* --------------------------------------------------------------------------
2366 External call (RIF): draw cursor.
2367 Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2368 -------------------------------------------------------------------------- */
2369 {
2370 NSRect r, s;
2371 int fx, fy, h, cursor_height;
2372 struct frame *f = WINDOW_XFRAME (w);
2373 struct glyph *phys_cursor_glyph;
2374 struct glyph *cursor_glyph;
2375 struct face *face;
2376 NSColor *hollow_color = FRAME_BACKGROUND_COLOR (f);
2377
2378 /* If cursor is out of bounds, don't draw garbage. This can happen
2379 in mini-buffer windows when switching between echo area glyphs
2380 and mini-buffer. */
2381
2382 NSTRACE (dumpcursor);
2383
2384 if (!on_p)
2385 return;
2386
2387 w->phys_cursor_type = cursor_type;
2388 w->phys_cursor_on_p = on_p;
2389
2390 if (cursor_type == NO_CURSOR)
2391 {
2392 w->phys_cursor_width = 0;
2393 return;
2394 }
2395
2396 if ((phys_cursor_glyph = get_phys_cursor_glyph (w)) == NULL)
2397 {
2398 if (glyph_row->exact_window_width_line_p
2399 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
2400 {
2401 glyph_row->cursor_in_fringe_p = 1;
2402 draw_fringe_bitmap (w, glyph_row, 0);
2403 }
2404 return;
2405 }
2406
2407 /* We draw the cursor (with NSRectFill), then draw the glyph on top
2408 (other terminals do it the other way round). We must set
2409 w->phys_cursor_width to the cursor width. For bar cursors, that
2410 is CURSOR_WIDTH; for box cursors, it is the glyph width. */
2411 get_phys_cursor_geometry (w, glyph_row, phys_cursor_glyph, &fx, &fy, &h);
2412
2413 /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2414 to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2415 if (cursor_type == BAR_CURSOR)
2416 {
2417 if (cursor_width < 1)
2418 cursor_width = max (FRAME_CURSOR_WIDTH (f), 1);
2419 w->phys_cursor_width = cursor_width;
2420 }
2421 /* If we have an HBAR, "cursor_width" MAY specify height. */
2422 else if (cursor_type == HBAR_CURSOR)
2423 {
2424 cursor_height = (cursor_width < 1) ? lrint (0.25 * h) : cursor_width;
2425 if (cursor_height > glyph_row->height)
2426 cursor_height = glyph_row->height;
2427 if (h > cursor_height) // Cursor smaller than line height, move down
2428 fy += h - cursor_height;
2429 h = cursor_height;
2430 }
2431
2432 r.origin.x = fx, r.origin.y = fy;
2433 r.size.height = h;
2434 r.size.width = w->phys_cursor_width;
2435
2436 /* TODO: only needed in rare cases with last-resort font in HELLO..
2437 should we do this more efficiently? */
2438 ns_clip_to_row (w, glyph_row, ANY_AREA, NO); /* do ns_focus(f, &r, 1); if remove */
2439
2440
2441 face = FACE_FROM_ID (f, phys_cursor_glyph->face_id);
2442 if (face && NS_FACE_BACKGROUND (face)
2443 == ns_index_color (FRAME_CURSOR_COLOR (f), f))
2444 {
2445 [ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), f) set];
2446 hollow_color = FRAME_CURSOR_COLOR (f);
2447 }
2448 else
2449 [FRAME_CURSOR_COLOR (f) set];
2450
2451 #ifdef NS_IMPL_COCOA
2452 /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2453 atomic. Cleaner ways of doing this should be investigated.
2454 One way would be to set a global variable DRAWING_CURSOR
2455 when making the call to draw_phys..(), don't focus in that
2456 case, then move the ns_unfocus() here after that call. */
2457 NSDisableScreenUpdates ();
2458 #endif
2459
2460 switch (cursor_type)
2461 {
2462 case NO_CURSOR:
2463 break;
2464 case FILLED_BOX_CURSOR:
2465 NSRectFill (r);
2466 break;
2467 case HOLLOW_BOX_CURSOR:
2468 NSRectFill (r);
2469 [hollow_color set];
2470 NSRectFill (NSInsetRect (r, 1, 1));
2471 [FRAME_CURSOR_COLOR (f) set];
2472 break;
2473 case HBAR_CURSOR:
2474 NSRectFill (r);
2475 break;
2476 case BAR_CURSOR:
2477 s = r;
2478 /* If the character under cursor is R2L, draw the bar cursor
2479 on the right of its glyph, rather than on the left. */
2480 cursor_glyph = get_phys_cursor_glyph (w);
2481 if ((cursor_glyph->resolved_level & 1) != 0)
2482 s.origin.x += cursor_glyph->pixel_width - s.size.width;
2483
2484 NSRectFill (s);
2485 break;
2486 }
2487 ns_unfocus (f);
2488
2489 /* draw the character under the cursor */
2490 if (cursor_type != NO_CURSOR)
2491 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2492
2493 #ifdef NS_IMPL_COCOA
2494 NSEnableScreenUpdates ();
2495 #endif
2496
2497 }
2498
2499
2500 static void
2501 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2502 /* --------------------------------------------------------------------------
2503 External (RIF): Draw a vertical line.
2504 -------------------------------------------------------------------------- */
2505 {
2506 struct frame *f = XFRAME (WINDOW_FRAME (w));
2507 struct face *face;
2508 NSRect r = NSMakeRect (x, y0, 1, y1-y0);
2509
2510 NSTRACE (ns_draw_vertical_window_border);
2511
2512 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2513 if (face)
2514 [ns_lookup_indexed_color(face->foreground, f) set];
2515
2516 ns_focus (f, &r, 1);
2517 NSRectFill(r);
2518 ns_unfocus (f);
2519 }
2520
2521
2522 static void
2523 ns_draw_window_divider (struct window *w, int x0, int x1, int y0, int y1)
2524 /* --------------------------------------------------------------------------
2525 External (RIF): Draw a window divider.
2526 -------------------------------------------------------------------------- */
2527 {
2528 struct frame *f = XFRAME (WINDOW_FRAME (w));
2529 struct face *face;
2530 NSRect r = NSMakeRect (x0, y0, x1-x0, y1-y0);
2531
2532 NSTRACE (ns_draw_window_divider);
2533
2534 face = FACE_FROM_ID (f, WINDOW_DIVIDER_FACE_ID);
2535 if (face)
2536 [ns_lookup_indexed_color(face->foreground, f) set];
2537
2538 ns_focus (f, &r, 1);
2539 NSRectFill(r);
2540 ns_unfocus (f);
2541 }
2542
2543 static void
2544 ns_show_hourglass (struct frame *f)
2545 {
2546 /* TODO: add NSProgressIndicator to all frames. */
2547 }
2548
2549 static void
2550 ns_hide_hourglass (struct frame *f)
2551 {
2552 /* TODO: remove NSProgressIndicator from all frames. */
2553 }
2554
2555 /* ==========================================================================
2556
2557 Glyph drawing operations
2558
2559 ========================================================================== */
2560
2561 static int
2562 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2563 /* --------------------------------------------------------------------------
2564 Wrapper utility to account for internal border width on full-width lines,
2565 and allow top full-width rows to hit the frame top. nr should be pointer
2566 to two successive NSRects. Number of rects actually used is returned.
2567 -------------------------------------------------------------------------- */
2568 {
2569 int n = get_glyph_string_clip_rects (s, nr, 2);
2570 return n;
2571 }
2572
2573 /* --------------------------------------------------------------------
2574 Draw a wavy line under glyph string s. The wave fills wave_height
2575 pixels from y.
2576
2577 x wave_length = 2
2578 --
2579 y * * * * *
2580 |* * * * * * * * *
2581 wave_height = 3 | * * * *
2582 --------------------------------------------------------------------- */
2583
2584 static void
2585 ns_draw_underwave (struct glyph_string *s, EmacsCGFloat width, EmacsCGFloat x)
2586 {
2587 int wave_height = 3, wave_length = 2;
2588 int y, dx, dy, odd, xmax;
2589 NSPoint a, b;
2590 NSRect waveClip;
2591
2592 dx = wave_length;
2593 dy = wave_height - 1;
2594 y = s->ybase - wave_height + 3;
2595 xmax = x + width;
2596
2597 /* Find and set clipping rectangle */
2598 waveClip = NSMakeRect (x, y, width, wave_height);
2599 [[NSGraphicsContext currentContext] saveGraphicsState];
2600 NSRectClip (waveClip);
2601
2602 /* Draw the waves */
2603 a.x = x - ((int)(x) % dx) + (EmacsCGFloat) 0.5;
2604 b.x = a.x + dx;
2605 odd = (int)(a.x/dx) % 2;
2606 a.y = b.y = y + 0.5;
2607
2608 if (odd)
2609 a.y += dy;
2610 else
2611 b.y += dy;
2612
2613 while (a.x <= xmax)
2614 {
2615 [NSBezierPath strokeLineFromPoint:a toPoint:b];
2616 a.x = b.x, a.y = b.y;
2617 b.x += dx, b.y = y + 0.5 + odd*dy;
2618 odd = !odd;
2619 }
2620
2621 /* Restore previous clipping rectangle(s) */
2622 [[NSGraphicsContext currentContext] restoreGraphicsState];
2623 }
2624
2625
2626
2627 void
2628 ns_draw_text_decoration (struct glyph_string *s, struct face *face,
2629 NSColor *defaultCol, CGFloat width, CGFloat x)
2630 /* --------------------------------------------------------------------------
2631 Draw underline, overline, and strike-through on glyph string s.
2632 -------------------------------------------------------------------------- */
2633 {
2634 if (s->for_overlaps)
2635 return;
2636
2637 /* Do underline. */
2638 if (face->underline_p)
2639 {
2640 if (s->face->underline_type == FACE_UNDER_WAVE)
2641 {
2642 if (face->underline_defaulted_p)
2643 [defaultCol set];
2644 else
2645 [ns_lookup_indexed_color (face->underline_color, s->f) set];
2646
2647 ns_draw_underwave (s, width, x);
2648 }
2649 else if (s->face->underline_type == FACE_UNDER_LINE)
2650 {
2651
2652 NSRect r;
2653 unsigned long thickness, position;
2654
2655 /* If the prev was underlined, match its appearance. */
2656 if (s->prev && s->prev->face->underline_p
2657 && s->prev->face->underline_type == FACE_UNDER_LINE
2658 && s->prev->underline_thickness > 0)
2659 {
2660 thickness = s->prev->underline_thickness;
2661 position = s->prev->underline_position;
2662 }
2663 else
2664 {
2665 struct font *font;
2666 unsigned long descent;
2667
2668 font=s->font;
2669 descent = s->y + s->height - s->ybase;
2670
2671 /* Use underline thickness of font, defaulting to 1. */
2672 thickness = (font && font->underline_thickness > 0)
2673 ? font->underline_thickness : 1;
2674
2675 /* Determine the offset of underlining from the baseline. */
2676 if (x_underline_at_descent_line)
2677 position = descent - thickness;
2678 else if (x_use_underline_position_properties
2679 && font && font->underline_position >= 0)
2680 position = font->underline_position;
2681 else if (font)
2682 position = lround (font->descent / 2);
2683 else
2684 position = underline_minimum_offset;
2685
2686 position = max (position, underline_minimum_offset);
2687
2688 /* Ensure underlining is not cropped. */
2689 if (descent <= position)
2690 {
2691 position = descent - 1;
2692 thickness = 1;
2693 }
2694 else if (descent < position + thickness)
2695 thickness = 1;
2696 }
2697
2698 s->underline_thickness = thickness;
2699 s->underline_position = position;
2700
2701 r = NSMakeRect (x, s->ybase + position, width, thickness);
2702
2703 if (face->underline_defaulted_p)
2704 [defaultCol set];
2705 else
2706 [ns_lookup_indexed_color (face->underline_color, s->f) set];
2707 NSRectFill (r);
2708 }
2709 }
2710 /* Do overline. We follow other terms in using a thickness of 1
2711 and ignoring overline_margin. */
2712 if (face->overline_p)
2713 {
2714 NSRect r;
2715 r = NSMakeRect (x, s->y, width, 1);
2716
2717 if (face->overline_color_defaulted_p)
2718 [defaultCol set];
2719 else
2720 [ns_lookup_indexed_color (face->overline_color, s->f) set];
2721 NSRectFill (r);
2722 }
2723
2724 /* Do strike-through. We follow other terms for thickness and
2725 vertical position.*/
2726 if (face->strike_through_p)
2727 {
2728 NSRect r;
2729 unsigned long dy;
2730
2731 dy = lrint ((s->height - 1) / 2);
2732 r = NSMakeRect (x, s->y + dy, width, 1);
2733
2734 if (face->strike_through_color_defaulted_p)
2735 [defaultCol set];
2736 else
2737 [ns_lookup_indexed_color (face->strike_through_color, s->f) set];
2738 NSRectFill (r);
2739 }
2740 }
2741
2742 static void
2743 ns_draw_box (NSRect r, CGFloat thickness, NSColor *col,
2744 char left_p, char right_p)
2745 /* --------------------------------------------------------------------------
2746 Draw an unfilled rect inside r, optionally leaving left and/or right open.
2747 Note we can't just use an NSDrawRect command, because of the possibility
2748 of some sides not being drawn, and because the rect will be filled.
2749 -------------------------------------------------------------------------- */
2750 {
2751 NSRect s = r;
2752 [col set];
2753
2754 /* top, bottom */
2755 s.size.height = thickness;
2756 NSRectFill (s);
2757 s.origin.y += r.size.height - thickness;
2758 NSRectFill (s);
2759
2760 s.size.height = r.size.height;
2761 s.origin.y = r.origin.y;
2762
2763 /* left, right (optional) */
2764 s.size.width = thickness;
2765 if (left_p)
2766 NSRectFill (s);
2767 if (right_p)
2768 {
2769 s.origin.x += r.size.width - thickness;
2770 NSRectFill (s);
2771 }
2772 }
2773
2774
2775 static void
2776 ns_draw_relief (NSRect r, int thickness, char raised_p,
2777 char top_p, char bottom_p, char left_p, char right_p,
2778 struct glyph_string *s)
2779 /* --------------------------------------------------------------------------
2780 Draw a relief rect inside r, optionally leaving some sides open.
2781 Note we can't just use an NSDrawBezel command, because of the possibility
2782 of some sides not being drawn, and because the rect will be filled.
2783 -------------------------------------------------------------------------- */
2784 {
2785 static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2786 NSColor *newBaseCol = nil;
2787 NSRect sr = r;
2788
2789 NSTRACE (ns_draw_relief);
2790
2791 /* set up colors */
2792
2793 if (s->face->use_box_color_for_shadows_p)
2794 {
2795 newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2796 }
2797 /* else if (s->first_glyph->type == IMAGE_GLYPH
2798 && s->img->pixmap
2799 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2800 {
2801 newBaseCol = IMAGE_BACKGROUND (s->img, s->f, 0);
2802 } */
2803 else
2804 {
2805 newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2806 }
2807
2808 if (newBaseCol == nil)
2809 newBaseCol = [NSColor grayColor];
2810
2811 if (newBaseCol != baseCol) /* TODO: better check */
2812 {
2813 [baseCol release];
2814 baseCol = [newBaseCol retain];
2815 [lightCol release];
2816 lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2817 [darkCol release];
2818 darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2819 }
2820
2821 [(raised_p ? lightCol : darkCol) set];
2822
2823 /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2824
2825 /* top */
2826 sr.size.height = thickness;
2827 if (top_p) NSRectFill (sr);
2828
2829 /* left */
2830 sr.size.height = r.size.height;
2831 sr.size.width = thickness;
2832 if (left_p) NSRectFill (sr);
2833
2834 [(raised_p ? darkCol : lightCol) set];
2835
2836 /* bottom */
2837 sr.size.width = r.size.width;
2838 sr.size.height = thickness;
2839 sr.origin.y += r.size.height - thickness;
2840 if (bottom_p) NSRectFill (sr);
2841
2842 /* right */
2843 sr.size.height = r.size.height;
2844 sr.origin.y = r.origin.y;
2845 sr.size.width = thickness;
2846 sr.origin.x += r.size.width - thickness;
2847 if (right_p) NSRectFill (sr);
2848 }
2849
2850
2851 static void
2852 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2853 /* --------------------------------------------------------------------------
2854 Function modeled after x_draw_glyph_string_box ().
2855 Sets up parameters for drawing.
2856 -------------------------------------------------------------------------- */
2857 {
2858 int right_x, last_x;
2859 char left_p, right_p;
2860 struct glyph *last_glyph;
2861 NSRect r;
2862 int thickness;
2863 struct face *face;
2864
2865 if (s->hl == DRAW_MOUSE_FACE)
2866 {
2867 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2868 if (!face)
2869 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2870 }
2871 else
2872 face = s->face;
2873
2874 thickness = face->box_line_width;
2875
2876 NSTRACE (ns_dumpglyphs_box_or_relief);
2877
2878 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2879 ? WINDOW_RIGHT_EDGE_X (s->w)
2880 : window_box_right (s->w, s->area));
2881 last_glyph = (s->cmp || s->img
2882 ? s->first_glyph : s->first_glyph + s->nchars-1);
2883
2884 right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2885 ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2886
2887 left_p = (s->first_glyph->left_box_line_p
2888 || (s->hl == DRAW_MOUSE_FACE
2889 && (s->prev == NULL || s->prev->hl != s->hl)));
2890 right_p = (last_glyph->right_box_line_p
2891 || (s->hl == DRAW_MOUSE_FACE
2892 && (s->next == NULL || s->next->hl != s->hl)));
2893
2894 r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2895
2896 /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
2897 if (s->face->box == FACE_SIMPLE_BOX && s->face->box_color)
2898 {
2899 ns_draw_box (r, abs (thickness),
2900 ns_lookup_indexed_color (face->box_color, s->f),
2901 left_p, right_p);
2902 }
2903 else
2904 {
2905 ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2906 1, 1, left_p, right_p, s);
2907 }
2908 }
2909
2910
2911 static void
2912 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2913 /* --------------------------------------------------------------------------
2914 Modeled after x_draw_glyph_string_background, which draws BG in
2915 certain cases. Others are left to the text rendering routine.
2916 -------------------------------------------------------------------------- */
2917 {
2918 NSTRACE (ns_maybe_dumpglyphs_background);
2919
2920 if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2921 {
2922 int box_line_width = max (s->face->box_line_width, 0);
2923 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2924 || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2925 {
2926 struct face *face;
2927 if (s->hl == DRAW_MOUSE_FACE)
2928 {
2929 face = FACE_FROM_ID (s->f,
2930 MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2931 if (!face)
2932 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2933 }
2934 else
2935 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2936 if (!face->stipple)
2937 [(NS_FACE_BACKGROUND (face) != 0
2938 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2939 : FRAME_BACKGROUND_COLOR (s->f)) set];
2940 else
2941 {
2942 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (s->f);
2943 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2944 }
2945
2946 if (s->hl != DRAW_CURSOR)
2947 {
2948 NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2949 s->background_width,
2950 s->height-2*box_line_width);
2951 NSRectFill (r);
2952 }
2953
2954 s->background_filled_p = 1;
2955 }
2956 }
2957 }
2958
2959
2960 static void
2961 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2962 /* --------------------------------------------------------------------------
2963 Renders an image and associated borders.
2964 -------------------------------------------------------------------------- */
2965 {
2966 EmacsImage *img = s->img->pixmap;
2967 int box_line_vwidth = max (s->face->box_line_width, 0);
2968 int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2969 int bg_x, bg_y, bg_height;
2970 int th;
2971 char raised_p;
2972 NSRect br;
2973 struct face *face;
2974 NSColor *tdCol;
2975
2976 NSTRACE (ns_dumpglyphs_image);
2977
2978 if (s->face->box != FACE_NO_BOX
2979 && s->first_glyph->left_box_line_p && s->slice.x == 0)
2980 x += abs (s->face->box_line_width);
2981
2982 bg_x = x;
2983 bg_y = s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2984 bg_height = s->height;
2985 /* other terms have this, but was causing problems w/tabbar mode */
2986 /* - 2 * box_line_vwidth; */
2987
2988 if (s->slice.x == 0) x += s->img->hmargin;
2989 if (s->slice.y == 0) y += s->img->vmargin;
2990
2991 /* Draw BG: if we need larger area than image itself cleared, do that,
2992 otherwise, since we composite the image under NS (instead of mucking
2993 with its background color), we must clear just the image area. */
2994 if (s->hl == DRAW_MOUSE_FACE)
2995 {
2996 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
2997 if (!face)
2998 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2999 }
3000 else
3001 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3002
3003 [ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f) set];
3004
3005 if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
3006 || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
3007 {
3008 br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
3009 s->background_filled_p = 1;
3010 }
3011 else
3012 {
3013 br = NSMakeRect (x, y, s->slice.width, s->slice.height);
3014 }
3015
3016 NSRectFill (br);
3017
3018 /* Draw the image.. do we need to draw placeholder if img ==nil? */
3019 if (img != nil)
3020 {
3021 #ifdef NS_IMPL_COCOA
3022 NSRect dr = NSMakeRect (x, y, s->slice.width, s->slice.height);
3023 NSRect ir = NSMakeRect (s->slice.x, s->slice.y,
3024 s->slice.width, s->slice.height);
3025 [img drawInRect: dr
3026 fromRect: ir
3027 operation: NSCompositeSourceOver
3028 fraction: 1.0
3029 respectFlipped: YES
3030 hints: nil];
3031 #else
3032 [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
3033 operation: NSCompositeSourceOver];
3034 #endif
3035 }
3036
3037 if (s->hl == DRAW_CURSOR)
3038 {
3039 [FRAME_CURSOR_COLOR (s->f) set];
3040 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3041 tdCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3042 else
3043 /* Currently on NS img->mask is always 0. Since
3044 get_window_cursor_type specifies a hollow box cursor when on
3045 a non-masked image we never reach this clause. But we put it
3046 in in anticipation of better support for image masks on
3047 NS. */
3048 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3049 }
3050 else
3051 {
3052 tdCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3053 }
3054
3055 /* Draw underline, overline, strike-through. */
3056 ns_draw_text_decoration (s, face, tdCol, br.size.width, br.origin.x);
3057
3058 /* Draw relief, if requested */
3059 if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
3060 {
3061 if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
3062 {
3063 th = tool_bar_button_relief >= 0 ?
3064 tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
3065 raised_p = (s->hl == DRAW_IMAGE_RAISED);
3066 }
3067 else
3068 {
3069 th = abs (s->img->relief);
3070 raised_p = (s->img->relief > 0);
3071 }
3072
3073 r.origin.x = x - th;
3074 r.origin.y = y - th;
3075 r.size.width = s->slice.width + 2*th-1;
3076 r.size.height = s->slice.height + 2*th-1;
3077 ns_draw_relief (r, th, raised_p,
3078 s->slice.y == 0,
3079 s->slice.y + s->slice.height == s->img->height,
3080 s->slice.x == 0,
3081 s->slice.x + s->slice.width == s->img->width, s);
3082 }
3083
3084 /* If there is no mask, the background won't be seen,
3085 so draw a rectangle on the image for the cursor.
3086 Do this for all images, getting transparency right is not reliable. */
3087 if (s->hl == DRAW_CURSOR)
3088 {
3089 int thickness = abs (s->img->relief);
3090 if (thickness == 0) thickness = 1;
3091 ns_draw_box (br, thickness, FRAME_CURSOR_COLOR (s->f), 1, 1);
3092 }
3093 }
3094
3095
3096 static void
3097 ns_dumpglyphs_stretch (struct glyph_string *s)
3098 {
3099 NSRect r[2];
3100 int n, i;
3101 struct face *face;
3102 NSColor *fgCol, *bgCol;
3103
3104 if (!s->background_filled_p)
3105 {
3106 n = ns_get_glyph_string_clip_rect (s, r);
3107 *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
3108
3109 ns_focus (s->f, r, n);
3110
3111 if (s->hl == DRAW_MOUSE_FACE)
3112 {
3113 face = FACE_FROM_ID (s->f, MOUSE_HL_INFO (s->f)->mouse_face_face_id);
3114 if (!face)
3115 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
3116 }
3117 else
3118 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
3119
3120 bgCol = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f);
3121 fgCol = ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f);
3122
3123 for (i = 0; i < n; ++i)
3124 {
3125 if (!s->row->full_width_p)
3126 {
3127 int overrun, leftoverrun;
3128
3129 /* truncate to avoid overwriting fringe and/or scrollbar */
3130 overrun = max (0, (s->x + s->background_width)
3131 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
3132 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
3133 r[i].size.width -= overrun;
3134
3135 /* truncate to avoid overwriting to left of the window box */
3136 leftoverrun = (WINDOW_BOX_LEFT_EDGE_X (s->w)
3137 + WINDOW_LEFT_FRINGE_WIDTH (s->w)) - s->x;
3138
3139 if (leftoverrun > 0)
3140 {
3141 r[i].origin.x += leftoverrun;
3142 r[i].size.width -= leftoverrun;
3143 }
3144
3145 /* XXX: Try to work between problem where a stretch glyph on
3146 a partially-visible bottom row will clear part of the
3147 modeline, and another where list-buffers headers and similar
3148 rows erroneously have visible_height set to 0. Not sure
3149 where this is coming from as other terms seem not to show. */
3150 r[i].size.height = min (s->height, s->row->visible_height);
3151 }
3152
3153 [bgCol set];
3154
3155 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3156 overwriting cursor (usually when cursor on a tab) */
3157 if (s->hl == DRAW_CURSOR)
3158 {
3159 CGFloat x, width;
3160
3161 x = r[i].origin.x;
3162 width = s->w->phys_cursor_width;
3163 r[i].size.width -= width;
3164 r[i].origin.x += width;
3165
3166 NSRectFill (r[i]);
3167
3168 /* Draw overlining, etc. on the cursor. */
3169 if (s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3170 ns_draw_text_decoration (s, face, bgCol, width, x);
3171 else
3172 ns_draw_text_decoration (s, face, fgCol, width, x);
3173 }
3174 else
3175 {
3176 NSRectFill (r[i]);
3177 }
3178
3179 /* Draw overlining, etc. on the stretch glyph (or the part
3180 of the stretch glyph after the cursor). */
3181 ns_draw_text_decoration (s, face, fgCol, r[i].size.width,
3182 r[i].origin.x);
3183 }
3184 ns_unfocus (s->f);
3185 s->background_filled_p = 1;
3186 }
3187 }
3188
3189
3190 static void
3191 ns_draw_glyph_string (struct glyph_string *s)
3192 /* --------------------------------------------------------------------------
3193 External (RIF): Main draw-text call.
3194 -------------------------------------------------------------------------- */
3195 {
3196 /* TODO (optimize): focus for box and contents draw */
3197 NSRect r[2];
3198 int n, flags;
3199 char box_drawn_p = 0;
3200 struct font *font = s->face->font;
3201 if (! font) font = FRAME_FONT (s->f);
3202
3203 NSTRACE (ns_draw_glyph_string);
3204
3205 if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
3206 {
3207 int width;
3208 struct glyph_string *next;
3209
3210 for (width = 0, next = s->next;
3211 next && width < s->right_overhang;
3212 width += next->width, next = next->next)
3213 if (next->first_glyph->type != IMAGE_GLYPH)
3214 {
3215 if (next->first_glyph->type != STRETCH_GLYPH)
3216 {
3217 n = ns_get_glyph_string_clip_rect (s->next, r);
3218 ns_focus (s->f, r, n);
3219 ns_maybe_dumpglyphs_background (s->next, 1);
3220 ns_unfocus (s->f);
3221 }
3222 else
3223 {
3224 ns_dumpglyphs_stretch (s->next);
3225 }
3226 next->num_clips = 0;
3227 }
3228 }
3229
3230 if (!s->for_overlaps && s->face->box != FACE_NO_BOX
3231 && (s->first_glyph->type == CHAR_GLYPH
3232 || s->first_glyph->type == COMPOSITE_GLYPH))
3233 {
3234 n = ns_get_glyph_string_clip_rect (s, r);
3235 ns_focus (s->f, r, n);
3236 ns_maybe_dumpglyphs_background (s, 1);
3237 ns_dumpglyphs_box_or_relief (s);
3238 ns_unfocus (s->f);
3239 box_drawn_p = 1;
3240 }
3241
3242 switch (s->first_glyph->type)
3243 {
3244
3245 case IMAGE_GLYPH:
3246 n = ns_get_glyph_string_clip_rect (s, r);
3247 ns_focus (s->f, r, n);
3248 ns_dumpglyphs_image (s, r[0]);
3249 ns_unfocus (s->f);
3250 break;
3251
3252 case STRETCH_GLYPH:
3253 ns_dumpglyphs_stretch (s);
3254 break;
3255
3256 case CHAR_GLYPH:
3257 case COMPOSITE_GLYPH:
3258 n = ns_get_glyph_string_clip_rect (s, r);
3259 ns_focus (s->f, r, n);
3260
3261 if (s->for_overlaps || (s->cmp_from > 0
3262 && ! s->first_glyph->u.cmp.automatic))
3263 s->background_filled_p = 1;
3264 else
3265 ns_maybe_dumpglyphs_background
3266 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3267
3268 flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
3269 (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
3270 (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
3271 NS_DUMPGLYPH_NORMAL));
3272
3273 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3274 {
3275 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3276 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3277 NS_FACE_FOREGROUND (s->face) = tmp;
3278 }
3279
3280 {
3281 BOOL isComposite = s->first_glyph->type == COMPOSITE_GLYPH;
3282 int end = isComposite ? s->cmp_to : s->nchars;
3283
3284 font->driver->draw
3285 (s, s->cmp_from, end, s->x, s->ybase,
3286 (flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
3287 || flags == NS_DUMPGLYPH_MOUSEFACE);
3288
3289 }
3290
3291 {
3292 NSColor *col = (NS_FACE_FOREGROUND (s->face) != 0
3293 ? ns_lookup_indexed_color (NS_FACE_FOREGROUND (s->face),
3294 s->f)
3295 : FRAME_FOREGROUND_COLOR (s->f));
3296 [col set];
3297
3298 /* Draw underline, overline, strike-through. */
3299 ns_draw_text_decoration (s, s->face, col, s->width, s->x);
3300 }
3301
3302 if (s->hl == DRAW_CURSOR && s->w->phys_cursor_type == FILLED_BOX_CURSOR)
3303 {
3304 unsigned long tmp = NS_FACE_BACKGROUND (s->face);
3305 NS_FACE_BACKGROUND (s->face) = NS_FACE_FOREGROUND (s->face);
3306 NS_FACE_FOREGROUND (s->face) = tmp;
3307 }
3308
3309 ns_unfocus (s->f);
3310 break;
3311
3312 case GLYPHLESS_GLYPH:
3313 n = ns_get_glyph_string_clip_rect (s, r);
3314 ns_focus (s->f, r, n);
3315
3316 if (s->for_overlaps || (s->cmp_from > 0
3317 && ! s->first_glyph->u.cmp.automatic))
3318 s->background_filled_p = 1;
3319 else
3320 ns_maybe_dumpglyphs_background
3321 (s, s->first_glyph->type == COMPOSITE_GLYPH);
3322 /* ... */
3323 /* Not yet implemented. */
3324 /* ... */
3325 ns_unfocus (s->f);
3326 break;
3327
3328 default:
3329 emacs_abort ();
3330 }
3331
3332 /* Draw box if not done already. */
3333 if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
3334 {
3335 n = ns_get_glyph_string_clip_rect (s, r);
3336 ns_focus (s->f, r, n);
3337 ns_dumpglyphs_box_or_relief (s);
3338 ns_unfocus (s->f);
3339 }
3340
3341 s->num_clips = 0;
3342 }
3343
3344
3345
3346 /* ==========================================================================
3347
3348 Event loop
3349
3350 ========================================================================== */
3351
3352
3353 static void
3354 ns_send_appdefined (int value)
3355 /* --------------------------------------------------------------------------
3356 Internal: post an appdefined event which EmacsApp-sendEvent will
3357 recognize and take as a command to halt the event loop.
3358 -------------------------------------------------------------------------- */
3359 {
3360 /*NSTRACE (ns_send_appdefined); */
3361
3362 #ifdef NS_IMPL_GNUSTEP
3363 // GNUstep needs postEvent to happen on the main thread.
3364 if (! [[NSThread currentThread] isMainThread])
3365 {
3366 EmacsApp *app = (EmacsApp *)NSApp;
3367 app->nextappdefined = value;
3368 [app performSelectorOnMainThread:@selector (sendFromMainThread:)
3369 withObject:nil
3370 waitUntilDone:YES];
3371 return;
3372 }
3373 #endif
3374
3375 /* Only post this event if we haven't already posted one. This will end
3376 the [NXApp run] main loop after having processed all events queued at
3377 this moment. */
3378
3379 #ifdef NS_IMPL_COCOA
3380 if (! send_appdefined)
3381 {
3382 /* OSX 10.10.1 swallows the AppDefined event we are sending ourselves
3383 in certain situations (rapid incoming events).
3384 So check if we have one, if not add one. */
3385 NSEvent *appev = [NSApp nextEventMatchingMask:NSApplicationDefinedMask
3386 untilDate:[NSDate distantPast]
3387 inMode:NSDefaultRunLoopMode
3388 dequeue:NO];
3389 if (! appev) send_appdefined = YES;
3390 }
3391 #endif
3392
3393 if (send_appdefined)
3394 {
3395 NSEvent *nxev;
3396
3397 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
3398 send_appdefined = NO;
3399
3400 /* Don't need wakeup timer any more */
3401 if (timed_entry)
3402 {
3403 [timed_entry invalidate];
3404 [timed_entry release];
3405 timed_entry = nil;
3406 }
3407
3408 nxev = [NSEvent otherEventWithType: NSApplicationDefined
3409 location: NSMakePoint (0, 0)
3410 modifierFlags: 0
3411 timestamp: 0
3412 windowNumber: [[NSApp mainWindow] windowNumber]
3413 context: [NSApp context]
3414 subtype: 0
3415 data1: value
3416 data2: 0];
3417
3418 /* Post an application defined event on the event queue. When this is
3419 received the [NXApp run] will return, thus having processed all
3420 events which are currently queued. */
3421 [NSApp postEvent: nxev atStart: NO];
3422 }
3423 }
3424
3425 #ifdef HAVE_NATIVE_FS
3426 static void
3427 check_native_fs ()
3428 {
3429 Lisp_Object frame, tail;
3430
3431 if (ns_last_use_native_fullscreen == ns_use_native_fullscreen)
3432 return;
3433
3434 ns_last_use_native_fullscreen = ns_use_native_fullscreen;
3435
3436 FOR_EACH_FRAME (tail, frame)
3437 {
3438 struct frame *f = XFRAME (frame);
3439 if (FRAME_NS_P (f))
3440 {
3441 EmacsView *view = FRAME_NS_VIEW (f);
3442 [view updateCollectionBehavior];
3443 }
3444 }
3445 }
3446 #endif
3447
3448 /* GNUstep does not have cancelTracking. */
3449 #ifdef NS_IMPL_COCOA
3450 /* Check if menu open should be canceled or continued as normal. */
3451 void
3452 ns_check_menu_open (NSMenu *menu)
3453 {
3454 /* Click in menu bar? */
3455 NSArray *a = [[NSApp mainMenu] itemArray];
3456 int i;
3457 BOOL found = NO;
3458
3459 if (menu == nil) // Menu tracking ended.
3460 {
3461 if (menu_will_open_state == MENU_OPENING)
3462 menu_will_open_state = MENU_NONE;
3463 return;
3464 }
3465
3466 for (i = 0; ! found && i < [a count]; i++)
3467 found = menu == [[a objectAtIndex:i] submenu];
3468 if (found)
3469 {
3470 if (menu_will_open_state == MENU_NONE && emacs_event)
3471 {
3472 NSEvent *theEvent = [NSApp currentEvent];
3473 struct frame *emacsframe = SELECTED_FRAME ();
3474
3475 [menu cancelTracking];
3476 menu_will_open_state = MENU_PENDING;
3477 emacs_event->kind = MENU_BAR_ACTIVATE_EVENT;
3478 EV_TRAILER (theEvent);
3479
3480 CGEventRef ourEvent = CGEventCreate (NULL);
3481 menu_mouse_point = CGEventGetLocation (ourEvent);
3482 CFRelease (ourEvent);
3483 }
3484 else if (menu_will_open_state == MENU_OPENING)
3485 {
3486 menu_will_open_state = MENU_NONE;
3487 }
3488 }
3489 }
3490
3491 /* Redo saved menu click if state is MENU_PENDING. */
3492 void
3493 ns_check_pending_open_menu ()
3494 {
3495 if (menu_will_open_state == MENU_PENDING)
3496 {
3497 CGEventSourceRef source
3498 = CGEventSourceCreate (kCGEventSourceStateHIDSystemState);
3499
3500 CGEventRef event = CGEventCreateMouseEvent (source,
3501 kCGEventLeftMouseDown,
3502 menu_mouse_point,
3503 kCGMouseButtonLeft);
3504 CGEventSetType (event, kCGEventLeftMouseDown);
3505 CGEventPost (kCGHIDEventTap, event);
3506 CFRelease (event);
3507 CFRelease (source);
3508
3509 menu_will_open_state = MENU_OPENING;
3510 }
3511 }
3512 #endif /* NS_IMPL_COCOA */
3513
3514 static void
3515 unwind_apploopnr (Lisp_Object not_used)
3516 {
3517 --apploopnr;
3518 n_emacs_events_pending = 0;
3519 ns_finish_events ();
3520 q_event_ptr = NULL;
3521 }
3522
3523 static int
3524 ns_read_socket (struct terminal *terminal, struct input_event *hold_quit)
3525 /* --------------------------------------------------------------------------
3526 External (hook): Post an event to ourself and keep reading events until
3527 we read it back again. In effect process all events which were waiting.
3528 From 21+ we have to manage the event buffer ourselves.
3529 -------------------------------------------------------------------------- */
3530 {
3531 struct input_event ev;
3532 int nevents;
3533
3534 /* NSTRACE (ns_read_socket); */
3535
3536 #ifdef HAVE_NATIVE_FS
3537 check_native_fs ();
3538 #endif
3539
3540 if ([NSApp modalWindow] != nil)
3541 return -1;
3542
3543 if (hold_event_q.nr > 0)
3544 {
3545 int i;
3546 for (i = 0; i < hold_event_q.nr; ++i)
3547 kbd_buffer_store_event_hold (&hold_event_q.q[i], hold_quit);
3548 hold_event_q.nr = 0;
3549 return i;
3550 }
3551
3552 block_input ();
3553 n_emacs_events_pending = 0;
3554 ns_init_events (&ev);
3555 q_event_ptr = hold_quit;
3556
3557 /* we manage autorelease pools by allocate/reallocate each time around
3558 the loop; strict nesting is occasionally violated but seems not to
3559 matter.. earlier methods using full nesting caused major memory leaks */
3560 [outerpool release];
3561 outerpool = [[NSAutoreleasePool alloc] init];
3562
3563 /* If have pending open-file requests, attend to the next one of those. */
3564 if (ns_pending_files && [ns_pending_files count] != 0
3565 && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3566 {
3567 [ns_pending_files removeObjectAtIndex: 0];
3568 }
3569 /* Deal with pending service requests. */
3570 else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3571 && [(EmacsApp *)
3572 NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3573 withArg: [ns_pending_service_args objectAtIndex: 0]])
3574 {
3575 [ns_pending_service_names removeObjectAtIndex: 0];
3576 [ns_pending_service_args removeObjectAtIndex: 0];
3577 }
3578 else
3579 {
3580 ptrdiff_t specpdl_count = SPECPDL_INDEX ();
3581 /* Run and wait for events. We must always send one NX_APPDEFINED event
3582 to ourself, otherwise [NXApp run] will never exit. */
3583 send_appdefined = YES;
3584 ns_send_appdefined (-1);
3585
3586 if (++apploopnr != 1)
3587 {
3588 emacs_abort ();
3589 }
3590 record_unwind_protect (unwind_apploopnr, Qt);
3591 [NSApp run];
3592 unbind_to (specpdl_count, Qnil); /* calls unwind_apploopnr */
3593 }
3594
3595 nevents = n_emacs_events_pending;
3596 n_emacs_events_pending = 0;
3597 ns_finish_events ();
3598 q_event_ptr = NULL;
3599 unblock_input ();
3600
3601 return nevents;
3602 }
3603
3604
3605 int
3606 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3607 fd_set *exceptfds, struct timespec const *timeout,
3608 sigset_t const *sigmask)
3609 /* --------------------------------------------------------------------------
3610 Replacement for select, checking for events
3611 -------------------------------------------------------------------------- */
3612 {
3613 int result;
3614 int t, k, nr = 0;
3615 struct input_event event;
3616 char c;
3617
3618 /* NSTRACE (ns_select); */
3619
3620 #ifdef HAVE_NATIVE_FS
3621 check_native_fs ();
3622 #endif
3623
3624 if (hold_event_q.nr > 0)
3625 {
3626 /* We already have events pending. */
3627 raise (SIGIO);
3628 errno = EINTR;
3629 return -1;
3630 }
3631
3632 for (k = 0; k < nfds+1; k++)
3633 {
3634 if (readfds && FD_ISSET(k, readfds)) ++nr;
3635 if (writefds && FD_ISSET(k, writefds)) ++nr;
3636 }
3637
3638 if (NSApp == nil
3639 || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0))
3640 return pselect (nfds, readfds, writefds, exceptfds, timeout, sigmask);
3641
3642 [outerpool release];
3643 outerpool = [[NSAutoreleasePool alloc] init];
3644
3645
3646 send_appdefined = YES;
3647 if (nr > 0)
3648 {
3649 pthread_mutex_lock (&select_mutex);
3650 select_nfds = nfds;
3651 select_valid = 0;
3652 if (readfds)
3653 {
3654 select_readfds = *readfds;
3655 select_valid += SELECT_HAVE_READ;
3656 }
3657 if (writefds)
3658 {
3659 select_writefds = *writefds;
3660 select_valid += SELECT_HAVE_WRITE;
3661 }
3662
3663 if (timeout)
3664 {
3665 select_timeout = *timeout;
3666 select_valid += SELECT_HAVE_TMO;
3667 }
3668
3669 pthread_mutex_unlock (&select_mutex);
3670
3671 /* Inform fd_handler that select should be called */
3672 c = 'g';
3673 emacs_write_sig (selfds[1], &c, 1);
3674 }
3675 else if (nr == 0 && timeout)
3676 {
3677 /* No file descriptor, just a timeout, no need to wake fd_handler */
3678 double time = timespectod (*timeout);
3679 timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3680 target: NSApp
3681 selector:
3682 @selector (timeout_handler:)
3683 userInfo: 0
3684 repeats: NO]
3685 retain];
3686 }
3687 else /* No timeout and no file descriptors, can this happen? */
3688 {
3689 /* Send appdefined so we exit from the loop */
3690 ns_send_appdefined (-1);
3691 }
3692
3693 block_input ();
3694 ns_init_events (&event);
3695 if (++apploopnr != 1)
3696 {
3697 emacs_abort ();
3698 }
3699
3700 {
3701 ptrdiff_t specpdl_count = SPECPDL_INDEX ();
3702 record_unwind_protect (unwind_apploopnr, Qt);
3703 [NSApp run];
3704 unbind_to (specpdl_count, Qnil); /* calls unwind_apploopnr */
3705 }
3706
3707 ns_finish_events ();
3708 if (nr > 0 && readfds)
3709 {
3710 c = 's';
3711 emacs_write_sig (selfds[1], &c, 1);
3712 }
3713 unblock_input ();
3714
3715 t = last_appdefined_event_data;
3716
3717 if (t != NO_APPDEFINED_DATA)
3718 {
3719 last_appdefined_event_data = NO_APPDEFINED_DATA;
3720
3721 if (t == -2)
3722 {
3723 /* The NX_APPDEFINED event we received was a timeout. */
3724 result = 0;
3725 }
3726 else if (t == -1)
3727 {
3728 /* The NX_APPDEFINED event we received was the result of
3729 at least one real input event arriving. */
3730 errno = EINTR;
3731 result = -1;
3732 }
3733 else
3734 {
3735 /* Received back from select () in fd_handler; copy the results */
3736 pthread_mutex_lock (&select_mutex);
3737 if (readfds) *readfds = select_readfds;
3738 if (writefds) *writefds = select_writefds;
3739 pthread_mutex_unlock (&select_mutex);
3740 result = t;
3741 }
3742 }
3743 else
3744 {
3745 errno = EINTR;
3746 result = -1;
3747 }
3748
3749 return result;
3750 }
3751
3752
3753
3754 /* ==========================================================================
3755
3756 Scrollbar handling
3757
3758 ========================================================================== */
3759
3760
3761 static void
3762 ns_set_vertical_scroll_bar (struct window *window,
3763 int portion, int whole, int position)
3764 /* --------------------------------------------------------------------------
3765 External (hook): Update or add scrollbar
3766 -------------------------------------------------------------------------- */
3767 {
3768 Lisp_Object win;
3769 NSRect r, v;
3770 struct frame *f = XFRAME (WINDOW_FRAME (window));
3771 EmacsView *view = FRAME_NS_VIEW (f);
3772 EmacsScroller *bar;
3773 int window_y, window_height;
3774 int top, left, height, width;
3775 BOOL update_p = YES;
3776
3777 /* optimization; display engine sends WAY too many of these.. */
3778 if (!NILP (window->vertical_scroll_bar))
3779 {
3780 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3781 if ([bar checkSamePosition: position portion: portion whole: whole])
3782 {
3783 if (view->scrollbarsNeedingUpdate == 0)
3784 {
3785 if (!windows_or_buffers_changed)
3786 return;
3787 }
3788 else
3789 view->scrollbarsNeedingUpdate--;
3790 update_p = NO;
3791 }
3792 }
3793
3794 NSTRACE (ns_set_vertical_scroll_bar);
3795
3796 /* Get dimensions. */
3797 window_box (window, ANY_AREA, 0, &window_y, 0, &window_height);
3798 top = window_y;
3799 height = window_height;
3800 width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3801 left = WINDOW_SCROLL_BAR_AREA_X (window);
3802
3803 r = NSMakeRect (left, top, width, height);
3804 /* the parent view is flipped, so we need to flip y value */
3805 v = [view frame];
3806 r.origin.y = (v.size.height - r.size.height - r.origin.y);
3807
3808 XSETWINDOW (win, window);
3809 block_input ();
3810
3811 /* we want at least 5 lines to display a scrollbar */
3812 if (WINDOW_TOTAL_LINES (window) < 5)
3813 {
3814 if (!NILP (window->vertical_scroll_bar))
3815 {
3816 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3817 [bar removeFromSuperview];
3818 wset_vertical_scroll_bar (window, Qnil);
3819 [bar release];
3820 }
3821 ns_clear_frame_area (f, left, top, width, height);
3822 unblock_input ();
3823 return;
3824 }
3825
3826 if (NILP (window->vertical_scroll_bar))
3827 {
3828 if (width > 0 && height > 0)
3829 ns_clear_frame_area (f, left, top, width, height);
3830
3831 bar = [[EmacsScroller alloc] initFrame: r window: win];
3832 wset_vertical_scroll_bar (window, make_save_ptr (bar));
3833 update_p = YES;
3834 }
3835 else
3836 {
3837 NSRect oldRect;
3838 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3839 oldRect = [bar frame];
3840 r.size.width = oldRect.size.width;
3841 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3842 {
3843 if (oldRect.origin.x != r.origin.x)
3844 ns_clear_frame_area (f, left, top, width, height);
3845 [bar setFrame: r];
3846 }
3847 }
3848
3849 if (update_p)
3850 [bar setPosition: position portion: portion whole: whole];
3851 unblock_input ();
3852 }
3853
3854
3855 static void
3856 ns_set_horizontal_scroll_bar (struct window *window,
3857 int portion, int whole, int position)
3858 /* --------------------------------------------------------------------------
3859 External (hook): Update or add scrollbar
3860 -------------------------------------------------------------------------- */
3861 {
3862 Lisp_Object win;
3863 NSRect r, v;
3864 struct frame *f = XFRAME (WINDOW_FRAME (window));
3865 EmacsView *view = FRAME_NS_VIEW (f);
3866 EmacsScroller *bar;
3867 int top, height, left, width;
3868 int window_x, window_width;
3869 int pixel_width = WINDOW_PIXEL_WIDTH (window);
3870 BOOL update_p = YES;
3871
3872 /* optimization; display engine sends WAY too many of these.. */
3873 if (!NILP (window->horizontal_scroll_bar))
3874 {
3875 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
3876 if ([bar checkSamePosition: position portion: portion whole: whole])
3877 {
3878 if (view->scrollbarsNeedingUpdate == 0)
3879 {
3880 if (!windows_or_buffers_changed)
3881 return;
3882 }
3883 else
3884 view->scrollbarsNeedingUpdate--;
3885 update_p = NO;
3886 }
3887 }
3888
3889 NSTRACE (ns_set_horizontal_scroll_bar);
3890
3891 /* Get dimensions. */
3892 window_box (window, ANY_AREA, 0, &window_x, &window_width, 0);
3893 left = window_x;
3894 width = window_width;
3895 height = WINDOW_CONFIG_SCROLL_BAR_LINES (window) * FRAME_LINE_HEIGHT (f);
3896 top = WINDOW_SCROLL_BAR_AREA_Y (window);
3897
3898 r = NSMakeRect (left, top, width, height);
3899 /* the parent view is flipped, so we need to flip y value */
3900 v = [view frame];
3901 /* ??????? PXW/scrollbars !!!!!!!!!!!!!!!!!!!! */
3902 r.origin.y = (v.size.height - r.size.height - r.origin.y);
3903
3904 XSETWINDOW (win, window);
3905 block_input ();
3906
3907 if (WINDOW_TOTAL_COLS (window) < 5)
3908 {
3909 if (!NILP (window->horizontal_scroll_bar))
3910 {
3911 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
3912 [bar removeFromSuperview];
3913 wset_horizontal_scroll_bar (window, Qnil);
3914 }
3915 ns_clear_frame_area (f, left, top, width, height);
3916 unblock_input ();
3917 return;
3918 }
3919
3920 if (NILP (window->horizontal_scroll_bar))
3921 {
3922 if (width > 0 && height > 0)
3923 ns_clear_frame_area (f, left, top, width, height);
3924
3925 bar = [[EmacsScroller alloc] initFrame: r window: win];
3926 wset_horizontal_scroll_bar (window, make_save_ptr (bar));
3927 update_p = YES;
3928 }
3929 else
3930 {
3931 NSRect oldRect;
3932 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
3933 oldRect = [bar frame];
3934 r.size.width = oldRect.size.width;
3935 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3936 {
3937 if (oldRect.origin.x != r.origin.x)
3938 ns_clear_frame_area (f, left, top, width, height);
3939 [bar setFrame: r];
3940 update_p = YES;
3941 }
3942 }
3943
3944 if (update_p)
3945 [bar setPosition: position portion: portion whole: whole];
3946 unblock_input ();
3947 }
3948
3949
3950 static void
3951 ns_condemn_scroll_bars (struct frame *f)
3952 /* --------------------------------------------------------------------------
3953 External (hook): arrange for all frame's scrollbars to be removed
3954 at next call to judge_scroll_bars, except for those redeemed.
3955 -------------------------------------------------------------------------- */
3956 {
3957 int i;
3958 id view;
3959 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3960
3961 NSTRACE (ns_condemn_scroll_bars);
3962
3963 for (i =[subviews count]-1; i >= 0; i--)
3964 {
3965 view = [subviews objectAtIndex: i];
3966 if ([view isKindOfClass: [EmacsScroller class]])
3967 [view condemn];
3968 }
3969 }
3970
3971
3972 static void
3973 ns_redeem_scroll_bar (struct window *window)
3974 /* --------------------------------------------------------------------------
3975 External (hook): arrange to spare this window's scrollbar
3976 at next call to judge_scroll_bars.
3977 -------------------------------------------------------------------------- */
3978 {
3979 id bar;
3980 NSTRACE (ns_redeem_scroll_bar);
3981 if (!NILP (window->vertical_scroll_bar))
3982 {
3983 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3984 [bar reprieve];
3985 }
3986
3987 if (!NILP (window->horizontal_scroll_bar))
3988 {
3989 bar = XNS_SCROLL_BAR (window->horizontal_scroll_bar);
3990 [bar reprieve];
3991 }
3992 }
3993
3994
3995 static void
3996 ns_judge_scroll_bars (struct frame *f)
3997 /* --------------------------------------------------------------------------
3998 External (hook): destroy all scrollbars on frame that weren't
3999 redeemed after call to condemn_scroll_bars.
4000 -------------------------------------------------------------------------- */
4001 {
4002 int i;
4003 id view;
4004 EmacsView *eview = FRAME_NS_VIEW (f);
4005 NSArray *subviews = [[eview superview] subviews];
4006 BOOL removed = NO;
4007
4008 NSTRACE (ns_judge_scroll_bars);
4009 for (i = [subviews count]-1; i >= 0; --i)
4010 {
4011 view = [subviews objectAtIndex: i];
4012 if (![view isKindOfClass: [EmacsScroller class]]) continue;
4013 if ([view judge])
4014 removed = YES;
4015 }
4016
4017 if (removed)
4018 [eview updateFrameSize: NO];
4019 }
4020
4021 /* ==========================================================================
4022
4023 Initialization
4024
4025 ========================================================================== */
4026
4027 int
4028 x_display_pixel_height (struct ns_display_info *dpyinfo)
4029 {
4030 NSArray *screens = [NSScreen screens];
4031 NSEnumerator *enumerator = [screens objectEnumerator];
4032 NSScreen *screen;
4033 NSRect frame;
4034
4035 frame = NSZeroRect;
4036 while ((screen = [enumerator nextObject]) != nil)
4037 frame = NSUnionRect (frame, [screen frame]);
4038
4039 return NSHeight (frame);
4040 }
4041
4042 int
4043 x_display_pixel_width (struct ns_display_info *dpyinfo)
4044 {
4045 NSArray *screens = [NSScreen screens];
4046 NSEnumerator *enumerator = [screens objectEnumerator];
4047 NSScreen *screen;
4048 NSRect frame;
4049
4050 frame = NSZeroRect;
4051 while ((screen = [enumerator nextObject]) != nil)
4052 frame = NSUnionRect (frame, [screen frame]);
4053
4054 return NSWidth (frame);
4055 }
4056
4057
4058 static Lisp_Object ns_string_to_lispmod (const char *s)
4059 /* --------------------------------------------------------------------------
4060 Convert modifier name to lisp symbol
4061 -------------------------------------------------------------------------- */
4062 {
4063 if (!strncmp (SSDATA (SYMBOL_NAME (Qmeta)), s, 10))
4064 return Qmeta;
4065 else if (!strncmp (SSDATA (SYMBOL_NAME (Qsuper)), s, 10))
4066 return Qsuper;
4067 else if (!strncmp (SSDATA (SYMBOL_NAME (Qcontrol)), s, 10))
4068 return Qcontrol;
4069 else if (!strncmp (SSDATA (SYMBOL_NAME (Qalt)), s, 10))
4070 return Qalt;
4071 else if (!strncmp (SSDATA (SYMBOL_NAME (Qhyper)), s, 10))
4072 return Qhyper;
4073 else if (!strncmp (SSDATA (SYMBOL_NAME (Qnone)), s, 10))
4074 return Qnone;
4075 else
4076 return Qnil;
4077 }
4078
4079
4080 static void
4081 ns_default (const char *parameter, Lisp_Object *result,
4082 Lisp_Object yesval, Lisp_Object noval,
4083 BOOL is_float, BOOL is_modstring)
4084 /* --------------------------------------------------------------------------
4085 Check a parameter value in user's preferences
4086 -------------------------------------------------------------------------- */
4087 {
4088 const char *value = ns_get_defaults_value (parameter);
4089
4090 if (value)
4091 {
4092 double f;
4093 char *pos;
4094 if (c_strcasecmp (value, "YES") == 0)
4095 *result = yesval;
4096 else if (c_strcasecmp (value, "NO") == 0)
4097 *result = noval;
4098 else if (is_float && (f = strtod (value, &pos), pos != value))
4099 *result = make_float (f);
4100 else if (is_modstring && value)
4101 *result = ns_string_to_lispmod (value);
4102 else fprintf (stderr,
4103 "Bad value for default \"%s\": \"%s\"\n", parameter, value);
4104 }
4105 }
4106
4107
4108 static void
4109 ns_initialize_display_info (struct ns_display_info *dpyinfo)
4110 /* --------------------------------------------------------------------------
4111 Initialize global info and storage for display.
4112 -------------------------------------------------------------------------- */
4113 {
4114 NSScreen *screen = [NSScreen mainScreen];
4115 NSWindowDepth depth = [screen depth];
4116
4117 dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
4118 dpyinfo->resy = 72.27;
4119 dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
4120 NSColorSpaceFromDepth (depth)]
4121 && ![NSCalibratedWhiteColorSpace isEqualToString:
4122 NSColorSpaceFromDepth (depth)];
4123 dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
4124 dpyinfo->color_table = xmalloc (sizeof *dpyinfo->color_table);
4125 dpyinfo->color_table->colors = NULL;
4126 dpyinfo->root_window = 42; /* a placeholder.. */
4127 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
4128 dpyinfo->n_fonts = 0;
4129 dpyinfo->smallest_font_height = 1;
4130 dpyinfo->smallest_char_width = 1;
4131
4132 reset_mouse_highlight (&dpyinfo->mouse_highlight);
4133 }
4134
4135
4136 /* This and next define (many of the) public functions in this file. */
4137 /* x_... are generic versions in xdisp.c that we, and other terms, get away
4138 with using despite presence in the "system dependent" redisplay
4139 interface. In addition, many of the ns_ methods have code that is
4140 shared with all terms, indicating need for further refactoring. */
4141 extern frame_parm_handler ns_frame_parm_handlers[];
4142 static struct redisplay_interface ns_redisplay_interface =
4143 {
4144 ns_frame_parm_handlers,
4145 x_produce_glyphs,
4146 x_write_glyphs,
4147 x_insert_glyphs,
4148 x_clear_end_of_line,
4149 ns_scroll_run,
4150 ns_after_update_window_line,
4151 ns_update_window_begin,
4152 ns_update_window_end,
4153 0, /* flush_display */
4154 x_clear_window_mouse_face,
4155 x_get_glyph_overhangs,
4156 x_fix_overlapping_area,
4157 ns_draw_fringe_bitmap,
4158 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
4159 0, /* destroy_fringe_bitmap */
4160 ns_compute_glyph_string_overhangs,
4161 ns_draw_glyph_string,
4162 ns_define_frame_cursor,
4163 ns_clear_frame_area,
4164 ns_draw_window_cursor,
4165 ns_draw_vertical_window_border,
4166 ns_draw_window_divider,
4167 ns_shift_glyphs_for_insert,
4168 ns_show_hourglass,
4169 ns_hide_hourglass
4170 };
4171
4172
4173 static void
4174 ns_delete_display (struct ns_display_info *dpyinfo)
4175 {
4176 /* TODO... */
4177 }
4178
4179
4180 /* This function is called when the last frame on a display is deleted. */
4181 static void
4182 ns_delete_terminal (struct terminal *terminal)
4183 {
4184 struct ns_display_info *dpyinfo = terminal->display_info.ns;
4185
4186 /* Protect against recursive calls. delete_frame in
4187 delete_terminal calls us back when it deletes our last frame. */
4188 if (!terminal->name)
4189 return;
4190
4191 block_input ();
4192
4193 x_destroy_all_bitmaps (dpyinfo);
4194 ns_delete_display (dpyinfo);
4195 unblock_input ();
4196 }
4197
4198
4199 static struct terminal *
4200 ns_create_terminal (struct ns_display_info *dpyinfo)
4201 /* --------------------------------------------------------------------------
4202 Set up use of NS before we make the first connection.
4203 -------------------------------------------------------------------------- */
4204 {
4205 struct terminal *terminal;
4206
4207 NSTRACE (ns_create_terminal);
4208
4209 terminal = create_terminal (output_ns, &ns_redisplay_interface);
4210
4211 terminal->display_info.ns = dpyinfo;
4212 dpyinfo->terminal = terminal;
4213
4214 terminal->clear_frame_hook = ns_clear_frame;
4215 terminal->ring_bell_hook = ns_ring_bell;
4216 terminal->update_begin_hook = ns_update_begin;
4217 terminal->update_end_hook = ns_update_end;
4218 terminal->read_socket_hook = ns_read_socket;
4219 terminal->frame_up_to_date_hook = ns_frame_up_to_date;
4220 terminal->mouse_position_hook = ns_mouse_position;
4221 terminal->frame_rehighlight_hook = ns_frame_rehighlight;
4222 terminal->frame_raise_lower_hook = ns_frame_raise_lower;
4223 terminal->fullscreen_hook = ns_fullscreen_hook;
4224 terminal->menu_show_hook = ns_menu_show;
4225 terminal->popup_dialog_hook = ns_popup_dialog;
4226 terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
4227 terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
4228 terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
4229 terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
4230 terminal->delete_frame_hook = x_destroy_window;
4231 terminal->delete_terminal_hook = ns_delete_terminal;
4232 /* Other hooks are NULL by default. */
4233
4234 return terminal;
4235 }
4236
4237
4238 struct ns_display_info *
4239 ns_term_init (Lisp_Object display_name)
4240 /* --------------------------------------------------------------------------
4241 Start the Application and get things rolling.
4242 -------------------------------------------------------------------------- */
4243 {
4244 struct terminal *terminal;
4245 struct ns_display_info *dpyinfo;
4246 static int ns_initialized = 0;
4247 Lisp_Object tmp;
4248
4249 if (ns_initialized) return x_display_list;
4250 ns_initialized = 1;
4251
4252 NSTRACE (ns_term_init);
4253
4254 [outerpool release];
4255 outerpool = [[NSAutoreleasePool alloc] init];
4256
4257 /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4258 /*GSDebugAllocationActive (YES); */
4259 block_input ();
4260
4261 baud_rate = 38400;
4262 Fset_input_interrupt_mode (Qnil);
4263
4264 if (selfds[0] == -1)
4265 {
4266 if (emacs_pipe (selfds) != 0)
4267 {
4268 fprintf (stderr, "Failed to create pipe: %s\n",
4269 emacs_strerror (errno));
4270 emacs_abort ();
4271 }
4272
4273 fcntl (selfds[0], F_SETFL, O_NONBLOCK|fcntl (selfds[0], F_GETFL));
4274 FD_ZERO (&select_readfds);
4275 FD_ZERO (&select_writefds);
4276 pthread_mutex_init (&select_mutex, NULL);
4277 }
4278
4279 ns_pending_files = [[NSMutableArray alloc] init];
4280 ns_pending_service_names = [[NSMutableArray alloc] init];
4281 ns_pending_service_args = [[NSMutableArray alloc] init];
4282
4283 /* Start app and create the main menu, window, view.
4284 Needs to be here because ns_initialize_display_info () uses AppKit classes.
4285 The view will then ask the NSApp to stop and return to Emacs. */
4286 [EmacsApp sharedApplication];
4287 if (NSApp == nil)
4288 return NULL;
4289 [NSApp setDelegate: NSApp];
4290
4291 /* Start the select thread. */
4292 [NSThread detachNewThreadSelector:@selector (fd_handler:)
4293 toTarget:NSApp
4294 withObject:nil];
4295
4296 /* debugging: log all notifications */
4297 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
4298 selector: @selector (logNotification:)
4299 name: nil object: nil]; */
4300
4301 dpyinfo = xzalloc (sizeof *dpyinfo);
4302
4303 ns_initialize_display_info (dpyinfo);
4304 terminal = ns_create_terminal (dpyinfo);
4305
4306 terminal->kboard = allocate_kboard (Qns);
4307 /* Don't let the initial kboard remain current longer than necessary.
4308 That would cause problems if a file loaded on startup tries to
4309 prompt in the mini-buffer. */
4310 if (current_kboard == initial_kboard)
4311 current_kboard = terminal->kboard;
4312 terminal->kboard->reference_count++;
4313
4314 dpyinfo->next = x_display_list;
4315 x_display_list = dpyinfo;
4316
4317 dpyinfo->name_list_element = Fcons (display_name, Qnil);
4318
4319 terminal->name = xlispstrdup (display_name);
4320
4321 unblock_input ();
4322
4323 if (!inhibit_x_resources)
4324 {
4325 ns_default ("GSFontAntiAlias", &ns_antialias_text,
4326 Qt, Qnil, NO, NO);
4327 tmp = Qnil;
4328 /* this is a standard variable */
4329 ns_default ("AppleAntiAliasingThreshold", &tmp,
4330 make_float (10.0), make_float (6.0), YES, NO);
4331 ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
4332 }
4333
4334 {
4335 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
4336
4337 if ( cl == nil )
4338 {
4339 Lisp_Object color_file, color_map, color;
4340 unsigned long c;
4341 char *name;
4342
4343 color_file = Fexpand_file_name (build_string ("rgb.txt"),
4344 Fsymbol_value (intern ("data-directory")));
4345
4346 color_map = Fx_load_color_file (color_file);
4347 if (NILP (color_map))
4348 fatal ("Could not read %s.\n", SDATA (color_file));
4349
4350 cl = [[NSColorList alloc] initWithName: @"Emacs"];
4351 for ( ; CONSP (color_map); color_map = XCDR (color_map))
4352 {
4353 color = XCAR (color_map);
4354 name = SSDATA (XCAR (color));
4355 c = XINT (XCDR (color));
4356 [cl setColor:
4357 [NSColor colorForEmacsRed: RED_FROM_ULONG (c) / 255.0
4358 green: GREEN_FROM_ULONG (c) / 255.0
4359 blue: BLUE_FROM_ULONG (c) / 255.0
4360 alpha: 1.0]
4361 forKey: [NSString stringWithUTF8String: name]];
4362 }
4363 [cl writeToFile: nil];
4364 }
4365 }
4366
4367 {
4368 #ifdef NS_IMPL_GNUSTEP
4369 Vwindow_system_version = build_string (gnustep_base_version);
4370 #else
4371 /*PSnextrelease (128, c); */
4372 char c[DBL_BUFSIZE_BOUND];
4373 int len = dtoastr (c, sizeof c, 0, 0, NSAppKitVersionNumber);
4374 Vwindow_system_version = make_unibyte_string (c, len);
4375 #endif
4376 }
4377
4378 delete_keyboard_wait_descriptor (0);
4379
4380 ns_app_name = [[NSProcessInfo processInfo] processName];
4381
4382 /* Set up OS X app menu */
4383 #ifdef NS_IMPL_COCOA
4384 {
4385 NSMenu *appMenu;
4386 NSMenuItem *item;
4387 /* set up the application menu */
4388 svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
4389 [svcsMenu setAutoenablesItems: NO];
4390 appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
4391 [appMenu setAutoenablesItems: NO];
4392 mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4393 dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
4394
4395 [appMenu insertItemWithTitle: @"About Emacs"
4396 action: @selector (orderFrontStandardAboutPanel:)
4397 keyEquivalent: @""
4398 atIndex: 0];
4399 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
4400 [appMenu insertItemWithTitle: @"Preferences..."
4401 action: @selector (showPreferencesWindow:)
4402 keyEquivalent: @","
4403 atIndex: 2];
4404 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
4405 item = [appMenu insertItemWithTitle: @"Services"
4406 action: @selector (menuDown:)
4407 keyEquivalent: @""
4408 atIndex: 4];
4409 [appMenu setSubmenu: svcsMenu forItem: item];
4410 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
4411 [appMenu insertItemWithTitle: @"Hide Emacs"
4412 action: @selector (hide:)
4413 keyEquivalent: @"h"
4414 atIndex: 6];
4415 item = [appMenu insertItemWithTitle: @"Hide Others"
4416 action: @selector (hideOtherApplications:)
4417 keyEquivalent: @"h"
4418 atIndex: 7];
4419 [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
4420 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
4421 [appMenu insertItemWithTitle: @"Quit Emacs"
4422 action: @selector (terminate:)
4423 keyEquivalent: @"q"
4424 atIndex: 9];
4425
4426 item = [mainMenu insertItemWithTitle: ns_app_name
4427 action: @selector (menuDown:)
4428 keyEquivalent: @""
4429 atIndex: 0];
4430 [mainMenu setSubmenu: appMenu forItem: item];
4431 [dockMenu insertItemWithTitle: @"New Frame"
4432 action: @selector (newFrame:)
4433 keyEquivalent: @""
4434 atIndex: 0];
4435
4436 [NSApp setMainMenu: mainMenu];
4437 [NSApp setAppleMenu: appMenu];
4438 [NSApp setServicesMenu: svcsMenu];
4439 /* Needed at least on Cocoa, to get dock menu to show windows */
4440 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
4441
4442 [[NSNotificationCenter defaultCenter]
4443 addObserver: mainMenu
4444 selector: @selector (trackingNotification:)
4445 name: NSMenuDidBeginTrackingNotification object: mainMenu];
4446 [[NSNotificationCenter defaultCenter]
4447 addObserver: mainMenu
4448 selector: @selector (trackingNotification:)
4449 name: NSMenuDidEndTrackingNotification object: mainMenu];
4450 }
4451 #endif /* MAC OS X menu setup */
4452
4453 /* Register our external input/output types, used for determining
4454 applicable services and also drag/drop eligibility. */
4455 ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
4456 ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
4457 retain];
4458 ns_drag_types = [[NSArray arrayWithObjects:
4459 NSStringPboardType,
4460 NSTabularTextPboardType,
4461 NSFilenamesPboardType,
4462 NSURLPboardType, nil] retain];
4463
4464 /* If fullscreen is in init/default-frame-alist, focus isn't set
4465 right for fullscreen windows, so set this. */
4466 [NSApp activateIgnoringOtherApps:YES];
4467
4468 [NSApp run];
4469 ns_do_open_file = YES;
4470
4471 #ifdef NS_IMPL_GNUSTEP
4472 /* GNUstep steals SIGCHLD for use in NSTask, but we don't use NSTask.
4473 We must re-catch it so subprocess works. */
4474 catch_child_signal ();
4475 #endif
4476 return dpyinfo;
4477 }
4478
4479
4480 void
4481 ns_term_shutdown (int sig)
4482 {
4483 [[NSUserDefaults standardUserDefaults] synchronize];
4484
4485 /* code not reached in emacs.c after this is called by shut_down_emacs: */
4486 if (STRINGP (Vauto_save_list_file_name))
4487 unlink (SSDATA (Vauto_save_list_file_name));
4488
4489 if (sig == 0 || sig == SIGTERM)
4490 {
4491 [NSApp terminate: NSApp];
4492 }
4493 else // force a stack trace to happen
4494 {
4495 emacs_abort ();
4496 }
4497 }
4498
4499
4500 /* ==========================================================================
4501
4502 EmacsApp implementation
4503
4504 ========================================================================== */
4505
4506
4507 @implementation EmacsApp
4508
4509 - (id)init
4510 {
4511 if (self = [super init])
4512 {
4513 #ifdef NS_IMPL_COCOA
4514 self->isFirst = YES;
4515 #endif
4516 #ifdef NS_IMPL_GNUSTEP
4517 self->applicationDidFinishLaunchingCalled = NO;
4518 #endif
4519 }
4520
4521 return self;
4522 }
4523
4524 #ifdef NS_IMPL_COCOA
4525 - (void)run
4526 {
4527 #ifndef NSAppKitVersionNumber10_9
4528 #define NSAppKitVersionNumber10_9 1265
4529 #endif
4530
4531 if ((int)NSAppKitVersionNumber != NSAppKitVersionNumber10_9)
4532 {
4533 [super run];
4534 return;
4535 }
4536
4537 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
4538
4539 if (isFirst) [self finishLaunching];
4540 isFirst = NO;
4541
4542 shouldKeepRunning = YES;
4543 do
4544 {
4545 [pool release];
4546 pool = [[NSAutoreleasePool alloc] init];
4547
4548 NSEvent *event =
4549 [self nextEventMatchingMask:NSAnyEventMask
4550 untilDate:[NSDate distantFuture]
4551 inMode:NSDefaultRunLoopMode
4552 dequeue:YES];
4553
4554 [self sendEvent:event];
4555 [self updateWindows];
4556 } while (shouldKeepRunning);
4557
4558 [pool release];
4559 }
4560
4561 - (void)stop: (id)sender
4562 {
4563 shouldKeepRunning = NO;
4564 // Stop possible dialog also. Noop if no dialog present.
4565 // The file dialog still leaks 7k - 10k on 10.9 though.
4566 [super stop:sender];
4567 }
4568 #endif /* NS_IMPL_COCOA */
4569
4570 - (void)logNotification: (NSNotification *)notification
4571 {
4572 const char *name = [[notification name] UTF8String];
4573 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4574 && !strstr (name, "WindowNumber"))
4575 NSLog (@"notification: '%@'", [notification name]);
4576 }
4577
4578
4579 - (void)sendEvent: (NSEvent *)theEvent
4580 /* --------------------------------------------------------------------------
4581 Called when NSApp is running for each event received. Used to stop
4582 the loop when we choose, since there's no way to just run one iteration.
4583 -------------------------------------------------------------------------- */
4584 {
4585 int type = [theEvent type];
4586 NSWindow *window = [theEvent window];
4587
4588 /* NSTRACE (sendEvent); */
4589 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4590
4591 #ifdef NS_IMPL_GNUSTEP
4592 // Keyboard events aren't propagated to file dialogs for some reason.
4593 if ([NSApp modalWindow] != nil &&
4594 (type == NSKeyDown || type == NSKeyUp || type == NSFlagsChanged))
4595 {
4596 [[NSApp modalWindow] sendEvent: theEvent];
4597 return;
4598 }
4599 #endif
4600
4601 if (represented_filename != nil && represented_frame)
4602 {
4603 NSString *fstr = represented_filename;
4604 NSView *view = FRAME_NS_VIEW (represented_frame);
4605 #ifdef NS_IMPL_COCOA
4606 /* work around a bug observed on 10.3 and later where
4607 setTitleWithRepresentedFilename does not clear out previous state
4608 if given filename does not exist */
4609 if (! [[NSFileManager defaultManager] fileExistsAtPath: fstr])
4610 [[view window] setRepresentedFilename: @""];
4611 #endif
4612 [[view window] setRepresentedFilename: fstr];
4613 [represented_filename release];
4614 represented_filename = nil;
4615 represented_frame = NULL;
4616 }
4617
4618 if (type == NSApplicationDefined)
4619 {
4620 switch ([theEvent data2])
4621 {
4622 #ifdef NS_IMPL_COCOA
4623 case NSAPP_DATA2_RUNASSCRIPT:
4624 ns_run_ascript ();
4625 [self stop: self];
4626 return;
4627 #endif
4628 case NSAPP_DATA2_RUNFILEDIALOG:
4629 ns_run_file_dialog ();
4630 [self stop: self];
4631 return;
4632 }
4633 }
4634
4635 if (type == NSCursorUpdate && window == nil)
4636 {
4637 fprintf (stderr, "Dropping external cursor update event.\n");
4638 return;
4639 }
4640
4641 if (type == NSApplicationDefined)
4642 {
4643 /* Events posted by ns_send_appdefined interrupt the run loop here.
4644 But, if a modal window is up, an appdefined can still come through,
4645 (e.g., from a makeKeyWindow event) but stopping self also stops the
4646 modal loop. Just defer it until later. */
4647 if ([NSApp modalWindow] == nil)
4648 {
4649 last_appdefined_event_data = [theEvent data1];
4650 [self stop: self];
4651 }
4652 else
4653 {
4654 send_appdefined = YES;
4655 }
4656 }
4657
4658
4659 #ifdef NS_IMPL_COCOA
4660 /* If no dialog and none of our frames have focus and it is a move, skip it.
4661 It is a mouse move in an auxiliary menu, i.e. on the top right on OSX,
4662 such as Wifi, sound, date or similar.
4663 This prevents "spooky" highlighting in the frame under the menu. */
4664 if (type == NSMouseMoved && [NSApp modalWindow] == nil)
4665 {
4666 struct ns_display_info *di;
4667 BOOL has_focus = NO;
4668 for (di = x_display_list; ! has_focus && di; di = di->next)
4669 has_focus = di->x_focus_frame != 0;
4670 if (! has_focus)
4671 return;
4672 }
4673 #endif
4674
4675 [super sendEvent: theEvent];
4676 }
4677
4678
4679 - (void)showPreferencesWindow: (id)sender
4680 {
4681 struct frame *emacsframe = SELECTED_FRAME ();
4682 NSEvent *theEvent = [NSApp currentEvent];
4683
4684 if (!emacs_event)
4685 return;
4686 emacs_event->kind = NS_NONKEY_EVENT;
4687 emacs_event->code = KEY_NS_SHOW_PREFS;
4688 emacs_event->modifiers = 0;
4689 EV_TRAILER (theEvent);
4690 }
4691
4692
4693 - (void)newFrame: (id)sender
4694 {
4695 struct frame *emacsframe = SELECTED_FRAME ();
4696 NSEvent *theEvent = [NSApp currentEvent];
4697
4698 if (!emacs_event)
4699 return;
4700 emacs_event->kind = NS_NONKEY_EVENT;
4701 emacs_event->code = KEY_NS_NEW_FRAME;
4702 emacs_event->modifiers = 0;
4703 EV_TRAILER (theEvent);
4704 }
4705
4706
4707 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4708 - (BOOL) openFile: (NSString *)fileName
4709 {
4710 struct frame *emacsframe = SELECTED_FRAME ();
4711 NSEvent *theEvent = [NSApp currentEvent];
4712
4713 if (!emacs_event)
4714 return NO;
4715
4716 emacs_event->kind = NS_NONKEY_EVENT;
4717 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4718 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4719 ns_input_line = Qnil; /* can be start or cons start,end */
4720 emacs_event->modifiers =0;
4721 EV_TRAILER (theEvent);
4722
4723 return YES;
4724 }
4725
4726
4727 /* **************************************************************************
4728
4729 EmacsApp delegate implementation
4730
4731 ************************************************************************** */
4732
4733 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4734 /* --------------------------------------------------------------------------
4735 When application is loaded, terminate event loop in ns_term_init
4736 -------------------------------------------------------------------------- */
4737 {
4738 NSTRACE (applicationDidFinishLaunching);
4739 #ifdef NS_IMPL_GNUSTEP
4740 ((EmacsApp *)self)->applicationDidFinishLaunchingCalled = YES;
4741 #endif
4742 [NSApp setServicesProvider: NSApp];
4743
4744 [self antialiasThresholdDidChange:nil];
4745 #ifdef NS_IMPL_COCOA
4746 [[NSNotificationCenter defaultCenter]
4747 addObserver:self
4748 selector:@selector(antialiasThresholdDidChange:)
4749 name:NSAntialiasThresholdChangedNotification
4750 object:nil];
4751 #endif
4752
4753 ns_send_appdefined (-2);
4754 }
4755
4756 - (void)antialiasThresholdDidChange:(NSNotification *)notification
4757 {
4758 #ifdef NS_IMPL_COCOA
4759 macfont_update_antialias_threshold ();
4760 #endif
4761 }
4762
4763
4764 /* Termination sequences:
4765 C-x C-c:
4766 Cmd-Q:
4767 MenuBar | File | Exit:
4768 Select Quit from App menubar:
4769 -terminate
4770 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4771 ns_term_shutdown()
4772
4773 Select Quit from Dock menu:
4774 Logout attempt:
4775 -appShouldTerminate
4776 Cancel -> Nothing else
4777 Accept ->
4778
4779 -terminate
4780 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4781 ns_term_shutdown()
4782
4783 */
4784
4785 - (void) terminate: (id)sender
4786 {
4787 struct frame *emacsframe = SELECTED_FRAME ();
4788
4789 if (!emacs_event)
4790 return;
4791
4792 emacs_event->kind = NS_NONKEY_EVENT;
4793 emacs_event->code = KEY_NS_POWER_OFF;
4794 emacs_event->arg = Qt; /* mark as non-key event */
4795 EV_TRAILER ((id)nil);
4796 }
4797
4798
4799 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4800 {
4801 int ret;
4802
4803 if (NILP (ns_confirm_quit)) // || ns_shutdown_properly --> TO DO
4804 return NSTerminateNow;
4805
4806 ret = NSRunAlertPanel(ns_app_name,
4807 @"Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?",
4808 @"Save Buffers and Exit", @"Cancel", nil);
4809
4810 if (ret == NSAlertDefaultReturn)
4811 return NSTerminateNow;
4812 else if (ret == NSAlertAlternateReturn)
4813 return NSTerminateCancel;
4814 return NSTerminateNow; /* just in case */
4815 }
4816
4817 static int
4818 not_in_argv (NSString *arg)
4819 {
4820 int k;
4821 const char *a = [arg UTF8String];
4822 for (k = 1; k < initial_argc; ++k)
4823 if (strcmp (a, initial_argv[k]) == 0) return 0;
4824 return 1;
4825 }
4826
4827 /* Notification from the Workspace to open a file */
4828 - (BOOL)application: sender openFile: (NSString *)file
4829 {
4830 if (ns_do_open_file || not_in_argv (file))
4831 [ns_pending_files addObject: file];
4832 return YES;
4833 }
4834
4835
4836 /* Open a file as a temporary file */
4837 - (BOOL)application: sender openTempFile: (NSString *)file
4838 {
4839 if (ns_do_open_file || not_in_argv (file))
4840 [ns_pending_files addObject: file];
4841 return YES;
4842 }
4843
4844
4845 /* Notification from the Workspace to open a file noninteractively (?) */
4846 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4847 {
4848 if (ns_do_open_file || not_in_argv (file))
4849 [ns_pending_files addObject: file];
4850 return YES;
4851 }
4852
4853 /* Notification from the Workspace to open multiple files */
4854 - (void)application: sender openFiles: (NSArray *)fileList
4855 {
4856 NSEnumerator *files = [fileList objectEnumerator];
4857 NSString *file;
4858 /* Don't open files from the command line unconditionally,
4859 Cocoa parses the command line wrong, --option value tries to open value
4860 if --option is the last option. */
4861 while ((file = [files nextObject]) != nil)
4862 if (ns_do_open_file || not_in_argv (file))
4863 [ns_pending_files addObject: file];
4864
4865 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4866
4867 }
4868
4869
4870 /* Handle dock menu requests. */
4871 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4872 {
4873 return dockMenu;
4874 }
4875
4876
4877 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4878 - (void)applicationWillBecomeActive: (NSNotification *)notification
4879 {
4880 //ns_app_active=YES;
4881 }
4882 - (void)applicationDidBecomeActive: (NSNotification *)notification
4883 {
4884 NSTRACE (applicationDidBecomeActive);
4885
4886 #ifdef NS_IMPL_GNUSTEP
4887 if (! applicationDidFinishLaunchingCalled)
4888 [self applicationDidFinishLaunching:notification];
4889 #endif
4890 //ns_app_active=YES;
4891
4892 ns_update_auto_hide_menu_bar ();
4893 // No constraining takes place when the application is not active.
4894 ns_constrain_all_frames ();
4895 }
4896 - (void)applicationDidResignActive: (NSNotification *)notification
4897 {
4898 //ns_app_active=NO;
4899 ns_send_appdefined (-1);
4900 }
4901
4902
4903
4904 /* ==========================================================================
4905
4906 EmacsApp aux handlers for managing event loop
4907
4908 ========================================================================== */
4909
4910
4911 - (void)timeout_handler: (NSTimer *)timedEntry
4912 /* --------------------------------------------------------------------------
4913 The timeout specified to ns_select has passed.
4914 -------------------------------------------------------------------------- */
4915 {
4916 /*NSTRACE (timeout_handler); */
4917 ns_send_appdefined (-2);
4918 }
4919
4920 #ifdef NS_IMPL_GNUSTEP
4921 - (void)sendFromMainThread:(id)unused
4922 {
4923 ns_send_appdefined (nextappdefined);
4924 }
4925 #endif
4926
4927 - (void)fd_handler:(id)unused
4928 /* --------------------------------------------------------------------------
4929 Check data waiting on file descriptors and terminate if so
4930 -------------------------------------------------------------------------- */
4931 {
4932 int result;
4933 int waiting = 1, nfds;
4934 char c;
4935
4936 fd_set readfds, writefds, *wfds;
4937 struct timespec timeout, *tmo;
4938 NSAutoreleasePool *pool = nil;
4939
4940 /* NSTRACE (fd_handler); */
4941
4942 for (;;)
4943 {
4944 [pool release];
4945 pool = [[NSAutoreleasePool alloc] init];
4946
4947 if (waiting)
4948 {
4949 fd_set fds;
4950 FD_ZERO (&fds);
4951 FD_SET (selfds[0], &fds);
4952 result = select (selfds[0]+1, &fds, NULL, NULL, NULL);
4953 if (result > 0 && read (selfds[0], &c, 1) == 1 && c == 'g')
4954 waiting = 0;
4955 }
4956 else
4957 {
4958 pthread_mutex_lock (&select_mutex);
4959 nfds = select_nfds;
4960
4961 if (select_valid & SELECT_HAVE_READ)
4962 readfds = select_readfds;
4963 else
4964 FD_ZERO (&readfds);
4965
4966 if (select_valid & SELECT_HAVE_WRITE)
4967 {
4968 writefds = select_writefds;
4969 wfds = &writefds;
4970 }
4971 else
4972 wfds = NULL;
4973 if (select_valid & SELECT_HAVE_TMO)
4974 {
4975 timeout = select_timeout;
4976 tmo = &timeout;
4977 }
4978 else
4979 tmo = NULL;
4980
4981 pthread_mutex_unlock (&select_mutex);
4982
4983 FD_SET (selfds[0], &readfds);
4984 if (selfds[0] >= nfds) nfds = selfds[0]+1;
4985
4986 result = pselect (nfds, &readfds, wfds, NULL, tmo, NULL);
4987
4988 if (result == 0)
4989 ns_send_appdefined (-2);
4990 else if (result > 0)
4991 {
4992 if (FD_ISSET (selfds[0], &readfds))
4993 {
4994 if (read (selfds[0], &c, 1) == 1 && c == 's')
4995 waiting = 1;
4996 }
4997 else
4998 {
4999 pthread_mutex_lock (&select_mutex);
5000 if (select_valid & SELECT_HAVE_READ)
5001 select_readfds = readfds;
5002 if (select_valid & SELECT_HAVE_WRITE)
5003 select_writefds = writefds;
5004 if (select_valid & SELECT_HAVE_TMO)
5005 select_timeout = timeout;
5006 pthread_mutex_unlock (&select_mutex);
5007
5008 ns_send_appdefined (result);
5009 }
5010 }
5011 waiting = 1;
5012 }
5013 }
5014 }
5015
5016
5017
5018 /* ==========================================================================
5019
5020 Service provision
5021
5022 ========================================================================== */
5023
5024 /* called from system: queue for next pass through event loop */
5025 - (void)requestService: (NSPasteboard *)pboard
5026 userData: (NSString *)userData
5027 error: (NSString **)error
5028 {
5029 [ns_pending_service_names addObject: userData];
5030 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
5031 SSDATA (ns_string_from_pasteboard (pboard))]];
5032 }
5033
5034
5035 /* called from ns_read_socket to clear queue */
5036 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
5037 {
5038 struct frame *emacsframe = SELECTED_FRAME ();
5039 NSEvent *theEvent = [NSApp currentEvent];
5040
5041 if (!emacs_event)
5042 return NO;
5043
5044 emacs_event->kind = NS_NONKEY_EVENT;
5045 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
5046 ns_input_spi_name = build_string ([name UTF8String]);
5047 ns_input_spi_arg = build_string ([arg UTF8String]);
5048 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5049 EV_TRAILER (theEvent);
5050
5051 return YES;
5052 }
5053
5054
5055 @end /* EmacsApp */
5056
5057
5058
5059 /* ==========================================================================
5060
5061 EmacsView implementation
5062
5063 ========================================================================== */
5064
5065
5066 @implementation EmacsView
5067
5068 /* needed to inform when window closed from LISP */
5069 - (void) setWindowClosing: (BOOL)closing
5070 {
5071 windowClosing = closing;
5072 }
5073
5074
5075 - (void)dealloc
5076 {
5077 NSTRACE (EmacsView_dealloc);
5078 [toolbar release];
5079 if (fs_state == FULLSCREEN_BOTH)
5080 [nonfs_window release];
5081 [super dealloc];
5082 }
5083
5084
5085 /* called on font panel selection */
5086 - (void)changeFont: (id)sender
5087 {
5088 NSEvent *e = [[self window] currentEvent];
5089 struct face *face = FRAME_DEFAULT_FACE (emacsframe);
5090 struct font *font = face->font;
5091 id newFont;
5092 CGFloat size;
5093 NSFont *nsfont;
5094
5095 NSTRACE (changeFont);
5096
5097 if (!emacs_event)
5098 return;
5099
5100 #ifdef NS_IMPL_GNUSTEP
5101 nsfont = ((struct nsfont_info *)font)->nsfont;
5102 #endif
5103 #ifdef NS_IMPL_COCOA
5104 nsfont = (NSFont *) macfont_get_nsctfont (font);
5105 #endif
5106
5107 if ((newFont = [sender convertFont: nsfont]))
5108 {
5109 SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
5110
5111 emacs_event->kind = NS_NONKEY_EVENT;
5112 emacs_event->modifiers = 0;
5113 emacs_event->code = KEY_NS_CHANGE_FONT;
5114
5115 size = [newFont pointSize];
5116 ns_input_fontsize = make_number (lrint (size));
5117 ns_input_font = build_string ([[newFont familyName] UTF8String]);
5118 EV_TRAILER (e);
5119 }
5120 }
5121
5122
5123 - (BOOL)acceptsFirstResponder
5124 {
5125 NSTRACE (acceptsFirstResponder);
5126 return YES;
5127 }
5128
5129
5130 - (void)resetCursorRects
5131 {
5132 NSRect visible = [self visibleRect];
5133 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
5134 NSTRACE (resetCursorRects);
5135
5136 if (currentCursor == nil)
5137 currentCursor = [NSCursor arrowCursor];
5138
5139 if (!NSIsEmptyRect (visible))
5140 [self addCursorRect: visible cursor: currentCursor];
5141 [currentCursor setOnMouseEntered: YES];
5142 }
5143
5144
5145
5146 /*****************************************************************************/
5147 /* Keyboard handling. */
5148 #define NS_KEYLOG 0
5149
5150 - (void)keyDown: (NSEvent *)theEvent
5151 {
5152 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5153 int code;
5154 unsigned fnKeysym = 0;
5155 static NSMutableArray *nsEvArray;
5156 #ifdef NS_IMPL_GNUSTEP
5157 static BOOL firstTime = YES;
5158 #endif
5159 int left_is_none;
5160 unsigned int flags = [theEvent modifierFlags];
5161
5162 NSTRACE (keyDown);
5163
5164 /* Rhapsody and OS X give up and down events for the arrow keys */
5165 if (ns_fake_keydown == YES)
5166 ns_fake_keydown = NO;
5167 else if ([theEvent type] != NSKeyDown)
5168 return;
5169
5170 if (!emacs_event)
5171 return;
5172
5173 if (![[self window] isKeyWindow]
5174 && [[theEvent window] isKindOfClass: [EmacsWindow class]]
5175 /* we must avoid an infinite loop here. */
5176 && (EmacsView *)[[theEvent window] delegate] != self)
5177 {
5178 /* XXX: There is an occasional condition in which, when Emacs display
5179 updates a different frame from the current one, and temporarily
5180 selects it, then processes some interrupt-driven input
5181 (dispnew.c:3878), OS will send the event to the correct NSWindow, but
5182 for some reason that window has its first responder set to the NSView
5183 most recently updated (I guess), which is not the correct one. */
5184 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
5185 return;
5186 }
5187
5188 if (nsEvArray == nil)
5189 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
5190
5191 [NSCursor setHiddenUntilMouseMoves: YES];
5192
5193 if (hlinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
5194 {
5195 clear_mouse_face (hlinfo);
5196 hlinfo->mouse_face_hidden = 1;
5197 }
5198
5199 if (!processingCompose)
5200 {
5201 /* When using screen sharing, no left or right information is sent,
5202 so use Left key in those cases. */
5203 int is_left_key, is_right_key;
5204
5205 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
5206 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
5207
5208 /* (Carbon way: [theEvent keyCode]) */
5209
5210 /* is it a "function key"? */
5211 /* Note: Sometimes a plain key will have the NSNumericPadKeyMask
5212 flag set (this is probably a bug in the OS).
5213 */
5214 if (code < 0x00ff && (flags&NSNumericPadKeyMask))
5215 {
5216 fnKeysym = ns_convert_key ([theEvent keyCode] | NSNumericPadKeyMask);
5217 }
5218 if (fnKeysym == 0)
5219 {
5220 fnKeysym = ns_convert_key (code);
5221 }
5222
5223 if (fnKeysym)
5224 {
5225 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
5226 because Emacs treats Delete and KP-Delete same (in simple.el). */
5227 if ((fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
5228 #ifdef NS_IMPL_GNUSTEP
5229 /* GNUstep uses incompatible keycodes, even for those that are
5230 supposed to be hardware independent. Just check for delete.
5231 Keypad delete does not have keysym 0xFFFF.
5232 See http://savannah.gnu.org/bugs/?25395
5233 */
5234 || (fnKeysym == 0xFFFF && code == 127)
5235 #endif
5236 )
5237 code = 0xFF08; /* backspace */
5238 else
5239 code = fnKeysym;
5240 }
5241
5242 /* are there modifiers? */
5243 emacs_event->modifiers = 0;
5244
5245 if (flags & NSHelpKeyMask)
5246 emacs_event->modifiers |= hyper_modifier;
5247
5248 if (flags & NSShiftKeyMask)
5249 emacs_event->modifiers |= shift_modifier;
5250
5251 is_right_key = (flags & NSRightCommandKeyMask) == NSRightCommandKeyMask;
5252 is_left_key = (flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask
5253 || (! is_right_key && (flags & NSCommandKeyMask) == NSCommandKeyMask);
5254
5255 if (is_right_key)
5256 emacs_event->modifiers |= parse_solitary_modifier
5257 (EQ (ns_right_command_modifier, Qleft)
5258 ? ns_command_modifier
5259 : ns_right_command_modifier);
5260
5261 if (is_left_key)
5262 {
5263 emacs_event->modifiers |= parse_solitary_modifier
5264 (ns_command_modifier);
5265
5266 /* if super (default), take input manager's word so things like
5267 dvorak / qwerty layout work */
5268 if (EQ (ns_command_modifier, Qsuper)
5269 && !fnKeysym
5270 && [[theEvent characters] length] != 0)
5271 {
5272 /* XXX: the code we get will be unshifted, so if we have
5273 a shift modifier, must convert ourselves */
5274 if (!(flags & NSShiftKeyMask))
5275 code = [[theEvent characters] characterAtIndex: 0];
5276 #if 0
5277 /* this is ugly and also requires linking w/Carbon framework
5278 (for LMGetKbdType) so for now leave this rare (?) case
5279 undealt with.. in future look into CGEvent methods */
5280 else
5281 {
5282 long smv = GetScriptManagerVariable (smKeyScript);
5283 Handle uchrHandle = GetResource
5284 ('uchr', GetScriptVariable (smv, smScriptKeys));
5285 UInt32 dummy = 0;
5286 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
5287 [[theEvent characters] characterAtIndex: 0],
5288 kUCKeyActionDisplay,
5289 (flags & ~NSCommandKeyMask) >> 8,
5290 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
5291 &dummy, 1, &dummy, &code);
5292 code &= 0xFF;
5293 }
5294 #endif
5295 }
5296 }
5297
5298 is_right_key = (flags & NSRightControlKeyMask) == NSRightControlKeyMask;
5299 is_left_key = (flags & NSLeftControlKeyMask) == NSLeftControlKeyMask
5300 || (! is_right_key && (flags & NSControlKeyMask) == NSControlKeyMask);
5301
5302 if (is_right_key)
5303 emacs_event->modifiers |= parse_solitary_modifier
5304 (EQ (ns_right_control_modifier, Qleft)
5305 ? ns_control_modifier
5306 : ns_right_control_modifier);
5307
5308 if (is_left_key)
5309 emacs_event->modifiers |= parse_solitary_modifier
5310 (ns_control_modifier);
5311
5312 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
5313 emacs_event->modifiers |=
5314 parse_solitary_modifier (ns_function_modifier);
5315
5316 left_is_none = NILP (ns_alternate_modifier)
5317 || EQ (ns_alternate_modifier, Qnone);
5318
5319 is_right_key = (flags & NSRightAlternateKeyMask)
5320 == NSRightAlternateKeyMask;
5321 is_left_key = (flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask
5322 || (! is_right_key
5323 && (flags & NSAlternateKeyMask) == NSAlternateKeyMask);
5324
5325 if (is_right_key)
5326 {
5327 if ((NILP (ns_right_alternate_modifier)
5328 || EQ (ns_right_alternate_modifier, Qnone)
5329 || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
5330 && !fnKeysym)
5331 { /* accept pre-interp alt comb */
5332 if ([[theEvent characters] length] > 0)
5333 code = [[theEvent characters] characterAtIndex: 0];
5334 /*HACK: clear lone shift modifier to stop next if from firing */
5335 if (emacs_event->modifiers == shift_modifier)
5336 emacs_event->modifiers = 0;
5337 }
5338 else
5339 emacs_event->modifiers |= parse_solitary_modifier
5340 (EQ (ns_right_alternate_modifier, Qleft)
5341 ? ns_alternate_modifier
5342 : ns_right_alternate_modifier);
5343 }
5344
5345 if (is_left_key) /* default = meta */
5346 {
5347 if (left_is_none && !fnKeysym)
5348 { /* accept pre-interp alt comb */
5349 if ([[theEvent characters] length] > 0)
5350 code = [[theEvent characters] characterAtIndex: 0];
5351 /*HACK: clear lone shift modifier to stop next if from firing */
5352 if (emacs_event->modifiers == shift_modifier)
5353 emacs_event->modifiers = 0;
5354 }
5355 else
5356 emacs_event->modifiers |=
5357 parse_solitary_modifier (ns_alternate_modifier);
5358 }
5359
5360 if (NS_KEYLOG)
5361 fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
5362 code, fnKeysym, flags, emacs_event->modifiers);
5363
5364 /* if it was a function key or had modifiers, pass it directly to emacs */
5365 if (fnKeysym || (emacs_event->modifiers
5366 && (emacs_event->modifiers != shift_modifier)
5367 && [[theEvent charactersIgnoringModifiers] length] > 0))
5368 /*[[theEvent characters] length] */
5369 {
5370 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5371 if (code < 0x20)
5372 code |= (1<<28)|(3<<16);
5373 else if (code == 0x7f)
5374 code |= (1<<28)|(3<<16);
5375 else if (!fnKeysym)
5376 emacs_event->kind = code > 0xFF
5377 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5378
5379 emacs_event->code = code;
5380 EV_TRAILER (theEvent);
5381 processingCompose = NO;
5382 return;
5383 }
5384 }
5385
5386
5387 #ifdef NS_IMPL_GNUSTEP
5388 /* if we get here we should send the key for input manager processing */
5389 /* Disable warning, there is nothing a user can do about it anyway, and
5390 it does not seem to matter. */
5391 #if 0
5392 if (firstTime && [[NSInputManager currentInputManager]
5393 wantsToDelayTextChangeNotifications] == NO)
5394 fprintf (stderr,
5395 "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
5396 #endif
5397 firstTime = NO;
5398 #endif
5399 if (NS_KEYLOG && !processingCompose)
5400 fprintf (stderr, "keyDown: Begin compose sequence.\n");
5401
5402 processingCompose = YES;
5403 [nsEvArray addObject: theEvent];
5404 [self interpretKeyEvents: nsEvArray];
5405 [nsEvArray removeObject: theEvent];
5406 }
5407
5408
5409 #ifdef NS_IMPL_COCOA
5410 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
5411 decided not to send key-down for.
5412 See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
5413 This only applies on Tiger and earlier.
5414 If it matches one of these, send it on to keyDown. */
5415 -(void)keyUp: (NSEvent *)theEvent
5416 {
5417 int flags = [theEvent modifierFlags];
5418 int code = [theEvent keyCode];
5419 if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
5420 code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
5421 {
5422 if (NS_KEYLOG)
5423 fprintf (stderr, "keyUp: passed test");
5424 ns_fake_keydown = YES;
5425 [self keyDown: theEvent];
5426 }
5427 }
5428 #endif
5429
5430
5431 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
5432
5433
5434 /* <NSTextInput>: called when done composing;
5435 NOTE: also called when we delete over working text, followed immed.
5436 by doCommandBySelector: deleteBackward: */
5437 - (void)insertText: (id)aString
5438 {
5439 int code;
5440 int len = [(NSString *)aString length];
5441 int i;
5442
5443 if (NS_KEYLOG)
5444 NSLog (@"insertText '%@'\tlen = %d", aString, len);
5445 processingCompose = NO;
5446
5447 if (!emacs_event)
5448 return;
5449
5450 /* first, clear any working text */
5451 if (workingText != nil)
5452 [self deleteWorkingText];
5453
5454 /* now insert the string as keystrokes */
5455 for (i =0; i<len; i++)
5456 {
5457 code = [aString characterAtIndex: i];
5458 /* TODO: still need this? */
5459 if (code == 0x2DC)
5460 code = '~'; /* 0x7E */
5461 if (code != 32) /* Space */
5462 emacs_event->modifiers = 0;
5463 emacs_event->kind
5464 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
5465 emacs_event->code = code;
5466 EV_TRAILER ((id)nil);
5467 }
5468 }
5469
5470
5471 /* <NSTextInput>: inserts display of composing characters */
5472 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
5473 {
5474 NSString *str = [aString respondsToSelector: @selector (string)] ?
5475 [aString string] : aString;
5476 if (NS_KEYLOG)
5477 NSLog (@"setMarkedText '%@' len =%lu range %lu from %lu",
5478 str, (unsigned long)[str length],
5479 (unsigned long)selRange.length,
5480 (unsigned long)selRange.location);
5481
5482 if (workingText != nil)
5483 [self deleteWorkingText];
5484 if ([str length] == 0)
5485 return;
5486
5487 if (!emacs_event)
5488 return;
5489
5490 processingCompose = YES;
5491 workingText = [str copy];
5492 ns_working_text = build_string ([workingText UTF8String]);
5493
5494 emacs_event->kind = NS_TEXT_EVENT;
5495 emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
5496 EV_TRAILER ((id)nil);
5497 }
5498
5499
5500 /* delete display of composing characters [not in <NSTextInput>] */
5501 - (void)deleteWorkingText
5502 {
5503 if (workingText == nil)
5504 return;
5505 if (NS_KEYLOG)
5506 NSLog(@"deleteWorkingText len =%lu\n", (unsigned long)[workingText length]);
5507 [workingText release];
5508 workingText = nil;
5509 processingCompose = NO;
5510
5511 if (!emacs_event)
5512 return;
5513
5514 emacs_event->kind = NS_TEXT_EVENT;
5515 emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
5516 EV_TRAILER ((id)nil);
5517 }
5518
5519
5520 - (BOOL)hasMarkedText
5521 {
5522 return workingText != nil;
5523 }
5524
5525
5526 - (NSRange)markedRange
5527 {
5528 NSRange rng = workingText != nil
5529 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
5530 if (NS_KEYLOG)
5531 NSLog (@"markedRange request");
5532 return rng;
5533 }
5534
5535
5536 - (void)unmarkText
5537 {
5538 if (NS_KEYLOG)
5539 NSLog (@"unmark (accept) text");
5540 [self deleteWorkingText];
5541 processingCompose = NO;
5542 }
5543
5544
5545 /* used to position char selection windows, etc. */
5546 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
5547 {
5548 NSRect rect;
5549 NSPoint pt;
5550 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
5551 if (NS_KEYLOG)
5552 NSLog (@"firstRectForCharRange request");
5553
5554 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
5555 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
5556 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
5557 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
5558 +FRAME_LINE_HEIGHT (emacsframe));
5559
5560 pt = [self convertPoint: pt toView: nil];
5561 pt = [[self window] convertBaseToScreen: pt];
5562 rect.origin = pt;
5563 return rect;
5564 }
5565
5566
5567 - (NSInteger)conversationIdentifier
5568 {
5569 return (NSInteger)self;
5570 }
5571
5572
5573 - (void)doCommandBySelector: (SEL)aSelector
5574 {
5575 if (NS_KEYLOG)
5576 NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
5577
5578 processingCompose = NO;
5579 if (aSelector == @selector (deleteBackward:))
5580 {
5581 /* happens when user backspaces over an ongoing composition:
5582 throw a 'delete' into the event queue */
5583 if (!emacs_event)
5584 return;
5585 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5586 emacs_event->code = 0xFF08;
5587 EV_TRAILER ((id)nil);
5588 }
5589 }
5590
5591 - (NSArray *)validAttributesForMarkedText
5592 {
5593 static NSArray *arr = nil;
5594 if (arr == nil) arr = [NSArray new];
5595 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
5596 return arr;
5597 }
5598
5599 - (NSRange)selectedRange
5600 {
5601 if (NS_KEYLOG)
5602 NSLog (@"selectedRange request");
5603 return NSMakeRange (NSNotFound, 0);
5604 }
5605
5606 #if defined (NS_IMPL_COCOA) || GNUSTEP_GUI_MAJOR_VERSION > 0 || \
5607 GNUSTEP_GUI_MINOR_VERSION > 22
5608 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
5609 #else
5610 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
5611 #endif
5612 {
5613 if (NS_KEYLOG)
5614 NSLog (@"characterIndexForPoint request");
5615 return 0;
5616 }
5617
5618 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
5619 {
5620 static NSAttributedString *str = nil;
5621 if (str == nil) str = [NSAttributedString new];
5622 if (NS_KEYLOG)
5623 NSLog (@"attributedSubstringFromRange request");
5624 return str;
5625 }
5626
5627 /* End <NSTextInput> impl. */
5628 /*****************************************************************************/
5629
5630
5631 /* This is what happens when the user presses a mouse button. */
5632 - (void)mouseDown: (NSEvent *)theEvent
5633 {
5634 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
5635 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5636
5637 NSTRACE (mouseDown);
5638
5639 [self deleteWorkingText];
5640
5641 if (!emacs_event)
5642 return;
5643
5644 dpyinfo->last_mouse_frame = emacsframe;
5645 /* appears to be needed to prevent spurious movement events generated on
5646 button clicks */
5647 emacsframe->mouse_moved = 0;
5648
5649 if ([theEvent type] == NSScrollWheel)
5650 {
5651 CGFloat delta = [theEvent deltaY];
5652 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
5653 if (delta == 0)
5654 {
5655 delta = [theEvent deltaX];
5656 if (delta == 0)
5657 {
5658 NSTRACE (deltaIsZero);
5659 return;
5660 }
5661 emacs_event->kind = HORIZ_WHEEL_EVENT;
5662 }
5663 else
5664 emacs_event->kind = WHEEL_EVENT;
5665
5666 emacs_event->code = 0;
5667 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
5668 ((delta > 0) ? up_modifier : down_modifier);
5669 }
5670 else
5671 {
5672 emacs_event->kind = MOUSE_CLICK_EVENT;
5673 emacs_event->code = EV_BUTTON (theEvent);
5674 emacs_event->modifiers = EV_MODIFIERS (theEvent)
5675 | EV_UDMODIFIERS (theEvent);
5676 }
5677 XSETINT (emacs_event->x, lrint (p.x));
5678 XSETINT (emacs_event->y, lrint (p.y));
5679 EV_TRAILER (theEvent);
5680 }
5681
5682
5683 - (void)rightMouseDown: (NSEvent *)theEvent
5684 {
5685 NSTRACE (rightMouseDown);
5686 [self mouseDown: theEvent];
5687 }
5688
5689
5690 - (void)otherMouseDown: (NSEvent *)theEvent
5691 {
5692 NSTRACE (otherMouseDown);
5693 [self mouseDown: theEvent];
5694 }
5695
5696
5697 - (void)mouseUp: (NSEvent *)theEvent
5698 {
5699 NSTRACE (mouseUp);
5700 [self mouseDown: theEvent];
5701 }
5702
5703
5704 - (void)rightMouseUp: (NSEvent *)theEvent
5705 {
5706 NSTRACE (rightMouseUp);
5707 [self mouseDown: theEvent];
5708 }
5709
5710
5711 - (void)otherMouseUp: (NSEvent *)theEvent
5712 {
5713 NSTRACE (otherMouseUp);
5714 [self mouseDown: theEvent];
5715 }
5716
5717
5718 - (void) scrollWheel: (NSEvent *)theEvent
5719 {
5720 NSTRACE (scrollWheel);
5721 [self mouseDown: theEvent];
5722 }
5723
5724
5725 /* Tell emacs the mouse has moved. */
5726 - (void)mouseMoved: (NSEvent *)e
5727 {
5728 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5729 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
5730 Lisp_Object frame;
5731 NSPoint pt;
5732
5733 // NSTRACE (mouseMoved);
5734
5735 dpyinfo->last_mouse_movement_time = EV_TIMESTAMP (e);
5736 pt = [self convertPoint: [e locationInWindow] fromView: nil];
5737 dpyinfo->last_mouse_motion_x = pt.x;
5738 dpyinfo->last_mouse_motion_y = pt.y;
5739
5740 /* update any mouse face */
5741 if (hlinfo->mouse_face_hidden)
5742 {
5743 hlinfo->mouse_face_hidden = 0;
5744 clear_mouse_face (hlinfo);
5745 }
5746
5747 /* tooltip handling */
5748 previous_help_echo_string = help_echo_string;
5749 help_echo_string = Qnil;
5750
5751 if (!NILP (Vmouse_autoselect_window))
5752 {
5753 NSTRACE (mouse_autoselect_window);
5754 static Lisp_Object last_mouse_window;
5755 Lisp_Object window
5756 = window_from_coordinates (emacsframe, pt.x, pt.y, 0, 0);
5757
5758 if (WINDOWP (window)
5759 && !EQ (window, last_mouse_window)
5760 && !EQ (window, selected_window)
5761 && (focus_follows_mouse
5762 || (EQ (XWINDOW (window)->frame,
5763 XWINDOW (selected_window)->frame))))
5764 {
5765 NSTRACE (in_window);
5766 emacs_event->kind = SELECT_WINDOW_EVENT;
5767 emacs_event->frame_or_window = window;
5768 EV_TRAILER2 (e);
5769 }
5770 /* Remember the last window where we saw the mouse. */
5771 last_mouse_window = window;
5772 }
5773
5774 if (!note_mouse_movement (emacsframe, pt.x, pt.y))
5775 help_echo_string = previous_help_echo_string;
5776
5777 XSETFRAME (frame, emacsframe);
5778 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
5779 {
5780 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
5781 (note_mouse_highlight), which is called through the
5782 note_mouse_movement () call above */
5783 any_help_event_p = YES;
5784 gen_help_event (help_echo_string, frame, help_echo_window,
5785 help_echo_object, help_echo_pos);
5786 }
5787
5788 if (emacsframe->mouse_moved && send_appdefined)
5789 ns_send_appdefined (-1);
5790 }
5791
5792
5793 - (void)mouseDragged: (NSEvent *)e
5794 {
5795 NSTRACE (mouseDragged);
5796 [self mouseMoved: e];
5797 }
5798
5799
5800 - (void)rightMouseDragged: (NSEvent *)e
5801 {
5802 NSTRACE (rightMouseDragged);
5803 [self mouseMoved: e];
5804 }
5805
5806
5807 - (void)otherMouseDragged: (NSEvent *)e
5808 {
5809 NSTRACE (otherMouseDragged);
5810 [self mouseMoved: e];
5811 }
5812
5813
5814 - (BOOL)windowShouldClose: (id)sender
5815 {
5816 NSEvent *e =[[self window] currentEvent];
5817
5818 NSTRACE (windowShouldClose);
5819 windowClosing = YES;
5820 if (!emacs_event)
5821 return NO;
5822 emacs_event->kind = DELETE_WINDOW_EVENT;
5823 emacs_event->modifiers = 0;
5824 emacs_event->code = 0;
5825 EV_TRAILER (e);
5826 /* Don't close this window, let this be done from lisp code. */
5827 return NO;
5828 }
5829
5830 - (void) updateFrameSize: (BOOL) delay;
5831 {
5832 NSWindow *window = [self window];
5833 NSRect wr = [window frame];
5834 int extra = 0;
5835 int oldc = cols, oldr = rows;
5836 int oldw = FRAME_PIXEL_WIDTH (emacsframe);
5837 int oldh = FRAME_PIXEL_HEIGHT (emacsframe);
5838 int neww, newh;
5839
5840 NSTRACE (updateFrameSize);
5841 NSTRACE_SIZE ("Original size", NSMakeSize (oldw, oldh));
5842
5843 if (! [self isFullscreen])
5844 {
5845 #ifdef NS_IMPL_GNUSTEP
5846 // GNUstep does not always update the tool bar height. Force it.
5847 if (toolbar && [toolbar isVisible])
5848 update_frame_tool_bar (emacsframe);
5849 #endif
5850
5851 extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5852 + FRAME_TOOLBAR_HEIGHT (emacsframe);
5853 }
5854
5855 if (wait_for_tool_bar)
5856 {
5857 if (FRAME_TOOLBAR_HEIGHT (emacsframe) == 0)
5858 return;
5859 wait_for_tool_bar = NO;
5860 }
5861
5862 neww = (int)wr.size.width - emacsframe->border_width;
5863 newh = (int)wr.size.height - extra;
5864
5865 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, neww);
5866 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, newh);
5867
5868 if (cols < MINWIDTH)
5869 cols = MINWIDTH;
5870
5871 if (rows < MINHEIGHT)
5872 rows = MINHEIGHT;
5873
5874 if (oldr != rows || oldc != cols || neww != oldw || newh != oldh)
5875 {
5876 NSView *view = FRAME_NS_VIEW (emacsframe);
5877 NSWindow *win = [view window];
5878 NSSize sz = [win resizeIncrements];
5879
5880 change_frame_size (emacsframe,
5881 FRAME_PIXEL_TO_TEXT_WIDTH (emacsframe, neww),
5882 FRAME_PIXEL_TO_TEXT_HEIGHT (emacsframe, newh),
5883 0, delay, 0, 1);
5884 SET_FRAME_GARBAGED (emacsframe);
5885 cancel_mouse_face (emacsframe);
5886
5887 // Did resize increments change because of a font change?
5888 if (sz.width != FRAME_COLUMN_WIDTH (emacsframe) ||
5889 sz.height != FRAME_LINE_HEIGHT (emacsframe) ||
5890 (frame_resize_pixelwise && sz.width != 1))
5891 {
5892 sz.width = frame_resize_pixelwise
5893 ? 1 : FRAME_COLUMN_WIDTH (emacsframe);
5894 sz.height = frame_resize_pixelwise
5895 ? 1 : FRAME_LINE_HEIGHT (emacsframe);
5896 [win setResizeIncrements: sz];
5897
5898 NSTRACE_SIZE ("New size", NSMakeSize (neww, newh));
5899 }
5900
5901 [view setFrame: NSMakeRect (0, 0, neww, newh)];
5902 [self windowDidMove:nil]; // Update top/left.
5903 }
5904 }
5905
5906 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
5907 /* normalize frame to gridded text size */
5908 {
5909 int extra = 0;
5910
5911 NSTRACE (windowWillResize);
5912 NSTRACE_SIZE ("Original size", frameSize);
5913 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
5914
5915 if (fs_state == FULLSCREEN_MAXIMIZED
5916 && (maximized_width != (int)frameSize.width
5917 || maximized_height != (int)frameSize.height))
5918 [self setFSValue: FULLSCREEN_NONE];
5919 else if (fs_state == FULLSCREEN_WIDTH
5920 && maximized_width != (int)frameSize.width)
5921 [self setFSValue: FULLSCREEN_NONE];
5922 else if (fs_state == FULLSCREEN_HEIGHT
5923 && maximized_height != (int)frameSize.height)
5924 [self setFSValue: FULLSCREEN_NONE];
5925 if (fs_state == FULLSCREEN_NONE)
5926 maximized_width = maximized_height = -1;
5927
5928 if (! [self isFullscreen])
5929 {
5930 extra = FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5931 + FRAME_TOOLBAR_HEIGHT (emacsframe);
5932 }
5933
5934 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe, frameSize.width);
5935 if (cols < MINWIDTH)
5936 cols = MINWIDTH;
5937
5938 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe,
5939 frameSize.height - extra);
5940 if (rows < MINHEIGHT)
5941 rows = MINHEIGHT;
5942 #ifdef NS_IMPL_COCOA
5943 {
5944 /* this sets window title to have size in it; the wm does this under GS */
5945 NSRect r = [[self window] frame];
5946 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
5947 {
5948 if (old_title != 0)
5949 {
5950 xfree (old_title);
5951 old_title = 0;
5952 }
5953 }
5954 else if (fs_state == FULLSCREEN_NONE && ! maximizing_resize)
5955 {
5956 char *size_title;
5957 NSWindow *window = [self window];
5958 if (old_title == 0)
5959 {
5960 char *t = strdup ([[[self window] title] UTF8String]);
5961 char *pos = strstr (t, " — ");
5962 if (pos)
5963 *pos = '\0';
5964 old_title = t;
5965 }
5966 size_title = xmalloc (strlen (old_title) + 40);
5967 esprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
5968 [window setTitle: [NSString stringWithUTF8String: size_title]];
5969 [window display];
5970 xfree (size_title);
5971 }
5972 }
5973 #endif /* NS_IMPL_COCOA */
5974 /*fprintf (stderr," ...size became %.0f x %.0f (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
5975
5976 return frameSize;
5977 }
5978
5979
5980 - (void)windowDidResize: (NSNotification *)notification
5981 {
5982 if (! [self fsIsNative])
5983 {
5984 NSWindow *theWindow = [notification object];
5985 /* We can get notification on the non-FS window when in
5986 fullscreen mode. */
5987 if ([self window] != theWindow) return;
5988 }
5989
5990 #ifdef NS_IMPL_GNUSTEP
5991 NSWindow *theWindow = [notification object];
5992
5993 /* In GNUstep, at least currently, it's possible to get a didResize
5994 without getting a willResize.. therefore we need to act as if we got
5995 the willResize now */
5996 NSSize sz = [theWindow frame].size;
5997 sz = [self windowWillResize: theWindow toSize: sz];
5998 #endif /* NS_IMPL_GNUSTEP */
5999
6000 NSTRACE (windowDidResize);
6001 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
6002
6003 if (cols > 0 && rows > 0)
6004 {
6005 [self updateFrameSize: YES];
6006 }
6007
6008 ns_send_appdefined (-1);
6009 }
6010
6011 #ifdef NS_IMPL_COCOA
6012 - (void)viewDidEndLiveResize
6013 {
6014 [super viewDidEndLiveResize];
6015 if (old_title != 0)
6016 {
6017 [[self window] setTitle: [NSString stringWithUTF8String: old_title]];
6018 xfree (old_title);
6019 old_title = 0;
6020 }
6021 maximizing_resize = NO;
6022 }
6023 #endif /* NS_IMPL_COCOA */
6024
6025
6026 - (void)windowDidBecomeKey: (NSNotification *)notification
6027 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6028 {
6029 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6030 struct frame *old_focus = dpyinfo->x_focus_frame;
6031
6032 NSTRACE (windowDidBecomeKey);
6033
6034 if (emacsframe != old_focus)
6035 dpyinfo->x_focus_frame = emacsframe;
6036
6037 ns_frame_rehighlight (emacsframe);
6038
6039 if (emacs_event)
6040 {
6041 emacs_event->kind = FOCUS_IN_EVENT;
6042 EV_TRAILER ((id)nil);
6043 }
6044 }
6045
6046
6047 - (void)windowDidResignKey: (NSNotification *)notification
6048 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
6049 {
6050 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
6051 BOOL is_focus_frame = dpyinfo->x_focus_frame == emacsframe;
6052 NSTRACE (windowDidResignKey);
6053
6054 if (is_focus_frame)
6055 dpyinfo->x_focus_frame = 0;
6056
6057 emacsframe->mouse_moved = 0;
6058 ns_frame_rehighlight (emacsframe);
6059
6060 /* FIXME: for some reason needed on second and subsequent clicks away
6061 from sole-frame Emacs to get hollow box to show */
6062 if (!windowClosing && [[self window] isVisible] == YES)
6063 {
6064 x_update_cursor (emacsframe, 1);
6065 x_set_frame_alpha (emacsframe);
6066 }
6067
6068 if (any_help_event_p)
6069 {
6070 Lisp_Object frame;
6071 XSETFRAME (frame, emacsframe);
6072 help_echo_string = Qnil;
6073 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
6074 }
6075
6076 if (emacs_event && is_focus_frame)
6077 {
6078 [self deleteWorkingText];
6079 emacs_event->kind = FOCUS_OUT_EVENT;
6080 EV_TRAILER ((id)nil);
6081 }
6082 }
6083
6084
6085 - (void)windowWillMiniaturize: sender
6086 {
6087 NSTRACE (windowWillMiniaturize);
6088 }
6089
6090
6091 - (BOOL)isFlipped
6092 {
6093 return YES;
6094 }
6095
6096
6097 - (BOOL)isOpaque
6098 {
6099 return NO;
6100 }
6101
6102
6103 - initFrameFromEmacs: (struct frame *)f
6104 {
6105 NSRect r, wr;
6106 Lisp_Object tem;
6107 NSWindow *win;
6108 NSSize sz;
6109 NSColor *col;
6110 NSString *name;
6111
6112 NSTRACE (initFrameFromEmacs);
6113
6114 windowClosing = NO;
6115 processingCompose = NO;
6116 scrollbarsNeedingUpdate = 0;
6117 fs_state = FULLSCREEN_NONE;
6118 fs_before_fs = next_maximized = -1;
6119 #ifdef HAVE_NATIVE_FS
6120 fs_is_native = ns_use_native_fullscreen;
6121 #else
6122 fs_is_native = NO;
6123 #endif
6124 maximized_width = maximized_height = -1;
6125 nonfs_window = nil;
6126
6127 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
6128
6129 ns_userRect = NSMakeRect (0, 0, 0, 0);
6130 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
6131 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
6132 [self initWithFrame: r];
6133 [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
6134
6135 FRAME_NS_VIEW (f) = self;
6136 emacsframe = f;
6137 #ifdef NS_IMPL_COCOA
6138 old_title = 0;
6139 maximizing_resize = NO;
6140 #endif
6141
6142 win = [[EmacsWindow alloc]
6143 initWithContentRect: r
6144 styleMask: (NSResizableWindowMask |
6145 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6146 NSTitledWindowMask |
6147 #endif
6148 NSMiniaturizableWindowMask |
6149 NSClosableWindowMask)
6150 backing: NSBackingStoreBuffered
6151 defer: YES];
6152
6153 #ifdef HAVE_NATIVE_FS
6154 [win setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
6155 #endif
6156
6157 wr = [win frame];
6158 bwidth = f->border_width = wr.size.width - r.size.width;
6159 tibar_height = FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
6160
6161 [win setAcceptsMouseMovedEvents: YES];
6162 [win setDelegate: self];
6163 [win useOptimizedDrawing: YES];
6164
6165 sz.width = frame_resize_pixelwise ? 1 : FRAME_COLUMN_WIDTH (f);
6166 sz.height = frame_resize_pixelwise ? 1 : FRAME_LINE_HEIGHT (f);
6167 [win setResizeIncrements: sz];
6168
6169 [[win contentView] addSubview: self];
6170
6171 if (ns_drag_types)
6172 [self registerForDraggedTypes: ns_drag_types];
6173
6174 tem = f->name;
6175 name = [NSString stringWithUTF8String:
6176 NILP (tem) ? "Emacs" : SSDATA (tem)];
6177 [win setTitle: name];
6178
6179 /* toolbar support */
6180 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
6181 [NSString stringWithFormat: @"Emacs Frame %d",
6182 ns_window_num]];
6183 [win setToolbar: toolbar];
6184 [toolbar setVisible: NO];
6185
6186 /* Don't set frame garbaged until tool bar is up to date?
6187 This avoids an extra clear and redraw (flicker) at frame creation. */
6188 if (FRAME_EXTERNAL_TOOL_BAR (f)) wait_for_tool_bar = YES;
6189 else wait_for_tool_bar = NO;
6190
6191
6192 #ifdef NS_IMPL_COCOA
6193 {
6194 NSButton *toggleButton;
6195 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
6196 [toggleButton setTarget: self];
6197 [toggleButton setAction: @selector (toggleToolbar: )];
6198 }
6199 #endif
6200 FRAME_TOOLBAR_HEIGHT (f) = 0;
6201
6202 tem = f->icon_name;
6203 if (!NILP (tem))
6204 [win setMiniwindowTitle:
6205 [NSString stringWithUTF8String: SSDATA (tem)]];
6206
6207 {
6208 NSScreen *screen = [win screen];
6209
6210 if (screen != 0)
6211 [win setFrameTopLeftPoint: NSMakePoint
6212 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
6213 IN_BOUND (-SCREENMAX,
6214 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
6215 }
6216
6217 [win makeFirstResponder: self];
6218
6219 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6220 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
6221 [win setBackgroundColor: col];
6222 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6223 [win setOpaque: NO];
6224
6225 [self allocateGState];
6226
6227 [NSApp registerServicesMenuSendTypes: ns_send_types
6228 returnTypes: nil];
6229
6230 ns_window_num++;
6231 return self;
6232 }
6233
6234
6235 - (void)windowDidMove: sender
6236 {
6237 NSWindow *win = [self window];
6238 NSRect r = [win frame];
6239 NSArray *screens = [NSScreen screens];
6240 NSScreen *screen = [screens objectAtIndex: 0];
6241
6242 NSTRACE (windowDidMove);
6243
6244 if (!emacsframe->output_data.ns)
6245 return;
6246 if (screen != nil)
6247 {
6248 emacsframe->left_pos = r.origin.x;
6249 emacsframe->top_pos =
6250 [screen frame].size.height - (r.origin.y + r.size.height);
6251 }
6252 }
6253
6254
6255 /* Called AFTER method below, but before our windowWillResize call there leads
6256 to windowDidResize -> x_set_window_size. Update emacs' notion of frame
6257 location so set_window_size moves the frame. */
6258 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
6259 {
6260 emacsframe->output_data.ns->zooming = 1;
6261 return YES;
6262 }
6263
6264
6265 /* Override to do something slightly nonstandard, but nice. First click on
6266 zoom button will zoom vertically. Second will zoom completely. Third
6267 returns to original. */
6268 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
6269 defaultFrame:(NSRect)defaultFrame
6270 {
6271 NSRect result = [sender frame];
6272
6273 NSTRACE (windowWillUseStandardFrame);
6274
6275 if (fs_before_fs != -1) /* Entering fullscreen */
6276 {
6277 result = defaultFrame;
6278 }
6279 else if (next_maximized == FULLSCREEN_HEIGHT
6280 || (next_maximized == -1
6281 && abs (defaultFrame.size.height - result.size.height)
6282 > FRAME_LINE_HEIGHT (emacsframe)))
6283 {
6284 /* first click */
6285 ns_userRect = result;
6286 maximized_height = result.size.height = defaultFrame.size.height;
6287 maximized_width = -1;
6288 result.origin.y = defaultFrame.origin.y;
6289 [self setFSValue: FULLSCREEN_HEIGHT];
6290 #ifdef NS_IMPL_COCOA
6291 maximizing_resize = YES;
6292 #endif
6293 }
6294 else if (next_maximized == FULLSCREEN_WIDTH)
6295 {
6296 ns_userRect = result;
6297 maximized_width = result.size.width = defaultFrame.size.width;
6298 maximized_height = -1;
6299 result.origin.x = defaultFrame.origin.x;
6300 [self setFSValue: FULLSCREEN_WIDTH];
6301 }
6302 else if (next_maximized == FULLSCREEN_MAXIMIZED
6303 || (next_maximized == -1
6304 && abs (defaultFrame.size.width - result.size.width)
6305 > FRAME_COLUMN_WIDTH (emacsframe)))
6306 {
6307 result = defaultFrame; /* second click */
6308 maximized_width = result.size.width;
6309 maximized_height = result.size.height;
6310 [self setFSValue: FULLSCREEN_MAXIMIZED];
6311 #ifdef NS_IMPL_COCOA
6312 maximizing_resize = YES;
6313 #endif
6314 }
6315 else
6316 {
6317 /* restore */
6318 result = ns_userRect.size.height ? ns_userRect : result;
6319 ns_userRect = NSMakeRect (0, 0, 0, 0);
6320 #ifdef NS_IMPL_COCOA
6321 maximizing_resize = fs_state != FULLSCREEN_NONE;
6322 #endif
6323 [self setFSValue: FULLSCREEN_NONE];
6324 maximized_width = maximized_height = -1;
6325 }
6326
6327 if (fs_before_fs == -1) next_maximized = -1;
6328 [self windowWillResize: sender toSize: result.size];
6329 return result;
6330 }
6331
6332
6333 - (void)windowDidDeminiaturize: sender
6334 {
6335 NSTRACE (windowDidDeminiaturize);
6336 if (!emacsframe->output_data.ns)
6337 return;
6338
6339 SET_FRAME_ICONIFIED (emacsframe, 0);
6340 SET_FRAME_VISIBLE (emacsframe, 1);
6341 windows_or_buffers_changed = 63;
6342
6343 if (emacs_event)
6344 {
6345 emacs_event->kind = DEICONIFY_EVENT;
6346 EV_TRAILER ((id)nil);
6347 }
6348 }
6349
6350
6351 - (void)windowDidExpose: sender
6352 {
6353 NSTRACE (windowDidExpose);
6354 if (!emacsframe->output_data.ns)
6355 return;
6356
6357 SET_FRAME_VISIBLE (emacsframe, 1);
6358 SET_FRAME_GARBAGED (emacsframe);
6359
6360 if (send_appdefined)
6361 ns_send_appdefined (-1);
6362 }
6363
6364
6365 - (void)windowDidMiniaturize: sender
6366 {
6367 NSTRACE (windowDidMiniaturize);
6368 if (!emacsframe->output_data.ns)
6369 return;
6370
6371 SET_FRAME_ICONIFIED (emacsframe, 1);
6372 SET_FRAME_VISIBLE (emacsframe, 0);
6373
6374 if (emacs_event)
6375 {
6376 emacs_event->kind = ICONIFY_EVENT;
6377 EV_TRAILER ((id)nil);
6378 }
6379 }
6380
6381 #ifdef HAVE_NATIVE_FS
6382 - (NSApplicationPresentationOptions)window:(NSWindow *)window
6383 willUseFullScreenPresentationOptions:
6384 (NSApplicationPresentationOptions)proposedOptions
6385 {
6386 return proposedOptions|NSApplicationPresentationAutoHideToolbar;
6387 }
6388 #endif
6389
6390 - (void)windowWillEnterFullScreen:(NSNotification *)notification
6391 {
6392 fs_before_fs = fs_state;
6393 }
6394
6395 - (void)windowDidEnterFullScreen:(NSNotification *)notification
6396 {
6397 [self setFSValue: FULLSCREEN_BOTH];
6398 if (! [self fsIsNative])
6399 {
6400 [self windowDidBecomeKey:notification];
6401 [nonfs_window orderOut:self];
6402 }
6403 else
6404 {
6405 BOOL tbar_visible = FRAME_EXTERNAL_TOOL_BAR (emacsframe) ? YES : NO;
6406 #ifdef NS_IMPL_COCOA
6407 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
6408 unsigned val = (unsigned)[NSApp presentationOptions];
6409
6410 // OSX 10.7 bug fix, the menu won't appear without this.
6411 // val is non-zero on other OSX versions.
6412 if (val == 0)
6413 {
6414 NSApplicationPresentationOptions options
6415 = NSApplicationPresentationAutoHideDock
6416 | NSApplicationPresentationAutoHideMenuBar
6417 | NSApplicationPresentationFullScreen
6418 | NSApplicationPresentationAutoHideToolbar;
6419
6420 [NSApp setPresentationOptions: options];
6421 }
6422 #endif
6423 #endif
6424 [toolbar setVisible:tbar_visible];
6425 }
6426 }
6427
6428 - (void)windowWillExitFullScreen:(NSNotification *)notification
6429 {
6430 if (next_maximized != -1)
6431 fs_before_fs = next_maximized;
6432 }
6433
6434 - (void)windowDidExitFullScreen:(NSNotification *)notification
6435 {
6436 [self setFSValue: fs_before_fs];
6437 fs_before_fs = -1;
6438 #ifdef HAVE_NATIVE_FS
6439 [self updateCollectionBehavior];
6440 #endif
6441 if (FRAME_EXTERNAL_TOOL_BAR (emacsframe))
6442 {
6443 [toolbar setVisible:YES];
6444 update_frame_tool_bar (emacsframe);
6445 [self updateFrameSize:YES];
6446 [[self window] display];
6447 }
6448 else
6449 [toolbar setVisible:NO];
6450
6451 if (next_maximized != -1)
6452 [[self window] performZoom:self];
6453 }
6454
6455 - (BOOL)fsIsNative
6456 {
6457 return fs_is_native;
6458 }
6459
6460 - (BOOL)isFullscreen
6461 {
6462 if (! fs_is_native) return nonfs_window != nil;
6463 #ifdef HAVE_NATIVE_FS
6464 return ([[self window] styleMask] & NSFullScreenWindowMask) != 0;
6465 #else
6466 return NO;
6467 #endif
6468 }
6469
6470 #ifdef HAVE_NATIVE_FS
6471 - (void)updateCollectionBehavior
6472 {
6473 if (! [self isFullscreen])
6474 {
6475 NSWindow *win = [self window];
6476 NSWindowCollectionBehavior b = [win collectionBehavior];
6477 if (ns_use_native_fullscreen)
6478 b |= NSWindowCollectionBehaviorFullScreenPrimary;
6479 else
6480 b &= ~NSWindowCollectionBehaviorFullScreenPrimary;
6481
6482 [win setCollectionBehavior: b];
6483 fs_is_native = ns_use_native_fullscreen;
6484 }
6485 }
6486 #endif
6487
6488 - (void)toggleFullScreen: (id)sender
6489 {
6490 NSWindow *w, *fw;
6491 BOOL onFirstScreen;
6492 struct frame *f;
6493 NSSize sz;
6494 NSRect r, wr;
6495 NSColor *col;
6496
6497 if (fs_is_native)
6498 {
6499 #ifdef HAVE_NATIVE_FS
6500 [[self window] toggleFullScreen:sender];
6501 #endif
6502 return;
6503 }
6504
6505 w = [self window];
6506 onFirstScreen = [[w screen] isEqual:[[NSScreen screens] objectAtIndex:0]];
6507 f = emacsframe;
6508 wr = [w frame];
6509 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6510 (FRAME_DEFAULT_FACE (f)),
6511 f);
6512
6513 sz.width = frame_resize_pixelwise ? 1 : FRAME_COLUMN_WIDTH (f);
6514 sz.height = frame_resize_pixelwise ? 1 : FRAME_LINE_HEIGHT (f);
6515
6516 if (fs_state != FULLSCREEN_BOTH)
6517 {
6518 NSScreen *screen = [w screen];
6519
6520 #if defined (NS_IMPL_COCOA) && \
6521 MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
6522 /* Hide ghost menu bar on secondary monitor? */
6523 if (! onFirstScreen)
6524 onFirstScreen = [NSScreen screensHaveSeparateSpaces];
6525 #endif
6526 /* Hide dock and menubar if we are on the primary screen. */
6527 if (onFirstScreen)
6528 {
6529 #ifdef NS_IMPL_COCOA
6530 NSApplicationPresentationOptions options
6531 = NSApplicationPresentationAutoHideDock
6532 | NSApplicationPresentationAutoHideMenuBar;
6533
6534 [NSApp setPresentationOptions: options];
6535 #else
6536 [NSMenu setMenuBarVisible:NO];
6537 #endif
6538 }
6539
6540 fw = [[EmacsFSWindow alloc]
6541 initWithContentRect:[w contentRectForFrameRect:wr]
6542 styleMask:NSBorderlessWindowMask
6543 backing:NSBackingStoreBuffered
6544 defer:YES
6545 screen:screen];
6546
6547 [fw setContentView:[w contentView]];
6548 [fw setTitle:[w title]];
6549 [fw setDelegate:self];
6550 [fw setAcceptsMouseMovedEvents: YES];
6551 [fw useOptimizedDrawing: YES];
6552 [fw setResizeIncrements: sz];
6553 [fw setBackgroundColor: col];
6554 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6555 [fw setOpaque: NO];
6556
6557 f->border_width = 0;
6558 FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
6559 tobar_height = FRAME_TOOLBAR_HEIGHT (f);
6560 FRAME_TOOLBAR_HEIGHT (f) = 0;
6561
6562 nonfs_window = w;
6563
6564 [self windowWillEnterFullScreen:nil];
6565 [fw makeKeyAndOrderFront:NSApp];
6566 [fw makeFirstResponder:self];
6567 [w orderOut:self];
6568 r = [fw frameRectForContentRect:[screen frame]];
6569 [fw setFrame: r display:YES animate:ns_use_fullscreen_animation];
6570 [self windowDidEnterFullScreen:nil];
6571 [fw display];
6572 }
6573 else
6574 {
6575 fw = w;
6576 w = nonfs_window;
6577 nonfs_window = nil;
6578
6579 if (onFirstScreen)
6580 {
6581 #ifdef NS_IMPL_COCOA
6582 [NSApp setPresentationOptions: NSApplicationPresentationDefault];
6583 #else
6584 [NSMenu setMenuBarVisible:YES];
6585 #endif
6586 }
6587
6588 [w setContentView:[fw contentView]];
6589 [w setResizeIncrements: sz];
6590 [w setBackgroundColor: col];
6591 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6592 [w setOpaque: NO];
6593
6594 f->border_width = bwidth;
6595 FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
6596 if (FRAME_EXTERNAL_TOOL_BAR (f))
6597 FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
6598
6599 [self windowWillExitFullScreen:nil];
6600 [fw setFrame: [w frame] display:YES animate:ns_use_fullscreen_animation];
6601 [fw close];
6602 [w makeKeyAndOrderFront:NSApp];
6603 [self windowDidExitFullScreen:nil];
6604 [self updateFrameSize:YES];
6605 }
6606 }
6607
6608 - (void)handleFS
6609 {
6610 if (fs_state != emacsframe->want_fullscreen)
6611 {
6612 if (fs_state == FULLSCREEN_BOTH)
6613 {
6614 [self toggleFullScreen:self];
6615 }
6616
6617 switch (emacsframe->want_fullscreen)
6618 {
6619 case FULLSCREEN_BOTH:
6620 [self toggleFullScreen:self];
6621 break;
6622 case FULLSCREEN_WIDTH:
6623 next_maximized = FULLSCREEN_WIDTH;
6624 if (fs_state != FULLSCREEN_BOTH)
6625 [[self window] performZoom:self];
6626 break;
6627 case FULLSCREEN_HEIGHT:
6628 next_maximized = FULLSCREEN_HEIGHT;
6629 if (fs_state != FULLSCREEN_BOTH)
6630 [[self window] performZoom:self];
6631 break;
6632 case FULLSCREEN_MAXIMIZED:
6633 next_maximized = FULLSCREEN_MAXIMIZED;
6634 if (fs_state != FULLSCREEN_BOTH)
6635 [[self window] performZoom:self];
6636 break;
6637 case FULLSCREEN_NONE:
6638 if (fs_state != FULLSCREEN_BOTH)
6639 {
6640 next_maximized = FULLSCREEN_NONE;
6641 [[self window] performZoom:self];
6642 }
6643 break;
6644 }
6645
6646 emacsframe->want_fullscreen = FULLSCREEN_NONE;
6647 }
6648
6649 }
6650
6651 - (void) setFSValue: (int)value
6652 {
6653 Lisp_Object lval = Qnil;
6654 switch (value)
6655 {
6656 case FULLSCREEN_BOTH:
6657 lval = Qfullboth;
6658 break;
6659 case FULLSCREEN_WIDTH:
6660 lval = Qfullwidth;
6661 break;
6662 case FULLSCREEN_HEIGHT:
6663 lval = Qfullheight;
6664 break;
6665 case FULLSCREEN_MAXIMIZED:
6666 lval = Qmaximized;
6667 break;
6668 }
6669 store_frame_param (emacsframe, Qfullscreen, lval);
6670 fs_state = value;
6671 }
6672
6673 - (void)mouseEntered: (NSEvent *)theEvent
6674 {
6675 NSTRACE (mouseEntered);
6676 if (emacsframe)
6677 FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
6678 = EV_TIMESTAMP (theEvent);
6679 }
6680
6681
6682 - (void)mouseExited: (NSEvent *)theEvent
6683 {
6684 Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
6685
6686 NSTRACE (mouseExited);
6687
6688 if (!hlinfo)
6689 return;
6690
6691 FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
6692 = EV_TIMESTAMP (theEvent);
6693
6694 if (emacsframe == hlinfo->mouse_face_mouse_frame)
6695 {
6696 clear_mouse_face (hlinfo);
6697 hlinfo->mouse_face_mouse_frame = 0;
6698 }
6699 }
6700
6701
6702 - menuDown: sender
6703 {
6704 NSTRACE (menuDown);
6705 if (context_menu_value == -1)
6706 context_menu_value = [sender tag];
6707 else
6708 {
6709 NSInteger tag = [sender tag];
6710 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
6711 emacsframe->menu_bar_vector,
6712 (void *)tag);
6713 }
6714
6715 ns_send_appdefined (-1);
6716 return self;
6717 }
6718
6719
6720 - (EmacsToolbar *)toolbar
6721 {
6722 return toolbar;
6723 }
6724
6725
6726 /* this gets called on toolbar button click */
6727 - toolbarClicked: (id)item
6728 {
6729 NSEvent *theEvent;
6730 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
6731
6732 NSTRACE (toolbarClicked);
6733
6734 if (!emacs_event)
6735 return self;
6736
6737 /* send first event (for some reason two needed) */
6738 theEvent = [[self window] currentEvent];
6739 emacs_event->kind = TOOL_BAR_EVENT;
6740 XSETFRAME (emacs_event->arg, emacsframe);
6741 EV_TRAILER (theEvent);
6742
6743 emacs_event->kind = TOOL_BAR_EVENT;
6744 /* XSETINT (emacs_event->code, 0); */
6745 emacs_event->arg = AREF (emacsframe->tool_bar_items,
6746 idx + TOOL_BAR_ITEM_KEY);
6747 emacs_event->modifiers = EV_MODIFIERS (theEvent);
6748 EV_TRAILER (theEvent);
6749 return self;
6750 }
6751
6752
6753 - toggleToolbar: (id)sender
6754 {
6755 if (!emacs_event)
6756 return self;
6757
6758 emacs_event->kind = NS_NONKEY_EVENT;
6759 emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
6760 EV_TRAILER ((id)nil);
6761 return self;
6762 }
6763
6764
6765 - (void)drawRect: (NSRect)rect
6766 {
6767 int x = NSMinX (rect), y = NSMinY (rect);
6768 int width = NSWidth (rect), height = NSHeight (rect);
6769
6770 NSTRACE (drawRect);
6771
6772 if (!emacsframe || !emacsframe->output_data.ns)
6773 return;
6774
6775 ns_clear_frame_area (emacsframe, x, y, width, height);
6776 block_input ();
6777 expose_frame (emacsframe, x, y, width, height);
6778 unblock_input ();
6779
6780 /*
6781 drawRect: may be called (at least in OS X 10.5) for invisible
6782 views as well for some reason. Thus, do not infer visibility
6783 here.
6784
6785 emacsframe->async_visible = 1;
6786 emacsframe->async_iconified = 0;
6787 */
6788 }
6789
6790
6791 /* NSDraggingDestination protocol methods. Actually this is not really a
6792 protocol, but a category of Object. O well... */
6793
6794 -(NSUInteger) draggingEntered: (id <NSDraggingInfo>) sender
6795 {
6796 NSTRACE (draggingEntered);
6797 return NSDragOperationGeneric;
6798 }
6799
6800
6801 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
6802 {
6803 return YES;
6804 }
6805
6806
6807 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
6808 {
6809 id pb;
6810 int x, y;
6811 NSString *type;
6812 NSEvent *theEvent = [[self window] currentEvent];
6813 NSPoint position;
6814 NSDragOperation op = [sender draggingSourceOperationMask];
6815 int modifiers = 0;
6816
6817 NSTRACE (performDragOperation);
6818
6819 if (!emacs_event)
6820 return NO;
6821
6822 position = [self convertPoint: [sender draggingLocation] fromView: nil];
6823 x = lrint (position.x); y = lrint (position.y);
6824
6825 pb = [sender draggingPasteboard];
6826 type = [pb availableTypeFromArray: ns_drag_types];
6827
6828 if (! (op & (NSDragOperationMove|NSDragOperationDelete)) &&
6829 // URL drags contain all operations (0xf), don't allow all to be set.
6830 (op & 0xf) != 0xf)
6831 {
6832 if (op & NSDragOperationLink)
6833 modifiers |= NSControlKeyMask;
6834 if (op & NSDragOperationCopy)
6835 modifiers |= NSAlternateKeyMask;
6836 if (op & NSDragOperationGeneric)
6837 modifiers |= NSCommandKeyMask;
6838 }
6839
6840 modifiers = EV_MODIFIERS2 (modifiers);
6841 if (type == 0)
6842 {
6843 return NO;
6844 }
6845 else if ([type isEqualToString: NSFilenamesPboardType])
6846 {
6847 NSArray *files;
6848 NSEnumerator *fenum;
6849 NSString *file;
6850
6851 if (!(files = [pb propertyListForType: type]))
6852 return NO;
6853
6854 fenum = [files objectEnumerator];
6855 while ( (file = [fenum nextObject]) )
6856 {
6857 emacs_event->kind = DRAG_N_DROP_EVENT;
6858 XSETINT (emacs_event->x, x);
6859 XSETINT (emacs_event->y, y);
6860 ns_input_file = append2 (ns_input_file,
6861 build_string ([file UTF8String]));
6862 emacs_event->modifiers = modifiers;
6863 emacs_event->arg = list2 (Qfile, build_string ([file UTF8String]));
6864 EV_TRAILER (theEvent);
6865 }
6866 return YES;
6867 }
6868 else if ([type isEqualToString: NSURLPboardType])
6869 {
6870 NSURL *url = [NSURL URLFromPasteboard: pb];
6871 if (url == nil) return NO;
6872
6873 emacs_event->kind = DRAG_N_DROP_EVENT;
6874 XSETINT (emacs_event->x, x);
6875 XSETINT (emacs_event->y, y);
6876 emacs_event->modifiers = modifiers;
6877 emacs_event->arg = list2 (Qurl,
6878 build_string ([[url absoluteString]
6879 UTF8String]));
6880 EV_TRAILER (theEvent);
6881
6882 if ([url isFileURL] != NO)
6883 {
6884 NSString *file = [url path];
6885 ns_input_file = append2 (ns_input_file,
6886 build_string ([file UTF8String]));
6887 }
6888 return YES;
6889 }
6890 else if ([type isEqualToString: NSStringPboardType]
6891 || [type isEqualToString: NSTabularTextPboardType])
6892 {
6893 NSString *data;
6894
6895 if (! (data = [pb stringForType: type]))
6896 return NO;
6897
6898 emacs_event->kind = DRAG_N_DROP_EVENT;
6899 XSETINT (emacs_event->x, x);
6900 XSETINT (emacs_event->y, y);
6901 emacs_event->modifiers = modifiers;
6902 emacs_event->arg = list2 (Qnil, build_string ([data UTF8String]));
6903 EV_TRAILER (theEvent);
6904 return YES;
6905 }
6906 else
6907 {
6908 fprintf (stderr, "Invalid data type in dragging pasteboard");
6909 return NO;
6910 }
6911 }
6912
6913
6914 - (id) validRequestorForSendType: (NSString *)typeSent
6915 returnType: (NSString *)typeReturned
6916 {
6917 NSTRACE (validRequestorForSendType);
6918 if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
6919 && typeReturned == nil)
6920 {
6921 if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
6922 return self;
6923 }
6924
6925 return [super validRequestorForSendType: typeSent
6926 returnType: typeReturned];
6927 }
6928
6929
6930 /* The next two methods are part of NSServicesRequests informal protocol,
6931 supposedly called when a services menu item is chosen from this app.
6932 But this should not happen because we override the services menu with our
6933 own entries which call ns-perform-service.
6934 Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
6935 So let's at least stub them out until further investigation can be done. */
6936
6937 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
6938 {
6939 /* we could call ns_string_from_pasteboard(pboard) here but then it should
6940 be written into the buffer in place of the existing selection..
6941 ordinary service calls go through functions defined in ns-win.el */
6942 return NO;
6943 }
6944
6945 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
6946 {
6947 NSArray *typesDeclared;
6948 Lisp_Object val;
6949
6950 /* We only support NSStringPboardType */
6951 if ([types containsObject:NSStringPboardType] == NO) {
6952 return NO;
6953 }
6954
6955 val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
6956 if (CONSP (val) && SYMBOLP (XCAR (val)))
6957 {
6958 val = XCDR (val);
6959 if (CONSP (val) && NILP (XCDR (val)))
6960 val = XCAR (val);
6961 }
6962 if (! STRINGP (val))
6963 return NO;
6964
6965 typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
6966 [pb declareTypes:typesDeclared owner:nil];
6967 ns_string_to_pasteboard (pb, val);
6968 return YES;
6969 }
6970
6971
6972 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
6973 (gives a miniaturized version of the window); currently we use the latter for
6974 frames whose active buffer doesn't correspond to any file
6975 (e.g., '*scratch*') */
6976 - setMiniwindowImage: (BOOL) setMini
6977 {
6978 id image = [[self window] miniwindowImage];
6979 NSTRACE (setMiniwindowImage);
6980
6981 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
6982 about "AppleDockIconEnabled" notwithstanding, however the set message
6983 below has its effect nonetheless. */
6984 if (image != emacsframe->output_data.ns->miniimage)
6985 {
6986 if (image && [image isKindOfClass: [EmacsImage class]])
6987 [image release];
6988 [[self window] setMiniwindowImage:
6989 setMini ? emacsframe->output_data.ns->miniimage : nil];
6990 }
6991
6992 return self;
6993 }
6994
6995
6996 - (void) setRows: (int) r andColumns: (int) c
6997 {
6998 rows = r;
6999 cols = c;
7000 }
7001
7002 @end /* EmacsView */
7003
7004
7005
7006 /* ==========================================================================
7007
7008 EmacsWindow implementation
7009
7010 ========================================================================== */
7011
7012 @implementation EmacsWindow
7013
7014 #ifdef NS_IMPL_COCOA
7015 - (id)accessibilityAttributeValue:(NSString *)attribute
7016 {
7017 Lisp_Object str = Qnil;
7018 struct frame *f = SELECTED_FRAME ();
7019 struct buffer *curbuf = XBUFFER (XWINDOW (f->selected_window)->contents);
7020
7021 if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
7022 return NSAccessibilityTextFieldRole;
7023
7024 if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]
7025 && curbuf && ! NILP (BVAR (curbuf, mark_active)))
7026 {
7027 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7028 }
7029 else if (curbuf && [attribute isEqualToString:NSAccessibilityValueAttribute])
7030 {
7031 if (! NILP (BVAR (curbuf, mark_active)))
7032 str = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
7033
7034 if (NILP (str))
7035 {
7036 ptrdiff_t start_byte = BUF_BEGV_BYTE (curbuf);
7037 ptrdiff_t byte_range = BUF_ZV_BYTE (curbuf) - start_byte;
7038 ptrdiff_t range = BUF_ZV (curbuf) - BUF_BEGV (curbuf);
7039
7040 if (! NILP (BVAR (curbuf, enable_multibyte_characters)))
7041 str = make_uninit_multibyte_string (range, byte_range);
7042 else
7043 str = make_uninit_string (range);
7044 /* To check: This returns emacs-utf-8, which is a superset of utf-8.
7045 Is this a problem? */
7046 memcpy (SDATA (str), BYTE_POS_ADDR (start_byte), byte_range);
7047 }
7048 }
7049
7050
7051 if (! NILP (str))
7052 {
7053 if (CONSP (str) && SYMBOLP (XCAR (str)))
7054 {
7055 str = XCDR (str);
7056 if (CONSP (str) && NILP (XCDR (str)))
7057 str = XCAR (str);
7058 }
7059 if (STRINGP (str))
7060 {
7061 const char *utfStr = SSDATA (str);
7062 NSString *nsStr = [NSString stringWithUTF8String: utfStr];
7063 return nsStr;
7064 }
7065 }
7066
7067 return [super accessibilityAttributeValue:attribute];
7068 }
7069 #endif /* NS_IMPL_COCOA */
7070
7071 /* If we have multiple monitors, one above the other, we don't want to
7072 restrict the height to just one monitor. So we override this. */
7073 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
7074 {
7075 /* When making the frame visible for the first time or if there is just
7076 one screen, we want to constrain. Other times not. */
7077 NSArray *screens = [NSScreen screens];
7078 NSUInteger nr_screens = [screens count], nr_eff_screens = 0, i;
7079 struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
7080 NSTRACE (constrainFrameRect);
7081 NSTRACE_RECT ("input", frameRect);
7082
7083 if (ns_menu_bar_should_be_hidden ())
7084 return frameRect;
7085
7086 if (nr_screens == 1)
7087 return [super constrainFrameRect:frameRect toScreen:screen];
7088
7089 #ifdef NS_IMPL_COCOA
7090 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
7091 // If separate spaces is on, it is like each screen is independent. There is
7092 // no spanning of frames across screens.
7093 if ([NSScreen screensHaveSeparateSpaces])
7094 return [super constrainFrameRect:frameRect toScreen:screen];
7095 #endif
7096 #endif
7097
7098 for (i = 0; i < nr_screens; ++i)
7099 {
7100 NSScreen *s = [screens objectAtIndex: i];
7101 NSRect scrrect = [s frame];
7102 NSRect intersect = NSIntersectionRect (frameRect, scrrect);
7103
7104 if (intersect.size.width > 0 || intersect.size.height > 0)
7105 ++nr_eff_screens;
7106 }
7107
7108 if (nr_eff_screens == 1)
7109 return [super constrainFrameRect:frameRect toScreen:screen];
7110
7111 /* The default implementation does two things 1) ensure that the top
7112 of the rectangle is below the menu bar (or below the top of the
7113 screen) and 2) resizes windows larger than the screen. As we
7114 don't want the latter, a smaller rectangle is used. */
7115 #define FAKE_HEIGHT 64
7116 float old_top = frameRect.origin.y + frameRect.size.height;
7117 NSRect r;
7118 r.size.height = FAKE_HEIGHT;
7119 r.size.width = frameRect.size.width;
7120 r.origin.x = frameRect.origin.x;
7121 r.origin.y = old_top - FAKE_HEIGHT;
7122
7123 NSTRACE_RECT ("input to super", r);
7124
7125 r = [super constrainFrameRect:r toScreen:screen];
7126
7127 NSTRACE_RECT ("output from super", r);
7128
7129 float new_top = r.origin.y + FAKE_HEIGHT;
7130 if (new_top < old_top)
7131 {
7132 frameRect.origin.y = new_top - frameRect.size.height;
7133 }
7134
7135 NSTRACE_RECT ("output", frameRect);
7136
7137 return frameRect;
7138 #undef FAKE_HEIGHT
7139 }
7140
7141 @end /* EmacsWindow */
7142
7143
7144 @implementation EmacsFSWindow
7145
7146 - (BOOL)canBecomeKeyWindow
7147 {
7148 return YES;
7149 }
7150
7151 - (BOOL)canBecomeMainWindow
7152 {
7153 return YES;
7154 }
7155
7156 @end
7157
7158 /* ==========================================================================
7159
7160 EmacsScroller implementation
7161
7162 ========================================================================== */
7163
7164
7165 @implementation EmacsScroller
7166
7167 /* for repeat button push */
7168 #define SCROLL_BAR_FIRST_DELAY 0.5
7169 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
7170
7171 + (CGFloat) scrollerWidth
7172 {
7173 /* TODO: if we want to allow variable widths, this is the place to do it,
7174 however neither GNUstep nor Cocoa support it very well */
7175 return [NSScroller scrollerWidth];
7176 }
7177
7178
7179 - initFrame: (NSRect )r window: (Lisp_Object)nwin
7180 {
7181 NSTRACE (EmacsScroller_initFrame);
7182
7183 r.size.width = [EmacsScroller scrollerWidth];
7184 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
7185 [self setContinuous: YES];
7186 [self setEnabled: YES];
7187
7188 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
7189 locked against the top and bottom edges, and right edge on OS X, where
7190 scrollers are on right. */
7191 #ifdef NS_IMPL_GNUSTEP
7192 [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
7193 #else
7194 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
7195 #endif
7196
7197 window = XWINDOW (nwin);
7198 condemned = NO;
7199 pixel_height = NSHeight (r);
7200 if (pixel_height == 0) pixel_height = 1;
7201 min_portion = 20 / pixel_height;
7202
7203 frame = XFRAME (window->frame);
7204 if (FRAME_LIVE_P (frame))
7205 {
7206 int i;
7207 EmacsView *view = FRAME_NS_VIEW (frame);
7208 NSView *sview = [[view window] contentView];
7209 NSArray *subs = [sview subviews];
7210
7211 /* disable optimization stopping redraw of other scrollbars */
7212 view->scrollbarsNeedingUpdate = 0;
7213 for (i =[subs count]-1; i >= 0; i--)
7214 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
7215 view->scrollbarsNeedingUpdate++;
7216 [sview addSubview: self];
7217 }
7218
7219 /* [self setFrame: r]; */
7220
7221 return self;
7222 }
7223
7224
7225 - (void)setFrame: (NSRect)newRect
7226 {
7227 NSTRACE (EmacsScroller_setFrame);
7228 /* block_input (); */
7229 pixel_height = NSHeight (newRect);
7230 if (pixel_height == 0) pixel_height = 1;
7231 min_portion = 20 / pixel_height;
7232 [super setFrame: newRect];
7233 /* unblock_input (); */
7234 }
7235
7236
7237 - (void)dealloc
7238 {
7239 NSTRACE (EmacsScroller_dealloc);
7240 if (window)
7241 wset_vertical_scroll_bar (window, Qnil);
7242 window = 0;
7243 [super dealloc];
7244 }
7245
7246
7247 - condemn
7248 {
7249 NSTRACE (condemn);
7250 condemned =YES;
7251 return self;
7252 }
7253
7254
7255 - reprieve
7256 {
7257 NSTRACE (reprieve);
7258 condemned =NO;
7259 return self;
7260 }
7261
7262
7263 -(bool)judge
7264 {
7265 NSTRACE (judge);
7266 bool ret = condemned;
7267 if (condemned)
7268 {
7269 EmacsView *view;
7270 block_input ();
7271 /* ensure other scrollbar updates after deletion */
7272 view = (EmacsView *)FRAME_NS_VIEW (frame);
7273 if (view != nil)
7274 view->scrollbarsNeedingUpdate++;
7275 if (window)
7276 wset_vertical_scroll_bar (window, Qnil);
7277 window = 0;
7278 [self removeFromSuperview];
7279 [self release];
7280 unblock_input ();
7281 }
7282 return ret;
7283 }
7284
7285
7286 - (void)resetCursorRects
7287 {
7288 NSRect visible = [self visibleRect];
7289 NSTRACE (resetCursorRects);
7290
7291 if (!NSIsEmptyRect (visible))
7292 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
7293 [[NSCursor arrowCursor] setOnMouseEntered: YES];
7294 }
7295
7296
7297 - (int) checkSamePosition: (int) position portion: (int) portion
7298 whole: (int) whole
7299 {
7300 return em_position ==position && em_portion ==portion && em_whole ==whole
7301 && portion != whole; /* needed for resize empty buf */
7302 }
7303
7304
7305 - setPosition: (int)position portion: (int)portion whole: (int)whole
7306 {
7307 NSTRACE (setPosition);
7308
7309 em_position = position;
7310 em_portion = portion;
7311 em_whole = whole;
7312
7313 if (portion >= whole)
7314 {
7315 #ifdef NS_IMPL_COCOA
7316 [self setKnobProportion: 1.0];
7317 [self setDoubleValue: 1.0];
7318 #else
7319 [self setFloatValue: 0.0 knobProportion: 1.0];
7320 #endif
7321 }
7322 else
7323 {
7324 float pos;
7325 CGFloat por;
7326 portion = max ((float)whole*min_portion/pixel_height, portion);
7327 pos = (float)position / (whole - portion);
7328 por = (CGFloat)portion/whole;
7329 #ifdef NS_IMPL_COCOA
7330 [self setKnobProportion: por];
7331 [self setDoubleValue: pos];
7332 #else
7333 [self setFloatValue: pos knobProportion: por];
7334 #endif
7335 }
7336
7337 return self;
7338 }
7339
7340 /* set up emacs_event */
7341 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
7342 {
7343 Lisp_Object win;
7344 if (!emacs_event)
7345 return;
7346
7347 emacs_event->part = last_hit_part;
7348 emacs_event->code = 0;
7349 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
7350 XSETWINDOW (win, window);
7351 emacs_event->frame_or_window = win;
7352 emacs_event->timestamp = EV_TIMESTAMP (e);
7353 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
7354 emacs_event->arg = Qnil;
7355 XSETINT (emacs_event->x, loc * pixel_height);
7356 XSETINT (emacs_event->y, pixel_height-20);
7357
7358 if (q_event_ptr)
7359 {
7360 n_emacs_events_pending++;
7361 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
7362 }
7363 else
7364 hold_event (emacs_event);
7365 EVENT_INIT (*emacs_event);
7366 ns_send_appdefined (-1);
7367 }
7368
7369
7370 /* called manually thru timer to implement repeated button action w/hold-down */
7371 - repeatScroll: (NSTimer *)scrollEntry
7372 {
7373 NSEvent *e = [[self window] currentEvent];
7374 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
7375 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
7376
7377 /* clear timer if need be */
7378 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
7379 {
7380 [scroll_repeat_entry invalidate];
7381 [scroll_repeat_entry release];
7382 scroll_repeat_entry = nil;
7383
7384 if (inKnob)
7385 return self;
7386
7387 scroll_repeat_entry
7388 = [[NSTimer scheduledTimerWithTimeInterval:
7389 SCROLL_BAR_CONTINUOUS_DELAY
7390 target: self
7391 selector: @selector (repeatScroll:)
7392 userInfo: 0
7393 repeats: YES]
7394 retain];
7395 }
7396
7397 [self sendScrollEventAtLoc: 0 fromEvent: e];
7398 return self;
7399 }
7400
7401
7402 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
7403 mouseDragged events without going into a modal loop. */
7404 - (void)mouseDown: (NSEvent *)e
7405 {
7406 NSRect sr, kr;
7407 /* hitPart is only updated AFTER event is passed on */
7408 NSScrollerPart part = [self testPart: [e locationInWindow]];
7409 CGFloat inc = 0.0, loc, kloc, pos;
7410 int edge = 0;
7411
7412 NSTRACE (EmacsScroller_mouseDown);
7413
7414 switch (part)
7415 {
7416 case NSScrollerDecrementPage:
7417 last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
7418 case NSScrollerIncrementPage:
7419 last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
7420 case NSScrollerDecrementLine:
7421 last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
7422 case NSScrollerIncrementLine:
7423 last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
7424 case NSScrollerKnob:
7425 last_hit_part = scroll_bar_handle; break;
7426 case NSScrollerKnobSlot: /* GNUstep-only */
7427 last_hit_part = scroll_bar_move_ratio; break;
7428 default: /* NSScrollerNoPart? */
7429 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
7430 (long) part);
7431 return;
7432 }
7433
7434 if (inc != 0.0)
7435 {
7436 pos = 0; /* ignored */
7437
7438 /* set a timer to repeat, as we can't let superclass do this modally */
7439 scroll_repeat_entry
7440 = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
7441 target: self
7442 selector: @selector (repeatScroll:)
7443 userInfo: 0
7444 repeats: YES]
7445 retain];
7446 }
7447 else
7448 {
7449 /* handle, or on GNUstep possibly slot */
7450 NSEvent *fake_event;
7451
7452 /* compute float loc in slot and mouse offset on knob */
7453 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
7454 toView: nil];
7455 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
7456 if (loc <= 0.0)
7457 {
7458 loc = 0.0;
7459 edge = -1;
7460 }
7461 else if (loc >= NSHeight (sr))
7462 {
7463 loc = NSHeight (sr);
7464 edge = 1;
7465 }
7466
7467 if (edge)
7468 kloc = 0.5 * edge;
7469 else
7470 {
7471 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
7472 toView: nil];
7473 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
7474 }
7475 last_mouse_offset = kloc;
7476
7477 /* if knob, tell emacs a location offset by knob pos
7478 (to indicate top of handle) */
7479 if (part == NSScrollerKnob)
7480 pos = (loc - last_mouse_offset) / NSHeight (sr);
7481 else
7482 /* else this is a slot click on GNUstep: go straight there */
7483 pos = loc / NSHeight (sr);
7484
7485 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
7486 fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
7487 location: [e locationInWindow]
7488 modifierFlags: [e modifierFlags]
7489 timestamp: [e timestamp]
7490 windowNumber: [e windowNumber]
7491 context: [e context]
7492 eventNumber: [e eventNumber]
7493 clickCount: [e clickCount]
7494 pressure: [e pressure]];
7495 [super mouseUp: fake_event];
7496 }
7497
7498 if (part != NSScrollerKnob)
7499 [self sendScrollEventAtLoc: pos fromEvent: e];
7500 }
7501
7502
7503 /* Called as we manually track scroller drags, rather than superclass. */
7504 - (void)mouseDragged: (NSEvent *)e
7505 {
7506 NSRect sr;
7507 double loc, pos;
7508
7509 NSTRACE (EmacsScroller_mouseDragged);
7510
7511 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
7512 toView: nil];
7513 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
7514
7515 if (loc <= 0.0)
7516 {
7517 loc = 0.0;
7518 }
7519 else if (loc >= NSHeight (sr) + last_mouse_offset)
7520 {
7521 loc = NSHeight (sr) + last_mouse_offset;
7522 }
7523
7524 pos = (loc - last_mouse_offset) / NSHeight (sr);
7525 [self sendScrollEventAtLoc: pos fromEvent: e];
7526 }
7527
7528
7529 - (void)mouseUp: (NSEvent *)e
7530 {
7531 if (scroll_repeat_entry)
7532 {
7533 [scroll_repeat_entry invalidate];
7534 [scroll_repeat_entry release];
7535 scroll_repeat_entry = nil;
7536 }
7537 last_hit_part = scroll_bar_above_handle;
7538 }
7539
7540
7541 /* treat scrollwheel events in the bar as though they were in the main window */
7542 - (void) scrollWheel: (NSEvent *)theEvent
7543 {
7544 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
7545 [view mouseDown: theEvent];
7546 }
7547
7548 @end /* EmacsScroller */
7549
7550
7551 #ifdef NS_IMPL_GNUSTEP
7552 /* Dummy class to get rid of startup warnings. */
7553 @implementation EmacsDocument
7554
7555 @end
7556 #endif
7557
7558
7559 /* ==========================================================================
7560
7561 Font-related functions; these used to be in nsfaces.m
7562
7563 ========================================================================== */
7564
7565
7566 Lisp_Object
7567 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
7568 {
7569 struct font *font = XFONT_OBJECT (font_object);
7570 EmacsView *view = FRAME_NS_VIEW (f);
7571
7572 if (fontset < 0)
7573 fontset = fontset_from_font (font_object);
7574 FRAME_FONTSET (f) = fontset;
7575
7576 if (FRAME_FONT (f) == font)
7577 /* This font is already set in frame F. There's nothing more to
7578 do. */
7579 return font_object;
7580
7581 FRAME_FONT (f) = font;
7582
7583 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
7584 FRAME_COLUMN_WIDTH (f) = font->average_width;
7585 FRAME_LINE_HEIGHT (f) = font->height;
7586
7587 /* Compute the scroll bar width in character columns. */
7588 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
7589 {
7590 int wid = FRAME_COLUMN_WIDTH (f);
7591 FRAME_CONFIG_SCROLL_BAR_COLS (f)
7592 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
7593 }
7594 else
7595 {
7596 int wid = FRAME_COLUMN_WIDTH (f);
7597 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
7598 }
7599
7600 /* Compute the scroll bar height in character lines. */
7601 if (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) > 0)
7602 {
7603 int height = FRAME_LINE_HEIGHT (f);
7604 FRAME_CONFIG_SCROLL_BAR_LINES (f)
7605 = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + height - 1) / height;
7606 }
7607 else
7608 {
7609 int height = FRAME_LINE_HEIGHT (f);
7610 FRAME_CONFIG_SCROLL_BAR_LINES (f) = (14 + height - 1) / height;
7611 }
7612
7613 /* Now make the frame display the given font. */
7614 if (FRAME_NS_WINDOW (f) != 0 && ! [view isFullscreen])
7615 x_set_window_size (f, false, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
7616 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), true);
7617
7618 return font_object;
7619 }
7620
7621
7622 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
7623 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
7624 in 1.43. */
7625
7626 const char *
7627 ns_xlfd_to_fontname (const char *xlfd)
7628 /* --------------------------------------------------------------------------
7629 Convert an X font name (XLFD) to an NS font name.
7630 Only family is used.
7631 The string returned is temporarily allocated.
7632 -------------------------------------------------------------------------- */
7633 {
7634 char *name = xmalloc (180);
7635 int i, len;
7636 const char *ret;
7637
7638 if (!strncmp (xlfd, "--", 2))
7639 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
7640 else
7641 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
7642
7643 /* stopgap for malformed XLFD input */
7644 if (strlen (name) == 0)
7645 strcpy (name, "Monaco");
7646
7647 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
7648 also uppercase after '-' or ' ' */
7649 name[0] = c_toupper (name[0]);
7650 for (len =strlen (name), i =0; i<len; i++)
7651 {
7652 if (name[i] == '$')
7653 {
7654 name[i] = '-';
7655 if (i+1<len)
7656 name[i+1] = c_toupper (name[i+1]);
7657 }
7658 else if (name[i] == '_')
7659 {
7660 name[i] = ' ';
7661 if (i+1<len)
7662 name[i+1] = c_toupper (name[i+1]);
7663 }
7664 }
7665 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
7666 ret = [[NSString stringWithUTF8String: name] UTF8String];
7667 xfree (name);
7668 return ret;
7669 }
7670
7671
7672 void
7673 syms_of_nsterm (void)
7674 {
7675 NSTRACE (syms_of_nsterm);
7676
7677 ns_antialias_threshold = 10.0;
7678
7679 /* from 23+ we need to tell emacs what modifiers there are.. */
7680 DEFSYM (Qmodifier_value, "modifier-value");
7681 DEFSYM (Qalt, "alt");
7682 DEFSYM (Qhyper, "hyper");
7683 DEFSYM (Qmeta, "meta");
7684 DEFSYM (Qsuper, "super");
7685 DEFSYM (Qcontrol, "control");
7686 DEFSYM (QUTF8_STRING, "UTF8_STRING");
7687
7688 DEFSYM (Qfile, "file");
7689 DEFSYM (Qurl, "url");
7690
7691 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
7692 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
7693 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
7694 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
7695 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
7696
7697 DEFVAR_LISP ("ns-input-file", ns_input_file,
7698 "The file specified in the last NS event.");
7699 ns_input_file =Qnil;
7700
7701 DEFVAR_LISP ("ns-working-text", ns_working_text,
7702 "String for visualizing working composition sequence.");
7703 ns_working_text =Qnil;
7704
7705 DEFVAR_LISP ("ns-input-font", ns_input_font,
7706 "The font specified in the last NS event.");
7707 ns_input_font =Qnil;
7708
7709 DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
7710 "The fontsize specified in the last NS event.");
7711 ns_input_fontsize =Qnil;
7712
7713 DEFVAR_LISP ("ns-input-line", ns_input_line,
7714 "The line specified in the last NS event.");
7715 ns_input_line =Qnil;
7716
7717 DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
7718 "The service name specified in the last NS event.");
7719 ns_input_spi_name =Qnil;
7720
7721 DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
7722 "The service argument specified in the last NS event.");
7723 ns_input_spi_arg =Qnil;
7724
7725 DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
7726 "This variable describes the behavior of the alternate or option key.\n\
7727 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7728 Set to none means that the alternate / option key is not interpreted by Emacs\n\
7729 at all, allowing it to be used at a lower level for accented character entry.");
7730 ns_alternate_modifier = Qmeta;
7731
7732 DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
7733 "This variable describes the behavior of the right alternate or option key.\n\
7734 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7735 Set to left means be the same key as `ns-alternate-modifier'.\n\
7736 Set to none means that the alternate / option key is not interpreted by Emacs\n\
7737 at all, allowing it to be used at a lower level for accented character entry.");
7738 ns_right_alternate_modifier = Qleft;
7739
7740 DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
7741 "This variable describes the behavior of the command key.\n\
7742 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
7743 ns_command_modifier = Qsuper;
7744
7745 DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
7746 "This variable describes the behavior of the right command key.\n\
7747 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7748 Set to left means be the same key as `ns-command-modifier'.\n\
7749 Set to none means that the command / option key is not interpreted by Emacs\n\
7750 at all, allowing it to be used at a lower level for accented character entry.");
7751 ns_right_command_modifier = Qleft;
7752
7753 DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
7754 "This variable describes the behavior of the control key.\n\
7755 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
7756 ns_control_modifier = Qcontrol;
7757
7758 DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
7759 "This variable describes the behavior of the right control key.\n\
7760 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7761 Set to left means be the same key as `ns-control-modifier'.\n\
7762 Set to none means that the control / option key is not interpreted by Emacs\n\
7763 at all, allowing it to be used at a lower level for accented character entry.");
7764 ns_right_control_modifier = Qleft;
7765
7766 DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
7767 "This variable describes the behavior of the function key (on laptops).\n\
7768 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7769 Set to none means that the function key is not interpreted by Emacs at all,\n\
7770 allowing it to be used at a lower level for accented character entry.");
7771 ns_function_modifier = Qnone;
7772
7773 DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
7774 "Non-nil (the default) means to render text antialiased.");
7775 ns_antialias_text = Qt;
7776
7777 DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
7778 "Whether to confirm application quit using dialog.");
7779 ns_confirm_quit = Qnil;
7780
7781 DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
7782 doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
7783 Only works on OSX 10.6 or later. */);
7784 ns_auto_hide_menu_bar = Qnil;
7785
7786 DEFVAR_BOOL ("ns-use-native-fullscreen", ns_use_native_fullscreen,
7787 doc: /*Non-nil means to use native fullscreen on OSX >= 10.7.
7788 Nil means use fullscreen the old (< 10.7) way. The old way works better with
7789 multiple monitors, but lacks tool bar. This variable is ignored on OSX < 10.7.
7790 Default is t for OSX >= 10.7, nil otherwise. */);
7791 #ifdef HAVE_NATIVE_FS
7792 ns_use_native_fullscreen = YES;
7793 #else
7794 ns_use_native_fullscreen = NO;
7795 #endif
7796 ns_last_use_native_fullscreen = ns_use_native_fullscreen;
7797
7798 DEFVAR_BOOL ("ns-use-fullscreen-animation", ns_use_fullscreen_animation,
7799 doc: /*Non-nil means use animation on non-native fullscreen.
7800 For native fullscreen, this does nothing.
7801 Default is nil. */);
7802 ns_use_fullscreen_animation = NO;
7803
7804 DEFVAR_BOOL ("ns-use-srgb-colorspace", ns_use_srgb_colorspace,
7805 doc: /*Non-nil means to use sRGB colorspace on OSX >= 10.7.
7806 Note that this does not apply to images.
7807 This variable is ignored on OSX < 10.7 and GNUstep. */);
7808 ns_use_srgb_colorspace = YES;
7809
7810 /* TODO: move to common code */
7811 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
7812 doc: /* Which toolkit scroll bars Emacs uses, if any.
7813 A value of nil means Emacs doesn't use toolkit scroll bars.
7814 With the X Window system, the value is a symbol describing the
7815 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
7816 With MS Windows or Nextstep, the value is t. */);
7817 Vx_toolkit_scroll_bars = Qt;
7818
7819 DEFVAR_BOOL ("x-use-underline-position-properties",
7820 x_use_underline_position_properties,
7821 doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
7822 A value of nil means ignore them. If you encounter fonts with bogus
7823 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
7824 to 4.1, set this to nil. */);
7825 x_use_underline_position_properties = 0;
7826
7827 DEFVAR_BOOL ("x-underline-at-descent-line",
7828 x_underline_at_descent_line,
7829 doc: /* Non-nil means to draw the underline at the same place as the descent line.
7830 A value of nil means to draw the underline according to the value of the
7831 variable `x-use-underline-position-properties', which is usually at the
7832 baseline level. The default value is nil. */);
7833 x_underline_at_descent_line = 0;
7834
7835 /* Tell Emacs about this window system. */
7836 Fprovide (Qns, Qnil);
7837
7838 DEFSYM (Qcocoa, "cocoa");
7839 DEFSYM (Qgnustep, "gnustep");
7840
7841 #ifdef NS_IMPL_COCOA
7842 Fprovide (Qcocoa, Qnil);
7843 syms_of_macfont ();
7844 #else
7845 Fprovide (Qgnustep, Qnil);
7846 syms_of_nsfont ();
7847 #endif
7848
7849 }