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