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