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