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