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