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