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