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