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