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