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