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