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