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