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