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