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