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