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