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