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