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