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