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