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