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