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