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