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