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