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