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