(ns_draw_window_cursor): When hbar cursor is on over-sized glyph, draw
[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.width = min (FRAME_COLUMN_WIDTH (f), s.size.width);
2345 s.size.height = lrint (s.size.height * 0.25);
2346 NSRectFill (s);
2347 break;
2348 case BAR_CURSOR:
2349 s = r;
2350 s.size.width = min (cursor_width, 2); //FIXME(see above)
2351 NSRectFill (s);
2352 break;
2353 }
2354 ns_unfocus (f);
2355
2356 /* draw the character under the cursor */
2357 if (cursorToDraw != NO_CURSOR)
2358 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
2359
2360 #ifdef NS_IMPL_COCOA
2361 NSEnableScreenUpdates ();
2362 #endif
2363
2364 }
2365
2366
2367 static void
2368 ns_draw_vertical_window_border (struct window *w, int x, int y0, int y1)
2369 /* --------------------------------------------------------------------------
2370 External (RIF): Draw a vertical line.
2371 -------------------------------------------------------------------------- */
2372 {
2373 struct frame *f = XFRAME (WINDOW_FRAME (w));
2374 struct face *face;
2375 NSRect r = NSMakeRect (x, y0, 2, y1-y0);
2376
2377 NSTRACE (ns_draw_vertical_window_border);
2378
2379 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
2380 if (face)
2381 [ns_lookup_indexed_color(face->foreground, f) set];
2382
2383 ns_focus (f, &r, 1);
2384 NSDrawGroove (r, r);
2385 ns_unfocus (f);
2386 }
2387
2388
2389 void
2390 show_hourglass (struct atimer *timer)
2391 {
2392 if (hourglass_shown_p)
2393 return;
2394
2395 BLOCK_INPUT;
2396
2397 /* TODO: add NSProgressIndicator to selected frame (see macfns.c) */
2398
2399 hourglass_shown_p = 1;
2400 UNBLOCK_INPUT;
2401 }
2402
2403
2404 void
2405 hide_hourglass ()
2406 {
2407 if (!hourglass_shown_p)
2408 return;
2409
2410 BLOCK_INPUT;
2411
2412 /* TODO: remove NSProgressIndicator from all frames */
2413
2414 hourglass_shown_p = 0;
2415 UNBLOCK_INPUT;
2416 }
2417
2418
2419
2420 /* ==========================================================================
2421
2422 Glyph drawing operations
2423
2424 ========================================================================== */
2425
2426
2427 static inline NSRect
2428 ns_fix_rect_ibw (NSRect r, int fibw, int frame_pixel_width)
2429 /* --------------------------------------------------------------------------
2430 Under NS we draw internal borders inside fringes, and want full-width
2431 rendering to go all the way to edge. This function makes that correction.
2432 -------------------------------------------------------------------------- */
2433 {
2434 if (r.origin.y <= fibw+1)
2435 {
2436 r.size.height += r.origin.y;
2437 r.origin.y = 0;
2438 }
2439 if (r.origin.x <= fibw+1)
2440 {
2441 r.size.width += r.origin.x;
2442 r.origin.x = 0;
2443 }
2444 if (frame_pixel_width - (r.origin.x+r.size.width) <= fibw+1)
2445 r.size.width += fibw;
2446
2447 return r;
2448 }
2449
2450
2451 static int
2452 ns_get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
2453 /* --------------------------------------------------------------------------
2454 Wrapper utility to account for internal border width on full-width lines,
2455 and allow top full-width rows to hit the frame top. nr should be pointer
2456 to two successive NSRects. Number of rects actually used is returned.
2457 -------------------------------------------------------------------------- */
2458 {
2459 int n = get_glyph_string_clip_rects (s, nr, 2);
2460 if (s->row->full_width_p)
2461 {
2462 *nr = ns_fix_rect_ibw (*nr, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2463 FRAME_PIXEL_WIDTH (s->f));
2464 if (n == 2)
2465 *nr = ns_fix_rect_ibw (*(nr+1), FRAME_INTERNAL_BORDER_WIDTH (s->f),
2466 FRAME_PIXEL_WIDTH (s->f));
2467 }
2468 return n;
2469 }
2470
2471
2472 static void
2473 ns_draw_box (NSRect r, float thickness, NSColor *col, char left_p, char right_p)
2474 /* --------------------------------------------------------------------------
2475 Draw an unfilled rect inside r, optionally leaving left and/or right open.
2476 Note we can't just use an NSDrawRect command, because of the possibility
2477 of some sides not being drawn, and because the rect will be filled.
2478 -------------------------------------------------------------------------- */
2479 {
2480 NSRect s = r;
2481 [col set];
2482
2483 /* top, bottom */
2484 s.size.height = thickness;
2485 NSRectFill (s);
2486 s.origin.y += r.size.height - thickness;
2487 NSRectFill (s);
2488
2489 s.size.height = r.size.height;
2490 s.origin.y = r.origin.y;
2491
2492 /* left, right (optional) */
2493 s.size.width = thickness;
2494 if (left_p)
2495 NSRectFill (s);
2496 if (right_p)
2497 {
2498 s.origin.x += r.size.width - thickness;
2499 NSRectFill (s);
2500 }
2501 }
2502
2503
2504 static void
2505 ns_draw_relief (NSRect r, int thickness, char raised_p,
2506 char top_p, char bottom_p, char left_p, char right_p,
2507 struct glyph_string *s)
2508 /* --------------------------------------------------------------------------
2509 Draw a relief rect inside r, optionally leaving some sides open.
2510 Note we can't just use an NSDrawBezel command, because of the possibility
2511 of some sides not being drawn, and because the rect will be filled.
2512 -------------------------------------------------------------------------- */
2513 {
2514 static NSColor *baseCol = nil, *lightCol = nil, *darkCol = nil;
2515 NSColor *newBaseCol = nil;
2516 NSRect sr = r;
2517
2518 NSTRACE (ns_draw_relief);
2519
2520 /* set up colors */
2521
2522 if (s->face->use_box_color_for_shadows_p)
2523 {
2524 newBaseCol = ns_lookup_indexed_color (s->face->box_color, s->f);
2525 }
2526 /* else if (s->first_glyph->type == IMAGE_GLYPH
2527 && s->img->pixmap
2528 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2529 {
2530 newBaseCol = IMAGE_BACKGROUND (s->img, s->f, 0);
2531 } */
2532 else
2533 {
2534 newBaseCol = ns_lookup_indexed_color (s->face->background, s->f);
2535 }
2536
2537 if (newBaseCol == nil)
2538 newBaseCol = [NSColor grayColor];
2539
2540 if (newBaseCol != baseCol) /* TODO: better check */
2541 {
2542 [baseCol release];
2543 baseCol = [newBaseCol retain];
2544 [lightCol release];
2545 lightCol = [[baseCol highlightWithLevel: 0.2] retain];
2546 [darkCol release];
2547 darkCol = [[baseCol shadowWithLevel: 0.3] retain];
2548 }
2549
2550 [(raised_p ? lightCol : darkCol) set];
2551
2552 /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2553
2554 /* top */
2555 sr.size.height = thickness;
2556 if (top_p) NSRectFill (sr);
2557
2558 /* left */
2559 sr.size.height = r.size.height;
2560 sr.size.width = thickness;
2561 if (left_p) NSRectFill (sr);
2562
2563 [(raised_p ? darkCol : lightCol) set];
2564
2565 /* bottom */
2566 sr.size.width = r.size.width;
2567 sr.size.height = thickness;
2568 sr.origin.y += r.size.height - thickness;
2569 if (bottom_p) NSRectFill (sr);
2570
2571 /* right */
2572 sr.size.height = r.size.height;
2573 sr.origin.y = r.origin.y;
2574 sr.size.width = thickness;
2575 sr.origin.x += r.size.width - thickness;
2576 if (right_p) NSRectFill (sr);
2577 }
2578
2579
2580 static void
2581 ns_dumpglyphs_box_or_relief (struct glyph_string *s)
2582 /* --------------------------------------------------------------------------
2583 Function modeled after x_draw_glyph_string_box ().
2584 Sets up parameters for drawing.
2585 -------------------------------------------------------------------------- */
2586 {
2587 int right_x, last_x;
2588 char left_p, right_p;
2589 struct glyph *last_glyph;
2590 NSRect r;
2591 int thickness;
2592 struct face *face;
2593
2594 if (s->hl == DRAW_MOUSE_FACE)
2595 {
2596 face = FACE_FROM_ID
2597 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2598 if (!face)
2599 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2600 }
2601 else
2602 face = s->face;
2603
2604 thickness = face->box_line_width;
2605
2606 NSTRACE (ns_dumpglyphs_box_or_relief);
2607
2608 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2609 ? WINDOW_RIGHT_EDGE_X (s->w)
2610 : window_box_right (s->w, s->area));
2611 last_glyph = (s->cmp || s->img
2612 ? s->first_glyph : s->first_glyph + s->nchars-1);
2613
2614 right_x = ((s->row->full_width_p && s->extends_to_end_of_line_p
2615 ? last_x - 1 : min (last_x, s->x + s->background_width) - 1));
2616
2617 left_p = (s->first_glyph->left_box_line_p
2618 || (s->hl == DRAW_MOUSE_FACE
2619 && (s->prev == NULL || s->prev->hl != s->hl)));
2620 right_p = (last_glyph->right_box_line_p
2621 || (s->hl == DRAW_MOUSE_FACE
2622 && (s->next == NULL || s->next->hl != s->hl)));
2623
2624 r = NSMakeRect (s->x, s->y, right_x - s->x + 1, s->height);
2625
2626 /* expand full-width row over internal borders */
2627 if (s->row->full_width_p)
2628 r = ns_fix_rect_ibw (r, FRAME_INTERNAL_BORDER_WIDTH (s->f),
2629 FRAME_PIXEL_WIDTH (s->f));
2630
2631 if (s->face->box == FACE_SIMPLE_BOX)
2632 {
2633 xassert (s->face->box_color != nil);
2634 ns_draw_box (r, abs (thickness),
2635 ns_lookup_indexed_color (face->box_color, s->f),
2636 left_p, right_p);
2637 }
2638 else
2639 {
2640 ns_draw_relief (r, abs (thickness), s->face->box == FACE_RAISED_BOX,
2641 1, 1, left_p, right_p, s);
2642 }
2643 }
2644
2645
2646 static void
2647 ns_maybe_dumpglyphs_background (struct glyph_string *s, char force_p)
2648 /* --------------------------------------------------------------------------
2649 Modeled after x_draw_glyph_string_background, which draws BG in
2650 certain cases. Others are left to the text rendering routine.
2651 -------------------------------------------------------------------------- */
2652 {
2653 NSTRACE (ns_maybe_dumpglyphs_background);
2654
2655 if (!s->background_filled_p/* || s->hl == DRAW_MOUSE_FACE*/)
2656 {
2657 int box_line_width = max (s->face->box_line_width, 0);
2658 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2659 || s->font_not_found_p || s->extends_to_end_of_line_p || force_p)
2660 {
2661 struct face *face;
2662 if (s->hl == DRAW_MOUSE_FACE)
2663 {
2664 face = FACE_FROM_ID
2665 (s->f, FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
2666 if (!face)
2667 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
2668 }
2669 else
2670 face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
2671 if (!face->stipple)
2672 [(NS_FACE_BACKGROUND (face) != 0
2673 ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
2674 : FRAME_BACKGROUND_COLOR (s->f)) set];
2675 else
2676 {
2677 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (s->f);
2678 [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
2679 }
2680
2681 if (s->hl != DRAW_CURSOR)
2682 {
2683 NSRect r = NSMakeRect (s->x, s->y + box_line_width,
2684 s->background_width,
2685 s->height-2*box_line_width);
2686
2687 /* expand full-width row over internal borders */
2688 if (s->row->full_width_p)
2689 {
2690 int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2691 if (r.origin.y <= fibw+1 + box_line_width)
2692 {
2693 r.size.height += r.origin.y;
2694 r.origin.y = 0;
2695 }
2696 if (r.origin.x <= fibw+1)
2697 {
2698 r.size.width += 2*r.origin.x;
2699 r.origin.x = 0;
2700 }
2701 if (FRAME_PIXEL_WIDTH (s->f) - (r.origin.x + r.size.width)
2702 <= fibw+1)
2703 r.size.width += fibw;
2704 }
2705
2706 NSRectFill (r);
2707 }
2708
2709 s->background_filled_p = 1;
2710 }
2711 }
2712 }
2713
2714
2715 static void
2716 ns_dumpglyphs_image (struct glyph_string *s, NSRect r)
2717 /* --------------------------------------------------------------------------
2718 Renders an image and associated borders.
2719 -------------------------------------------------------------------------- */
2720 {
2721 EmacsImage *img = s->img->pixmap;
2722 int box_line_vwidth = max (s->face->box_line_width, 0);
2723 int x = s->x, y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2724 int bg_x, bg_y, bg_height;
2725 int th;
2726 char raised_p;
2727 NSRect br;
2728
2729 NSTRACE (ns_dumpglyphs_image);
2730
2731 if (s->face->box != FACE_NO_BOX
2732 && s->first_glyph->left_box_line_p && s->slice.x == 0)
2733 x += abs (s->face->box_line_width);
2734
2735 bg_x = x;
2736 bg_y = s->slice.y == 0 ? s->y : s->y + box_line_vwidth;
2737 bg_height = s->height;
2738 /* other terms have this, but was causing problems w/tabbar mode */
2739 /* - 2 * box_line_vwidth; */
2740
2741 if (s->slice.x == 0) x += s->img->hmargin;
2742 if (s->slice.y == 0) y += s->img->vmargin;
2743
2744 /* Draw BG: if we need larger area than image itself cleared, do that,
2745 otherwise, since we composite the image under NS (instead of mucking
2746 with its background color), we must clear just the image area. */
2747 [ns_lookup_indexed_color (NS_FACE_BACKGROUND
2748 (FACE_FROM_ID (s->f, s->first_glyph->face_id)), s->f) set];
2749
2750 if (bg_height > s->slice.height || s->img->hmargin || s->img->vmargin
2751 || s->img->mask || s->img->pixmap == 0 || s->width != s->background_width)
2752 {
2753 br = NSMakeRect (bg_x, bg_y, s->background_width, bg_height);
2754 s->background_filled_p = 1;
2755 }
2756 else
2757 {
2758 br = NSMakeRect (x, y, s->slice.width, s->slice.height);
2759 }
2760
2761 /* expand full-width row over internal borders */
2762 if (s->row->full_width_p)
2763 {
2764 int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
2765 if (br.origin.y <= fibw+1 + box_line_vwidth)
2766 {
2767 br.size.height += br.origin.y;
2768 br.origin.y = 0;
2769 }
2770 if (br.origin.x <= fibw+1 + box_line_vwidth)
2771 {
2772 br.size.width += br.origin.x;
2773 br.origin.x = 0;
2774 }
2775 if (FRAME_PIXEL_WIDTH (s->f) - (br.origin.x + br.size.width) <= fibw+1)
2776 br.size.width += fibw;
2777 }
2778
2779 NSRectFill (br);
2780
2781 /* Draw the image.. do we need to draw placeholder if img ==nil? */
2782 if (img != nil)
2783 [img compositeToPoint: NSMakePoint (x, y + s->slice.height)
2784 operation: NSCompositeSourceOver];
2785
2786 /* Draw relief, if requested */
2787 if (s->img->relief || s->hl ==DRAW_IMAGE_RAISED || s->hl ==DRAW_IMAGE_SUNKEN)
2788 {
2789 if (s->hl == DRAW_IMAGE_SUNKEN || s->hl == DRAW_IMAGE_RAISED)
2790 {
2791 th = tool_bar_button_relief >= 0 ?
2792 tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2793 raised_p = (s->hl == DRAW_IMAGE_RAISED);
2794 }
2795 else
2796 {
2797 th = abs (s->img->relief);
2798 raised_p = (s->img->relief > 0);
2799 }
2800
2801 r.origin.x = x - th;
2802 r.origin.y = y - th;
2803 r.size.width = s->slice.width + 2*th-1;
2804 r.size.height = s->slice.height + 2*th-1;
2805 ns_draw_relief (r, th, raised_p,
2806 s->slice.y == 0,
2807 s->slice.y + s->slice.height == s->img->height,
2808 s->slice.x == 0,
2809 s->slice.x + s->slice.width == s->img->width, s);
2810 }
2811 }
2812
2813
2814 static void
2815 ns_draw_glyph_string (struct glyph_string *s)
2816 /* --------------------------------------------------------------------------
2817 External (RIF): Main draw-text call.
2818 -------------------------------------------------------------------------- */
2819 {
2820 /* TODO (optimize): focus for box and contents draw */
2821 NSRect r[2];
2822 int n;
2823 char box_drawn_p = 0;
2824
2825 NSTRACE (ns_draw_glyph_string);
2826
2827 if (s->next && s->right_overhang && !s->for_overlaps/*&&s->hl!=DRAW_CURSOR*/)
2828 {
2829 int width;
2830 struct glyph_string *next;
2831
2832 for (width = 0, next = s->next; next;
2833 width += next->width, next = next->next)
2834 if (next->first_glyph->type != IMAGE_GLYPH)
2835 {
2836 n = ns_get_glyph_string_clip_rect (s->next, r);
2837 ns_focus (s->f, r, n);
2838 ns_maybe_dumpglyphs_background (s->next, 1);
2839 ns_unfocus (s->f);
2840 next->num_clips = 0;
2841 }
2842 }
2843
2844 if (!s->for_overlaps && s->face->box != FACE_NO_BOX
2845 && (s->first_glyph->type == CHAR_GLYPH
2846 || s->first_glyph->type == COMPOSITE_GLYPH))
2847 {
2848 n = ns_get_glyph_string_clip_rect (s, r);
2849 ns_focus (s->f, r, n);
2850 ns_maybe_dumpglyphs_background (s, 1);
2851 ns_dumpglyphs_box_or_relief (s);
2852 ns_unfocus (s->f);
2853 box_drawn_p = 1;
2854 }
2855
2856 switch (s->first_glyph->type)
2857 {
2858
2859 case IMAGE_GLYPH:
2860 n = ns_get_glyph_string_clip_rect (s, r);
2861 ns_focus (s->f, r, n);
2862 ns_dumpglyphs_image (s, r[0]);
2863 ns_unfocus (s->f);
2864 break;
2865
2866 case STRETCH_GLYPH:
2867 if (!s->background_filled_p)
2868 {
2869 *r = NSMakeRect (s->x, s->y, s->background_width, s->height);
2870
2871 if (!s->row->full_width_p)
2872 {
2873 /* truncate to avoid overwriting fringe and/or scrollbar */
2874 int overrun = max (0, (s->x + s->background_width)
2875 - (WINDOW_BOX_RIGHT_EDGE_X (s->w)
2876 - WINDOW_RIGHT_FRINGE_WIDTH (s->w)));
2877 r[0].size.width -= overrun;
2878
2879 /* XXX: Try to work between problem where a stretch glyph on
2880 a partially-visible bottom row will clear part of the
2881 modeline, and another where list-buffers headers and similar
2882 rows erroneously have visible_height set to 0. Not sure
2883 where this is coming from as other terms seem not to show. */
2884 r[0].size.height = min (s->height, s->row->visible_height);
2885 }
2886
2887 /* expand full-width rows over internal borders */
2888 else
2889 {
2890 r[0] = ns_fix_rect_ibw (r[0], FRAME_INTERNAL_BORDER_WIDTH (s->f),
2891 FRAME_PIXEL_WIDTH (s->f));
2892 }
2893
2894 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
2895 overwriting cursor (usually when cursor on a tab) */
2896 if (s->hl == DRAW_CURSOR)
2897 {
2898 r[0].origin.x += s->width;
2899 r[0].size.width -= s->width;
2900 }
2901
2902 ns_focus (s->f, r, 1);
2903 [ns_lookup_indexed_color (NS_FACE_BACKGROUND
2904 (FACE_FROM_ID (s->f, s->first_glyph->face_id)), s->f) set];
2905 NSRectFill (r[0]);
2906 ns_unfocus (s->f);
2907 s->background_filled_p = 1;
2908 }
2909 break;
2910
2911 case CHAR_GLYPH:
2912 case COMPOSITE_GLYPH:
2913 n = ns_get_glyph_string_clip_rect (s, r);
2914 ns_focus (s->f, r, n);
2915
2916 if (s->for_overlaps || (s->cmp_from > 0
2917 && ! s->first_glyph->u.cmp.automatic))
2918 s->background_filled_p = 1;
2919 else /* 1 */
2920 ns_maybe_dumpglyphs_background
2921 (s, s->first_glyph->type == COMPOSITE_GLYPH);
2922
2923 ns_tmp_flags = s->hl == DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR :
2924 (s->hl == DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE :
2925 (s->for_overlaps ? NS_DUMPGLYPH_FOREGROUND :
2926 NS_DUMPGLYPH_NORMAL));
2927 ns_tmp_font = (struct nsfont_info *)s->face->font;
2928 if (ns_tmp_font == NULL)
2929 ns_tmp_font = (struct nsfont_info *)FRAME_FONT (s->f);
2930
2931 ns_tmp_font->font.driver->draw
2932 (s, 0, s->nchars, s->x, s->y,
2933 (ns_tmp_flags == NS_DUMPGLYPH_NORMAL && !s->background_filled_p)
2934 || ns_tmp_flags == NS_DUMPGLYPH_MOUSEFACE);
2935
2936 ns_unfocus (s->f);
2937 break;
2938
2939 default:
2940 abort ();
2941 }
2942
2943 /* Draw box if not done already. */
2944 if (!s->for_overlaps && !box_drawn_p && s->face->box != FACE_NO_BOX)
2945 {
2946 n = ns_get_glyph_string_clip_rect (s, r);
2947 ns_focus (s->f, r, n);
2948 ns_dumpglyphs_box_or_relief (s);
2949 ns_unfocus (s->f);
2950 }
2951
2952 s->num_clips = 0;
2953 }
2954
2955
2956
2957 /* ==========================================================================
2958
2959 Event loop
2960
2961 ========================================================================== */
2962
2963
2964 static void
2965 ns_send_appdefined (int value)
2966 /* --------------------------------------------------------------------------
2967 Internal: post an appdefined event which EmacsApp-sendEvent will
2968 recognize and take as a command to halt the event loop.
2969 -------------------------------------------------------------------------- */
2970 {
2971 /*NSTRACE (ns_send_appdefined); */
2972
2973 /* Only post this event if we haven't already posted one. This will end
2974 the [NXApp run] main loop after having processed all events queued at
2975 this moment. */
2976 if (send_appdefined)
2977 {
2978 NSEvent *nxev;
2979
2980 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
2981 send_appdefined = NO;
2982
2983 /* Don't need wakeup timer any more */
2984 if (timed_entry)
2985 {
2986 [timed_entry invalidate];
2987 [timed_entry release];
2988 timed_entry = nil;
2989 }
2990
2991 /* Ditto for file descriptor poller */
2992 if (fd_entry)
2993 {
2994 [fd_entry invalidate];
2995 [fd_entry release];
2996 fd_entry = nil;
2997 }
2998
2999 nxev = [NSEvent otherEventWithType: NSApplicationDefined
3000 location: NSMakePoint (0, 0)
3001 modifierFlags: 0
3002 timestamp: 0
3003 windowNumber: [[NSApp mainWindow] windowNumber]
3004 context: [NSApp context]
3005 subtype: 0
3006 data1: value
3007 data2: 0];
3008
3009 /* Post an application defined event on the event queue. When this is
3010 received the [NXApp run] will return, thus having processed all
3011 events which are currently queued. */
3012 [NSApp postEvent: nxev atStart: NO];
3013 }
3014 }
3015
3016
3017 static int
3018 ns_read_socket (struct terminal *terminal, int expected,
3019 struct input_event *hold_quit)
3020 /* --------------------------------------------------------------------------
3021 External (hook): Post an event to ourself and keep reading events until
3022 we read it back again. In effect process all events which were waiting.
3023 23: Now we have to manage the event buffer ourselves.
3024 -------------------------------------------------------------------------- */
3025 {
3026 struct input_event ev;
3027 int nevents;
3028 static NSDate *lastCheck = nil;
3029 /* NSTRACE (ns_read_socket); */
3030
3031 if (interrupt_input_blocked)
3032 {
3033 interrupt_input_pending = 1;
3034 return -1;
3035 }
3036
3037 interrupt_input_pending = 0;
3038 BLOCK_INPUT;
3039
3040 #ifdef COCOA_EXPERIMENTAL_CTRL_G
3041 /* causes Feval to abort; unclear on why this isn't in calling code */
3042 ++handling_signal;
3043 #endif
3044
3045 n_emacs_events_pending = 0;
3046 EVENT_INIT (ev);
3047 emacs_event = &ev;
3048 q_event_ptr = hold_quit;
3049
3050 /* we manage autorelease pools by allocate/reallocate each time around
3051 the loop; strict nesting is occasionally violated but seems not to
3052 matter.. earlier methods using full nesting caused major memory leaks */
3053 [outerpool release];
3054 outerpool = [[NSAutoreleasePool alloc] init];
3055
3056 /* If have pending open-file requests, attend to the next one of those. */
3057 if (ns_pending_files && [ns_pending_files count] != 0
3058 && [(EmacsApp *)NSApp openFile: [ns_pending_files objectAtIndex: 0]])
3059 {
3060 [ns_pending_files removeObjectAtIndex: 0];
3061 }
3062 /* Deal with pending service requests. */
3063 else if (ns_pending_service_names && [ns_pending_service_names count] != 0
3064 && [(EmacsApp *)
3065 NSApp fulfillService: [ns_pending_service_names objectAtIndex: 0]
3066 withArg: [ns_pending_service_args objectAtIndex: 0]])
3067 {
3068 [ns_pending_service_names removeObjectAtIndex: 0];
3069 [ns_pending_service_args removeObjectAtIndex: 0];
3070 }
3071 else
3072 {
3073 /* Run and wait for events. We must always send one NX_APPDEFINED event
3074 to ourself, otherwise [NXApp run] will never exit. */
3075 send_appdefined = YES;
3076
3077 /* TODO: from termhooks.h: */
3078 /* XXX Please note that a non-zero value of EXPECTED only means that
3079 there is available input on at least one of the currently opened
3080 terminal devices -- but not necessarily on this device.
3081 Therefore, in most cases EXPECTED should be simply ignored. */
3082 /* However, if in ns_select, this is called from gobble_input, which
3083 appears to set it correctly for our purposes, and always assuming
3084 !expected causes 100% CPU usage. */
3085 if (!inNsSelect || !expected)
3086 {
3087 /* Post an application defined event on the event queue. When this is
3088 received the [NXApp run] will return, thus having processed all
3089 events which are currently queued, if any. */
3090 ns_send_appdefined (-1);
3091 }
3092
3093 [NSApp run];
3094 }
3095
3096 nevents = n_emacs_events_pending;
3097 n_emacs_events_pending = 0;
3098 emacs_event = q_event_ptr = NULL;
3099
3100 #ifdef COCOA_EXPERIMENTAL_CTRL_G
3101 --handling_signal;
3102 #endif
3103 UNBLOCK_INPUT;
3104 return nevents;
3105 }
3106
3107
3108 int
3109 ns_select (int nfds, fd_set *readfds, fd_set *writefds,
3110 fd_set *exceptfds, struct timeval *timeout)
3111 /* --------------------------------------------------------------------------
3112 Replacement for select, checking for events
3113 -------------------------------------------------------------------------- */
3114 {
3115 int result;
3116 double time;
3117 NSEvent *ev;
3118 /* NSTRACE (ns_select); */
3119
3120 if (NSApp == nil /* || ([NSApp isActive] == NO &&
3121 [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil
3122 inMode:NSDefaultRunLoopMode dequeue:NO] == nil) */)
3123 return select (nfds, readfds, writefds, exceptfds, timeout);
3124
3125 /* Save file descriptor set, which gets overwritten in calls to select ()
3126 Note, this is called from process.c, and only readfds is ever set */
3127 if (readfds)
3128 {
3129 memcpy (&select_readfds, readfds, sizeof (fd_set));
3130 select_nfds = nfds;
3131 }
3132 else
3133 select_nfds = 0;
3134
3135 /* Try an initial select for pending data on input files */
3136 select_timeout.tv_sec = select_timeout.tv_usec = 0;
3137 result = select (nfds, readfds, writefds, exceptfds, &select_timeout);
3138 if (result)
3139 return result;
3140
3141 /* if (!timeout || timed_entry || fd_entry)
3142 fprintf (stderr, "assertion failed: timeout null or timed_entry/fd_entry non-null in ns_select\n"); */
3143
3144 /* set a timeout and run the main AppKit event loop while continuing
3145 to monitor the files */
3146 time = ((double) timeout->tv_sec) + ((double) timeout->tv_usec)/1000000.0;
3147 timed_entry = [[NSTimer scheduledTimerWithTimeInterval: time
3148 target: NSApp
3149 selector: @selector (timeout_handler:)
3150 userInfo: 0
3151 repeats: YES] /* for safe removal */
3152 retain];
3153
3154 /* set a periodic task to try the select () again */
3155 fd_entry = [[NSTimer scheduledTimerWithTimeInterval: 0.1
3156 target: NSApp
3157 selector: @selector (fd_handler:)
3158 userInfo: 0
3159 repeats: YES]
3160 retain];
3161
3162 /* Let Application dispatch events until it receives an event of the type
3163 NX_APPDEFINED, which should only be sent by timeout_handler. */
3164 inNsSelect = 1;
3165 gobble_input (timeout ? 1 : 0);
3166 ev = last_appdefined_event;
3167 inNsSelect = 0;
3168
3169 if (ev)
3170 {
3171 int t;
3172 if ([ev type] != NSApplicationDefined)
3173 abort ();
3174
3175 t = [ev data1];
3176 last_appdefined_event = 0;
3177
3178 if (t == -2)
3179 {
3180 /* The NX_APPDEFINED event we received was a timeout. */
3181 return 0;
3182 }
3183 else if (t == -1)
3184 {
3185 /* The NX_APPDEFINED event we received was the result of
3186 at least one real input event arriving. */
3187 errno = EINTR;
3188 return -1;
3189 }
3190 else
3191 {
3192 /* Received back from select () in fd_handler; copy the results */
3193 if (readfds)
3194 memcpy (readfds, &select_readfds, sizeof (fd_set));
3195 return t;
3196 }
3197 }
3198 /* never reached, shut compiler up */
3199 return 0;
3200 }
3201
3202
3203
3204 /* ==========================================================================
3205
3206 Scrollbar handling
3207
3208 ========================================================================== */
3209
3210
3211 static void
3212 ns_set_vertical_scroll_bar (struct window *window,
3213 int portion, int whole, int position)
3214 /* --------------------------------------------------------------------------
3215 External (hook): Update or add scrollbar
3216 -------------------------------------------------------------------------- */
3217 {
3218 Lisp_Object win;
3219 NSRect r, v;
3220 struct frame *f = XFRAME (WINDOW_FRAME (window));
3221 EmacsView *view = FRAME_NS_VIEW (f);
3222 int window_y, window_height;
3223 BOOL barOnVeryLeft, barOnVeryRight;
3224 int top, left, height, width, sb_width, sb_left;
3225 EmacsScroller *bar;
3226 static int count = 0;
3227
3228 /* optimization; display engine sends WAY too many of these.. */
3229 if (!NILP (window->vertical_scroll_bar))
3230 {
3231 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3232 if ([bar checkSamePosition: position portion: portion whole: whole])
3233 {
3234 if (view->scrollbarsNeedingUpdate == 0)
3235 {
3236 if (!windows_or_buffers_changed)
3237 return;
3238 }
3239 else
3240 view->scrollbarsNeedingUpdate--;
3241 }
3242 }
3243
3244 NSTRACE (ns_set_vertical_scroll_bar);
3245
3246 /* Get dimensions. */
3247 window_box (window, -1, 0, &window_y, 0, &window_height);
3248 top = window_y;
3249 height = window_height;
3250 width = WINDOW_CONFIG_SCROLL_BAR_COLS (window) * FRAME_COLUMN_WIDTH (f);
3251 left = WINDOW_SCROLL_BAR_AREA_X (window);
3252
3253 if (top < 5) /* top scrollbar adjustment */
3254 {
3255 top -= FRAME_INTERNAL_BORDER_WIDTH (f);
3256 height += FRAME_INTERNAL_BORDER_WIDTH (f);
3257 }
3258
3259 /* allow for displaying a skinnier scrollbar than char area allotted */
3260 sb_width = (WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) > 0) ?
3261 WINDOW_CONFIG_SCROLL_BAR_WIDTH (window) : width;
3262
3263 barOnVeryLeft = left < 5;
3264 barOnVeryRight = FRAME_PIXEL_WIDTH (f) - left - width < 5;
3265 sb_left = left + FRAME_INTERNAL_BORDER_WIDTH (f)
3266 * (barOnVeryLeft ? -1 : (barOnVeryRight ? 1 : 0));
3267
3268 r = NSMakeRect (sb_left, top, sb_width, height);
3269 /* the parent view is flipped, so we need to flip y value */
3270 v = [view frame];
3271 r.origin.y = (v.size.height - r.size.height - r.origin.y);
3272
3273 XSETWINDOW (win, window);
3274 BLOCK_INPUT;
3275
3276 /* we want at least 5 lines to display a scrollbar */
3277 if (WINDOW_TOTAL_LINES (window) < 5)
3278 {
3279 if (!NILP (window->vertical_scroll_bar))
3280 {
3281 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3282 [bar removeFromSuperview];
3283 window->vertical_scroll_bar = Qnil;
3284 }
3285 ns_clear_frame_area (f, sb_left, top, width, height);
3286 UNBLOCK_INPUT;
3287 return;
3288 }
3289
3290 if (NILP (window->vertical_scroll_bar))
3291 {
3292 ns_clear_frame_area (f, sb_left, top, width, height);
3293 bar = [[EmacsScroller alloc] initFrame: r window: win];
3294 window->vertical_scroll_bar = make_save_value (bar, 0);
3295 }
3296 else
3297 {
3298 NSRect oldRect;
3299 bar = XNS_SCROLL_BAR (window->vertical_scroll_bar);
3300 oldRect = [bar frame];
3301 r.size.width = oldRect.size.width;
3302 if (FRAME_LIVE_P (f) && !NSEqualRects (oldRect, r))
3303 {
3304 if (oldRect.origin.x != r.origin.x)
3305 ns_clear_frame_area (f, sb_left, top, width, height);
3306 [bar setFrame: r];
3307 }
3308 }
3309
3310 [bar setPosition: position portion: portion whole: whole];
3311 UNBLOCK_INPUT;
3312 }
3313
3314
3315 static void
3316 ns_condemn_scroll_bars (struct frame *f)
3317 /* --------------------------------------------------------------------------
3318 External (hook): arrange for all frame's scrollbars to be removed
3319 at next call to judge_scroll_bars, except for those redeemed.
3320 -------------------------------------------------------------------------- */
3321 {
3322 int i;
3323 id view;
3324 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3325
3326 NSTRACE (ns_condemn_scroll_bars);
3327
3328 for (i =[subviews count]-1; i >= 0; i--)
3329 {
3330 view = [subviews objectAtIndex: i];
3331 if ([view isKindOfClass: [EmacsScroller class]])
3332 [view condemn];
3333 }
3334 }
3335
3336
3337 static void
3338 ns_redeem_scroll_bar (struct window *window)
3339 /* --------------------------------------------------------------------------
3340 External (hook): arrange to spare this window's scrollbar
3341 at next call to judge_scroll_bars.
3342 -------------------------------------------------------------------------- */
3343 {
3344 id bar;
3345 NSTRACE (ns_redeem_scroll_bar);
3346 if (!NILP (window->vertical_scroll_bar))
3347 {
3348 bar =XNS_SCROLL_BAR (window->vertical_scroll_bar);
3349 [bar reprieve];
3350 }
3351 }
3352
3353
3354 static void
3355 ns_judge_scroll_bars (struct frame *f)
3356 /* --------------------------------------------------------------------------
3357 External (hook): destroy all scrollbars on frame that weren't
3358 redeemed after call to condemn_scroll_bars.
3359 -------------------------------------------------------------------------- */
3360 {
3361 int i;
3362 id view;
3363 NSArray *subviews = [[FRAME_NS_VIEW (f) superview] subviews];
3364 NSTRACE (ns_judge_scroll_bars);
3365 for (i =[subviews count]-1; i >= 0; i--)
3366 {
3367 view = [subviews objectAtIndex: i];
3368 if (![view isKindOfClass: [EmacsScroller class]]) continue;
3369 [view judge];
3370 }
3371 }
3372
3373
3374
3375 /* ==========================================================================
3376
3377 Miscellaneous, mainly stubbed-out functions added in 23
3378
3379 ========================================================================== */
3380
3381
3382 void
3383 x_wm_set_icon_position (struct frame *f, int icon_x, int icon_y)
3384 {
3385 }
3386
3387
3388
3389 /* ==========================================================================
3390
3391 Initialization
3392
3393 ========================================================================== */
3394
3395 int
3396 x_display_pixel_height (dpyinfo)
3397 struct ns_display_info *dpyinfo;
3398 {
3399 NSScreen *screen = [NSScreen mainScreen];
3400 return [screen frame].size.height;
3401 }
3402
3403 int
3404 x_display_pixel_width (dpyinfo)
3405 struct ns_display_info *dpyinfo;
3406 {
3407 NSScreen *screen = [NSScreen mainScreen];
3408 return [screen frame].size.width;
3409 }
3410
3411
3412 static Lisp_Object ns_string_to_lispmod (const char *s)
3413 /* --------------------------------------------------------------------------
3414 Convert modifier name to lisp symbol
3415 -------------------------------------------------------------------------- */
3416 {
3417 if (!strncmp (SDATA (SYMBOL_NAME (Qmeta)), s, 10))
3418 return Qmeta;
3419 else if (!strncmp (SDATA (SYMBOL_NAME (Qsuper)), s, 10))
3420 return Qsuper;
3421 else if (!strncmp (SDATA (SYMBOL_NAME (Qcontrol)), s, 10))
3422 return Qcontrol;
3423 else if (!strncmp (SDATA (SYMBOL_NAME (Qalt)), s, 10))
3424 return Qalt;
3425 else if (!strncmp (SDATA (SYMBOL_NAME (Qhyper)), s, 10))
3426 return Qhyper;
3427 else if (!strncmp (SDATA (SYMBOL_NAME (Qnone)), s, 10))
3428 return Qnone;
3429 else
3430 return Qnil;
3431 }
3432
3433
3434 static Lisp_Object ns_mod_to_lisp (int m)
3435 /* --------------------------------------------------------------------------
3436 Convert modifier code (see lisp.h) to lisp symbol
3437 -------------------------------------------------------------------------- */
3438 {
3439 if (m == CHAR_META)
3440 return Qmeta;
3441 else if (m == CHAR_SUPER)
3442 return Qsuper;
3443 else if (m == CHAR_CTL)
3444 return Qcontrol;
3445 else if (m == CHAR_ALT)
3446 return Qalt;
3447 else if (m == CHAR_HYPER)
3448 return Qhyper;
3449 else /* if (m == 0) */
3450 return Qnone;
3451 }
3452
3453
3454 static void
3455 ns_set_default_prefs ()
3456 /* --------------------------------------------------------------------------
3457 Initialize preference variables to defaults
3458 -------------------------------------------------------------------------- */
3459 {
3460 ns_alternate_modifier = Qmeta;
3461 ns_command_modifier = Qsuper;
3462 ns_control_modifier = Qcontrol;
3463 ns_function_modifier = Qnone;
3464 ns_expand_space = make_float (0.0);
3465 ns_antialias_text = Qt;
3466 ns_antialias_threshold = 10.0; /* not exposed to lisp side */
3467 ns_use_qd_smoothing = Qnil;
3468 ns_use_system_highlight_color = Qt;
3469 }
3470
3471
3472 static void
3473 ns_default (const char *parameter, Lisp_Object *result,
3474 Lisp_Object yesval, Lisp_Object noval,
3475 BOOL is_float, BOOL is_modstring)
3476 /* --------------------------------------------------------------------------
3477 Check a parameter value in user's preferences
3478 -------------------------------------------------------------------------- */
3479 {
3480 const char *value;
3481
3482 if ( (value =[[[NSUserDefaults standardUserDefaults]
3483 stringForKey: [NSString stringWithUTF8String: parameter]]
3484 UTF8String]) )
3485 {
3486 double f;
3487 char *pos;
3488 if (strcasecmp (value, "YES") == 0)
3489 *result = yesval;
3490 else if (strcasecmp (value, "NO") == 0)
3491 *result = noval;
3492 else if (is_float && (f = strtod (value, &pos), pos != value))
3493 *result = make_float (f);
3494 else if (is_modstring && value)
3495 *result = ns_string_to_lispmod (value);
3496 else fprintf (stderr,
3497 "Bad value for default \"%s\": \"%s\"\n", parameter, value);
3498 }
3499 }
3500
3501
3502 void
3503 ns_initialize_display_info (struct ns_display_info *dpyinfo)
3504 /* --------------------------------------------------------------------------
3505 Initialize global info and storage for display.
3506 -------------------------------------------------------------------------- */
3507 {
3508 NSScreen *screen = [NSScreen mainScreen];
3509 NSWindowDepth depth = [screen depth];
3510
3511 dpyinfo->resx = 72.27; /* used 75.0, but this makes pt == pixel, expected */
3512 dpyinfo->resy = 72.27;
3513 dpyinfo->color_p = ![NSDeviceWhiteColorSpace isEqualToString:
3514 NSColorSpaceFromDepth (depth)]
3515 && ![NSCalibratedWhiteColorSpace isEqualToString:
3516 NSColorSpaceFromDepth (depth)];
3517 dpyinfo->n_planes = NSBitsPerPixelFromDepth (depth);
3518 dpyinfo->image_cache = make_image_cache ();
3519 dpyinfo->color_table
3520 = (struct ns_color_table *)xmalloc (sizeof (struct ns_color_table));
3521 dpyinfo->color_table->colors = NULL;
3522 dpyinfo->root_window = 42; /* a placeholder.. */
3523
3524 dpyinfo->mouse_face_mouse_frame = NULL;
3525 dpyinfo->mouse_face_deferred_gc = 0;
3526 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
3527 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
3528 dpyinfo->mouse_face_face_id = DEFAULT_FACE_ID;
3529 dpyinfo->mouse_face_window = dpyinfo->mouse_face_overlay = Qnil;
3530 dpyinfo->mouse_face_hidden = 0;
3531
3532 dpyinfo->mouse_face_mouse_x = dpyinfo->mouse_face_mouse_y = 0;
3533 dpyinfo->mouse_face_defer = 0;
3534
3535 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame = NULL;
3536
3537 dpyinfo->n_fonts = 0;
3538 dpyinfo->smallest_font_height = 1;
3539 dpyinfo->smallest_char_width = 1;
3540 }
3541
3542
3543 /* 23: Needed as new part of display engine; this and next define public
3544 functions in this file (well, many of them, anyway). */
3545 /* x_... are generic versions in xdisp.c that we, and other terms, get away
3546 with using despite presence in the "system dependent" redisplay
3547 interface. In addition, many of the ns_ methods have code that is
3548 shared with all terms, indicating need for further refactoring. */
3549 extern frame_parm_handler ns_frame_parm_handlers[];
3550 static struct redisplay_interface ns_redisplay_interface =
3551 {
3552 ns_frame_parm_handlers,
3553 x_produce_glyphs, /*generic OK */
3554 x_write_glyphs, /*generic OK */
3555 x_insert_glyphs, /*generic OK */
3556 x_clear_end_of_line, /*generic OK */
3557 ns_scroll_run, /*23 */
3558 ns_after_update_window_line, /*23: added */
3559 ns_update_window_begin, /*23: split from update_begin */
3560 ns_update_window_end, /*23: split from update_end */
3561 x_cursor_to, /*generic OK */
3562 ns_flush,
3563 0, /* flush_display_optional */
3564 x_clear_window_mouse_face, /*generic OK */
3565 x_get_glyph_overhangs, /*23: generic OK */
3566 x_fix_overlapping_area, /*generic OK */
3567 ns_draw_fringe_bitmap, /*23 */
3568 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
3569 0, /* destroy_fringe_bitmap */
3570 ns_compute_glyph_string_overhangs, /*23 */
3571 ns_draw_glyph_string, /*23: interface to nsfont.m */
3572 ns_define_frame_cursor, /*23 */
3573 ns_clear_frame_area, /*23 */
3574 ns_draw_window_cursor, /*23: revamped ns_dumpcursor */
3575 ns_draw_vertical_window_border,
3576 ns_shift_glyphs_for_insert
3577 };
3578
3579
3580 static void
3581 ns_delete_display (struct ns_display_info *dpyinfo)
3582 {
3583 /* TODO... */
3584 }
3585
3586
3587 /* This function is called when the last frame on a display is deleted. */
3588 static void
3589 ns_delete_terminal (struct terminal *terminal)
3590 {
3591 struct ns_display_info *dpyinfo = terminal->display_info.ns;
3592 int i;
3593
3594 /* Protect against recursive calls. Fdelete_frame in
3595 delete_terminal calls us back when it deletes our last frame. */
3596 if (!terminal->name)
3597 return;
3598
3599 BLOCK_INPUT;
3600
3601 x_destroy_all_bitmaps (dpyinfo);
3602 ns_delete_display (dpyinfo);
3603 UNBLOCK_INPUT;
3604 }
3605
3606
3607 static struct terminal *
3608 ns_create_terminal (struct ns_display_info *dpyinfo)
3609 /* --------------------------------------------------------------------------
3610 Set up use of NS before we make the first connection.
3611 -------------------------------------------------------------------------- */
3612 {
3613 struct terminal *terminal;
3614
3615 NSTRACE (ns_create_terminal);
3616
3617 terminal = create_terminal ();
3618
3619 terminal->type = output_ns;
3620 terminal->display_info.ns = dpyinfo;
3621 dpyinfo->terminal = terminal;
3622
3623 terminal->rif = &ns_redisplay_interface;
3624
3625 terminal->clear_frame_hook = ns_clear_frame;
3626 terminal->ins_del_lines_hook = 0; /* 23: vestigial? */
3627 terminal->delete_glyphs_hook = 0; /* 23: vestigial? */
3628 terminal->ring_bell_hook = ns_ring_bell;
3629 terminal->reset_terminal_modes_hook = ns_reset_terminal_modes;
3630 terminal->set_terminal_modes_hook = ns_set_terminal_modes;
3631 terminal->update_begin_hook = ns_update_begin;
3632 terminal->update_end_hook = ns_update_end;
3633 terminal->set_terminal_window_hook = NULL; /* 23: vestigial? */
3634 terminal->read_socket_hook = ns_read_socket;
3635 terminal->frame_up_to_date_hook = ns_frame_up_to_date;
3636 terminal->mouse_position_hook = ns_mouse_position;
3637 terminal->frame_rehighlight_hook = ns_frame_rehighlight;
3638 terminal->frame_raise_lower_hook = ns_frame_raise_lower;
3639
3640 terminal->fullscreen_hook = 0; /*XTfullscreen_hook;//23.50 */
3641
3642 terminal->set_vertical_scroll_bar_hook = ns_set_vertical_scroll_bar;
3643 terminal->condemn_scroll_bars_hook = ns_condemn_scroll_bars;
3644 terminal->redeem_scroll_bar_hook = ns_redeem_scroll_bar;
3645 terminal->judge_scroll_bars_hook = ns_judge_scroll_bars;
3646
3647 terminal->delete_frame_hook = x_destroy_window;
3648 terminal->delete_terminal_hook = ns_delete_terminal;
3649
3650 terminal->scroll_region_ok = 1;
3651 terminal->char_ins_del_ok = 1;
3652 terminal->line_ins_del_ok = 1;
3653 terminal->fast_clear_end_of_line = 1;
3654 terminal->memory_below_frame = 0;
3655
3656 return terminal;
3657 }
3658
3659
3660 void
3661 ns_initialize ()
3662 /* --------------------------------------------------------------------------
3663 Mainly vestigial under NS now that ns_create_terminal () does most things.
3664 -------------------------------------------------------------------------- */
3665 {
3666 baud_rate = 38400;
3667 Fset_input_interrupt_mode (Qt);
3668 }
3669
3670
3671 struct ns_display_info *
3672 ns_term_init (Lisp_Object display_name)
3673 /* --------------------------------------------------------------------------
3674 Start the Application and get things rolling.
3675 -------------------------------------------------------------------------- */
3676 {
3677 extern Lisp_Object Fset_input_mode (Lisp_Object, Lisp_Object,
3678 Lisp_Object, Lisp_Object);
3679 struct terminal *terminal;
3680 struct ns_display_info *dpyinfo;
3681 static int ns_initialized = 0;
3682 Lisp_Object tmp;
3683
3684 NSTRACE (ns_term_init);
3685
3686 /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
3687 /*GSDebugAllocationActive (YES); */
3688 BLOCK_INPUT;
3689 handling_signal = 0;
3690
3691 if (!ns_initialized)
3692 {
3693 ns_initialize ();
3694 ns_initialized = 1;
3695 }
3696
3697 ns_pending_files = [[NSMutableArray alloc] init];
3698 ns_pending_service_names = [[NSMutableArray alloc] init];
3699 ns_pending_service_args = [[NSMutableArray alloc] init];
3700
3701 /* Start app and create the main menu, window, view.
3702 Needs to be here because ns_initialize_display_info () uses AppKit classes.
3703 The view will then ask the NSApp to stop and return to Emacs. */
3704 [EmacsApp sharedApplication];
3705 if (NSApp == nil)
3706 return NULL;
3707 [NSApp setDelegate: NSApp];
3708
3709 /* debugging: log all notifications */
3710 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
3711 selector: @selector (logNotification:)
3712 name: nil object: nil]; */
3713
3714 dpyinfo = (struct ns_display_info *)xmalloc (sizeof (struct ns_display_info));
3715 bzero (dpyinfo, sizeof (struct ns_display_info));
3716
3717 ns_initialize_display_info (dpyinfo);
3718 terminal = ns_create_terminal (dpyinfo);
3719
3720 terminal->kboard = (KBOARD *) xmalloc (sizeof (KBOARD));
3721 init_kboard (terminal->kboard);
3722 terminal->kboard->Vwindow_system = Qns;
3723 terminal->kboard->next_kboard = all_kboards;
3724 all_kboards = terminal->kboard;
3725 /* Don't let the initial kboard remain current longer than necessary.
3726 That would cause problems if a file loaded on startup tries to
3727 prompt in the mini-buffer. */
3728 if (current_kboard == initial_kboard)
3729 current_kboard = terminal->kboard;
3730 terminal->kboard->reference_count++;
3731
3732 dpyinfo->next = x_display_list;
3733 x_display_list = dpyinfo;
3734
3735 /* Put it on ns_display_name_list */
3736 ns_display_name_list = Fcons (Fcons (display_name, Qnil),
3737 ns_display_name_list);
3738 /* ns_display_name_list = Fcons (Fcons (display_name,
3739 Fcons (Qnil, dpyinfo->xrdb)),
3740 ns_display_name_list); */
3741 dpyinfo->name_list_element = XCAR (ns_display_name_list);
3742
3743 /* Set the name of the terminal. */
3744 terminal->name = (char *) xmalloc (SBYTES (display_name) + 1);
3745 strncpy (terminal->name, SDATA (display_name), SBYTES (display_name));
3746 terminal->name[SBYTES (display_name)] = 0;
3747
3748 UNBLOCK_INPUT;
3749
3750 /* Read various user defaults. */
3751 ns_set_default_prefs ();
3752 ns_default ("AlternateModifier", &ns_alternate_modifier,
3753 Qnil, Qnil, NO, YES);
3754 if (NILP (ns_alternate_modifier))
3755 ns_alternate_modifier = Qmeta;
3756 ns_default ("CommandModifier", &ns_command_modifier,
3757 Qnil, Qnil, NO, YES);
3758 if (NILP (ns_command_modifier))
3759 ns_command_modifier = Qsuper;
3760 ns_default ("ControlModifier", &ns_control_modifier,
3761 Qnil, Qnil, NO, YES);
3762 if (NILP (ns_control_modifier))
3763 ns_control_modifier = Qcontrol;
3764 ns_default ("FunctionModifier", &ns_function_modifier,
3765 Qnil, Qnil, NO, YES);
3766 if (NILP (ns_function_modifier))
3767 ns_function_modifier = Qnone;
3768 ns_default ("ExpandSpace", &ns_expand_space,
3769 make_float (0.5), make_float (0.0), YES, NO);
3770 ns_default ("GSFontAntiAlias", &ns_antialias_text,
3771 Qt, Qnil, NO, NO);
3772 tmp = Qnil;
3773 ns_default ("AppleAntiAliasingThreshold", &tmp,
3774 make_float (10.0), make_float (6.0), YES, NO);
3775 ns_antialias_threshold = NILP (tmp) ? 10.0 : XFLOATINT (tmp);
3776 ns_default ("UseQuickdrawSmoothing", &ns_use_qd_smoothing,
3777 Qt, Qnil, NO, NO);
3778 ns_default ("UseSystemHighlightColor", &ns_use_system_highlight_color,
3779 Qt, Qnil, NO, NO);
3780 if (EQ (ns_use_system_highlight_color, Qt))
3781 {
3782 ns_selection_color = [[NSUserDefaults standardUserDefaults]
3783 stringForKey: @"AppleHighlightColor"];
3784 if (ns_selection_color == nil)
3785 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
3786 }
3787 else
3788 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
3789
3790 {
3791 NSColorList *cl = [NSColorList colorListNamed: @"Emacs"];
3792
3793 if ( cl == nil )
3794 {
3795 Lisp_Object color_file, color_map, color;
3796 int r,g,b;
3797 unsigned long c;
3798 char *name;
3799
3800 color_file = Fexpand_file_name (build_string ("rgb.txt"),
3801 Fsymbol_value (intern ("data-directory")));
3802 if (NILP (Ffile_readable_p (color_file)))
3803 fatal ("Could not find %s.\n", SDATA (color_file));
3804
3805 color_map = Fx_load_color_file (color_file);
3806 if (NILP (color_map))
3807 fatal ("Could not read %s.\n", SDATA (color_file));
3808
3809 cl = [[NSColorList alloc] initWithName: @"Emacs"];
3810 for ( ; CONSP (color_map); color_map = XCDR (color_map))
3811 {
3812 color = XCAR (color_map);
3813 name = SDATA (XCAR (color));
3814 c = XINT (XCDR (color));
3815 [cl setColor:
3816 [NSColor colorWithCalibratedRed: RED_FROM_ULONG (c) / 255.0
3817 green: GREEN_FROM_ULONG (c) / 255.0
3818 blue: BLUE_FROM_ULONG (c) / 255.0
3819 alpha: 1.0]
3820 forKey: [NSString stringWithUTF8String: name]];
3821 }
3822 [cl writeToFile: nil];
3823 }
3824 }
3825
3826 {
3827 char c[128];
3828 #ifdef NS_IMPL_GNUSTEP
3829 strncpy (c, gnustep_base_version, sizeof (c));
3830 #else
3831 /*PSnextrelease (128, c); */
3832 snprintf (c, sizeof (c), "%g", NSAppKitVersionNumber);
3833 #endif
3834 Vwindow_system_version = build_string (c);
3835 }
3836
3837 delete_keyboard_wait_descriptor (0);
3838
3839 /* Set up OS X app menu */
3840 #ifdef NS_IMPL_COCOA
3841 {
3842 NSMenu *appMenu;
3843 NSMenuItem *item;
3844 /* set up the application menu */
3845 svcsMenu = [[EmacsMenu alloc] initWithTitle: @"Services"];
3846 [svcsMenu setAutoenablesItems: NO];
3847 appMenu = [[EmacsMenu alloc] initWithTitle: @"Emacs"];
3848 [appMenu setAutoenablesItems: NO];
3849 mainMenu = [[EmacsMenu alloc] initWithTitle: @""];
3850 dockMenu = [[EmacsMenu alloc] initWithTitle: @""];
3851
3852 [appMenu insertItemWithTitle: @"About Emacs"
3853 action: @selector (orderFrontStandardAboutPanel:)
3854 keyEquivalent: @""
3855 atIndex: 0];
3856 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 1];
3857 [appMenu insertItemWithTitle: @"Preferences..."
3858 action: @selector (showPreferencesWindow:)
3859 keyEquivalent: @","
3860 atIndex: 2];
3861 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 3];
3862 item = [appMenu insertItemWithTitle: @"Services"
3863 action: @selector (menuDown:)
3864 keyEquivalent: @""
3865 atIndex: 4];
3866 [appMenu setSubmenu: svcsMenu forItem: item];
3867 /* [svcsMenu setSupercell: item]; */
3868 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 5];
3869 [appMenu insertItemWithTitle: @"Hide Emacs"
3870 action: @selector (hide:)
3871 keyEquivalent: @"h"
3872 atIndex: 6];
3873 item = [appMenu insertItemWithTitle: @"Hide Others"
3874 action: @selector (hideOtherApplications:)
3875 keyEquivalent: @"h"
3876 atIndex: 7];
3877 [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
3878 [appMenu insertItem: [NSMenuItem separatorItem] atIndex: 8];
3879 [appMenu insertItemWithTitle: @"Quit Emacs"
3880 action: @selector (terminate:)
3881 keyEquivalent: @"q"
3882 atIndex: 9];
3883
3884 item = [mainMenu insertItemWithTitle: @"Emacs"
3885 action: @selector (menuDown:)
3886 keyEquivalent: @""
3887 atIndex: 0];
3888 [mainMenu setSubmenu: appMenu forItem: item];
3889 [dockMenu insertItemWithTitle: @"New Frame"
3890 action: @selector (newFrame:)
3891 keyEquivalent: @""
3892 atIndex: 0];
3893
3894 [NSApp setMainMenu: mainMenu];
3895 [NSApp setAppleMenu: appMenu];
3896 [NSApp setServicesMenu: svcsMenu];
3897 /* Needed at least on Cocoa, to get dock menu to show windows */
3898 [NSApp setWindowsMenu: [[NSMenu alloc] init]];
3899 }
3900 #endif /* MAC OS X menu setup */
3901
3902 [NSApp run];
3903
3904 return dpyinfo;
3905 }
3906
3907
3908 extern Lisp_Object Vauto_save_list_file_name;
3909 void
3910 ns_term_shutdown (int sig)
3911 {
3912 /* code not reached in emacs.c after this is called by shut_down_emacs: */
3913 if (STRINGP (Vauto_save_list_file_name))
3914 unlink (SDATA (Vauto_save_list_file_name));
3915
3916 ns_shutdown_properly = YES;
3917 [NSApp terminate: NSApp];
3918 }
3919
3920
3921 /* ==========================================================================
3922
3923 EmacsApp implementation
3924
3925 ========================================================================== */
3926
3927
3928 @implementation EmacsApp
3929
3930 - (void)logNotification: (NSNotification *)notification
3931 {
3932 const char *name = [[notification name] UTF8String];
3933 if (!strstr (name, "Update") && !strstr (name, "NSMenu")
3934 && !strstr (name, "WindowNumber"))
3935 NSLog (@"notification: '%@'", [notification name]);
3936 }
3937
3938
3939 - (void)sendEvent: (NSEvent *)theEvent
3940 /* --------------------------------------------------------------------------
3941 Events posted by ns_send_appdefined interrupt the run loop here
3942 -------------------------------------------------------------------------- */
3943 {
3944 int type = [theEvent type];
3945 NSWindow *window = [theEvent window];
3946 /* NSTRACE (sendEvent); */
3947 /*fprintf (stderr, "received event of type %d\n", [theEvent type]); */
3948
3949 if (type == NSCursorUpdate && window == nil)
3950 {
3951 fprintf (stderr, "Dropping external cursor update event.\n");
3952 return;
3953 }
3954
3955 #ifdef NS_IMPL_COCOA
3956 /* pass mouse down in resize handle and subsequent drags directly to
3957 EmacsWindow so we can generate continuous redisplays */
3958 if (ns_in_resize)
3959 {
3960 if (type == NSLeftMouseDragged)
3961 {
3962 [window mouseDragged: theEvent];
3963 return;
3964 }
3965 else if (type == NSLeftMouseUp)
3966 {
3967 [window mouseUp: theEvent];
3968 return;
3969 }
3970 }
3971 else if (type == NSLeftMouseDown)
3972 {
3973 NSRect r = ns_resize_handle_rect (window);
3974 if (NSPointInRect ([theEvent locationInWindow], r))
3975 {
3976 ns_in_resize = YES;
3977 [window mouseDown: theEvent];
3978 return;
3979 }
3980 }
3981 #endif
3982
3983 if (type == NSApplicationDefined)
3984 {
3985 last_appdefined_event = theEvent;
3986 [self stop: self];
3987 }
3988
3989 [super sendEvent: theEvent];
3990 }
3991
3992
3993 - (void)showPreferencesWindow: (id)sender
3994 {
3995 if (prefsController == nil)
3996 prefsController = [[EmacsPrefsController alloc] init];
3997 [prefsController showForFrame: SELECTED_FRAME ()];
3998 }
3999
4000
4001 - (void)newFrame: (id)sender
4002 {
4003 struct frame *emacsframe = SELECTED_FRAME ();
4004 NSEvent *theEvent = [NSApp currentEvent];
4005
4006 if (!emacs_event)
4007 return;
4008 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4009 emacs_event->code = KEY_NS_NEW_FRAME;
4010 emacs_event->modifiers = 0;
4011 EV_TRAILER (theEvent);
4012 }
4013
4014
4015 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4016 - (BOOL) openFile: (NSString *)fileName
4017 {
4018 struct frame *emacsframe = SELECTED_FRAME ();
4019 NSEvent *theEvent = [NSApp currentEvent];
4020
4021 if (!emacs_event)
4022 return NO;
4023
4024 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4025 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4026 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4027 ns_input_line = Qnil; /* can be start or cons start,end */
4028 emacs_event->modifiers =0;
4029 EV_TRAILER (theEvent);
4030
4031 return YES;
4032 }
4033
4034
4035 /* **************************************************************************
4036
4037 EmacsApp delegate implementation
4038
4039 ************************************************************************** */
4040
4041 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4042 /* --------------------------------------------------------------------------
4043 When application is loaded, terminate event loop in ns_term_init
4044 -------------------------------------------------------------------------- */
4045 {
4046 NSTRACE (applicationDidFinishLaunching);
4047 [NSApp setServicesProvider: NSApp];
4048 ns_send_appdefined (-2);
4049 }
4050
4051
4052 - (void) terminate: (id)sender
4053 {
4054 BLOCK_INPUT;
4055 if (ns_shutdown_properly)
4056 [super terminate: sender];
4057 else
4058 {
4059 /* Fkill_emacs (Qnil); */
4060 ns_shutdown_properly = YES;
4061 Feval (Fcons (intern ("save-buffers-kill-emacs"), Qnil));
4062 }
4063 UNBLOCK_INPUT;
4064 }
4065
4066
4067 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4068 {
4069 if (ns_shutdown_properly)
4070 return NSTerminateNow;
4071
4072 Lisp_Object contents = list3 (build_string ("Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?"),
4073 Fcons (build_string ("Cancel"), Qnil),
4074 Fcons (build_string ("Save and Exit"), Qt));
4075 Lisp_Object res = ns_popup_dialog (Qt, contents, Qnil);
4076 fprintf (stderr, "res = %d\n", EQ (res, Qt)); /* FIXME */
4077 if (EQ (res, Qt))
4078 {
4079 Feval (Fcons (intern ("save-buffers-kill-emacs"), Qnil));
4080 return NSTerminateNow;
4081 }
4082 return NSTerminateCancel;
4083 }
4084
4085
4086 /* Notification from the Workspace to open a file */
4087 - (BOOL)application: sender openFile: (NSString *)file
4088 {
4089 [ns_pending_files addObject: file];
4090 return YES;
4091 }
4092
4093
4094 /* Open a file as a temporary file */
4095 - (BOOL)application: sender openTempFile: (NSString *)file
4096 {
4097 [ns_pending_files addObject: file];
4098 return YES;
4099 }
4100
4101
4102 /* Notification from the Workspace to open a file noninteractively (?) */
4103 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4104 {
4105 [ns_pending_files addObject: file];
4106 return YES;
4107 }
4108
4109
4110 /* Notification from the Workspace to open multiple files */
4111 - (void)application: sender openFiles: (NSArray *)fileList
4112 {
4113 NSEnumerator *files = [fileList objectEnumerator];
4114 NSString *file;
4115 while ((file = [files nextObject]) != nil)
4116 [ns_pending_files addObject: file];
4117
4118 /* TODO: when GNUstep implements this (and we require that version of
4119 GNUstep), remove. */
4120 #ifndef NS_IMPL_GNUSTEP
4121 [self replyToOpenOrPrint: NSApplicationDelegateReplySuccess];
4122 #endif /* !NS_IMPL_GNUSTEP */
4123
4124 }
4125
4126
4127 /* Handle dock menu requests. */
4128 - (NSMenu *)applicationDockMenu: (NSApplication *) sender
4129 {
4130 return dockMenu;
4131 }
4132
4133
4134 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4135 - (void)applicationDidBecomeActive: (NSNotification *)notification
4136 {
4137 }
4138 - (void)applicationDidResignActive: (NSNotification *)notification
4139 {
4140 ns_send_appdefined (-1);
4141 }
4142
4143
4144
4145 /* ==========================================================================
4146
4147 EmacsApp aux handlers for managing event loop
4148
4149 ========================================================================== */
4150
4151
4152 - (void)timeout_handler: (NSTimer *)timedEntry
4153 /* --------------------------------------------------------------------------
4154 The timeout specified to ns_select has passed.
4155 -------------------------------------------------------------------------- */
4156 {
4157 /*NSTRACE (timeout_handler); */
4158 ns_send_appdefined (-2);
4159 }
4160
4161 extern void update_window_cursor (struct window *w, int on);
4162
4163 - (void)fd_handler: (NSTimer *) fdEntry
4164 /* --------------------------------------------------------------------------
4165 Check data waiting on file descriptors and terminate if so
4166 -------------------------------------------------------------------------- */
4167 {
4168 int result;
4169 /* NSTRACE (fd_handler); */
4170
4171 if (select_nfds == 0)
4172 return;
4173
4174 memcpy (&t_readfds, &select_readfds, sizeof (fd_set));
4175
4176 select_timeout.tv_sec = select_timeout.tv_usec = 0;
4177 result = select (select_nfds, &t_readfds, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
4178 &select_timeout);
4179 if (result)
4180 {
4181 memcpy (&select_readfds, &t_readfds, sizeof (fd_set));
4182 ns_send_appdefined (result);
4183 }
4184 }
4185
4186
4187
4188 /* ==========================================================================
4189
4190 Service provision
4191
4192 ========================================================================== */
4193
4194 /* called from system: queue for next pass through event loop */
4195 - (void)requestService: (NSPasteboard *)pboard
4196 userData: (NSString *)userData
4197 error: (NSString **)error
4198 {
4199 [ns_pending_service_names addObject: userData];
4200 [ns_pending_service_args addObject: [NSString stringWithUTF8String:
4201 SDATA (ns_string_from_pasteboard (pboard))]];
4202 }
4203
4204
4205 /* called from ns_read_socket to clear queue */
4206 - (BOOL)fulfillService: (NSString *)name withArg: (NSString *)arg
4207 {
4208 struct frame *emacsframe = SELECTED_FRAME ();
4209 NSEvent *theEvent = [NSApp currentEvent];
4210
4211 if (!emacs_event)
4212 return NO;
4213
4214 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4215 emacs_event->code = KEY_NS_SPI_SERVICE_CALL;
4216 ns_input_spi_name = build_string ([name UTF8String]);
4217 ns_input_spi_arg = build_string ([arg UTF8String]);
4218 emacs_event->modifiers = EV_MODIFIERS (theEvent);
4219 EV_TRAILER (theEvent);
4220
4221 return YES;
4222 }
4223
4224
4225 @end /* EmacsApp */
4226
4227
4228
4229 /* ==========================================================================
4230
4231 EmacsView implementation
4232
4233 ========================================================================== */
4234
4235
4236 @implementation EmacsView
4237
4238 /* needed to inform when window closed from LISP */
4239 - (void) setWindowClosing: (BOOL)closing
4240 {
4241 windowClosing = closing;
4242 }
4243
4244
4245 - (void)dealloc
4246 {
4247 NSTRACE (EmacsView_dealloc);
4248 [toolbar release];
4249 [super dealloc];
4250 }
4251
4252
4253 /* called on font panel selection */
4254 - (void)changeFont: (id)sender
4255 {
4256 NSEvent *e =[[self window] currentEvent];
4257 struct face *face =FRAME_DEFAULT_FACE (emacsframe);
4258 id newFont;
4259 float size;
4260
4261 NSTRACE (changeFont);
4262 if (!emacs_event)
4263 return;
4264
4265 if (newFont = [sender convertFont:
4266 ((struct nsfont_info *)face->font)->nsfont])
4267 {
4268 SET_FRAME_GARBAGED (emacsframe); /* now needed as of 2008/10 */
4269
4270 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4271 emacs_event->modifiers = 0;
4272 emacs_event->code = KEY_NS_CHANGE_FONT;
4273
4274 size = [newFont pointSize];
4275 ns_input_fontsize = make_number (lrint (size));
4276 ns_input_font = build_string ([[newFont familyName] UTF8String]);
4277 EV_TRAILER (e);
4278 }
4279 }
4280
4281
4282 - (BOOL)acceptsFirstResponder
4283 {
4284 NSTRACE (acceptsFirstResponder);
4285 return YES;
4286 }
4287
4288
4289 - (void)resetCursorRects
4290 {
4291 NSRect visible = [self visibleRect];
4292 NSCursor *currentCursor = FRAME_POINTER_TYPE (emacsframe);
4293 NSTRACE (resetCursorRects);
4294
4295 if (currentCursor == nil)
4296 currentCursor = [NSCursor arrowCursor];
4297
4298 if (!NSIsEmptyRect (visible))
4299 [self addCursorRect: visible cursor: currentCursor];
4300 [currentCursor setOnMouseEntered: YES];
4301 }
4302
4303
4304 /*****************************************************************************/
4305 /* Keyboard handling. */
4306 #define NS_KEYLOG 0
4307
4308 - (void)keyDown: (NSEvent *)theEvent
4309 {
4310 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4311 int code;
4312 unsigned fnKeysym = 0;
4313 int flags;
4314 static NSMutableArray *nsEvArray;
4315 static BOOL firstTime = YES;
4316
4317 NSTRACE (keyDown);
4318
4319 /* Rhapsody and OS X give up and down events for the arrow keys */
4320 if ([theEvent type] != NSKeyDown)
4321 return;
4322
4323 if (!emacs_event)
4324 return;
4325
4326 if (![[self window] isKeyWindow])
4327 {
4328 /* XXX: Using NO_SOCK_SIGIO like Carbon causes a condition in which,
4329 when Emacs display updates a different frame from the current one,
4330 and temporarily selects it, then processes some interrupt-driven
4331 input (dispnew.c:3878), OS will send the event to the correct NSWindow,
4332 but for some reason that window has its first responder set to the
4333 NSView most recently updated (I guess), which is not the correct one.
4334 UPDATE: After multi-TTY merge this happens even w/o NO_SOCK_SIGIO */
4335 if ([[theEvent window] isKindOfClass: [EmacsWindow class]])
4336 [(EmacsView *)[[theEvent window] delegate] keyDown: theEvent];
4337 return;
4338 }
4339
4340 if (nsEvArray == nil)
4341 nsEvArray = [[NSMutableArray alloc] initWithCapacity: 1];
4342
4343 [NSCursor setHiddenUntilMouseMoves: YES];
4344
4345 if (dpyinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
4346 {
4347 clear_mouse_face (dpyinfo);
4348 dpyinfo->mouse_face_hidden = 1;
4349 }
4350
4351 if (!processingCompose)
4352 {
4353 code = ([[theEvent charactersIgnoringModifiers] length] == 0) ?
4354 0 : [[theEvent charactersIgnoringModifiers] characterAtIndex: 0];
4355 /* (Carbon way: [theEvent keyCode]) */
4356
4357 /* is it a "function key"? */
4358 fnKeysym = ns_convert_key (code);
4359 if (fnKeysym)
4360 {
4361 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
4362 because Emacs treats Delete and KP-Delete same (in simple.el). */
4363 if (fnKeysym == 0xFFFF && [theEvent keyCode] == 0x33)
4364 code = 0xFF08; /* backspace */
4365 else
4366 code = fnKeysym;
4367 }
4368
4369 /* are there modifiers? */
4370 emacs_event->modifiers = 0;
4371 flags = [theEvent modifierFlags];
4372
4373 if (flags & NSHelpKeyMask)
4374 emacs_event->modifiers |= hyper_modifier;
4375
4376 if (flags & NSShiftKeyMask)
4377 emacs_event->modifiers |= shift_modifier;
4378
4379 if (flags & NSCommandKeyMask)
4380 {
4381 emacs_event->modifiers |= parse_solitary_modifier (ns_command_modifier);
4382 /* if super (default), take input manager's word so things like
4383 dvorak / qwerty layout work */
4384 if (EQ (ns_command_modifier, Qsuper)
4385 && !fnKeysym
4386 && [[theEvent characters] length] != 0)
4387 {
4388 /* XXX: the code we get will be unshifted, so if we have
4389 a shift modifier, must convert ourselves */
4390 if (!(flags & NSShiftKeyMask))
4391 code = [[theEvent characters] characterAtIndex: 0];
4392 #if 0
4393 /* this is ugly and also requires linking w/Carbon framework
4394 (for LMGetKbdType) so for now leave this rare (?) case
4395 undealt with.. in future look into CGEvent methods */
4396 else
4397 {
4398 long smv = GetScriptManagerVariable (smKeyScript);
4399 Handle uchrHandle = GetResource
4400 ('uchr', GetScriptVariable (smv, smScriptKeys));
4401 UInt32 dummy = 0;
4402 UCKeyTranslate ((UCKeyboardLayout*)*uchrHandle,
4403 [[theEvent characters] characterAtIndex: 0],
4404 kUCKeyActionDisplay,
4405 (flags & ~NSCommandKeyMask) >> 8,
4406 LMGetKbdType (), kUCKeyTranslateNoDeadKeysMask,
4407 &dummy, 1, &dummy, &code);
4408 code &= 0xFF;
4409 }
4410 #endif
4411 }
4412 }
4413
4414 if (flags & NSControlKeyMask)
4415 emacs_event->modifiers |= parse_solitary_modifier (ns_control_modifier);
4416
4417 if (flags & NS_FUNCTION_KEY_MASK && !fnKeysym)
4418 emacs_event->modifiers |= parse_solitary_modifier (ns_function_modifier);
4419
4420 if (flags & NSAlternateKeyMask) /* default = meta */
4421 {
4422 if (EQ (ns_alternate_modifier, Qnone) && !fnKeysym)
4423 { /* accept pre-interp alt comb */
4424 if ([[theEvent characters] length] > 0)
4425 code = [[theEvent characters] characterAtIndex: 0];
4426 /*HACK: clear lone shift modifier to stop next if from firing */
4427 if (emacs_event->modifiers == shift_modifier)
4428 emacs_event->modifiers = 0;
4429 }
4430 else
4431 emacs_event->modifiers |= parse_solitary_modifier (ns_alternate_modifier);
4432 }
4433
4434 /*fprintf (stderr,"code =%x\tfnKey =%x\tflags = %x\tmods = %x\n",code,fnKeysym,flags,emacs_event->modifiers); */
4435
4436 /* if it was a function key or had modifiers, pass it directly to emacs */
4437 if (fnKeysym || (emacs_event->modifiers
4438 && [[theEvent charactersIgnoringModifiers] length] > 0))
4439 /*[[theEvent characters] length] */
4440 {
4441 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4442 if (code < 0x20)
4443 code |= (1<<28)|(3<<16);
4444 else if (code == 0x7f)
4445 code |= (1<<28)|(3<<16);
4446 else if (!fnKeysym)
4447 emacs_event->kind = code > 0xFF
4448 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4449
4450 emacs_event->code = code;
4451 EV_TRAILER (theEvent);
4452 return;
4453 }
4454 }
4455
4456 /* if we get here we should send the key for input manager processing */
4457 if (firstTime && [[NSInputManager currentInputManager]
4458 wantsToDelayTextChangeNotifications] == NO)
4459 fprintf (stderr,
4460 "Emacs: WARNING: TextInput mgr wants marked text to be permanent!\n");
4461 firstTime = NO;
4462
4463 if (NS_KEYLOG && !processingCompose)
4464 fprintf (stderr, "Begin compose sequence.\n");
4465
4466 processingCompose = YES;
4467 [nsEvArray addObject: theEvent];
4468 [self interpretKeyEvents: nsEvArray];
4469 [nsEvArray removeObject: theEvent];
4470 }
4471
4472
4473 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
4474
4475
4476 /* <NSTextInput>: called through when done composing */
4477 - (void)insertText: (id)aString
4478 {
4479 int code;
4480 int len = [(NSString *)aString length];
4481 int i;
4482
4483 if (NS_KEYLOG) NSLog (@"insertText '%@'\tlen = %d", aString, len);
4484 processingCompose = NO;
4485
4486 if (!emacs_event)
4487 return;
4488
4489 /* first, clear any working text */
4490 if (workingText != nil)
4491 [self deleteWorkingText];
4492
4493 /* now insert the string as keystrokes */
4494 for (i =0; i<len; i++)
4495 {
4496 code = [aString characterAtIndex: i];
4497 /* TODO: still need this? */
4498 if (code == 0x2DC)
4499 code = '~'; /* 0x7E */
4500 emacs_event->modifiers = 0;
4501 emacs_event->kind
4502 = code > 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT : ASCII_KEYSTROKE_EVENT;
4503 emacs_event->code = code;
4504 EV_TRAILER ((id)nil);
4505 }
4506 }
4507
4508
4509 /* <NSTextInput>: inserts display of composing characters */
4510 - (void)setMarkedText: (id)aString selectedRange: (NSRange)selRange
4511 {
4512 NSString *str = [aString respondsToSelector: @selector (string)] ?
4513 [aString string] : aString;
4514 if (NS_KEYLOG)
4515 NSLog (@"setMarkedText '%@' len =%d range %d from %d", str, [str length],
4516 selRange.length, selRange.location);
4517
4518 if (workingText != nil)
4519 [self deleteWorkingText];
4520 if ([str length] == 0)
4521 return;
4522
4523 if (!emacs_event)
4524 return;
4525
4526 processingCompose = YES;
4527 workingText = [str copy];
4528 ns_working_text = build_string ([workingText UTF8String]);
4529
4530 /* if in "echo area", not true minibuffer, can't show chars in interactive
4531 mode, so call using eval; otherwise we send a key event, which was the
4532 original way this was done */
4533 if (!EQ (Feval (Fcons (intern ("ns-in-echo-area"), Qnil)), Qnil))
4534 {
4535 Feval (Fcons (intern ("ns-echo-working-text"), Qnil));
4536 ns_send_appdefined (-1);
4537 }
4538 else
4539 {
4540 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4541 emacs_event->code = KEY_NS_INSERT_WORKING_TEXT;
4542 EV_TRAILER ((id)nil);
4543 }
4544 }
4545
4546
4547 /* delete display of composing characters [not in <NSTextInput>] */
4548 - (void)deleteWorkingText
4549 {
4550 if (workingText == nil)
4551 return;
4552 if (NS_KEYLOG)
4553 fprintf (stderr, "deleteWorkingText len =%d\n", [workingText length]);
4554 [workingText release];
4555 workingText = nil;
4556 processingCompose = NO;
4557
4558 if (!emacs_event)
4559 return;
4560
4561 if (!EQ (Feval (Fcons (intern ("ns-in-echo-area"), Qnil)), Qnil))
4562 {
4563 Feval (Fcons (intern ("ns-unecho-working-text"), Qnil));
4564 ns_send_appdefined (-1);
4565 }
4566 else
4567 {
4568 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4569 emacs_event->code = KEY_NS_DELETE_WORKING_TEXT;
4570 EV_TRAILER ((id)nil);
4571 }
4572 }
4573
4574
4575 - (BOOL)hasMarkedText
4576 {
4577 return workingText != nil;
4578 }
4579
4580 - (NSRange)markedRange
4581 {
4582 NSRange rng = workingText != nil
4583 ? NSMakeRange (0, [workingText length]) : NSMakeRange (NSNotFound, 0);
4584 if (NS_KEYLOG) NSLog (@"markedRange request");
4585 return rng;
4586 }
4587
4588 - (void)unmarkText
4589 {
4590 if (NS_KEYLOG) NSLog (@"unmark (accept) text");
4591 [self deleteWorkingText];
4592 processingCompose = NO;
4593 }
4594
4595 /* used to position char selection windows, etc. */
4596 - (NSRect)firstRectForCharacterRange: (NSRange)theRange
4597 {
4598 NSRect rect;
4599 NSPoint pt;
4600 struct window *win = XWINDOW (FRAME_SELECTED_WINDOW (emacsframe));
4601 if (NS_KEYLOG) NSLog (@"firstRectForCharRange request");
4602
4603 rect.size.width = theRange.length * FRAME_COLUMN_WIDTH (emacsframe);
4604 rect.size.height = FRAME_LINE_HEIGHT (emacsframe);
4605 pt.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (win, win->phys_cursor.x);
4606 pt.y = WINDOW_TO_FRAME_PIXEL_Y (win, win->phys_cursor.y
4607 +FRAME_LINE_HEIGHT (emacsframe));
4608
4609 pt = [self convertPoint: pt toView: nil];
4610 pt = [[self window] convertBaseToScreen: pt];
4611 rect.origin = pt;
4612 return rect;
4613 }
4614
4615 - (NSInteger)conversationIdentifier
4616 {
4617 return (NSInteger)self;
4618 }
4619
4620 /* TODO: below here not yet implemented correctly, but may not be needed */
4621
4622 - (void)doCommandBySelector: (SEL)aSelector
4623 {
4624 if (NS_KEYLOG) NSLog (@"Do command by selector: %@",
4625 NSStringFromSelector (aSelector));
4626
4627 if (aSelector == @selector (deleteBackward:))
4628 {
4629 /* happens when user backspaces over an ongoing composition:
4630 throw a 'delete' into the event queue */
4631 if (!emacs_event)
4632 return;
4633 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
4634 emacs_event->code = 0xFF08;
4635 EV_TRAILER ((id)nil);
4636 }
4637 }
4638
4639 - (NSArray *)validAttributesForMarkedText
4640 {
4641 static NSArray *arr = nil;
4642 if (arr == nil) arr = [NSArray new];
4643 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
4644 return arr;
4645 }
4646
4647 - (NSRange)selectedRange
4648 {
4649 if (NS_KEYLOG) NSLog (@"selectedRange request");
4650 return NSMakeRange (NSNotFound, 0);
4651 }
4652
4653 - (unsigned int)characterIndexForPoint: (NSPoint)thePoint
4654 {
4655 if (NS_KEYLOG) NSLog (@"characterIndexForPoint request");
4656 return 0;
4657 }
4658
4659 - (NSAttributedString *)attributedSubstringFromRange: (NSRange)theRange
4660 {
4661 static NSAttributedString *str = nil;
4662 if (str == nil) str = [NSAttributedString new];
4663 if (NS_KEYLOG) NSLog (@"attributedSubstringFromRange request");
4664 return str;
4665 }
4666
4667 /* End <NSTextInput> impl. */
4668 /*****************************************************************************/
4669
4670
4671 /* This is what happens when the user presses a mouse button. */
4672 - (void)mouseDown: (NSEvent *)theEvent
4673 {
4674 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
4675 Lisp_Object window;
4676
4677 NSTRACE (mouseDown);
4678
4679 [self deleteWorkingText];
4680
4681 if (!emacs_event)
4682 return;
4683
4684 last_mouse_frame = emacsframe;
4685 /* appears to be needed to prevent spurious movement events generated on
4686 button clicks */
4687 last_mouse_frame->mouse_moved = 0;
4688
4689 if ([theEvent type] == NSScrollWheel)
4690 {
4691 float delta = [theEvent deltaY];
4692 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
4693 if (delta == 0)
4694 return;
4695 emacs_event->kind = WHEEL_EVENT;
4696 emacs_event->code = 0;
4697 emacs_event->modifiers = EV_MODIFIERS (theEvent) |
4698 ((delta > 0) ? up_modifier : down_modifier);
4699 }
4700 else
4701 {
4702 emacs_event->kind = MOUSE_CLICK_EVENT;
4703 emacs_event->code = EV_BUTTON (theEvent);
4704 emacs_event->modifiers = EV_MODIFIERS (theEvent)
4705 | EV_UDMODIFIERS (theEvent);
4706 }
4707 XSETINT (emacs_event->x, lrint (p.x));
4708 XSETINT (emacs_event->y, lrint (p.y));
4709 EV_TRAILER (theEvent);
4710 }
4711
4712
4713 - (void)mouseUp: (NSEvent *)theEvent
4714 {
4715 NSTRACE (mouseUp);
4716 [self mouseDown: theEvent];
4717 }
4718
4719
4720 - (void)rightMouseDown: (NSEvent *)theEvent
4721 {
4722 NSTRACE (rightMouseDown);
4723 [self mouseDown: theEvent];
4724 }
4725
4726
4727 - (void)rightMouseUp: (NSEvent *)theEvent
4728 {
4729 NSTRACE (rightMouseUp);
4730 [self mouseDown: theEvent];
4731 }
4732
4733
4734 - (void) scrollWheel: (NSEvent *)theEvent
4735 {
4736 NSTRACE (scrollWheel);
4737 [self mouseDown: theEvent];
4738 }
4739
4740
4741 /* Tell emacs the mouse has moved. */
4742 - (void)mouseMoved: (NSEvent *)e
4743 {
4744 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4745 Lisp_Object frame;
4746
4747 // NSTRACE (mouseMoved);
4748
4749 last_mouse_movement_time = EV_TIMESTAMP (e);
4750 last_mouse_motion_position
4751 = [self convertPoint: [e locationInWindow] fromView: nil];
4752
4753 /* update any mouse face */
4754 if (dpyinfo->mouse_face_hidden)
4755 {
4756 dpyinfo->mouse_face_hidden = 0;
4757 clear_mouse_face (dpyinfo);
4758 }
4759
4760 /* tooltip handling */
4761 previous_help_echo_string = help_echo_string;
4762 help_echo_string = Qnil;
4763
4764 if (!note_mouse_movement (emacsframe, last_mouse_motion_position.x,
4765 last_mouse_motion_position.y))
4766 help_echo_string = previous_help_echo_string;
4767
4768 XSETFRAME (frame, emacsframe);
4769 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
4770 {
4771 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
4772 (note_mouse_highlight), which is called through the
4773 note_mouse_movement () call above */
4774 gen_help_event (help_echo_string, frame, help_echo_window,
4775 help_echo_object, help_echo_pos);
4776 }
4777 else
4778 {
4779 help_echo_string = Qnil;
4780 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
4781 }
4782
4783 if (emacsframe->mouse_moved && send_appdefined)
4784 ns_send_appdefined (-1);
4785 }
4786
4787
4788 - (void)mouseDragged: (NSEvent *)e
4789 {
4790 NSTRACE (mouseDragged);
4791 [self mouseMoved: e];
4792 }
4793
4794
4795 - (void)rightMouseDragged: (NSEvent *)e
4796 {
4797 NSTRACE (rightMouseDragged);
4798 [self mouseMoved: e];
4799 }
4800
4801
4802 - (BOOL)windowShouldClose: (id)sender
4803 {
4804 NSEvent *e =[[self window] currentEvent];
4805
4806 NSTRACE (windowShouldClose);
4807 windowClosing = YES;
4808 if (!emacs_event)
4809 return NO;
4810 emacs_event->kind = DELETE_WINDOW_EVENT;
4811 emacs_event->modifiers = 0;
4812 emacs_event->code = 0;
4813 EV_TRAILER (e);
4814 /* Don't close this window, let this be done from lisp code. */
4815 return NO;
4816 }
4817
4818
4819 - (NSSize)windowWillResize: (NSWindow *)sender toSize: (NSSize)frameSize
4820 /* normalize frame to gridded text size */
4821 {
4822 NSTRACE (windowWillResize);
4823 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
4824
4825 cols = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (emacsframe,
4826 #ifdef NS_IMPL_GNUSTEP
4827 frameSize.width + 3);
4828 #else
4829 frameSize.width);
4830 #endif
4831 if (cols < MINWIDTH)
4832 cols = MINWIDTH;
4833 frameSize.width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (emacsframe, cols);
4834
4835 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (emacsframe, frameSize.height
4836 #ifdef NS_IMPL_GNUSTEP
4837 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe) + 3
4838 - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
4839 #else
4840 - FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
4841 - FRAME_NS_TOOLBAR_HEIGHT (emacsframe));
4842 #endif
4843 if (rows < MINHEIGHT)
4844 rows = MINHEIGHT;
4845 frameSize.height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (emacsframe, rows)
4846 + FRAME_NS_TITLEBAR_HEIGHT (emacsframe)
4847 + FRAME_NS_TOOLBAR_HEIGHT (emacsframe);
4848 #ifdef NS_IMPL_COCOA
4849 {
4850 /* this sets window title to have size in it; the wm does this under GS */
4851 NSRect r = [[self window] frame];
4852 if (r.size.height == frameSize.height && r.size.width == frameSize.width)
4853 {
4854 if (old_title != 0)
4855 {
4856 xfree (old_title);
4857 old_title = 0;
4858 }
4859 }
4860 else
4861 {
4862 char *size_title;
4863 NSWindow *window = [self window];
4864 if (old_title == 0)
4865 {
4866 const char *t = [[[self window] title] UTF8String];
4867 char *pos = strstr (t, " — ");
4868 if (pos)
4869 *pos = '\0';
4870 old_title = (char *) xmalloc (strlen (t) + 1);
4871 strcpy (old_title, t);
4872 }
4873 size_title = xmalloc (strlen (old_title) + 40);
4874 sprintf (size_title, "%s — (%d x %d)", old_title, cols, rows);
4875 [window setTitle: [NSString stringWithUTF8String: size_title]];
4876 [window display];
4877 xfree (size_title);
4878 }
4879 }
4880 #endif /* NS_IMPL_COCOA */
4881 /*fprintf (stderr," ...size became %.0f x %.0f (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
4882
4883 return frameSize;
4884 }
4885
4886
4887 - (void)windowDidResize: (NSNotification *)notification
4888 {
4889 NSWindow *theWindow = [notification object];
4890
4891 #ifdef NS_IMPL_GNUSTEP
4892 /* in GNUstep, at least currently, it's possible to get a didResize
4893 without getting a willResize.. therefore we need to act as if we got
4894 the willResize now */
4895 NSSize sz = [theWindow frame].size;
4896 sz = [self windowWillResize: theWindow toSize: sz];
4897 #endif /* NS_IMPL_GNUSTEP */
4898
4899 NSTRACE (windowDidResize);
4900 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
4901
4902 #ifdef NS_IMPL_COCOA
4903 if (old_title != 0)
4904 {
4905 xfree (old_title);
4906 old_title = 0;
4907 }
4908 #endif /* NS_IMPL_COCOA */
4909
4910 if (cols > 0 && rows > 0)
4911 x_set_window_size (emacsframe, 0, cols, rows);
4912
4913 ns_send_appdefined (-1);
4914
4915 /* The following line causes a crash on GNUstep. Adrian Robert
4916 says he doesn't remember why he added this line, but removing it
4917 doesn't seem to cause problems on OSX, either. */
4918 #if 0
4919 [NSApp stopModal];
4920 #endif
4921 }
4922
4923
4924 - (void)windowDidBecomeKey: (NSNotification *)notification
4925 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
4926 {
4927 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4928 struct frame *old_focus = dpyinfo->x_focus_frame;
4929
4930 NSTRACE (windowDidBecomeKey);
4931
4932 if (emacsframe != old_focus)
4933 dpyinfo->x_focus_frame = emacsframe;
4934
4935 ns_frame_rehighlight (emacsframe);
4936
4937 if (emacs_event)
4938 {
4939 emacs_event->kind = FOCUS_IN_EVENT;
4940 EV_TRAILER ((id)nil);
4941 }
4942 }
4943
4944
4945 - (void)windowDidResignKey: (NSNotification *)notification
4946 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
4947 {
4948 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
4949 NSTRACE (windowDidResignKey);
4950
4951 if (dpyinfo->x_focus_frame == emacsframe)
4952 dpyinfo->x_focus_frame = 0;
4953
4954 ns_frame_rehighlight (emacsframe);
4955
4956 /* FIXME: for some reason needed on second and subsequent clicks away
4957 from sole-frame Emacs to get hollow box to show */
4958 if (!windowClosing && [[self window] isVisible] == YES)
4959 x_update_cursor (emacsframe, 1);
4960
4961 if (emacs_event)
4962 {
4963 [self deleteWorkingText];
4964 emacs_event->kind = FOCUS_IN_EVENT;
4965 EV_TRAILER ((id)nil);
4966 }
4967 }
4968
4969
4970 - (void)windowWillMiniaturize: sender
4971 {
4972 NSTRACE (windowWillMiniaturize);
4973 }
4974
4975
4976 - (BOOL)isFlipped
4977 {
4978 return YES;
4979 }
4980
4981
4982 - (BOOL)isOpaque
4983 {
4984 return NO;
4985 }
4986
4987
4988 - initFrameFromEmacs: (struct frame *)f
4989 {
4990 NSRect r, wr;
4991 Lisp_Object tem;
4992 NSWindow *win;
4993 NSButton *toggleButton;
4994 int vbextra = NS_SCROLL_BAR_WIDTH (f);
4995 NSSize sz;
4996 NSColor *col;
4997 NSString *name;
4998
4999 NSTRACE (initFrameFromEmacs);
5000
5001 windowClosing = NO;
5002 processingCompose = NO;
5003 scrollbarsNeedingUpdate = 0;
5004
5005 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
5006
5007 r = NSMakeRect (0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, f->text_cols),
5008 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, f->text_lines));
5009 [self initWithFrame: r];
5010
5011 FRAME_NS_VIEW (f) = self;
5012 emacsframe = f;
5013 old_title = 0;
5014
5015 win = [[EmacsWindow alloc]
5016 initWithContentRect: r
5017 styleMask: (NSResizableWindowMask |
5018 NSMiniaturizableWindowMask |
5019 NSClosableWindowMask)
5020 backing: NSBackingStoreBuffered
5021 defer: YES];
5022
5023 wr = [win frame];
5024 f->border_width = wr.size.width - r.size.width;
5025 FRAME_NS_TITLEBAR_HEIGHT (f) = wr.size.height - r.size.height;
5026
5027 [win setAcceptsMouseMovedEvents: YES];
5028 [win setDelegate: self];
5029 [win useOptimizedDrawing: YES];
5030
5031 sz.width = FRAME_COLUMN_WIDTH (f);
5032 sz.height = FRAME_LINE_HEIGHT (f);
5033 [win setResizeIncrements: sz];
5034
5035 [[win contentView] addSubview: self];
5036
5037 if (ns_drag_types)
5038 [self registerForDraggedTypes: ns_drag_types];
5039
5040 tem = f->name;
5041 name = [NSString stringWithUTF8String:
5042 NILP (tem) ? (unsigned char *)"Emacs" : SDATA (tem)];
5043 [win setTitle: name];
5044
5045 /* toolbar support */
5046 toolbar = [[EmacsToolbar alloc] initForView: self withIdentifier:
5047 [NSString stringWithFormat: @"Emacs Frame %d",
5048 ns_window_num]];
5049 [win setToolbar: toolbar];
5050 [toolbar setVisible: NO];
5051 #ifdef NS_IMPL_COCOA
5052 toggleButton = [win standardWindowButton: NSWindowToolbarButton];
5053 [toggleButton setTarget: self];
5054 [toggleButton setAction: @selector (toggleToolbar: )];
5055 #endif
5056 FRAME_NS_TOOLBAR_HEIGHT (f) = 0;
5057
5058 tem = f->icon_name;
5059 if (!NILP (tem))
5060 [win setMiniwindowTitle:
5061 [NSString stringWithUTF8String: SDATA (tem)]];
5062
5063 {
5064 NSScreen *screen = [win screen];
5065
5066 if (screen != 0)
5067 [win setFrameTopLeftPoint: NSMakePoint
5068 (IN_BOUND (-SCREENMAX, f->left_pos, SCREENMAX),
5069 IN_BOUND (-SCREENMAX,
5070 [screen frame].size.height - NS_TOP_POS (f), SCREENMAX))];
5071 }
5072
5073 [win makeFirstResponder: self];
5074
5075 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
5076 (FRAME_DEFAULT_FACE (emacsframe)), emacsframe);
5077 [win setBackgroundColor: col];
5078 if ([col alphaComponent] != 1.0)
5079 [win setOpaque: NO];
5080
5081 [self allocateGState];
5082
5083 ns_window_num++;
5084 return self;
5085 }
5086
5087
5088 - (void)windowDidMove: sender
5089 {
5090 NSWindow *win = [self window];
5091 NSRect r = [win frame];
5092 NSScreen *screen = [win screen];
5093 NSRect sr = [screen frame];
5094
5095 NSTRACE (windowDidMove);
5096
5097 if (!emacsframe->output_data.ns)
5098 return;
5099 if (screen != nil)
5100 {
5101 emacsframe->left_pos = r.origin.x; /* - sr.origin.x; */
5102 emacsframe->top_pos = sr.size.height -
5103 (r.origin.y + r.size.height); /* + sr.origin.y; */
5104 }
5105 }
5106
5107 #ifdef NS_IMPL_COCOA
5108 /* if we don't do this manually, the window will resize but not move */
5109 - (BOOL)windowShouldZoom: (NSWindow *)sender toFrame: (NSRect)newFrame
5110 {
5111 [[self window] setFrame: newFrame display: NO];
5112 return YES;
5113 }
5114 #endif
5115
5116 /* Implement this to control size of frame on zoom.
5117 - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
5118 defaultFrame:(NSRect)defaultFrame; */
5119
5120
5121 - (void)windowDidDeminiaturize: sender
5122 {
5123 NSTRACE (windowDidDeminiaturize);
5124 if (!emacsframe->output_data.ns)
5125 return;
5126 emacsframe->async_visible = 1;
5127 emacsframe->async_iconified = 0;
5128 windows_or_buffers_changed++;
5129
5130 if (emacs_event)
5131 {
5132 emacs_event->kind = ICONIFY_EVENT;
5133 EV_TRAILER ((id)nil);
5134 }
5135 }
5136
5137
5138 - (void)windowDidExpose: sender
5139 {
5140 NSTRACE (windowDidExpose);
5141 if (!emacsframe->output_data.ns)
5142 return;
5143 emacsframe->async_visible = 1;
5144 SET_FRAME_GARBAGED (emacsframe);
5145
5146 if (send_appdefined)
5147 ns_send_appdefined (-1);
5148 }
5149
5150
5151 - (void)windowDidMiniaturize: sender
5152 {
5153 NSTRACE (windowDidMiniaturize);
5154 if (!emacsframe->output_data.ns)
5155 return;
5156
5157 emacsframe->async_iconified = 1;
5158
5159 if (emacs_event)
5160 {
5161 emacs_event->kind = ICONIFY_EVENT;
5162 EV_TRAILER ((id)nil);
5163 }
5164 }
5165
5166
5167 - (void)mouseEntered: (NSEvent *)theEvent
5168 {
5169 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5170 struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (emacsframe);
5171 NSTRACE (mouseEntered);
5172
5173 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5174 }
5175
5176
5177 - (void)mouseExited: (NSEvent *)theEvent
5178 {
5179 NSPoint p = [self convertPoint: [theEvent locationInWindow] fromView: nil];
5180 NSRect r;
5181 struct ns_display_info *dpyinfo
5182 = emacsframe ? FRAME_NS_DISPLAY_INFO (emacsframe) : NULL;
5183
5184 NSTRACE (mouseExited);
5185
5186 if (dpyinfo || !emacsframe)
5187 return;
5188
5189 last_mouse_movement_time = EV_TIMESTAMP (theEvent);
5190
5191 if (emacsframe == dpyinfo->mouse_face_mouse_frame)
5192 {
5193 clear_mouse_face (dpyinfo);
5194 dpyinfo->mouse_face_mouse_frame = 0;
5195 }
5196 }
5197
5198
5199 - menuDown: sender
5200 {
5201 NSTRACE (menuDown);
5202 if (context_menu_value == -1)
5203 context_menu_value = [sender tag];
5204 else
5205 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
5206 emacsframe->menu_bar_vector,
5207 (void *)[sender tag]);
5208 ns_send_appdefined (-1);
5209 return self;
5210 }
5211
5212
5213 - (EmacsToolbar *)toolbar
5214 {
5215 return toolbar;
5216 }
5217
5218
5219 /* this gets called on toolbar button click */
5220 - toolbarClicked: (id)item
5221 {
5222 NSEvent *theEvent;
5223 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
5224
5225 NSTRACE (toolbarClicked);
5226
5227 if (!emacs_event)
5228 return self;
5229
5230 /* send first event (for some reason two needed) */
5231 theEvent =[[self window] currentEvent];
5232 emacs_event->kind = TOOL_BAR_EVENT;
5233 XSETFRAME (emacs_event->arg, emacsframe);
5234 EV_TRAILER (theEvent);
5235
5236 emacs_event->kind = TOOL_BAR_EVENT;
5237 /* XSETINT (emacs_event->code, 0); */
5238 emacs_event->arg = AREF (emacsframe->tool_bar_items,
5239 idx + TOOL_BAR_ITEM_KEY);
5240 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5241 EV_TRAILER (theEvent);
5242 return self;
5243 }
5244
5245
5246 - toggleToolbar: (id)sender
5247 {
5248 Lisp_Object lispFrame;
5249 XSETFRAME (lispFrame, emacsframe);
5250 Feval (Fcons (intern ("ns-toggle-toolbar"), Fcons (lispFrame, Qnil)));
5251 SET_FRAME_GARBAGED (emacsframe);
5252 ns_send_appdefined (-1);
5253 }
5254
5255
5256 - (void)drawRect: (NSRect)rect
5257 {
5258 int x = NSMinX (rect), y = NSMinY (rect);
5259 int width = NSWidth (rect), height = NSHeight (rect);
5260
5261 NSTRACE (drawRect);
5262
5263 if (!emacsframe || !emacsframe->output_data.ns)
5264 return;
5265
5266 if (!ns_in_resize)
5267 ns_clear_frame_area (emacsframe, x, y, width, height);
5268 expose_frame (emacsframe, x, y, width, height);
5269
5270 emacsframe->async_visible = 1;
5271 emacsframe->async_iconified = 0;
5272
5273 /* SET_FRAME_GARBAGED (emacsframe);
5274 ns_send_appdefined (-1); */
5275 }
5276
5277
5278 /* NSDraggingDestination protocol methods. Actually this is not really a
5279 protocol, but a category of Object. O well... */
5280
5281 -(unsigned int) draggingEntered: (id <NSDraggingInfo>) sender
5282 {
5283 NSTRACE (draggingEntered);
5284 return NSDragOperationGeneric;
5285 }
5286
5287
5288 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
5289 {
5290 return YES;
5291 }
5292
5293
5294 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
5295 {
5296 id pb;
5297 int x, y;
5298 NSString *type;
5299 NSEvent *theEvent = [[self window] currentEvent];
5300 NSPoint position;
5301
5302 NSTRACE (performDragOperation);
5303
5304 if (!emacs_event)
5305 return;
5306
5307 position = [self convertPoint: [sender draggingLocation] fromView: nil];
5308 x = lrint (position.x); y = lrint (position.y);
5309
5310 pb = [sender draggingPasteboard];
5311 type = [pb availableTypeFromArray: ns_drag_types];
5312 if (type == 0)
5313 {
5314 return NO;
5315 }
5316 else if ([type isEqualToString: NSFilenamesPboardType])
5317 {
5318 NSArray *files;
5319 NSEnumerator *fenum;
5320 NSString *file;
5321
5322 if (!(files = [pb propertyListForType: type]))
5323 return NO;
5324
5325 fenum = [files objectEnumerator];
5326 while ( (file = [fenum nextObject]) )
5327 {
5328 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5329 emacs_event->code = KEY_NS_DRAG_FILE;
5330 XSETINT (emacs_event->x, x);
5331 XSETINT (emacs_event->y, y);
5332 ns_input_file = append2 (ns_input_file,
5333 build_string ([file UTF8String]));
5334 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5335 EV_TRAILER (theEvent);
5336 }
5337 return YES;
5338 }
5339 else if ([type isEqualToString: NSURLPboardType])
5340 {
5341 NSString *file;
5342 NSURL *fileURL;
5343
5344 if (!(fileURL = [NSURL URLFromPasteboard: pb]) ||
5345 [fileURL isFileURL] == NO)
5346 return NO;
5347
5348 file = [fileURL path];
5349 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5350 emacs_event->code = KEY_NS_DRAG_FILE;
5351 XSETINT (emacs_event->x, x);
5352 XSETINT (emacs_event->y, y);
5353 ns_input_file = append2 (ns_input_file, build_string ([file UTF8String]));
5354 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5355 EV_TRAILER (theEvent);
5356 return YES;
5357 }
5358 else if ([type isEqualToString: NSStringPboardType]
5359 || [type isEqualToString: NSTabularTextPboardType])
5360 {
5361 NSString *data;
5362
5363 if (! (data = [pb stringForType: type]))
5364 return NO;
5365
5366 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5367 emacs_event->code = KEY_NS_DRAG_TEXT;
5368 XSETINT (emacs_event->x, x);
5369 XSETINT (emacs_event->y, y);
5370 ns_input_text = build_string ([data UTF8String]);
5371 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5372 EV_TRAILER (theEvent);
5373 return YES;
5374 }
5375 else if ([type isEqualToString: NSColorPboardType])
5376 {
5377 NSColor *c = [NSColor colorFromPasteboard: pb];
5378 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5379 emacs_event->code = KEY_NS_DRAG_COLOR;
5380 XSETINT (emacs_event->x, x);
5381 XSETINT (emacs_event->y, y);
5382 ns_input_color = ns_color_to_lisp (c);
5383 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5384 EV_TRAILER (theEvent);
5385 return YES;
5386 }
5387 else if ([type isEqualToString: NSFontPboardType])
5388 {
5389 /* impl based on GNUstep NSTextView.m */
5390 NSData *data = [pb dataForType: NSFontPboardType];
5391 NSDictionary *dict = [NSUnarchiver unarchiveObjectWithData: data];
5392 NSFont *font = [dict objectForKey: NSFontAttributeName];
5393 char fontSize[10];
5394
5395 if (font == nil)
5396 return NO;
5397
5398 emacs_event->kind = NON_ASCII_KEYSTROKE_EVENT;
5399 emacs_event->code = KEY_NS_CHANGE_FONT;
5400 XSETINT (emacs_event->x, x);
5401 XSETINT (emacs_event->y, y);
5402 ns_input_font = build_string ([[font fontName] UTF8String]);
5403 snprintf (fontSize, 10, "%f", [font pointSize]);
5404 ns_input_fontsize = build_string (fontSize);
5405 emacs_event->modifiers = EV_MODIFIERS (theEvent);
5406 EV_TRAILER (theEvent);
5407 return YES;
5408 }
5409 else
5410 {
5411 error ("Invalid data type in dragging pasteboard.");
5412 return NO;
5413 }
5414 }
5415
5416
5417 - validRequestorForSendType: (NSString *)typeSent
5418 returnType: (NSString *)typeReturned
5419 {
5420 NSTRACE (validRequestorForSendType);
5421 if ([ns_send_types indexOfObjectIdenticalTo: typeSent] != NSNotFound &&
5422 [ns_return_types indexOfObjectIdenticalTo: typeSent] != NSNotFound)
5423 return self;
5424
5425 return [super validRequestorForSendType: typeSent
5426 returnType: typeReturned];
5427 }
5428
5429
5430 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
5431 (gives a miniaturized version of the window); currently we use the latter for
5432 frames whose active buffer doesn't correspond to any file
5433 (e.g., '*scratch*') */
5434 - setMiniwindowImage: (BOOL) setMini
5435 {
5436 id image = [[self window] miniwindowImage];
5437 NSTRACE (setMiniwindowImage);
5438
5439 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
5440 about "AppleDockIconEnabled" notwithstanding, however the set message
5441 below has its effect nonetheless. */
5442 if (image != emacsframe->output_data.ns->miniimage)
5443 {
5444 if (image && [image isKindOfClass: [EmacsImage class]])
5445 [image release];
5446 [[self window] setMiniwindowImage:
5447 setMini ? emacsframe->output_data.ns->miniimage : nil];
5448 }
5449
5450 return self;
5451 }
5452
5453
5454 - (void) setRows: (int) r andColumns: (int) c
5455 {
5456 rows = r;
5457 cols = c;
5458 }
5459
5460 @end /* EmacsView */
5461
5462
5463
5464 /* ==========================================================================
5465
5466 EmacsWindow implementation
5467
5468 ========================================================================== */
5469
5470 @implementation EmacsWindow
5471
5472 /* called only on resize clicks by special case in EmacsApp-sendEvent */
5473 - (void)mouseDown: (NSEvent *)theEvent
5474 {
5475 if (ns_in_resize)
5476 {
5477 NSSize size = [[theEvent window] frame].size;
5478 grabOffset = [theEvent locationInWindow];
5479 grabOffset.x = size.width - grabOffset.x;
5480 }
5481 else
5482 [super mouseDown: theEvent];
5483 }
5484
5485
5486 /* stop resizing */
5487 - (void)mouseUp: (NSEvent *)theEvent
5488 {
5489 if (ns_in_resize)
5490 {
5491 struct frame *f = ((EmacsView *)[self delegate])->emacsframe;
5492 ns_in_resize = NO;
5493 ns_set_name_as_filename (f);
5494 [self display];
5495 ns_send_appdefined (-1);
5496 }
5497 else
5498 [super mouseUp: theEvent];
5499 }
5500
5501
5502 /* send resize events */
5503 - (void)mouseDragged: (NSEvent *)theEvent
5504 {
5505 if (ns_in_resize)
5506 {
5507 NSPoint p = [theEvent locationInWindow];
5508 NSSize size, vettedSize, origSize = [self frame].size;
5509
5510 size.width = p.x + grabOffset.x;
5511 size.height = origSize.height - p.y + grabOffset.y;
5512
5513 if (size.width == origSize.width && size.height == origSize.height)
5514 return;
5515
5516 vettedSize = [[self delegate] windowWillResize: self toSize: size];
5517 if (vettedSize.width != size.width || vettedSize.height != size.height)
5518 {
5519 [[NSNotificationCenter defaultCenter]
5520 postNotificationName: NSWindowDidResizeNotification
5521 object: self];
5522 }
5523 }
5524 else
5525 [super mouseDragged: theEvent];
5526 }
5527
5528 @end /* EmacsWindow */
5529
5530
5531 /* ==========================================================================
5532
5533 EmacsScroller implementation
5534
5535 ========================================================================== */
5536
5537
5538 @implementation EmacsScroller
5539
5540 /* for repeat button push */
5541 #define SCROLL_BAR_FIRST_DELAY 0.5
5542 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
5543
5544 + (float) scrollerWidth
5545 {
5546 /* TODO: if we want to allow variable widths, this is the place to do it,
5547 however neither GNUstep nor Cocoa support it very well */
5548 return [NSScroller scrollerWidth];
5549 }
5550
5551
5552 - initFrame: (NSRect )r window: (Lisp_Object)nwin
5553 {
5554 NSTRACE (EmacsScroller_initFrame);
5555
5556 r.size.width = [EmacsScroller scrollerWidth];
5557 [super initWithFrame: r/*NSMakeRect (0, 0, 0, 0)*/];
5558 [self setContinuous: YES];
5559 [self setEnabled: YES];
5560
5561 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
5562 locked against the right, top and bottom edges. */
5563 [self setAutoresizingMask: NSViewMinXMargin | NSViewHeightSizable];
5564
5565 win = nwin;
5566 condemned = NO;
5567 pixel_height = NSHeight (r);
5568 min_portion = 20 / pixel_height;
5569
5570 frame = XFRAME (XWINDOW (win)->frame);
5571 if (FRAME_LIVE_P (frame))
5572 {
5573 int i;
5574 EmacsView *view = FRAME_NS_VIEW (frame);
5575 NSView *sview = [[view window] contentView];
5576 NSArray *subs = [sview subviews];
5577
5578 /* disable optimization stopping redraw of other scrollbars */
5579 view->scrollbarsNeedingUpdate = 0;
5580 for (i =[subs count]-1; i >= 0; i--)
5581 if ([[subs objectAtIndex: i] isKindOfClass: [EmacsScroller class]])
5582 view->scrollbarsNeedingUpdate++;
5583 [sview addSubview: self];
5584 }
5585
5586 /* [self setFrame: r]; */
5587
5588 return self;
5589 }
5590
5591
5592 - (void)setFrame: (NSRect)newRect
5593 {
5594 NSTRACE (EmacsScroller_setFrame);
5595 /* BLOCK_INPUT; */
5596 pixel_height = NSHeight (newRect);
5597 min_portion = 20 / pixel_height;
5598 [super setFrame: newRect];
5599 [self display];
5600 /* UNBLOCK_INPUT; */
5601 }
5602
5603
5604 - (void)dealloc
5605 {
5606 NSTRACE (EmacsScroller_dealloc);
5607 if (!NILP (win))
5608 XWINDOW (win)->vertical_scroll_bar = Qnil;
5609 [super dealloc];
5610 }
5611
5612
5613 - condemn
5614 {
5615 NSTRACE (condemn);
5616 condemned =YES;
5617 return self;
5618 }
5619
5620
5621 - reprieve
5622 {
5623 NSTRACE (reprieve);
5624 condemned =NO;
5625 return self;
5626 }
5627
5628
5629 - judge
5630 {
5631 NSTRACE (judge);
5632 if (condemned)
5633 {
5634 BLOCK_INPUT;
5635 /* ensure other scrollbar updates after deletion */
5636 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
5637 if (view != nil)
5638 view->scrollbarsNeedingUpdate++;
5639 [self removeFromSuperview];
5640 [self release];
5641 UNBLOCK_INPUT;
5642 }
5643 return self;
5644 }
5645
5646
5647 - (void)resetCursorRects
5648 {
5649 NSRect visible = [self visibleRect];
5650 NSTRACE (resetCursorRects);
5651
5652 if (!NSIsEmptyRect (visible))
5653 [self addCursorRect: visible cursor: [NSCursor arrowCursor]];
5654 [[NSCursor arrowCursor] setOnMouseEntered: YES];
5655 }
5656
5657
5658 - (int) checkSamePosition: (int) position portion: (int) portion
5659 whole: (int) whole
5660 {
5661 return em_position ==position && em_portion ==portion && em_whole ==whole
5662 && portion != whole; /* needed for resize empty buf */
5663 }
5664
5665
5666 - setPosition: (int)position portion: (int)portion whole: (int)whole
5667 {
5668 NSTRACE (setPosition);
5669
5670 em_position = position;
5671 em_portion = portion;
5672 em_whole = whole;
5673
5674 if (portion >= whole)
5675 [self setFloatValue: 0.0 knobProportion: 1.0];
5676 else
5677 {
5678 float pos, por;
5679 portion = max ((float)whole*min_portion/pixel_height, portion);
5680 pos = (float)position / (whole - portion);
5681 por = (float)portion/whole;
5682 [self setFloatValue: pos knobProportion: por];
5683 }
5684 #ifdef NS_IMPL_GNUSTEP
5685 [self display];
5686 #endif
5687 return self;
5688 }
5689
5690 /* FIXME: unused at moment (see ns_mouse_position) at the moment because
5691 drag events will go directly to the EmacsScroller. Leaving in for now. */
5692 -(void)getMouseMotionPart: (int *)part window: (Lisp_Object *)window
5693 x: (Lisp_Object *)x y: ( Lisp_Object *)y
5694 {
5695 *part = last_hit_part;
5696 *window = win;
5697 XSETINT (*y, pixel_height);
5698 if ([self floatValue] > 0.999)
5699 XSETINT (*x, pixel_height);
5700 else
5701 XSETINT (*x, pixel_height * [self floatValue]);
5702 }
5703
5704
5705 /* set up emacs_event */
5706 - (void) sendScrollEventAtLoc: (float)loc fromEvent: (NSEvent *)e
5707 {
5708 if (!emacs_event)
5709 return;
5710
5711 emacs_event->part = last_hit_part;
5712 emacs_event->code = 0;
5713 emacs_event->modifiers = EV_MODIFIERS (e) | down_modifier;
5714 emacs_event->frame_or_window = win;
5715 emacs_event->timestamp = EV_TIMESTAMP (e);
5716 emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
5717 emacs_event->arg = Qnil;
5718 XSETINT (emacs_event->x, loc * pixel_height);
5719 XSETINT (emacs_event->y, pixel_height-20);
5720
5721 n_emacs_events_pending++;
5722 kbd_buffer_store_event_hold (emacs_event, q_event_ptr);
5723 EVENT_INIT (*emacs_event);
5724 ns_send_appdefined (-1);
5725 }
5726
5727
5728 /* called manually thru timer to implement repeated button action w/hold-down */
5729 - repeatScroll: (NSTimer *)scrollEntry
5730 {
5731 NSEvent *e = [[self window] currentEvent];
5732 NSPoint p = [[self window] mouseLocationOutsideOfEventStream];
5733 BOOL inKnob = [self testPart: p] == NSScrollerKnob;
5734
5735 /* clear timer if need be */
5736 if (inKnob || [scroll_repeat_entry timeInterval] == SCROLL_BAR_FIRST_DELAY)
5737 {
5738 [scroll_repeat_entry invalidate];
5739 [scroll_repeat_entry release];
5740 scroll_repeat_entry = nil;
5741
5742 if (inKnob)
5743 return self;
5744
5745 scroll_repeat_entry
5746 = [[NSTimer scheduledTimerWithTimeInterval:
5747 SCROLL_BAR_CONTINUOUS_DELAY
5748 target: self
5749 selector: @selector (repeatScroll:)
5750 userInfo: 0
5751 repeats: YES]
5752 retain];
5753 }
5754
5755 [self sendScrollEventAtLoc: 0 fromEvent: e];
5756 return self;
5757 }
5758
5759
5760 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
5761 mouseDragged events without going into a modal loop. */
5762 - (void)mouseDown: (NSEvent *)e
5763 {
5764 NSRect sr, kr;
5765 /* hitPart is only updated AFTER event is passed on */
5766 NSScrollerPart part = [self testPart: [e locationInWindow]];
5767 double inc = 0.0, loc, kloc, pos;
5768 int edge = 0;
5769
5770 NSTRACE (EmacsScroller_mouseDown);
5771
5772 switch (part)
5773 {
5774 case NSScrollerDecrementPage:
5775 last_hit_part = scroll_bar_above_handle; inc = -1.0; break;
5776 case NSScrollerIncrementPage:
5777 last_hit_part = scroll_bar_below_handle; inc = 1.0; break;
5778 case NSScrollerDecrementLine:
5779 last_hit_part = scroll_bar_up_arrow; inc = -0.1; break;
5780 case NSScrollerIncrementLine:
5781 last_hit_part = scroll_bar_down_arrow; inc = 0.1; break;
5782 case NSScrollerKnob:
5783 last_hit_part = scroll_bar_handle; break;
5784 case NSScrollerKnobSlot: /* GNUstep-only */
5785 last_hit_part = scroll_bar_move_ratio; break;
5786 default: /* NSScrollerNoPart? */
5787 fprintf (stderr, "EmacsScoller-mouseDown: unexpected part %d\n", part);
5788 return;
5789 }
5790
5791 if (inc != 0.0)
5792 {
5793 pos = 0; /* ignored */
5794
5795 /* set a timer to repeat, as we can't let superclass do this modally */
5796 scroll_repeat_entry
5797 = [[NSTimer scheduledTimerWithTimeInterval: 0.5
5798 target: self
5799 selector: @selector (repeatScroll:)
5800 userInfo: 0
5801 repeats: YES]
5802 retain];
5803 }
5804 else
5805 {
5806 /* handle, or on GNUstep possibly slot */
5807 NSEvent *fake_event;
5808
5809 /* compute float loc in slot and mouse offset on knob */
5810 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
5811 toView: nil];
5812 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
5813 if (loc <= 0.0)
5814 {
5815 loc = 0.0;
5816 edge = -1;
5817 }
5818 else if (loc >= NSHeight (sr))
5819 {
5820 loc = NSHeight (sr);
5821 edge = 1;
5822 }
5823
5824 if (edge)
5825 kloc = 0.5 * edge;
5826 else
5827 {
5828 kr = [self convertRect: [self rectForPart: NSScrollerKnob]
5829 toView: nil];
5830 kloc = NSHeight (kr) - ([e locationInWindow].y - NSMinY (kr));
5831 }
5832 last_mouse_offset = kloc;
5833
5834 /* if knob, tell emacs a location offset by knob pos
5835 (to indicate top of handle) */
5836 if (part == NSScrollerKnob)
5837 pos = (loc - last_mouse_offset) / NSHeight (sr);
5838 else
5839 /* else this is a slot click on GNUstep: go straight there */
5840 pos = loc / NSHeight (sr);
5841
5842 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
5843 fake_event = [NSEvent mouseEventWithType: NSLeftMouseUp
5844 location: [e locationInWindow]
5845 modifierFlags: [e modifierFlags]
5846 timestamp: [e timestamp]
5847 windowNumber: [e windowNumber]
5848 context: [e context]
5849 eventNumber: [e eventNumber]
5850 clickCount: [e clickCount]
5851 pressure: [e pressure]];
5852 [super mouseUp: fake_event];
5853 }
5854
5855 if (part != NSScrollerKnob)
5856 [self sendScrollEventAtLoc: pos fromEvent: e];
5857 }
5858
5859
5860 /* Called as we manually track scroller drags, rather than superclass. */
5861 - (void)mouseDragged: (NSEvent *)e
5862 {
5863 NSRect sr;
5864 double loc, pos;
5865 int edge = 0;
5866
5867 NSTRACE (EmacsScroller_mouseDragged);
5868
5869 sr = [self convertRect: [self rectForPart: NSScrollerKnobSlot]
5870 toView: nil];
5871 loc = NSHeight (sr) - ([e locationInWindow].y - NSMinY (sr));
5872
5873 if (loc <= 0.0)
5874 {
5875 loc = 0.0;
5876 edge = -1;
5877 }
5878 else if (loc >= NSHeight (sr) + last_mouse_offset)
5879 {
5880 loc = NSHeight (sr) + last_mouse_offset;
5881 edge = 1;
5882 }
5883
5884 pos = /*(edge ? loc :*/ (loc - last_mouse_offset) / NSHeight (sr);
5885 [self sendScrollEventAtLoc: pos fromEvent: e];
5886 }
5887
5888
5889 - (void)mouseUp: (NSEvent *)e
5890 {
5891 if (scroll_repeat_entry)
5892 {
5893 [scroll_repeat_entry invalidate];
5894 [scroll_repeat_entry release];
5895 scroll_repeat_entry = nil;
5896 }
5897 last_hit_part = 0;
5898 }
5899
5900
5901 /* treat scrollwheel events in the bar as though they were in the main window */
5902 - (void) scrollWheel: (NSEvent *)theEvent
5903 {
5904 EmacsView *view = (EmacsView *)FRAME_NS_VIEW (frame);
5905 [view mouseDown: theEvent];
5906 }
5907
5908 @end /* EmacsScroller */
5909
5910
5911
5912 /* ==========================================================================
5913
5914 EmacsPrefsController implementation
5915
5916 ========================================================================== */
5917
5918
5919 @implementation EmacsPrefsController
5920
5921 /* in Tiger+, can just do [popup selectItemWithTag: tag]; */
5922 static void selectItemWithTag (NSPopUpButton *popup, int tag)
5923 {
5924 NSEnumerator *items = [[popup itemArray] objectEnumerator];
5925 NSMenuItem *item;
5926 while (item = [items nextObject])
5927 {
5928 if ([item tag] == tag)
5929 {
5930 [popup selectItem: item];
5931 return;
5932 }
5933 }
5934 }
5935
5936 - init
5937 {
5938 [NSBundle loadNibNamed: @"preferences" owner: self];
5939 return self;
5940 }
5941
5942
5943 - (void) showForFrame: (struct frame *)f
5944 {
5945 frame = f;
5946 [self setPanelFromValues];
5947 [prefsWindow makeKeyAndOrderFront: self];
5948 [prefsWindow display];
5949 }
5950
5951
5952 - (void) setPanelFromValues
5953 {
5954 int cursorType
5955 = ns_lisp_to_cursor_type (get_frame_param (frame, Qcursor_type));
5956 prevExpandSpace = XFLOATINT (ns_expand_space);
5957
5958 #ifdef NS_IMPL_COCOA
5959 prevUseHighlightColor = ns_use_system_highlight_color;
5960 #endif
5961
5962 [expandSpaceSlider setFloatValue: prevExpandSpace];
5963 [cursorTypeMatrix selectCellWithTag: (cursorType == FILLED_BOX_CURSOR ? 1 :
5964 (cursorType == BAR_CURSOR ? 2 :
5965 (cursorType == HBAR_CURSOR ? 3 : 4)))];
5966 selectItemWithTag (alternateModMenu,
5967 parse_solitary_modifier (ns_alternate_modifier));
5968 selectItemWithTag (commandModMenu,
5969 parse_solitary_modifier (ns_command_modifier));
5970 #ifdef NS_IMPL_COCOA
5971 selectItemWithTag (controlModMenu,
5972 parse_solitary_modifier (ns_control_modifier));
5973 selectItemWithTag (functionModMenu,
5974 parse_solitary_modifier (ns_function_modifier));
5975 [smoothFontsCheck setState: (NILP (ns_antialias_text) ? NO : YES)];
5976 [useQuickdrawCheck setState: (NILP (ns_use_qd_smoothing) ? NO : YES)];
5977 [useSysHiliteCheck setState: (NILP (prevUseHighlightColor) ? NO : YES)];
5978 #endif
5979 }
5980
5981
5982 - (void) setValuesFromPanel
5983 {
5984 int altTag = [[alternateModMenu selectedItem] tag];
5985 int cmdTag = [[commandModMenu selectedItem] tag];
5986 #ifdef NS_IMPL_COCOA
5987 int ctrlTag = [[controlModMenu selectedItem] tag];
5988 int fnTag = [[functionModMenu selectedItem] tag];
5989 #endif
5990 float expandSpace = [expandSpaceSlider floatValue];
5991 int cursorTag = [[cursorTypeMatrix selectedCell] tag];
5992 Lisp_Object cursor_type = ns_cursor_type_to_lisp
5993 ( cursorTag == 1 ? FILLED_BOX_CURSOR
5994 : cursorTag == 2 ? BAR_CURSOR
5995 : cursorTag == 3 ? HBAR_CURSOR : HOLLOW_BOX_CURSOR);
5996
5997 if (expandSpace != prevExpandSpace)
5998 {
5999 ns_expand_space = make_float (expandSpace);
6000 /* TODO: more needed: store needed metrics in nsfont_info, update
6001 frame default font max_bounds and fontp, recompute faces */
6002 /* FRAME_LINE_HEIGHT (frame) *= (expandSpace / prevExpandSpace);
6003 x_set_window_size (frame, 0, frame->text_cols, frame->text_lines); */
6004 prevExpandSpace = expandSpace;
6005 }
6006
6007 store_frame_param (frame, Qcursor_type, cursor_type);
6008 ns_set_cursor_type(frame, cursor_type, Qnil); /* FIXME: do only if changed */
6009
6010 ns_alternate_modifier = ns_mod_to_lisp (altTag);
6011 ns_command_modifier = ns_mod_to_lisp (cmdTag);
6012 #ifdef NS_IMPL_COCOA
6013 ns_control_modifier = ns_mod_to_lisp (ctrlTag);
6014 ns_function_modifier = ns_mod_to_lisp (fnTag);
6015 ns_antialias_text = [smoothFontsCheck state] ? Qt : Qnil;
6016 ns_use_qd_smoothing = [useQuickdrawCheck state] ? Qt : Qnil;
6017 ns_use_system_highlight_color = [useSysHiliteCheck state] ? Qt : Qnil;
6018 if (! EQ (ns_use_system_highlight_color, prevUseHighlightColor))
6019 {
6020 prevUseHighlightColor = ns_use_system_highlight_color;
6021 if (EQ (ns_use_system_highlight_color, Qt))
6022 {
6023 ns_selection_color = [[NSUserDefaults standardUserDefaults]
6024 stringForKey: @"AppleHighlightColor"];
6025 if (ns_selection_color == nil)
6026 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
6027 }
6028 else
6029 ns_selection_color = NS_SELECTION_COLOR_DEFAULT;
6030 }
6031 #endif /* NS_IMPL_COCOA */
6032 Fcall_interactively (intern ("ns-save-preferences"), Qnil, Qnil);
6033 }
6034
6035
6036 /* buttons */
6037 - (IBAction)cancel: (id)sender
6038 {
6039 [prefsWindow close];
6040 }
6041
6042
6043 - (IBAction)ok: (id)sender
6044 {
6045 [self setValuesFromPanel];
6046 [prefsWindow close];
6047 }
6048
6049
6050 - (IBAction)resetToDefaults: (id)sender
6051 {
6052 ns_set_default_prefs ();
6053 [self setPanelFromValues];
6054 }
6055
6056
6057 - (IBAction)runHelp: (id)sender
6058 {
6059 Feval (Fcons (intern ("info"),
6060 Fcons (build_string ("(ns-emacs)Preferences Panel"), Qnil)));
6061 SET_FRAME_GARBAGED (frame);
6062 ns_send_appdefined (-1);
6063 }
6064
6065
6066 - (IBAction)setColors: (id)sender
6067 {
6068 Lisp_Object lispFrame;
6069 XSETFRAME (lispFrame, frame);
6070 Fns_popup_color_panel (lispFrame);
6071 }
6072
6073
6074 - (IBAction)setDefaultFont: (id)sender
6075 {
6076 Lisp_Object lispFrame;
6077 XSETFRAME (lispFrame, frame);
6078 Fns_popup_font_panel (lispFrame);
6079 }
6080
6081 @end /* EmacsPrefsController */
6082
6083
6084
6085
6086 /* ==========================================================================
6087
6088 Font-related functions; these used to be in nsfaces.m
6089 The XLFD functions (115 lines) are an abomination that should be removed.
6090
6091 ========================================================================== */
6092
6093
6094 Lisp_Object
6095 x_new_font (struct frame *f, Lisp_Object font_object, int fontset)
6096 {
6097 struct font *font = XFONT_OBJECT (font_object);
6098
6099 if (fontset < 0)
6100 fontset = fontset_from_font (font_object);
6101 FRAME_FONTSET (f) = fontset;
6102
6103 if (FRAME_FONT (f) == font)
6104 /* This font is already set in frame F. There's nothing more to
6105 do. */
6106 return font_object;
6107
6108 FRAME_FONT (f) = font;
6109
6110 FRAME_BASELINE_OFFSET (f) = font->baseline_offset;
6111 FRAME_COLUMN_WIDTH (f) = font->average_width;
6112 FRAME_SPACE_WIDTH (f) = font->space_width;
6113 FRAME_LINE_HEIGHT (f) = font->height;
6114
6115 compute_fringe_widths (f, 1);
6116
6117 /* Compute the scroll bar width in character columns. */
6118 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
6119 {
6120 int wid = FRAME_COLUMN_WIDTH (f);
6121 FRAME_CONFIG_SCROLL_BAR_COLS (f)
6122 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid - 1) / wid;
6123 }
6124 else
6125 {
6126 int wid = FRAME_COLUMN_WIDTH (f);
6127 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
6128 }
6129
6130 /* Now make the frame display the given font. */
6131 if (FRAME_NS_WINDOW (f) != 0)
6132 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
6133
6134 return font_object;
6135 }
6136
6137
6138 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
6139
6140 static const char *
6141 ns_font_to_xlfd (NSFont *nsfont)
6142 /* --------------------------------------------------------------------------
6143 Convert an NS font name to an X font name (XLFD).
6144 The string returned is temporarily allocated.
6145 -------------------------------------------------------------------------- */
6146 {
6147 NSFontManager *mgr = [NSFontManager sharedFontManager];
6148 NSString *sname = [nsfont /*familyName*/fontName];
6149 char *famName = (char *)[sname UTF8String];
6150 char *weightStr = [mgr fontNamed: sname hasTraits: NSBoldFontMask] ?
6151 "bold" : "medium";
6152 char *slantStr = [mgr fontNamed: sname hasTraits: NSItalicFontMask] ?
6153 "i" : "r";
6154 int size = [nsfont pointSize];
6155 int aWidth = lrint (10.0 * [nsfont widthOfString: @"a"]);
6156 const char *xlfd;
6157 int i, len;
6158
6159 /* change '-' to '$' to avoid messing w/XLFD separator */
6160 for (len = strlen (famName), i =0; i<len; i++)
6161 if (famName[i] == '-')
6162 {
6163 famName[i] = '\0';
6164 break;
6165 }
6166
6167 xlfd = [[NSString stringWithFormat:
6168 @"-apple-%s-%s-%s-normal--%d-%d-75-75-m-%d-iso10646-1",
6169 famName, weightStr, slantStr, size, 10*size, aWidth]
6170 UTF8String];
6171 /*fprintf (stderr, "converted '%s' to '%s'\n",name,xlfd); */
6172 return xlfd;
6173 }
6174
6175 static const char *
6176 ns_fontname_to_xlfd (const char *name)
6177 /* --------------------------------------------------------------------------
6178 Convert an NS font name to an X font name (XLFD).
6179 Sizes are set to 0.
6180 The string returned is temporarily allocated.
6181 -------------------------------------------------------------------------- */
6182 {
6183 char famName[180];
6184 char *weightStr = strcasestr (name, "bold") ? "bold" : "medium";
6185 char *slantStr = strcasestr (name, "italic") || strcasestr (name, "oblique")
6186 || strcasestr (name, "synthital") ? "i" : "r";
6187 int i, len;
6188 const char *xlfd;
6189
6190 /* change '-' to '$' to avoid messing w/XLFD separator, and ' ' to '_' */
6191 bzero (famName, 180);
6192 bcopy (name, famName, max (strlen (name), 179));
6193 for (len =strlen (famName), i =0; i<len; i++)
6194 {
6195 if (famName[i] == '-')
6196 famName[i] = '$';
6197 else if (famName[i] == ' ')
6198 famName[i] = '_';
6199 }
6200
6201 xlfd = [[NSString stringWithFormat:
6202 @"-apple-%s-%s-%s-normal--0-0-75-75-m-0-iso10646-1",
6203 famName, weightStr, slantStr]
6204 UTF8String];
6205 /*fprintf (stderr, "converted '%s' to '%s'\n",name,xlfd); */
6206 return xlfd;
6207 }
6208
6209
6210 const char *
6211 ns_xlfd_to_fontname (const char *xlfd)
6212 /* --------------------------------------------------------------------------
6213 Convert an X font name (XLFD) to an NS font name.
6214 Only family is used.
6215 The string returned is temporarily allocated.
6216 -------------------------------------------------------------------------- */
6217 {
6218 char *name = xmalloc (180);
6219 int i, len;
6220 const char *ret;
6221
6222 if (!strncmp (xlfd, "--", 2))
6223 sscanf (xlfd, "--%*[^-]-%[^-]179-", name);
6224 else
6225 sscanf (xlfd, "-%*[^-]-%[^-]179-", name);
6226
6227 /* stopgap for malformed XLFD input */
6228 if (strlen (name) == 0)
6229 strcpy (name, "Monaco");
6230
6231 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
6232 also uppercase after '-' or ' ' */
6233 name[0] = toupper (name[0]);
6234 for (len =strlen (name), i =0; i<len; i++)
6235 {
6236 if (name[i] == '$')
6237 {
6238 name[i] = '-';
6239 if (i+1<len)
6240 name[i+1] = toupper (name[i+1]);
6241 }
6242 else if (name[i] == '_')
6243 {
6244 name[i] = ' ';
6245 if (i+1<len)
6246 name[i+1] = toupper (name[i+1]);
6247 }
6248 }
6249 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
6250 ret = [[NSString stringWithUTF8String: name] UTF8String];
6251 xfree (name);
6252 return ret;
6253 }
6254
6255
6256 void
6257 syms_of_nsterm ()
6258 {
6259 NSTRACE (syms_of_nsterm);
6260 DEFVAR_LISP ("ns-input-file", &ns_input_file,
6261 "The file specified in the last NS event.");
6262 ns_input_file =Qnil;
6263
6264 DEFVAR_LISP ("ns-input-text", &ns_input_text,
6265 "The data received in the last NS text drag event.");
6266 ns_input_text =Qnil;
6267
6268 DEFVAR_LISP ("ns-working-text", &ns_working_text,
6269 "String for visualizing working composition sequence.");
6270 ns_working_text =Qnil;
6271
6272 DEFVAR_LISP ("ns-input-font", &ns_input_font,
6273 "The font specified in the last NS event.");
6274 ns_input_font =Qnil;
6275
6276 DEFVAR_LISP ("ns-input-fontsize", &ns_input_fontsize,
6277 "The fontsize specified in the last NS event.");
6278 ns_input_fontsize =Qnil;
6279
6280 DEFVAR_LISP ("ns-input-line", &ns_input_line,
6281 "The line specified in the last NS event.");
6282 ns_input_line =Qnil;
6283
6284 DEFVAR_LISP ("ns-input-color", &ns_input_color,
6285 "The color specified in the last NS event.");
6286 ns_input_color =Qnil;
6287
6288 DEFVAR_LISP ("ns-input-spi-name", &ns_input_spi_name,
6289 "The service name specified in the last NS event.");
6290 ns_input_spi_name =Qnil;
6291
6292 DEFVAR_LISP ("ns-input-spi-arg", &ns_input_spi_arg,
6293 "The service argument specified in the last NS event.");
6294 ns_input_spi_arg =Qnil;
6295
6296 DEFVAR_LISP ("ns-alternate-modifier", &ns_alternate_modifier,
6297 "This variable describes the behavior of the alternate or option key.\n\
6298 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6299 Set to none means that the alternate / option key is not interpreted by Emacs\n\
6300 at all, allowing it to be used at a lower level for accented character entry.");
6301
6302 DEFVAR_LISP ("ns-command-modifier", &ns_command_modifier,
6303 "This variable describes the behavior of the command key.\n\
6304 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6305
6306 DEFVAR_LISP ("ns-control-modifier", &ns_control_modifier,
6307 "This variable describes the behavior of the control key.\n\
6308 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
6309
6310 DEFVAR_LISP ("ns-function-modifier", &ns_function_modifier,
6311 "This variable describes the behavior of the function key (on laptops).\n\
6312 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
6313 Set to none means that the function key is not interpreted by Emacs at all,\n\
6314 allowing it to be used at a lower level for accented character entry.");
6315
6316 DEFVAR_LISP ("ns-expand-space", &ns_expand_space,
6317 "Amount by which spacing between lines is expanded (positive)\n\
6318 or shrunk (negative). Zero (the default) means standard line height.\n\
6319 (This variable should only be read, never set.)");
6320
6321 DEFVAR_LISP ("ns-antialias-text", &ns_antialias_text,
6322 "Non-nil (the default) means to render text antialiased. Only has an effect on OS X Panther and above.");
6323
6324 DEFVAR_LISP ("ns-use-qd-smoothing", &ns_use_qd_smoothing,
6325 "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).");
6326
6327 DEFVAR_LISP ("ns-use-system-highlight-color",
6328 &ns_use_system_highlight_color,
6329 "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'.");
6330
6331 staticpro (&ns_display_name_list);
6332 ns_display_name_list = Qnil;
6333
6334 staticpro (&last_mouse_motion_frame);
6335 last_mouse_motion_frame = Qnil;
6336
6337 /*23: now apparently we need to tell emacs what modifiers there are.. */
6338 Qmodifier_value = intern ("modifier-value");
6339 Qalt = intern ("alt");
6340 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
6341 Qhyper = intern ("hyper");
6342 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
6343 Qmeta = intern ("meta");
6344 Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
6345 Qsuper = intern ("super");
6346 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
6347 Qcontrol = intern ("control");
6348 Fput (Qcontrol, Qmodifier_value, make_number (ctrl_modifier));
6349
6350 /* TODO: move to common code */
6351 DEFVAR_LISP ("x-toolkit-scroll-bars", &Vx_toolkit_scroll_bars,
6352 doc: /* If not nil, Emacs uses toolkit scroll bars. */);
6353 #ifdef USE_TOOLKIT_SCROLL_BARS
6354 Vx_toolkit_scroll_bars = Qt;
6355 #else
6356 Vx_toolkit_scroll_bars = Qnil;
6357 #endif
6358
6359 /* these are unsupported but we need the declarations to avoid whining
6360 messages from cus-start.el */
6361 DEFVAR_BOOL ("x-use-underline-position-properties",
6362 &x_use_underline_position_properties,
6363 doc: /* NOT SUPPORTED UNDER NS.
6364 *Non-nil means make use of UNDERLINE_POSITION font properties.
6365 A value of nil means ignore them. If you encounter fonts with bogus
6366 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
6367 to 4.1, set this to nil.
6368
6369 NOTE: Not supported on Mac yet. */);
6370 x_use_underline_position_properties = 0;
6371
6372 DEFVAR_BOOL ("x-underline-at-descent-line",
6373 &x_underline_at_descent_line,
6374 doc: /* NOT SUPPORTED UNDER NS.
6375 *Non-nil means to draw the underline at the same place as the descent line.
6376 A value of nil means to draw the underline according to the value of the
6377 variable `x-use-underline-position-properties', which is usually at the
6378 baseline level. The default value is nil. */);
6379 x_underline_at_descent_line = 0;
6380
6381 /* Tell emacs about this window system. */
6382 Fprovide (intern ("ns"), Qnil);
6383 }
6384
6385
6386 // arch-tag: 6eaa8f7d-a69b-4e1c-b43d-ab31defbe0d2