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