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