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