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