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