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