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