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