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