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