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