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