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