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