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