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