* emacs.c (main): Do fork+exec under --daemon in Cocoa.
[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
3fe53a83 555 external (RIF) call; whole frame, called before update_window_begin
edfda783
AR
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
3fe53a83 574 external (RIF) call; for one window, called after update_begin
edfda783
AR
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
3fe53a83 608 external (RIF) call; for one window called before update_end
edfda783
AR
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
3fe53a83 647 external (RIF) call; for whole frame, called after update_window_end
edfda783
AR
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/* --------------------------------------------------------------------------
3fe53a83 676 external (RIF) call
edfda783
AR
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
3fe53a83 749 /* clipping */
edfda783
AR
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 791/* --------------------------------------------------------------------------
3fe53a83 792 Internal (but parallels other terms): Focus drawing on given row
edfda783
AR
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
3fe53a83
AR
1379 /* 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/* --------------------------------------------------------------------------
3fe53a83 1593 Return 1 if named color found, and set color_def rgb accordingly.
edfda783
AR
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/* --------------------------------------------------------------------------
3fe53a83 1988 External (RIF): Clear section of frame
edfda783
AR
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/* --------------------------------------------------------------------------
3fe53a83 2041 External (RIF): Insert or delete n lines at line vpos
edfda783
AR
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/* --------------------------------------------------------------------------
3fe53a83 2104 External (RIF): preparatory to fringe update after text was updated
edfda783
AR
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/* --------------------------------------------------------------------------
3fe53a83 2159 External (RIF): copy an area horizontally, don't worry about clearing src
edfda783
AR
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/* --------------------------------------------------------------------------
3fe53a83 2185 External (RIF); compute left/right overhang of whole string and set in s
edfda783
AR
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/* --------------------------------------------------------------------------
3fe53a83 2226 External (RIF); fringe-related
edfda783
AR
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.
3fe53a83 3097 From 21+ we have to manage the event buffer ourselves.
edfda783
AR
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
edfda783
AR
3448void
3449x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
3450{
3fe53a83 3451 /* XXX irrelevant under NS */
edfda783
AR
3452}
3453
3454
3455
3456/* ==========================================================================
3457
3458 Initialization
3459
3460 ========================================================================== */
3461
1ee27840
CY
3462int
3463x_display_pixel_height (dpyinfo)
3464 struct ns_display_info *dpyinfo;
3465{
3466 NSScreen *screen = [NSScreen mainScreen];
3467 return [screen frame].size.height;
3468}
3469
3470int
3471x_display_pixel_width (dpyinfo)
3472 struct ns_display_info *dpyinfo;
3473{
3474 NSScreen *screen = [NSScreen mainScreen];
3475 return [screen frame].size.width;
3476}
3477
3478
15034960 3479static Lisp_Object ns_string_to_lispmod (const char *s)
edfda783
AR
3480/* --------------------------------------------------------------------------
3481 Convert modifier name to lisp symbol
3482 -------------------------------------------------------------------------- */
3483{
3484 if (!strncmp (SDATA (SYMBOL_NAME (Qmeta)), s, 10))
3485 return Qmeta;
3486 else if (!strncmp (SDATA (SYMBOL_NAME (Qsuper)), s, 10))
3487 return Qsuper;
3488 else if (!strncmp (SDATA (SYMBOL_NAME (Qcontrol)), s, 10))
3489 return Qcontrol;
3490 else if (!strncmp (SDATA (SYMBOL_NAME (Qalt)), s, 10))
3491 return Qalt;
3492 else if (!strncmp (SDATA (SYMBOL_NAME (Qhyper)), s, 10))
3493 return Qhyper;
3494 else if (!strncmp (SDATA (SYMBOL_NAME (Qnone)), s, 10))
3495 return Qnone;
3496 else
3497 return Qnil;
3498}
3499
3500
3501static Lisp_Object ns_mod_to_lisp (int m)
3502/* --------------------------------------------------------------------------
3503 Convert modifier code (see lisp.h) to lisp symbol
3504 -------------------------------------------------------------------------- */
3505{
3506 if (m == CHAR_META)
3507 return Qmeta;
3508 else if (m == CHAR_SUPER)
3509 return Qsuper;
3510 else if (m == CHAR_CTL)
3511 return Qcontrol;
3512 else if (m == CHAR_ALT)
3513 return Qalt;
3514 else if (m == CHAR_HYPER)
3515 return Qhyper;
3516 else /* if (m == 0) */
3517 return Qnone;
3518}
3519
3520
3521static void
3522ns_set_default_prefs ()
3523/* --------------------------------------------------------------------------
3524 Initialize preference variables to defaults
3525 -------------------------------------------------------------------------- */
3526{
3527 ns_alternate_modifier = Qmeta;
3528 ns_command_modifier = Qsuper;
3529 ns_control_modifier = Qcontrol;
3530 ns_function_modifier = Qnone;
edfda783 3531 ns_expand_space = make_float (0.0);
5c976973
AR
3532 ns_antialias_text = Qt;
3533 ns_antialias_threshold = 10.0; /* not exposed to lisp side */
3534 ns_use_qd_smoothing = Qnil;
3535 ns_use_system_highlight_color = Qt;
edfda783
AR
3536}
3537
3538
3539static void
3540ns_default (const char *parameter, Lisp_Object *result,
3541 Lisp_Object yesval, Lisp_Object noval,
3542 BOOL is_float, BOOL is_modstring)
3543/* --------------------------------------------------------------------------
3544 Check a parameter value in user's preferences
3545 -------------------------------------------------------------------------- */
3546{
3547 const char *value;
3548
3549 if ( (value =[[[NSUserDefaults standardUserDefaults]
3550 stringForKey: [NSString stringWithUTF8String: parameter]]
3551 UTF8String]) )
3552 {
3553 double f;
3554 char *pos;
3555 if (strcasecmp (value, "YES") == 0)
3556 *result = yesval;
3557 else if (strcasecmp (value, "NO") == 0)
3558 *result = noval;
3559 else if (is_float && (f = strtod (value, &pos), pos != value))
3560 *result = make_float (f);
3561 else if (is_modstring && value)
3562 *result = ns_string_to_lispmod (value);
3563 else fprintf (stderr,
3564 "Bad value for default \"%s\": \"%s\"\n", parameter, value);
3565 }
3566}
3567
3568
3569void
3570ns_initialize_display_info (struct ns_display_info *dpyinfo)
3571/* --------------------------------------------------------------------------
3572 Initialize global info and storage for display.
3573 -------------------------------------------------------------------------- */
3574{
3575 NSScreen *screen = [NSScreen mainScreen];
3576 NSWindowDepth depth = [screen depth];
3577
edfda783
AR
3578 dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
3579 dpyinfo->resy = 72.27;
3580 dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
3581 NSColorSpaceFromDepth (depth)]
3582 && ![NSCalibratedWhiteColorSpace isEqualToString:
3583 NSColorSpaceFromDepth (depth)];
3584 dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
3585 dpyinfo->image_cache = make_image_cache ();
facfbbbd
SM
3586 dpyinfo->color_table
3587 = (struct ns_color_table *)xmalloc (sizeof (struct ns_color_table));
edfda783
AR
3588 dpyinfo->color_table->colors = NULL;
3589 dpyinfo->root_window = 42; /* a placeholder.. */
3590
3591 dpyinfo->mouse_face_mouse_frame = NULL;
3592 dpyinfo->mouse_face_deferred_gc = 0;
3593 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
3594 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
3595 dpyinfo->mouse_face_face_id = DEFAULT_FACE_ID;
3596 dpyinfo->mouse_face_window = dpyinfo->mouse_face_overlay = Qnil;
3597 dpyinfo->mouse_face_hidden = 0;
3598
3599 dpyinfo->mouse_face_mouse_x = dpyinfo->mouse_face_mouse_y = 0;
3600 dpyinfo->mouse_face_defer = 0;
3601
9e50ff0c 3602 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
edfda783
AR
3603
3604 dpyinfo->n_fonts = 0;
3605 dpyinfo->smallest_font_height = 1;
3606 dpyinfo->smallest_char_width = 1;
3607}
3608
3609
3fe53a83 3610/* This and next define (many of the) public functions in this file. */
edfda783
AR
3611/* x_... are generic versions in xdisp.c that we, and other terms, get away
3612 with using despite presence in the "system dependent" redisplay
3613 interface. In addition, many of the ns_ methods have code that is
3614 shared with all terms, indicating need for further refactoring. */
3615extern frame_parm_handler ns_frame_parm_handlers[];
3616static struct redisplay_interface ns_redisplay_interface =
3617{
3618 ns_frame_parm_handlers,
3fe53a83
AR
3619 x_produce_glyphs,
3620 x_write_glyphs,
3621 x_insert_glyphs,
3622 x_clear_end_of_line,
3623 ns_scroll_run,
3624 ns_after_update_window_line,
3625 ns_update_window_begin,
3626 ns_update_window_end,
3627 x_cursor_to,
edfda783
AR
3628 ns_flush,
3629 0, /* flush_display_optional */
3fe53a83
AR
3630 x_clear_window_mouse_face,
3631 x_get_glyph_overhangs,
3632 x_fix_overlapping_area,
3633 ns_draw_fringe_bitmap,
df2142db 3634 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
edfda783 3635 0, /* destroy_fringe_bitmap */
3fe53a83
AR
3636 ns_compute_glyph_string_overhangs,
3637 ns_draw_glyph_string, /* interface to nsfont.m */
3638 ns_define_frame_cursor,
3639 ns_clear_frame_area,
3640 ns_draw_window_cursor,
edfda783
AR
3641 ns_draw_vertical_window_border,
3642 ns_shift_glyphs_for_insert
3643};
3644
3645
3646static void
3647ns_delete_display (struct ns_display_info *dpyinfo)
3648{
df2142db 3649 /* TODO... */
edfda783
AR
3650}
3651
3652
3653/* This function is called when the last frame on a display is deleted. */
3654static void
3655ns_delete_terminal (struct terminal *terminal)
3656{
3657 struct ns_display_info *dpyinfo = terminal->display_info.ns;
3658 int i;
3659
e2749141 3660 /* Protect against recursive calls. delete_frame in
edfda783
AR
3661 delete_terminal calls us back when it deletes our last frame. */
3662 if (!terminal->name)
3663 return;
3664
3665 BLOCK_INPUT;
3666
3667 x_destroy_all_bitmaps (dpyinfo);
3668 ns_delete_display (dpyinfo);
3669 UNBLOCK_INPUT;
3670}
3671
3672
3673static struct terminal *
3674ns_create_terminal (struct ns_display_info *dpyinfo)
3675/* --------------------------------------------------------------------------
3676 Set up use of NS before we make the first connection.
3677 -------------------------------------------------------------------------- */
3678{
3679 struct terminal *terminal;
3680
3681 NSTRACE (ns_create_terminal);
3682
3683 terminal = create_terminal ();
3684
3685 terminal->type = output_ns;
3686 terminal->display_info.ns = dpyinfo;
3687 dpyinfo->terminal = terminal;
3688
3689 terminal->rif = &ns_redisplay_interface;
3690
3691 terminal->clear_frame_hook = ns_clear_frame;
3fe53a83
AR
3692 terminal->ins_del_lines_hook = 0; /* XXX vestigial? */
3693 terminal->delete_glyphs_hook = 0; /* XXX vestigial? */
edfda783
AR
3694 terminal->ring_bell_hook = ns_ring_bell;
3695 terminal->reset_terminal_modes_hook = ns_reset_terminal_modes;
3696 terminal->set_terminal_modes_hook = ns_set_terminal_modes;
3697 terminal->update_begin_hook = ns_update_begin;
3698 terminal->update_end_hook = ns_update_end;
3fe53a83 3699 terminal->set_terminal_window_hook = NULL; /* XXX vestigial? */
edfda783
AR
3700 terminal->read_socket_hook = ns_read_socket;
3701 terminal->frame_up_to_date_hook = ns_frame_up_to_date;
3702 terminal->mouse_position_hook = ns_mouse_position;
3703 terminal->frame_rehighlight_hook = ns_frame_rehighlight;
3704 terminal->frame_raise_lower_hook = ns_frame_raise_lower;
3705
3fe53a83 3706 terminal->fullscreen_hook = 0; /* see XTfullscreen_hook */
edfda783
AR
3707
3708 terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
3709 terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
3710 terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
3711 terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
3712
3713 terminal->delete_frame_hook = x_destroy_window;
3714 terminal->delete_terminal_hook = ns_delete_terminal;
3715
3716 terminal->scroll_region_ok = 1;
3717 terminal->char_ins_del_ok = 1;
3718 terminal->line_ins_del_ok = 1;
3719 terminal->fast_clear_end_of_line = 1;
3720 terminal->memory_below_frame = 0;
3721
3722 return terminal;
3723}
3724
3725
3726void
3727ns_initialize ()
3728/* --------------------------------------------------------------------------
3729 Mainly vestigial under NS now that ns_create_terminal () does most things.
3730 -------------------------------------------------------------------------- */
3731{
3732 baud_rate = 38400;
3733 Fset_input_interrupt_mode (Qt);
3734}
3735
3736
3737struct ns_display_info *
3738ns_term_init (Lisp_Object display_name)
3739/* --------------------------------------------------------------------------
3740 Start the Application and get things rolling.
3741 -------------------------------------------------------------------------- */
3742{
3743 extern Lisp_Object Fset_input_mode (Lisp_Object, Lisp_Object,
3744 Lisp_Object, Lisp_Object);
3745 struct terminal *terminal;
3746 struct ns_display_info *dpyinfo;
3747 static int ns_initialized = 0;
3748 Lisp_Object tmp;
3749
3750 NSTRACE (ns_term_init);
3751
3752 /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
3753 /*GSDebugAllocationActive (YES); */
3754 BLOCK_INPUT;
1baa6236 3755 handling_signal = 0;
edfda783
AR
3756
3757 if (!ns_initialized)
3758 {
3759 ns_initialize ();
3760 ns_initialized = 1;
3761 }
3762
3763 ns_pending_files = [[NSMutableArray alloc] init];
3764 ns_pending_service_names = [[NSMutableArray alloc] init];
3765 ns_pending_service_args = [[NSMutableArray alloc] init];
3766
3767 /* Start app and create the main menu, window, view.
3768 Needs to be here because ns_initialize_display_info () uses AppKit classes.
3769 The view will then ask the NSApp to stop and return to Emacs. */
3770 [EmacsApp sharedApplication];
3771 if (NSApp == nil)
3772 return NULL;
3773 [NSApp setDelegate: NSApp];
3774
3775 /* debugging: log all notifications */
3776 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
3777 selector: @selector (logNotification:)
3778 name: nil object: nil]; */
3779
3780 dpyinfo = (struct ns_display_info *)xmalloc (sizeof (struct ns_display_info));
3781 bzero (dpyinfo, sizeof (struct ns_display_info));
3782
3783 ns_initialize_display_info (dpyinfo);
3784 terminal = ns_create_terminal (dpyinfo);
3785
3786 terminal->kboard = (KBOARD *) xmalloc (sizeof (KBOARD));
3787 init_kboard (terminal->kboard);
3788 terminal->kboard->Vwindow_system = Qns;
3789 terminal->kboard->next_kboard = all_kboards;
3790 all_kboards = terminal->kboard;
3791 /* Don't let the initial kboard remain current longer than necessary.
3792 That would cause problems if a file loaded on startup tries to
3793 prompt in the mini-buffer. */
3794 if (current_kboard == initial_kboard)
3795 current_kboard = terminal->kboard;
3796 terminal->kboard->reference_count++;
3797
9e50ff0c
DN
3798 dpyinfo->next = x_display_list;
3799 x_display_list = dpyinfo;
edfda783
AR
3800
3801 /* Put it on ns_display_name_list */
3802 ns_display_name_list = Fcons (Fcons (display_name, Qnil),
3803 ns_display_name_list);
3804/* ns_display_name_list = Fcons (Fcons (display_name,
3805 Fcons (Qnil, dpyinfo->xrdb)),
3806 ns_display_name_list); */
3807 dpyinfo->name_list_element = XCAR (ns_display_name_list);
3808
3809 /* Set the name of the terminal. */
3810 terminal->name = (char *) xmalloc (SBYTES (display_name) + 1);
3811 strncpy (terminal->name, SDATA (display_name), SBYTES (display_name));
3812 terminal->name[SBYTES (display_name)] = 0;
3813
3814 UNBLOCK_INPUT;
3815
3816 /* Read various user defaults. */
3817 ns_set_default_prefs ();
3818 ns_default ("AlternateModifier", &ns_alternate_modifier,
3819 Qnil, Qnil, NO, YES);
3820 if (NILP (ns_alternate_modifier))
3821 ns_alternate_modifier = Qmeta;
3822 ns_default ("CommandModifier", &ns_command_modifier,
3823 Qnil, Qnil, NO, YES);
3824 if (NILP (ns_command_modifier))
3825 ns_command_modifier = Qsuper;
3826 ns_default ("ControlModifier", &ns_control_modifier,
3827 Qnil, Qnil, NO, YES);
3828 if (NILP (ns_control_modifier))
3829 ns_control_modifier = Qcontrol;
3830 ns_default ("FunctionModifier", &ns_function_modifier,
3831 Qnil, Qnil, NO, YES);
3832 if (NILP (ns_function_modifier))
3833 ns_function_modifier = Qnone;
edfda783
AR
3834 ns_default ("ExpandSpace", &ns_expand_space,
3835 make_float (0.5), make_float (0.0), YES, NO);
3836 ns_default ("GSFontAntiAlias", &ns_antialias_text,
facfbbbd 3837 Qt, Qnil, NO, NO);
edfda783
AR
3838 tmp = Qnil;
3839 ns_default ("AppleAntiAliasingThreshold", &tmp,
3840 make_float (10.0), make_float (6.0), YES, NO);
3841 ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
3842 ns_default ("UseQuickdrawSmoothing", &ns_use_qd_smoothing,
facfbbbd 3843 Qt, Qnil, NO, NO);
edfda783 3844 ns_default ("UseSystemHighlightColor", &ns_use_system_highlight_color,
facfbbbd 3845 Qt, Qnil, NO, NO);
5c976973 3846 if (EQ (ns_use_system_highlight_color, Qt))
edfda783
AR
3847 {
3848 ns_selection_color = [[NSUserDefaults standardUserDefaults]
3849 stringForKey: @"AppleHighlightColor"];
3850 if (ns_selection_color == nil)
3851 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
3852 }
3853 else
3854 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
3855
3856 {
7ded3383 3857 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
edfda783
AR
3858
3859 if ( cl == nil )
3860 {
7ded3383
AR
3861 Lisp_Object color_file, color_map, color;
3862 int r,g,b;
3863 unsigned long c;
3864 char *name;
3865
3866 color_file = Fexpand_file_name (build_string ("rgb.txt"),
3867 Fsymbol_value (intern ("data-directory")));
3868 if (NILP (Ffile_readable_p (color_file)))
3869 fatal ("Could not find %s.\n", SDATA (color_file));
3870
3871 color_map = Fx_load_color_file (color_file);
3872 if (NILP (color_map))
3873 fatal ("Could not read %s.\n", SDATA (color_file));
3874
3875 cl = [[NSColorList alloc] initWithName: @"Emacs"];
3876 for ( ; CONSP (color_map); color_map = XCDR (color_map))
edfda783 3877 {
7ded3383
AR
3878 color = XCAR (color_map);
3879 name = SDATA (XCAR (color));
3880 c = XINT (XCDR (color));
3881 [cl setColor:
3882 [NSColor colorWithCalibratedRed: RED_FROM_ULONG (c) / 255.0
3883 green: GREEN_FROM_ULONG (c) / 255.0
3884 blue: BLUE_FROM_ULONG (c) / 255.0
3885 alpha: 1.0]
3886 forKey: [NSString stringWithUTF8String: name]];
edfda783 3887 }
edfda783
AR
3888 [cl writeToFile: nil];
3889 }
3890 }
3891
3892 {
3893 char c[128];
3894#ifdef NS_IMPL_GNUSTEP
3895 strncpy (c, gnustep_base_version, sizeof (c));
3896#else
3897 /*PSnextrelease (128, c); */
3898 snprintf (c, sizeof (c), "%g", NSAppKitVersionNumber);
3899#endif
3900 Vwindow_system_version = build_string (c);
3901 }
3902
3903 delete_keyboard_wait_descriptor (0);
3904
3905/* Set up OS X app menu */
3906#ifdef NS_IMPL_COCOA
3907 {
3908 NSMenu *appMenu;
15034960 3909 NSMenuItem *item;
edfda783
AR
3910 /* set up the application menu */
3911 svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
3912 [svcsMenu setAutoenablesItems: NO];
3913 appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
3914 [appMenu setAutoenablesItems: NO];
3915 mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
4e622592 3916 dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
edfda783
AR
3917
3918 [appMenu insertItemWithTitle: @"About Emacs"
3919 action: @selector (orderFrontStandardAboutPanel:)
3920 keyEquivalent: @""
3921 atIndex: 0];
3922 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
3923 [appMenu insertItemWithTitle: @"Preferences..."
3924 action: @selector (showPreferencesWindow:)
3925 keyEquivalent: @","
3926 atIndex: 2];
3927 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
3928 item = [appMenu insertItemWithTitle: @"Services"
3929 action: @selector (menuDown:)
3930 keyEquivalent: @""
3931 atIndex: 4];
3932 [appMenu setSubmenu: svcsMenu forItem: item];
3933/* [svcsMenu setSupercell: item]; */
3934 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
3935 [appMenu insertItemWithTitle: @"Hide Emacs"
3936 action: @selector (hide:)
3937 keyEquivalent: @"h"
3938 atIndex: 6];
3939 item = [appMenu insertItemWithTitle: @"Hide Others"
3940 action: @selector (hideOtherApplications:)
3941 keyEquivalent: @"h"
3942 atIndex: 7];
3943 [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
3944 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
3945 [appMenu insertItemWithTitle: @"Quit Emacs"
3946 action: @selector (terminate:)
3947 keyEquivalent: @"q"
3948 atIndex: 9];
3949
3950 item = [mainMenu insertItemWithTitle: @"Emacs"
3951 action: @selector (menuDown:)
3952 keyEquivalent: @""
3953 atIndex: 0];
3954 [mainMenu setSubmenu: appMenu forItem: item];
4e622592
AR
3955 [dockMenu insertItemWithTitle: @"New Frame"
3956 action: @selector (newFrame:)
3957 keyEquivalent: @""
3958 atIndex: 0];
edfda783
AR
3959
3960 [NSApp setMainMenu: mainMenu];
3961 [NSApp setAppleMenu: appMenu];
3962 [NSApp setServicesMenu: svcsMenu];
3963 /* Needed at least on Cocoa, to get dock menu to show windows */
3964 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
3965 }
3966#endif /* MAC OS X menu setup */
3967
3968 [NSApp run];
3969
3970 return dpyinfo;
3971}
3972
3973
3974extern Lisp_Object Vauto_save_list_file_name;
3975void
3976ns_term_shutdown (int sig)
3977{
3978 /* code not reached in emacs.c after this is called by shut_down_emacs: */
3979 if (STRINGP (Vauto_save_list_file_name))
6882361b 3980 unlink (SDATA (Vauto_save_list_file_name));
edfda783 3981
a9b4df69
AR
3982 if (sig == 0 || sig == SIGTERM)
3983 {
3984 ns_shutdown_properly = YES;
3985 [NSApp terminate: NSApp];
3986 }
3987 else // force a stack trace to happen
3988 {
3989 abort();
3990 }
edfda783
AR
3991}
3992
3993
edfda783
AR
3994/* ==========================================================================
3995
3996 EmacsApp implementation
3997
3998 ========================================================================== */
3999
4000
4001@implementation EmacsApp
4002
4003- (void)logNotification: (NSNotification *)notification
4004{
4005 const char *name = [[notification name] UTF8String];
4006 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
4007 && !strstr (name, "WindowNumber"))
4008 NSLog (@"notification: '%@'", [notification name]);
4009}
4010
4011
4012- (void)sendEvent: (NSEvent *)theEvent
4013/* --------------------------------------------------------------------------
4014 Events posted by ns_send_appdefined interrupt the run loop here
4015 -------------------------------------------------------------------------- */
4016{
4017 int type = [theEvent type];
4018 NSWindow *window = [theEvent window];
4019/* NSTRACE (sendEvent); */
4020/*fprintf (stderr, "received event of type %d\n", [theEvent type]); */
4021
4022 if (type == NSCursorUpdate && window == nil)
4023 {
4024 fprintf (stderr, "Dropping external cursor update event.\n");
4025 return;
4026 }
4027
4028#ifdef NS_IMPL_COCOA
4029 /* pass mouse down in resize handle and subsequent drags directly to
4030 EmacsWindow so we can generate continuous redisplays */
4031 if (ns_in_resize)
4032 {
4033 if (type == NSLeftMouseDragged)
4034 {
4035 [window mouseDragged: theEvent];
4036 return;
4037 }
4038 else if (type == NSLeftMouseUp)
4039 {
4040 [window mouseUp: theEvent];
4041 return;
4042 }
4043 }
4044 else if (type == NSLeftMouseDown)
4045 {
4046 NSRect r = ns_resize_handle_rect (window);
4047 if (NSPointInRect ([theEvent locationInWindow], r))
4048 {
4049 ns_in_resize = YES;
4050 [window mouseDown: theEvent];
4051 return;
4052 }
4053 }
4054#endif
4055
4056 if (type == NSApplicationDefined)
4057 {
4058 last_appdefined_event = theEvent;
4059 [self stop: self];
4060 }
4061
4062 [super sendEvent: theEvent];
4063}
4064
4065
4066- (void)showPreferencesWindow: (id)sender
4067{
4068 if (prefsController == nil)
4069 prefsController = [[EmacsPrefsController alloc] init];
4070 [prefsController showForFrame: SELECTED_FRAME ()];
4071}
4072
4073
4e622592
AR
4074- (void)newFrame: (id)sender
4075{
4076 struct frame *emacsframe = SELECTED_FRAME ();
4077 NSEvent *theEvent = [NSApp currentEvent];
4078
4079 if (!emacs_event)
4080 return;
4081 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4082 emacs_event->code = KEY_NS_NEW_FRAME;
4083 emacs_event->modifiers = 0;
4084 EV_TRAILER (theEvent);
4085}
4086
4087
15034960
AR
4088/* Open a file (used by below, after going into queue read by ns_read_socket) */
4089- (BOOL) openFile: (NSString *)fileName
4090{
4091 struct frame *emacsframe = SELECTED_FRAME ();
4092 NSEvent *theEvent = [NSApp currentEvent];
4093
4094 if (!emacs_event)
4095 return NO;
4096
4097 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4098 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4099 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4100 ns_input_line = Qnil; /* can be start or cons start,end */
4101 emacs_event->modifiers =0;
4102 EV_TRAILER (theEvent);
4103
4104 return YES;
4105}
4106
4107
edfda783
AR
4108/* **************************************************************************
4109
4110 EmacsApp delegate implementation
4111
4112 ************************************************************************** */
4113
4114- (void)applicationDidFinishLaunching: (NSNotification *)notification
4115/* --------------------------------------------------------------------------
4116 When application is loaded, terminate event loop in ns_term_init
4117 -------------------------------------------------------------------------- */
4118{
4119 NSTRACE (applicationDidFinishLaunching);
4120 [NSApp setServicesProvider: NSApp];
4121 ns_send_appdefined (-2);
4122}
e2749141 4123
edfda783
AR
4124
4125- (void) terminate: (id)sender
4126{
4127 BLOCK_INPUT;
4128 if (ns_shutdown_properly)
4129 [super terminate: sender];
4130 else
4131 {
4132/* Fkill_emacs (Qnil); */
4133 ns_shutdown_properly = YES;
4134 Feval (Fcons (intern ("save-buffers-kill-emacs"), Qnil));
4135 }
4136 UNBLOCK_INPUT;
4137}
4138
4139
4140- (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4141{
4142 if (ns_shutdown_properly)
4143 return NSTerminateNow;
4144
4145 Lisp_Object contents = list3 (build_string ("Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?"),
4146 Fcons (build_string ("Cancel"), Qnil),
4147 Fcons (build_string ("Save and Exit"), Qt));
4148 Lisp_Object res = ns_popup_dialog (Qt, contents, Qnil);
712b2de1 4149fprintf (stderr, "res = %d\n", EQ (res, Qt)); /* FIXME */
facfbbbd 4150 if (EQ (res, Qt))
edfda783
AR
4151 {
4152 Feval (Fcons (intern ("save-buffers-kill-emacs"), Qnil));
4153 return NSTerminateNow;
4154 }
4155 return NSTerminateCancel;
4156}
4157
4158
edfda783
AR
4159/* Notification from the Workspace to open a file */
4160- (BOOL)application: sender openFile: (NSString *)file
4161{
4162 [ns_pending_files addObject: file];
4163 return YES;
4164}
4165
4166
4167/* Open a file as a temporary file */
4168- (BOOL)application: sender openTempFile: (NSString *)file
4169{
4170 [ns_pending_files addObject: file];
4171 return YES;
4172}
4173
4174
4175/* Notification from the Workspace to open a file noninteractively (?) */
4176- (BOOL)application: sender openFileWithoutUI: (NSString *)file
4177{
4178 [ns_pending_files addObject: file];
4179 return YES;
4180}
4181
4182
4183/* Notification from the Workspace to open multiple files */
4184- (void)application: sender openFiles: (NSArray *)fileList
4185{
4186 NSEnumerator *files = [fileList objectEnumerator];
4187 NSString *file;
4188 while ((file = [files nextObject]) != nil)
4189 [ns_pending_files addObject: file];
98a2166a 4190
f2f7f42c
AR
4191/* TODO: when GNUstep implements this (and we require that version of
4192 GNUstep), remove. */
4193#ifndef NS_IMPL_GNUSTEP
15034960 4194 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
f2f7f42c 4195#endif /* !NS_IMPL_GNUSTEP */
98a2166a 4196
edfda783
AR
4197}
4198
4e622592
AR
4199
4200/* Handle dock menu requests. */
4201- (NSMenu *)applicationDockMenu: (NSApplication *) sender
4202{
4203 return dockMenu;
4204}
4205
4206
df2142db 4207/* TODO: these may help w/IO switching btwn terminal and NSApp */
a3b53a85
AR
4208- (void)applicationWillBecomeActive: (NSNotification *)notification
4209{
4210 //ns_app_active=YES;
4211}
edfda783
AR
4212- (void)applicationDidBecomeActive: (NSNotification *)notification
4213{
a3b53a85 4214 //ns_app_active=YES;
edfda783
AR
4215}
4216- (void)applicationDidResignActive: (NSNotification *)notification
4217{
a3b53a85 4218 //ns_app_active=NO;
edfda783
AR
4219 ns_send_appdefined (-1);
4220}
4221
4222
4223
4224/* ==========================================================================
4225
4226 EmacsApp aux handlers for managing event loop
4227
4228 ========================================================================== */
4229
4230
4231- (void)timeout_handler: (NSTimer *)timedEntry
4232/* --------------------------------------------------------------------------
4233 The timeout specified to ns_select has passed.
4234 -------------------------------------------------------------------------- */
4235{
4236 /*NSTRACE (timeout_handler); */
4237 ns_send_appdefined (-2);
4238}
4239
4240extern void update_window_cursor (struct window *w, int on);
4241
edfda783
AR
4242- (void)fd_handler: (NSTimer *) fdEntry
4243/* --------------------------------------------------------------------------
4244 Check data waiting on file descriptors and terminate if so
4245 -------------------------------------------------------------------------- */
4246{
4247 int result;
4248 /* NSTRACE (fd_handler); */
4249
4250 if (select_nfds == 0)
4251 return;
4252
4253 memcpy (&t_readfds, &select_readfds, sizeof (fd_set));
4254
4255 select_timeout.tv_sec = select_timeout.tv_usec = 0;
4256 result = select (select_nfds, &t_readfds, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
4257 &select_timeout);
4258 if (result)
4259 {
4260 memcpy (&select_readfds, &t_readfds, sizeof (fd_set));
4261 ns_send_appdefined (result);
4262 }
4263}
4264
4265
4266
4267/* ==========================================================================
4268
4269 Service provision
4270
4271 ========================================================================== */
4272
4273/* called from system: queue for next pass through event loop */
4274- (void)requestService: (NSPasteboard *)pboard
4275 userData: (NSString *)userData
4276 error: (NSString **)error
4277{
4278 [ns_pending_service_names addObject: userData];
4279 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
4280 SDATA (ns_string_from_pasteboard (pboard))]];
4281}
4282
4283
4284/* called from ns_read_socket to clear queue */
4285- (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
4286{
4287 struct frame *emacsframe = SELECTED_FRAME ();
4288 NSEvent *theEvent = [NSApp currentEvent];
4289
4290 if (!emacs_event)
4291 return NO;
4292
4293 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4294 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
4295 ns_input_spi_name = build_string ([name UTF8String]);
4296 ns_input_spi_arg = build_string ([arg UTF8String]);
4297 emacs_event->modifiers = EV_MODIFIERS (theEvent);
4298 EV_TRAILER (theEvent);
4299
4300 return YES;
4301}
4302
4303
4304@end /* EmacsApp */
4305
4306
4307
4308/* ==========================================================================
4309
4310 EmacsView implementation
4311
4312 ========================================================================== */
4313
4314
4315@implementation EmacsView
4316
4317/* needed to inform when window closed from LISP */
4318- (void) setWindowClosing: (BOOL)closing
4319{
4320 windowClosing = closing;
4321}
4322
4323
4324- (void)dealloc
4325{
4326 NSTRACE (EmacsView_dealloc);
4327 [toolbar release];
4328 [super dealloc];
4329}
4330
4331
4332/* called on font panel selection */
4333- (void)changeFont: (id)sender
4334{
4335 NSEvent *e =[[self window] currentEvent];
4336 struct face *face =FRAME_DEFAULT_FACE (emacsframe);
4337 id newFont;
4338 float size;
4339
4340 NSTRACE (changeFont);
4341 if (!emacs_event)
4342 return;
4343
4344 if (newFont = [sender convertFont:
4345 ((struct nsfont_info *)face->font)->nsfont])
4346 {
c8c057de
AR
4347 SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
4348
edfda783
AR
4349 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4350 emacs_event->modifiers = 0;
4351 emacs_event->code = KEY_NS_CHANGE_FONT;
4352
4353 size = [newFont pointSize];
ed96cde8 4354 ns_input_fontsize = make_number (lrint (size));
edfda783
AR
4355 ns_input_font = build_string ([[newFont familyName] UTF8String]);
4356 EV_TRAILER (e);
4357 }
4358}
4359
4360
4361- (BOOL)acceptsFirstResponder
4362{
4363 NSTRACE (acceptsFirstResponder);
4364 return YES;
4365}
4366
4367
4368- (void)resetCursorRects
4369{
4370 NSRect visible = [self visibleRect];
4371 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
4372 NSTRACE (resetCursorRects);
4373
4374 if (currentCursor == nil)
4375 currentCursor = [NSCursor arrowCursor];
4376
4377 if (!NSIsEmptyRect (visible))
4378 [self addCursorRect: visible cursor: currentCursor];
4379 [currentCursor setOnMouseEntered: YES];
4380}
4381
4382
a9b4df69 4383
edfda783
AR
4384/*****************************************************************************/
4385/* Keyboard handling. */
4386#define NS_KEYLOG 0
4387
4388- (void)keyDown: (NSEvent *)theEvent
4389{
4390 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4391 int code;
4392 unsigned fnKeysym = 0;
4393 int flags;
4394 static NSMutableArray *nsEvArray;
4395 static BOOL firstTime = YES;
4396
4397 NSTRACE (keyDown);
4398
4399 /* Rhapsody and OS X give up and down events for the arrow keys */
a9b4df69
AR
4400 if (ns_fake_keydown == YES)
4401 ns_fake_keydown = NO;
4402 else if ([theEvent type] != NSKeyDown)
edfda783
AR
4403 return;
4404
4405 if (!emacs_event)
4406 return;
4407
edfda783
AR
4408 if (![[self window] isKeyWindow])
4409 {
df2142db
AR
4410 /* XXX: Using NO_SOCK_SIGIO like Carbon causes a condition in which,
4411 when Emacs display updates a different frame from the current one,
4412 and temporarily selects it, then processes some interrupt-driven
4413 input (dispnew.c:3878), OS will send the event to the correct NSWindow,
4414 but for some reason that window has its first responder set to the
4415 NSView most recently updated (I guess), which is not the correct one.
4416 UPDATE: After multi-TTY merge this happens even w/o NO_SOCK_SIGIO */
edfda783 4417 if ([[theEvent window] isKindOfClass: [EmacsWindow class]])
15034960 4418 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
edfda783
AR
4419 return;
4420 }
edfda783
AR
4421
4422 if (nsEvArray == nil)
4423 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
4424
4425 [NSCursor setHiddenUntilMouseMoves: YES];
4426
4427 if (dpyinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
4428 {
4429 clear_mouse_face (dpyinfo);
4430 dpyinfo->mouse_face_hidden = 1;
4431 }
4432
4433 if (!processingCompose)
4434 {
4435 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
4436 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
4437 /* (Carbon way: [theEvent keyCode]) */
4438
4439 /* is it a "function key"? */
4440 fnKeysym = ns_convert_key (code);
4441 if (fnKeysym)
4442 {
4443 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
4444 because Emacs treats Delete and KP-Delete same (in simple.el). */
4445 if (fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
4446 code = 0xFF08; /* backspace */
4447 else
4448 code = fnKeysym;
4449 }
4450
4451 /* are there modifiers? */
4452 emacs_event->modifiers = 0;
4453 flags = [theEvent modifierFlags];
4454
4455 if (flags & NSHelpKeyMask)
4456 emacs_event->modifiers |= hyper_modifier;
4457
4458 if (flags & NSShiftKeyMask)
4459 emacs_event->modifiers |= shift_modifier;
4460
4461 if (flags & NSCommandKeyMask)
4462 {
6882361b 4463 emacs_event->modifiers |= parse_solitary_modifier (ns_command_modifier);
edfda783
AR
4464 /* if super (default), take input manager's word so things like
4465 dvorak / qwerty layout work */
4466 if (EQ (ns_command_modifier, Qsuper)
4467 && !fnKeysym
4468 && [[theEvent characters] length] != 0)
4469 {
df2142db 4470 /* XXX: the code we get will be unshifted, so if we have
edfda783
AR
4471 a shift modifier, must convert ourselves */
4472 if (!(flags & NSShiftKeyMask))
4473 code = [[theEvent characters] characterAtIndex: 0];
4474#if 0
4475 /* this is ugly and also requires linking w/Carbon framework
4476 (for LMGetKbdType) so for now leave this rare (?) case
4477 undealt with.. in future look into CGEvent methods */
4478 else
4479 {
4480 long smv = GetScriptManagerVariable (smKeyScript);
4481 Handle uchrHandle = GetResource
4482 ('uchr', GetScriptVariable (smv, smScriptKeys));
4483 UInt32 dummy = 0;
4484 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
4485 [[theEvent characters] characterAtIndex: 0],
4486 kUCKeyActionDisplay,
4487 (flags & ~NSCommandKeyMask) >> 8,
4488 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
4489 &dummy, 1, &dummy, &code);
4490 code &= 0xFF;
4491 }
4492#endif
4493 }
4494 }
4495
4496 if (flags & NSControlKeyMask)
a9b4df69
AR
4497 emacs_event->modifiers |=
4498 parse_solitary_modifier (ns_control_modifier);
edfda783
AR
4499
4500 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
a9b4df69
AR
4501 emacs_event->modifiers |=
4502 parse_solitary_modifier (ns_function_modifier);
edfda783
AR
4503
4504 if (flags & NSAlternateKeyMask) /* default = meta */
4505 {
a3b53a85
AR
4506 if ((NILP (ns_alternate_modifier) || EQ (ns_alternate_modifier, Qnone))
4507 && !fnKeysym)
edfda783
AR
4508 { /* accept pre-interp alt comb */
4509 if ([[theEvent characters] length] > 0)
4510 code = [[theEvent characters] characterAtIndex: 0];
4511 /*HACK: clear lone shift modifier to stop next if from firing */
4512 if (emacs_event->modifiers == shift_modifier)
4513 emacs_event->modifiers = 0;
4514 }
4515 else
a9b4df69
AR
4516 emacs_event->modifiers |=
4517 parse_solitary_modifier (ns_alternate_modifier);
edfda783
AR
4518 }
4519
a9b4df69
AR
4520 if (NS_KEYLOG)
4521 fprintf (stderr, "keyDown: code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",
4522 code, fnKeysym, flags, emacs_event->modifiers);
edfda783
AR
4523
4524 /* if it was a function key or had modifiers, pass it directly to emacs */
4525 if (fnKeysym || (emacs_event->modifiers
4526 && [[theEvent charactersIgnoringModifiers] length] > 0))
4527/*[[theEvent characters] length] */
4528 {
4529 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4530 if (code < 0x20)
4531 code |= (1<<28)|(3<<16);
4532 else if (code == 0x7f)
4533 code |= (1<<28)|(3<<16);
4534 else if (!fnKeysym)
4535 emacs_event->kind = code > 0xFF
4536 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4537
4538 emacs_event->code = code;
4539 EV_TRAILER (theEvent);
4540 return;
4541 }
4542 }
4543
4544 /* if we get here we should send the key for input manager processing */
4545 if (firstTime && [[NSInputManager currentInputManager]
4546 wantsToDelayTextChangeNotifications] == NO)
4547 fprintf (stderr,
4548 "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
4549 firstTime = NO;
4550
4551 if (NS_KEYLOG && !processingCompose)
a9b4df69 4552 fprintf (stderr, "keyDown: Begin compose sequence.\n");
edfda783
AR
4553
4554 processingCompose = YES;
4555 [nsEvArray addObject: theEvent];
4556 [self interpretKeyEvents: nsEvArray];
4557 [nsEvArray removeObject: theEvent];
4558}
4559
4560
a9b4df69
AR
4561#ifdef NS_IMPL_COCOA
4562/* Needed to pick up Ctrl-tab and possibly other events that OS X has
4563 decided not to send key-down for.
4564 See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
4565 If it matches one of these, send it on to keyDown. */
4566-(void)keyUp: (NSEvent *)theEvent
4567{
4568 int flags = [theEvent modifierFlags];
4569 int code = [theEvent keyCode];
4570 if (code == 0x30 && (flags & NSControlKeyMask) && !(flags & NSCommandKeyMask))
4571 {
4572 if (NS_KEYLOG)
4573 fprintf (stderr, "keyUp: passed test");
4574 ns_fake_keydown = YES;
4575 [self keyDown: theEvent];
4576 }
4577}
4578#endif
4579
4580
edfda783
AR
4581/* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
4582
4583
4584/* <NSTextInput>: called through when done composing */
4585- (void)insertText: (id)aString
4586{
4587 int code;
4588 int len = [(NSString *)aString length];
4589 int i;
4590
a9b4df69
AR
4591 if (NS_KEYLOG)
4592 NSLog (@"insertText '%@'\tlen = %d", aString, len);
edfda783
AR
4593 processingCompose = NO;
4594
4595 if (!emacs_event)
4596 return;
4597
4598 /* first, clear any working text */
4599 if (workingText != nil)
4600 [self deleteWorkingText];
4601
4602 /* now insert the string as keystrokes */
4603 for (i =0; i<len; i++)
4604 {
4605 code = [aString characterAtIndex: i];
df2142db 4606 /* TODO: still need this? */
edfda783
AR
4607 if (code == 0x2DC)
4608 code = '~'; /* 0x7E */
4609 emacs_event->modifiers = 0;
facfbbbd
SM
4610 emacs_event->kind
4611 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
edfda783
AR
4612 emacs_event->code = code;
4613 EV_TRAILER ((id)nil);
4614 }
4615}
4616
4617
4618/* <NSTextInput>: inserts display of composing characters */
4619- (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
4620{
4621 NSString *str = [aString respondsToSelector: @selector (string)] ?
4622 [aString string] : aString;
4623 if (NS_KEYLOG)
4624 NSLog (@"setMarkedText '%@' len =%d range %d from %d", str, [str length],
4625 selRange.length, selRange.location);
4626
4627 if (workingText != nil)
4628 [self deleteWorkingText];
4629 if ([str length] == 0)
4630 return;
4631
4632 if (!emacs_event)
4633 return;
4634
4635 processingCompose = YES;
4636 workingText = [str copy];
4637 ns_working_text = build_string ([workingText UTF8String]);
4638
4639 /* if in "echo area", not true minibuffer, can't show chars in interactive
4640 mode, so call using eval; otherwise we send a key event, which was the
4641 original way this was done */
4642 if (!EQ (Feval (Fcons (intern ("ns-in-echo-area"), Qnil)), Qnil))
4643 {
4644 Feval (Fcons (intern ("ns-echo-working-text"), Qnil));
4645 ns_send_appdefined (-1);
4646 }
4647 else
4648 {
4649 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4650 emacs_event->code = KEY_NS_INSERT_WORKING_TEXT;
4651 EV_TRAILER ((id)nil);
4652 }
4653}
4654
4655
4656/* delete display of composing characters [not in <NSTextInput>] */
4657- (void)deleteWorkingText
4658{
4659 if (workingText == nil)
4660 return;
4661 if (NS_KEYLOG)
4662 fprintf (stderr, "deleteWorkingText len =%d\n", [workingText length]);
4663 [workingText release];
4664 workingText = nil;
4665 processingCompose = NO;
4666
4667 if (!emacs_event)
4668 return;
4669
4670 if (!EQ (Feval (Fcons (intern ("ns-in-echo-area"), Qnil)), Qnil))
4671 {
4672 Feval (Fcons (intern ("ns-unecho-working-text"), Qnil));
4673 ns_send_appdefined (-1);
4674 }
4675 else
4676 {
4677 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4678 emacs_event->code = KEY_NS_DELETE_WORKING_TEXT;
4679 EV_TRAILER ((id)nil);
4680 }
4681 }
4682
4683
4684- (BOOL)hasMarkedText
4685{
4686 return workingText != nil;
4687}
4688
4689- (NSRange)markedRange
4690{
4691 NSRange rng = workingText != nil
4692 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
a9b4df69
AR
4693 if (NS_KEYLOG)
4694 NSLog (@"markedRange request");
edfda783
AR
4695 return rng;
4696}
4697
4698- (void)unmarkText
4699{
a9b4df69
AR
4700 if (NS_KEYLOG)
4701 NSLog (@"unmark (accept) text");
edfda783
AR
4702 [self deleteWorkingText];
4703 processingCompose = NO;
4704}
4705
4706/* used to position char selection windows, etc. */
4707- (NSRect)firstRectForCharacterRange: (NSRange)theRange
4708{
4709 NSRect rect;
4710 NSPoint pt;
4711 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
a9b4df69
AR
4712 if (NS_KEYLOG)
4713 NSLog (@"firstRectForCharRange request");
edfda783
AR
4714
4715 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
4716 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
4717 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
4718 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
4719 +FRAME_LINE_HEIGHT (emacsframe));
4720
4721 pt = [self convertPoint: pt toView: nil];
4722 pt = [[self window] convertBaseToScreen: pt];
4723 rect.origin = pt;
4724 return rect;
4725}
4726
15034960 4727- (NSInteger)conversationIdentifier
edfda783 4728{
15034960 4729 return (NSInteger)self;
edfda783
AR
4730}
4731
df2142db 4732/* TODO: below here not yet implemented correctly, but may not be needed */
edfda783
AR
4733
4734- (void)doCommandBySelector: (SEL)aSelector
4735{
a9b4df69
AR
4736 if (NS_KEYLOG)
4737 NSLog (@"doCommandBySelector: %@", NSStringFromSelector (aSelector));
edfda783
AR
4738
4739 if (aSelector == @selector (deleteBackward:))
4740 {
4741 /* happens when user backspaces over an ongoing composition:
4742 throw a 'delete' into the event queue */
4743 if (!emacs_event)
4744 return;
4745 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4746 emacs_event->code = 0xFF08;
4747 EV_TRAILER ((id)nil);
4748 }
4749}
4750
4751- (NSArray *)validAttributesForMarkedText
4752{
4753 static NSArray *arr = nil;
4754 if (arr == nil) arr = [NSArray new];
4755 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
4756 return arr;
4757}
4758
4759- (NSRange)selectedRange
4760{
a9b4df69
AR
4761 if (NS_KEYLOG)
4762 NSLog (@"selectedRange request");
edfda783
AR
4763 return NSMakeRange (NSNotFound, 0);
4764}
4765
4766- (unsigned int)characterIndexForPoint: (NSPoint)thePoint
4767{
a9b4df69
AR
4768 if (NS_KEYLOG)
4769 NSLog (@"characterIndexForPoint request");
edfda783
AR
4770 return 0;
4771}
4772
4773- (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
4774{
4775 static NSAttributedString *str = nil;
4776 if (str == nil) str = [NSAttributedString new];
a9b4df69
AR
4777 if (NS_KEYLOG)
4778 NSLog (@"attributedSubstringFromRange request");
edfda783
AR
4779 return str;
4780}
4781
4782/* End <NSTextInput> impl. */
4783/*****************************************************************************/
4784
4785
4786/* This is what happens when the user presses a mouse button. */
4787- (void)mouseDown: (NSEvent *)theEvent
4788{
4789 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
4790 Lisp_Object window;
4791
4792 NSTRACE (mouseDown);
4793
4794 [self deleteWorkingText];
4795
4796 if (!emacs_event)
4797 return;
4798
4799 last_mouse_frame = emacsframe;
4800 /* appears to be needed to prevent spurious movement events generated on
4801 button clicks */
4802 last_mouse_frame->mouse_moved = 0;
4803
4804 if ([theEvent type] == NSScrollWheel)
4805 {
4806 float delta = [theEvent deltaY];
4807 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
4808 if (delta == 0)
4809 return;
4810 emacs_event->kind = WHEEL_EVENT;
4811 emacs_event->code = 0;
4812 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
4813 ((delta > 0) ? up_modifier : down_modifier);
4814 }
4815 else
4816 {
4817 emacs_event->kind = MOUSE_CLICK_EVENT;
4818 emacs_event->code = EV_BUTTON (theEvent);
4819 emacs_event->modifiers = EV_MODIFIERS (theEvent)
4820 | EV_UDMODIFIERS (theEvent);
4821 }
4822 XSETINT (emacs_event->x, lrint (p.x));
4823 XSETINT (emacs_event->y, lrint (p.y));
4824 EV_TRAILER (theEvent);
4825}
4826
4827
19454c0a 4828- (void)rightMouseDown: (NSEvent *)theEvent
edfda783 4829{
19454c0a 4830 NSTRACE (rightMouseDown);
edfda783
AR
4831 [self mouseDown: theEvent];
4832}
4833
4834
19454c0a 4835- (void)otherMouseDown: (NSEvent *)theEvent
edfda783 4836{
19454c0a
AR
4837 NSTRACE (otherMouseDown);
4838 [self mouseDown: theEvent];
4839}
4840
4841
4842- (void)mouseUp: (NSEvent *)theEvent
4843{
4844 NSTRACE (mouseUp);
edfda783
AR
4845 [self mouseDown: theEvent];
4846}
4847
4848
4849- (void)rightMouseUp: (NSEvent *)theEvent
4850{
4851 NSTRACE (rightMouseUp);
4852 [self mouseDown: theEvent];
4853}
4854
4855
19454c0a
AR
4856- (void)otherMouseUp: (NSEvent *)theEvent
4857{
4858 NSTRACE (otherMouseUp);
4859 [self mouseDown: theEvent];
4860}
4861
4862
edfda783
AR
4863- (void) scrollWheel: (NSEvent *)theEvent
4864{
4865 NSTRACE (scrollWheel);
4866 [self mouseDown: theEvent];
4867}
4868
4869
4870/* Tell emacs the mouse has moved. */
4871- (void)mouseMoved: (NSEvent *)e
4872{
4873 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4874 Lisp_Object frame;
4875
c8c057de 4876// NSTRACE (mouseMoved);
edfda783
AR
4877
4878 last_mouse_movement_time = EV_TIMESTAMP (e);
facfbbbd
SM
4879 last_mouse_motion_position
4880 = [self convertPoint: [e locationInWindow] fromView: nil];
edfda783
AR
4881
4882 /* update any mouse face */
4883 if (dpyinfo->mouse_face_hidden)
4884 {
4885 dpyinfo->mouse_face_hidden = 0;
4886 clear_mouse_face (dpyinfo);
4887 }
4888
4889 /* tooltip handling */
4890 previous_help_echo_string = help_echo_string;
4891 help_echo_string = Qnil;
4892
4893 if (!note_mouse_movement (emacsframe, last_mouse_motion_position.x,
4894 last_mouse_motion_position.y))
4895 help_echo_string = previous_help_echo_string;
4896
4897 XSETFRAME (frame, emacsframe);
4898 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
4899 {
4900 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
4901 (note_mouse_highlight), which is called through the
4902 note_mouse_movement () call above */
4903 gen_help_event (help_echo_string, frame, help_echo_window,
4904 help_echo_object, help_echo_pos);
4905 }
4906 else
4907 {
4908 help_echo_string = Qnil;
4909 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
4910 }
4911
4912 if (emacsframe->mouse_moved && send_appdefined)
4913 ns_send_appdefined (-1);
4914}
4915
4916
4917- (void)mouseDragged: (NSEvent *)e
4918{
4919 NSTRACE (mouseDragged);
4920 [self mouseMoved: e];
4921}
4922
4923
4924- (void)rightMouseDragged: (NSEvent *)e
4925{
4926 NSTRACE (rightMouseDragged);
4927 [self mouseMoved: e];
4928}
4929
4930
19454c0a
AR
4931- (void)otherMouseDragged: (NSEvent *)e
4932{
4933 NSTRACE (otherMouseDragged);
4934 [self mouseMoved: e];
4935}
4936
4937
edfda783
AR
4938- (BOOL)windowShouldClose: (id)sender
4939{
4940 NSEvent *e =[[self window] currentEvent];
4941
4942 NSTRACE (windowShouldClose);
4943 windowClosing = YES;
edfda783
AR
4944 if (!emacs_event)
4945 return NO;
4946 emacs_event->kind = DELETE_WINDOW_EVENT;
4947 emacs_event->modifiers = 0;
4948 emacs_event->code = 0;
4949 EV_TRAILER (e);
4950 /* Don't close this window, let this be done from lisp code. */
4951 return NO;
4952}
4953
4954
4955- (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
4956/* normalize frame to gridded text size */
4957{
4958 NSTRACE (windowWillResize);
4959/*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
4960
4961 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe,
4962#ifdef NS_IMPL_GNUSTEP
4963 frameSize.width + 3);
4964#else
4965 frameSize.width);
4966#endif
4967 if (cols < MINWIDTH)
4968 cols = MINWIDTH;
4969 frameSize.width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (emacsframe, cols);
4970
4971 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, frameSize.height
4972#ifdef NS_IMPL_GNUSTEP
4973 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe) + 3
4974 - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
4975#else
4976 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
4977 - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
4978#endif
4979 if (rows < MINHEIGHT)
4980 rows = MINHEIGHT;
4981 frameSize.height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows)
4982 + FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
4983 + FRAME_NS_TOOLBAR_HEIGHT (emacsframe);
4984#ifdef NS_IMPL_COCOA
4985 {
4986 /* this sets window title to have size in it; the wm does this under GS */
4987 NSRect r = [[self window] frame];
4988 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
4989 {
4990 if (old_title != 0)
4991 {
4992 xfree (old_title);
4993 old_title = 0;
4994 }
4995 }
4996 else
4997 {
4998 char *size_title;
4999 NSWindow *window = [self window];
5000 if (old_title == 0)
5001 {
5002 const char *t = [[[self window] title] UTF8String];
5003 char *pos = strstr (t, " — ");
5004 if (pos)
5005 *pos = '\0';
5006 old_title = (char *) xmalloc (strlen (t) + 1);
5007 strcpy (old_title, t);
5008 }
5009 size_title = xmalloc (strlen (old_title) + 40);
5010 sprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
5011 [window setTitle: [NSString stringWithUTF8String: size_title]];
5012 [window display];
5013 xfree (size_title);
5014 }
5015 }
5016#endif /* NS_IMPL_COCOA */
5017/*fprintf (stderr," ...size became %.0f x %.0f (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
5018
5019 return frameSize;
5020}
5021
5022
5023- (void)windowDidResize: (NSNotification *)notification
5024{
5025 NSWindow *theWindow = [notification object];
5026
5027#ifdef NS_IMPL_GNUSTEP
5028 /* in GNUstep, at least currently, it's possible to get a didResize
5029 without getting a willResize.. therefore we need to act as if we got
5030 the willResize now */
5031 NSSize sz = [theWindow frame].size;
5032 sz = [self windowWillResize: theWindow toSize: sz];
5033#endif /* NS_IMPL_GNUSTEP */
5034
5035 NSTRACE (windowDidResize);
5036/*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
5037
5038#ifdef NS_IMPL_COCOA
5039 if (old_title != 0)
5040 {
5041 xfree (old_title);
5042 old_title = 0;
5043 }
5044#endif /* NS_IMPL_COCOA */
5045
5046 if (cols > 0 && rows > 0)
5047 x_set_window_size (emacsframe, 0, cols, rows);
5048
5049 ns_send_appdefined (-1);
1caf0534 5050
4e622592 5051 /* The following line causes a crash on GNUstep. Adrian Robert
1caf0534
CY
5052 says he doesn't remember why he added this line, but removing it
5053 doesn't seem to cause problems on OSX, either. */
5054#if 0
edfda783 5055 [NSApp stopModal];
1caf0534 5056#endif
edfda783
AR
5057}
5058
5059
5060- (void)windowDidBecomeKey: (NSNotification *)notification
c8c057de 5061/* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
edfda783 5062{
edfda783 5063 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
9e50ff0c 5064 struct frame *old_focus = dpyinfo->x_focus_frame;
edfda783
AR
5065
5066 NSTRACE (windowDidBecomeKey);
5067
5068 if (emacsframe != old_focus)
9e50ff0c 5069 dpyinfo->x_focus_frame = emacsframe;
81cfe31c 5070
edfda783
AR
5071 ns_frame_rehighlight (emacsframe);
5072
5073 if (emacs_event)
5074 {
5075 emacs_event->kind = FOCUS_IN_EVENT;
5076 EV_TRAILER ((id)nil);
5077 }
5078}
5079
5080
5081- (void)windowDidResignKey: (NSNotification *)notification
c8c057de 5082/* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
edfda783
AR
5083{
5084 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5085 NSTRACE (windowDidResignKey);
5086
9e50ff0c
DN
5087 if (dpyinfo->x_focus_frame == emacsframe)
5088 dpyinfo->x_focus_frame = 0;
edfda783 5089
c8c057de
AR
5090 ns_frame_rehighlight (emacsframe);
5091
5092 /* FIXME: for some reason needed on second and subsequent clicks away
5093 from sole-frame Emacs to get hollow box to show */
5094 if (!windowClosing && [[self window] isVisible] == YES)
59bc82c0
SZ
5095 {
5096 x_update_cursor (emacsframe, 1);
5097 x_set_frame_alpha (emacsframe);
5098 }
edfda783
AR
5099
5100 if (emacs_event)
5101 {
5102 [self deleteWorkingText];
5103 emacs_event->kind = FOCUS_IN_EVENT;
5104 EV_TRAILER ((id)nil);
5105 }
5106}
5107
5108
5109- (void)windowWillMiniaturize: sender
5110{
5111 NSTRACE (windowWillMiniaturize);
5112}
5113
5114
5115- (BOOL)isFlipped
5116{
5117 return YES;
5118}
5119
5120
5121- (BOOL)isOpaque
5122{
5123 return NO;
5124}
5125
5126
5127- initFrameFromEmacs: (struct frame *)f
5128{
5129 NSRect r, wr;
5130 Lisp_Object tem;
5131 NSWindow *win;
5132 NSButton *toggleButton;
5133 int vbextra = NS_SCROLL_BAR_WIDTH (f);
5134 NSSize sz;
5135 NSColor *col;
5136 NSString *name;
5137
5138 NSTRACE (initFrameFromEmacs);
5139
5140 windowClosing = NO;
5141 processingCompose = NO;
5142 scrollbarsNeedingUpdate = 0;
5143
5144/*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
5145
5146 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
5147 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
5148 [self initWithFrame: r];
5149
5150 FRAME_NS_VIEW (f) = self;
5151 emacsframe = f;
5152 old_title = 0;
5153
5154 win = [[EmacsWindow alloc]
5155 initWithContentRect: r
5156 styleMask: (NSResizableWindowMask |
5157 NSMiniaturizableWindowMask |
5158 NSClosableWindowMask)
5159 backing: NSBackingStoreBuffered
5160 defer: YES];
5161
5162 wr = [win frame];
5163 f->border_width = wr.size.width - r.size.width;
5164 FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
5165
5166 [win setAcceptsMouseMovedEvents: YES];
5167 [win setDelegate: self];
5168 [win useOptimizedDrawing: YES];
5169
5170 sz.width = FRAME_COLUMN_WIDTH (f);
5171 sz.height = FRAME_LINE_HEIGHT (f);
5172 [win setResizeIncrements: sz];
5173
5174 [[win contentView] addSubview: self];
5175
5176 if (ns_drag_types)
5177 [self registerForDraggedTypes: ns_drag_types];
5178
5179 tem = f->name;
5180 name = [NSString stringWithUTF8String:
6882361b 5181 NILP (tem) ? (unsigned char *)"Emacs" : SDATA (tem)];
edfda783
AR
5182 [win setTitle: name];
5183
5184 /* toolbar support */
5185 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
5186 [NSString stringWithFormat: @"Emacs Frame %d",
5187 ns_window_num]];
5188 [win setToolbar: toolbar];
5189 [toolbar setVisible: NO];
5190#ifdef NS_IMPL_COCOA
5191 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
5192 [toggleButton setTarget: self];
5193 [toggleButton setAction: @selector (toggleToolbar: )];
5194#endif
5195 FRAME_NS_TOOLBAR_HEIGHT (f) = 0;
5196
5197 tem = f->icon_name;
5198 if (!NILP (tem))
5199 [win setMiniwindowTitle:
6882361b 5200 [NSString stringWithUTF8String: SDATA (tem)]];
edfda783
AR
5201
5202 {
5203 NSScreen *screen = [win screen];
5204
5205 if (screen != 0)
5206 [win setFrameTopLeftPoint: NSMakePoint
5207 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
5208 IN_BOUND (-SCREENMAX,
5209 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
5210 }
5211
5212 [win makeFirstResponder: self];
5213
5214 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5215 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
5216 [win setBackgroundColor: col];
5217 if ([col alphaComponent] != 1.0)
5218 [win setOpaque: NO];
5219
5220 [self allocateGState];
5221
5222 ns_window_num++;
5223 return self;
5224}
5225
5226
5227- (void)windowDidMove: sender
5228{
5229 NSWindow *win = [self window];
5230 NSRect r = [win frame];
5231 NSScreen *screen = [win screen];
5232 NSRect sr = [screen frame];
5233
5234 NSTRACE (windowDidMove);
5235
5236 if (!emacsframe->output_data.ns)
5237 return;
5238 if (screen != nil)
5239 {
5240 emacsframe->left_pos = r.origin.x; /* - sr.origin.x; */
5241 emacsframe->top_pos = sr.size.height -
5242 (r.origin.y + r.size.height); /* + sr.origin.y; */
5243 }
5244}
5245
5246#ifdef NS_IMPL_COCOA
5247/* if we don't do this manually, the window will resize but not move */
5248- (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
5249{
5250 [[self window] setFrame: newFrame display: NO];
5251 return YES;
5252}
5253#endif
5254
5255/* Implement this to control size of frame on zoom.
5256- (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
5257 defaultFrame:(NSRect)defaultFrame; */
5258
5259
5260- (void)windowDidDeminiaturize: sender
5261{
5262 NSTRACE (windowDidDeminiaturize);
5263 if (!emacsframe->output_data.ns)
5264 return;
5265 emacsframe->async_visible = 1;
5266 emacsframe->async_iconified = 0;
5267 windows_or_buffers_changed++;
5268
5269 if (emacs_event)
5270 {
5271 emacs_event->kind = ICONIFY_EVENT;
5272 EV_TRAILER ((id)nil);
5273 }
5274}
5275
5276
5277- (void)windowDidExpose: sender
5278{
5279 NSTRACE (windowDidExpose);
5280 if (!emacsframe->output_data.ns)
5281 return;
5282 emacsframe->async_visible = 1;
5283 SET_FRAME_GARBAGED (emacsframe);
5284
5285 if (send_appdefined)
5286 ns_send_appdefined (-1);
5287}
5288
5289
5290- (void)windowDidMiniaturize: sender
5291{
5292 NSTRACE (windowDidMiniaturize);
5293 if (!emacsframe->output_data.ns)
5294 return;
5295
5296 emacsframe->async_iconified = 1;
5297
5298 if (emacs_event)
5299 {
5300 emacs_event->kind = ICONIFY_EVENT;
5301 EV_TRAILER ((id)nil);
5302 }
5303}
5304
5305
5306- (void)mouseEntered: (NSEvent *)theEvent
5307{
5308 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5309 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5310 NSTRACE (mouseEntered);
5311
5312 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5313}
5314
5315
5316- (void)mouseExited: (NSEvent *)theEvent
5317{
5318 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5319 NSRect r;
facfbbbd
SM
5320 struct ns_display_info *dpyinfo
5321 = emacsframe ? FRAME_NS_DISPLAY_INFO (emacsframe) : NULL;
edfda783
AR
5322
5323 NSTRACE (mouseExited);
5324
5325 if (dpyinfo || !emacsframe)
5326 return;
5327
5328 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5329
5330 if (emacsframe == dpyinfo->mouse_face_mouse_frame)
5331 {
5332 clear_mouse_face (dpyinfo);
5333 dpyinfo->mouse_face_mouse_frame = 0;
5334 }
5335}
5336
5337
5338- menuDown: sender
5339{
5340 NSTRACE (menuDown);
5341 if (context_menu_value == -1)
5342 context_menu_value = [sender tag];
5343 else
5344 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
15034960
AR
5345 emacsframe->menu_bar_vector,
5346 (void *)[sender tag]);
edfda783
AR
5347 ns_send_appdefined (-1);
5348 return self;
5349}
5350
5351
5352- (EmacsToolbar *)toolbar
5353{
5354 return toolbar;
5355}
5356
5357
5358/* this gets called on toolbar button click */
5359- toolbarClicked: (id)item
5360{
5361 NSEvent *theEvent;
5362 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
5363
5364 NSTRACE (toolbarClicked);
5365
5366 if (!emacs_event)
5367 return self;
5368
5369 /* send first event (for some reason two needed) */
5370 theEvent =[[self window] currentEvent];
5371 emacs_event->kind = TOOL_BAR_EVENT;
5372 XSETFRAME (emacs_event->arg, emacsframe);
5373 EV_TRAILER (theEvent);
5374
5375 emacs_event->kind = TOOL_BAR_EVENT;
5376/* XSETINT (emacs_event->code, 0); */
5377 emacs_event->arg = AREF (emacsframe->tool_bar_items,
5378 idx + TOOL_BAR_ITEM_KEY);
5379 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5380 EV_TRAILER (theEvent);
5381 return self;
5382}
5383
5384
5385- toggleToolbar: (id)sender
5386{
5387 Lisp_Object lispFrame;
5388 XSETFRAME (lispFrame, emacsframe);
5389 Feval (Fcons (intern ("ns-toggle-toolbar"), Fcons (lispFrame, Qnil)));
5390 SET_FRAME_GARBAGED (emacsframe);
5391 ns_send_appdefined (-1);
5392}
5393
5394
5395- (void)drawRect: (NSRect)rect
5396{
5397 int x = NSMinX (rect), y = NSMinY (rect);
5398 int width = NSWidth (rect), height = NSHeight (rect);
5399
5400 NSTRACE (drawRect);
5401
5402 if (!emacsframe || !emacsframe->output_data.ns)
5403 return;
5404
5405 if (!ns_in_resize)
5406 ns_clear_frame_area (emacsframe, x, y, width, height);
5407 expose_frame (emacsframe, x, y, width, height);
5408
5409 emacsframe->async_visible = 1;
5410 emacsframe->async_iconified = 0;
5411
5412/* SET_FRAME_GARBAGED (emacsframe);
5413 ns_send_appdefined (-1); */
5414}
5415
5416
5417/* NSDraggingDestination protocol methods. Actually this is not really a
5418 protocol, but a category of Object. O well... */
5419
5420-(unsigned int) draggingEntered: (id <NSDraggingInfo>) sender
5421{
5422 NSTRACE (draggingEntered);
5423 return NSDragOperationGeneric;
5424}
5425
5426
5427-(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
5428{
5429 return YES;
5430}
5431
5432
5433-(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
5434{
5435 id pb;
5436 int x, y;
5437 NSString *type;
5438 NSEvent *theEvent = [[self window] currentEvent];
5439 NSPoint position;
5440
5441 NSTRACE (performDragOperation);
5442
5443 if (!emacs_event)
5444 return;
5445
5446 position = [self convertPoint: [sender draggingLocation] fromView: nil];
5447 x = lrint (position.x); y = lrint (position.y);
5448
5449 pb = [sender draggingPasteboard];
5450 type = [pb availableTypeFromArray: ns_drag_types];
5451 if (type == 0)
5452 {
5453 return NO;
5454 }
5455 else if ([type isEqualToString: NSFilenamesPboardType])
5456 {
5457 NSArray *files;
5458 NSEnumerator *fenum;
5459 NSString *file;
5460
5461 if (!(files = [pb propertyListForType: type]))
5462 return NO;
5463
5464 fenum = [files objectEnumerator];
5465 while ( (file = [fenum nextObject]) )
5466 {
5467 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5468 emacs_event->code = KEY_NS_DRAG_FILE;
5469 XSETINT (emacs_event->x, x);
5470 XSETINT (emacs_event->y, y);
5471 ns_input_file = append2 (ns_input_file,
5472 build_string ([file UTF8String]));
5473 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5474 EV_TRAILER (theEvent);
5475 }
5476 return YES;
5477 }
5478 else if ([type isEqualToString: NSURLPboardType])
5479 {
5480 NSString *file;
5481 NSURL *fileURL;
5482
5483 if (!(fileURL = [NSURL URLFromPasteboard: pb]) ||
5484 [fileURL isFileURL] == NO)
5485 return NO;
5486
5487 file = [fileURL path];
5488 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5489 emacs_event->code = KEY_NS_DRAG_FILE;
5490 XSETINT (emacs_event->x, x);
5491 XSETINT (emacs_event->y, y);
5492 ns_input_file = append2 (ns_input_file, build_string ([file UTF8String]));
5493 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5494 EV_TRAILER (theEvent);
5495 return YES;
5496 }
5497 else if ([type isEqualToString: NSStringPboardType]
5498 || [type isEqualToString: NSTabularTextPboardType])
5499 {
5500 NSString *data;
5501
5502 if (! (data = [pb stringForType: type]))
5503 return NO;
5504
5505 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5506 emacs_event->code = KEY_NS_DRAG_TEXT;
5507 XSETINT (emacs_event->x, x);
5508 XSETINT (emacs_event->y, y);
5509 ns_input_text = build_string ([data UTF8String]);
5510 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5511 EV_TRAILER (theEvent);
5512 return YES;
5513 }
5514 else if ([type isEqualToString: NSColorPboardType])
5515 {
5516 NSColor *c = [NSColor colorFromPasteboard: pb];
5517 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5518 emacs_event->code = KEY_NS_DRAG_COLOR;
5519 XSETINT (emacs_event->x, x);
5520 XSETINT (emacs_event->y, y);
5521 ns_input_color = ns_color_to_lisp (c);
5522 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5523 EV_TRAILER (theEvent);
5524 return YES;
5525 }
5526 else if ([type isEqualToString: NSFontPboardType])
5527 {
5528 /* impl based on GNUstep NSTextView.m */
5529 NSData *data = [pb dataForType: NSFontPboardType];
5530 NSDictionary *dict = [NSUnarchiver unarchiveObjectWithData: data];
5531 NSFont *font = [dict objectForKey: NSFontAttributeName];
5532 char fontSize[10];
5533
5534 if (font == nil)
5535 return NO;
5536
5537 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5538 emacs_event->code = KEY_NS_CHANGE_FONT;
5539 XSETINT (emacs_event->x, x);
5540 XSETINT (emacs_event->y, y);
5541 ns_input_font = build_string ([[font fontName] UTF8String]);
5542 snprintf (fontSize, 10, "%f", [font pointSize]);
5543 ns_input_fontsize = build_string (fontSize);
5544 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5545 EV_TRAILER (theEvent);
5546 return YES;
5547 }
5548 else
5549 {
5550 error ("Invalid data type in dragging pasteboard.");
5551 return NO;
5552 }
5553}
5554
5555
5556- validRequestorForSendType: (NSString *)typeSent
5557 returnType: (NSString *)typeReturned
5558{
5559 NSTRACE (validRequestorForSendType);
5560 if ([ns_send_types indexOfObjectIdenticalTo: typeSent] != NSNotFound &&
5561 [ns_return_types indexOfObjectIdenticalTo: typeSent] != NSNotFound)
5562 return self;
5563
5564 return [super validRequestorForSendType: typeSent
5565 returnType: typeReturned];
5566}
5567
5568
5569/* setMini =YES means set from internal (gives a finder icon), NO means set nil
5570 (gives a miniaturized version of the window); currently we use the latter for
5571 frames whose active buffer doesn't correspond to any file
5572 (e.g., '*scratch*') */
5573- setMiniwindowImage: (BOOL) setMini
5574{
5575 id image = [[self window] miniwindowImage];
5576 NSTRACE (setMiniwindowImage);
5577
5578 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
5579 about "AppleDockIconEnabled" notwithstanding, however the set message
5580 below has its effect nonetheless. */
5581 if (image != emacsframe->output_data.ns->miniimage)
5582 {
5583 if (image && [image isKindOfClass: [EmacsImage class]])
5584 [image release];
5585 [[self window] setMiniwindowImage:
5586 setMini ? emacsframe->output_data.ns->miniimage : nil];
5587 }
5588
5589 return self;
5590}
5591
5592
5593- (void) setRows: (int) r andColumns: (int) c
5594{
5595 rows = r;
5596 cols = c;
5597}
5598
5599@end /* EmacsView */
5600
5601
5602
5603/* ==========================================================================
5604
5605 EmacsWindow implementation
5606
5607 ========================================================================== */
5608
5609@implementation EmacsWindow
5610
5611/* called only on resize clicks by special case in EmacsApp-sendEvent */
5612- (void)mouseDown: (NSEvent *)theEvent
5613{
5614 if (ns_in_resize)
5615 {
5616 NSSize size = [[theEvent window] frame].size;
5617 grabOffset = [theEvent locationInWindow];
5618 grabOffset.x = size.width - grabOffset.x;
5619 }
5620 else
5621 [super mouseDown: theEvent];
5622}
5623
5624
5625/* stop resizing */
5626- (void)mouseUp: (NSEvent *)theEvent
5627{
5628 if (ns_in_resize)
5629 {
5630 struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
5631 ns_in_resize = NO;
5632 ns_set_name_as_filename (f);
5633 [self display];
5634 ns_send_appdefined (-1);
5635 }
5636 else
5637 [super mouseUp: theEvent];
5638}
5639
5640
5641/* send resize events */
5642- (void)mouseDragged: (NSEvent *)theEvent
5643{
5644 if (ns_in_resize)
5645 {
5646 NSPoint p = [theEvent locationInWindow];
5647 NSSize size, vettedSize, origSize = [self frame].size;
5648
5649 size.width = p.x + grabOffset.x;
5650 size.height = origSize.height - p.y + grabOffset.y;
5651
5652 if (size.width == origSize.width && size.height == origSize.height)
5653 return;
5654
5655 vettedSize = [[self delegate] windowWillResize: self toSize: size];
5656 if (vettedSize.width != size.width || vettedSize.height != size.height)
5657 {
5658 [[NSNotificationCenter defaultCenter]
5659 postNotificationName: NSWindowDidResizeNotification
5660 object: self];
5661 }
5662 }
5663 else
5664 [super mouseDragged: theEvent];
5665}
5666
5667@end /* EmacsWindow */
5668
5669
5670/* ==========================================================================
5671
5672 EmacsScroller implementation
5673
5674 ========================================================================== */
5675
5676
5677@implementation EmacsScroller
5678
5679/* for repeat button push */
5680#define SCROLL_BAR_FIRST_DELAY 0.5
5681#define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
5682
5683+ (float) scrollerWidth
5684{
df2142db
AR
5685 /* TODO: if we want to allow variable widths, this is the place to do it,
5686 however neither GNUstep nor Cocoa support it very well */
edfda783
AR
5687 return [NSScroller scrollerWidth];
5688}
5689
5690
5691- initFrame: (NSRect )r window: (Lisp_Object)nwin
5692{
5693 NSTRACE (EmacsScroller_initFrame);
5694
5695 r.size.width = [EmacsScroller scrollerWidth];
5696 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
5697 [self setContinuous: YES];
5698 [self setEnabled: YES];
5699
5700 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
5701 locked against the right, top and bottom edges. */
5702 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
5703
5704 win = nwin;
5705 condemned = NO;
5706 pixel_height = NSHeight (r);
5707 min_portion = 20 / pixel_height;
5708
5709 frame = XFRAME (XWINDOW (win)->frame);
5710 if (FRAME_LIVE_P (frame))
5711 {
5712 int i;
5713 EmacsView *view = FRAME_NS_VIEW (frame);
5714 NSView *sview = [[view window] contentView];
5715 NSArray *subs = [sview subviews];
5716
5717 /* disable optimization stopping redraw of other scrollbars */
5718 view->scrollbarsNeedingUpdate = 0;
5719 for (i =[subs count]-1; i >= 0; i--)
5720 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
5721 view->scrollbarsNeedingUpdate++;
5722 [sview addSubview: self];
5723 }
5724
5725/* [self setFrame: r]; */
5726
5727 return self;
5728}
5729
5730
5731- (void)setFrame: (NSRect)newRect
5732{
5733 NSTRACE (EmacsScroller_setFrame);
5734/* BLOCK_INPUT; */
5735 pixel_height = NSHeight (newRect);
5736 min_portion = 20 / pixel_height;
5737 [super setFrame: newRect];
5738 [self display];
5739/* UNBLOCK_INPUT; */
5740}
5741
5742
5743- (void)dealloc
5744{
5745 NSTRACE (EmacsScroller_dealloc);
5746 if (!NILP (win))
5747 XWINDOW (win)->vertical_scroll_bar = Qnil;
5748 [super dealloc];
5749}
5750
5751
5752- condemn
5753{
5754 NSTRACE (condemn);
5755 condemned =YES;
5756 return self;
5757}
5758
5759
5760- reprieve
5761{
5762 NSTRACE (reprieve);
5763 condemned =NO;
5764 return self;
5765}
5766
5767
5768- judge
5769{
5770 NSTRACE (judge);
5771 if (condemned)
5772 {
5773 BLOCK_INPUT;
5774 /* ensure other scrollbar updates after deletion */
5775 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
5776 if (view != nil)
5777 view->scrollbarsNeedingUpdate++;
5778 [self removeFromSuperview];
5779 [self release];
5780 UNBLOCK_INPUT;
5781 }
5782 return self;
5783}
5784
5785
5786- (void)resetCursorRects
5787{
5788 NSRect visible = [self visibleRect];
5789 NSTRACE (resetCursorRects);
5790
5791 if (!NSIsEmptyRect (visible))
5792 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
5793 [[NSCursor arrowCursor] setOnMouseEntered: YES];
5794}
5795
5796
5797- (int) checkSamePosition: (int) position portion: (int) portion
5798 whole: (int) whole
5799{
5800 return em_position ==position && em_portion ==portion && em_whole ==whole
5801 && portion != whole; /* needed for resize empty buf */
5802}
5803
5804
5805- setPosition: (int)position portion: (int)portion whole: (int)whole
5806{
5807 NSTRACE (setPosition);
5808
5809 em_position = position;
5810 em_portion = portion;
5811 em_whole = whole;
5812
5813 if (portion >= whole)
5814 [self setFloatValue: 0.0 knobProportion: 1.0];
5815 else
5816 {
5817 float pos, por;
5818 portion = max ((float)whole*min_portion/pixel_height, portion);
5819 pos = (float)position / (whole - portion);
5820 por = (float)portion/whole;
5821 [self setFloatValue: pos knobProportion: por];
5822 }
5823#ifdef NS_IMPL_GNUSTEP
5824 [self display];
5825#endif
5826 return self;
5827}
5828
df2142db
AR
5829/* FIXME: unused at moment (see ns_mouse_position) at the moment because
5830 drag events will go directly to the EmacsScroller. Leaving in for now. */
edfda783
AR
5831-(void)getMouseMotionPart: (int *)part window: (Lisp_Object *)window
5832 x: (Lisp_Object *)x y: ( Lisp_Object *)y
5833{
5834 *part = last_hit_part;
5835 *window = win;
5836 XSETINT (*y, pixel_height);
5837 if ([self floatValue] > 0.999)
5838 XSETINT (*x, pixel_height);
5839 else
5840 XSETINT (*x, pixel_height * [self floatValue]);
5841}
5842
5843
5844/* set up emacs_event */
5845- (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
5846{
5847 if (!emacs_event)
5848 return;
5849
5850 emacs_event->part = last_hit_part;
5851 emacs_event->code = 0;
5852 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
5853 emacs_event->frame_or_window = win;
5854 emacs_event->timestamp = EV_TIMESTAMP (e);
5855 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
5856 emacs_event->arg = Qnil;
5857 XSETINT (emacs_event->x, loc * pixel_height);
5858 XSETINT (emacs_event->y, pixel_height-20);
5859
5860 n_emacs_events_pending++;
5861 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
5862 EVENT_INIT (*emacs_event);
5863 ns_send_appdefined (-1);
5864}
5865
5866
5867/* called manually thru timer to implement repeated button action w/hold-down */
5868- repeatScroll: (NSTimer *)scrollEntry
5869{
5870 NSEvent *e = [[self window] currentEvent];
5871 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
5872 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
5873
5874 /* clear timer if need be */
5875 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
5876 {
5877 [scroll_repeat_entry invalidate];
5878 [scroll_repeat_entry release];
5879 scroll_repeat_entry = nil;
5880
5881 if (inKnob)
5882 return self;
5883
facfbbbd
SM
5884 scroll_repeat_entry
5885 = [[NSTimer scheduledTimerWithTimeInterval:
5886 SCROLL_BAR_CONTINUOUS_DELAY
edfda783
AR
5887 target: self
5888 selector: @selector (repeatScroll:)
5889 userInfo: 0
5890 repeats: YES]
facfbbbd 5891 retain];
edfda783
AR
5892 }
5893
5894 [self sendScrollEventAtLoc: 0 fromEvent: e];
5895 return self;
5896}
5897
5898
5899/* Asynchronous mouse tracking for scroller. This allows us to dispatch
5900 mouseDragged events without going into a modal loop. */
5901- (void)mouseDown: (NSEvent *)e
5902{
5903 NSRect sr, kr;
5904 /* hitPart is only updated AFTER event is passed on */
5905 NSScrollerPart part = [self testPart: [e locationInWindow]];
5906 double inc = 0.0, loc, kloc, pos;
5907 int edge = 0;
5908
5909 NSTRACE (EmacsScroller_mouseDown);
5910
5911 switch (part)
5912 {
5913 case NSScrollerDecrementPage:
5914 last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
5915 case NSScrollerIncrementPage:
5916 last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
5917 case NSScrollerDecrementLine:
5918 last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
5919 case NSScrollerIncrementLine:
5920 last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
5921 case NSScrollerKnob:
5922 last_hit_part = scroll_bar_handle; break;
5923 case NSScrollerKnobSlot: /* GNUstep-only */
5924 last_hit_part = scroll_bar_move_ratio; break;
5925 default: /* NSScrollerNoPart? */
5926 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %d\n", part);
5927 return;
5928 }
5929
5930 if (inc != 0.0)
5931 {
5932 pos = 0; /* ignored */
5933
5934 /* set a timer to repeat, as we can't let superclass do this modally */
facfbbbd
SM
5935 scroll_repeat_entry
5936 = [[NSTimer scheduledTimerWithTimeInterval: 0.5
5937 target: self
5938 selector: @selector (repeatScroll:)
5939 userInfo: 0
5940 repeats: YES]
5941 retain];
edfda783
AR
5942 }
5943 else
5944 {
5945 /* handle, or on GNUstep possibly slot */
5946 NSEvent *fake_event;
5947
5948 /* compute float loc in slot and mouse offset on knob */
5949 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
5950 toView: nil];
5951 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
5952 if (loc <= 0.0)
5953 {
5954 loc = 0.0;
5955 edge = -1;
5956 }
5957 else if (loc >= NSHeight (sr))
5958 {
5959 loc = NSHeight (sr);
5960 edge = 1;
5961 }
5962
5963 if (edge)
5964 kloc = 0.5 * edge;
5965 else
5966 {
5967 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
5968 toView: nil];
5969 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
5970 }
5971 last_mouse_offset = kloc;
5972
5973 /* if knob, tell emacs a location offset by knob pos
5974 (to indicate top of handle) */
5975 if (part == NSScrollerKnob)
5976 pos = (loc - last_mouse_offset) / NSHeight (sr);
5977 else
5978 /* else this is a slot click on GNUstep: go straight there */
5979 pos = loc / NSHeight (sr);
5980
5981 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
5982 fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
5983 location: [e locationInWindow]
5984 modifierFlags: [e modifierFlags]
5985 timestamp: [e timestamp]
5986 windowNumber: [e windowNumber]
5987 context: [e context]
5988 eventNumber: [e eventNumber]
5989 clickCount: [e clickCount]
5990 pressure: [e pressure]];
5991 [super mouseUp: fake_event];
5992 }
5993
5994 if (part != NSScrollerKnob)
5995 [self sendScrollEventAtLoc: pos fromEvent: e];
5996}
5997
5998
5999/* Called as we manually track scroller drags, rather than superclass. */
6000- (void)mouseDragged: (NSEvent *)e
6001{
6002 NSRect sr;
6003 double loc, pos;
6004 int edge = 0;
6005
6006 NSTRACE (EmacsScroller_mouseDragged);
6007
6008 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
6009 toView: nil];
6010 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
6011
6012 if (loc <= 0.0)
6013 {
6014 loc = 0.0;
6015 edge = -1;
6016 }
6017 else if (loc >= NSHeight (sr) + last_mouse_offset)
6018 {
6019 loc = NSHeight (sr) + last_mouse_offset;
6020 edge = 1;
6021 }
6022
6023 pos = /*(edge ? loc :*/ (loc - last_mouse_offset) / NSHeight (sr);
6024 [self sendScrollEventAtLoc: pos fromEvent: e];
6025}
6026
6027
6028- (void)mouseUp: (NSEvent *)e
6029{
6030 if (scroll_repeat_entry)
6031 {
6032 [scroll_repeat_entry invalidate];
6033 [scroll_repeat_entry release];
6034 scroll_repeat_entry = nil;
6035 }
6036 last_hit_part = 0;
6037}
6038
6039
6040/* treat scrollwheel events in the bar as though they were in the main window */
6041- (void) scrollWheel: (NSEvent *)theEvent
6042{
6043 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
6044 [view mouseDown: theEvent];
6045}
6046
6047@end /* EmacsScroller */
6048
6049
6050
6051/* ==========================================================================
6052
6053 EmacsPrefsController implementation
6054
6055 ========================================================================== */
6056
6057
6058@implementation EmacsPrefsController
6059
6060/* in Tiger+, can just do [popup selectItemWithTag: tag]; */
6061static void selectItemWithTag (NSPopUpButton *popup, int tag)
6062{
6063 NSEnumerator *items = [[popup itemArray] objectEnumerator];
6064 NSMenuItem *item;
6065 while (item = [items nextObject])
6066 {
6067 if ([item tag] == tag)
6068 {
6069 [popup selectItem: item];
6070 return;
6071 }
6072 }
6073}
6074
6075- init
6076{
6077 [NSBundle loadNibNamed: @"preferences" owner: self];
6078 return self;
6079}
6080
6081
6082- (void) showForFrame: (struct frame *)f
6083{
6084 frame = f;
6085 [self setPanelFromValues];
6086 [prefsWindow makeKeyAndOrderFront: self];
6087 [prefsWindow display];
6088}
6089
6090
6049d3a0 6091/* If you change this, change setPanelFromDefaultValues too. */
edfda783
AR
6092- (void) setPanelFromValues
6093{
facfbbbd
SM
6094 int cursorType
6095 = ns_lisp_to_cursor_type (get_frame_param (frame, Qcursor_type));
edfda783 6096 prevExpandSpace = XFLOATINT (ns_expand_space);
edfda783
AR
6097
6098#ifdef NS_IMPL_COCOA
6099 prevUseHighlightColor = ns_use_system_highlight_color;
6100#endif
6101
6102 [expandSpaceSlider setFloatValue: prevExpandSpace];
c8c057de
AR
6103 [cursorTypeMatrix selectCellWithTag: (cursorType == FILLED_BOX_CURSOR ? 1 :
6104 (cursorType == BAR_CURSOR ? 2 :
6105 (cursorType == HBAR_CURSOR ? 3 : 4)))];
6882361b
SM
6106 selectItemWithTag (alternateModMenu,
6107 parse_solitary_modifier (ns_alternate_modifier));
6108 selectItemWithTag (commandModMenu,
6109 parse_solitary_modifier (ns_command_modifier));
edfda783 6110#ifdef NS_IMPL_COCOA
6882361b
SM
6111 selectItemWithTag (controlModMenu,
6112 parse_solitary_modifier (ns_control_modifier));
6113 selectItemWithTag (functionModMenu,
6114 parse_solitary_modifier (ns_function_modifier));
5c976973
AR
6115 [smoothFontsCheck setState: (NILP (ns_antialias_text) ? NO : YES)];
6116 [useQuickdrawCheck setState: (NILP (ns_use_qd_smoothing) ? NO : YES)];
6117 [useSysHiliteCheck setState: (NILP (prevUseHighlightColor) ? NO : YES)];
edfda783
AR
6118#endif
6119}
6120
6121
6049d3a0
AR
6122/* This and ns_set_default_prefs should be changed together. */
6123- (void) setPanelFromDefaultValues
6124{
6125 [expandSpaceSlider setFloatValue: 0.0];
6126 [cursorTypeMatrix selectCellWithTag: 1]; /* filled box */
6127 selectItemWithTag (alternateModMenu, meta_modifier);
6128 selectItemWithTag (commandModMenu, super_modifier);
6129#ifdef NS_IMPL_COCOA
6130 selectItemWithTag (controlModMenu, ctrl_modifier);
6131 selectItemWithTag (functionModMenu, 0); /* none */
6132 [smoothFontsCheck setState: YES];
6133 [useQuickdrawCheck setState: NO];
6134 [useSysHiliteCheck setState: YES];
6135#endif
6136}
6137
6138
edfda783
AR
6139- (void) setValuesFromPanel
6140{
edfda783
AR
6141 int altTag = [[alternateModMenu selectedItem] tag];
6142 int cmdTag = [[commandModMenu selectedItem] tag];
6143#ifdef NS_IMPL_COCOA
6144 int ctrlTag = [[controlModMenu selectedItem] tag];
6145 int fnTag = [[functionModMenu selectedItem] tag];
6146#endif
edfda783 6147 float expandSpace = [expandSpaceSlider floatValue];
c8c057de
AR
6148 int cursorTag = [[cursorTypeMatrix selectedCell] tag];
6149 Lisp_Object cursor_type = ns_cursor_type_to_lisp
6150 ( cursorTag == 1 ? FILLED_BOX_CURSOR
6151 : cursorTag == 2 ? BAR_CURSOR
6152 : cursorTag == 3 ? HBAR_CURSOR : HOLLOW_BOX_CURSOR);
edfda783
AR
6153
6154 if (expandSpace != prevExpandSpace)
6155 {
6156 ns_expand_space = make_float (expandSpace);
df2142db 6157 /* TODO: more needed: store needed metrics in nsfont_info, update
edfda783
AR
6158 frame default font max_bounds and fontp, recompute faces */
6159/* FRAME_LINE_HEIGHT (frame) *= (expandSpace / prevExpandSpace);
6160 x_set_window_size (frame, 0, frame->text_cols, frame->text_lines); */
6161 prevExpandSpace = expandSpace;
6162 }
c8c057de
AR
6163
6164 store_frame_param (frame, Qcursor_type, cursor_type);
89e2438a 6165 x_set_cursor_type (frame, cursor_type, Qnil); /* FIXME: do only if changed */
c8c057de 6166
edfda783
AR
6167 ns_alternate_modifier = ns_mod_to_lisp (altTag);
6168 ns_command_modifier = ns_mod_to_lisp (cmdTag);
6169#ifdef NS_IMPL_COCOA
6170 ns_control_modifier = ns_mod_to_lisp (ctrlTag);
6171 ns_function_modifier = ns_mod_to_lisp (fnTag);
5c976973
AR
6172 ns_antialias_text = [smoothFontsCheck state] ? Qt : Qnil;
6173 ns_use_qd_smoothing = [useQuickdrawCheck state] ? Qt : Qnil;
6174 ns_use_system_highlight_color = [useSysHiliteCheck state] ? Qt : Qnil;
6175 if (! EQ (ns_use_system_highlight_color, prevUseHighlightColor))
edfda783
AR
6176 {
6177 prevUseHighlightColor = ns_use_system_highlight_color;
5c976973 6178 if (EQ (ns_use_system_highlight_color, Qt))
edfda783
AR
6179 {
6180 ns_selection_color = [[NSUserDefaults standardUserDefaults]
6181 stringForKey: @"AppleHighlightColor"];
6182 if (ns_selection_color == nil)
6183 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
6184 }
6185 else
6186 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
6187 }
6188#endif /* NS_IMPL_COCOA */
6189 Fcall_interactively (intern ("ns-save-preferences"), Qnil, Qnil);
6190}
6191
6192
6193/* buttons */
6194- (IBAction)cancel: (id)sender
6195{
6196 [prefsWindow close];
6197}
6198
6199
6200- (IBAction)ok: (id)sender
6201{
6202 [self setValuesFromPanel];
6203 [prefsWindow close];
6204}
6205
6206
6207- (IBAction)resetToDefaults: (id)sender
6208{
6049d3a0 6209 [self setPanelFromDefaultValues];
edfda783
AR
6210}
6211
6212
6213- (IBAction)runHelp: (id)sender
6214{
6215 Feval (Fcons (intern ("info"),
e889fa06
AR
6216 Fcons (build_string ("(emacs)Mac / GNUstep Customization"),
6217 Qnil)));
edfda783
AR
6218 SET_FRAME_GARBAGED (frame);
6219 ns_send_appdefined (-1);
6220}
6221
6222
6223- (IBAction)setColors: (id)sender
6224{
6225 Lisp_Object lispFrame;
6226 XSETFRAME (lispFrame, frame);
e889fa06 6227 ns_raise_frame(frame);
edfda783
AR
6228 Fns_popup_color_panel (lispFrame);
6229}
6230
6231
6232- (IBAction)setDefaultFont: (id)sender
6233{
6234 Lisp_Object lispFrame;
6235 XSETFRAME (lispFrame, frame);
e889fa06 6236 ns_raise_frame(frame);
edfda783
AR
6237 Fns_popup_font_panel (lispFrame);
6238}
6239
6240@end /* EmacsPrefsController */
6241
6242
6243
6244
6245/* ==========================================================================
6246
6247 Font-related functions; these used to be in nsfaces.m
6248
6249 ========================================================================== */
6250
6251
6252Lisp_Object
6253x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
6254{
6255 struct font *font = XFONT_OBJECT (font_object);
6256
6257 if (fontset < 0)
6258 fontset = fontset_from_font (font_object);
6259 FRAME_FONTSET (f) = fontset;
6260
6261 if (FRAME_FONT (f) == font)
6262 /* This font is already set in frame F. There's nothing more to
6263 do. */
6264 return font_object;
6265
6266 FRAME_FONT (f) = font;
6267
6268 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
6269 FRAME_COLUMN_WIDTH (f) = font->average_width;
6270 FRAME_SPACE_WIDTH (f) = font->space_width;
6271 FRAME_LINE_HEIGHT (f) = font->height;
6272
6273 compute_fringe_widths (f, 1);
6274
6275 /* Compute the scroll bar width in character columns. */
6276 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
6277 {
6278 int wid = FRAME_COLUMN_WIDTH (f);
6279 FRAME_CONFIG_SCROLL_BAR_COLS (f)
6280 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
6281 }
6282 else
6283 {
6284 int wid = FRAME_COLUMN_WIDTH (f);
6285 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
6286 }
6287
6288 /* Now make the frame display the given font. */
6289 if (FRAME_NS_WINDOW (f) != 0)
6290 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
6291
6292 return font_object;
6293}
6294
6295
edfda783 6296/* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
35ed44db
AR
6297/* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
6298 in 1.43. */
edfda783
AR
6299
6300const char *
6301ns_xlfd_to_fontname (const char *xlfd)
6302/* --------------------------------------------------------------------------
6303 Convert an X font name (XLFD) to an NS font name.
6304 Only family is used.
6305 The string returned is temporarily allocated.
6306 -------------------------------------------------------------------------- */
6307{
6308 char *name = xmalloc (180);
6309 int i, len;
6310 const char *ret;
e2749141 6311
edfda783
AR
6312 if (!strncmp (xlfd, "--", 2))
6313 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
6314 else
6315 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
6316
6317 /* stopgap for malformed XLFD input */
6318 if (strlen (name) == 0)
6319 strcpy (name, "Monaco");
6320
6321 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
6322 also uppercase after '-' or ' ' */
6323 name[0] = toupper (name[0]);
6324 for (len =strlen (name), i =0; i<len; i++)
6325 {
6326 if (name[i] == '$')
6327 {
6328 name[i] = '-';
6329 if (i+1<len)
6330 name[i+1] = toupper (name[i+1]);
6331 }
6332 else if (name[i] == '_')
6333 {
6334 name[i] = ' ';
6335 if (i+1<len)
6336 name[i+1] = toupper (name[i+1]);
6337 }
6338 }
6339/*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
6340 ret = [[NSString stringWithUTF8String: name] UTF8String];
6341 xfree (name);
6342 return ret;
6343}
0ae1e5e5 6344
15034960 6345
1baa6236
DN
6346void
6347syms_of_nsterm ()
6348{
6349 NSTRACE (syms_of_nsterm);
6350 DEFVAR_LISP ("ns-input-file", &ns_input_file,
6351 "The file specified in the last NS event.");
6352 ns_input_file =Qnil;
6353
6354 DEFVAR_LISP ("ns-input-text", &ns_input_text,
6355 "The data received in the last NS text drag event.");
6356 ns_input_text =Qnil;
6357
6358 DEFVAR_LISP ("ns-working-text", &ns_working_text,
6359 "String for visualizing working composition sequence.");
6360 ns_working_text =Qnil;
6361
6362 DEFVAR_LISP ("ns-input-font", &ns_input_font,
6363 "The font specified in the last NS event.");
6364 ns_input_font =Qnil;
6365
6366 DEFVAR_LISP ("ns-input-fontsize", &ns_input_fontsize,
6367 "The fontsize specified in the last NS event.");
6368 ns_input_fontsize =Qnil;
6369
6370 DEFVAR_LISP ("ns-input-line", &ns_input_line,
6371 "The line specified in the last NS event.");
6372 ns_input_line =Qnil;
6373
6374 DEFVAR_LISP ("ns-input-color", &ns_input_color,
6375 "The color specified in the last NS event.");
6376 ns_input_color =Qnil;
6377
6378 DEFVAR_LISP ("ns-input-spi-name", &ns_input_spi_name,
6379 "The service name specified in the last NS event.");
6380 ns_input_spi_name =Qnil;
6381
6382 DEFVAR_LISP ("ns-input-spi-arg", &ns_input_spi_arg,
6383 "The service argument specified in the last NS event.");
6384 ns_input_spi_arg =Qnil;
6385
6386 DEFVAR_LISP ("ns-alternate-modifier", &ns_alternate_modifier,
6387 "This variable describes the behavior of the alternate or option key.\n\
6388Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6389Set to none means that the alternate / option key is not interpreted by Emacs\n\
6390at all, allowing it to be used at a lower level for accented character entry.");
6391
6392 DEFVAR_LISP ("ns-command-modifier", &ns_command_modifier,
6393 "This variable describes the behavior of the command key.\n\
6394Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6395
6396 DEFVAR_LISP ("ns-control-modifier", &ns_control_modifier,
6397 "This variable describes the behavior of the control key.\n\
6398Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6399
6400 DEFVAR_LISP ("ns-function-modifier", &ns_function_modifier,
6401 "This variable describes the behavior of the function key (on laptops).\n\
6402Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6403Set to none means that the function key is not interpreted by Emacs at all,\n\
6404allowing it to be used at a lower level for accented character entry.");
6405
1baa6236
DN
6406 DEFVAR_LISP ("ns-expand-space", &ns_expand_space,
6407 "Amount by which spacing between lines is expanded (positive)\n\
6408or shrunk (negative). Zero (the default) means standard line height.\n\
6409(This variable should only be read, never set.)");
6410
6411 DEFVAR_LISP ("ns-antialias-text", &ns_antialias_text,
6412 "Non-nil (the default) means to render text antialiased. Only has an effect on OS X Panther and above.");
6413
6414 DEFVAR_LISP ("ns-use-qd-smoothing", &ns_use_qd_smoothing,
6415 "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).");
6416
6417 DEFVAR_LISP ("ns-use-system-highlight-color",
6418 &ns_use_system_highlight_color,
6419 "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'.");
6420
6421 staticpro (&ns_display_name_list);
6422 ns_display_name_list = Qnil;
6423
6424 staticpro (&last_mouse_motion_frame);
6425 last_mouse_motion_frame = Qnil;
6426
3fe53a83 6427 /* from 23+ we need to tell emacs what modifiers there are.. */
1baa6236
DN
6428 Qmodifier_value = intern ("modifier-value");
6429 Qalt = intern ("alt");
6430 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
6431 Qhyper = intern ("hyper");
6432 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
6433 Qmeta = intern ("meta");
6434 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
6435 Qsuper = intern ("super");
6436 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
6437 Qcontrol = intern ("control");
6438 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
6439
7ded3383 6440 /* TODO: move to common code */
1baa6236
DN
6441 DEFVAR_LISP ("x-toolkit-scroll-bars", &Vx_toolkit_scroll_bars,
6442 doc: /* If not nil, Emacs uses toolkit scroll bars. */);
6443#ifdef USE_TOOLKIT_SCROLL_BARS
6444 Vx_toolkit_scroll_bars = Qt;
6445#else
6446 Vx_toolkit_scroll_bars = Qnil;
6447#endif
6448
6449 /* these are unsupported but we need the declarations to avoid whining
6450 messages from cus-start.el */
6451 DEFVAR_BOOL ("x-use-underline-position-properties",
6452 &x_use_underline_position_properties,
6453 doc: /* NOT SUPPORTED UNDER NS.
6454*Non-nil means make use of UNDERLINE_POSITION font properties.
6455A value of nil means ignore them. If you encounter fonts with bogus
6456UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
6457to 4.1, set this to nil.
6458
6459NOTE: Not supported on Mac yet. */);
6460 x_use_underline_position_properties = 0;
6461
6462 DEFVAR_BOOL ("x-underline-at-descent-line",
6463 &x_underline_at_descent_line,
6464 doc: /* NOT SUPPORTED UNDER NS.
6465*Non-nil means to draw the underline at the same place as the descent line.
6466A value of nil means to draw the underline according to the value of the
6467variable `x-use-underline-position-properties', which is usually at the
6468baseline level. The default value is nil. */);
6469 x_underline_at_descent_line = 0;
6470
6471 /* Tell emacs about this window system. */
7c799cf5 6472 Fprovide (intern ("ns"), Qnil);
1baa6236
DN
6473}
6474
6475
2f8e74bb 6476// arch-tag: 6eaa8f7d-a69b-4e1c-b43d-ab31defbe0d2