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