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