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