Remove compiler warnings in objective-C files.
[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 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
4724 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
4725 /* (Carbon way: [theEvent keyCode]) */
4726
4727 /* is it a "function key"? */
4728 fnKeysym = ns_convert_key (code);
4729 if (fnKeysym)
4730 {
4731 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
4732 because Emacs treats Delete and KP-Delete same (in simple.el). */
4733 if (fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
4734 code = 0xFF08; /* backspace */
4735 else
4736 code = fnKeysym;
4737 }
4738
4739 /* are there modifiers? */
4740 emacs_event->modifiers = 0;
4741 flags = [theEvent modifierFlags];
4742
4743 if (flags & NSHelpKeyMask)
4744 emacs_event->modifiers |= hyper_modifier;
4745
4746 if (flags & NSShiftKeyMask)
4747 emacs_event->modifiers |= shift_modifier;
4748
4749 if ((flags & NSRightCommandKeyMask) == NSRightCommandKeyMask)
4750 emacs_event->modifiers |= parse_solitary_modifier
4751 (EQ (ns_right_command_modifier, Qleft)
4752 ? ns_command_modifier
4753 : ns_right_command_modifier);
4754
4755 if ((flags & NSLeftCommandKeyMask) == NSLeftCommandKeyMask)
4756 {
4757 emacs_event->modifiers |= parse_solitary_modifier
4758 (ns_command_modifier);
4759
4760 /* if super (default), take input manager's word so things like
4761 dvorak / qwerty layout work */
4762 if (EQ (ns_command_modifier, Qsuper)
4763 && !fnKeysym
4764 && [[theEvent characters] length] != 0)
4765 {
4766 /* XXX: the code we get will be unshifted, so if we have
4767 a shift modifier, must convert ourselves */
4768 if (!(flags & NSShiftKeyMask))
4769 code = [[theEvent characters] characterAtIndex: 0];
4770 #if 0
4771 /* this is ugly and also requires linking w/Carbon framework
4772 (for LMGetKbdType) so for now leave this rare (?) case
4773 undealt with.. in future look into CGEvent methods */
4774 else
4775 {
4776 long smv = GetScriptManagerVariable (smKeyScript);
4777 Handle uchrHandle = GetResource
4778 ('uchr', GetScriptVariable (smv, smScriptKeys));
4779 UInt32 dummy = 0;
4780 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
4781 [[theEvent characters] characterAtIndex: 0],
4782 kUCKeyActionDisplay,
4783 (flags & ~NSCommandKeyMask) >> 8,
4784 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
4785 &dummy, 1, &dummy, &code);
4786 code &= 0xFF;
4787 }
4788 #endif
4789 }
4790 }
4791
4792 if ((flags & NSRightControlKeyMask) == NSRightControlKeyMask)
4793 emacs_event->modifiers |= parse_solitary_modifier
4794 (EQ (ns_right_control_modifier, Qleft)
4795 ? ns_control_modifier
4796 : ns_right_control_modifier);
4797
4798 if ((flags & NSLeftControlKeyMask) == NSLeftControlKeyMask)
4799 emacs_event->modifiers |= parse_solitary_modifier
4800 (ns_control_modifier);
4801
4802 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
4803 emacs_event->modifiers |=
4804 parse_solitary_modifier (ns_function_modifier);
4805
4806 left_is_none = NILP (ns_alternate_modifier)
4807 || EQ (ns_alternate_modifier, Qnone);
4808
4809 if ((flags & NSRightAlternateKeyMask) == NSRightAlternateKeyMask)
4810 {
4811 if ((NILP (ns_right_alternate_modifier)
4812 || EQ (ns_right_alternate_modifier, Qnone)
4813 || (EQ (ns_right_alternate_modifier, Qleft) && left_is_none))
4814 && !fnKeysym)
4815 { /* accept pre-interp alt comb */
4816 if ([[theEvent characters] length] > 0)
4817 code = [[theEvent characters] characterAtIndex: 0];
4818 /*HACK: clear lone shift modifier to stop next if from firing */
4819 if (emacs_event->modifiers == shift_modifier)
4820 emacs_event->modifiers = 0;
4821 }
4822 else
4823 emacs_event->modifiers |= parse_solitary_modifier
4824 (EQ (ns_right_alternate_modifier, Qleft)
4825 ? ns_alternate_modifier
4826 : ns_right_alternate_modifier);
4827 }
4828
4829 if ((flags & NSLeftAlternateKeyMask) == NSLeftAlternateKeyMask) /* default = meta */
4830 {
4831 if (left_is_none && !fnKeysym)
4832 { /* accept pre-interp alt comb */
4833 if ([[theEvent characters] length] > 0)
4834 code = [[theEvent characters] characterAtIndex: 0];
4835 /*HACK: clear lone shift modifier to stop next if from firing */
4836 if (emacs_event->modifiers == shift_modifier)
4837 emacs_event->modifiers = 0;
4838 }
4839 else
4840 emacs_event->modifiers |=
4841 parse_solitary_modifier (ns_alternate_modifier);
4842 }
4843
4844 if (NS_KEYLOG)
4845 fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
4846 code, fnKeysym, flags, emacs_event->modifiers);
4847
4848 /* if it was a function key or had modifiers, pass it directly to emacs */
4849 if (fnKeysym || (emacs_event->modifiers
4850 && (emacs_event->modifiers != shift_modifier)
4851 && [[theEvent charactersIgnoringModifiers] length] > 0))
4852 /*[[theEvent characters] length] */
4853 {
4854 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4855 if (code < 0x20)
4856 code |= (1<<28)|(3<<16);
4857 else if (code == 0x7f)
4858 code |= (1<<28)|(3<<16);
4859 else if (!fnKeysym)
4860 emacs_event->kind = code > 0xFF
4861 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4862
4863 emacs_event->code = code;
4864 EV_TRAILER (theEvent);
4865 return;
4866 }
4867 }
4868
4869
4870 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
4871 /* if we get here we should send the key for input manager processing */
4872 if (firstTime && [[NSInputManager currentInputManager]
4873 wantsToDelayTextChangeNotifications] == NO)
4874 fprintf (stderr,
4875 "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
4876 firstTime = NO;
4877 #endif
4878 if (NS_KEYLOG && !processingCompose)
4879 fprintf (stderr, "keyDown: Begin compose sequence.\n");
4880
4881 processingCompose = YES;
4882 [nsEvArray addObject: theEvent];
4883 [self interpretKeyEvents: nsEvArray];
4884 [nsEvArray removeObject: theEvent];
4885 }
4886
4887
4888 #ifdef NS_IMPL_COCOA
4889 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
4890 decided not to send key-down for.
4891 See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
4892 This only applies on Tiger and earlier.
4893 If it matches one of these, send it on to keyDown. */
4894 -(void)keyUp: (NSEvent *)theEvent
4895 {
4896 int flags = [theEvent modifierFlags];
4897 int code = [theEvent keyCode];
4898 if (floor (NSAppKitVersionNumber) <= 824 /*NSAppKitVersionNumber10_4*/ &&
4899 code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
4900 {
4901 if (NS_KEYLOG)
4902 fprintf (stderr, "keyUp: passed test");
4903 ns_fake_keydown = YES;
4904 [self keyDown: theEvent];
4905 }
4906 }
4907 #endif
4908
4909
4910 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
4911
4912
4913 /* <NSTextInput>: called when done composing;
4914 NOTE: also called when we delete over working text, followed immed.
4915 by doCommandBySelector: deleteBackward: */
4916 - (void)insertText: (id)aString
4917 {
4918 int code;
4919 int len = [(NSString *)aString length];
4920 int i;
4921
4922 if (NS_KEYLOG)
4923 NSLog (@"insertText '%@'\tlen = %d", aString, len);
4924 processingCompose = NO;
4925
4926 if (!emacs_event)
4927 return;
4928
4929 /* first, clear any working text */
4930 if (workingText != nil)
4931 [self deleteWorkingText];
4932
4933 /* now insert the string as keystrokes */
4934 for (i =0; i<len; i++)
4935 {
4936 code = [aString characterAtIndex: i];
4937 /* TODO: still need this? */
4938 if (code == 0x2DC)
4939 code = '~'; /* 0x7E */
4940 emacs_event->modifiers = 0;
4941 emacs_event->kind
4942 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4943 emacs_event->code = code;
4944 EV_TRAILER ((id)nil);
4945 }
4946 }
4947
4948
4949 /* <NSTextInput>: inserts display of composing characters */
4950 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
4951 {
4952 NSString *str = [aString respondsToSelector: @selector (string)] ?
4953 [aString string] : aString;
4954 if (NS_KEYLOG)
4955 NSLog (@"setMarkedText '%@' len =%d range %d from %d", str, [str length],
4956 selRange.length, selRange.location);
4957
4958 if (workingText != nil)
4959 [self deleteWorkingText];
4960 if ([str length] == 0)
4961 return;
4962
4963 if (!emacs_event)
4964 return;
4965
4966 processingCompose = YES;
4967 workingText = [str copy];
4968 ns_working_text = build_string ([workingText UTF8String]);
4969
4970 emacs_event->kind = NS_TEXT_EVENT;
4971 emacs_event->code = KEY_NS_PUT_WORKING_TEXT;
4972 EV_TRAILER ((id)nil);
4973 }
4974
4975
4976 /* delete display of composing characters [not in <NSTextInput>] */
4977 - (void)deleteWorkingText
4978 {
4979 if (workingText == nil)
4980 return;
4981 if (NS_KEYLOG)
4982 NSLog(@"deleteWorkingText len =%d\n", [workingText length]);
4983 [workingText release];
4984 workingText = nil;
4985 processingCompose = NO;
4986
4987 if (!emacs_event)
4988 return;
4989
4990 emacs_event->kind = NS_TEXT_EVENT;
4991 emacs_event->code = KEY_NS_UNPUT_WORKING_TEXT;
4992 EV_TRAILER ((id)nil);
4993 }
4994
4995
4996 - (BOOL)hasMarkedText
4997 {
4998 return workingText != nil;
4999 }
5000
5001
5002 - (NSRange)markedRange
5003 {
5004 NSRange rng = workingText != nil
5005 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
5006 if (NS_KEYLOG)
5007 NSLog (@"markedRange request");
5008 return rng;
5009 }
5010
5011
5012 - (void)unmarkText
5013 {
5014 if (NS_KEYLOG)
5015 NSLog (@"unmark (accept) text");
5016 [self deleteWorkingText];
5017 processingCompose = NO;
5018 }
5019
5020
5021 /* used to position char selection windows, etc. */
5022 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
5023 {
5024 NSRect rect;
5025 NSPoint pt;
5026 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
5027 if (NS_KEYLOG)
5028 NSLog (@"firstRectForCharRange request");
5029
5030 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
5031 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
5032 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
5033 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
5034 +FRAME_LINE_HEIGHT (emacsframe));
5035
5036 pt = [self convertPoint: pt toView: nil];
5037 pt = [[self window] convertBaseToScreen: pt];
5038 rect.origin = pt;
5039 return rect;
5040 }
5041
5042
5043 - (long)conversationIdentifier
5044 {
5045 return (long)self;
5046 }
5047
5048
5049 - (void)doCommandBySelector: (SEL)aSelector
5050 {
5051 if (NS_KEYLOG)
5052 NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
5053
5054 if (aSelector == @selector (deleteBackward:))
5055 {
5056 /* happens when user backspaces over an ongoing composition:
5057 throw a 'delete' into the event queue */
5058 if (!emacs_event)
5059 return;
5060 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5061 emacs_event->code = 0xFF08;
5062 EV_TRAILER ((id)nil);
5063 }
5064 }
5065
5066 - (NSArray *)validAttributesForMarkedText
5067 {
5068 static NSArray *arr = nil;
5069 if (arr == nil) arr = [NSArray new];
5070 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
5071 return arr;
5072 }
5073
5074 - (NSRange)selectedRange
5075 {
5076 if (NS_KEYLOG)
5077 NSLog (@"selectedRange request");
5078 return NSMakeRange (NSNotFound, 0);
5079 }
5080
5081 - (NSUInteger)characterIndexForPoint: (NSPoint)thePoint
5082 {
5083 if (NS_KEYLOG)
5084 NSLog (@"characterIndexForPoint request");
5085 return 0;
5086 }
5087
5088 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
5089 {
5090 static NSAttributedString *str = nil;
5091 if (str == nil) str = [NSAttributedString new];
5092 if (NS_KEYLOG)
5093 NSLog (@"attributedSubstringFromRange request");
5094 return str;
5095 }
5096
5097 /* End <NSTextInput> impl. */
5098 /*****************************************************************************/
5099
5100
5101 /* This is what happens when the user presses a mouse button. */
5102 - (void)mouseDown: (NSEvent *)theEvent
5103 {
5104 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5105
5106 NSTRACE (mouseDown);
5107
5108 [self deleteWorkingText];
5109
5110 if (!emacs_event)
5111 return;
5112
5113 last_mouse_frame = emacsframe;
5114 /* appears to be needed to prevent spurious movement events generated on
5115 button clicks */
5116 last_mouse_frame->mouse_moved = 0;
5117
5118 if ([theEvent type] == NSScrollWheel)
5119 {
5120 float delta = [theEvent deltaY];
5121 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
5122 if (delta == 0)
5123 return;
5124 emacs_event->kind = WHEEL_EVENT;
5125 emacs_event->code = 0;
5126 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
5127 ((delta > 0) ? up_modifier : down_modifier);
5128 }
5129 else
5130 {
5131 emacs_event->kind = MOUSE_CLICK_EVENT;
5132 emacs_event->code = EV_BUTTON (theEvent);
5133 emacs_event->modifiers = EV_MODIFIERS (theEvent)
5134 | EV_UDMODIFIERS (theEvent);
5135 }
5136 XSETINT (emacs_event->x, lrint (p.x));
5137 XSETINT (emacs_event->y, lrint (p.y));
5138 EV_TRAILER (theEvent);
5139 }
5140
5141
5142 - (void)rightMouseDown: (NSEvent *)theEvent
5143 {
5144 NSTRACE (rightMouseDown);
5145 [self mouseDown: theEvent];
5146 }
5147
5148
5149 - (void)otherMouseDown: (NSEvent *)theEvent
5150 {
5151 NSTRACE (otherMouseDown);
5152 [self mouseDown: theEvent];
5153 }
5154
5155
5156 - (void)mouseUp: (NSEvent *)theEvent
5157 {
5158 NSTRACE (mouseUp);
5159 [self mouseDown: theEvent];
5160 }
5161
5162
5163 - (void)rightMouseUp: (NSEvent *)theEvent
5164 {
5165 NSTRACE (rightMouseUp);
5166 [self mouseDown: theEvent];
5167 }
5168
5169
5170 - (void)otherMouseUp: (NSEvent *)theEvent
5171 {
5172 NSTRACE (otherMouseUp);
5173 [self mouseDown: theEvent];
5174 }
5175
5176
5177 - (void) scrollWheel: (NSEvent *)theEvent
5178 {
5179 NSTRACE (scrollWheel);
5180 [self mouseDown: theEvent];
5181 }
5182
5183
5184 /* Tell emacs the mouse has moved. */
5185 - (void)mouseMoved: (NSEvent *)e
5186 {
5187 Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (emacsframe);
5188 Lisp_Object frame;
5189
5190 // NSTRACE (mouseMoved);
5191
5192 last_mouse_movement_time = EV_TIMESTAMP (e);
5193 last_mouse_motion_position
5194 = [self convertPoint: [e locationInWindow] fromView: nil];
5195
5196 /* update any mouse face */
5197 if (hlinfo->mouse_face_hidden)
5198 {
5199 hlinfo->mouse_face_hidden = 0;
5200 clear_mouse_face (hlinfo);
5201 }
5202
5203 /* tooltip handling */
5204 previous_help_echo_string = help_echo_string;
5205 help_echo_string = Qnil;
5206
5207 if (!note_mouse_movement (emacsframe, last_mouse_motion_position.x,
5208 last_mouse_motion_position.y))
5209 help_echo_string = previous_help_echo_string;
5210
5211 XSETFRAME (frame, emacsframe);
5212 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
5213 {
5214 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
5215 (note_mouse_highlight), which is called through the
5216 note_mouse_movement () call above */
5217 gen_help_event (help_echo_string, frame, help_echo_window,
5218 help_echo_object, help_echo_pos);
5219 }
5220 else
5221 {
5222 help_echo_string = Qnil;
5223 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
5224 }
5225
5226 if (emacsframe->mouse_moved && send_appdefined)
5227 ns_send_appdefined (-1);
5228 }
5229
5230
5231 - (void)mouseDragged: (NSEvent *)e
5232 {
5233 NSTRACE (mouseDragged);
5234 [self mouseMoved: e];
5235 }
5236
5237
5238 - (void)rightMouseDragged: (NSEvent *)e
5239 {
5240 NSTRACE (rightMouseDragged);
5241 [self mouseMoved: e];
5242 }
5243
5244
5245 - (void)otherMouseDragged: (NSEvent *)e
5246 {
5247 NSTRACE (otherMouseDragged);
5248 [self mouseMoved: e];
5249 }
5250
5251
5252 - (BOOL)windowShouldClose: (id)sender
5253 {
5254 NSEvent *e =[[self window] currentEvent];
5255
5256 NSTRACE (windowShouldClose);
5257 windowClosing = YES;
5258 if (!emacs_event)
5259 return NO;
5260 emacs_event->kind = DELETE_WINDOW_EVENT;
5261 emacs_event->modifiers = 0;
5262 emacs_event->code = 0;
5263 EV_TRAILER (e);
5264 /* Don't close this window, let this be done from lisp code. */
5265 return NO;
5266 }
5267
5268
5269 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
5270 /* normalize frame to gridded text size */
5271 {
5272 NSTRACE (windowWillResize);
5273 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
5274
5275 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe,
5276 #ifdef NS_IMPL_GNUSTEP
5277 frameSize.width + 3);
5278 #else
5279 frameSize.width);
5280 #endif
5281 if (cols < MINWIDTH)
5282 cols = MINWIDTH;
5283
5284 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, frameSize.height
5285 #ifdef NS_IMPL_GNUSTEP
5286 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe) + 3
5287 - FRAME_TOOLBAR_HEIGHT (emacsframe));
5288 #else
5289 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5290 - FRAME_TOOLBAR_HEIGHT (emacsframe));
5291 #endif
5292 if (rows < MINHEIGHT)
5293 rows = MINHEIGHT;
5294 #ifdef NS_IMPL_COCOA
5295 {
5296 /* this sets window title to have size in it; the wm does this under GS */
5297 NSRect r = [[self window] frame];
5298 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
5299 {
5300 if (old_title != 0)
5301 {
5302 xfree (old_title);
5303 old_title = 0;
5304 }
5305 }
5306 else
5307 {
5308 char *size_title;
5309 NSWindow *window = [self window];
5310 if (old_title == 0)
5311 {
5312 const char *t = [[[self window] title] UTF8String];
5313 char *pos = strstr (t, " — ");
5314 if (pos)
5315 *pos = '\0';
5316 old_title = xstrdup (t);
5317 }
5318 size_title = xmalloc (strlen (old_title) + 40);
5319 esprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
5320 [window setTitle: [NSString stringWithUTF8String: size_title]];
5321 [window display];
5322 xfree (size_title);
5323 }
5324 }
5325 #endif /* NS_IMPL_COCOA */
5326 /*fprintf (stderr," ...size became %.0f x %.0f (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
5327
5328 return frameSize;
5329 }
5330
5331
5332 - (void)windowDidResize: (NSNotification *)notification
5333 {
5334 #ifdef NS_IMPL_GNUSTEP
5335 NSWindow *theWindow = [notification object];
5336
5337 /* in GNUstep, at least currently, it's possible to get a didResize
5338 without getting a willResize.. therefore we need to act as if we got
5339 the willResize now */
5340 NSSize sz = [theWindow frame].size;
5341 sz = [self windowWillResize: theWindow toSize: sz];
5342 #endif /* NS_IMPL_GNUSTEP */
5343
5344 NSTRACE (windowDidResize);
5345 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
5346
5347 #ifdef NS_IMPL_COCOA
5348 if (old_title != 0)
5349 {
5350 xfree (old_title);
5351 old_title = 0;
5352 }
5353 #endif /* NS_IMPL_COCOA */
5354
5355 /* Avoid loop under GNUstep due to call at beginning of this function.
5356 (x_set_window_size causes a resize which causes
5357 a "windowDidResize" which calls x_set_window_size). */
5358 #ifndef NS_IMPL_GNUSTEP
5359 if (cols > 0 && rows > 0)
5360 {
5361 if (ns_in_resize)
5362 x_set_window_size (emacsframe, 0, cols, rows);
5363 else
5364 {
5365 NSWindow *window = [self window];
5366 NSRect wr = [window frame];
5367 FRAME_PIXEL_WIDTH (emacsframe) = (int)wr.size.width
5368 - emacsframe->border_width;
5369 FRAME_PIXEL_HEIGHT (emacsframe) = (int)wr.size.height
5370 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
5371 - FRAME_TOOLBAR_HEIGHT (emacsframe);
5372 change_frame_size (emacsframe, rows, cols, 0, 0, 1);
5373 SET_FRAME_GARBAGED (emacsframe);
5374 cancel_mouse_face (emacsframe);
5375 }
5376 }
5377 #endif
5378
5379 ns_send_appdefined (-1);
5380 }
5381
5382
5383 - (void)windowDidBecomeKey: (NSNotification *)notification
5384 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5385 {
5386 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5387 struct frame *old_focus = dpyinfo->x_focus_frame;
5388
5389 NSTRACE (windowDidBecomeKey);
5390
5391 if (emacsframe != old_focus)
5392 dpyinfo->x_focus_frame = emacsframe;
5393
5394 ns_frame_rehighlight (emacsframe);
5395
5396 if (emacs_event)
5397 {
5398 emacs_event->kind = FOCUS_IN_EVENT;
5399 EV_TRAILER ((id)nil);
5400 }
5401 }
5402
5403
5404 - (void)windowDidResignKey: (NSNotification *)notification
5405 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5406 {
5407 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5408 NSTRACE (windowDidResignKey);
5409
5410 if (dpyinfo->x_focus_frame == emacsframe)
5411 dpyinfo->x_focus_frame = 0;
5412
5413 ns_frame_rehighlight (emacsframe);
5414
5415 /* FIXME: for some reason needed on second and subsequent clicks away
5416 from sole-frame Emacs to get hollow box to show */
5417 if (!windowClosing && [[self window] isVisible] == YES)
5418 {
5419 x_update_cursor (emacsframe, 1);
5420 x_set_frame_alpha (emacsframe);
5421 }
5422
5423 if (emacs_event)
5424 {
5425 [self deleteWorkingText];
5426 emacs_event->kind = FOCUS_IN_EVENT;
5427 EV_TRAILER ((id)nil);
5428 }
5429 }
5430
5431
5432 - (void)windowWillMiniaturize: sender
5433 {
5434 NSTRACE (windowWillMiniaturize);
5435 }
5436
5437
5438 - (BOOL)isFlipped
5439 {
5440 return YES;
5441 }
5442
5443
5444 - (BOOL)isOpaque
5445 {
5446 return NO;
5447 }
5448
5449
5450 - initFrameFromEmacs: (struct frame *)f
5451 {
5452 NSRect r, wr;
5453 Lisp_Object tem;
5454 NSWindow *win;
5455 NSButton *toggleButton;
5456 NSSize sz;
5457 NSColor *col;
5458 NSString *name;
5459
5460 NSTRACE (initFrameFromEmacs);
5461
5462 windowClosing = NO;
5463 processingCompose = NO;
5464 scrollbarsNeedingUpdate = 0;
5465
5466 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
5467
5468 ns_userRect = NSMakeRect (0, 0, 0, 0);
5469 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
5470 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
5471 [self initWithFrame: r];
5472 [self setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
5473
5474 FRAME_NS_VIEW (f) = self;
5475 emacsframe = f;
5476 old_title = 0;
5477
5478 win = [[EmacsWindow alloc]
5479 initWithContentRect: r
5480 styleMask: (NSResizableWindowMask |
5481 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
5482 NSTitledWindowMask |
5483 #endif
5484 NSMiniaturizableWindowMask |
5485 NSClosableWindowMask)
5486 backing: NSBackingStoreBuffered
5487 defer: YES];
5488
5489 wr = [win frame];
5490 f->border_width = wr.size.width - r.size.width;
5491 FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
5492
5493 [win setAcceptsMouseMovedEvents: YES];
5494 [win setDelegate: self];
5495 [win useOptimizedDrawing: YES];
5496
5497 sz.width = FRAME_COLUMN_WIDTH (f);
5498 sz.height = FRAME_LINE_HEIGHT (f);
5499 [win setResizeIncrements: sz];
5500
5501 [[win contentView] addSubview: self];
5502
5503 if (ns_drag_types)
5504 [self registerForDraggedTypes: ns_drag_types];
5505
5506 tem = f->name;
5507 name = [NSString stringWithUTF8String:
5508 NILP (tem) ? "Emacs" : SSDATA (tem)];
5509 [win setTitle: name];
5510
5511 /* toolbar support */
5512 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
5513 [NSString stringWithFormat: @"Emacs Frame %d",
5514 ns_window_num]];
5515 [win setToolbar: toolbar];
5516 [toolbar setVisible: NO];
5517 #ifdef NS_IMPL_COCOA
5518 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
5519 [toggleButton setTarget: self];
5520 [toggleButton setAction: @selector (toggleToolbar: )];
5521 #endif
5522 FRAME_TOOLBAR_HEIGHT (f) = 0;
5523
5524 tem = f->icon_name;
5525 if (!NILP (tem))
5526 [win setMiniwindowTitle:
5527 [NSString stringWithUTF8String: SSDATA (tem)]];
5528
5529 {
5530 NSScreen *screen = [win screen];
5531
5532 if (screen != 0)
5533 [win setFrameTopLeftPoint: NSMakePoint
5534 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
5535 IN_BOUND (-SCREENMAX,
5536 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
5537 }
5538
5539 [win makeFirstResponder: self];
5540
5541 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5542 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
5543 [win setBackgroundColor: col];
5544 if ([col alphaComponent] != 1.0)
5545 [win setOpaque: NO];
5546
5547 [self allocateGState];
5548
5549 [NSApp registerServicesMenuSendTypes: ns_send_types
5550 returnTypes: nil];
5551
5552 ns_window_num++;
5553 return self;
5554 }
5555
5556
5557 - (void)windowDidMove: sender
5558 {
5559 NSWindow *win = [self window];
5560 NSRect r = [win frame];
5561 NSArray *screens = [NSScreen screens];
5562 NSScreen *screen = [screens objectAtIndex: 0];
5563
5564 NSTRACE (windowDidMove);
5565
5566 if (!emacsframe->output_data.ns)
5567 return;
5568 if (screen != nil)
5569 {
5570 emacsframe->left_pos = r.origin.x;
5571 emacsframe->top_pos =
5572 [screen frame].size.height - (r.origin.y + r.size.height);
5573 }
5574 }
5575
5576
5577 /* Called AFTER method below, but before our windowWillResize call there leads
5578 to windowDidResize -> x_set_window_size. Update emacs' notion of frame
5579 location so set_window_size moves the frame. */
5580 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
5581 {
5582 emacsframe->output_data.ns->zooming = 1;
5583 return YES;
5584 }
5585
5586
5587 /* Override to do something slightly nonstandard, but nice. First click on
5588 zoom button will zoom vertically. Second will zoom completely. Third
5589 returns to original. */
5590 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
5591 defaultFrame:(NSRect)defaultFrame
5592 {
5593 NSRect result = [sender frame];
5594
5595 NSTRACE (windowWillUseStandardFrame);
5596
5597 if (abs (defaultFrame.size.height - result.size.height)
5598 > FRAME_LINE_HEIGHT (emacsframe))
5599 {
5600 /* first click */
5601 ns_userRect = result;
5602 result.size.height = defaultFrame.size.height;
5603 result.origin.y = defaultFrame.origin.y;
5604 }
5605 else
5606 {
5607 if (abs (defaultFrame.size.width - result.size.width)
5608 > FRAME_COLUMN_WIDTH (emacsframe))
5609 result = defaultFrame; /* second click */
5610 else
5611 {
5612 /* restore */
5613 result = ns_userRect.size.height ? ns_userRect : result;
5614 ns_userRect = NSMakeRect (0, 0, 0, 0);
5615 }
5616 }
5617
5618 [self windowWillResize: sender toSize: result.size];
5619 return result;
5620 }
5621
5622
5623 - (void)windowDidDeminiaturize: sender
5624 {
5625 NSTRACE (windowDidDeminiaturize);
5626 if (!emacsframe->output_data.ns)
5627 return;
5628 emacsframe->async_iconified = 0;
5629 emacsframe->async_visible = 1;
5630 windows_or_buffers_changed++;
5631
5632 if (emacs_event)
5633 {
5634 emacs_event->kind = ICONIFY_EVENT;
5635 EV_TRAILER ((id)nil);
5636 }
5637 }
5638
5639
5640 - (void)windowDidExpose: sender
5641 {
5642 NSTRACE (windowDidExpose);
5643 if (!emacsframe->output_data.ns)
5644 return;
5645 emacsframe->async_visible = 1;
5646 SET_FRAME_GARBAGED (emacsframe);
5647
5648 if (send_appdefined)
5649 ns_send_appdefined (-1);
5650 }
5651
5652
5653 - (void)windowDidMiniaturize: sender
5654 {
5655 NSTRACE (windowDidMiniaturize);
5656 if (!emacsframe->output_data.ns)
5657 return;
5658
5659 emacsframe->async_iconified = 1;
5660 emacsframe->async_visible = 0;
5661
5662 if (emacs_event)
5663 {
5664 emacs_event->kind = ICONIFY_EVENT;
5665 EV_TRAILER ((id)nil);
5666 }
5667 }
5668
5669
5670 - (void)mouseEntered: (NSEvent *)theEvent
5671 {
5672 NSTRACE (mouseEntered);
5673 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5674 }
5675
5676
5677 - (void)mouseExited: (NSEvent *)theEvent
5678 {
5679 Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
5680
5681 NSTRACE (mouseExited);
5682
5683 if (!hlinfo)
5684 return;
5685
5686 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5687
5688 if (emacsframe == hlinfo->mouse_face_mouse_frame)
5689 {
5690 clear_mouse_face (hlinfo);
5691 hlinfo->mouse_face_mouse_frame = 0;
5692 }
5693 }
5694
5695
5696 - menuDown: sender
5697 {
5698 NSTRACE (menuDown);
5699 if (context_menu_value == -1)
5700 context_menu_value = [sender tag];
5701 else
5702 {
5703 NSInteger tag = [sender tag];
5704 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
5705 emacsframe->menu_bar_vector,
5706 (void *)tag);
5707 }
5708
5709 ns_send_appdefined (-1);
5710 return self;
5711 }
5712
5713
5714 - (EmacsToolbar *)toolbar
5715 {
5716 return toolbar;
5717 }
5718
5719
5720 /* this gets called on toolbar button click */
5721 - toolbarClicked: (id)item
5722 {
5723 NSEvent *theEvent;
5724 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
5725
5726 NSTRACE (toolbarClicked);
5727
5728 if (!emacs_event)
5729 return self;
5730
5731 /* send first event (for some reason two needed) */
5732 theEvent = [[self window] currentEvent];
5733 emacs_event->kind = TOOL_BAR_EVENT;
5734 XSETFRAME (emacs_event->arg, emacsframe);
5735 EV_TRAILER (theEvent);
5736
5737 emacs_event->kind = TOOL_BAR_EVENT;
5738 /* XSETINT (emacs_event->code, 0); */
5739 emacs_event->arg = AREF (emacsframe->tool_bar_items,
5740 idx + TOOL_BAR_ITEM_KEY);
5741 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5742 EV_TRAILER (theEvent);
5743 return self;
5744 }
5745
5746
5747 - toggleToolbar: (id)sender
5748 {
5749 if (!emacs_event)
5750 return self;
5751
5752 emacs_event->kind = NS_NONKEY_EVENT;
5753 emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
5754 EV_TRAILER ((id)nil);
5755 return self;
5756 }
5757
5758
5759 - (void)drawRect: (NSRect)rect
5760 {
5761 int x = NSMinX (rect), y = NSMinY (rect);
5762 int width = NSWidth (rect), height = NSHeight (rect);
5763
5764 NSTRACE (drawRect);
5765
5766 if (!emacsframe || !emacsframe->output_data.ns || ns_in_resize)
5767 return;
5768
5769 ns_clear_frame_area (emacsframe, x, y, width, height);
5770 expose_frame (emacsframe, x, y, width, height);
5771
5772 /*
5773 drawRect: may be called (at least in OS X 10.5) for invisible
5774 views as well for some reason. Thus, do not infer visibility
5775 here.
5776
5777 emacsframe->async_visible = 1;
5778 emacsframe->async_iconified = 0;
5779 */
5780 }
5781
5782
5783 /* NSDraggingDestination protocol methods. Actually this is not really a
5784 protocol, but a category of Object. O well... */
5785
5786 -(NSUInteger) draggingEntered: (id <NSDraggingInfo>) sender
5787 {
5788 NSTRACE (draggingEntered);
5789 return NSDragOperationGeneric;
5790 }
5791
5792
5793 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
5794 {
5795 return YES;
5796 }
5797
5798
5799 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
5800 {
5801 id pb;
5802 int x, y;
5803 NSString *type;
5804 NSEvent *theEvent = [[self window] currentEvent];
5805 NSPoint position;
5806
5807 NSTRACE (performDragOperation);
5808
5809 if (!emacs_event)
5810 return NO;
5811
5812 position = [self convertPoint: [sender draggingLocation] fromView: nil];
5813 x = lrint (position.x); y = lrint (position.y);
5814
5815 pb = [sender draggingPasteboard];
5816 type = [pb availableTypeFromArray: ns_drag_types];
5817 if (type == 0)
5818 {
5819 return NO;
5820 }
5821 else if ([type isEqualToString: NSFilenamesPboardType])
5822 {
5823 NSArray *files;
5824 NSEnumerator *fenum;
5825 NSString *file;
5826
5827 if (!(files = [pb propertyListForType: type]))
5828 return NO;
5829
5830 fenum = [files objectEnumerator];
5831 while ( (file = [fenum nextObject]) )
5832 {
5833 emacs_event->kind = NS_NONKEY_EVENT;
5834 emacs_event->code = KEY_NS_DRAG_FILE;
5835 XSETINT (emacs_event->x, x);
5836 XSETINT (emacs_event->y, y);
5837 ns_input_file = append2 (ns_input_file,
5838 build_string ([file UTF8String]));
5839 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5840 EV_TRAILER (theEvent);
5841 }
5842 return YES;
5843 }
5844 else if ([type isEqualToString: NSURLPboardType])
5845 {
5846 NSString *file;
5847 NSURL *fileURL;
5848
5849 if (!(fileURL = [NSURL URLFromPasteboard: pb]) ||
5850 [fileURL isFileURL] == NO)
5851 return NO;
5852
5853 file = [fileURL path];
5854 emacs_event->kind = NS_NONKEY_EVENT;
5855 emacs_event->code = KEY_NS_DRAG_FILE;
5856 XSETINT (emacs_event->x, x);
5857 XSETINT (emacs_event->y, y);
5858 ns_input_file = append2 (ns_input_file, build_string ([file UTF8String]));
5859 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5860 EV_TRAILER (theEvent);
5861 return YES;
5862 }
5863 else if ([type isEqualToString: NSStringPboardType]
5864 || [type isEqualToString: NSTabularTextPboardType])
5865 {
5866 NSString *data;
5867
5868 if (! (data = [pb stringForType: type]))
5869 return NO;
5870
5871 emacs_event->kind = NS_NONKEY_EVENT;
5872 emacs_event->code = KEY_NS_DRAG_TEXT;
5873 XSETINT (emacs_event->x, x);
5874 XSETINT (emacs_event->y, y);
5875 ns_input_text = build_string ([data UTF8String]);
5876 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5877 EV_TRAILER (theEvent);
5878 return YES;
5879 }
5880 else if ([type isEqualToString: NSColorPboardType])
5881 {
5882 NSColor *c = [NSColor colorFromPasteboard: pb];
5883 emacs_event->kind = NS_NONKEY_EVENT;
5884 emacs_event->code = KEY_NS_DRAG_COLOR;
5885 XSETINT (emacs_event->x, x);
5886 XSETINT (emacs_event->y, y);
5887 ns_input_color = ns_color_to_lisp (c);
5888 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5889 EV_TRAILER (theEvent);
5890 return YES;
5891 }
5892 else if ([type isEqualToString: NSFontPboardType])
5893 {
5894 /* impl based on GNUstep NSTextView.m */
5895 NSData *data = [pb dataForType: NSFontPboardType];
5896 NSDictionary *dict = [NSUnarchiver unarchiveObjectWithData: data];
5897 NSFont *font = [dict objectForKey: NSFontAttributeName];
5898 char fontSize[10];
5899
5900 if (font == nil)
5901 return NO;
5902
5903 emacs_event->kind = NS_NONKEY_EVENT;
5904 emacs_event->code = KEY_NS_CHANGE_FONT;
5905 XSETINT (emacs_event->x, x);
5906 XSETINT (emacs_event->y, y);
5907 ns_input_font = build_string ([[font fontName] UTF8String]);
5908 snprintf (fontSize, 10, "%f", [font pointSize]);
5909 ns_input_fontsize = build_string (fontSize);
5910 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5911 EV_TRAILER (theEvent);
5912 return YES;
5913 }
5914 else
5915 {
5916 error ("Invalid data type in dragging pasteboard.");
5917 return NO;
5918 }
5919 }
5920
5921
5922 - (id) validRequestorForSendType: (NSString *)typeSent
5923 returnType: (NSString *)typeReturned
5924 {
5925 NSTRACE (validRequestorForSendType);
5926 if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
5927 && typeReturned == nil)
5928 {
5929 if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
5930 return self;
5931 }
5932
5933 return [super validRequestorForSendType: typeSent
5934 returnType: typeReturned];
5935 }
5936
5937
5938 /* The next two methods are part of NSServicesRequests informal protocol,
5939 supposedly called when a services menu item is chosen from this app.
5940 But this should not happen because we override the services menu with our
5941 own entries which call ns-perform-service.
5942 Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
5943 So let's at least stub them out until further investigation can be done. */
5944
5945 - (BOOL) readSelectionFromPasteboard: (NSPasteboard *)pb
5946 {
5947 /* we could call ns_string_from_pasteboard(pboard) here but then it should
5948 be written into the buffer in place of the existing selection..
5949 ordinary service calls go through functions defined in ns-win.el */
5950 return NO;
5951 }
5952
5953 - (BOOL) writeSelectionToPasteboard: (NSPasteboard *)pb types: (NSArray *)types
5954 {
5955 NSArray *typesDeclared;
5956 Lisp_Object val;
5957
5958 /* We only support NSStringPboardType */
5959 if ([types containsObject:NSStringPboardType] == NO) {
5960 return NO;
5961 }
5962
5963 val = ns_get_local_selection (QPRIMARY, QUTF8_STRING);
5964 if (CONSP (val) && SYMBOLP (XCAR (val)))
5965 {
5966 val = XCDR (val);
5967 if (CONSP (val) && NILP (XCDR (val)))
5968 val = XCAR (val);
5969 }
5970 if (! STRINGP (val))
5971 return NO;
5972
5973 typesDeclared = [NSArray arrayWithObject:NSStringPboardType];
5974 [pb declareTypes:typesDeclared owner:nil];
5975 ns_string_to_pasteboard (pb, val);
5976 return YES;
5977 }
5978
5979
5980 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
5981 (gives a miniaturized version of the window); currently we use the latter for
5982 frames whose active buffer doesn't correspond to any file
5983 (e.g., '*scratch*') */
5984 - setMiniwindowImage: (BOOL) setMini
5985 {
5986 id image = [[self window] miniwindowImage];
5987 NSTRACE (setMiniwindowImage);
5988
5989 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
5990 about "AppleDockIconEnabled" notwithstanding, however the set message
5991 below has its effect nonetheless. */
5992 if (image != emacsframe->output_data.ns->miniimage)
5993 {
5994 if (image && [image isKindOfClass: [EmacsImage class]])
5995 [image release];
5996 [[self window] setMiniwindowImage:
5997 setMini ? emacsframe->output_data.ns->miniimage : nil];
5998 }
5999
6000 return self;
6001 }
6002
6003
6004 - (void) setRows: (int) r andColumns: (int) c
6005 {
6006 rows = r;
6007 cols = c;
6008 }
6009
6010 @end /* EmacsView */
6011
6012
6013
6014 /* ==========================================================================
6015
6016 EmacsWindow implementation
6017
6018 ========================================================================== */
6019
6020 @implementation EmacsWindow
6021
6022 /* If we have multiple monitors, one above the other, we don't want to
6023 restrict the height to just one monitor. So we override this. */
6024 - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
6025 {
6026 /* When making the frame visible for the first time or if there is just
6027 one screen, we want to constrain. Other times not. */
6028 NSUInteger nr_screens = [[NSScreen screens] count];
6029 struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
6030 NSTRACE (constrainFrameRect);
6031
6032 if (nr_screens == 1)
6033 return [super constrainFrameRect:frameRect toScreen:screen];
6034
6035 if (f->output_data.ns->dont_constrain
6036 || ns_menu_bar_should_be_hidden ())
6037 return frameRect;
6038
6039 f->output_data.ns->dont_constrain = 1;
6040 return [super constrainFrameRect:frameRect toScreen:screen];
6041 }
6042
6043
6044 /* called only on resize clicks by special case in EmacsApp-sendEvent */
6045 - (void)mouseDown: (NSEvent *)theEvent
6046 {
6047 if (ns_in_resize)
6048 {
6049 NSSize size = [[theEvent window] frame].size;
6050 grabOffset = [theEvent locationInWindow];
6051 grabOffset.x = size.width - grabOffset.x;
6052 }
6053 else
6054 [super mouseDown: theEvent];
6055 }
6056
6057
6058 /* stop resizing */
6059 - (void)mouseUp: (NSEvent *)theEvent
6060 {
6061 if (ns_in_resize)
6062 {
6063 struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
6064 ns_in_resize = NO;
6065 ns_set_name_as_filename (f);
6066 [self display];
6067 ns_send_appdefined (-1);
6068 }
6069 else
6070 [super mouseUp: theEvent];
6071 }
6072
6073
6074 /* send resize events */
6075 - (void)mouseDragged: (NSEvent *)theEvent
6076 {
6077 if (ns_in_resize)
6078 {
6079 NSPoint p = [theEvent locationInWindow];
6080 NSSize size, vettedSize, origSize = [self frame].size;
6081
6082 size.width = p.x + grabOffset.x;
6083 size.height = origSize.height - p.y + grabOffset.y;
6084
6085 if (size.width == origSize.width && size.height == origSize.height)
6086 return;
6087
6088 vettedSize = [[self delegate] windowWillResize: self toSize: size];
6089 [[NSNotificationCenter defaultCenter]
6090 postNotificationName: NSWindowDidResizeNotification
6091 object: self];
6092 }
6093 else
6094 [super mouseDragged: theEvent];
6095 }
6096
6097 @end /* EmacsWindow */
6098
6099
6100 /* ==========================================================================
6101
6102 EmacsScroller implementation
6103
6104 ========================================================================== */
6105
6106
6107 @implementation EmacsScroller
6108
6109 /* for repeat button push */
6110 #define SCROLL_BAR_FIRST_DELAY 0.5
6111 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
6112
6113 + (CGFloat) scrollerWidth
6114 {
6115 /* TODO: if we want to allow variable widths, this is the place to do it,
6116 however neither GNUstep nor Cocoa support it very well */
6117 return [NSScroller scrollerWidth];
6118 }
6119
6120
6121 - initFrame: (NSRect )r window: (Lisp_Object)nwin
6122 {
6123 NSTRACE (EmacsScroller_initFrame);
6124
6125 r.size.width = [EmacsScroller scrollerWidth];
6126 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
6127 [self setContinuous: YES];
6128 [self setEnabled: YES];
6129
6130 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
6131 locked against the top and bottom edges, and right edge on OS X, where
6132 scrollers are on right. */
6133 #ifdef NS_IMPL_GNUSTEP
6134 [self setAutoresizingMask: NSViewMaxXMargin | NSViewHeightSizable];
6135 #else
6136 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
6137 #endif
6138
6139 win = nwin;
6140 condemned = NO;
6141 pixel_height = NSHeight (r);
6142 if (pixel_height == 0) pixel_height = 1;
6143 min_portion = 20 / pixel_height;
6144
6145 frame = XFRAME (XWINDOW (win)->frame);
6146 if (FRAME_LIVE_P (frame))
6147 {
6148 int i;
6149 EmacsView *view = FRAME_NS_VIEW (frame);
6150 NSView *sview = [[view window] contentView];
6151 NSArray *subs = [sview subviews];
6152
6153 /* disable optimization stopping redraw of other scrollbars */
6154 view->scrollbarsNeedingUpdate = 0;
6155 for (i =[subs count]-1; i >= 0; i--)
6156 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
6157 view->scrollbarsNeedingUpdate++;
6158 [sview addSubview: self];
6159 }
6160
6161 /* [self setFrame: r]; */
6162
6163 return self;
6164 }
6165
6166
6167 - (void)setFrame: (NSRect)newRect
6168 {
6169 NSTRACE (EmacsScroller_setFrame);
6170 /* BLOCK_INPUT; */
6171 pixel_height = NSHeight (newRect);
6172 if (pixel_height == 0) pixel_height = 1;
6173 min_portion = 20 / pixel_height;
6174 [super setFrame: newRect];
6175 [self display];
6176 /* UNBLOCK_INPUT; */
6177 }
6178
6179
6180 - (void)dealloc
6181 {
6182 NSTRACE (EmacsScroller_dealloc);
6183 if (!NILP (win))
6184 XWINDOW (win)->vertical_scroll_bar = Qnil;
6185 [super dealloc];
6186 }
6187
6188
6189 - condemn
6190 {
6191 NSTRACE (condemn);
6192 condemned =YES;
6193 return self;
6194 }
6195
6196
6197 - reprieve
6198 {
6199 NSTRACE (reprieve);
6200 condemned =NO;
6201 return self;
6202 }
6203
6204
6205 - judge
6206 {
6207 NSTRACE (judge);
6208 if (condemned)
6209 {
6210 EmacsView *view;
6211 BLOCK_INPUT;
6212 /* ensure other scrollbar updates after deletion */
6213 view = (EmacsView *)FRAME_NS_VIEW (frame);
6214 if (view != nil)
6215 view->scrollbarsNeedingUpdate++;
6216 [self removeFromSuperview];
6217 [self release];
6218 UNBLOCK_INPUT;
6219 }
6220 return self;
6221 }
6222
6223
6224 - (void)resetCursorRects
6225 {
6226 NSRect visible = [self visibleRect];
6227 NSTRACE (resetCursorRects);
6228
6229 if (!NSIsEmptyRect (visible))
6230 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
6231 [[NSCursor arrowCursor] setOnMouseEntered: YES];
6232 }
6233
6234
6235 - (int) checkSamePosition: (int) position portion: (int) portion
6236 whole: (int) whole
6237 {
6238 return em_position ==position && em_portion ==portion && em_whole ==whole
6239 && portion != whole; /* needed for resize empty buf */
6240 }
6241
6242
6243 - setPosition: (int)position portion: (int)portion whole: (int)whole
6244 {
6245 NSTRACE (setPosition);
6246
6247 em_position = position;
6248 em_portion = portion;
6249 em_whole = whole;
6250
6251 if (portion >= whole)
6252 {
6253 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
6254 [self setKnobProportion: 1.0];
6255 [self setDoubleValue: 1.0];
6256 #else
6257 [self setFloatValue: 0.0 knobProportion: 1.0];
6258 #endif
6259 }
6260 else
6261 {
6262 float pos, por;
6263 portion = max ((float)whole*min_portion/pixel_height, portion);
6264 pos = (float)position / (whole - portion);
6265 por = (float)portion/whole;
6266 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
6267 [self setKnobProportion: por];
6268 [self setDoubleValue: pos];
6269 #else
6270 [self setFloatValue: pos knobProportion: por];
6271 #endif
6272 }
6273 return self;
6274 }
6275
6276 /* FIXME: unused at moment (see ns_mouse_position) at the moment because
6277 drag events will go directly to the EmacsScroller. Leaving in for now. */
6278 -(void)getMouseMotionPart: (int *)part window: (Lisp_Object *)window
6279 x: (Lisp_Object *)x y: ( Lisp_Object *)y
6280 {
6281 *part = last_hit_part;
6282 *window = win;
6283 XSETINT (*y, pixel_height);
6284 if ([self floatValue] > 0.999)
6285 XSETINT (*x, pixel_height);
6286 else
6287 XSETINT (*x, pixel_height * [self floatValue]);
6288 }
6289
6290
6291 /* set up emacs_event */
6292 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
6293 {
6294 if (!emacs_event)
6295 return;
6296
6297 emacs_event->part = last_hit_part;
6298 emacs_event->code = 0;
6299 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
6300 emacs_event->frame_or_window = win;
6301 emacs_event->timestamp = EV_TIMESTAMP (e);
6302 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
6303 emacs_event->arg = Qnil;
6304 XSETINT (emacs_event->x, loc * pixel_height);
6305 XSETINT (emacs_event->y, pixel_height-20);
6306
6307 n_emacs_events_pending++;
6308 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
6309 EVENT_INIT (*emacs_event);
6310 ns_send_appdefined (-1);
6311 }
6312
6313
6314 /* called manually thru timer to implement repeated button action w/hold-down */
6315 - repeatScroll: (NSTimer *)scrollEntry
6316 {
6317 NSEvent *e = [[self window] currentEvent];
6318 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
6319 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
6320
6321 /* clear timer if need be */
6322 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
6323 {
6324 [scroll_repeat_entry invalidate];
6325 [scroll_repeat_entry release];
6326 scroll_repeat_entry = nil;
6327
6328 if (inKnob)
6329 return self;
6330
6331 scroll_repeat_entry
6332 = [[NSTimer scheduledTimerWithTimeInterval:
6333 SCROLL_BAR_CONTINUOUS_DELAY
6334 target: self
6335 selector: @selector (repeatScroll:)
6336 userInfo: 0
6337 repeats: YES]
6338 retain];
6339 }
6340
6341 [self sendScrollEventAtLoc: 0 fromEvent: e];
6342 return self;
6343 }
6344
6345
6346 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
6347 mouseDragged events without going into a modal loop. */
6348 - (void)mouseDown: (NSEvent *)e
6349 {
6350 NSRect sr, kr;
6351 /* hitPart is only updated AFTER event is passed on */
6352 NSScrollerPart part = [self testPart: [e locationInWindow]];
6353 double inc = 0.0, loc, kloc, pos;
6354 int edge = 0;
6355
6356 NSTRACE (EmacsScroller_mouseDown);
6357
6358 switch (part)
6359 {
6360 case NSScrollerDecrementPage:
6361 last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
6362 case NSScrollerIncrementPage:
6363 last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
6364 case NSScrollerDecrementLine:
6365 last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
6366 case NSScrollerIncrementLine:
6367 last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
6368 case NSScrollerKnob:
6369 last_hit_part = scroll_bar_handle; break;
6370 case NSScrollerKnobSlot: /* GNUstep-only */
6371 last_hit_part = scroll_bar_move_ratio; break;
6372 default: /* NSScrollerNoPart? */
6373 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %ld\n",
6374 (long) part);
6375 return;
6376 }
6377
6378 if (inc != 0.0)
6379 {
6380 pos = 0; /* ignored */
6381
6382 /* set a timer to repeat, as we can't let superclass do this modally */
6383 scroll_repeat_entry
6384 = [[NSTimer scheduledTimerWithTimeInterval: SCROLL_BAR_FIRST_DELAY
6385 target: self
6386 selector: @selector (repeatScroll:)
6387 userInfo: 0
6388 repeats: YES]
6389 retain];
6390 }
6391 else
6392 {
6393 /* handle, or on GNUstep possibly slot */
6394 NSEvent *fake_event;
6395
6396 /* compute float loc in slot and mouse offset on knob */
6397 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6398 toView: nil];
6399 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6400 if (loc <= 0.0)
6401 {
6402 loc = 0.0;
6403 edge = -1;
6404 }
6405 else if (loc >= NSHeight (sr))
6406 {
6407 loc = NSHeight (sr);
6408 edge = 1;
6409 }
6410
6411 if (edge)
6412 kloc = 0.5 * edge;
6413 else
6414 {
6415 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
6416 toView: nil];
6417 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
6418 }
6419 last_mouse_offset = kloc;
6420
6421 /* if knob, tell emacs a location offset by knob pos
6422 (to indicate top of handle) */
6423 if (part == NSScrollerKnob)
6424 pos = (loc - last_mouse_offset) / NSHeight (sr);
6425 else
6426 /* else this is a slot click on GNUstep: go straight there */
6427 pos = loc / NSHeight (sr);
6428
6429 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
6430 fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
6431 location: [e locationInWindow]
6432 modifierFlags: [e modifierFlags]
6433 timestamp: [e timestamp]
6434 windowNumber: [e windowNumber]
6435 context: [e context]
6436 eventNumber: [e eventNumber]
6437 clickCount: [e clickCount]
6438 pressure: [e pressure]];
6439 [super mouseUp: fake_event];
6440 }
6441
6442 if (part != NSScrollerKnob)
6443 [self sendScrollEventAtLoc: pos fromEvent: e];
6444 }
6445
6446
6447 /* Called as we manually track scroller drags, rather than superclass. */
6448 - (void)mouseDragged: (NSEvent *)e
6449 {
6450 NSRect sr;
6451 double loc, pos;
6452 int edge = 0;
6453
6454 NSTRACE (EmacsScroller_mouseDragged);
6455
6456 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6457 toView: nil];
6458 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6459
6460 if (loc <= 0.0)
6461 {
6462 loc = 0.0;
6463 edge = -1;
6464 }
6465 else if (loc >= NSHeight (sr) + last_mouse_offset)
6466 {
6467 loc = NSHeight (sr) + last_mouse_offset;
6468 edge = 1;
6469 }
6470
6471 pos = /*(edge ? loc :*/ (loc - last_mouse_offset) / NSHeight (sr);
6472 [self sendScrollEventAtLoc: pos fromEvent: e];
6473 }
6474
6475
6476 - (void)mouseUp: (NSEvent *)e
6477 {
6478 if (scroll_repeat_entry)
6479 {
6480 [scroll_repeat_entry invalidate];
6481 [scroll_repeat_entry release];
6482 scroll_repeat_entry = nil;
6483 }
6484 last_hit_part = 0;
6485 }
6486
6487
6488 /* treat scrollwheel events in the bar as though they were in the main window */
6489 - (void) scrollWheel: (NSEvent *)theEvent
6490 {
6491 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
6492 [view mouseDown: theEvent];
6493 }
6494
6495 @end /* EmacsScroller */
6496
6497
6498
6499
6500 /* ==========================================================================
6501
6502 Font-related functions; these used to be in nsfaces.m
6503
6504 ========================================================================== */
6505
6506
6507 Lisp_Object
6508 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
6509 {
6510 struct font *font = XFONT_OBJECT (font_object);
6511
6512 if (fontset < 0)
6513 fontset = fontset_from_font (font_object);
6514 FRAME_FONTSET (f) = fontset;
6515
6516 if (FRAME_FONT (f) == font)
6517 /* This font is already set in frame F. There's nothing more to
6518 do. */
6519 return font_object;
6520
6521 FRAME_FONT (f) = font;
6522
6523 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
6524 FRAME_COLUMN_WIDTH (f) = font->average_width;
6525 FRAME_SPACE_WIDTH (f) = font->space_width;
6526 FRAME_LINE_HEIGHT (f) = font->height;
6527
6528 compute_fringe_widths (f, 1);
6529
6530 /* Compute the scroll bar width in character columns. */
6531 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
6532 {
6533 int wid = FRAME_COLUMN_WIDTH (f);
6534 FRAME_CONFIG_SCROLL_BAR_COLS (f)
6535 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
6536 }
6537 else
6538 {
6539 int wid = FRAME_COLUMN_WIDTH (f);
6540 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
6541 }
6542
6543 /* Now make the frame display the given font. */
6544 if (FRAME_NS_WINDOW (f) != 0)
6545 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
6546
6547 return font_object;
6548 }
6549
6550
6551 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
6552 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
6553 in 1.43. */
6554
6555 const char *
6556 ns_xlfd_to_fontname (const char *xlfd)
6557 /* --------------------------------------------------------------------------
6558 Convert an X font name (XLFD) to an NS font name.
6559 Only family is used.
6560 The string returned is temporarily allocated.
6561 -------------------------------------------------------------------------- */
6562 {
6563 char *name = xmalloc (180);
6564 int i, len;
6565 const char *ret;
6566
6567 if (!strncmp (xlfd, "--", 2))
6568 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
6569 else
6570 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
6571
6572 /* stopgap for malformed XLFD input */
6573 if (strlen (name) == 0)
6574 strcpy (name, "Monaco");
6575
6576 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
6577 also uppercase after '-' or ' ' */
6578 name[0] = toupper (name[0]);
6579 for (len =strlen (name), i =0; i<len; i++)
6580 {
6581 if (name[i] == '$')
6582 {
6583 name[i] = '-';
6584 if (i+1<len)
6585 name[i+1] = toupper (name[i+1]);
6586 }
6587 else if (name[i] == '_')
6588 {
6589 name[i] = ' ';
6590 if (i+1<len)
6591 name[i+1] = toupper (name[i+1]);
6592 }
6593 }
6594 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
6595 ret = [[NSString stringWithUTF8String: name] UTF8String];
6596 xfree (name);
6597 return ret;
6598 }
6599
6600
6601 void
6602 syms_of_nsterm (void)
6603 {
6604 NSTRACE (syms_of_nsterm);
6605
6606 ns_antialias_threshold = 10.0;
6607
6608 /* from 23+ we need to tell emacs what modifiers there are.. */
6609 DEFSYM (Qmodifier_value, "modifier-value");
6610 DEFSYM (Qalt, "alt");
6611 DEFSYM (Qhyper, "hyper");
6612 DEFSYM (Qmeta, "meta");
6613 DEFSYM (Qsuper, "super");
6614 DEFSYM (Qcontrol, "control");
6615 DEFSYM (Qnone, "none");
6616 DEFSYM (QUTF8_STRING, "UTF8_STRING");
6617
6618 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
6619 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
6620 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
6621 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
6622 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
6623
6624 DEFVAR_LISP ("ns-input-file", ns_input_file,
6625 "The file specified in the last NS event.");
6626 ns_input_file =Qnil;
6627
6628 DEFVAR_LISP ("ns-input-text", ns_input_text,
6629 "The data received in the last NS text drag event.");
6630 ns_input_text =Qnil;
6631
6632 DEFVAR_LISP ("ns-working-text", ns_working_text,
6633 "String for visualizing working composition sequence.");
6634 ns_working_text =Qnil;
6635
6636 DEFVAR_LISP ("ns-input-font", ns_input_font,
6637 "The font specified in the last NS event.");
6638 ns_input_font =Qnil;
6639
6640 DEFVAR_LISP ("ns-input-fontsize", ns_input_fontsize,
6641 "The fontsize specified in the last NS event.");
6642 ns_input_fontsize =Qnil;
6643
6644 DEFVAR_LISP ("ns-input-line", ns_input_line,
6645 "The line specified in the last NS event.");
6646 ns_input_line =Qnil;
6647
6648 DEFVAR_LISP ("ns-input-color", ns_input_color,
6649 "The color specified in the last NS event.");
6650 ns_input_color =Qnil;
6651
6652 DEFVAR_LISP ("ns-input-spi-name", ns_input_spi_name,
6653 "The service name specified in the last NS event.");
6654 ns_input_spi_name =Qnil;
6655
6656 DEFVAR_LISP ("ns-input-spi-arg", ns_input_spi_arg,
6657 "The service argument specified in the last NS event.");
6658 ns_input_spi_arg =Qnil;
6659
6660 DEFVAR_LISP ("ns-alternate-modifier", ns_alternate_modifier,
6661 "This variable describes the behavior of the alternate or option key.\n\
6662 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6663 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6664 at all, allowing it to be used at a lower level for accented character entry.");
6665 ns_alternate_modifier = Qmeta;
6666
6667 DEFVAR_LISP ("ns-right-alternate-modifier", ns_right_alternate_modifier,
6668 "This variable describes the behavior of the right alternate or option key.\n\
6669 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6670 Set to left means be the same key as `ns-alternate-modifier'.\n\
6671 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6672 at all, allowing it to be used at a lower level for accented character entry.");
6673 ns_right_alternate_modifier = Qleft;
6674
6675 DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
6676 "This variable describes the behavior of the command key.\n\
6677 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6678 ns_command_modifier = Qsuper;
6679
6680 DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
6681 "This variable describes the behavior of the right command key.\n\
6682 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6683 Set to left means be the same key as `ns-command-modifier'.\n\
6684 Set to none means that the command / option key is not interpreted by Emacs\n\
6685 at all, allowing it to be used at a lower level for accented character entry.");
6686 ns_right_command_modifier = Qleft;
6687
6688 DEFVAR_LISP ("ns-control-modifier", ns_control_modifier,
6689 "This variable describes the behavior of the control key.\n\
6690 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6691 ns_control_modifier = Qcontrol;
6692
6693 DEFVAR_LISP ("ns-right-control-modifier", ns_right_control_modifier,
6694 "This variable describes the behavior of the right control key.\n\
6695 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6696 Set to left means be the same key as `ns-control-modifier'.\n\
6697 Set to none means that the control / option key is not interpreted by Emacs\n\
6698 at all, allowing it to be used at a lower level for accented character entry.");
6699 ns_right_control_modifier = Qleft;
6700
6701 DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
6702 "This variable describes the behavior of the function key (on laptops).\n\
6703 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6704 Set to none means that the function key is not interpreted by Emacs at all,\n\
6705 allowing it to be used at a lower level for accented character entry.");
6706 ns_function_modifier = Qnone;
6707
6708 DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
6709 "Non-nil (the default) means to render text antialiased. Only has an effect on OS X Panther and above.");
6710 ns_antialias_text = Qt;
6711
6712 DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
6713 "Whether to confirm application quit using dialog.");
6714 ns_confirm_quit = Qnil;
6715
6716 staticpro (&ns_display_name_list);
6717 ns_display_name_list = Qnil;
6718
6719 staticpro (&last_mouse_motion_frame);
6720 last_mouse_motion_frame = Qnil;
6721
6722 DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
6723 doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
6724 Only works on OSX 10.6 or later. */);
6725 ns_auto_hide_menu_bar = Qnil;
6726
6727 /* TODO: move to common code */
6728 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
6729 doc: /* Which toolkit scroll bars Emacs uses, if any.
6730 A value of nil means Emacs doesn't use toolkit scroll bars.
6731 With the X Window system, the value is a symbol describing the
6732 X toolkit. Possible values are: gtk, motif, xaw, or xaw3d.
6733 With MS Windows or Nextstep, the value is t. */);
6734 Vx_toolkit_scroll_bars = Qt;
6735
6736 DEFVAR_BOOL ("x-use-underline-position-properties",
6737 x_use_underline_position_properties,
6738 doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
6739 A value of nil means ignore them. If you encounter fonts with bogus
6740 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
6741 to 4.1, set this to nil. */);
6742 x_use_underline_position_properties = 0;
6743
6744 DEFVAR_BOOL ("x-underline-at-descent-line",
6745 x_underline_at_descent_line,
6746 doc: /* Non-nil means to draw the underline at the same place as the descent line.
6747 A value of nil means to draw the underline according to the value of the
6748 variable `x-use-underline-position-properties', which is usually at the
6749 baseline level. The default value is nil. */);
6750 x_underline_at_descent_line = 0;
6751
6752 /* Tell emacs about this window system. */
6753 Fprovide (intern ("ns"), Qnil);
6754 }