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