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