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