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