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