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