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