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