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