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