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