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