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