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