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