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