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