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