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