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