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