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