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