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