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