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