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