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