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