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