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