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