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