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