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