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