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