1 /* NeXT/Open/GNUstep / MacOSX communication module.
3 Copyright (C) 1989, 1993-1994, 2005-2006, 2008-2013 Free Software
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 Originally by Carl Edman
23 Updated by Christian Limpach (chris@nice.ch)
24 OpenStep/Rhapsody port by Scott Bender (sbender@harmony-ds.com)
25 MacOSX/Aqua port by Christophe de Dinechin (descubes@earthlink.net)
26 GNUstep port and post-20 update by Adrian Robert (arobert@cogsci.ucsd.edu)
29 /* This should be the first include, as it may set up #defines affecting
30 interpretation of even the system includes. */
36 #include
<sys
/types.h
>
42 #include
<c
-strcase.h
>
46 #include "blockinput.h"
47 #include "sysselect.h"
50 #include "character.h"
52 #include "composite.h"
55 #include "termhooks.h"
63 #ifdef NS_IMPL_GNUSTEP
68 #
if MAC_OS_X_VERSION_MAX_ALLOWED
>= MAC_OS_X_VERSION_10_5
75 int term_trace_num
= 0;
76 #define NSTRACE
(x
) fprintf (stderr
, "
%s:%d: [%d] " #x "\n", \
77 __FILE__
, __LINE__
, ++term_trace_num
)
82 extern NSString
*NSMenuDidBeginTrackingNotification
;
84 /* ==========================================================================
88 ========================================================================== */
90 /* Convert a symbol indexed with an NSxxx value to a value as defined
91 in keyboard.c (lispy_function_key). I hope this is a correct way
93 static unsigned convert_ns_to_X_keysym
[] =
95 NSHomeFunctionKey
, 0x50,
96 NSLeftArrowFunctionKey
, 0x51,
97 NSUpArrowFunctionKey
, 0x52,
98 NSRightArrowFunctionKey
, 0x53,
99 NSDownArrowFunctionKey
, 0x54,
100 NSPageUpFunctionKey
, 0x55,
101 NSPageDownFunctionKey
, 0x56,
102 NSEndFunctionKey
, 0x57,
103 NSBeginFunctionKey
, 0x58,
104 NSSelectFunctionKey
, 0x60,
105 NSPrintFunctionKey
, 0x61,
106 NSClearLineFunctionKey
, 0x0B,
107 NSExecuteFunctionKey
, 0x62,
108 NSInsertFunctionKey
, 0x63,
109 NSUndoFunctionKey
, 0x65,
110 NSRedoFunctionKey
, 0x66,
111 NSMenuFunctionKey
, 0x67,
112 NSFindFunctionKey
, 0x68,
113 NSHelpFunctionKey
, 0x6A,
114 NSBreakFunctionKey
, 0x6B,
116 NSF1FunctionKey
, 0xBE,
117 NSF2FunctionKey
, 0xBF,
118 NSF3FunctionKey
, 0xC0,
119 NSF4FunctionKey
, 0xC1,
120 NSF5FunctionKey
, 0xC2,
121 NSF6FunctionKey
, 0xC3,
122 NSF7FunctionKey
, 0xC4,
123 NSF8FunctionKey
, 0xC5,
124 NSF9FunctionKey
, 0xC6,
125 NSF10FunctionKey
, 0xC7,
126 NSF11FunctionKey
, 0xC8,
127 NSF12FunctionKey
, 0xC9,
128 NSF13FunctionKey
, 0xCA,
129 NSF14FunctionKey
, 0xCB,
130 NSF15FunctionKey
, 0xCC,
131 NSF16FunctionKey
, 0xCD,
132 NSF17FunctionKey
, 0xCE,
133 NSF18FunctionKey
, 0xCF,
134 NSF19FunctionKey
, 0xD0,
135 NSF20FunctionKey
, 0xD1,
136 NSF21FunctionKey
, 0xD2,
137 NSF22FunctionKey
, 0xD3,
138 NSF23FunctionKey
, 0xD4,
139 NSF24FunctionKey
, 0xD5,
141 NSBackspaceCharacter
, 0x08, /* 8: Not on some KBs. */
142 NSDeleteCharacter
, 0xFF, /* 127: Big 'delete' key upper right. */
143 NSDeleteFunctionKey
, 0x9F, /* 63272: Del forw key off main array. */
145 NSTabCharacter
, 0x09,
146 0x19, 0x09, /* left tab->regular since pass shift */
147 NSCarriageReturnCharacter
, 0x0D,
148 NSNewlineCharacter
, 0x0D,
149 NSEnterCharacter
, 0x8D,
151 0x41|NSNumericPadKeyMask
, 0xAE, /* KP_Decimal */
152 0x43|NSNumericPadKeyMask
, 0xAA, /* KP_Multiply */
153 0x45|NSNumericPadKeyMask
, 0xAB, /* KP_Add */
154 0x4B|NSNumericPadKeyMask
, 0xAF, /* KP_Divide */
155 0x4E|NSNumericPadKeyMask
, 0xAD, /* KP_Subtract */
156 0x51|NSNumericPadKeyMask
, 0xBD, /* KP_Equal */
157 0x52|NSNumericPadKeyMask
, 0xB0, /* KP_0 */
158 0x53|NSNumericPadKeyMask
, 0xB1, /* KP_1 */
159 0x54|NSNumericPadKeyMask
, 0xB2, /* KP_2 */
160 0x55|NSNumericPadKeyMask
, 0xB3, /* KP_3 */
161 0x56|NSNumericPadKeyMask
, 0xB4, /* KP_4 */
162 0x57|NSNumericPadKeyMask
, 0xB5, /* KP_5 */
163 0x58|NSNumericPadKeyMask
, 0xB6, /* KP_6 */
164 0x59|NSNumericPadKeyMask
, 0xB7, /* KP_7 */
165 0x5B|NSNumericPadKeyMask
, 0xB8, /* KP_8 */
166 0x5C|NSNumericPadKeyMask
, 0xB9, /* KP_9 */
168 0x1B, 0x1B /* escape */
171 static Lisp_Object Qmodifier_value
;
172 Lisp_Object Qalt
, Qcontrol
, Qhyper
, Qmeta
, Qsuper
;
173 extern Lisp_Object Qcursor_color
, Qcursor_type
, Qns
, Qleft
;
175 static Lisp_Object QUTF8_STRING
;
177 /* On OS X picks up the default NSGlobalDomain AppleAntiAliasingThreshold,
178 the maximum font size to NOT antialias. On GNUstep there is currently
179 no way to control this behavior. */
180 float ns_antialias_threshold
;
182 NSArray
*ns_send_types
=0, *ns_return_types
=0, *ns_drag_types
=0;
183 NSString
*ns_app_name
= @"Emacs"
; /* default changed later */
185 /* Display variables */
186 struct ns_display_info
*x_display_list
; /* Chain of existing displays */
187 Lisp_Object ns_display_name_list
;
188 long context_menu_value
= 0;
191 static
struct frame
*ns_updating_frame
;
192 static NSView
*focus_view
= NULL;
193 static int ns_window_num
= 0;
194 #ifdef NS_IMPL_GNUSTEP
197 static BOOL gsaved
= NO
;
198 static BOOL ns_fake_keydown
= NO
;
200 static BOOL ns_menu_bar_is_hidden
= NO
;
202 /*static int debug_lock = 0; */
205 static BOOL send_appdefined
= YES
;
206 #define NO_APPDEFINED_DATA
(-8)
207 static int last_appdefined_event_data
= NO_APPDEFINED_DATA
;
208 static NSTimer
*timed_entry
= 0;
209 static NSTimer
*scroll_repeat_entry
= nil
;
210 static fd_set select_readfds
, select_writefds
;
211 enum
{ SELECT_HAVE_READ
= 1, SELECT_HAVE_WRITE
= 2, SELECT_HAVE_TMO
= 4 };
212 static int select_nfds
= 0, select_valid
= 0;
213 static
struct timespec select_timeout
= { 0, 0 };
214 static int selfds
[2] = { -1, -1 };
215 static pthread_mutex_t select_mutex
;
216 static int apploopnr
= 0;
217 static NSAutoreleasePool
*outerpool
;
218 static
struct input_event
*emacs_event
= NULL;
219 static
struct input_event
*q_event_ptr
= NULL;
220 static int n_emacs_events_pending
= 0;
221 static NSMutableArray
*ns_pending_files
, *ns_pending_service_names
,
222 *ns_pending_service_args
;
223 static BOOL ns_do_open_file
= NO
;
224 static BOOL ns_last_use_native_fullscreen
;
227 struct input_event
*q
;
235 * State for pending menu activation:
236 * MENU_NONE Normal state
237 * MENU_PENDING A menu has been clicked on, but has been canceled so we can
238 * run lisp to update the menu.
239 * MENU_OPENING Menu is up to date, and the click event is redone so the menu
243 #define MENU_PENDING
1
244 #define MENU_OPENING
2
245 static int menu_will_open_state
= MENU_NONE
;
247 /* Saved position for menu click. */
248 static CGPoint menu_mouse_point
;
251 /* Convert modifiers in a NeXTstep event to emacs style modifiers. */
252 #define NS_FUNCTION_KEY_MASK
0x800000
253 #define NSLeftControlKeyMask
(0x000001 | NSControlKeyMask
)
254 #define NSRightControlKeyMask
(0x002000 | NSControlKeyMask
)
255 #define NSLeftCommandKeyMask
(0x000008 | NSCommandKeyMask
)
256 #define NSRightCommandKeyMask
(0x000010 | NSCommandKeyMask
)
257 #define NSLeftAlternateKeyMask
(0x000020 | NSAlternateKeyMask
)
258 #define NSRightAlternateKeyMask
(0x000040 | NSAlternateKeyMask
)
259 #define EV_MODIFIERS
(e
) \
260 ((([e modifierFlags
] & NSHelpKeyMask
) ? \
261 hyper_modifier
: 0) \
262 |
(!EQ
(ns_right_alternate_modifier
, Qleft
) && \
263 (([e modifierFlags
] & NSRightAlternateKeyMask
) \
264 == NSRightAlternateKeyMask
) ? \
265 parse_solitary_modifier
(ns_right_alternate_modifier
) : 0) \
266 |
(([e modifierFlags
] & NSAlternateKeyMask
) ? \
267 parse_solitary_modifier
(ns_alternate_modifier
) : 0) \
268 |
(([e modifierFlags
] & NSShiftKeyMask
) ? \
269 shift_modifier
: 0) \
270 |
(!EQ
(ns_right_control_modifier
, Qleft
) && \
271 (([e modifierFlags
] & NSRightControlKeyMask
) \
272 == NSRightControlKeyMask
) ? \
273 parse_solitary_modifier
(ns_right_control_modifier
) : 0) \
274 |
(([e modifierFlags
] & NSControlKeyMask
) ? \
275 parse_solitary_modifier
(ns_control_modifier
) : 0) \
276 |
(([e modifierFlags
] & NS_FUNCTION_KEY_MASK
) ? \
277 parse_solitary_modifier
(ns_function_modifier
) : 0) \
278 |
(!EQ
(ns_right_command_modifier
, Qleft
) && \
279 (([e modifierFlags
] & NSRightCommandKeyMask
) \
280 == NSRightCommandKeyMask
) ? \
281 parse_solitary_modifier
(ns_right_command_modifier
) : 0) \
282 |
(([e modifierFlags
] & NSCommandKeyMask
) ? \
283 parse_solitary_modifier
(ns_command_modifier
):0))
285 #define EV_UDMODIFIERS
(e
) \
286 ((([e
type] == NSLeftMouseDown
) ? down_modifier
: 0) \
287 |
(([e
type] == NSRightMouseDown
) ? down_modifier
: 0) \
288 |
(([e
type] == NSOtherMouseDown
) ? down_modifier
: 0) \
289 |
(([e
type] == NSLeftMouseDragged
) ? down_modifier
: 0) \
290 |
(([e
type] == NSRightMouseDragged
) ? down_modifier
: 0) \
291 |
(([e
type] == NSOtherMouseDragged
) ? down_modifier
: 0) \
292 |
(([e
type] == NSLeftMouseUp
) ? up_modifier
: 0) \
293 |
(([e
type] == NSRightMouseUp
) ? up_modifier
: 0) \
294 |
(([e
type] == NSOtherMouseUp
) ? up_modifier
: 0))
296 #define EV_BUTTON
(e
) \
297 ((([e
type] == NSLeftMouseDown
) ||
([e
type] == NSLeftMouseUp
)) ?
0 : \
298 (([e
type] == NSRightMouseDown
) ||
([e
type] == NSRightMouseUp
)) ?
2 : \
299 [e buttonNumber
] - 1)
301 /* Convert the time field to a timestamp in milliseconds. */
302 #define EV_TIMESTAMP
(e
) ([e timestamp
] * 1000)
304 /* This is a piece of code which is common to all the event handling
305 methods. Maybe it should even be a function. */
306 #define EV_TRAILER
(e
) \
308 XSETFRAME
(emacs_event
->frame_or_window
, emacsframe
); \
312 #define EV_TRAILER2
(e
) \
314 if (e
) emacs_event
->timestamp
= EV_TIMESTAMP
(e
); \
317 n_emacs_events_pending
++; \
318 kbd_buffer_store_event_hold
(emacs_event
, q_event_ptr
); \
321 hold_event
(emacs_event
); \
322 EVENT_INIT
(*emacs_event
); \
323 ns_send_appdefined
(-1); \
326 /* TODO: get rid of need for these forward declarations */
327 static void ns_condemn_scroll_bars
(struct frame
*f
);
328 static void ns_judge_scroll_bars
(struct frame
*f
);
329 void x_set_frame_alpha
(struct frame
*f
);
332 /* ==========================================================================
336 ========================================================================== */
339 hold_event
(struct input_event
*event
)
341 if (hold_event_q.nr
== hold_event_q.cap
)
343 if (hold_event_q.cap
== 0) hold_event_q.cap
= 10;
344 else hold_event_q.cap
*= 2;
346 xrealloc
(hold_event_q.q
, hold_event_q.cap
* sizeof
*hold_event_q.q
);
349 hold_event_q.q
[hold_event_q.nr
++] = *event
;
350 /* Make sure ns_read_socket is called, i.e. we have input. */
352 send_appdefined
= YES
;
356 append2
(Lisp_Object list
, Lisp_Object item
)
357 /* --------------------------------------------------------------------------
358 Utility to append to a list
359 -------------------------------------------------------------------------- */
361 Lisp_Object array
[2];
363 array
[1] = list1
(item
);
364 return Fnconc
(2, &array
[0]);
369 ns_etc_directory
(void
)
370 /* If running as a self-contained app bundle, return as a string the
371 filename of the etc directory, if present; else nil. */
373 NSBundle
*bundle
= [NSBundle mainBundle
];
374 NSString
*resourceDir
= [bundle resourcePath
];
375 NSString
*resourcePath
;
376 NSFileManager
*fileManager
= [NSFileManager defaultManager
];
379 resourcePath
= [resourceDir stringByAppendingPathComponent
: @"etc"
];
380 if ([fileManager fileExistsAtPath
: resourcePath isDirectory
: &isDir
])
382 if (isDir
) return [resourcePath UTF8String
];
390 /* If running as a self-contained app bundle, return as a path string
391 the filenames of the libexec and bin directories, ie libexec:bin.
392 Otherwise, return nil.
393 Normally, Emacs does not add its own bin/ directory to the PATH.
394 However, a self-contained NS build has a different layout, with
395 bin/ and libexec/ subdirectories in the directory that contains
397 We put libexec first, because init_callproc_1 uses the first
398 element to initialize exec-directory. An alternative would be
399 for init_callproc to check for invocation-directory/libexec.
402 NSBundle
*bundle
= [NSBundle mainBundle
];
403 NSString
*resourceDir
= [bundle resourcePath
];
404 NSString
*binDir
= [bundle bundlePath
];
405 NSString
*resourcePath
, *resourcePaths
;
407 NSString
*pathSeparator
= [NSString stringWithFormat
: @"
%c", SEPCHAR];
408 NSFileManager
*fileManager
= [NSFileManager defaultManager
];
410 NSEnumerator
*pathEnum
;
413 range
= [resourceDir rangeOfString
: @"Contents"
];
414 if (range.location
!= NSNotFound
)
416 binDir
= [binDir stringByAppendingPathComponent
: @"Contents"
];
418 binDir
= [binDir stringByAppendingPathComponent
: @"MacOS"
];
422 paths
= [binDir stringsByAppendingPaths
:
423 [NSArray arrayWithObjects
: @"libexec"
, @"bin"
, nil
]];
424 pathEnum
= [paths objectEnumerator
];
427 while ((resourcePath
= [pathEnum nextObject
]))
429 if ([fileManager fileExistsAtPath
: resourcePath isDirectory
: &isDir
])
432 if ([resourcePaths
length] > 0)
434 = [resourcePaths stringByAppendingString
: pathSeparator
];
436 = [resourcePaths stringByAppendingString
: resourcePath
];
439 if ([resourcePaths
length] > 0) return [resourcePaths UTF8String
];
447 /* If running as a self-contained app bundle, return as a path string
448 the filenames of the site-lisp, lisp and leim directories.
449 Ie, site-lisp:lisp:leim. Otherwise, return nil. */
451 NSBundle
*bundle
= [NSBundle mainBundle
];
452 NSString
*resourceDir
= [bundle resourcePath
];
453 NSString
*resourcePath
, *resourcePaths
;
454 NSString
*pathSeparator
= [NSString stringWithFormat
: @"
%c", SEPCHAR];
455 NSFileManager
*fileManager
= [NSFileManager defaultManager
];
457 NSArray
*paths
= [resourceDir stringsByAppendingPaths
:
458 [NSArray arrayWithObjects
:
459 @"site
-lisp"
, @"lisp"
, @"leim"
, nil
]];
460 NSEnumerator
*pathEnum
= [paths objectEnumerator
];
463 /* Hack to skip site-lisp. */
464 if (no_site_lisp
) resourcePath
= [pathEnum nextObject
];
466 while ((resourcePath
= [pathEnum nextObject
]))
468 if ([fileManager fileExistsAtPath
: resourcePath isDirectory
: &isDir
])
471 if ([resourcePaths
length] > 0)
473 = [resourcePaths stringByAppendingString
: pathSeparator
];
475 = [resourcePaths stringByAppendingString
: resourcePath
];
478 if ([resourcePaths
length] > 0) return [resourcePaths UTF8String
];
484 ns_timeout
(int usecs
)
485 /* --------------------------------------------------------------------------
486 Blocking timer utility used by ns_ring_bell
487 -------------------------------------------------------------------------- */
489 struct timespec wakeup
= timespec_add
(current_timespec
(),
490 make_timespec
(0, usecs
* 1000));
492 /* Keep waiting until past the time wakeup. */
495 struct timespec timeout
, now
= current_timespec
();
496 if (timespec_cmp
(wakeup
, now
) <= 0)
498 timeout
= timespec_sub
(wakeup
, now
);
500 /* Try to wait that long--but we might wake up sooner. */
501 pselect
(0, NULL, NULL, NULL, &timeout
, NULL);
507 ns_release_object
(void
*obj
)
508 /* --------------------------------------------------------------------------
509 Release an object (callable from C)
510 -------------------------------------------------------------------------- */
517 ns_retain_object
(void
*obj
)
518 /* --------------------------------------------------------------------------
519 Retain an object (callable from C)
520 -------------------------------------------------------------------------- */
527 ns_alloc_autorelease_pool
(void
)
528 /* --------------------------------------------------------------------------
529 Allocate a pool for temporary objects (callable from C)
530 -------------------------------------------------------------------------- */
532 return [[NSAutoreleasePool alloc
] init
];
537 ns_release_autorelease_pool
(void
*pool
)
538 /* --------------------------------------------------------------------------
539 Free a pool and temporary objects it refers to (callable from C)
540 -------------------------------------------------------------------------- */
542 ns_release_object
(pool
);
547 /* ==========================================================================
549 Focus (clipping) and screen update
551 ========================================================================== */
554 // Window constraining
555 // -------------------
557 // To ensure that the windows are not placed under the
menu bar, they
558 // are typically moved by the call
-back constrainFrameRect. However
,
559 // by overriding it
, it
's possible to inhibit this, leaving the window
560 // in it's original position.
562 // It
's possible to hide the menu bar. However, technically, it's only
563 // possible to hide it when the application is active. To ensure that
564 // this work properly
, the
menu bar and window constraining are
565 // deferred until the application becomes active.
567 // Even though it
's not possible to manually move a window above the
568 // top of the screen, it is allowed if it's done programmatically
,
569 // when the
menu is
hidden. This allows the editable area to cover the
570 // full screen height.
575 // Use the following extra files
:
578 // ;; Hide
menu and place frame slightly above the top of the screen.
579 // (setq ns
-auto
-hide
-menu-bar t
)
580 // (set-frame
-position
(selected
-frame
) 0 -20)
584 // emacs
-Q
-l init.el
586 // Result
: No
menu bar, and the
title bar should be above the screen.
592 // Result
: Menu bar visible
, frame placed immediately below the
menu.
596 ns_constrain_all_frames
(void
)
598 Lisp_Object tail
, frame
;
600 FOR_EACH_FRAME
(tail
, frame
)
602 struct frame
*f
= XFRAME
(frame
);
605 NSView
*view = FRAME_NS_VIEW
(f
);
606 /* This no-op will trigger the default window placing
607 * constraint system. */
608 f
->output_data.ns
->dont_constrain
= 0;
609 [[view window
] setFrameOrigin
:[[view window
] frame
].origin
];
615 /* True, if the menu bar should be hidden. */
618 ns_menu_bar_should_be_hidden
(void
)
620 return !NILP
(ns_auto_hide_menu_bar
)
621 && [NSApp respondsToSelector
:@selector
(setPresentationOptions
:)];
625 /* Show or hide the menu bar, based on user setting. */
628 ns_update_auto_hide_menu_bar
(void
)
631 #
if MAC_OS_X_VERSION_MAX_ALLOWED
>= MAC_OS_X_VERSION_10_6
634 NSTRACE
(ns_update_auto_hide_menu_bar
);
636 if (NSApp
!= nil
&& [NSApp isActive
])
638 // Note
, "setPresentationOptions" triggers an
error unless the
639 // application is active.
640 BOOL menu_bar_should_be_hidden
= ns_menu_bar_should_be_hidden
();
642 if (menu_bar_should_be_hidden
!= ns_menu_bar_is_hidden
)
644 NSApplicationPresentationOptions options
645 = NSApplicationPresentationDefault
;
647 if (menu_bar_should_be_hidden
)
648 options |
= NSApplicationPresentationAutoHideMenuBar
649 | NSApplicationPresentationAutoHideDock
;
651 [NSApp setPresentationOptions
: options
];
653 ns_menu_bar_is_hidden
= menu_bar_should_be_hidden
;
655 if (!ns_menu_bar_is_hidden
)
657 ns_constrain_all_frames
();
669 ns_update_begin
(struct frame
*f
)
670 /* --------------------------------------------------------------------------
671 Prepare for a grouped sequence of drawing calls
672 external (RIF) call; whole frame, called before update_window_begin
673 -------------------------------------------------------------------------- */
675 EmacsView
*view = FRAME_NS_VIEW
(f
);
676 NSTRACE
(ns_update_begin
);
678 ns_update_auto_hide_menu_bar
();
681 if ([view isFullscreen
] && [view fsIsNative
])
683 // Fix reappearing tool
bar in fullscreen
for OSX
10.7
684 BOOL tbar_visible
= FRAME_EXTERNAL_TOOL_BAR
(f
) ? YES
: NO
;
685 NSToolbar
*toolbar
= [FRAME_NS_VIEW
(f
) toolbar
];
686 if (! tbar_visible
!= ! [toolbar isVisible
])
687 [toolbar setVisible
: tbar_visible
];
691 ns_updating_frame
= f
;
694 /* drawRect may have been called for say the minibuffer, and then clip path
695 is for the minibuffer. But the display engine may draw more because
696 we have set the frame as garbaged. So reset clip path to the whole
701 NSRect r
= [view frame
];
702 NSRect cr
= [[view window
] frame
];
703 /* If a large frame size is set, r may be larger than the window frame
704 before constrained. In that case don't change the clip path, as we
705 will clear in to the tool bar and title bar. */
707 + FRAME_NS_TITLEBAR_HEIGHT
(f
)
708 + FRAME_TOOLBAR_HEIGHT
(f
) <= cr.
size.height
)
710 bp
= [[NSBezierPath bezierPathWithRect
: r
] retain
];
717 #ifdef NS_IMPL_GNUSTEP
718 uRect
= NSMakeRect
(0, 0, 0, 0);
724 ns_update_window_begin
(struct window
*w
)
725 /* --------------------------------------------------------------------------
726 Prepare for a grouped sequence of drawing calls
727 external (RIF) call; for one window, called after update_begin
728 -------------------------------------------------------------------------- */
730 struct frame
*f
= XFRAME
(WINDOW_FRAME
(w
));
731 Mouse_HLInfo
*hlinfo
= MOUSE_HL_INFO
(f
);
733 NSTRACE
(ns_update_window_begin
);
734 w
->output_cursor
= w
->cursor
;
738 if (f
== hlinfo
->mouse_face_mouse_frame
)
740 /* Don't do highlighting for mouse motion during the update. */
741 hlinfo
->mouse_face_defer
= 1;
743 /* If the frame needs to be redrawn,
744 simply forget about any prior mouse highlighting. */
745 if (FRAME_GARBAGED_P
(f
))
746 hlinfo
->mouse_face_window
= Qnil
;
748 /* (further code for mouse faces ifdef'd out in other terms elided) */
756 ns_update_window_end
(struct window
*w
, bool cursor_on_p
,
757 bool mouse_face_overwritten_p
)
758 /* --------------------------------------------------------------------------
759 Finished a grouped sequence of drawing calls
760 external (RIF) call; for one window called before update_end
761 -------------------------------------------------------------------------- */
763 /* note: this fn is nearly identical in all terms */
764 if (!w
->pseudo_window_p
)
769 display_and_set_cursor
(w
, 1,
770 w
->output_cursor.hpos
, w
->output_cursor.vpos
,
771 w
->output_cursor.x
, w
->output_cursor.y
);
773 if (draw_window_fringes
(w
, 1))
774 x_draw_vertical_border
(w
);
779 /* If a row with mouse-face was overwritten, arrange for
780 frame_up_to_date to redisplay the mouse highlight. */
781 if (mouse_face_overwritten_p
)
782 reset_mouse_highlight
(MOUSE_HL_INFO
(XFRAME
(w
->frame
)));
784 NSTRACE
(update_window_end
);
789 ns_update_end
(struct frame
*f
)
790 /* --------------------------------------------------------------------------
791 Finished a grouped sequence of drawing calls
792 external (RIF) call; for whole frame, called after update_window_end
793 -------------------------------------------------------------------------- */
795 EmacsView
*view = FRAME_NS_VIEW
(f
);
797 /* if (f == MOUSE_HL_INFO (f)->mouse_face_mouse_frame) */
798 MOUSE_HL_INFO
(f
)->mouse_face_defer
= 0;
803 [[view window
] flushWindow
];
806 ns_updating_frame
= NULL;
807 NSTRACE
(ns_update_end
);
811 ns_focus
(struct frame
*f
, NSRect
*r
, int n
)
812 /* --------------------------------------------------------------------------
813 Internal: Focus on given frame. During small local updates this is used to
814 draw, however during large updates, ns_update_begin and ns_update_end are
815 called to wrap the whole thing, in which case these calls are stubbed out.
816 Except, on GNUstep, we accumulate the rectangle being drawn into, because
817 the back end won't do this automatically, and will just end up flushing
819 -------------------------------------------------------------------------- */
821 // NSTRACE
(ns_focus
);
823 fprintf (stderr, "focus: %d", c++);
824 if (r) fprintf (stderr, " (%.0f, %.0f : %.0f x %.0f)", r->origin.x, r->origin.y, r->size.width, r->size.height);
825 fprintf (stderr, "\n"); */
827 if (f
!= ns_updating_frame
)
829 NSView
*view = FRAME_NS_VIEW
(f
);
830 if (view != focus_view
)
832 if (focus_view
!= NULL)
834 [focus_view unlockFocus
];
835 [[focus_view window
] flushWindow
];
842 /*if (view) debug_lock++; */
849 [[NSGraphicsContext currentContext
] saveGraphicsState
];
851 NSRectClipList
(r
, 2);
860 ns_unfocus
(struct frame
*f
)
861 /* --------------------------------------------------------------------------
862 Internal: Remove focus on given frame
863 -------------------------------------------------------------------------- */
865 // NSTRACE
(ns_unfocus
);
869 [[NSGraphicsContext currentContext
] restoreGraphicsState
];
873 if (f
!= ns_updating_frame
)
875 if (focus_view
!= NULL)
877 [focus_view unlockFocus
];
878 [[focus_view window
] flushWindow
];
887 ns_clip_to_row
(struct window
*w
, struct glyph_row
*row
,
888 enum glyph_row_area area
, BOOL gc
)
889 /* --------------------------------------------------------------------------
890 Internal (but parallels other terms): Focus drawing on given row
891 -------------------------------------------------------------------------- */
893 struct frame
*f
= XFRAME
(WINDOW_FRAME
(w
));
895 int window_x
, window_y
, window_width
;
897 window_box
(w
, area
, &window_x
, &window_y
, &window_width
, 0);
899 clip_rect.origin.x
= window_x
;
900 clip_rect.origin.y
= WINDOW_TO_FRAME_PIXEL_Y
(w
, max (0, row
->y
));
901 clip_rect.origin.y
= max (clip_rect.origin.y
, window_y
);
902 clip_rect.
size.width
= window_width
;
903 clip_rect.
size.height
= row
->visible_height
;
905 ns_focus
(f
, &clip_rect
, 1);
910 ns_ring_bell
(struct frame
*f
)
911 /* --------------------------------------------------------------------------
913 -------------------------------------------------------------------------- */
915 NSTRACE
(ns_ring_bell
);
918 NSAutoreleasePool
*pool
;
919 struct frame
*frame
= SELECTED_FRAME
();
923 pool
= [[NSAutoreleasePool alloc
] init
];
925 view = FRAME_NS_VIEW
(frame
);
929 NSPoint dim
= NSMakePoint
(128, 128);
932 r.origin.x
+= (r.
size.width
- dim.x
) / 2;
933 r.origin.y
+= (r.
size.height
- dim.y
) / 2;
934 r.
size.width
= dim.x
;
935 r.
size.height
= dim.y
;
936 surr
= NSInsetRect
(r
, -2, -2);
937 ns_focus
(frame
, &surr
, 1);
938 [[view window
] cacheImageInRect
: [view convertRect
: surr toView
:nil
]];
939 [ns_lookup_indexed_color
(NS_FACE_FOREGROUND
940 (FRAME_DEFAULT_FACE
(frame
)), frame
) set];
942 [[view window
] flushWindow
];
944 [[view window
] restoreCachedImage
];
945 [[view window
] flushWindow
];
957 /* ==========================================================================
959 Frame / window manager related functions
961 ========================================================================== */
965 ns_raise_frame
(struct frame
*f
)
966 /* --------------------------------------------------------------------------
967 Bring window to foreground and make it active
968 -------------------------------------------------------------------------- */
971 check_window_system
(f
);
972 view = FRAME_NS_VIEW
(f
);
974 if (FRAME_VISIBLE_P
(f
))
975 [[view window
] makeKeyAndOrderFront
: NSApp
];
981 ns_lower_frame
(struct frame
*f
)
982 /* --------------------------------------------------------------------------
984 -------------------------------------------------------------------------- */
987 check_window_system
(f
);
988 view = FRAME_NS_VIEW
(f
);
990 [[view window
] orderBack
: NSApp
];
996 ns_frame_raise_lower
(struct frame
*f
, int raise
)
997 /* --------------------------------------------------------------------------
999 -------------------------------------------------------------------------- */
1001 NSTRACE
(ns_frame_raise_lower
);
1011 ns_frame_rehighlight
(struct frame
*frame
)
1012 /* --------------------------------------------------------------------------
1013 External (hook): called on things like window switching within frame
1014 -------------------------------------------------------------------------- */
1016 struct ns_display_info
*dpyinfo
= FRAME_DISPLAY_INFO
(frame
);
1017 struct frame
*old_highlight
= dpyinfo
->x_highlight_frame
;
1019 NSTRACE
(ns_frame_rehighlight
);
1020 if (dpyinfo
->x_focus_frame
)
1022 dpyinfo
->x_highlight_frame
1023 = (FRAMEP
(FRAME_FOCUS_FRAME
(dpyinfo
->x_focus_frame
))
1024 ? XFRAME
(FRAME_FOCUS_FRAME
(dpyinfo
->x_focus_frame
))
1025 : dpyinfo
->x_focus_frame
);
1026 if (!FRAME_LIVE_P
(dpyinfo
->x_highlight_frame
))
1028 fset_focus_frame
(dpyinfo
->x_focus_frame
, Qnil
);
1029 dpyinfo
->x_highlight_frame
= dpyinfo
->x_focus_frame
;
1033 dpyinfo
->x_highlight_frame
= 0;
1035 if (dpyinfo
->x_highlight_frame
&&
1036 dpyinfo
->x_highlight_frame
!= old_highlight
)
1040 x_update_cursor
(old_highlight
, 1);
1041 x_set_frame_alpha
(old_highlight
);
1043 if (dpyinfo
->x_highlight_frame
)
1045 x_update_cursor
(dpyinfo
->x_highlight_frame
, 1);
1046 x_set_frame_alpha
(dpyinfo
->x_highlight_frame
);
1053 x_make_frame_visible
(struct frame
*f
)
1054 /* --------------------------------------------------------------------------
1055 External: Show the window (X11 semantics)
1056 -------------------------------------------------------------------------- */
1058 NSTRACE
(x_make_frame_visible
);
1059 /* XXX: at some points in past this was not needed, as the only place that
1060 called this (frame.c:Fraise_frame ()) also called raise_lower;
1061 if this ends up the case again, comment this out again. */
1062 if (!FRAME_VISIBLE_P
(f
))
1064 EmacsView
*view = (EmacsView
*)FRAME_NS_VIEW
(f
);
1066 SET_FRAME_VISIBLE
(f
, 1);
1069 /* Making a new frame from a fullscreen frame will make the new frame
1070 fullscreen also. So skip handleFS as this will print an error. */
1071 if ([view fsIsNative
] && f
->want_fullscreen
== FULLSCREEN_BOTH
1072 && [view isFullscreen
])
1075 if (f
->want_fullscreen
!= FULLSCREEN_NONE
)
1086 x_make_frame_invisible
(struct frame
*f
)
1087 /* --------------------------------------------------------------------------
1088 External: Hide the window (X11 semantics)
1089 -------------------------------------------------------------------------- */
1092 NSTRACE
(x_make_frame_invisible
);
1093 check_window_system
(f
);
1094 view = FRAME_NS_VIEW
(f
);
1095 [[view window
] orderOut
: NSApp
];
1096 SET_FRAME_VISIBLE
(f
, 0);
1097 SET_FRAME_ICONIFIED
(f
, 0);
1102 x_iconify_frame
(struct frame
*f
)
1103 /* --------------------------------------------------------------------------
1104 External: Iconify window
1105 -------------------------------------------------------------------------- */
1108 struct ns_display_info
*dpyinfo
;
1110 NSTRACE
(x_iconify_frame
);
1111 check_window_system
(f
);
1112 view = FRAME_NS_VIEW
(f
);
1113 dpyinfo
= FRAME_DISPLAY_INFO
(f
);
1115 if (dpyinfo
->x_highlight_frame
== f
)
1116 dpyinfo
->x_highlight_frame
= 0;
1118 if ([[view window
] windowNumber
] <= 0)
1120 /* the window is still deferred. Make it very small, bring it
1121 on screen and order it out. */
1122 NSRect s
= { { 100, 100}, {0, 0} };
1124 t
= [[view window
] frame
];
1125 [[view window
] setFrame
: s display
: NO
];
1126 [[view window
] orderBack
: NSApp
];
1127 [[view window
] orderOut
: NSApp
];
1128 [[view window
] setFrame
: t display
: NO
];
1130 [[view window
] miniaturize
: NSApp
];
1133 /* Free X resources of frame F. */
1136 x_free_frame_resources
(struct frame
*f
)
1139 struct ns_display_info
*dpyinfo
;
1140 Mouse_HLInfo
*hlinfo
;
1142 NSTRACE
(x_free_frame_resources
);
1143 check_window_system
(f
);
1144 view = FRAME_NS_VIEW
(f
);
1145 dpyinfo
= FRAME_DISPLAY_INFO
(f
);
1146 hlinfo
= MOUSE_HL_INFO
(f
);
1148 [(EmacsView
*)view setWindowClosing
: YES
]; /* may not have been informed */
1152 free_frame_menubar
(f
);
1154 if (FRAME_FACE_CACHE
(f
))
1155 free_frame_faces
(f
);
1157 if (f
== dpyinfo
->x_focus_frame
)
1158 dpyinfo
->x_focus_frame
= 0;
1159 if (f
== dpyinfo
->x_highlight_frame
)
1160 dpyinfo
->x_highlight_frame
= 0;
1161 if (f
== hlinfo
->mouse_face_mouse_frame
)
1162 reset_mouse_highlight
(hlinfo
);
1164 if (f
->output_data.ns
->miniimage
!= nil
)
1165 [f
->output_data.ns
->miniimage release
];
1167 [[view window
] close];
1170 xfree
(f
->output_data.ns
);
1176 x_destroy_window
(struct frame
*f
)
1177 /* --------------------------------------------------------------------------
1178 External: Delete the window
1179 -------------------------------------------------------------------------- */
1181 NSTRACE
(x_destroy_window
);
1182 check_window_system
(f
);
1183 x_free_frame_resources
(f
);
1189 x_set_offset
(struct frame
*f
, int xoff
, int yoff
, int change_grav
)
1190 /* --------------------------------------------------------------------------
1191 External: Position the window
1192 -------------------------------------------------------------------------- */
1194 NSView
*view = FRAME_NS_VIEW
(f
);
1195 NSArray
*screens
= [NSScreen screens
];
1196 NSScreen
*fscreen
= [screens objectAtIndex
: 0];
1197 NSScreen
*screen
= [[view window
] screen
];
1199 NSTRACE
(x_set_offset
);
1206 if (view != nil
&& screen
&& fscreen
)
1208 f
->left_pos
= f
->size_hint_flags
& XNegative
1209 ?
[screen visibleFrame
].
size.width
+ f
->left_pos
- FRAME_PIXEL_WIDTH
(f
)
1211 /* We use visibleFrame here to take menu bar into account.
1212 Ideally we should also adjust left/top with visibleFrame.origin. */
1214 f
->top_pos
= f
->size_hint_flags
& YNegative
1215 ?
([screen visibleFrame
].
size.height
+ f
->top_pos
1216 - FRAME_PIXEL_HEIGHT
(f
) - FRAME_NS_TITLEBAR_HEIGHT
(f
)
1217 - FRAME_TOOLBAR_HEIGHT
(f
))
1219 #ifdef NS_IMPL_GNUSTEP
1220 if (f
->left_pos
< 100)
1221 f
->left_pos
= 100; /* don't overlap menu */
1223 /* Constrain the setFrameTopLeftPoint so we don't move behind the
1225 f
->output_data.ns
->dont_constrain
= 0;
1226 [[view window
] setFrameTopLeftPoint
:
1227 NSMakePoint
(SCREENMAXBOUND
(f
->left_pos
),
1228 SCREENMAXBOUND
([fscreen frame
].
size.height
1229 - NS_TOP_POS
(f
)))];
1230 f
->size_hint_flags
&= ~
(XNegative|YNegative
);
1238 x_set_window_size
(struct frame
*f
, int change_grav
, int cols
, int rows
)
1239 /* --------------------------------------------------------------------------
1240 Adjust window pixel size based on given character grid size
1241 Impl is a bit more complex than other terms, need to do some
1243 -------------------------------------------------------------------------- */
1245 EmacsView
*view = FRAME_NS_VIEW
(f
);
1246 NSWindow
*window
= [view window
];
1247 NSRect wr
= [window frame
];
1248 int tb
= FRAME_EXTERNAL_TOOL_BAR
(f
);
1249 int pixelwidth
, pixelheight
;
1251 NSTRACE
(x_set_window_size
);
1256 /*fprintf (stderr, "\tsetWindowSize: %d x %d, font size %d x %d\n", cols, rows, FRAME_COLUMN_WIDTH (f), FRAME_LINE_HEIGHT (f)); */
1260 check_frame_size
(f
, &rows
, &cols
);
1262 f
->scroll_bar_actual_width
= NS_SCROLL_BAR_WIDTH
(f
);
1263 compute_fringe_widths
(f
, 0);
1265 pixelwidth
= FRAME_TEXT_COLS_TO_PIXEL_WIDTH
(f
, cols
);
1266 pixelheight
= FRAME_TEXT_LINES_TO_PIXEL_HEIGHT
(f
, rows
);
1268 /* If we have a toolbar, take its height into account. */
1269 if (tb
&& ! [view isFullscreen
])
1271 /* NOTE: previously this would generate wrong result if toolbar not
1272 yet displayed and fixing toolbar_height=32 helped, but
1273 now (200903) seems no longer needed */
1274 FRAME_TOOLBAR_HEIGHT
(f
) =
1275 NSHeight
([window frameRectForContentRect
: NSMakeRect
(0, 0, 0, 0)])
1276 - FRAME_NS_TITLEBAR_HEIGHT
(f
);
1277 #ifdef NS_IMPL_GNUSTEP
1278 FRAME_TOOLBAR_HEIGHT
(f
) -= 3;
1282 FRAME_TOOLBAR_HEIGHT
(f
) = 0;
1284 wr.
size.width
= pixelwidth
+ f
->border_width
;
1285 wr.
size.height
= pixelheight
;
1286 if (! [view isFullscreen
])
1287 wr.
size.height
+= FRAME_NS_TITLEBAR_HEIGHT
(f
)
1288 + FRAME_TOOLBAR_HEIGHT
(f
);
1290 /* Do not try to constrain to this screen. We may have multiple
1291 screens, and want Emacs to span those. Constraining to screen
1292 prevents that, and that is not nice to the user. */
1293 if (f
->output_data.ns
->zooming
)
1294 f
->output_data.ns
->zooming
= 0;
1296 wr.origin.y
+= FRAME_PIXEL_HEIGHT
(f
) - pixelheight
;
1298 [view setRows
: rows andColumns
: cols
];
1299 [window setFrame
: wr display
: YES
];
1301 /*fprintf (stderr, "\tx_set_window_size %d, %d\t%d, %d\n", cols, rows, pixelwidth, pixelheight); */
1303 /* This is a trick to compensate for Emacs' managing the scrollbar area
1304 as a fixed number of standard character columns. Instead of leaving
1305 blank space for the extra, we chopped it off above. Now for
1306 left-hand scrollbars, we shift all rendering to the left by the
1307 difference between the real width and Emacs' imagined one. For
1308 right-hand bars, don't worry about it since the extra is never used.
1309 (Obviously doesn't work for vertically split windows tho..) */
1311 NSPoint origin
= FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT
(f
)
1312 ? NSMakePoint
(FRAME_SCROLL_BAR_COLS
(f
) * FRAME_COLUMN_WIDTH
(f
)
1313 - NS_SCROLL_BAR_WIDTH
(f
), 0)
1314 : NSMakePoint
(0, 0);
1315 [view setFrame
: NSMakeRect
(0, 0, pixelwidth
, pixelheight
)];
1316 [view setBoundsOrigin
: origin
];
1319 change_frame_size
(f
, rows
, cols
, 0, 1, 0); /* pretend, delay, safe */
1320 FRAME_PIXEL_WIDTH
(f
) = pixelwidth
;
1321 FRAME_PIXEL_HEIGHT
(f
) = pixelheight
;
1322 /* SET_FRAME_GARBAGED (f); // this short-circuits expose call in drawRect */
1324 mark_window_cursors_off
(XWINDOW
(f
->root_window
));
1325 cancel_mouse_face
(f
);
1332 ns_fullscreen_hook
(struct frame
*f
)
1334 EmacsView
*view = (EmacsView
*)FRAME_NS_VIEW
(f
);
1336 if (!FRAME_VISIBLE_P
(f
))
1339 if (! [view fsIsNative
] && f
->want_fullscreen
== FULLSCREEN_BOTH
)
1341 /* Old style fs don't initiate correctly if created from
1342 init/default-frame alist, so use a timer (not nice...).
1344 [NSTimer scheduledTimerWithTimeInterval
: 0.5 target
: view
1345 selector
: @selector
(handleFS
)
1346 userInfo
: nil repeats
: NO
];
1355 /* ==========================================================================
1359 ========================================================================== */
1363 ns_lookup_indexed_color
(unsigned
long idx
, struct frame
*f
)
1365 struct ns_color_table
*color_table
= FRAME_DISPLAY_INFO
(f
)->color_table
;
1366 if (idx
< 1 || idx
>= color_table
->avail
)
1368 return color_table
->colors
[idx
];
1373 ns_index_color
(NSColor
*color
, struct frame
*f
)
1375 struct ns_color_table
*color_table
= FRAME_DISPLAY_INFO
(f
)->color_table
;
1379 if (!color_table
->colors
)
1381 color_table
->size = NS_COLOR_CAPACITY
;
1382 color_table
->avail
= 1; /* skip idx=0 as marker */
1383 color_table
->colors
= xmalloc
(color_table
->size * sizeof
(NSColor
*));
1384 color_table
->colors
[0] = nil
;
1385 color_table
->empty_indices
= [[NSMutableSet alloc
] init
];
1388 /* do we already have this color ? */
1389 for (i
= 1; i
< color_table
->avail
; i
++)
1390 if (color_table
->colors
[i
] && [color_table
->colors
[i
] isEqual: color
])
1393 if ([color_table
->empty_indices count
] > 0)
1395 NSNumber
*index
= [color_table
->empty_indices anyObject
];
1396 [color_table
->empty_indices removeObject
: index
];
1397 idx
= [index unsignedLongValue
];
1401 if (color_table
->avail
== color_table
->size)
1402 color_table
->colors
=
1403 xpalloc
(color_table
->colors
, &color_table
->size, 1,
1404 min (ULONG_MAX
, PTRDIFF_MAX
), sizeof
*color_table
->colors
);
1405 idx
= color_table
->avail
++;
1408 color_table
->colors
[idx
] = color
;
1410 /*fprintf(stderr, "color_table: allocated %d\n",idx);*/
1416 ns_free_indexed_color
(unsigned
long idx
, struct frame
*f
)
1418 struct ns_color_table
*color_table
;
1425 color_table
= FRAME_DISPLAY_INFO
(f
)->color_table
;
1427 if (idx
<= 0 || idx
>= color_table
->size) {
1428 message1
("ns_free_indexed_color
: Color index out of range.
\n"
);
1432 index
= [NSNumber numberWithUnsignedInt
: idx
];
1433 if ([color_table
->empty_indices containsObject
: index
]) {
1434 message1
("ns_free_indexed_color
: attempt to free already freed color.
\n"
);
1438 color
= color_table
->colors
[idx
];
1440 color_table
->colors
[idx
] = nil
;
1441 [color_table
->empty_indices addObject
: index
];
1442 /*fprintf(stderr, "color_table: FREED %d\n",idx);*/
1447 ns_get_color
(const
char *name
, NSColor
**col
)
1448 /* --------------------------------------------------------------------------
1450 -------------------------------------------------------------------------- */
1451 /* On *Step, we attempt to mimic the X11 platform here, down to installing an
1452 X11 rgb.txt-compatible color list in Emacs.clr (see ns_term_init()).
1453 See: http://thread.gmane.org/gmane.emacs.devel/113050/focus=113272). */
1456 static
char hex
[20];
1458 float r
= -1.0, g
, b
;
1459 NSString
*nsname
= [NSString stringWithUTF8String
: name
];
1461 /*fprintf (stderr, "ns_get_color: '%s'\n", name); */
1464 #ifdef NS_IMPL_COCOA
1465 if ([nsname isEqualToString
: @"ns_selection_bg_color"
])
1467 NSString
*defname
= [[NSUserDefaults standardUserDefaults
]
1468 stringForKey
: @"AppleHighlightColor"
];
1472 else if ((new
= [NSColor selectedTextBackgroundColor
]) != nil
)
1474 *col
= [new colorUsingColorSpaceName
: NSCalibratedRGBColorSpace
];
1479 nsname
= NS_SELECTION_BG_COLOR_DEFAULT
;
1481 name
= [nsname UTF8String
];
1483 else if ([nsname isEqualToString
: @"ns_selection_fg_color"
])
1485 /* NOTE: OSX applications normally don't set foreground selection, but
1486 text may be unreadable if we don't.
1488 if ((new
= [NSColor selectedTextColor
]) != nil
)
1490 *col
= [new colorUsingColorSpaceName
: NSCalibratedRGBColorSpace
];
1495 nsname
= NS_SELECTION_FG_COLOR_DEFAULT
;
1496 name
= [nsname UTF8String
];
1498 #endif
// NS_IMPL_COCOA
1500 /* First, check for some sort of numeric specification. */
1503 if (name
[0] == '0' || name
[0] == '1' || name
[0] == '.') /* RGB decimal */
1505 NSScanner
*scanner
= [NSScanner scannerWithString
: nsname
];
1506 [scanner scanFloat
: &r
];
1507 [scanner scanFloat
: &g
];
1508 [scanner scanFloat
: &b
];
1510 else if (!strncmp
(name
, "rgb
:"
, 4)) /* A newer X11 format -- rgb:r/g/b */
1511 scaling
= (snprintf
(hex
, sizeof hex
, "
%s", name + 4) - 2) / 3;
1512 else if (name
[0] == '#') /* An old X11 format; convert to newer */
1514 int len
= (strlen
(name
) - 1);
1515 int start
= (len
% 3 == 0) ? 1 : len / 4 + 1;
1517 scaling
= strlen
(name
+start
) / 3;
1518 for (i
= 0; i
< 3; i
++)
1519 sprintf (hex
+ i
* (scaling
+ 1), "
%.*s/", scaling,
1520 name
+ start
+ i
* scaling
);
1521 hex
[3 * (scaling
+ 1) - 1] = '\0';
1527 float fscale
= scaling
== 4 ?
65535.0 : (scaling
== 2 ?
255.0 : 15.0);
1528 if (sscanf (hex
, "
%x/%x/%x", &rr, &gg, &bb))
1538 *col
= [NSColor colorWithCalibratedRed
: r green
: g blue
: b alpha
: 1.0];
1543 /* Otherwise, color is expected to be from a list */
1545 NSEnumerator
*lenum
, *cenum
;
1549 #ifdef NS_IMPL_GNUSTEP
1550 /* XXX: who is wrong, the requestor or the implementation? */
1551 if ([nsname compare
: @"Highlight" options
: NSCaseInsensitiveSearch
]
1553 nsname
= @"highlightColor"
;
1556 lenum
= [[NSColorList availableColorLists
] objectEnumerator
];
1557 while ( (clist
= [lenum nextObject
]) && new
== nil
)
1559 cenum
= [[clist allKeys
] objectEnumerator
];
1560 while ( (name
= [cenum nextObject
]) && new
== nil
)
1562 if ([name compare
: nsname
1563 options
: NSCaseInsensitiveSearch
] == NSOrderedSame
)
1564 new
= [clist colorWithKey
: name
];
1570 *col
= [new colorUsingColorSpaceName
: NSCalibratedRGBColorSpace
];
1577 ns_lisp_to_color
(Lisp_Object color
, NSColor
**col
)
1578 /* --------------------------------------------------------------------------
1579 Convert a Lisp string object to a NS color
1580 -------------------------------------------------------------------------- */
1582 NSTRACE
(ns_lisp_to_color
);
1583 if (STRINGP
(color
))
1584 return ns_get_color
(SSDATA
(color
), col
);
1585 else if (SYMBOLP
(color
))
1586 return ns_get_color
(SSDATA
(SYMBOL_NAME
(color
)), col
);
1592 ns_color_to_lisp
(NSColor
*col
)
1593 /* --------------------------------------------------------------------------
1594 Convert a color to a lisp string with the RGB equivalent
1595 -------------------------------------------------------------------------- */
1597 EmacsCGFloat red
, green
, blue
, alpha
, gray;
1600 NSTRACE
(ns_color_to_lisp
);
1603 if ([[col colorSpaceName
] isEqualToString
: NSNamedColorSpace
])
1605 if ((str
=[[col colorNameComponent
] UTF8String
]))
1608 return build_string
((char *)str
);
1611 [[col colorUsingColorSpaceName
: NSCalibratedRGBColorSpace
]
1612 getRed
: &red green
: &green blue
: &blue alpha
: &alpha
];
1613 if (red
==green
&& red
==blue
)
1615 [[col colorUsingColorSpaceName
: NSCalibratedWhiteColorSpace
]
1616 getWhite
: &gray alpha
: &alpha
];
1617 snprintf
(buf
, sizeof
(buf
), "#
%2.2lx%2.2lx%2.2lx",
1618 lrint
(gray * 0xff), lrint
(gray * 0xff), lrint
(gray * 0xff));
1620 return build_string
(buf
);
1623 snprintf
(buf
, sizeof
(buf
), "#
%2.2lx%2.2lx%2.2lx",
1624 lrint
(red
*0xff), lrint
(green
*0xff), lrint
(blue
*0xff));
1627 return build_string
(buf
);
1632 ns_query_color
(void
*col
, XColor
*color_def
, int setPixel
)
1633 /* --------------------------------------------------------------------------
1634 Get ARGB values out of NSColor col and put them into color_def.
1635 If setPixel, set the pixel to a concatenated version.
1636 and set color_def pixel to the resulting index.
1637 -------------------------------------------------------------------------- */
1639 EmacsCGFloat r
, g
, b
, a
;
1641 [((NSColor
*)col
) getRed
: &r green
: &g blue
: &b alpha
: &a
];
1642 color_def
->red
= r
* 65535;
1643 color_def
->green
= g
* 65535;
1644 color_def
->blue
= b
* 65535;
1646 if (setPixel
== YES
)
1648 = ARGB_TO_ULONG
((int
)(a
*255),
1649 (int
)(r
*255), (int
)(g
*255), (int
)(b
*255));
1654 ns_defined_color
(struct frame
*f
,
1659 /* --------------------------------------------------------------------------
1660 Return true if named color found, and set color_def rgb accordingly.
1661 If makeIndex and alloc are nonzero put the color in the color_table,
1662 and set color_def pixel to the resulting index.
1663 If makeIndex is zero, set color_def pixel to ARGB.
1664 Return false if not found
1665 -------------------------------------------------------------------------- */
1668 NSTRACE
(ns_defined_color
);
1671 if (ns_get_color
(name
, &col
) != 0) /* Color not found */
1676 if (makeIndex
&& alloc
)
1677 color_def
->pixel
= ns_index_color
(col
, f
);
1678 ns_query_color
(col
, color_def
, !makeIndex
);
1685 x_set_frame_alpha
(struct frame
*f
)
1686 /* --------------------------------------------------------------------------
1687 change the entire-frame transparency
1688 -------------------------------------------------------------------------- */
1690 struct ns_display_info
*dpyinfo
= FRAME_DISPLAY_INFO
(f
);
1692 double alpha_min
= 1.0;
1694 if (dpyinfo
->x_highlight_frame
== f
)
1695 alpha
= f
->alpha
[0];
1697 alpha
= f
->alpha
[1];
1699 if (FLOATP
(Vframe_alpha_lower_limit
))
1700 alpha_min
= XFLOAT_DATA
(Vframe_alpha_lower_limit
);
1701 else if (INTEGERP
(Vframe_alpha_lower_limit
))
1702 alpha_min
= (XINT
(Vframe_alpha_lower_limit
)) / 100.0;
1706 else if (1.0 < alpha
)
1708 else if (0.0 <= alpha
&& alpha
< alpha_min
&& alpha_min
<= 1.0)
1711 #ifdef NS_IMPL_COCOA
1713 EmacsView
*view = FRAME_NS_VIEW
(f
);
1714 [[view window
] setAlphaValue
: alpha
];
1720 /* ==========================================================================
1724 ========================================================================== */
1728 x_set_mouse_pixel_position
(struct frame
*f
, int pix_x
, int pix_y
)
1729 /* --------------------------------------------------------------------------
1730 Programmatically reposition mouse pointer in pixel coordinates
1731 -------------------------------------------------------------------------- */
1733 NSTRACE
(x_set_mouse_pixel_position
);
1736 /* FIXME: this does not work, and what about GNUstep? */
1737 #ifdef NS_IMPL_COCOA
1738 [FRAME_NS_VIEW
(f
) lockFocus
];
1739 PSsetmouse
((float
)pix_x
, (float
)pix_y
);
1740 [FRAME_NS_VIEW
(f
) unlockFocus
];
1747 x_set_mouse_position
(struct frame
*f
, int h
, int v
)
1748 /* --------------------------------------------------------------------------
1749 Programmatically reposition mouse pointer in character coordinates
1750 -------------------------------------------------------------------------- */
1754 pix_x
= FRAME_COL_TO_PIXEL_X
(f
, h
) + FRAME_COLUMN_WIDTH
(f
) / 2;
1755 pix_y
= FRAME_LINE_TO_PIXEL_Y
(f
, v
) + FRAME_LINE_HEIGHT
(f
) / 2;
1757 if (pix_x
< 0) pix_x
= 0;
1758 if (pix_x
> FRAME_PIXEL_WIDTH
(f
)) pix_x
= FRAME_PIXEL_WIDTH
(f
);
1760 if (pix_y
< 0) pix_y
= 0;
1761 if (pix_y
> FRAME_PIXEL_HEIGHT
(f
)) pix_y
= FRAME_PIXEL_HEIGHT
(f
);
1763 x_set_mouse_pixel_position
(f
, pix_x
, pix_y
);
1768 note_mouse_movement
(struct frame
*frame
, CGFloat x
, CGFloat y
)
1769 /* ------------------------------------------------------------------------
1770 Called by EmacsView on mouseMovement events. Passes on
1771 to emacs mainstream code if we moved off of a rect of interest
1772 known as last_mouse_glyph.
1773 ------------------------------------------------------------------------ */
1775 struct ns_display_info
*dpyinfo
= FRAME_DISPLAY_INFO
(frame
);
1778 // NSTRACE
(note_mouse_movement
);
1780 dpyinfo
->last_mouse_motion_frame
= frame
;
1781 r
= &dpyinfo
->last_mouse_glyph
;
1783 /* Note, this doesn't get called for enter/leave, since we don't have a
1784 position. Those are taken care of in the corresponding NSView methods. */
1786 /* has movement gone beyond last rect we were tracking? */
1787 if (x
< r
->origin.x || x
>= r
->origin.x
+ r
->size.width
1788 || y
< r
->origin.y || y
>= r
->origin.y
+ r
->size.height
)
1790 ns_update_begin
(frame
);
1791 frame
->mouse_moved
= 1;
1792 note_mouse_highlight
(frame
, x
, y
);
1793 remember_mouse_glyph
(frame
, x
, y
, r
);
1794 ns_update_end
(frame
);
1803 ns_mouse_position
(struct frame
**fp
, int insist
, Lisp_Object
*bar_window
,
1804 enum scroll_bar_part
*part
, Lisp_Object
*x
, Lisp_Object
*y
,
1806 /* --------------------------------------------------------------------------
1807 External (hook): inform emacs about mouse position and hit parts.
1808 If a scrollbar is being dragged, set bar_window, part, x, y, time.
1809 x & y should be position in the scrollbar (the whole bar, not the handle)
1810 and length of scrollbar respectively
1811 -------------------------------------------------------------------------- */
1815 Lisp_Object frame
, tail
;
1817 struct ns_display_info
*dpyinfo
;
1819 NSTRACE
(ns_mouse_position
);
1823 fprintf (stderr
, "Warning
: ns_mouse_position
() called with
null *fp.
\n"
);
1827 dpyinfo
= FRAME_DISPLAY_INFO
(*fp
);
1831 if (dpyinfo
->last_mouse_scroll_bar
!= nil
&& insist
== 0)
1833 /* TODO: we do not use this path at the moment because drag events will
1834 go directly to the EmacsScroller. Leaving code in for now. */
1835 [dpyinfo
->last_mouse_scroll_bar
1836 getMouseMotionPart
: (int
*)part window
: bar_window x
: x y
: y
];
1838 *time
= dpyinfo
->last_mouse_movement_time
;
1839 dpyinfo
->last_mouse_scroll_bar
= nil
;
1843 /* Clear the mouse-moved flag for every frame on this display. */
1844 FOR_EACH_FRAME
(tail
, frame
)
1845 if (FRAME_NS_P
(XFRAME
(frame
))
1846 && FRAME_NS_DISPLAY
(XFRAME
(frame
)) == FRAME_NS_DISPLAY
(*fp
))
1847 XFRAME
(frame
)->mouse_moved
= 0;
1849 dpyinfo
->last_mouse_scroll_bar
= nil
;
1850 if (dpyinfo
->last_mouse_frame
1851 && FRAME_LIVE_P
(dpyinfo
->last_mouse_frame
))
1852 f
= dpyinfo
->last_mouse_frame
;
1854 f
= dpyinfo
->x_focus_frame ? dpyinfo
->x_focus_frame
1855 : SELECTED_FRAME
();
1857 if (f
&& FRAME_NS_P
(f
))
1859 view = FRAME_NS_VIEW
(*fp
);
1861 position
= [[view window
] mouseLocationOutsideOfEventStream
];
1862 position
= [view convertPoint
: position fromView
: nil
];
1863 remember_mouse_glyph
(f
, position.x
, position.y
,
1864 &dpyinfo
->last_mouse_glyph
);
1865 /*fprintf (stderr, "ns_mouse_position: %.0f, %.0f\n", position.x, position.y); */
1867 if (bar_window
) *bar_window
= Qnil
;
1868 if (part
) *part
= 0; /*scroll_bar_handle; */
1870 if (x
) XSETINT
(*x
, lrint
(position.x
));
1871 if (y
) XSETINT
(*y
, lrint
(position.y
));
1873 *time
= dpyinfo
->last_mouse_movement_time
;
1883 ns_frame_up_to_date
(struct frame
*f
)
1884 /* --------------------------------------------------------------------------
1885 External (hook): Fix up mouse highlighting right after a full update.
1886 Can't use FRAME_MOUSE_UPDATE due to ns_frame_begin and ns_frame_end calls.
1887 -------------------------------------------------------------------------- */
1889 NSTRACE
(ns_frame_up_to_date
);
1893 Mouse_HLInfo
*hlinfo
= MOUSE_HL_INFO
(f
);
1894 if (f
== hlinfo
->mouse_face_mouse_frame
)
1898 note_mouse_highlight
(hlinfo
->mouse_face_mouse_frame
,
1899 hlinfo
->mouse_face_mouse_x
,
1900 hlinfo
->mouse_face_mouse_y
);
1909 ns_define_frame_cursor
(struct frame
*f
, Cursor cursor
)
1910 /* --------------------------------------------------------------------------
1911 External (RIF): set frame mouse pointer type.
1912 -------------------------------------------------------------------------- */
1914 NSTRACE
(ns_define_frame_cursor
);
1915 if (FRAME_POINTER_TYPE
(f
) != cursor
)
1917 EmacsView
*view = FRAME_NS_VIEW
(f
);
1918 FRAME_POINTER_TYPE
(f
) = cursor
;
1919 [[view window
] invalidateCursorRectsForView
: view];
1920 /* Redisplay assumes this function also draws the changed frame
1921 cursor, but this function doesn't, so do it explicitly. */
1922 x_update_cursor
(f
, 1);
1928 /* ==========================================================================
1932 ========================================================================== */
1936 ns_convert_key
(unsigned code
)
1937 /* --------------------------------------------------------------------------
1938 Internal call used by NSView-keyDown.
1939 -------------------------------------------------------------------------- */
1941 const unsigned last_keysym
= (sizeof
(convert_ns_to_X_keysym
)
1942 / sizeof
(convert_ns_to_X_keysym
[0]));
1944 /* An array would be faster, but less easy to read. */
1945 for (keysym
= 0; keysym
< last_keysym
; keysym
+= 2)
1946 if (code
== convert_ns_to_X_keysym
[keysym
])
1947 return 0xFF00 | convert_ns_to_X_keysym
[keysym
+1];
1949 /* if decide to use keyCode and Carbon table, use this line:
1950 return code > 0xff ? 0 : 0xFF00 | ns_keycode_to_xkeysym_table[code]; */
1955 x_get_keysym_name
(int keysym
)
1956 /* --------------------------------------------------------------------------
1957 Called by keyboard.c. Not sure if the return val is important, except
1959 -------------------------------------------------------------------------- */
1961 static
char value
[16];
1962 NSTRACE
(x_get_keysym_name
);
1963 sprintf (value
, "
%d", keysym);
1969 /* ==========================================================================
1971 Block drawing operations
1973 ========================================================================== */
1977 ns_redraw_scroll_bars
(struct frame
*f
)
1981 NSArray
*subviews
= [[FRAME_NS_VIEW
(f
) superview
] subviews
];
1982 NSTRACE
(ns_redraw_scroll_bars
);
1983 for (i
=[subviews count
]-1; i
>= 0; i
--)
1985 view = [subviews objectAtIndex
: i
];
1986 if (![view isKindOfClass
: [EmacsScroller
class]]) continue
;
1993 ns_clear_frame
(struct frame
*f
)
1994 /* --------------------------------------------------------------------------
1995 External (hook): Erase the entire frame
1996 -------------------------------------------------------------------------- */
1998 NSView
*view = FRAME_NS_VIEW
(f
);
2001 NSTRACE
(ns_clear_frame
);
2003 /* comes on initial frame because we have
2004 after-make-frame-functions = select-frame */
2005 if (!FRAME_DEFAULT_FACE
(f
))
2008 mark_window_cursors_off
(XWINDOW
(FRAME_ROOT_WINDOW
(f
)));
2013 ns_focus
(f
, &r
, 1);
2014 [ns_lookup_indexed_color
(NS_FACE_BACKGROUND
(FRAME_DEFAULT_FACE
(f
)), f
) set];
2018 /* as of 2006/11 or so this is now needed */
2019 ns_redraw_scroll_bars
(f
);
2025 ns_clear_frame_area
(struct frame
*f
, int x
, int y
, int width
, int height
)
2026 /* --------------------------------------------------------------------------
2027 External (RIF): Clear section of frame
2028 -------------------------------------------------------------------------- */
2030 NSRect r
= NSMakeRect
(x
, y
, width
, height
);
2031 NSView
*view = FRAME_NS_VIEW
(f
);
2032 struct face
*face
= FRAME_DEFAULT_FACE
(f
);
2037 NSTRACE
(ns_clear_frame_area
);
2039 r
= NSIntersectionRect
(r
, [view frame
]);
2040 ns_focus
(f
, &r
, 1);
2041 [ns_lookup_indexed_color
(NS_FACE_BACKGROUND
(face
), f
) set];
2051 ns_scroll_run
(struct window
*w
, struct run
*run
)
2052 /* --------------------------------------------------------------------------
2053 External (RIF): Insert or delete n lines at line vpos
2054 -------------------------------------------------------------------------- */
2056 struct frame
*f
= XFRAME
(w
->frame
);
2057 int x
, y
, width
, height
, from_y
, to_y
, bottom_y
;
2059 NSTRACE
(ns_scroll_run
);
2061 /* begin copy from other terms */
2062 /* Get frame-relative bounding box of the text display area of W,
2063 without mode lines. Include in this box the left and right
2065 window_box
(w
, ANY_AREA
, &x
, &y
, &width
, &height
);
2067 from_y
= WINDOW_TO_FRAME_PIXEL_Y
(w
, run
->current_y
);
2068 to_y
= WINDOW_TO_FRAME_PIXEL_Y
(w
, run
->desired_y
);
2069 bottom_y
= y
+ height
;
2073 /* Scrolling up. Make sure we don't copy part of the mode
2074 line at the bottom. */
2075 if (from_y
+ run
->height
> bottom_y
)
2076 height
= bottom_y
- from_y
;
2078 height
= run
->height
;
2082 /* Scrolling down. Make sure we don't copy over the mode line.
2084 if (to_y
+ run
->height
> bottom_y
)
2085 height
= bottom_y
- to_y
;
2087 height
= run
->height
;
2089 /* end copy from other terms */
2099 NSRect srcRect
= NSMakeRect
(x
, from_y
, width
, height
);
2100 NSRect dstRect
= NSMakeRect
(x
, to_y
, width
, height
);
2101 NSPoint dstOrigin
= NSMakePoint
(x
, to_y
);
2103 ns_focus
(f
, &dstRect
, 1);
2104 NSCopyBits
(0, srcRect
, dstOrigin
);
2113 ns_after_update_window_line
(struct window
*w
, struct glyph_row
*desired_row
)
2114 /* --------------------------------------------------------------------------
2115 External (RIF): preparatory to fringe update after text was updated
2116 -------------------------------------------------------------------------- */
2121 NSTRACE
(ns_after_update_window_line
);
2123 /* begin copy from other terms */
2126 if (!desired_row
->mode_line_p
&& !w
->pseudo_window_p
)
2127 desired_row
->redraw_fringe_bitmaps_p
= 1;
2129 /* When a window has disappeared, make sure that no rest of
2130 full-width rows stays visible in the internal border. */
2131 if (windows_or_buffers_changed
2132 && desired_row
->full_width_p
2133 && (f
= XFRAME
(w
->frame
),
2134 width
= FRAME_INTERNAL_BORDER_WIDTH
(f
),
2136 && (height
= desired_row
->visible_height
,
2139 int y
= WINDOW_TO_FRAME_PIXEL_Y
(w
, max (0, desired_row
->y
));
2142 ns_clear_frame_area
(f
, 0, y
, width
, height
);
2143 ns_clear_frame_area
(f
,
2144 FRAME_PIXEL_WIDTH
(f
) - width
,
2152 ns_shift_glyphs_for_insert
(struct frame
*f
,
2153 int x
, int y
, int width
, int height
,
2155 /* --------------------------------------------------------------------------
2156 External (RIF): copy an area horizontally, don't worry about clearing src
2157 -------------------------------------------------------------------------- */
2159 NSRect srcRect
= NSMakeRect
(x
, y
, width
, height
);
2160 NSRect dstRect
= NSMakeRect
(x
+shift_by
, y
, width
, height
);
2161 NSPoint dstOrigin
= dstRect.origin
;
2163 NSTRACE
(ns_shift_glyphs_for_insert
);
2165 ns_focus
(f
, &dstRect
, 1);
2166 NSCopyBits
(0, srcRect
, dstOrigin
);
2172 /* ==========================================================================
2174 Character encoding and metrics
2176 ========================================================================== */
2180 ns_compute_glyph_string_overhangs
(struct glyph_string
*s
)
2181 /* --------------------------------------------------------------------------
2182 External (RIF); compute left/right overhang of whole string and set in s
2183 -------------------------------------------------------------------------- */
2185 struct font
*font
= s
->font
;
2189 struct font_metrics metrics
;
2190 unsigned int codes
[2];
2191 codes
[0] = *(s
->char2b
);
2192 codes
[1] = *(s
->char2b
+ s
->nchars
- 1);
2194 font
->driver
->text_extents
(font
, codes
, 2, &metrics
);
2195 s
->left_overhang
= -metrics.lbearing
;
2197 = metrics.rbearing
> metrics.width
2198 ? metrics.rbearing
- metrics.width
: 0;
2202 s
->left_overhang
= 0;
2203 if (EQ
(font
->driver
->type, Qns
))
2204 s
->right_overhang
= ((struct nsfont_info
*)font
)->ital ?
2205 FONT_HEIGHT
(font
) * 0.2 : 0;
2207 s
->right_overhang
= 0;
2213 /* ==========================================================================
2215 Fringe and cursor drawing
2217 ========================================================================== */
2220 extern int max_used_fringe_bitmap
;
2222 ns_draw_fringe_bitmap
(struct window
*w
, struct glyph_row
*row
,
2223 struct draw_fringe_bitmap_params
*p
)
2224 /* --------------------------------------------------------------------------
2225 External (RIF); fringe-related
2226 -------------------------------------------------------------------------- */
2228 struct frame
*f
= XFRAME
(WINDOW_FRAME
(w
));
2229 struct face
*face
= p
->face
;
2230 static EmacsImage
**bimgs
= NULL;
2231 static int nBimgs
= 0;
2233 /* grow bimgs if needed */
2234 if (nBimgs
< max_used_fringe_bitmap
)
2236 bimgs
= xrealloc
(bimgs
, max_used_fringe_bitmap
* sizeof
*bimgs
);
2237 memset
(bimgs
+ nBimgs
, 0,
2238 (max_used_fringe_bitmap
- nBimgs
) * sizeof
*bimgs
);
2239 nBimgs
= max_used_fringe_bitmap
;
2242 /* Must clip because of partially visible lines. */
2243 ns_clip_to_row
(w
, row
, ANY_AREA
, YES
);
2247 int bx
= p
->bx
, by
= p
->by
, nx
= p
->nx
, ny
= p
->ny
;
2249 /* If the fringe is adjacent to the left (right) scroll bar of a
2250 leftmost (rightmost, respectively) window, then extend its
2251 background to the gap between the fringe and the bar. */
2252 if ((WINDOW_LEFTMOST_P
(w
)
2253 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT
(w
))
2254 ||
(WINDOW_RIGHTMOST_P
(w
)
2255 && WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT
(w
)))
2257 int sb_width
= WINDOW_CONFIG_SCROLL_BAR_WIDTH
(w
);
2261 int bar_area_x
= WINDOW_SCROLL_BAR_AREA_X
(w
);
2262 int bar_area_width
= (WINDOW_CONFIG_SCROLL_BAR_COLS
(w
)
2263 * FRAME_COLUMN_WIDTH
(f
));
2267 /* Bitmap fills the fringe. */
2268 if (bar_area_x
+ bar_area_width
== p
->x
)
2269 bx
= bar_area_x
+ sb_width
;
2270 else if (p
->x
+ p
->wd
== bar_area_x
)
2274 int header_line_height
= WINDOW_HEADER_LINE_HEIGHT
(w
);
2276 nx
= bar_area_width
- sb_width
;
2277 by
= WINDOW_TO_FRAME_PIXEL_Y
(w
, max (header_line_height
,
2279 ny
= row
->visible_height
;
2284 if (bar_area_x
+ bar_area_width
== bx
)
2286 bx
= bar_area_x
+ sb_width
;
2287 nx
+= bar_area_width
- sb_width
;
2289 else if (bx
+ nx
== bar_area_x
)
2290 nx
+= bar_area_width
- sb_width
;
2295 if (bx
>= 0 && nx
> 0)
2297 NSRect r
= NSMakeRect
(bx
, by
, nx
, ny
);
2299 [ns_lookup_indexed_color
(face
->background
, f
) set];
2306 NSRect r
= NSMakeRect
(p
->x
, p
->y
, p
->wd
, p
->h
);
2307 EmacsImage
*img
= bimgs
[p
->which - 1];
2311 unsigned short
*bits
= p
->bits
+ p
->dh
;
2314 unsigned
char *cbits
= xmalloc
(len
);
2316 for (i
= 0; i
< len
; i
++)
2317 cbits
[i
] = ~
(bits
[i
] & 0xff);
2318 img
= [[EmacsImage alloc
] initFromXBM
: cbits width
: 8 height
: p
->h
2320 bimgs
[p
->which - 1] = img
;
2325 /* Since we composite the bitmap instead of just blitting it, we need
2326 to erase the whole background. */
2327 [ns_lookup_indexed_color
(face
->background
, f
) set];
2329 [img setXBMColor
: ns_lookup_indexed_color
(face
->foreground
, f
)];
2330 #
if defined
(NS_IMPL_COCOA
) && MAC_OS_X_VERSION_MAX_ALLOWED
>= MAC_OS_X_VERSION_10_6
2332 fromRect
: NSZeroRect
2333 operation
: NSCompositeSourceOver
2339 NSPoint pt
= r.origin
;
2341 [img compositeToPoint
: pt operation
: NSCompositeSourceOver
];
2350 ns_draw_window_cursor
(struct window
*w
, struct glyph_row
*glyph_row
,
2351 int x
, int y
, enum text_cursor_kinds cursor_type
,
2352 int cursor_width
, bool on_p
, bool active_p
)
2353 /* --------------------------------------------------------------------------
2354 External call (RIF): draw cursor.
2355 Note that CURSOR_WIDTH is meaningful only for (h)bar cursors.
2356 -------------------------------------------------------------------------- */
2359 int fx
, fy
, h
, cursor_height
;
2360 struct frame
*f
= WINDOW_XFRAME
(w
);
2361 struct glyph
*phys_cursor_glyph
;
2362 struct glyph
*cursor_glyph
;
2364 NSColor
*hollow_color
= FRAME_BACKGROUND_COLOR
(f
);
2366 /* If cursor is out of bounds, don't draw garbage. This can happen
2367 in mini-buffer windows when switching between echo area glyphs
2370 NSTRACE
(dumpcursor
);
2375 w
->phys_cursor_type
= cursor_type
;
2376 w
->phys_cursor_on_p
= on_p
;
2378 if (cursor_type
== NO_CURSOR
)
2380 w
->phys_cursor_width
= 0;
2384 if ((phys_cursor_glyph
= get_phys_cursor_glyph
(w
)) == NULL)
2386 if (glyph_row
->exact_window_width_line_p
2387 && w
->phys_cursor.hpos
>= glyph_row
->used
[TEXT_AREA
])
2389 glyph_row
->cursor_in_fringe_p
= 1;
2390 draw_fringe_bitmap
(w
, glyph_row
, 0);
2395 /* We draw the cursor (with NSRectFill), then draw the glyph on top
2396 (other terminals do it the other way round). We must set
2397 w->phys_cursor_width to the cursor width. For bar cursors, that
2398 is CURSOR_WIDTH; for box cursors, it is the glyph width. */
2399 get_phys_cursor_geometry
(w
, glyph_row
, phys_cursor_glyph
, &fx
, &fy
, &h
);
2401 /* The above get_phys_cursor_geometry call set w->phys_cursor_width
2402 to the glyph width; replace with CURSOR_WIDTH for (V)BAR cursors. */
2403 if (cursor_type
== BAR_CURSOR
)
2405 if (cursor_width
< 1)
2406 cursor_width
= max (FRAME_CURSOR_WIDTH
(f
), 1);
2407 w
->phys_cursor_width
= cursor_width
;
2409 /* If we have an HBAR, "cursor_width" MAY specify height. */
2410 else if (cursor_type
== HBAR_CURSOR
)
2412 cursor_height
= (cursor_width
< 1) ? lrint
(0.25 * h
) : cursor_width
;
2413 fy
+= h
- cursor_height
;
2417 r.origin.x
= fx
, r.origin.y
= fy
;
2419 r.
size.width
= w
->phys_cursor_width
;
2421 /* TODO: only needed in rare cases with last-resort font in HELLO..
2422 should we do this more efficiently? */
2423 ns_clip_to_row
(w
, glyph_row
, ANY_AREA
, NO
); /* do ns_focus(f, &r, 1); if remove */
2426 face
= FACE_FROM_ID
(f
, phys_cursor_glyph
->face_id
);
2427 if (face
&& NS_FACE_BACKGROUND
(face
)
2428 == ns_index_color
(FRAME_CURSOR_COLOR
(f
), f
))
2430 [ns_lookup_indexed_color
(NS_FACE_FOREGROUND
(face
), f
) set];
2431 hollow_color
= FRAME_CURSOR_COLOR
(f
);
2434 [FRAME_CURSOR_COLOR
(f
) set];
2436 #ifdef NS_IMPL_COCOA
2437 /* TODO: This makes drawing of cursor plus that of phys_cursor_glyph
2438 atomic. Cleaner ways of doing this should be investigated.
2439 One way would be to set a global variable DRAWING_CURSOR
2440 when making the call to draw_phys..(), don't focus in that
2441 case, then move the ns_unfocus() here after that call. */
2442 NSDisableScreenUpdates
();
2445 switch (cursor_type
)
2449 case FILLED_BOX_CURSOR
:
2452 case HOLLOW_BOX_CURSOR
:
2455 NSRectFill
(NSInsetRect
(r
, 1, 1));
2456 [FRAME_CURSOR_COLOR
(f
) set];
2463 /* If the character under cursor is R2L, draw the bar cursor
2464 on the right of its glyph, rather than on the left. */
2465 cursor_glyph
= get_phys_cursor_glyph
(w
);
2466 if ((cursor_glyph
->resolved_level
& 1) != 0)
2467 s.origin.x
+= cursor_glyph
->pixel_width
- s.
size.width
;
2474 /* draw the character under the cursor */
2475 if (cursor_type
!= NO_CURSOR
)
2476 draw_phys_cursor_glyph
(w
, glyph_row
, DRAW_CURSOR
);
2478 #ifdef NS_IMPL_COCOA
2479 NSEnableScreenUpdates
();
2486 ns_draw_vertical_window_border
(struct window
*w
, int x
, int y0
, int y1
)
2487 /* --------------------------------------------------------------------------
2488 External (RIF): Draw a vertical line.
2489 -------------------------------------------------------------------------- */
2491 struct frame
*f
= XFRAME
(WINDOW_FRAME
(w
));
2493 NSRect r
= NSMakeRect
(x
, y0
, 1, y1
-y0
);
2495 NSTRACE
(ns_draw_vertical_window_border
);
2497 face
= FACE_FROM_ID
(f
, VERTICAL_BORDER_FACE_ID
);
2499 [ns_lookup_indexed_color
(face
->foreground
, f
) set];
2501 ns_focus
(f
, &r
, 1);
2508 show_hourglass
(struct atimer
*timer
)
2510 if (hourglass_shown_p
)
2515 /* TODO: add NSProgressIndicator to selected frame (see macfns.c) */
2517 hourglass_shown_p
= 1;
2523 hide_hourglass
(void
)
2525 if (!hourglass_shown_p
)
2530 /* TODO: remove NSProgressIndicator from all frames */
2532 hourglass_shown_p
= 0;
2538 /* ==========================================================================
2540 Glyph drawing operations
2542 ========================================================================== */
2545 ns_get_glyph_string_clip_rect
(struct glyph_string
*s
, NativeRectangle
*nr
)
2546 /* --------------------------------------------------------------------------
2547 Wrapper utility to account for internal border width on full-width lines,
2548 and allow top full-width rows to hit the frame top. nr should be pointer
2549 to two successive NSRects. Number of rects actually used is returned.
2550 -------------------------------------------------------------------------- */
2552 int n
= get_glyph_string_clip_rects
(s
, nr
, 2);
2556 /* --------------------------------------------------------------------
2557 Draw a wavy line under glyph string s. The wave fills wave_height
2564 wave_height = 3 | * * * *
2565 --------------------------------------------------------------------- */
2568 ns_draw_underwave
(struct glyph_string
*s
, EmacsCGFloat width
, EmacsCGFloat x
)
2570 int wave_height
= 3, wave_length
= 2;
2571 int y
, dx
, dy
, odd
, xmax
;
2576 dy
= wave_height
- 1;
2577 y
= s
->ybase
- wave_height
+ 3;
2580 /* Find and set clipping rectangle */
2581 waveClip
= NSMakeRect
(x
, y
, width
, wave_height
);
2582 [[NSGraphicsContext currentContext
] saveGraphicsState
];
2583 NSRectClip
(waveClip
);
2585 /* Draw the waves */
2586 a.x
= x
- ((int
)(x
) % dx) + (EmacsCGFloat) 0.5;
2588 odd
= (int
)(a.x
/dx
) % 2;
2589 a.y
= b.y
= y
+ 0.5;
2598 [NSBezierPath strokeLineFromPoint
:a toPoint
:b
];
2599 a.x
= b.x
, a.y
= b.y
;
2600 b.x
+= dx
, b.y
= y
+ 0.5 + odd
*dy
;
2604 /* Restore previous clipping rectangle(s) */
2605 [[NSGraphicsContext currentContext
] restoreGraphicsState
];
2611 ns_draw_text_decoration
(struct glyph_string
*s
, struct face
*face
,
2612 NSColor
*defaultCol
, CGFloat width
, CGFloat x
)
2613 /* --------------------------------------------------------------------------
2614 Draw underline, overline, and strike-through on glyph string s.
2615 -------------------------------------------------------------------------- */
2617 if (s
->for_overlaps
)
2621 if (face
->underline_p
)
2623 if (s
->face
->underline_type
== FACE_UNDER_WAVE
)
2625 if (face
->underline_defaulted_p
)
2628 [ns_lookup_indexed_color
(face
->underline_color
, s
->f
) set];
2630 ns_draw_underwave
(s
, width
, x
);
2632 else if (s
->face
->underline_type
== FACE_UNDER_LINE
)
2636 unsigned
long thickness
, position
;
2638 /* If the prev was underlined, match its appearance. */
2639 if (s
->prev
&& s
->prev
->face
->underline_p
2640 && s
->prev
->face
->underline_type
== FACE_UNDER_LINE
2641 && s
->prev
->underline_thickness
> 0)
2643 thickness
= s
->prev
->underline_thickness
;
2644 position
= s
->prev
->underline_position
;
2649 unsigned
long descent
;
2652 descent
= s
->y
+ s
->height
- s
->ybase
;
2654 /* Use underline thickness of font, defaulting to 1. */
2655 thickness
= (font
&& font
->underline_thickness
> 0)
2656 ? font
->underline_thickness
: 1;
2658 /* Determine the offset of underlining from the baseline. */
2659 if (x_underline_at_descent_line
)
2660 position
= descent
- thickness
;
2661 else if (x_use_underline_position_properties
2662 && font
&& font
->underline_position
>= 0)
2663 position
= font
->underline_position
;
2665 position
= lround
(font
->descent
/ 2);
2667 position
= underline_minimum_offset
;
2669 position
= max (position
, underline_minimum_offset
);
2671 /* Ensure underlining is not cropped. */
2672 if (descent
<= position
)
2674 position
= descent
- 1;
2677 else if (descent
< position
+ thickness
)
2681 s
->underline_thickness
= thickness
;
2682 s
->underline_position
= position
;
2684 r
= NSMakeRect
(x
, s
->ybase
+ position
, width
, thickness
);
2686 if (face
->underline_defaulted_p
)
2689 [ns_lookup_indexed_color
(face
->underline_color
, s
->f
) set];
2693 /* Do overline. We follow other terms in using a thickness of 1
2694 and ignoring overline_margin. */
2695 if (face
->overline_p
)
2698 r
= NSMakeRect
(x
, s
->y
, width
, 1);
2700 if (face
->overline_color_defaulted_p
)
2703 [ns_lookup_indexed_color
(face
->overline_color
, s
->f
) set];
2707 /* Do strike-through. We follow other terms for thickness and
2708 vertical position.*/
2709 if (face
->strike_through_p
)
2714 dy
= lrint
((s
->height
- 1) / 2);
2715 r
= NSMakeRect
(x
, s
->y
+ dy
, width
, 1);
2717 if (face
->strike_through_color_defaulted_p
)
2720 [ns_lookup_indexed_color
(face
->strike_through_color
, s
->f
) set];
2726 ns_draw_box
(NSRect r
, CGFloat thickness
, NSColor
*col
,
2727 char left_p
, char right_p
)
2728 /* --------------------------------------------------------------------------
2729 Draw an unfilled rect inside r, optionally leaving left and/or right open.
2730 Note we can't just use an NSDrawRect command, because of the possibility
2731 of some sides not being drawn, and because the rect will be filled.
2732 -------------------------------------------------------------------------- */
2738 s.
size.height
= thickness
;
2740 s.origin.y
+= r.
size.height
- thickness
;
2743 s.
size.height
= r.
size.height
;
2744 s.origin.y
= r.origin.y
;
2746 /* left, right (optional) */
2747 s.
size.width
= thickness
;
2752 s.origin.x
+= r.
size.width
- thickness
;
2759 ns_draw_relief
(NSRect r
, int thickness
, char raised_p
,
2760 char top_p
, char bottom_p
, char left_p
, char right_p
,
2761 struct glyph_string
*s
)
2762 /* --------------------------------------------------------------------------
2763 Draw a relief rect inside r, optionally leaving some sides open.
2764 Note we can't just use an NSDrawBezel command, because of the possibility
2765 of some sides not being drawn, and because the rect will be filled.
2766 -------------------------------------------------------------------------- */
2768 static NSColor
*baseCol
= nil
, *lightCol
= nil
, *darkCol
= nil
;
2769 NSColor
*newBaseCol
= nil
;
2772 NSTRACE
(ns_draw_relief
);
2776 if (s
->face
->use_box_color_for_shadows_p
)
2778 newBaseCol
= ns_lookup_indexed_color
(s
->face
->box_color
, s
->f
);
2780 /* else if (s->first_glyph->type == IMAGE_GLYPH
2782 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2784 newBaseCol = IMAGE_BACKGROUND (s->img, s->f, 0);
2788 newBaseCol
= ns_lookup_indexed_color
(s
->face
->background
, s
->f
);
2791 if (newBaseCol
== nil
)
2792 newBaseCol
= [NSColor grayColor
];
2794 if (newBaseCol
!= baseCol
) /* TODO: better check */
2797 baseCol
= [newBaseCol retain
];
2799 lightCol
= [[baseCol highlightWithLevel
: 0.2] retain
];
2801 darkCol
= [[baseCol shadowWithLevel
: 0.3] retain
];
2804 [(raised_p ? lightCol
: darkCol
) set];
2806 /* TODO: mitering. Using NSBezierPath doesn't work because of color switch. */
2809 sr.
size.height
= thickness
;
2810 if (top_p
) NSRectFill
(sr
);
2813 sr.
size.height
= r.
size.height
;
2814 sr.
size.width
= thickness
;
2815 if (left_p
) NSRectFill
(sr
);
2817 [(raised_p ? darkCol
: lightCol
) set];
2820 sr.
size.width
= r.
size.width
;
2821 sr.
size.height
= thickness
;
2822 sr.origin.y
+= r.
size.height
- thickness
;
2823 if (bottom_p
) NSRectFill
(sr
);
2826 sr.
size.height
= r.
size.height
;
2827 sr.origin.y
= r.origin.y
;
2828 sr.
size.width
= thickness
;
2829 sr.origin.x
+= r.
size.width
- thickness
;
2830 if (right_p
) NSRectFill
(sr
);
2835 ns_dumpglyphs_box_or_relief
(struct glyph_string
*s
)
2836 /* --------------------------------------------------------------------------
2837 Function modeled after x_draw_glyph_string_box ().
2838 Sets up parameters for drawing.
2839 -------------------------------------------------------------------------- */
2841 int right_x
, last_x
;
2842 char left_p
, right_p
;
2843 struct glyph
*last_glyph
;
2848 if (s
->hl
== DRAW_MOUSE_FACE
)
2850 face
= FACE_FROM_ID
(s
->f
, MOUSE_HL_INFO
(s
->f
)->mouse_face_face_id
);
2852 face
= FACE_FROM_ID
(s
->f
, MOUSE_FACE_ID
);
2857 thickness
= face
->box_line_width
;
2859 NSTRACE
(ns_dumpglyphs_box_or_relief
);
2861 last_x
= ((s
->row
->full_width_p
&& !s
->w
->pseudo_window_p
)
2862 ? WINDOW_RIGHT_EDGE_X
(s
->w
)
2863 : window_box_right
(s
->w
, s
->area
));
2864 last_glyph
= (s
->cmp || s
->img
2865 ? s
->first_glyph
: s
->first_glyph
+ s
->nchars
-1);
2867 right_x
= ((s
->row
->full_width_p
&& s
->extends_to_end_of_line_p
2868 ? last_x
- 1 : min (last_x
, s
->x
+ s
->background_width
) - 1));
2870 left_p
= (s
->first_glyph
->left_box_line_p
2871 ||
(s
->hl
== DRAW_MOUSE_FACE
2872 && (s
->prev
== NULL || s
->prev
->hl
!= s
->hl
)));
2873 right_p
= (last_glyph
->right_box_line_p
2874 ||
(s
->hl
== DRAW_MOUSE_FACE
2875 && (s
->next
== NULL || s
->next
->hl
!= s
->hl
)));
2877 r
= NSMakeRect
(s
->x
, s
->y
, right_x
- s
->x
+ 1, s
->height
);
2879 /* TODO: Sometimes box_color is 0 and this seems wrong; should investigate. */
2880 if (s
->face
->box
== FACE_SIMPLE_BOX
&& s
->face
->box_color
)
2882 ns_draw_box
(r
, abs (thickness
),
2883 ns_lookup_indexed_color
(face
->box_color
, s
->f
),
2888 ns_draw_relief
(r
, abs (thickness
), s
->face
->box
== FACE_RAISED_BOX
,
2889 1, 1, left_p
, right_p
, s
);
2895 ns_maybe_dumpglyphs_background
(struct glyph_string
*s
, char force_p
)
2896 /* --------------------------------------------------------------------------
2897 Modeled after x_draw_glyph_string_background, which draws BG in
2898 certain cases. Others are left to the text rendering routine.
2899 -------------------------------------------------------------------------- */
2901 NSTRACE
(ns_maybe_dumpglyphs_background
);
2903 if (!s
->background_filled_p
/* || s->hl == DRAW_MOUSE_FACE*/)
2905 int box_line_width
= max (s
->face
->box_line_width
, 0);
2906 if (FONT_HEIGHT
(s
->font
) < s
->height
- 2 * box_line_width
2907 || s
->font_not_found_p || s
->extends_to_end_of_line_p || force_p
)
2910 if (s
->hl
== DRAW_MOUSE_FACE
)
2912 face
= FACE_FROM_ID
(s
->f
,
2913 MOUSE_HL_INFO
(s
->f
)->mouse_face_face_id
);
2915 face
= FACE_FROM_ID
(s
->f
, MOUSE_FACE_ID
);
2918 face
= FACE_FROM_ID
(s
->f
, s
->first_glyph
->face_id
);
2920 [(NS_FACE_BACKGROUND
(face
) != 0
2921 ? ns_lookup_indexed_color
(NS_FACE_BACKGROUND
(face
), s
->f
)
2922 : FRAME_BACKGROUND_COLOR
(s
->f
)) set];
2925 struct ns_display_info
*dpyinfo
= FRAME_DISPLAY_INFO
(s
->f
);
2926 [[dpyinfo
->bitmaps
[face
->stipple
-1].img stippleMask
] set];
2929 if (s
->hl
!= DRAW_CURSOR
)
2931 NSRect r
= NSMakeRect
(s
->x
, s
->y
+ box_line_width
,
2932 s
->background_width
,
2933 s
->height
-2*box_line_width
);
2937 s
->background_filled_p
= 1;
2944 ns_dumpglyphs_image
(struct glyph_string
*s
, NSRect r
)
2945 /* --------------------------------------------------------------------------
2946 Renders an image and associated borders.
2947 -------------------------------------------------------------------------- */
2949 EmacsImage
*img
= s
->img
->pixmap
;
2950 int box_line_vwidth
= max (s
->face
->box_line_width
, 0);
2951 int x
= s
->x
, y
= s
->ybase
- image_ascent
(s
->img
, s
->face
, &s
->slice);
2952 int bg_x
, bg_y
, bg_height
;
2959 NSTRACE
(ns_dumpglyphs_image
);
2961 if (s
->face
->box
!= FACE_NO_BOX
2962 && s
->first_glyph
->left_box_line_p
&& s
->slice.x
== 0)
2963 x
+= abs (s
->face
->box_line_width
);
2966 bg_y
= s
->slice.y
== 0 ? s
->y
: s
->y
+ box_line_vwidth
;
2967 bg_height
= s
->height
;
2968 /* other terms have this, but was causing problems w/tabbar mode */
2969 /* - 2 * box_line_vwidth; */
2971 if (s
->slice.x
== 0) x
+= s
->img
->hmargin
;
2972 if (s
->slice.y
== 0) y
+= s
->img
->vmargin
;
2974 /* Draw BG: if we need larger area than image itself cleared, do that,
2975 otherwise, since we composite the image under NS (instead of mucking
2976 with its background color), we must clear just the image area. */
2977 if (s
->hl
== DRAW_MOUSE_FACE
)
2979 face
= FACE_FROM_ID
(s
->f
, MOUSE_HL_INFO
(s
->f
)->mouse_face_face_id
);
2981 face
= FACE_FROM_ID
(s
->f
, MOUSE_FACE_ID
);
2984 face
= FACE_FROM_ID
(s
->f
, s
->first_glyph
->face_id
);
2986 [ns_lookup_indexed_color
(NS_FACE_BACKGROUND
(face
), s
->f
) set];
2988 if (bg_height
> s
->slice.height || s
->img
->hmargin || s
->img
->vmargin
2989 || s
->img
->mask || s
->img
->pixmap
== 0 || s
->width
!= s
->background_width
)
2991 br
= NSMakeRect
(bg_x
, bg_y
, s
->background_width
, bg_height
);
2992 s
->background_filled_p
= 1;
2996 br
= NSMakeRect
(x
, y
, s
->slice.width
, s
->slice.height
);
3001 /* Draw the image.. do we need to draw placeholder if img ==nil? */
3004 #
if defined
(NS_IMPL_COCOA
) && MAC_OS_X_VERSION_MAX_ALLOWED
>= MAC_OS_X_VERSION_10_6
3005 NSRect dr
= NSMakeRect
(x
, y
, s
->slice.width
, s
->slice.height
);
3006 NSRect ir
= NSMakeRect
(s
->slice.x
, s
->slice.y
,
3007 s
->slice.width
, s
->slice.height
);
3010 operation
: NSCompositeSourceOver
3015 [img compositeToPoint
: NSMakePoint
(x
, y
+ s
->slice.height
)
3016 operation
: NSCompositeSourceOver
];
3020 if (s
->hl
== DRAW_CURSOR
)
3022 [FRAME_CURSOR_COLOR
(s
->f
) set];
3023 if (s
->w
->phys_cursor_type
== FILLED_BOX_CURSOR
)
3024 tdCol
= ns_lookup_indexed_color
(NS_FACE_BACKGROUND
(face
), s
->f
);
3026 /* Currently on NS img->mask is always 0. Since
3027 get_window_cursor_type specifies a hollow box cursor when on
3028 a non-masked image we never reach this clause. But we put it
3029 in in anticipation of better support for image masks on
3031 tdCol
= ns_lookup_indexed_color
(NS_FACE_FOREGROUND
(face
), s
->f
);
3035 tdCol
= ns_lookup_indexed_color
(NS_FACE_FOREGROUND
(face
), s
->f
);
3038 /* Draw underline, overline, strike-through. */
3039 ns_draw_text_decoration
(s
, face
, tdCol
, br.
size.width
, br.origin.x
);
3041 /* Draw relief, if requested */
3042 if (s
->img
->relief || s
->hl
==DRAW_IMAGE_RAISED || s
->hl
==DRAW_IMAGE_SUNKEN
)
3044 if (s
->hl
== DRAW_IMAGE_SUNKEN || s
->hl
== DRAW_IMAGE_RAISED
)
3046 th
= tool_bar_button_relief
>= 0 ?
3047 tool_bar_button_relief
: DEFAULT_TOOL_BAR_BUTTON_RELIEF
;
3048 raised_p
= (s
->hl
== DRAW_IMAGE_RAISED
);
3052 th
= abs (s
->img
->relief
);
3053 raised_p
= (s
->img
->relief
> 0);
3056 r.origin.x
= x
- th
;
3057 r.origin.y
= y
- th
;
3058 r.
size.width
= s
->slice.width
+ 2*th
-1;
3059 r.
size.height
= s
->slice.height
+ 2*th
-1;
3060 ns_draw_relief
(r
, th
, raised_p
,
3062 s
->slice.y
+ s
->slice.height
== s
->img
->height
,
3064 s
->slice.x
+ s
->slice.width
== s
->img
->width
, s
);
3067 /* If there is no mask, the background won't be seen,
3068 so draw a rectangle on the image for the cursor.
3069 Do this for all images, getting transparency right is not reliable. */
3070 if (s
->hl
== DRAW_CURSOR
)
3072 int thickness
= abs (s
->img
->relief
);
3073 if (thickness
== 0) thickness
= 1;
3074 ns_draw_box
(br
, thickness
, FRAME_CURSOR_COLOR
(s
->f
), 1, 1);
3080 ns_dumpglyphs_stretch
(struct glyph_string
*s
)
3085 NSColor
*fgCol
, *bgCol
;
3087 if (!s
->background_filled_p
)
3089 n
= ns_get_glyph_string_clip_rect
(s
, r
);
3090 *r
= NSMakeRect
(s
->x
, s
->y
, s
->background_width
, s
->height
);
3092 ns_focus
(s
->f
, r
, n
);
3094 if (s
->hl
== DRAW_MOUSE_FACE
)
3096 face
= FACE_FROM_ID
(s
->f
, MOUSE_HL_INFO
(s
->f
)->mouse_face_face_id
);
3098 face
= FACE_FROM_ID
(s
->f
, MOUSE_FACE_ID
);
3101 face
= FACE_FROM_ID
(s
->f
, s
->first_glyph
->face_id
);
3103 bgCol
= ns_lookup_indexed_color
(NS_FACE_BACKGROUND
(face
), s
->f
);
3104 fgCol
= ns_lookup_indexed_color
(NS_FACE_FOREGROUND
(face
), s
->f
);
3106 for (i
= 0; i
< n
; ++i
)
3108 if (!s
->row
->full_width_p
)
3110 int overrun
, leftoverrun
;
3112 /* truncate to avoid overwriting fringe and/or scrollbar */
3113 overrun
= max (0, (s
->x
+ s
->background_width
)
3114 - (WINDOW_BOX_RIGHT_EDGE_X
(s
->w
)
3115 - WINDOW_RIGHT_FRINGE_WIDTH
(s
->w
)));
3116 r
[i
].
size.width
-= overrun
;
3118 /* truncate to avoid overwriting to left of the window box */
3119 leftoverrun
= (WINDOW_BOX_LEFT_EDGE_X
(s
->w
)
3120 + WINDOW_LEFT_FRINGE_WIDTH
(s
->w
)) - s
->x
;
3122 if (leftoverrun
> 0)
3124 r
[i
].origin.x
+= leftoverrun
;
3125 r
[i
].
size.width
-= leftoverrun
;
3128 /* XXX: Try to work between problem where a stretch glyph on
3129 a partially-visible bottom row will clear part of the
3130 modeline, and another where list-buffers headers and similar
3131 rows erroneously have visible_height set to 0. Not sure
3132 where this is coming from as other terms seem not to show. */
3133 r
[i
].
size.height
= min (s
->height
, s
->row
->visible_height
);
3138 /* NOTE: under NS this is NOT used to draw cursors, but we must avoid
3139 overwriting cursor (usually when cursor on a tab) */
3140 if (s
->hl
== DRAW_CURSOR
)
3145 width
= s
->w
->phys_cursor_width
;
3146 r
[i
].
size.width
-= width
;
3147 r
[i
].origin.x
+= width
;
3151 /* Draw overlining, etc. on the cursor. */
3152 if (s
->w
->phys_cursor_type
== FILLED_BOX_CURSOR
)
3153 ns_draw_text_decoration
(s
, face
, bgCol
, width
, x
);
3155 ns_draw_text_decoration
(s
, face
, fgCol
, width
, x
);
3162 /* Draw overlining, etc. on the stretch glyph (or the part
3163 of the stretch glyph after the cursor). */
3164 ns_draw_text_decoration
(s
, face
, fgCol
, r
[i
].
size.width
,
3168 s
->background_filled_p
= 1;
3174 ns_draw_glyph_string
(struct glyph_string
*s
)
3175 /* --------------------------------------------------------------------------
3176 External (RIF): Main draw-text call.
3177 -------------------------------------------------------------------------- */
3179 /* TODO (optimize): focus for box and contents draw */
3182 char box_drawn_p
= 0;
3183 struct font
*font
= s
->face
->font
;
3184 if (! font
) font
= FRAME_FONT
(s
->f
);
3186 NSTRACE
(ns_draw_glyph_string
);
3188 if (s
->next
&& s
->right_overhang
&& !s
->for_overlaps
/*&&s->hl!=DRAW_CURSOR*/)
3191 struct glyph_string
*next
;
3193 for (width
= 0, next
= s
->next
;
3194 next
&& width
< s
->right_overhang
;
3195 width
+= next
->width
, next
= next
->next
)
3196 if (next
->first_glyph
->type != IMAGE_GLYPH
)
3198 if (next
->first_glyph
->type != STRETCH_GLYPH
)
3200 n
= ns_get_glyph_string_clip_rect
(s
->next
, r
);
3201 ns_focus
(s
->f
, r
, n
);
3202 ns_maybe_dumpglyphs_background
(s
->next
, 1);
3207 ns_dumpglyphs_stretch
(s
->next
);
3209 next
->num_clips
= 0;
3213 if (!s
->for_overlaps
&& s
->face
->box
!= FACE_NO_BOX
3214 && (s
->first_glyph
->type == CHAR_GLYPH
3215 || s
->first_glyph
->type == COMPOSITE_GLYPH
))
3217 n
= ns_get_glyph_string_clip_rect
(s
, r
);
3218 ns_focus
(s
->f
, r
, n
);
3219 ns_maybe_dumpglyphs_background
(s
, 1);
3220 ns_dumpglyphs_box_or_relief
(s
);
3225 switch (s
->first_glyph
->type)
3229 n
= ns_get_glyph_string_clip_rect
(s
, r
);
3230 ns_focus
(s
->f
, r
, n
);
3231 ns_dumpglyphs_image
(s
, r
[0]);
3236 ns_dumpglyphs_stretch
(s
);
3240 case COMPOSITE_GLYPH
:
3241 n
= ns_get_glyph_string_clip_rect
(s
, r
);
3242 ns_focus
(s
->f
, r
, n
);
3244 if (s
->for_overlaps ||
(s
->cmp_from
> 0
3245 && ! s
->first_glyph
->u.cmp.automatic
))
3246 s
->background_filled_p
= 1;
3248 ns_maybe_dumpglyphs_background
3249 (s
, s
->first_glyph
->type == COMPOSITE_GLYPH
);
3251 flags
= s
->hl
== DRAW_CURSOR ? NS_DUMPGLYPH_CURSOR
:
3252 (s
->hl
== DRAW_MOUSE_FACE ? NS_DUMPGLYPH_MOUSEFACE
:
3253 (s
->for_overlaps ? NS_DUMPGLYPH_FOREGROUND
:
3254 NS_DUMPGLYPH_NORMAL
));
3256 if (s
->hl
== DRAW_CURSOR
&& s
->w
->phys_cursor_type
== FILLED_BOX_CURSOR
)
3258 unsigned
long tmp
= NS_FACE_BACKGROUND
(s
->face
);
3259 NS_FACE_BACKGROUND
(s
->face
) = NS_FACE_FOREGROUND
(s
->face
);
3260 NS_FACE_FOREGROUND
(s
->face
) = tmp
;
3264 (s
, 0, s
->nchars
, s
->x
, s
->y
,
3265 (flags
== NS_DUMPGLYPH_NORMAL
&& !s
->background_filled_p
)
3266 || flags
== NS_DUMPGLYPH_MOUSEFACE
);
3269 NSColor
*col
= (NS_FACE_FOREGROUND
(s
->face
) != 0
3270 ? ns_lookup_indexed_color
(NS_FACE_FOREGROUND
(s
->face
),
3272 : FRAME_FOREGROUND_COLOR
(s
->f
));
3275 /* Draw underline, overline, strike-through. */
3276 ns_draw_text_decoration
(s
, s
->face
, col
, s
->width
, s
->x
);
3279 if (s
->hl
== DRAW_CURSOR
&& s
->w
->phys_cursor_type
== FILLED_BOX_CURSOR
)
3281 unsigned
long tmp
= NS_FACE_BACKGROUND
(s
->face
);
3282 NS_FACE_BACKGROUND
(s
->face
) = NS_FACE_FOREGROUND
(s
->face
);
3283 NS_FACE_FOREGROUND
(s
->face
) = tmp
;
3289 case GLYPHLESS_GLYPH
:
3290 n
= ns_get_glyph_string_clip_rect
(s
, r
);
3291 ns_focus
(s
->f
, r
, n
);
3293 if (s
->for_overlaps ||
(s
->cmp_from
> 0
3294 && ! s
->first_glyph
->u.cmp.automatic
))
3295 s
->background_filled_p
= 1;
3297 ns_maybe_dumpglyphs_background
3298 (s
, s
->first_glyph
->type == COMPOSITE_GLYPH
);
3300 /* Not yet implemented. */
3309 /* Draw box if not done already. */
3310 if (!s
->for_overlaps
&& !box_drawn_p
&& s
->face
->box
!= FACE_NO_BOX
)
3312 n
= ns_get_glyph_string_clip_rect
(s
, r
);
3313 ns_focus
(s
->f
, r
, n
);
3314 ns_dumpglyphs_box_or_relief
(s
);
3323 /* ==========================================================================
3327 ========================================================================== */
3331 ns_send_appdefined
(int value
)
3332 /* --------------------------------------------------------------------------
3333 Internal: post an appdefined event which EmacsApp-sendEvent will
3334 recognize and take as a command to halt the event loop.
3335 -------------------------------------------------------------------------- */
3337 /*NSTRACE (ns_send_appdefined); */
3339 #ifdef NS_IMPL_GNUSTEP
3340 // GNUStep needs postEvent to happen on the main thread.
3341 if (! [[NSThread currentThread
] isMainThread
])
3343 EmacsApp
*app
= (EmacsApp
*)NSApp
;
3344 app
->nextappdefined
= value
;
3345 [app performSelectorOnMainThread
:@selector
(sendFromMainThread
:)
3352 /* Only post this event if we haven't already posted one. This will end
3353 the [NXApp run] main loop after having processed all events queued at
3355 if (send_appdefined
)
3359 /* We only need one NX_APPDEFINED event to stop NXApp from running. */
3360 send_appdefined
= NO
;
3362 /* Don't need wakeup timer any more */
3365 [timed_entry invalidate
];
3366 [timed_entry release
];
3370 nxev
= [NSEvent otherEventWithType
: NSApplicationDefined
3371 location
: NSMakePoint
(0, 0)
3374 windowNumber
: [[NSApp mainWindow
] windowNumber
]
3375 context
: [NSApp context
]
3380 /* Post an application defined event on the event queue. When this is
3381 received the [NXApp run] will return, thus having processed all
3382 events which are currently queued. */
3383 [NSApp postEvent
: nxev atStart
: NO
];
3387 #ifdef HAVE_NATIVE_FS
3391 Lisp_Object frame
, tail
;
3393 if (ns_last_use_native_fullscreen
== ns_use_native_fullscreen
)
3396 ns_last_use_native_fullscreen
= ns_use_native_fullscreen
;
3398 FOR_EACH_FRAME
(tail
, frame
)
3400 struct frame
*f
= XFRAME
(frame
);
3403 EmacsView
*view = FRAME_NS_VIEW
(f
);
3404 [view updateCollectionBehaviour
];
3410 /* GNUStep and OSX <= 10.4 does not have cancelTracking. */
3411 #
if defined
(NS_IMPL_COCOA
) && \
3412 MAC_OS_X_VERSION_MAX_ALLOWED
>= MAC_OS_X_VERSION_10_5
3413 /* Check if menu open should be cancelled or continued as normal. */
3415 ns_check_menu_open
(NSMenu
*menu)
3417 /* Click in menu bar? */
3418 NSArray
*a
= [[NSApp mainMenu
] itemArray
];
3422 if (menu == nil
) // Menu tracking ended.
3424 if (menu_will_open_state
== MENU_OPENING
)
3425 menu_will_open_state
= MENU_NONE
;
3429 for (i
= 0; ! found
&& i
< [a count
]; i
++)
3430 found
= menu == [[a objectAtIndex
:i
] submenu
];
3433 if (menu_will_open_state
== MENU_NONE
&& emacs_event
)
3435 NSEvent
*theEvent
= [NSApp currentEvent
];
3436 struct frame
*emacsframe
= SELECTED_FRAME
();
3438 [menu cancelTracking
];
3439 menu_will_open_state
= MENU_PENDING
;
3440 emacs_event
->kind
= MENU_BAR_ACTIVATE_EVENT
;
3441 EV_TRAILER
(theEvent
);
3443 CGEventRef ourEvent
= CGEventCreate
(NULL);
3444 menu_mouse_point
= CGEventGetLocation
(ourEvent
);
3445 CFRelease
(ourEvent
);
3447 else if (menu_will_open_state
== MENU_OPENING
)
3449 menu_will_open_state
= MENU_NONE
;
3454 /* Redo saved menu click if state is MENU_PENDING. */
3456 ns_check_pending_open_menu
()
3458 if (menu_will_open_state
== MENU_PENDING
)
3460 CGEventSourceRef source
3461 = CGEventSourceCreate
(kCGEventSourceStateHIDSystemState
);
3463 CGEventRef event
= CGEventCreateMouseEvent
(source
,
3464 kCGEventLeftMouseDown
,
3466 kCGMouseButtonLeft
);
3467 CGEventSetType
(event
, kCGEventLeftMouseDown
);
3468 CGEventPost
(kCGHIDEventTap
, event
);
3472 menu_will_open_state
= MENU_OPENING
;
3475 #endif
/* NS_IMPL_COCOA) && >= MAC_OS_X_VERSION_10_5 */
3478 ns_read_socket
(struct terminal *terminal, struct input_event
*hold_quit
)
3479 /* --------------------------------------------------------------------------
3480 External (hook): Post an event to ourself and keep reading events until
3481 we read it back again. In effect process all events which were waiting.
3482 From 21+ we have to manage the event buffer ourselves.
3483 -------------------------------------------------------------------------- */
3485 struct input_event ev
;
3488 /* NSTRACE (ns_read_socket); */
3490 #ifdef HAVE_NATIVE_FS
3494 if ([NSApp modalWindow
] != nil
)
3497 if (hold_event_q.nr
> 0)
3500 for (i
= 0; i
< hold_event_q.nr
; ++i
)
3501 kbd_buffer_store_event_hold
(&hold_event_q.q
[i
], hold_quit
);
3502 hold_event_q.nr
= 0;
3507 n_emacs_events_pending
= 0;
3510 q_event_ptr
= hold_quit
;
3512 /* we manage autorelease pools by allocate/reallocate each time around
3513 the loop; strict nesting is occasionally violated but seems not to
3514 matter.. earlier methods using full nesting caused major memory leaks */
3515 [outerpool release
];
3516 outerpool
= [[NSAutoreleasePool alloc
] init
];
3518 /* If have pending open-file requests, attend to the next one of those. */
3519 if (ns_pending_files
&& [ns_pending_files count
] != 0
3520 && [(EmacsApp
*)NSApp openFile
: [ns_pending_files objectAtIndex
: 0]])
3522 [ns_pending_files removeObjectAtIndex
: 0];
3524 /* Deal with pending service requests. */
3525 else if (ns_pending_service_names
&& [ns_pending_service_names count
] != 0
3527 NSApp fulfillService
: [ns_pending_service_names objectAtIndex
: 0]
3528 withArg
: [ns_pending_service_args objectAtIndex
: 0]])
3530 [ns_pending_service_names removeObjectAtIndex
: 0];
3531 [ns_pending_service_args removeObjectAtIndex
: 0];
3535 /* Run and wait for events. We must always send one NX_APPDEFINED event
3536 to ourself, otherwise [NXApp run] will never exit. */
3537 send_appdefined
= YES
;
3538 ns_send_appdefined
(-1);
3540 if (++apploopnr
!= 1)
3548 nevents
= n_emacs_events_pending
;
3549 n_emacs_events_pending
= 0;
3550 emacs_event
= q_event_ptr
= NULL;
3558 ns_select
(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
3559 fd_set
*exceptfds
, struct timespec const
*timeout
,
3560 sigset_t const
*sigmask
)
3561 /* --------------------------------------------------------------------------
3562 Replacement for select, checking for events
3563 -------------------------------------------------------------------------- */
3567 struct input_event event
;
3570 /* NSTRACE (ns_select); */
3572 #ifdef HAVE_NATIVE_FS
3576 if (hold_event_q.nr
> 0)
3578 /* We already have events pending. */
3584 for (k
= 0; k
< nfds
+1; k
++)
3586 if (readfds
&& FD_ISSET
(k
, readfds
)) ++nr
;
3587 if (writefds
&& FD_ISSET
(k
, writefds
)) ++nr
;
3591 ||
(timeout
&& timeout
->tv_sec
== 0 && timeout
->tv_nsec
== 0))
3592 return pselect
(nfds
, readfds
, writefds
, exceptfds
, timeout
, sigmask
);
3594 [outerpool release
];
3595 outerpool
= [[NSAutoreleasePool alloc
] init
];
3598 send_appdefined
= YES
;
3601 pthread_mutex_lock
(&select_mutex
);
3606 select_readfds
= *readfds
;
3607 select_valid
+= SELECT_HAVE_READ
;
3611 select_writefds
= *writefds
;
3612 select_valid
+= SELECT_HAVE_WRITE
;
3617 select_timeout
= *timeout
;
3618 select_valid
+= SELECT_HAVE_TMO
;
3621 pthread_mutex_unlock
(&select_mutex
);
3623 /* Inform fd_handler that select should be called */
3625 emacs_write_sig
(selfds
[1], &c
, 1);
3627 else if (nr
== 0 && timeout
)
3629 /* No file descriptor, just a timeout, no need to wake fd_handler */
3630 double time
= timespectod
(*timeout
);
3631 timed_entry
= [[NSTimer scheduledTimerWithTimeInterval
: time
3634 @selector
(timeout_handler
:)
3639 else /* No timeout and no file descriptors, can this happen? */
3641 /* Send appdefined so we exit from the loop */
3642 ns_send_appdefined
(-1);
3647 emacs_event
= &event
;
3648 if (++apploopnr
!= 1)
3655 if (nr
> 0 && readfds
)
3658 emacs_write_sig
(selfds
[1], &c
, 1);
3662 t
= last_appdefined_event_data
;
3664 if (t
!= NO_APPDEFINED_DATA
)
3666 last_appdefined_event_data
= NO_APPDEFINED_DATA
;
3670 /* The NX_APPDEFINED event we received was a timeout. */
3675 /* The NX_APPDEFINED event we received was the result of
3676 at least one real input event arriving. */
3682 /* Received back from select () in fd_handler; copy the results */
3683 pthread_mutex_lock
(&select_mutex
);
3684 if (readfds
) *readfds
= select_readfds
;
3685 if (writefds
) *writefds
= select_writefds
;
3686 pthread_mutex_unlock
(&select_mutex
);
3701 /* ==========================================================================
3705 ========================================================================== */
3709 ns_set_vertical_scroll_bar
(struct window
*window
,
3710 int portion
, int whole
, int position
)
3711 /* --------------------------------------------------------------------------
3712 External (hook): Update or add scrollbar
3713 -------------------------------------------------------------------------- */
3717 struct frame
*f
= XFRAME
(WINDOW_FRAME
(window
));
3718 EmacsView
*view = FRAME_NS_VIEW
(f
);
3719 int window_y
, window_height
;
3720 int top
, left
, height
, width
, sb_width
, sb_left
;
3722 BOOL fringe_extended_p
;
3724 /* optimization; display engine sends WAY too many of these.. */
3725 if (!NILP
(window
->vertical_scroll_bar
))
3727 bar = XNS_SCROLL_BAR
(window
->vertical_scroll_bar
);
3728 if ([bar checkSamePosition
: position portion
: portion whole
: whole
])
3730 if (view->scrollbarsNeedingUpdate
== 0)
3732 if (!windows_or_buffers_changed
)
3736 view->scrollbarsNeedingUpdate
--;
3740 NSTRACE
(ns_set_vertical_scroll_bar
);
3742 /* Get dimensions. */
3743 window_box
(window
, ANY_AREA
, 0, &window_y
, 0, &window_height
);
3745 height
= window_height
;
3746 width
= WINDOW_CONFIG_SCROLL_BAR_COLS
(window
) * FRAME_COLUMN_WIDTH
(f
);
3747 left
= WINDOW_SCROLL_BAR_AREA_X
(window
);
3749 /* allow for displaying a skinnier scrollbar than char area allotted */
3750 sb_width
= (WINDOW_CONFIG_SCROLL_BAR_WIDTH
(window
) > 0) ?
3751 WINDOW_CONFIG_SCROLL_BAR_WIDTH
(window
) : width
;
3754 r
= NSMakeRect
(sb_left
, top
, sb_width
, height
);
3755 /* the parent view is flipped, so we need to flip y value */
3757 r.origin.y
= (v.
size.height
- r.
size.height
- r.origin.y
);
3759 fringe_extended_p
= WINDOW_FRINGE_EXTENDED_P
(window
);
3761 XSETWINDOW
(win
, window
);
3764 /* we want at least 5 lines to display a scrollbar */
3765 if (WINDOW_TOTAL_LINES
(window
) < 5)
3767 if (!NILP
(window
->vertical_scroll_bar
))
3769 bar = XNS_SCROLL_BAR
(window
->vertical_scroll_bar
);
3770 [bar removeFromSuperview
];
3771 wset_vertical_scroll_bar
(window
, Qnil
);
3773 ns_clear_frame_area
(f
, sb_left
, top
, width
, height
);
3778 if (NILP
(window
->vertical_scroll_bar
))
3780 if (width
> 0 && height
> 0)
3782 if (fringe_extended_p
)
3783 ns_clear_frame_area
(f
, sb_left
, top
, sb_width
, height
);
3785 ns_clear_frame_area
(f
, left
, top
, width
, height
);
3788 bar = [[EmacsScroller alloc
] initFrame
: r window
: win
];
3789 wset_vertical_scroll_bar
(window
, make_save_ptr
(bar));
3794 bar = XNS_SCROLL_BAR
(window
->vertical_scroll_bar
);
3795 oldRect
= [bar frame
];
3796 r.
size.width
= oldRect.
size.width
;
3797 if (FRAME_LIVE_P
(f
) && !NSEqualRects
(oldRect
, r
))
3799 if (oldRect.origin.x
!= r.origin.x
)
3800 ns_clear_frame_area
(f
, sb_left
, top
, width
, height
);
3805 [bar setPosition
: position portion
: portion whole
: whole
];
3811 ns_condemn_scroll_bars
(struct frame
*f
)
3812 /* --------------------------------------------------------------------------
3813 External (hook): arrange for all frame's scrollbars to be removed
3814 at next call to judge_scroll_bars, except for those redeemed.
3815 -------------------------------------------------------------------------- */
3819 NSArray
*subviews
= [[FRAME_NS_VIEW
(f
) superview
] subviews
];
3821 NSTRACE
(ns_condemn_scroll_bars
);
3823 for (i
=[subviews count
]-1; i
>= 0; i
--)
3825 view = [subviews objectAtIndex
: i
];
3826 if ([view isKindOfClass
: [EmacsScroller
class]])
3833 ns_redeem_scroll_bar
(struct window
*window
)
3834 /* --------------------------------------------------------------------------
3835 External (hook): arrange to spare this window's scrollbar
3836 at next call to judge_scroll_bars.
3837 -------------------------------------------------------------------------- */
3840 NSTRACE
(ns_redeem_scroll_bar
);
3841 if (!NILP
(window
->vertical_scroll_bar
))
3843 bar = XNS_SCROLL_BAR
(window
->vertical_scroll_bar
);
3850 ns_judge_scroll_bars
(struct frame
*f
)
3851 /* --------------------------------------------------------------------------
3852 External (hook): destroy all scrollbars on frame that weren't
3853 redeemed after call to condemn_scroll_bars.
3854 -------------------------------------------------------------------------- */
3858 EmacsView
*eview
= FRAME_NS_VIEW
(f
);
3859 NSArray
*subviews
= [[eview superview
] subviews
];
3862 NSTRACE
(ns_judge_scroll_bars
);
3863 for (i
= [subviews count
]-1; i
>= 0; --i
)
3865 view = [subviews objectAtIndex
: i
];
3866 if (![view isKindOfClass
: [EmacsScroller
class]]) continue
;
3872 [eview updateFrameSize
: NO
];
3875 /* ==========================================================================
3879 ========================================================================== */
3882 x_display_pixel_height
(struct ns_display_info
*dpyinfo
)
3884 NSArray
*screens
= [NSScreen screens
];
3885 NSEnumerator
*enumerator
= [screens objectEnumerator
];
3890 while ((screen
= [enumerator nextObject
]) != nil
)
3891 frame
= NSUnionRect
(frame
, [screen frame
]);
3893 return NSHeight
(frame
);
3897 x_display_pixel_width
(struct ns_display_info
*dpyinfo
)
3899 NSArray
*screens
= [NSScreen screens
];
3900 NSEnumerator
*enumerator
= [screens objectEnumerator
];
3905 while ((screen
= [enumerator nextObject
]) != nil
)
3906 frame
= NSUnionRect
(frame
, [screen frame
]);
3908 return NSWidth
(frame
);
3912 static Lisp_Object ns_string_to_lispmod
(const
char *s
)
3913 /* --------------------------------------------------------------------------
3914 Convert modifier name to lisp symbol
3915 -------------------------------------------------------------------------- */
3917 if (!strncmp
(SSDATA
(SYMBOL_NAME
(Qmeta
)), s
, 10))
3919 else if (!strncmp
(SSDATA
(SYMBOL_NAME
(Qsuper
)), s
, 10))
3921 else if (!strncmp
(SSDATA
(SYMBOL_NAME
(Qcontrol
)), s
, 10))
3923 else if (!strncmp
(SSDATA
(SYMBOL_NAME
(Qalt
)), s
, 10))
3925 else if (!strncmp
(SSDATA
(SYMBOL_NAME
(Qhyper
)), s
, 10))
3927 else if (!strncmp
(SSDATA
(SYMBOL_NAME
(Qnone
)), s
, 10))
3935 ns_default
(const
char *parameter
, Lisp_Object
*result
,
3936 Lisp_Object yesval
, Lisp_Object noval
,
3937 BOOL is_float
, BOOL is_modstring
)
3938 /* --------------------------------------------------------------------------
3939 Check a parameter value in user's preferences
3940 -------------------------------------------------------------------------- */
3942 const
char *value
= ns_get_defaults_value
(parameter
);
3948 if (c_strcasecmp
(value
, "YES"
) == 0)
3950 else if (c_strcasecmp
(value
, "NO"
) == 0)
3952 else if (is_float
&& (f
= strtod
(value
, &pos
), pos
!= value
))
3953 *result
= make_float
(f
);
3954 else if (is_modstring
&& value
)
3955 *result
= ns_string_to_lispmod
(value
);
3956 else fprintf (stderr
,
3957 "Bad value
for default
\"%s\": \"%s\"\n", parameter, value);
3963 ns_initialize_display_info
(struct ns_display_info
*dpyinfo
)
3964 /* --------------------------------------------------------------------------
3965 Initialize global info and storage for display.
3966 -------------------------------------------------------------------------- */
3968 NSScreen
*screen
= [NSScreen mainScreen
];
3969 NSWindowDepth depth
= [screen depth
];
3971 dpyinfo
->resx
= 72.27; /* used 75.0, but this makes pt == pixel, expected */
3972 dpyinfo
->resy
= 72.27;
3973 dpyinfo
->color_p
= ![NSDeviceWhiteColorSpace isEqualToString
:
3974 NSColorSpaceFromDepth
(depth
)]
3975 && ![NSCalibratedWhiteColorSpace isEqualToString
:
3976 NSColorSpaceFromDepth
(depth
)];
3977 dpyinfo
->n_planes
= NSBitsPerPixelFromDepth
(depth
);
3978 dpyinfo
->image_cache
= make_image_cache
();
3979 dpyinfo
->color_table
= xmalloc
(sizeof
*dpyinfo
->color_table
);
3980 dpyinfo
->color_table
->colors
= NULL;
3981 dpyinfo
->root_window
= 42; /* a placeholder.. */
3982 dpyinfo
->x_highlight_frame
= dpyinfo
->x_focus_frame
= NULL;
3983 dpyinfo
->n_fonts
= 0;
3984 dpyinfo
->smallest_font_height
= 1;
3985 dpyinfo
->smallest_char_width
= 1;
3987 reset_mouse_highlight
(&dpyinfo
->mouse_highlight
);
3991 /* This and next define (many of the) public functions in this file. */
3992 /* x_... are generic versions in xdisp.c that we, and other terms, get away
3993 with using despite presence in the "system dependent" redisplay
3994 interface. In addition, many of the ns_ methods have code that is
3995 shared with all terms, indicating need for further refactoring. */
3996 extern frame_parm_handler ns_frame_parm_handlers
[];
3997 static
struct redisplay_interface ns_redisplay_interface
=
3999 ns_frame_parm_handlers
,
4003 x_clear_end_of_line
,
4005 ns_after_update_window_line
,
4006 ns_update_window_begin
,
4007 ns_update_window_end
,
4008 0, /* flush_display */
4009 x_clear_window_mouse_face
,
4010 x_get_glyph_overhangs
,
4011 x_fix_overlapping_area
,
4012 ns_draw_fringe_bitmap
,
4013 0, /* define_fringe_bitmap */ /* FIXME: simplify ns_draw_fringe_bitmap */
4014 0, /* destroy_fringe_bitmap */
4015 ns_compute_glyph_string_overhangs
,
4016 ns_draw_glyph_string
,
4017 ns_define_frame_cursor
,
4018 ns_clear_frame_area
,
4019 ns_draw_window_cursor
,
4020 ns_draw_vertical_window_border
,
4021 ns_shift_glyphs_for_insert
4026 ns_delete_display
(struct ns_display_info
*dpyinfo
)
4032 /* This function is called when the last frame on a display is deleted. */
4034 ns_delete_terminal
(struct terminal *terminal)
4036 struct ns_display_info
*dpyinfo
= terminal->display_info.ns
;
4038 /* Protect against recursive calls. delete_frame in
4039 delete_terminal calls us back when it deletes our last frame. */
4040 if (!terminal->name
)
4045 x_destroy_all_bitmaps
(dpyinfo
);
4046 ns_delete_display
(dpyinfo
);
4051 static
struct terminal *
4052 ns_create_terminal
(struct ns_display_info
*dpyinfo
)
4053 /* --------------------------------------------------------------------------
4054 Set up use of NS before we make the first connection.
4055 -------------------------------------------------------------------------- */
4057 struct terminal *terminal;
4059 NSTRACE
(ns_create_terminal
);
4061 terminal = create_terminal
();
4063 terminal->type = output_ns
;
4064 terminal->display_info.ns
= dpyinfo
;
4065 dpyinfo
->terminal = terminal;
4067 terminal->rif
= &ns_redisplay_interface
;
4069 terminal->clear_frame_hook
= ns_clear_frame
;
4070 terminal->ins_del_lines_hook
= 0; /* XXX vestigial? */
4071 terminal->delete_glyphs_hook
= 0; /* XXX vestigial? */
4072 terminal->ring_bell_hook
= ns_ring_bell
;
4073 terminal->reset_terminal_modes_hook
= NULL;
4074 terminal->set_terminal_modes_hook
= NULL;
4075 terminal->update_begin_hook
= ns_update_begin
;
4076 terminal->update_end_hook
= ns_update_end
;
4077 terminal->set_terminal_window_hook
= NULL; /* XXX vestigial? */
4078 terminal->read_socket_hook
= ns_read_socket
;
4079 terminal->frame_up_to_date_hook
= ns_frame_up_to_date
;
4080 terminal->mouse_position_hook
= ns_mouse_position
;
4081 terminal->frame_rehighlight_hook
= ns_frame_rehighlight
;
4082 terminal->frame_raise_lower_hook
= ns_frame_raise_lower
;
4084 terminal->fullscreen_hook
= ns_fullscreen_hook
;
4086 terminal->set_vertical_scroll_bar_hook
= ns_set_vertical_scroll_bar
;
4087 terminal->condemn_scroll_bars_hook
= ns_condemn_scroll_bars
;
4088 terminal->redeem_scroll_bar_hook
= ns_redeem_scroll_bar
;
4089 terminal->judge_scroll_bars_hook
= ns_judge_scroll_bars
;
4091 terminal->delete_frame_hook
= x_destroy_window
;
4092 terminal->delete_terminal_hook
= ns_delete_terminal
;
4094 terminal->scroll_region_ok
= 1;
4095 terminal->char_ins_del_ok
= 1;
4096 terminal->line_ins_del_ok
= 1;
4097 terminal->memory_below_frame
= 0;
4103 struct ns_display_info
*
4104 ns_term_init
(Lisp_Object display_name
)
4105 /* --------------------------------------------------------------------------
4106 Start the Application and get things rolling.
4107 -------------------------------------------------------------------------- */
4109 struct terminal *terminal;
4110 struct ns_display_info
*dpyinfo
;
4111 static int ns_initialized
= 0;
4114 if (ns_initialized
) return x_display_list
;
4117 NSTRACE
(ns_term_init
);
4119 [outerpool release
];
4120 outerpool
= [[NSAutoreleasePool alloc
] init
];
4122 /* count object allocs (About, click icon); on OS X use ObjectAlloc tool */
4123 /*GSDebugAllocationActive (YES); */
4127 Fset_input_interrupt_mode
(Qnil
);
4129 if (selfds
[0] == -1)
4131 if (emacs_pipe
(selfds
) != 0)
4133 fprintf (stderr
, "Failed to create pipe
: %s\n",
4134 emacs_strerror
(errno
));
4138 fcntl
(selfds
[0], F_SETFL
, O_NONBLOCK|fcntl
(selfds
[0], F_GETFL
));
4139 FD_ZERO
(&select_readfds
);
4140 FD_ZERO
(&select_writefds
);
4141 pthread_mutex_init
(&select_mutex
, NULL);
4144 ns_pending_files
= [[NSMutableArray alloc
] init
];
4145 ns_pending_service_names
= [[NSMutableArray alloc
] init
];
4146 ns_pending_service_args
= [[NSMutableArray alloc
] init
];
4148 /* Start app and create the main menu, window, view.
4149 Needs to be here because ns_initialize_display_info () uses AppKit classes.
4150 The view will then ask the NSApp to stop and return to Emacs. */
4151 [EmacsApp sharedApplication
];
4154 [NSApp setDelegate
: NSApp
];
4156 /* Start the select thread. */
4157 [NSThread detachNewThreadSelector
:@selector
(fd_handler
:)
4161 /* debugging: log all notifications */
4162 /* [[NSNotificationCenter defaultCenter] addObserver: NSApp
4163 selector: @selector (logNotification:)
4164 name: nil object: nil]; */
4166 dpyinfo
= xzalloc
(sizeof
*dpyinfo
);
4168 ns_initialize_display_info
(dpyinfo
);
4169 terminal = ns_create_terminal
(dpyinfo
);
4171 terminal->kboard
= allocate_kboard
(Qns
);
4172 /* Don't let the initial kboard remain current longer than necessary.
4173 That would cause problems if a file loaded on startup tries to
4174 prompt in the mini-buffer. */
4175 if (current_kboard
== initial_kboard
)
4176 current_kboard
= terminal->kboard
;
4177 terminal->kboard
->reference_count
++;
4179 dpyinfo
->next
= x_display_list
;
4180 x_display_list
= dpyinfo
;
4182 /* Put it on ns_display_name_list */
4183 ns_display_name_list
= Fcons
(Fcons
(display_name
, Qnil
),
4184 ns_display_name_list
);
4185 dpyinfo
->name_list_element
= XCAR
(ns_display_name_list
);
4187 terminal->name
= xstrdup
(SSDATA
(display_name
));
4191 if (!inhibit_x_resources
)
4193 ns_default
("GSFontAntiAlias"
, &ns_antialias_text
,
4196 /* this is a standard variable */
4197 ns_default
("AppleAntiAliasingThreshold"
, &tmp
,
4198 make_float
(10.0), make_float
(6.0), YES
, NO
);
4199 ns_antialias_threshold
= NILP
(tmp
) ?
10.0 : XFLOATINT
(tmp
);
4203 NSColorList
*cl
= [NSColorList colorListNamed
: @"Emacs"
];
4207 Lisp_Object color_file
, color_map
, color
;
4211 color_file
= Fexpand_file_name
(build_string
("rgb.txt"
),
4212 Fsymbol_value
(intern
("data
-directory"
)));
4214 color_map
= Fx_load_color_file
(color_file
);
4215 if (NILP
(color_map
))
4216 fatal
("Could not read
%s.\n", SDATA (color_file));
4218 cl
= [[NSColorList alloc
] initWithName
: @"Emacs"
];
4219 for ( ; CONSP
(color_map
); color_map
= XCDR
(color_map
))
4221 color
= XCAR
(color_map
);
4222 name
= SSDATA
(XCAR
(color
));
4223 c
= XINT
(XCDR
(color
));
4225 [NSColor colorWithCalibratedRed
: RED_FROM_ULONG
(c
) / 255.0
4226 green
: GREEN_FROM_ULONG
(c
) / 255.0
4227 blue
: BLUE_FROM_ULONG
(c
) / 255.0
4229 forKey
: [NSString stringWithUTF8String
: name
]];
4231 [cl writeToFile
: nil
];
4236 #ifdef NS_IMPL_GNUSTEP
4237 Vwindow_system_version
= build_string
(gnustep_base_version
);
4239 /*PSnextrelease (128, c); */
4240 char c
[DBL_BUFSIZE_BOUND
];
4241 int len
= dtoastr
(c
, sizeof c
, 0, 0, NSAppKitVersionNumber
);
4242 Vwindow_system_version
= make_unibyte_string
(c
, len
);
4246 delete_keyboard_wait_descriptor
(0);
4248 ns_app_name
= [[NSProcessInfo processInfo
] processName
];
4250 /* Set up OS X app menu */
4251 #ifdef NS_IMPL_COCOA
4255 /* set up the application menu */
4256 svcsMenu
= [[EmacsMenu alloc
] initWithTitle
: @"Services"
];
4257 [svcsMenu setAutoenablesItems
: NO
];
4258 appMenu
= [[EmacsMenu alloc
] initWithTitle
: @"Emacs"
];
4259 [appMenu setAutoenablesItems
: NO
];
4260 mainMenu
= [[EmacsMenu alloc
] initWithTitle
: @""
];
4261 dockMenu
= [[EmacsMenu alloc
] initWithTitle
: @""
];
4263 [appMenu insertItemWithTitle
: @"About Emacs"
4264 action
: @selector
(orderFrontStandardAboutPanel
:)
4267 [appMenu insertItem
: [NSMenuItem separatorItem
] atIndex
: 1];
4268 [appMenu insertItemWithTitle
: @"Preferences..."
4269 action
: @selector
(showPreferencesWindow
:)
4272 [appMenu insertItem
: [NSMenuItem separatorItem
] atIndex
: 3];
4273 item
= [appMenu insertItemWithTitle
: @"Services"
4274 action
: @selector
(menuDown
:)
4277 [appMenu setSubmenu
: svcsMenu forItem
: item
];
4278 [appMenu insertItem
: [NSMenuItem separatorItem
] atIndex
: 5];
4279 [appMenu insertItemWithTitle
: @"Hide Emacs"
4280 action
: @selector
(hide
:)
4283 item
= [appMenu insertItemWithTitle
: @"Hide Others"
4284 action
: @selector
(hideOtherApplications
:)
4287 [item setKeyEquivalentModifierMask
: NSCommandKeyMask | NSAlternateKeyMask
];
4288 [appMenu insertItem
: [NSMenuItem separatorItem
] atIndex
: 8];
4289 [appMenu insertItemWithTitle
: @"
Quit Emacs"
4290 action
: @selector
(terminate
:)
4294 item
= [mainMenu insertItemWithTitle
: ns_app_name
4295 action
: @selector
(menuDown
:)
4298 [mainMenu setSubmenu
: appMenu forItem
: item
];
4299 [dockMenu insertItemWithTitle
: @"New Frame"
4300 action
: @selector
(newFrame
:)
4304 [NSApp setMainMenu
: mainMenu
];
4305 [NSApp setAppleMenu
: appMenu
];
4306 [NSApp setServicesMenu
: svcsMenu
];
4307 /* Needed at least on Cocoa, to get dock menu to show windows */
4308 [NSApp setWindowsMenu
: [[NSMenu alloc
] init
]];
4310 [[NSNotificationCenter defaultCenter
]
4311 addObserver
: mainMenu
4312 selector
: @selector
(trackingNotification
:)
4313 name
: NSMenuDidBeginTrackingNotification object
: mainMenu
];
4314 [[NSNotificationCenter defaultCenter
]
4315 addObserver
: mainMenu
4316 selector
: @selector
(trackingNotification
:)
4317 name
: NSMenuDidEndTrackingNotification object
: mainMenu
];
4319 #endif
/* MAC OS X menu setup */
4321 /* Register our external input/output types, used for determining
4322 applicable services and also drag/drop eligibility. */
4323 ns_send_types
= [[NSArray arrayWithObjects
: NSStringPboardType
, nil
] retain
];
4324 ns_return_types
= [[NSArray arrayWithObjects
: NSStringPboardType
, nil
]
4326 ns_drag_types
= [[NSArray arrayWithObjects
:
4328 NSTabularTextPboardType
,
4329 NSFilenamesPboardType
,
4332 NSFontPboardType
, nil
] retain
];
4334 /* If fullscreen is in init/default-frame-alist, focus isn't set
4335 right for fullscreen windows, so set this. */
4336 [NSApp activateIgnoringOtherApps
:YES
];
4339 ns_do_open_file
= YES
;
4341 #ifdef NS_IMPL_GNUSTEP
4342 /* GNUstep steals SIGCHLD for use in NSTask, but we don't use NSTask.
4343 We must re-catch it so subprocess works. */
4344 catch_child_signal
();
4351 ns_term_shutdown
(int sig
)
4353 [[NSUserDefaults standardUserDefaults
] synchronize
];
4355 /* code not reached in emacs.c after this is called by shut_down_emacs: */
4356 if (STRINGP
(Vauto_save_list_file_name
))
4357 unlink
(SSDATA
(Vauto_save_list_file_name
));
4359 if (sig
== 0 || sig
== SIGTERM
)
4361 [NSApp terminate
: NSApp
];
4363 else // force a stack
trace to happen
4370 /* ==========================================================================
4372 EmacsApp implementation
4374 ========================================================================== */
4377 @implementation EmacsApp
4379 - (void
)logNotification
: (NSNotification
*)notification
4381 const
char *name
= [[notification name
] UTF8String
];
4382 if (!strstr
(name
, "Update"
) && !strstr
(name
, "NSMenu"
)
4383 && !strstr
(name
, "WindowNumber"
))
4384 NSLog
(@"notification
: '%@'"
, [notification name
]);
4388 - (void
)sendEvent
: (NSEvent
*)theEvent
4389 /* --------------------------------------------------------------------------
4390 Called when NSApp is running for each event received. Used to stop
4391 the loop when we choose, since there's no way to just run one iteration.
4392 -------------------------------------------------------------------------- */
4394 int
type = [theEvent
type];
4395 NSWindow
*window
= [theEvent window
];
4397 /* NSTRACE (sendEvent); */
4398 /*fprintf (stderr, "received event of type %d\t%d\n", type);*/
4400 #ifdef NS_IMPL_GNUSTEP
4401 // Keyboard events aren
't propagated to file dialogs for some reason.
4402 if ([NSApp modalWindow] != nil &&
4403 (type == NSKeyDown || type == NSKeyUp || type == NSFlagsChanged))
4405 [[NSApp modalWindow] sendEvent: theEvent];
4410 if (type == NSApplicationDefined)
4412 switch ([theEvent data2])
4414 #ifdef NS_IMPL_COCOA
4415 case NSAPP_DATA2_RUNASSCRIPT:
4420 case NSAPP_DATA2_RUNFILEDIALOG:
4421 ns_run_file_dialog ();
4427 if (type == NSCursorUpdate && window == nil)
4429 fprintf (stderr, "Dropping external cursor update event.\n");
4433 if (type == NSApplicationDefined)
4435 /* Events posted by ns_send_appdefined interrupt the run loop here.
4436 But, if a modal window is up, an appdefined can still come through,
4437 (e.g., from a makeKeyWindow event) but stopping self also stops the
4438 modal loop. Just defer it until later. */
4439 if ([NSApp modalWindow] == nil)
4441 last_appdefined_event_data = [theEvent data1];
4446 send_appdefined = YES;
4451 #ifdef NS_IMPL_COCOA
4452 /* If no dialog and none of our frames have focus and it is a move, skip it.
4453 It is a mouse move in an auxiliary menu, i.e. on the top right on OSX,
4454 such as Wifi, sound, date or similar.
4455 This prevents "spooky" highlighting in the frame under the menu. */
4456 if (type == NSMouseMoved && [NSApp modalWindow] == nil)
4458 struct ns_display_info *di;
4459 BOOL has_focus = NO;
4460 for (di = x_display_list; ! has_focus && di; di = di->next)
4461 has_focus = di->x_focus_frame != 0;
4467 [super sendEvent: theEvent];
4471 - (void)showPreferencesWindow: (id)sender
4473 struct frame *emacsframe = SELECTED_FRAME ();
4474 NSEvent *theEvent = [NSApp currentEvent];
4478 emacs_event->kind = NS_NONKEY_EVENT;
4479 emacs_event->code = KEY_NS_SHOW_PREFS;
4480 emacs_event->modifiers = 0;
4481 EV_TRAILER (theEvent);
4485 - (void)newFrame: (id)sender
4487 struct frame *emacsframe = SELECTED_FRAME ();
4488 NSEvent *theEvent = [NSApp currentEvent];
4492 emacs_event->kind = NS_NONKEY_EVENT;
4493 emacs_event->code = KEY_NS_NEW_FRAME;
4494 emacs_event->modifiers = 0;
4495 EV_TRAILER (theEvent);
4499 /* Open a file (used by below, after going into queue read by ns_read_socket) */
4500 - (BOOL) openFile: (NSString *)fileName
4502 struct frame *emacsframe = SELECTED_FRAME ();
4503 NSEvent *theEvent = [NSApp currentEvent];
4508 emacs_event->kind = NS_NONKEY_EVENT;
4509 emacs_event->code = KEY_NS_OPEN_FILE_LINE;
4510 ns_input_file = append2 (ns_input_file, build_string ([fileName UTF8String]));
4511 ns_input_line = Qnil; /* can be start or cons start,end */
4512 emacs_event->modifiers =0;
4513 EV_TRAILER (theEvent);
4519 /* **************************************************************************
4521 EmacsApp delegate implementation
4523 ************************************************************************** */
4525 - (void)applicationDidFinishLaunching: (NSNotification *)notification
4526 /* --------------------------------------------------------------------------
4527 When application is loaded, terminate event loop in ns_term_init
4528 -------------------------------------------------------------------------- */
4530 NSTRACE (applicationDidFinishLaunching);
4531 [NSApp setServicesProvider: NSApp];
4532 ns_send_appdefined (-2);
4536 /* Termination sequences:
4539 MenuBar | File | Exit:
4540 Select Quit from App menubar:
4542 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4545 Select Quit from Dock menu:
4548 Cancel -> Nothing else
4552 KEY_NS_POWER_OFF, (save-buffers-kill-emacs)
4557 - (void) terminate: (id)sender
4559 struct frame *emacsframe = SELECTED_FRAME ();
4564 emacs_event->kind = NS_NONKEY_EVENT;
4565 emacs_event->code = KEY_NS_POWER_OFF;
4566 emacs_event->arg = Qt; /* mark as non-key event */
4567 EV_TRAILER ((id)nil);
4571 - (NSApplicationTerminateReply)applicationShouldTerminate: (id)sender
4575 if (NILP (ns_confirm_quit)) // || ns_shutdown_properly --> TO DO
4576 return NSTerminateNow;
4578 ret = NSRunAlertPanel(ns_app_name,
4579 @"Exit requested. Would you like to Save Buffers and Exit, or Cancel the request?",
4580 @"Save Buffers and Exit", @"Cancel", nil);
4582 if (ret == NSAlertDefaultReturn)
4583 return NSTerminateNow;
4584 else if (ret == NSAlertAlternateReturn)
4585 return NSTerminateCancel;
4586 return NSTerminateNow; /* just in case */
4590 not_in_argv (NSString *arg)
4593 const char *a = [arg UTF8String];
4594 for (k = 1; k < initial_argc; ++k)
4595 if (strcmp (a, initial_argv[k]) == 0) return 0;
4599 /* Notification from the Workspace to open a file */
4600 - (BOOL)application: sender openFile: (NSString *)file
4602 if (ns_do_open_file || not_in_argv (file))
4603 [ns_pending_files addObject: file];
4608 /* Open a file as a temporary file */
4609 - (BOOL)application: sender openTempFile: (NSString *)file
4611 if (ns_do_open_file || not_in_argv (file))
4612 [ns_pending_files addObject: file];
4617 /* Notification from the Workspace to open a file noninteractively (?) */
4618 - (BOOL)application: sender openFileWithoutUI: (NSString *)file
4620 if (ns_do_open_file || not_in_argv (file))
4621 [ns_pending_files addObject: file];
4625 /* Notification from the Workspace to open multiple files */
4626 - (void)application: sender openFiles: (NSArray *)fileList
4628 NSEnumerator *files = [fileList objectEnumerator];
4630 /* Don't open files from the command
line unconditionally
,
4631 Cocoa parses the command
line wrong
, --option value tries to open value
4632 if --option is the last option. */
4633 while ((file
= [files nextObject
]) != nil
)
4634 if (ns_do_open_file || not_in_argv
(file
))
4635 [ns_pending_files addObject
: file
];
4637 [self replyToOpenOrPrint
: NSApplicationDelegateReplySuccess
];
4642 /* Handle dock menu requests. */
4643 - (NSMenu
*)applicationDockMenu
: (NSApplication
*) sender
4649 /* TODO: these may help w/IO switching btwn terminal and NSApp */
4650 - (void
)applicationWillBecomeActive
: (NSNotification
*)notification
4652 //ns_app_active
=YES
;
4654 - (void
)applicationDidBecomeActive
: (NSNotification
*)notification
4656 NSTRACE
(applicationDidBecomeActive
);
4658 //ns_app_active
=YES
;
4660 ns_update_auto_hide_menu_bar
();
4661 // No constraining takes place when the application is not active.
4662 ns_constrain_all_frames
();
4664 - (void
)applicationDidResignActive
: (NSNotification
*)notification
4667 ns_send_appdefined
(-1);
4672 /* ==========================================================================
4674 EmacsApp aux handlers for managing event loop
4676 ========================================================================== */
4679 - (void
)timeout_handler
: (NSTimer
*)timedEntry
4680 /* --------------------------------------------------------------------------
4681 The timeout specified to ns_select has passed.
4682 -------------------------------------------------------------------------- */
4684 /*NSTRACE (timeout_handler); */
4685 ns_send_appdefined
(-2);
4688 #ifdef NS_IMPL_GNUSTEP
4689 - (void
)sendFromMainThread
:(id
)unused
4691 ns_send_appdefined
(nextappdefined
);
4695 - (void
)fd_handler
:(id
)unused
4696 /* --------------------------------------------------------------------------
4697 Check data waiting on file descriptors and terminate if so
4698 -------------------------------------------------------------------------- */
4701 int waiting
= 1, nfds
;
4704 fd_set readfds
, writefds
, *wfds
;
4705 struct timespec timeout
, *tmo
;
4706 NSAutoreleasePool
*pool
= nil
;
4708 /* NSTRACE (fd_handler); */
4713 pool
= [[NSAutoreleasePool alloc
] init
];
4719 FD_SET
(selfds
[0], &fds
);
4720 result
= select
(selfds
[0]+1, &fds
, NULL, NULL, NULL);
4721 if (result
> 0 && read
(selfds
[0], &c
, 1) == 1 && c
== 'g')
4726 pthread_mutex_lock
(&select_mutex
);
4729 if (select_valid
& SELECT_HAVE_READ
)
4730 readfds
= select_readfds
;
4734 if (select_valid
& SELECT_HAVE_WRITE
)
4736 writefds
= select_writefds
;
4741 if (select_valid
& SELECT_HAVE_TMO
)
4743 timeout
= select_timeout
;
4749 pthread_mutex_unlock
(&select_mutex
);
4751 FD_SET
(selfds
[0], &readfds
);
4752 if (selfds
[0] >= nfds
) nfds
= selfds
[0]+1;
4754 result
= pselect
(nfds
, &readfds
, wfds
, NULL, tmo
, NULL);
4757 ns_send_appdefined
(-2);
4758 else if (result
> 0)
4760 if (FD_ISSET
(selfds
[0], &readfds
))
4762 if (read
(selfds
[0], &c
, 1) == 1 && c
== 's')
4767 pthread_mutex_lock
(&select_mutex
);
4768 if (select_valid
& SELECT_HAVE_READ
)
4769 select_readfds
= readfds
;
4770 if (select_valid
& SELECT_HAVE_WRITE
)
4771 select_writefds
= writefds
;
4772 if (select_valid
& SELECT_HAVE_TMO
)
4773 select_timeout
= timeout
;
4774 pthread_mutex_unlock
(&select_mutex
);
4776 ns_send_appdefined
(result
);
4786 /* ==========================================================================
4790 ========================================================================== */
4792 /* called from system: queue for next pass through event loop */
4793 - (void
)requestService
: (NSPasteboard
*)pboard
4794 userData
: (NSString
*)userData
4795 error: (NSString
**)error
4797 [ns_pending_service_names addObject
: userData
];
4798 [ns_pending_service_args addObject
: [NSString stringWithUTF8String
:
4799 SSDATA
(ns_string_from_pasteboard
(pboard
))]];
4803 /* called from ns_read_socket to clear queue */
4804 - (BOOL
)fulfillService
: (NSString
*)name withArg
: (NSString
*)arg
4806 struct frame
*emacsframe
= SELECTED_FRAME
();
4807 NSEvent
*theEvent
= [NSApp currentEvent
];
4812 emacs_event
->kind
= NS_NONKEY_EVENT
;
4813 emacs_event
->code
= KEY_NS_SPI_SERVICE_CALL
;
4814 ns_input_spi_name
= build_string
([name UTF8String
]);
4815 ns_input_spi_arg
= build_string
([arg UTF8String
]);
4816 emacs_event
->modifiers
= EV_MODIFIERS
(theEvent
);
4817 EV_TRAILER
(theEvent
);
4827 /* ==========================================================================
4829 EmacsView implementation
4831 ========================================================================== */
4834 @implementation EmacsView
4836 /* needed to inform when window closed from LISP */
4837 - (void
) setWindowClosing
: (BOOL
)closing
4839 windowClosing
= closing
;
4845 NSTRACE
(EmacsView_dealloc
);
4847 if (fs_state
== FULLSCREEN_BOTH
)
4848 [nonfs_window release
];
4853 /* called on font panel selection */
4854 - (void
)changeFont
: (id
)sender
4856 NSEvent
*e
= [[self window
] currentEvent
];
4857 struct face
*face
= FRAME_DEFAULT_FACE
(emacsframe
);
4858 struct font
*font
= face
->font
;
4863 NSTRACE
(changeFont
);
4868 if (EQ
(font
->driver
->type, Qns
))
4869 nsfont
= ((struct nsfont_info
*)font
)->nsfont
;
4870 #
if MAC_OS_X_VERSION_MAX_ALLOWED
>= MAC_OS_X_VERSION_10_5
4872 nsfont
= (NSFont
*) macfont_get_nsctfont
(font
);
4875 if ((newFont
= [sender convertFont
: nsfont
]))
4877 SET_FRAME_GARBAGED
(emacsframe
); /* now needed as of 2008/10 */
4879 emacs_event
->kind
= NS_NONKEY_EVENT
;
4880 emacs_event
->modifiers
= 0;
4881 emacs_event
->code
= KEY_NS_CHANGE_FONT
;
4883 size = [newFont pointSize
];
4884 ns_input_fontsize
= make_number
(lrint
(size));
4885 ns_input_font
= build_string
([[newFont familyName
] UTF8String
]);
4891 - (BOOL
)acceptsFirstResponder
4893 NSTRACE
(acceptsFirstResponder
);
4898 - (void
)resetCursorRects
4900 NSRect visible
= [self visibleRect
];
4901 NSCursor
*currentCursor
= FRAME_POINTER_TYPE
(emacsframe
);
4902 NSTRACE
(resetCursorRects
);
4904 if (currentCursor
== nil
)
4905 currentCursor
= [NSCursor arrowCursor
];
4907 if (!NSIsEmptyRect
(visible
))
4908 [self addCursorRect
: visible cursor
: currentCursor
];
4909 [currentCursor setOnMouseEntered
: YES
];
4914 /*****************************************************************************/
4915 /* Keyboard handling. */
4918 - (void
)keyDown
: (NSEvent
*)theEvent
4920 Mouse_HLInfo
*hlinfo
= MOUSE_HL_INFO
(emacsframe
);
4922 unsigned fnKeysym
= 0;
4923 static NSMutableArray
*nsEvArray
;
4924 #
if !defined
(NS_IMPL_COCOA
) || MAC_OS_X_VERSION_MAX_ALLOWED
< MAC_OS_X_VERSION_10_6
4925 static BOOL firstTime
= YES
;
4928 unsigned int flags
= [theEvent modifierFlags
];
4932 /* Rhapsody and OS X give up and down events for the arrow keys */
4933 if (ns_fake_keydown
== YES
)
4934 ns_fake_keydown
= NO
;
4935 else if ([theEvent
type] != NSKeyDown
)
4941 if (![[self window
] isKeyWindow
]
4942 && [[theEvent window
] isKindOfClass
: [EmacsWindow
class]]
4943 /* we must avoid an infinite loop here. */
4944 && (EmacsView
*)[[theEvent window
] delegate
] != self
)
4946 /* XXX: There is an occasional condition in which, when Emacs display
4947 updates a different frame from the current one, and temporarily
4948 selects it, then processes some interrupt-driven input
4949 (dispnew.c:3878), OS will send the event to the correct NSWindow, but
4950 for some reason that window has its first responder set to the NSView
4951 most recently updated (I guess), which is not the correct one. */
4952 [(EmacsView
*)[[theEvent window
] delegate
] keyDown
: theEvent
];
4956 if (nsEvArray
== nil
)
4957 nsEvArray
= [[NSMutableArray alloc
] initWithCapacity
: 1];
4959 [NSCursor setHiddenUntilMouseMoves
: YES
];
4961 if (hlinfo
->mouse_face_hidden
&& INTEGERP
(Vmouse_highlight
))
4963 clear_mouse_face
(hlinfo
);
4964 hlinfo
->mouse_face_hidden
= 1;
4967 if (!processingCompose
)
4969 /* When using screen sharing, no left or right information is sent,
4970 so use Left key in those cases. */
4971 int is_left_key
, is_right_key
;
4973 code
= ([[theEvent charactersIgnoringModifiers
] length] == 0) ?
4974 0 : [[theEvent charactersIgnoringModifiers
] characterAtIndex
: 0];
4976 /* (Carbon way: [theEvent keyCode]) */
4978 /* is it a "function key"? */
4979 fnKeysym
= (code
< 0x00ff && (flags
&NSNumericPadKeyMask
))
4980 ? ns_convert_key
([theEvent keyCode
] | NSNumericPadKeyMask
)
4981 : ns_convert_key
(code
);
4985 /* COUNTERHACK: map 'Delete' on upper-right main KB to 'Backspace',
4986 because Emacs treats Delete and KP-Delete same (in simple.el). */
4987 if ((fnKeysym
== 0xFFFF && [theEvent keyCode
] == 0x33)
4988 #ifdef NS_IMPL_GNUSTEP
4989 /* GNUstep uses incompatible keycodes, even for those that are
4990 supposed to be hardware independent. Just check for delete.
4991 Keypad delete does not have keysym 0xFFFF.
4992 See http://savannah.gnu.org/bugs/?25395
4994 ||
(fnKeysym
== 0xFFFF && code
== 127)
4997 code
= 0xFF08; /* backspace */
5002 /* are there modifiers? */
5003 emacs_event
->modifiers
= 0;
5005 if (flags
& NSHelpKeyMask
)
5006 emacs_event
->modifiers |
= hyper_modifier
;
5008 if (flags
& NSShiftKeyMask
)
5009 emacs_event
->modifiers |
= shift_modifier
;
5011 is_right_key
= (flags
& NSRightCommandKeyMask
) == NSRightCommandKeyMask
;
5012 is_left_key
= (flags
& NSLeftCommandKeyMask
) == NSLeftCommandKeyMask
5013 ||
(! is_right_key
&& (flags
& NSCommandKeyMask
) == NSCommandKeyMask
);
5016 emacs_event
->modifiers |
= parse_solitary_modifier
5017 (EQ
(ns_right_command_modifier
, Qleft
)
5018 ? ns_command_modifier
5019 : ns_right_command_modifier
);
5023 emacs_event
->modifiers |
= parse_solitary_modifier
5024 (ns_command_modifier
);
5026 /* if super (default), take input manager's word so things like
5027 dvorak / qwerty layout work */
5028 if (EQ
(ns_command_modifier
, Qsuper
)
5030 && [[theEvent characters
] length] != 0)
5032 /* XXX: the code we get will be unshifted, so if we have
5033 a shift modifier, must convert ourselves */
5034 if (!(flags
& NSShiftKeyMask
))
5035 code
= [[theEvent characters
] characterAtIndex
: 0];
5037 /* this is ugly and also requires linking w/Carbon framework
5038 (for LMGetKbdType) so for now leave this rare (?) case
5039 undealt with.. in future look into CGEvent methods */
5042 long smv
= GetScriptManagerVariable
(smKeyScript
);
5043 Handle uchrHandle
= GetResource
5044 ('uchr', GetScriptVariable
(smv
, smScriptKeys
));
5046 UCKeyTranslate
((UCKeyboardLayout
*)*uchrHandle
,
5047 [[theEvent characters
] characterAtIndex
: 0],
5048 kUCKeyActionDisplay
,
5049 (flags
& ~NSCommandKeyMask
) >> 8,
5050 LMGetKbdType
(), kUCKeyTranslateNoDeadKeysMask
,
5051 &dummy
, 1, &dummy
, &code
);
5058 is_right_key
= (flags
& NSRightControlKeyMask
) == NSRightControlKeyMask
;
5059 is_left_key
= (flags
& NSLeftControlKeyMask
) == NSLeftControlKeyMask
5060 ||
(! is_right_key
&& (flags
& NSControlKeyMask
) == NSControlKeyMask
);
5063 emacs_event
->modifiers |
= parse_solitary_modifier
5064 (EQ
(ns_right_control_modifier
, Qleft
)
5065 ? ns_control_modifier
5066 : ns_right_control_modifier
);
5069 emacs_event
->modifiers |
= parse_solitary_modifier
5070 (ns_control_modifier
);
5072 if (flags
& NS_FUNCTION_KEY_MASK
&& !fnKeysym
)
5073 emacs_event
->modifiers |
=
5074 parse_solitary_modifier
(ns_function_modifier
);
5076 left_is_none
= NILP
(ns_alternate_modifier
)
5077 || EQ
(ns_alternate_modifier
, Qnone
);
5079 is_right_key
= (flags
& NSRightAlternateKeyMask
)
5080 == NSRightAlternateKeyMask
;
5081 is_left_key
= (flags
& NSLeftAlternateKeyMask
) == NSLeftAlternateKeyMask
5083 && (flags
& NSAlternateKeyMask
) == NSAlternateKeyMask
);
5087 if ((NILP
(ns_right_alternate_modifier
)
5088 || EQ
(ns_right_alternate_modifier
, Qnone
)
5089 ||
(EQ
(ns_right_alternate_modifier
, Qleft
) && left_is_none
))
5091 { /* accept pre-interp alt comb */
5092 if ([[theEvent characters
] length] > 0)
5093 code
= [[theEvent characters
] characterAtIndex
: 0];
5094 /*HACK: clear lone shift modifier to stop next if from firing */
5095 if (emacs_event
->modifiers
== shift_modifier
)
5096 emacs_event
->modifiers
= 0;
5099 emacs_event
->modifiers |
= parse_solitary_modifier
5100 (EQ
(ns_right_alternate_modifier
, Qleft
)
5101 ? ns_alternate_modifier
5102 : ns_right_alternate_modifier
);
5105 if (is_left_key
) /* default = meta */
5107 if (left_is_none
&& !fnKeysym
)
5108 { /* accept pre-interp alt comb */
5109 if ([[theEvent characters
] length] > 0)
5110 code
= [[theEvent characters
] characterAtIndex
: 0];
5111 /*HACK: clear lone shift modifier to stop next if from firing */
5112 if (emacs_event
->modifiers
== shift_modifier
)
5113 emacs_event
->modifiers
= 0;
5116 emacs_event
->modifiers |
=
5117 parse_solitary_modifier
(ns_alternate_modifier
);
5121 fprintf (stderr
, "keyDown
: code
=%x\tfnKey =%x\tflags = %x\tmods = %x\n",
5122 code
, fnKeysym
, flags
, emacs_event
->modifiers
);
5124 /* if it was a function key or had modifiers, pass it directly to emacs */
5125 if (fnKeysym ||
(emacs_event
->modifiers
5126 && (emacs_event
->modifiers
!= shift_modifier
)
5127 && [[theEvent charactersIgnoringModifiers
] length] > 0))
5128 /*[[theEvent characters] length] */
5130 emacs_event
->kind
= NON_ASCII_KEYSTROKE_EVENT
;
5132 code |
= (1<<28)|
(3<<16);
5133 else if (code
== 0x7f)
5134 code |
= (1<<28)|
(3<<16);
5136 emacs_event
->kind
= code
> 0xFF
5137 ? MULTIBYTE_CHAR_KEYSTROKE_EVENT
: ASCII_KEYSTROKE_EVENT
;
5139 emacs_event
->code
= code
;
5140 EV_TRAILER
(theEvent
);
5141 processingCompose
= NO
;
5147 #
if !defined
(NS_IMPL_COCOA
) || MAC_OS_X_VERSION_MAX_ALLOWED
< MAC_OS_X_VERSION_10_6
5148 /* if we get here we should send the key for input manager processing */
5149 /* Disable warning, there is nothing a user can do about it anyway, and
5150 it does not seem to matter. */
5152 if (firstTime
&& [[NSInputManager currentInputManager
]
5153 wantsToDelayTextChangeNotifications
] == NO
)
5155 "Emacs
: WARNING
: TextInput mgr wants marked
text to be permanent
!\n"
);
5159 if (NS_KEYLOG
&& !processingCompose
)
5160 fprintf (stderr
, "keyDown
: Begin compose sequence.
\n"
);
5162 processingCompose
= YES
;
5163 [nsEvArray addObject
: theEvent
];
5164 [self interpretKeyEvents
: nsEvArray
];
5165 [nsEvArray removeObject
: theEvent
];
5169 #ifdef NS_IMPL_COCOA
5170 /* Needed to pick up Ctrl-tab and possibly other events that OS X has
5171 decided not to send key-down for.
5172 See http://osdir.com/ml/editors.vim.mac/2007-10/msg00141.html
5173 This only applies on Tiger and earlier.
5174 If it matches one of these, send it on to keyDown. */
5175 -(void
)keyUp
: (NSEvent
*)theEvent
5177 int flags
= [theEvent modifierFlags
];
5178 int code
= [theEvent keyCode
];
5179 if (floor (NSAppKitVersionNumber
) <= 824 /*NSAppKitVersionNumber10_4*/ &&
5180 code
== 0x30 && (flags
& NSControlKeyMask
) && !(flags
& NSCommandKeyMask
))
5183 fprintf (stderr
, "keyUp
: passed test"
);
5184 ns_fake_keydown
= YES
;
5185 [self keyDown
: theEvent
];
5191 /* <NSTextInput> implementation (called through super interpretKeyEvents:]). */
5194 /* <NSTextInput>: called when done composing;
5195 NOTE: also called when we delete over working text, followed immed.
5196 by doCommandBySelector: deleteBackward: */
5197 - (void
)insertText
: (id
)aString
5200 int len
= [(NSString
*)aString
length];
5204 NSLog
(@"insertText
'%@'\tlen
= %d", aString, len);
5205 processingCompose
= NO
;
5210 /* first, clear any working text */
5211 if (workingText
!= nil
)
5212 [self deleteWorkingText
];
5214 /* now insert the string as keystrokes */
5215 for (i
=0; i
<len
; i
++)
5217 code
= [aString characterAtIndex
: i
];
5218 /* TODO: still need this? */
5220 code
= '~'; /* 0x7E */
5221 if (code
!= 32) /* Space */
5222 emacs_event
->modifiers
= 0;
5224 = code
> 0xFF ? MULTIBYTE_CHAR_KEYSTROKE_EVENT
: ASCII_KEYSTROKE_EVENT
;
5225 emacs_event
->code
= code
;
5226 EV_TRAILER
((id
)nil
);
5231 /* <NSTextInput>: inserts display of composing characters */
5232 - (void
)setMarkedText
: (id
)aString selectedRange
: (NSRange
)selRange
5234 NSString
*str
= [aString respondsToSelector
: @selector
(string
)] ?
5235 [aString string
] : aString
;
5237 NSLog
(@"setMarkedText
'%@' len
=%lu range %lu from %lu",
5238 str
, (unsigned
long)[str
length],
5239 (unsigned
long)selRange.
length,
5240 (unsigned
long)selRange.location
);
5242 if (workingText
!= nil
)
5243 [self deleteWorkingText
];
5244 if ([str
length] == 0)
5250 processingCompose
= YES
;
5251 workingText
= [str copy
];
5252 ns_working_text
= build_string
([workingText UTF8String
]);
5254 emacs_event
->kind
= NS_TEXT_EVENT
;
5255 emacs_event
->code
= KEY_NS_PUT_WORKING_TEXT
;
5256 EV_TRAILER
((id
)nil
);
5260 /* delete display of composing characters [not in <NSTextInput>] */
5261 - (void
)deleteWorkingText
5263 if (workingText
== nil
)
5266 NSLog
(@"deleteWorkingText len
=%lu\n", (unsigned long)[workingText length]);
5267 [workingText release
];
5269 processingCompose
= NO
;
5274 emacs_event
->kind
= NS_TEXT_EVENT
;
5275 emacs_event
->code
= KEY_NS_UNPUT_WORKING_TEXT
;
5276 EV_TRAILER
((id
)nil
);
5280 - (BOOL
)hasMarkedText
5282 return workingText
!= nil
;
5286 - (NSRange
)markedRange
5288 NSRange rng
= workingText
!= nil
5289 ? NSMakeRange
(0, [workingText
length]) : NSMakeRange
(NSNotFound
, 0);
5291 NSLog
(@"markedRange request"
);
5299 NSLog
(@"unmark
(accept
) text"
);
5300 [self deleteWorkingText
];
5301 processingCompose
= NO
;
5305 /* used to position char selection windows, etc. */
5306 - (NSRect
)firstRectForCharacterRange
: (NSRange
)theRange
5310 struct window
*win
= XWINDOW
(FRAME_SELECTED_WINDOW
(emacsframe
));
5312 NSLog
(@"firstRectForCharRange request"
);
5314 rect.
size.width
= theRange.
length * FRAME_COLUMN_WIDTH
(emacsframe
);
5315 rect.
size.height
= FRAME_LINE_HEIGHT
(emacsframe
);
5316 pt.x
= WINDOW_TEXT_TO_FRAME_PIXEL_X
(win
, win
->phys_cursor.x
);
5317 pt.y
= WINDOW_TO_FRAME_PIXEL_Y
(win
, win
->phys_cursor.y
5318 +FRAME_LINE_HEIGHT
(emacsframe
));
5320 pt
= [self convertPoint
: pt toView
: nil
];
5321 pt
= [[self window
] convertBaseToScreen
: pt
];
5327 - (NSInteger
)conversationIdentifier
5329 return (NSInteger
)self
;
5333 - (void
)doCommandBySelector
: (SEL
)aSelector
5336 NSLog
(@"doCommandBySelector
: %@", NSStringFromSelector (aSelector));
5338 processingCompose
= NO
;
5339 if (aSelector
== @selector
(deleteBackward
:))
5341 /* happens when user backspaces over an ongoing composition:
5342 throw a 'delete' into the event queue */
5345 emacs_event
->kind
= NON_ASCII_KEYSTROKE_EVENT
;
5346 emacs_event
->code
= 0xFF08;
5347 EV_TRAILER
((id
)nil
);
5351 - (NSArray
*)validAttributesForMarkedText
5353 static NSArray
*arr
= nil
;
5354 if (arr
== nil
) arr
= [NSArray new
];
5355 /* [[NSArray arrayWithObject: NSUnderlineStyleAttributeName] retain]; */
5359 - (NSRange
)selectedRange
5362 NSLog
(@"selectedRange request"
);
5363 return NSMakeRange
(NSNotFound
, 0);
5366 #
if defined
(NS_IMPL_COCOA
) || GNUSTEP_GUI_MAJOR_VERSION
> 0 || \
5367 GNUSTEP_GUI_MINOR_VERSION
> 22
5368 - (NSUInteger
)characterIndexForPoint
: (NSPoint
)thePoint
5370 - (unsigned int
)characterIndexForPoint
: (NSPoint
)thePoint
5374 NSLog
(@"characterIndexForPoint request"
);
5378 - (NSAttributedString
*)attributedSubstringFromRange
: (NSRange
)theRange
5380 static NSAttributedString
*str
= nil
;
5381 if (str
== nil
) str
= [NSAttributedString new
];
5383 NSLog
(@"attributedSubstringFromRange request"
);
5387 /* End <NSTextInput> impl. */
5388 /*****************************************************************************/
5391 /* This is what happens when the user presses a mouse button. */
5392 - (void
)mouseDown
: (NSEvent
*)theEvent
5394 struct ns_display_info
*dpyinfo
= FRAME_DISPLAY_INFO
(emacsframe
);
5395 NSPoint p
= [self convertPoint
: [theEvent locationInWindow
] fromView
: nil
];
5397 NSTRACE
(mouseDown
);
5399 [self deleteWorkingText
];
5404 dpyinfo
->last_mouse_frame
= emacsframe
;
5405 /* appears to be needed to prevent spurious movement events generated on
5407 emacsframe
->mouse_moved
= 0;
5409 if ([theEvent
type] == NSScrollWheel
)
5411 CGFloat delta
= [theEvent deltaY
];
5412 /* Mac notebooks send wheel events w/delta =0 when trackpad scrolling */
5415 emacs_event
->kind
= WHEEL_EVENT
;
5416 emacs_event
->code
= 0;
5417 emacs_event
->modifiers
= EV_MODIFIERS
(theEvent
) |
5418 ((delta
> 0) ? up_modifier
: down_modifier
);
5422 emacs_event
->kind
= MOUSE_CLICK_EVENT
;
5423 emacs_event
->code
= EV_BUTTON
(theEvent
);
5424 emacs_event
->modifiers
= EV_MODIFIERS
(theEvent
)
5425 | EV_UDMODIFIERS
(theEvent
);
5427 XSETINT
(emacs_event
->x
, lrint
(p.x
));
5428 XSETINT
(emacs_event
->y
, lrint
(p.y
));
5429 EV_TRAILER
(theEvent
);
5433 - (void
)rightMouseDown
: (NSEvent
*)theEvent
5435 NSTRACE
(rightMouseDown
);
5436 [self mouseDown
: theEvent
];
5440 - (void
)otherMouseDown
: (NSEvent
*)theEvent
5442 NSTRACE
(otherMouseDown
);
5443 [self mouseDown
: theEvent
];
5447 - (void
)mouseUp
: (NSEvent
*)theEvent
5450 [self mouseDown
: theEvent
];
5454 - (void
)rightMouseUp
: (NSEvent
*)theEvent
5456 NSTRACE
(rightMouseUp
);
5457 [self mouseDown
: theEvent
];
5461 - (void
)otherMouseUp
: (NSEvent
*)theEvent
5463 NSTRACE
(otherMouseUp
);
5464 [self mouseDown
: theEvent
];
5468 - (void
) scrollWheel
: (NSEvent
*)theEvent
5470 NSTRACE
(scrollWheel
);
5471 [self mouseDown
: theEvent
];
5475 /* Tell emacs the mouse has moved. */
5476 - (void
)mouseMoved
: (NSEvent
*)e
5478 Mouse_HLInfo
*hlinfo
= MOUSE_HL_INFO
(emacsframe
);
5479 struct ns_display_info
*dpyinfo
= FRAME_DISPLAY_INFO
(emacsframe
);
5483 // NSTRACE
(mouseMoved
);
5485 dpyinfo
->last_mouse_movement_time
= EV_TIMESTAMP
(e
);
5486 pt
= [self convertPoint
: [e locationInWindow
] fromView
: nil
];
5487 dpyinfo
->last_mouse_motion_x
= pt.x
;
5488 dpyinfo
->last_mouse_motion_y
= pt.y
;
5490 /* update any mouse face */
5491 if (hlinfo
->mouse_face_hidden
)
5493 hlinfo
->mouse_face_hidden
= 0;
5494 clear_mouse_face
(hlinfo
);
5497 /* tooltip handling */
5498 previous_help_echo_string
= help_echo_string
;
5499 help_echo_string
= Qnil
;
5501 if (!NILP
(Vmouse_autoselect_window
))
5503 NSTRACE
(mouse_autoselect_window
);
5504 static Lisp_Object last_mouse_window
;
5506 = window_from_coordinates
(emacsframe
, pt.x
, pt.y
, 0, 0);
5508 if (WINDOWP
(window
)
5509 && !EQ
(window
, last_mouse_window
)
5510 && !EQ
(window
, selected_window
)
5511 && (focus_follows_mouse
5512 ||
(EQ
(XWINDOW
(window
)->frame
,
5513 XWINDOW
(selected_window
)->frame
))))
5515 NSTRACE
(in_window
);
5516 emacs_event
->kind
= SELECT_WINDOW_EVENT
;
5517 emacs_event
->frame_or_window
= window
;
5520 /* Remember the last window where we saw the mouse. */
5521 last_mouse_window
= window
;
5524 if (!note_mouse_movement
(emacsframe
, pt.x
, pt.y
))
5525 help_echo_string
= previous_help_echo_string
;
5527 XSETFRAME
(frame
, emacsframe
);
5528 if (!NILP
(help_echo_string
) ||
!NILP
(previous_help_echo_string
))
5530 /* NOTE: help_echo_{window,pos,object} are set in xdisp.c
5531 (note_mouse_highlight), which is called through the
5532 note_mouse_movement () call above */
5533 gen_help_event
(help_echo_string
, frame
, help_echo_window
,
5534 help_echo_object
, help_echo_pos
);
5538 help_echo_string
= Qnil
;
5539 gen_help_event
(Qnil
, frame
, Qnil
, Qnil
, 0);
5542 if (emacsframe
->mouse_moved
&& send_appdefined
)
5543 ns_send_appdefined
(-1);
5547 - (void
)mouseDragged
: (NSEvent
*)e
5549 NSTRACE
(mouseDragged
);
5550 [self mouseMoved
: e
];
5554 - (void
)rightMouseDragged
: (NSEvent
*)e
5556 NSTRACE
(rightMouseDragged
);
5557 [self mouseMoved
: e
];
5561 - (void
)otherMouseDragged
: (NSEvent
*)e
5563 NSTRACE
(otherMouseDragged
);
5564 [self mouseMoved
: e
];
5568 - (BOOL
)windowShouldClose
: (id
)sender
5570 NSEvent
*e
=[[self window
] currentEvent
];
5572 NSTRACE
(windowShouldClose
);
5573 windowClosing
= YES
;
5576 emacs_event
->kind
= DELETE_WINDOW_EVENT
;
5577 emacs_event
->modifiers
= 0;
5578 emacs_event
->code
= 0;
5580 /* Don't close this window, let this be done from lisp code. */
5584 - (void
) updateFrameSize
: (BOOL
) delay
;
5586 NSWindow
*window
= [self window
];
5587 NSRect wr
= [window frame
];
5590 #ifdef NS_IMPL_GNUSTEP
5594 int oldc
= cols
, oldr
= rows
;
5595 int oldw
= FRAME_PIXEL_WIDTH
(emacsframe
),
5596 oldh
= FRAME_PIXEL_HEIGHT
(emacsframe
);
5599 cols
= FRAME_PIXEL_WIDTH_TO_TEXT_COLS
(emacsframe
, wr.
size.width
+ gsextra
);
5601 if (cols
< MINWIDTH
)
5604 if (! [self isFullscreen
])
5606 extra
= FRAME_NS_TITLEBAR_HEIGHT
(emacsframe
)
5607 + FRAME_TOOLBAR_HEIGHT
(emacsframe
) - gsextra
;
5610 rows
= FRAME_PIXEL_HEIGHT_TO_TEXT_LINES
(emacsframe
, wr.
size.height
- extra
);
5612 if (rows
< MINHEIGHT
)
5615 neww
= (int
)wr.
size.width
- emacsframe
->border_width
;
5616 newh
= (int
)wr.
size.height
- extra
;
5618 if (oldr
!= rows || oldc
!= cols || neww
!= oldw || newh
!= oldh
)
5620 NSView
*view = FRAME_NS_VIEW
(emacsframe
);
5621 NSWindow
*win
= [view window
];
5622 NSSize sz
= [win resizeIncrements
];
5624 FRAME_PIXEL_WIDTH
(emacsframe
) = neww
;
5625 FRAME_PIXEL_HEIGHT
(emacsframe
) = newh
;
5626 change_frame_size
(emacsframe
, rows
, cols
, 0, delay
, 0);
5627 SET_FRAME_GARBAGED
(emacsframe
);
5628 cancel_mouse_face
(emacsframe
);
5630 // Did resize increments change because of a font change?
5631 if (sz.width
!= FRAME_COLUMN_WIDTH
(emacsframe
) ||
5632 sz.height
!= FRAME_LINE_HEIGHT
(emacsframe
))
5634 sz.width
= FRAME_COLUMN_WIDTH
(emacsframe
);
5635 sz.height
= FRAME_LINE_HEIGHT
(emacsframe
);
5636 [win setResizeIncrements
: sz
];
5639 [view setFrame
: NSMakeRect
(0, 0, neww
, newh
)];
5640 [self windowDidMove
:nil
]; // Update top
/left.
5644 - (NSSize
)windowWillResize
: (NSWindow
*)sender toSize
: (NSSize
)frameSize
5645 /* normalize frame to gridded text size */
5649 #ifdef NS_IMPL_GNUSTEP
5653 NSTRACE
(windowWillResize
);
5654 /*fprintf (stderr,"Window will resize: %.0f x %.0f\n",frameSize.width,frameSize.height); */
5656 if (fs_state
== FULLSCREEN_MAXIMIZED
5657 && (maximized_width
!= (int
)frameSize.width
5658 || maximized_height
!= (int
)frameSize.height
))
5659 [self setFSValue
: FULLSCREEN_NONE
];
5660 else if (fs_state
== FULLSCREEN_WIDTH
5661 && maximized_width
!= (int
)frameSize.width
)
5662 [self setFSValue
: FULLSCREEN_NONE
];
5663 else if (fs_state
== FULLSCREEN_HEIGHT
5664 && maximized_height
!= (int
)frameSize.height
)
5665 [self setFSValue
: FULLSCREEN_NONE
];
5666 if (fs_state
== FULLSCREEN_NONE
)
5667 maximized_width
= maximized_height
= -1;
5669 cols
= FRAME_PIXEL_WIDTH_TO_TEXT_COLS
(emacsframe
,
5670 frameSize.width
+ gsextra
);
5671 if (cols
< MINWIDTH
)
5674 rows
= FRAME_PIXEL_HEIGHT_TO_TEXT_LINES
(emacsframe
,
5675 frameSize.height
- extra
);
5676 if (rows
< MINHEIGHT
)
5678 #ifdef NS_IMPL_COCOA
5680 /* this sets window title to have size in it; the wm does this under GS */
5681 NSRect r
= [[self window
] frame
];
5682 if (r.
size.height
== frameSize.height
&& r.
size.width
== frameSize.width
)
5690 else if (fs_state
== FULLSCREEN_NONE
&& ! maximizing_resize
)
5693 NSWindow
*window
= [self window
];
5696 char *t
= strdup
([[[self window
] title] UTF8String
]);
5697 char *pos
= strstr
(t
, " — "
);
5702 size_title
= xmalloc
(strlen
(old_title
) + 40);
5703 esprintf
(size_title
, "
%s — (%d x %d)", old_title, cols, rows);
5704 [window setTitle
: [NSString stringWithUTF8String
: size_title
]];
5709 #endif
/* NS_IMPL_COCOA */
5710 /*fprintf (stderr," ...size became %.0f x %.0f (%d x %d)\n",frameSize.width,frameSize.height,cols,rows); */
5716 - (void
)windowDidResize
: (NSNotification
*)notification
5718 if (! [self fsIsNative
])
5720 NSWindow
*theWindow
= [notification object
];
5721 /* We can get notification on the non-FS window when in
5723 if ([self window
] != theWindow
) return;
5726 #ifdef NS_IMPL_GNUSTEP
5727 NSWindow
*theWindow
= [notification object
];
5729 /* In GNUstep, at least currently, it's possible to get a didResize
5730 without getting a willResize.. therefore we need to act as if we got
5731 the willResize now */
5732 NSSize sz
= [theWindow frame
].
size;
5733 sz
= [self windowWillResize
: theWindow toSize
: sz
];
5734 #endif
/* NS_IMPL_GNUSTEP */
5736 NSTRACE
(windowDidResize
);
5737 /*fprintf (stderr,"windowDidResize: %.0f\n",[theWindow frame].size.height); */
5739 if (cols
> 0 && rows
> 0)
5741 [self updateFrameSize
: YES
];
5744 ns_send_appdefined
(-1);
5747 #ifdef NS_IMPL_COCOA
5748 - (void
)viewDidEndLiveResize
5750 [super viewDidEndLiveResize
];
5753 [[self window
] setTitle
: [NSString stringWithUTF8String
: old_title
]];
5757 maximizing_resize
= NO
;
5759 #endif
/* NS_IMPL_COCOA */
5762 - (void
)windowDidBecomeKey
: (NSNotification
*)notification
5763 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5765 struct ns_display_info
*dpyinfo
= FRAME_DISPLAY_INFO
(emacsframe
);
5766 struct frame
*old_focus
= dpyinfo
->x_focus_frame
;
5768 NSTRACE
(windowDidBecomeKey
);
5770 if (emacsframe
!= old_focus
)
5771 dpyinfo
->x_focus_frame
= emacsframe
;
5773 ns_frame_rehighlight
(emacsframe
);
5777 emacs_event
->kind
= FOCUS_IN_EVENT
;
5778 EV_TRAILER
((id
)nil
);
5783 - (void
)windowDidResignKey
: (NSNotification
*)notification
5784 /* cf. x_detect_focus_change(), x_focus_changed(), x_new_focus_frame() */
5786 struct ns_display_info
*dpyinfo
= FRAME_DISPLAY_INFO
(emacsframe
);
5787 BOOL is_focus_frame
= dpyinfo
->x_focus_frame
== emacsframe
;
5788 NSTRACE
(windowDidResignKey
);
5791 dpyinfo
->x_focus_frame
= 0;
5793 ns_frame_rehighlight
(emacsframe
);
5795 /* FIXME: for some reason needed on second and subsequent clicks away
5796 from sole-frame Emacs to get hollow box to show */
5797 if (!windowClosing
&& [[self window
] isVisible
] == YES
)
5799 x_update_cursor
(emacsframe
, 1);
5800 x_set_frame_alpha
(emacsframe
);
5803 if (emacs_event
&& is_focus_frame
)
5805 [self deleteWorkingText
];
5806 emacs_event
->kind
= FOCUS_OUT_EVENT
;
5807 EV_TRAILER
((id
)nil
);
5812 - (void
)windowWillMiniaturize
: sender
5814 NSTRACE
(windowWillMiniaturize
);
5830 - initFrameFromEmacs
: (struct frame
*)f
5839 NSTRACE
(initFrameFromEmacs
);
5842 processingCompose
= NO
;
5843 scrollbarsNeedingUpdate
= 0;
5844 fs_state
= FULLSCREEN_NONE
;
5845 fs_before_fs
= next_maximized
= -1;
5846 #ifdef HAVE_NATIVE_FS
5847 fs_is_native
= ns_use_native_fullscreen
;
5851 maximized_width
= maximized_height
= -1;
5854 /*fprintf (stderr,"init with %d, %d\n",f->text_cols, f->text_lines); */
5856 ns_userRect
= NSMakeRect
(0, 0, 0, 0);
5857 r
= NSMakeRect
(0, 0, FRAME_TEXT_COLS_TO_PIXEL_WIDTH
(f
, f
->text_cols
),
5858 FRAME_TEXT_LINES_TO_PIXEL_HEIGHT
(f
, f
->text_lines
));
5859 [self initWithFrame
: r
];
5860 [self setAutoresizingMask
: NSViewWidthSizable | NSViewHeightSizable
];
5862 FRAME_NS_VIEW
(f
) = self
;
5864 #ifdef NS_IMPL_COCOA
5866 maximizing_resize
= NO
;
5869 win
= [[EmacsWindow alloc
]
5870 initWithContentRect
: r
5871 styleMask
: (NSResizableWindowMask |
5872 #
if MAC_OS_X_VERSION_MAX_ALLOWED
>= MAC_OS_X_VERSION_10_7
5873 NSTitledWindowMask |
5875 NSMiniaturizableWindowMask |
5876 NSClosableWindowMask
)
5877 backing
: NSBackingStoreBuffered
5880 #ifdef HAVE_NATIVE_FS
5881 [win setCollectionBehavior
:NSWindowCollectionBehaviorFullScreenPrimary
];
5885 bwidth
= f
->border_width
= wr.
size.width
- r.
size.width
;
5886 tibar_height
= FRAME_NS_TITLEBAR_HEIGHT
(f
) = wr.
size.height
- r.
size.height
;
5888 [win setAcceptsMouseMovedEvents
: YES
];
5889 [win setDelegate
: self
];
5890 [win useOptimizedDrawing
: YES
];
5892 sz.width
= FRAME_COLUMN_WIDTH
(f
);
5893 sz.height
= FRAME_LINE_HEIGHT
(f
);
5894 [win setResizeIncrements
: sz
];
5896 [[win contentView
] addSubview
: self
];
5899 [self registerForDraggedTypes
: ns_drag_types
];
5902 name
= [NSString stringWithUTF8String
:
5903 NILP
(tem
) ? "Emacs"
: SSDATA
(tem
)];
5904 [win setTitle
: name
];
5906 /* toolbar support */
5907 toolbar
= [[EmacsToolbar alloc
] initForView
: self withIdentifier
:
5908 [NSString stringWithFormat
: @"Emacs Frame
%d",
5910 [win setToolbar
: toolbar
];
5911 [toolbar setVisible
: NO
];
5912 #ifdef NS_IMPL_COCOA
5914 NSButton
*toggleButton
;
5915 toggleButton
= [win standardWindowButton
: NSWindowToolbarButton
];
5916 [toggleButton setTarget
: self
];
5917 [toggleButton setAction
: @selector
(toggleToolbar
: )];
5920 FRAME_TOOLBAR_HEIGHT
(f
) = 0;
5924 [win setMiniwindowTitle
:
5925 [NSString stringWithUTF8String
: SSDATA
(tem
)]];
5928 NSScreen
*screen
= [win screen
];
5931 [win setFrameTopLeftPoint
: NSMakePoint
5932 (IN_BOUND
(-SCREENMAX
, f
->left_pos
, SCREENMAX
),
5933 IN_BOUND
(-SCREENMAX
,
5934 [screen frame
].
size.height
- NS_TOP_POS
(f
), SCREENMAX
))];
5937 [win makeFirstResponder
: self
];
5939 col
= ns_lookup_indexed_color
(NS_FACE_BACKGROUND
5940 (FRAME_DEFAULT_FACE
(emacsframe
)), emacsframe
);
5941 [win setBackgroundColor
: col
];
5942 if ([col alphaComponent
] != (EmacsCGFloat
) 1.0)
5943 [win setOpaque
: NO
];
5945 [self allocateGState
];
5947 [NSApp registerServicesMenuSendTypes
: ns_send_types
5955 - (void
)windowDidMove
: sender
5957 NSWindow
*win
= [self window
];
5958 NSRect r
= [win frame
];
5959 NSArray
*screens
= [NSScreen screens
];
5960 NSScreen
*screen
= [screens objectAtIndex
: 0];
5962 NSTRACE
(windowDidMove
);
5964 if (!emacsframe
->output_data.ns
)
5968 emacsframe
->left_pos
= r.origin.x
;
5969 emacsframe
->top_pos
=
5970 [screen frame
].
size.height
- (r.origin.y
+ r.
size.height
);
5975 /* Called AFTER method below, but before our windowWillResize call there leads
5976 to windowDidResize -> x_set_window_size. Update emacs' notion of frame
5977 location so set_window_size moves the frame. */
5978 - (BOOL
)windowShouldZoom
: (NSWindow
*)sender toFrame
: (NSRect
)newFrame
5980 emacsframe
->output_data.ns
->zooming
= 1;
5985 /* Override to do something slightly nonstandard, but nice. First click on
5986 zoom button will zoom vertically. Second will zoom completely. Third
5987 returns to original. */
5988 - (NSRect
)windowWillUseStandardFrame
:(NSWindow
*)sender
5989 defaultFrame
:(NSRect
)defaultFrame
5991 NSRect result
= [sender frame
];
5993 NSTRACE
(windowWillUseStandardFrame
);
5995 if (fs_before_fs
!= -1) /* Entering fullscreen */
5997 result
= defaultFrame
;
5999 else if (next_maximized
== FULLSCREEN_HEIGHT
6000 ||
(next_maximized
== -1
6001 && abs (defaultFrame.
size.height
- result.
size.height
)
6002 > FRAME_LINE_HEIGHT
(emacsframe
)))
6005 ns_userRect
= result
;
6006 maximized_height
= result.
size.height
= defaultFrame.
size.height
;
6007 maximized_width
= -1;
6008 result.origin.y
= defaultFrame.origin.y
;
6009 [self setFSValue
: FULLSCREEN_HEIGHT
];
6010 #ifdef NS_IMPL_COCOA
6011 maximizing_resize
= YES
;
6014 else if (next_maximized
== FULLSCREEN_WIDTH
)
6016 ns_userRect
= result
;
6017 maximized_width
= result.
size.width
= defaultFrame.
size.width
;
6018 maximized_height
= -1;
6019 result.origin.x
= defaultFrame.origin.x
;
6020 [self setFSValue
: FULLSCREEN_WIDTH
];
6022 else if (next_maximized
== FULLSCREEN_MAXIMIZED
6023 ||
(next_maximized
== -1
6024 && abs (defaultFrame.
size.width
- result.
size.width
)
6025 > FRAME_COLUMN_WIDTH
(emacsframe
)))
6027 result
= defaultFrame
; /* second click */
6028 maximized_width
= result.
size.width
;
6029 maximized_height
= result.
size.height
;
6030 [self setFSValue
: FULLSCREEN_MAXIMIZED
];
6031 #ifdef NS_IMPL_COCOA
6032 maximizing_resize
= YES
;
6038 result
= ns_userRect.
size.height ? ns_userRect
: result
;
6039 ns_userRect
= NSMakeRect
(0, 0, 0, 0);
6040 #ifdef NS_IMPL_COCOA
6041 maximizing_resize
= fs_state
!= FULLSCREEN_NONE
;
6043 [self setFSValue
: FULLSCREEN_NONE
];
6044 maximized_width
= maximized_height
= -1;
6047 if (fs_before_fs
== -1) next_maximized
= -1;
6048 [self windowWillResize
: sender toSize
: result.
size];
6053 - (void
)windowDidDeminiaturize
: sender
6055 NSTRACE
(windowDidDeminiaturize
);
6056 if (!emacsframe
->output_data.ns
)
6059 SET_FRAME_ICONIFIED
(emacsframe
, 0);
6060 SET_FRAME_VISIBLE
(emacsframe
, 1);
6061 windows_or_buffers_changed
++;
6065 emacs_event
->kind
= DEICONIFY_EVENT
;
6066 EV_TRAILER
((id
)nil
);
6071 - (void
)windowDidExpose
: sender
6073 NSTRACE
(windowDidExpose
);
6074 if (!emacsframe
->output_data.ns
)
6077 SET_FRAME_VISIBLE
(emacsframe
, 1);
6078 SET_FRAME_GARBAGED
(emacsframe
);
6080 if (send_appdefined
)
6081 ns_send_appdefined
(-1);
6085 - (void
)windowDidMiniaturize
: sender
6087 NSTRACE
(windowDidMiniaturize
);
6088 if (!emacsframe
->output_data.ns
)
6091 SET_FRAME_ICONIFIED
(emacsframe
, 1);
6092 SET_FRAME_VISIBLE
(emacsframe
, 0);
6096 emacs_event
->kind
= ICONIFY_EVENT
;
6097 EV_TRAILER
((id
)nil
);
6101 #ifdef HAVE_NATIVE_FS
6102 - (NSApplicationPresentationOptions
)window
:(NSWindow
*)window
6103 willUseFullScreenPresentationOptions
:
6104 (NSApplicationPresentationOptions
)proposedOptions
6106 return proposedOptions|NSApplicationPresentationAutoHideToolbar
;
6110 - (void
)windowWillEnterFullScreen
:(NSNotification
*)notification
6112 fs_before_fs
= fs_state
;
6115 - (void
)windowDidEnterFullScreen
:(NSNotification
*)notification
6117 [self setFSValue
: FULLSCREEN_BOTH
];
6118 if (! [self fsIsNative
])
6120 [self windowDidBecomeKey
:notification
];
6121 [nonfs_window orderOut
:self
];
6125 BOOL tbar_visible
= FRAME_EXTERNAL_TOOL_BAR
(emacsframe
) ? YES
: NO
;
6126 #ifdef NS_IMPL_COCOA
6127 #
if MAC_OS_X_VERSION_MAX_ALLOWED
>= MAC_OS_X_VERSION_10_7
6128 unsigned val
= (unsigned
)[NSApp presentationOptions
];
6130 // OSX
10.7 bug
fix, the
menu won
't appear without this.
6131 // val is non-zero on other OSX versions.
6134 NSApplicationPresentationOptions options
6135 = NSApplicationPresentationAutoHideDock
6136 | NSApplicationPresentationAutoHideMenuBar
6137 | NSApplicationPresentationFullScreen
6138 | NSApplicationPresentationAutoHideToolbar;
6140 [NSApp setPresentationOptions: options];
6144 [toolbar setVisible:tbar_visible];
6148 - (void)windowWillExitFullScreen:(NSNotification *)notification
6150 if (next_maximized != -1)
6151 fs_before_fs = next_maximized;
6154 - (void)windowDidExitFullScreen:(NSNotification *)notification
6156 [self setFSValue: fs_before_fs];
6158 #ifdef HAVE_NATIVE_FS
6159 [self updateCollectionBehaviour];
6161 if (FRAME_EXTERNAL_TOOL_BAR (emacsframe))
6163 [toolbar setVisible:YES];
6164 update_frame_tool_bar (emacsframe);
6165 [self updateFrameSize:YES];
6166 [[self window] display];
6169 [toolbar setVisible:NO];
6171 if (next_maximized != -1)
6172 [[self window] performZoom:self];
6177 return fs_is_native;
6180 - (BOOL)isFullscreen
6182 if (! fs_is_native) return nonfs_window != nil;
6183 #ifdef HAVE_NATIVE_FS
6184 return ([[self window] styleMask] & NSFullScreenWindowMask) != 0;
6190 #ifdef HAVE_NATIVE_FS
6191 - (void)updateCollectionBehaviour
6193 if (! [self isFullscreen])
6195 NSWindow *win = [self window];
6196 NSWindowCollectionBehavior b = [win collectionBehavior];
6197 if (ns_use_native_fullscreen)
6198 b |= NSWindowCollectionBehaviorFullScreenPrimary;
6200 b &= ~NSWindowCollectionBehaviorFullScreenPrimary;
6202 [win setCollectionBehavior: b];
6203 fs_is_native = ns_use_native_fullscreen;
6208 - (void)toggleFullScreen: (id)sender
6219 #ifdef HAVE_NATIVE_FS
6220 [[self window] toggleFullScreen:sender];
6226 onFirstScreen = [[w screen] isEqual:[[NSScreen screens] objectAtIndex:0]];
6229 col = ns_lookup_indexed_color (NS_FACE_BACKGROUND
6230 (FRAME_DEFAULT_FACE (f)),
6233 sz.width = FRAME_COLUMN_WIDTH (f);
6234 sz.height = FRAME_LINE_HEIGHT (f);
6236 if (fs_state != FULLSCREEN_BOTH)
6238 /* Hide dock and menubar if we are on the primary screen. */
6241 #if defined (NS_IMPL_COCOA) && \
6242 MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
6243 NSApplicationPresentationOptions options
6244 = NSApplicationPresentationAutoHideDock
6245 | NSApplicationPresentationAutoHideMenuBar;
6247 [NSApp setPresentationOptions: options];
6249 [NSMenu setMenuBarVisible:NO];
6253 fw = [[EmacsFSWindow alloc]
6254 initWithContentRect:[w contentRectForFrameRect:wr]
6255 styleMask:NSBorderlessWindowMask
6256 backing:NSBackingStoreBuffered
6260 [fw setContentView:[w contentView]];
6261 [fw setTitle:[w title]];
6262 [fw setDelegate:self];
6263 [fw setAcceptsMouseMovedEvents: YES];
6264 [fw useOptimizedDrawing: YES];
6265 [fw setResizeIncrements: sz];
6266 [fw setBackgroundColor: col];
6267 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6270 f->border_width = 0;
6271 FRAME_NS_TITLEBAR_HEIGHT (f) = 0;
6272 tobar_height = FRAME_TOOLBAR_HEIGHT (f);
6273 FRAME_TOOLBAR_HEIGHT (f) = 0;
6277 [self windowWillEnterFullScreen:nil];
6278 [fw makeKeyAndOrderFront:NSApp];
6279 [fw makeFirstResponder:self];
6281 r = [fw frameRectForContentRect:[[fw screen] frame]];
6282 [fw setFrame: r display:YES animate:YES];
6283 [self windowDidEnterFullScreen:nil];
6294 #if defined (NS_IMPL_COCOA) && \
6295 MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
6296 [NSApp setPresentationOptions: NSApplicationPresentationDefault];
6298 [NSMenu setMenuBarVisible:YES];
6302 [w setContentView:[fw contentView]];
6303 [w setResizeIncrements: sz];
6304 [w setBackgroundColor: col];
6305 if ([col alphaComponent] != (EmacsCGFloat) 1.0)
6308 f->border_width = bwidth;
6309 FRAME_NS_TITLEBAR_HEIGHT (f) = tibar_height;
6310 if (FRAME_EXTERNAL_TOOL_BAR (f))
6311 FRAME_TOOLBAR_HEIGHT (f) = tobar_height;
6313 [self windowWillExitFullScreen:nil];
6314 [fw setFrame: [w frame] display:YES animate:YES];
6316 [w makeKeyAndOrderFront:NSApp];
6317 [self windowDidExitFullScreen:nil];
6318 [self updateFrameSize:YES];
6324 if (fs_state != emacsframe->want_fullscreen)
6326 if (fs_state == FULLSCREEN_BOTH)
6328 [self toggleFullScreen:self];
6331 switch (emacsframe->want_fullscreen)
6333 case FULLSCREEN_BOTH:
6334 [self toggleFullScreen:self];
6336 case FULLSCREEN_WIDTH:
6337 next_maximized = FULLSCREEN_WIDTH;
6338 if (fs_state != FULLSCREEN_BOTH)
6339 [[self window] performZoom:self];
6341 case FULLSCREEN_HEIGHT:
6342 next_maximized = FULLSCREEN_HEIGHT;
6343 if (fs_state != FULLSCREEN_BOTH)
6344 [[self window] performZoom:self];
6346 case FULLSCREEN_MAXIMIZED:
6347 next_maximized = FULLSCREEN_MAXIMIZED;
6348 if (fs_state != FULLSCREEN_BOTH)
6349 [[self window] performZoom:self];
6351 case FULLSCREEN_NONE:
6352 if (fs_state != FULLSCREEN_BOTH)
6354 next_maximized = FULLSCREEN_NONE;
6355 [[self window] performZoom:self];
6360 emacsframe->want_fullscreen = FULLSCREEN_NONE;
6365 - (void) setFSValue: (int)value
6367 Lisp_Object lval = Qnil;
6370 case FULLSCREEN_BOTH:
6373 case FULLSCREEN_WIDTH:
6376 case FULLSCREEN_HEIGHT:
6379 case FULLSCREEN_MAXIMIZED:
6383 store_frame_param (emacsframe, Qfullscreen, lval);
6387 - (void)mouseEntered: (NSEvent *)theEvent
6389 NSTRACE (mouseEntered);
6391 FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
6392 = EV_TIMESTAMP (theEvent);
6396 - (void)mouseExited: (NSEvent *)theEvent
6398 Mouse_HLInfo *hlinfo = emacsframe ? MOUSE_HL_INFO (emacsframe) : NULL;
6400 NSTRACE (mouseExited);
6405 FRAME_DISPLAY_INFO (emacsframe)->last_mouse_movement_time
6406 = EV_TIMESTAMP (theEvent);
6408 if (emacsframe == hlinfo->mouse_face_mouse_frame)
6410 clear_mouse_face (hlinfo);
6411 hlinfo->mouse_face_mouse_frame = 0;
6419 if (context_menu_value == -1)
6420 context_menu_value = [sender tag];
6423 NSInteger tag = [sender tag];
6424 find_and_call_menu_selection (emacsframe, emacsframe->menu_bar_items_used,
6425 emacsframe->menu_bar_vector,
6429 ns_send_appdefined (-1);
6434 - (EmacsToolbar *)toolbar
6440 /* this gets called on toolbar button click */
6441 - toolbarClicked: (id)item
6444 int idx = [item tag] * TOOL_BAR_ITEM_NSLOTS;
6446 NSTRACE (toolbarClicked);
6451 /* send first event (for some reason two needed) */
6452 theEvent = [[self window] currentEvent];
6453 emacs_event->kind = TOOL_BAR_EVENT;
6454 XSETFRAME (emacs_event->arg, emacsframe);
6455 EV_TRAILER (theEvent);
6457 emacs_event->kind = TOOL_BAR_EVENT;
6458 /* XSETINT (emacs_event->code, 0); */
6459 emacs_event->arg = AREF (emacsframe->tool_bar_items,
6460 idx + TOOL_BAR_ITEM_KEY);
6461 emacs_event->modifiers = EV_MODIFIERS (theEvent);
6462 EV_TRAILER (theEvent);
6467 - toggleToolbar: (id)sender
6472 emacs_event->kind = NS_NONKEY_EVENT;
6473 emacs_event->code = KEY_NS_TOGGLE_TOOLBAR;
6474 EV_TRAILER ((id)nil);
6479 - (void)drawRect: (NSRect)rect
6481 int x = NSMinX (rect), y = NSMinY (rect);
6482 int width = NSWidth (rect), height = NSHeight (rect);
6486 if (!emacsframe || !emacsframe->output_data.ns)
6489 ns_clear_frame_area (emacsframe, x, y, width, height);
6490 expose_frame (emacsframe, x, y, width, height);
6493 drawRect: may be called (at least in OS X 10.5) for invisible
6494 views as well for some reason. Thus, do not infer visibility
6497 emacsframe->async_visible = 1;
6498 emacsframe->async_iconified = 0;
6503 /* NSDraggingDestination protocol methods. Actually this is not really a
6504 protocol, but a category of Object. O well... */
6506 -(NSUInteger) draggingEntered: (id <NSDraggingInfo>) sender
6508 NSTRACE (draggingEntered);
6509 return NSDragOperationGeneric;
6513 -(BOOL)prepareForDragOperation: (id <NSDraggingInfo>) sender
6519 -(BOOL)performDragOperation: (id <NSDraggingInfo>) sender
6524 NSEvent *theEvent = [[self window] currentEvent];
6527 NSTRACE (performDragOperation);
6532 position = [self convertPoint: [sender draggingLocation] fromView: nil];
6533 x = lrint (position.x); y = lrint (position.y);
6535 pb = [sender draggingPasteboard];
6536 type = [pb availableTypeFromArray: ns_drag_types];
6541 else if ([type isEqualToString: NSFilenamesPboardType])
6544 NSEnumerator *fenum;
6547 if (!(files = [pb propertyListForType: type]))
6550 fenum = [files objectEnumerator];
6551 while ( (file = [fenum nextObject]) )
6553 emacs_event->kind = NS_NONKEY_EVENT;
6554 emacs_event->code = KEY_NS_DRAG_FILE;
6555 XSETINT (emacs_event->x, x);
6556 XSETINT (emacs_event->y, y);
6557 ns_input_file = append2 (ns_input_file,
6558 build_string ([file UTF8String]));
6559 emacs_event->modifiers = EV_MODIFIERS (theEvent);
6560 EV_TRAILER (theEvent);
6564 else if ([type isEqualToString: NSURLPboardType])
6569 if (!(fileURL = [NSURL URLFromPasteboard: pb]) ||
6570 [fileURL isFileURL] == NO)
6573 file = [fileURL path];
6574 emacs_event->kind = NS_NONKEY_EVENT;
6575 emacs_event->code = KEY_NS_DRAG_FILE;
6576 XSETINT (emacs_event->x, x);
6577 XSETINT (emacs_event->y, y);
6578 ns_input_file = append2 (ns_input_file, build_string ([file UTF8String]));
6579 emacs_event->modifiers = EV_MODIFIERS (theEvent);
6580 EV_TRAILER (theEvent);
6583 else if ([type isEqualToString: NSStringPboardType]
6584 || [type isEqualToString: NSTabularTextPboardType])
6588 if (! (data = [pb stringForType: type]))
6591 emacs_event->kind = NS_NONKEY_EVENT;
6592 emacs_event->code = KEY_NS_DRAG_TEXT;
6593 XSETINT (emacs_event->x, x);
6594 XSETINT (emacs_event->y, y);
6595 ns_input_text = build_string ([data UTF8String]);
6596 emacs_event->modifiers = EV_MODIFIERS (theEvent);
6597 EV_TRAILER (theEvent);
6600 else if ([type isEqualToString: NSColorPboardType])
6602 NSColor *c = [NSColor colorFromPasteboard: pb];
6603 emacs_event->kind = NS_NONKEY_EVENT;
6604 emacs_event->code = KEY_NS_DRAG_COLOR;
6605 XSETINT (emacs_event->x, x);
6606 XSETINT (emacs_event->y, y);
6607 ns_input_color = ns_color_to_lisp (c);
6608 emacs_event->modifiers = EV_MODIFIERS (theEvent);
6609 EV_TRAILER (theEvent);
6612 else if ([type isEqualToString: NSFontPboardType])
6614 /* impl based on GNUstep NSTextView.m */
6615 NSData *data = [pb dataForType: NSFontPboardType];
6616 NSDictionary *dict = [NSUnarchiver unarchiveObjectWithData: data];
6617 NSFont *font = [dict objectForKey: NSFontAttributeName];
6623 emacs_event->kind = NS_NONKEY_EVENT;
6624 emacs_event->code = KEY_NS_CHANGE_FONT;
6625 XSETINT (emacs_event->x, x);
6626 XSETINT (emacs_event->y, y);
6627 ns_input_font = build_string ([[font fontName] UTF8String]);
6628 snprintf (fontSize, 10, "%f", [font pointSize]);
6629 ns_input_fontsize = build_string (fontSize);
6630 emacs_event->modifiers = EV_MODIFIERS (theEvent);
6631 EV_TRAILER (theEvent);
6636 error ("Invalid data type in dragging pasteboard.");
6642 - (id) validRequestorForSendType: (NSString *)typeSent
6643 returnType: (NSString *)typeReturned
6645 NSTRACE (validRequestorForSendType);
6646 if (typeSent != nil && [ns_send_types indexOfObject: typeSent] != NSNotFound
6647 && typeReturned == nil)
6649 if (! NILP (ns_get_local_selection (QPRIMARY, QUTF8_STRING)))
6653 return [super validRequestorForSendType: typeSent
6654 returnType: typeReturned];
6658 /* The next two methods are part of NSServicesRequests informal protocol,
6659 supposedly called when a services menu item is chosen from this app.
6660 But this should not happen because we override the services menu with our
6661 own entries which call ns-perform-service.
6662 Nonetheless, it appeared to happen (under strange circumstances): bug#1435.
6663 So let's at least stub them out until further investigation can be done. */
6665 - (BOOL
) readSelectionFromPasteboard
: (NSPasteboard
*)pb
6667 /* we could call ns_string_from_pasteboard(pboard) here but then it should
6668 be written into the buffer in place of the existing selection..
6669 ordinary service calls go through functions defined in ns-win.el */
6673 - (BOOL
) writeSelectionToPasteboard
: (NSPasteboard
*)pb types
: (NSArray
*)types
6675 NSArray
*typesDeclared
;
6678 /* We only support NSStringPboardType */
6679 if ([types containsObject
:NSStringPboardType
] == NO
) {
6683 val
= ns_get_local_selection
(QPRIMARY
, QUTF8_STRING
);
6684 if (CONSP
(val
) && SYMBOLP
(XCAR
(val
)))
6687 if (CONSP
(val
) && NILP
(XCDR
(val
)))
6690 if (! STRINGP
(val
))
6693 typesDeclared
= [NSArray arrayWithObject
:NSStringPboardType
];
6694 [pb declareTypes
:typesDeclared owner
:nil
];
6695 ns_string_to_pasteboard
(pb
, val
);
6700 /* setMini =YES means set from internal (gives a finder icon), NO means set nil
6701 (gives a miniaturized version of the window); currently we use the latter for
6702 frames whose active buffer doesn't correspond to any file
6703 (e.g., '*scratch*') */
6704 - setMiniwindowImage
: (BOOL
) setMini
6706 id
image = [[self window
] miniwindowImage
];
6707 NSTRACE
(setMiniwindowImage
);
6709 /* NOTE: under Cocoa miniwindowImage always returns nil, documentation
6710 about "AppleDockIconEnabled" notwithstanding, however the set message
6711 below has its effect nonetheless. */
6712 if (image != emacsframe
->output_data.ns
->miniimage
)
6714 if (image && [image isKindOfClass
: [EmacsImage
class]])
6716 [[self window
] setMiniwindowImage
:
6717 setMini ? emacsframe
->output_data.ns
->miniimage
: nil
];
6724 - (void
) setRows
: (int
) r andColumns
: (int
) c
6730 @
end /* EmacsView */
6734 /* ==========================================================================
6736 EmacsWindow implementation
6738 ========================================================================== */
6740 @implementation EmacsWindow
6742 #ifdef NS_IMPL_COCOA
6743 - (id
)accessibilityAttributeValue
:(NSString
*)attribute
6745 Lisp_Object str
= Qnil
;
6746 struct frame
*f
= SELECTED_FRAME
();
6747 struct buffer
*curbuf
= XBUFFER
(XWINDOW
(f
->selected_window
)->contents
);
6749 if ([attribute isEqualToString
:NSAccessibilityRoleAttribute
])
6750 return NSAccessibilityTextFieldRole
;
6752 if ([attribute isEqualToString
:NSAccessibilitySelectedTextAttribute
]
6753 && curbuf
&& ! NILP
(BVAR
(curbuf
, mark_active
)))
6755 str
= ns_get_local_selection
(QPRIMARY
, QUTF8_STRING
);
6757 else if (curbuf
&& [attribute isEqualToString
:NSAccessibilityValueAttribute
])
6759 if (! NILP
(BVAR
(curbuf
, mark_active
)))
6760 str
= ns_get_local_selection
(QPRIMARY
, QUTF8_STRING
);
6764 ptrdiff_t start_byte
= BUF_BEGV_BYTE
(curbuf
);
6765 ptrdiff_t byte_range
= BUF_ZV_BYTE
(curbuf
) - start_byte
;
6766 ptrdiff_t range
= BUF_ZV
(curbuf
) - BUF_BEGV
(curbuf
);
6768 if (! NILP
(BVAR
(curbuf
, enable_multibyte_characters
)))
6769 str
= make_uninit_multibyte_string
(range
, byte_range
);
6771 str
= make_uninit_string
(range
);
6772 /* To check: This returns emacs-utf-8, which is a superset of utf-8.
6773 Is this a problem? */
6774 memcpy
(SDATA
(str
), BYTE_POS_ADDR
(start_byte
), byte_range
);
6781 if (CONSP
(str
) && SYMBOLP
(XCAR
(str
)))
6784 if (CONSP
(str
) && NILP
(XCDR
(str
)))
6789 const
char *utfStr
= SSDATA
(str
);
6790 NSString
*nsStr
= [NSString stringWithUTF8String
: utfStr
];
6795 return [super accessibilityAttributeValue
:attribute
];
6797 #endif
/* NS_IMPL_COCOA */
6799 /* If we have multiple monitors, one above the other, we don't want to
6800 restrict the height to just one monitor. So we override this. */
6801 - (NSRect
)constrainFrameRect
:(NSRect
)frameRect toScreen
:(NSScreen
*)screen
6803 /* When making the frame visible for the first time or if there is just
6804 one screen, we want to constrain. Other times not. */
6805 NSUInteger nr_screens
= [[NSScreen screens
] count
];
6806 struct frame
*f
= ((EmacsView
*)[self delegate
])->emacsframe
;
6807 NSTRACE
(constrainFrameRect
);
6809 if (nr_screens
== 1)
6811 NSRect r
= [super constrainFrameRect
:frameRect toScreen
:screen
];
6815 if (f
->output_data.ns
->dont_constrain
6816 || ns_menu_bar_should_be_hidden
())
6819 f
->output_data.ns
->dont_constrain
= 1;
6820 return [super constrainFrameRect
:frameRect toScreen
:screen
];
6823 @
end /* EmacsWindow */
6826 @implementation EmacsFSWindow
6828 - (BOOL
)canBecomeKeyWindow
6833 - (BOOL
)canBecomeMainWindow
6840 /* ==========================================================================
6842 EmacsScroller implementation
6844 ========================================================================== */
6847 @implementation EmacsScroller
6849 /* for repeat button push */
6850 #define SCROLL_BAR_FIRST_DELAY
0.5
6851 #define SCROLL_BAR_CONTINUOUS_DELAY
(1.0 / 15)
6853 + (CGFloat
) scrollerWidth
6855 /* TODO: if we want to allow variable widths, this is the place to do it,
6856 however neither GNUstep nor Cocoa support it very well */
6857 return [NSScroller scrollerWidth
];
6861 - initFrame
: (NSRect
)r window
: (Lisp_Object
)nwin
6863 NSTRACE
(EmacsScroller_initFrame
);
6865 r.
size.width
= [EmacsScroller scrollerWidth
];
6866 [super initWithFrame
: r
/*NSMakeRect (0, 0, 0, 0)*/];
6867 [self setContinuous
: YES
];
6868 [self setEnabled
: YES
];
6870 /* Ensure auto resizing of scrollbars occurs within the emacs frame's view
6871 locked against the top and bottom edges, and right edge on OS X, where
6872 scrollers are on right. */
6873 #ifdef NS_IMPL_GNUSTEP
6874 [self setAutoresizingMask
: NSViewMaxXMargin | NSViewHeightSizable
];
6876 [self setAutoresizingMask
: NSViewMinXMargin | NSViewHeightSizable
];
6881 pixel_height
= NSHeight
(r
);
6882 if (pixel_height
== 0) pixel_height
= 1;
6883 min_portion
= 20 / pixel_height
;
6885 frame
= XFRAME
(XWINDOW
(win
)->frame
);
6886 if (FRAME_LIVE_P
(frame
))
6889 EmacsView
*view = FRAME_NS_VIEW
(frame
);
6890 NSView
*sview
= [[view window
] contentView
];
6891 NSArray
*subs
= [sview subviews
];
6893 /* disable optimization stopping redraw of other scrollbars */
6894 view->scrollbarsNeedingUpdate
= 0;
6895 for (i
=[subs count
]-1; i
>= 0; i
--)
6896 if ([[subs objectAtIndex
: i
] isKindOfClass
: [EmacsScroller
class]])
6897 view->scrollbarsNeedingUpdate
++;
6898 [sview addSubview
: self
];
6901 /* [self setFrame: r]; */
6907 - (void
)setFrame
: (NSRect
)newRect
6909 NSTRACE
(EmacsScroller_setFrame
);
6910 /* block_input (); */
6911 pixel_height
= NSHeight
(newRect
);
6912 if (pixel_height
== 0) pixel_height
= 1;
6913 min_portion
= 20 / pixel_height
;
6914 [super setFrame
: newRect
];
6916 /* unblock_input (); */
6922 NSTRACE
(EmacsScroller_dealloc
);
6924 wset_vertical_scroll_bar
(XWINDOW
(win
), Qnil
);
6952 /* ensure other scrollbar updates after deletion */
6953 view = (EmacsView
*)FRAME_NS_VIEW
(frame
);
6955 view->scrollbarsNeedingUpdate
++;
6956 [self removeFromSuperview
];
6964 - (void
)resetCursorRects
6966 NSRect visible
= [self visibleRect
];
6967 NSTRACE
(resetCursorRects
);
6969 if (!NSIsEmptyRect
(visible
))
6970 [self addCursorRect
: visible cursor
: [NSCursor arrowCursor
]];
6971 [[NSCursor arrowCursor
] setOnMouseEntered
: YES
];
6975 - (int
) checkSamePosition
: (int
) position portion
: (int
) portion
6978 return em_position
==position
&& em_portion
==portion
&& em_whole
==whole
6979 && portion
!= whole
; /* needed for resize empty buf */
6983 - setPosition
: (int
)position portion
: (int
)portion whole
: (int
)whole
6985 NSTRACE
(setPosition
);
6987 em_position
= position
;
6988 em_portion
= portion
;
6991 if (portion
>= whole
)
6993 #
if defined
(NS_IMPL_COCOA
) && MAC_OS_X_VERSION_MAX_ALLOWED
> MAC_OS_X_VERSION_10_5
6994 [self setKnobProportion
: 1.0];
6995 [self setDoubleValue
: 1.0];
6997 [self setFloatValue
: 0.0 knobProportion
: 1.0];
7004 portion
= max ((float
)whole
*min_portion
/pixel_height
, portion
);
7005 pos
= (float
)position
/ (whole
- portion
);
7006 por
= (CGFloat
)portion
/whole
;
7007 #
if defined
(NS_IMPL_COCOA
) && MAC_OS_X_VERSION_MAX_ALLOWED
> MAC_OS_X_VERSION_10_5
7008 [self setKnobProportion
: por
];
7009 [self setDoubleValue
: pos
];
7011 [self setFloatValue
: pos knobProportion
: por
];
7015 /* Events may come here even if the event loop is not running.
7016 If we don't enter the event loop, the scroll bar will not update.
7017 So send SIGIO to ourselves. */
7018 if (apploopnr
== 0) raise
(SIGIO
);
7023 /* FIXME: unused at moment (see ns_mouse_position) at the moment because
7024 drag events will go directly to the EmacsScroller. Leaving in for now. */
7025 -(void
)getMouseMotionPart
: (int
*)part window
: (Lisp_Object
*)window
7026 x
: (Lisp_Object
*)x y
: ( Lisp_Object
*)y
7028 *part
= last_hit_part
;
7030 XSETINT
(*y
, pixel_height
);
7031 if ([self floatValue
] > 0.999F
)
7032 XSETINT
(*x
, pixel_height
);
7034 XSETINT
(*x
, pixel_height
* [self floatValue
]);
7038 /* set up emacs_event */
7039 - (void
) sendScrollEventAtLoc
: (float
)loc fromEvent
: (NSEvent
*)e
7044 emacs_event
->part
= last_hit_part
;
7045 emacs_event
->code
= 0;
7046 emacs_event
->modifiers
= EV_MODIFIERS
(e
) | down_modifier
;
7047 emacs_event
->frame_or_window
= win
;
7048 emacs_event
->timestamp
= EV_TIMESTAMP
(e
);
7049 emacs_event
->kind
= SCROLL_BAR_CLICK_EVENT
;
7050 emacs_event
->arg
= Qnil
;
7051 XSETINT
(emacs_event
->x
, loc
* pixel_height
);
7052 XSETINT
(emacs_event
->y
, pixel_height
-20);
7056 n_emacs_events_pending
++;
7057 kbd_buffer_store_event_hold
(emacs_event
, q_event_ptr
);
7060 hold_event
(emacs_event
);
7061 EVENT_INIT
(*emacs_event
);
7062 ns_send_appdefined
(-1);
7066 /* called manually thru timer to implement repeated button action w/hold-down */
7067 - repeatScroll
: (NSTimer
*)scrollEntry
7069 NSEvent
*e
= [[self window
] currentEvent
];
7070 NSPoint p
= [[self window
] mouseLocationOutsideOfEventStream
];
7071 BOOL inKnob
= [self testPart
: p
] == NSScrollerKnob
;
7073 /* clear timer if need be */
7074 if (inKnob ||
[scroll_repeat_entry timeInterval
] == SCROLL_BAR_FIRST_DELAY
)
7076 [scroll_repeat_entry invalidate
];
7077 [scroll_repeat_entry release
];
7078 scroll_repeat_entry
= nil
;
7084 = [[NSTimer scheduledTimerWithTimeInterval
:
7085 SCROLL_BAR_CONTINUOUS_DELAY
7087 selector
: @selector
(repeatScroll
:)
7093 [self sendScrollEventAtLoc
: 0 fromEvent
: e
];
7098 /* Asynchronous mouse tracking for scroller. This allows us to dispatch
7099 mouseDragged events without going into a modal loop. */
7100 - (void
)mouseDown
: (NSEvent
*)e
7103 /* hitPart is only updated AFTER event is passed on */
7104 NSScrollerPart part
= [self testPart
: [e locationInWindow
]];
7105 CGFloat inc
= 0.0, loc
, kloc
, pos
;
7108 NSTRACE
(EmacsScroller_mouseDown
);
7112 case NSScrollerDecrementPage
:
7113 last_hit_part
= scroll_bar_above_handle
; inc
= -1.0; break;
7114 case NSScrollerIncrementPage
:
7115 last_hit_part
= scroll_bar_below_handle
; inc
= 1.0; break;
7116 case NSScrollerDecrementLine
:
7117 last_hit_part
= scroll_bar_up_arrow
; inc
= -0.1; break;
7118 case NSScrollerIncrementLine
:
7119 last_hit_part
= scroll_bar_down_arrow
; inc
= 0.1; break;
7120 case NSScrollerKnob
:
7121 last_hit_part
= scroll_bar_handle
; break;
7122 case NSScrollerKnobSlot
: /* GNUstep-only */
7123 last_hit_part
= scroll_bar_move_ratio
; break;
7124 default
: /* NSScrollerNoPart? */
7125 fprintf (stderr
, "EmacsScoller
-mouseDown
: unexpected part
%ld\n",
7132 pos
= 0; /* ignored */
7134 /* set a timer to repeat, as we can't let superclass do this modally */
7136 = [[NSTimer scheduledTimerWithTimeInterval
: SCROLL_BAR_FIRST_DELAY
7138 selector
: @selector
(repeatScroll
:)
7145 /* handle, or on GNUstep possibly slot */
7146 NSEvent
*fake_event
;
7148 /* compute float loc in slot and mouse offset on knob */
7149 sr
= [self convertRect
: [self rectForPart
: NSScrollerKnobSlot
]
7151 loc
= NSHeight
(sr
) - ([e locationInWindow
].y
- NSMinY
(sr
));
7157 else if (loc
>= NSHeight
(sr
))
7159 loc
= NSHeight
(sr
);
7167 kr
= [self convertRect
: [self rectForPart
: NSScrollerKnob
]
7169 kloc
= NSHeight
(kr
) - ([e locationInWindow
].y
- NSMinY
(kr
));
7171 last_mouse_offset
= kloc
;
7173 /* if knob, tell emacs a location offset by knob pos
7174 (to indicate top of handle) */
7175 if (part
== NSScrollerKnob
)
7176 pos
= (loc
- last_mouse_offset
) / NSHeight
(sr
);
7178 /* else this is a slot click on GNUstep: go straight there */
7179 pos
= loc
/ NSHeight
(sr
);
7181 /* send a fake mouse-up to super to preempt modal -trackKnob: mode */
7182 fake_event
= [NSEvent mouseEventWithType
: NSLeftMouseUp
7183 location
: [e locationInWindow
]
7184 modifierFlags
: [e modifierFlags
]
7185 timestamp
: [e timestamp
]
7186 windowNumber
: [e windowNumber
]
7187 context
: [e context
]
7188 eventNumber
: [e eventNumber
]
7189 clickCount
: [e clickCount
]
7190 pressure
: [e pressure
]];
7191 [super mouseUp
: fake_event
];
7194 if (part
!= NSScrollerKnob
)
7195 [self sendScrollEventAtLoc
: pos fromEvent
: e
];
7199 /* Called as we manually track scroller drags, rather than superclass. */
7200 - (void
)mouseDragged
: (NSEvent
*)e
7205 NSTRACE
(EmacsScroller_mouseDragged
);
7207 sr
= [self convertRect
: [self rectForPart
: NSScrollerKnobSlot
]
7209 loc
= NSHeight
(sr
) - ([e locationInWindow
].y
- NSMinY
(sr
));
7215 else if (loc
>= NSHeight
(sr
) + last_mouse_offset
)
7217 loc
= NSHeight
(sr
) + last_mouse_offset
;
7220 pos
= (loc
- last_mouse_offset
) / NSHeight
(sr
);
7221 [self sendScrollEventAtLoc
: pos fromEvent
: e
];
7225 - (void
)mouseUp
: (NSEvent
*)e
7227 if (scroll_repeat_entry
)
7229 [scroll_repeat_entry invalidate
];
7230 [scroll_repeat_entry release
];
7231 scroll_repeat_entry
= nil
;
7237 /* treat scrollwheel events in the bar as though they were in the main window */
7238 - (void
) scrollWheel
: (NSEvent
*)theEvent
7240 EmacsView
*view = (EmacsView
*)FRAME_NS_VIEW
(frame
);
7241 [view mouseDown
: theEvent
];
7244 @
end /* EmacsScroller */
7247 #ifdef NS_IMPL_GNUSTEP
7248 /* Dummy class to get rid of startup warnings. */
7249 @implementation EmacsDocument
7255 /* ==========================================================================
7257 Font-related functions; these used to be in nsfaces.m
7259 ========================================================================== */
7263 x_new_font
(struct frame
*f
, Lisp_Object font_object
, int fontset
)
7265 struct font
*font
= XFONT_OBJECT
(font_object
);
7268 fontset
= fontset_from_font
(font_object
);
7269 FRAME_FONTSET
(f
) = fontset
;
7271 if (FRAME_FONT
(f
) == font
)
7272 /* This font is already set in frame F. There's nothing more to
7276 FRAME_FONT
(f
) = font
;
7278 FRAME_BASELINE_OFFSET
(f
) = font
->baseline_offset
;
7279 FRAME_COLUMN_WIDTH
(f
) = font
->average_width
;
7280 FRAME_LINE_HEIGHT
(f
) = font
->height
;
7282 compute_fringe_widths
(f
, 1);
7284 /* Compute the scroll bar width in character columns. */
7285 if (FRAME_CONFIG_SCROLL_BAR_WIDTH
(f
) > 0)
7287 int wid
= FRAME_COLUMN_WIDTH
(f
);
7288 FRAME_CONFIG_SCROLL_BAR_COLS
(f
)
7289 = (FRAME_CONFIG_SCROLL_BAR_WIDTH
(f
) + wid
- 1) / wid
;
7293 int wid
= FRAME_COLUMN_WIDTH
(f
);
7294 FRAME_CONFIG_SCROLL_BAR_COLS
(f
) = (14 + wid
- 1) / wid
;
7297 /* Now make the frame display the given font. */
7298 if (FRAME_NS_WINDOW
(f
) != 0)
7299 x_set_window_size
(f
, 0, FRAME_COLS
(f
), FRAME_LINES
(f
));
7305 /* XLFD: -foundry-family-weight-slant-swidth-adstyle-pxlsz-ptSz-resx-resy-spc-avgWidth-rgstry-encoding */
7306 /* Note: ns_font_to_xlfd and ns_fontname_to_xlfd no longer needed, removed
7310 ns_xlfd_to_fontname
(const
char *xlfd
)
7311 /* --------------------------------------------------------------------------
7312 Convert an X font name (XLFD) to an NS font name.
7313 Only family is used.
7314 The string returned is temporarily allocated.
7315 -------------------------------------------------------------------------- */
7317 char *name
= xmalloc
(180);
7321 if (!strncmp
(xlfd
, "
--"
, 2))
7322 sscanf (xlfd
, "
--%*[^-]-%[^-]179-", name);
7324 sscanf (xlfd
, "
-%*[^-]-%[^-]179-", name);
7326 /* stopgap for malformed XLFD input */
7327 if (strlen
(name
) == 0)
7328 strcpy
(name
, "Monaco"
);
7330 /* undo hack in ns_fontname_to_xlfd, converting '$' to '-', '_' to ' '
7331 also uppercase after '-' or ' ' */
7332 name
[0] = c_toupper
(name
[0]);
7333 for (len
=strlen
(name
), i
=0; i
<len
; i
++)
7339 name
[i
+1] = c_toupper
(name
[i
+1]);
7341 else if (name
[i
] == '_')
7345 name
[i
+1] = c_toupper
(name
[i
+1]);
7348 /*fprintf (stderr, "converted '%s' to '%s'\n",xlfd,name); */
7349 ret
= [[NSString stringWithUTF8String
: name
] UTF8String
];
7356 syms_of_nsterm
(void
)
7358 NSTRACE
(syms_of_nsterm
);
7360 ns_antialias_threshold
= 10.0;
7362 /* from 23+ we need to tell emacs what modifiers there are.. */
7363 DEFSYM
(Qmodifier_value
, "modifier
-value"
);
7364 DEFSYM
(Qalt
, "alt"
);
7365 DEFSYM
(Qhyper
, "hyper"
);
7366 DEFSYM
(Qmeta
, "
meta"
);
7367 DEFSYM
(Qsuper
, "super"
);
7368 DEFSYM
(Qcontrol
, "control"
);
7369 DEFSYM
(QUTF8_STRING
, "UTF8_STRING"
);
7371 Fput
(Qalt
, Qmodifier_value
, make_number
(alt_modifier
));
7372 Fput
(Qhyper
, Qmodifier_value
, make_number
(hyper_modifier
));
7373 Fput
(Qmeta
, Qmodifier_value
, make_number
(meta_modifier
));
7374 Fput
(Qsuper
, Qmodifier_value
, make_number
(super_modifier
));
7375 Fput
(Qcontrol
, Qmodifier_value
, make_number
(ctrl_modifier
));
7377 DEFVAR_LISP
("ns
-input-file"
, ns_input_file
,
7378 "The file specified in the last NS event."
);
7379 ns_input_file
=Qnil
;
7381 DEFVAR_LISP
("ns
-input-text"
, ns_input_text
,
7382 "The data received in the last NS
text drag event."
);
7383 ns_input_text
=Qnil
;
7385 DEFVAR_LISP
("ns
-working
-text"
, ns_working_text
,
7386 "String
for visualizing working composition sequence."
);
7387 ns_working_text
=Qnil
;
7389 DEFVAR_LISP
("ns
-input-font"
, ns_input_font
,
7390 "The font specified in the last NS event."
);
7391 ns_input_font
=Qnil
;
7393 DEFVAR_LISP
("ns
-input-fontsize"
, ns_input_fontsize
,
7394 "The fontsize specified in the last NS event."
);
7395 ns_input_fontsize
=Qnil
;
7397 DEFVAR_LISP
("ns
-input-line"
, ns_input_line
,
7398 "The
line specified in the last NS event."
);
7399 ns_input_line
=Qnil
;
7401 DEFVAR_LISP
("ns
-input-color"
, ns_input_color
,
7402 "The color specified in the last NS event."
);
7403 ns_input_color
=Qnil
;
7405 DEFVAR_LISP
("ns
-input-spi
-name"
, ns_input_spi_name
,
7406 "The service name specified in the last NS event."
);
7407 ns_input_spi_name
=Qnil
;
7409 DEFVAR_LISP
("ns
-input-spi
-arg"
, ns_input_spi_arg
,
7410 "The service argument specified in the last NS event."
);
7411 ns_input_spi_arg
=Qnil
;
7413 DEFVAR_LISP
("ns
-alternate
-modifier"
, ns_alternate_modifier
,
7414 "This variable describes the behavior of the alternate or option key.
\n\
7415 Set to control
, meta, alt
, super
, or hyper means it is taken to be that key.
\n\
7416 Set to none means that the alternate
/ option key is not interpreted by Emacs
\n\
7417 at
all, allowing it to be used at a
lower level
for accented character entry."
);
7418 ns_alternate_modifier
= Qmeta
;
7420 DEFVAR_LISP
("ns
-right
-alternate
-modifier"
, ns_right_alternate_modifier
,
7421 "This variable describes the behavior of the right alternate or option key.
\n\
7422 Set to control
, meta, alt
, super
, or hyper means it is taken to be that key.
\n\
7423 Set to left means be the same key as `ns
-alternate
-modifier
'.\n\
7424 Set to none means that the alternate / option key is not interpreted by Emacs\n\
7425 at all, allowing it to be used at a lower level for accented character entry.");
7426 ns_right_alternate_modifier = Qleft;
7428 DEFVAR_LISP ("ns-command-modifier", ns_command_modifier,
7429 "This variable describes the behavior of the command key.\n\
7430 Set to control, meta, alt, super, or hyper means it is taken to be that key.");
7431 ns_command_modifier = Qsuper;
7433 DEFVAR_LISP ("ns-right-command-modifier", ns_right_command_modifier,
7434 "This variable describes the behavior of the right command key.\n\
7435 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7436 Set to left means be the same key as `ns-command-modifier'.
\n\
7437 Set to none means that the command
/ option key is not interpreted by Emacs
\n\
7438 at
all, allowing it to be used at a
lower level
for accented character entry."
);
7439 ns_right_command_modifier
= Qleft
;
7441 DEFVAR_LISP
("ns
-control
-modifier"
, ns_control_modifier
,
7442 "This variable describes the behavior of the control key.
\n\
7443 Set to control
, meta, alt
, super
, or hyper means it is taken to be that key."
);
7444 ns_control_modifier
= Qcontrol
;
7446 DEFVAR_LISP
("ns
-right
-control
-modifier"
, ns_right_control_modifier
,
7447 "This variable describes the behavior of the right control key.
\n\
7448 Set to control
, meta, alt
, super
, or hyper means it is taken to be that key.
\n\
7449 Set to left means be the same key as `ns
-control
-modifier
'.\n\
7450 Set to none means that the control / option key is not interpreted by Emacs\n\
7451 at all, allowing it to be used at a lower level for accented character entry.");
7452 ns_right_control_modifier = Qleft;
7454 DEFVAR_LISP ("ns-function-modifier", ns_function_modifier,
7455 "This variable describes the behavior of the function key (on laptops).\n\
7456 Set to control, meta, alt, super, or hyper means it is taken to be that key.\n\
7457 Set to none means that the function key is not interpreted by Emacs at all,\n\
7458 allowing it to be used at a lower level for accented character entry.");
7459 ns_function_modifier = Qnone;
7461 DEFVAR_LISP ("ns-antialias-text", ns_antialias_text,
7462 "Non-nil (the default) means to render text antialiased.");
7463 ns_antialias_text = Qt;
7465 DEFVAR_LISP ("ns-confirm-quit", ns_confirm_quit,
7466 "Whether to confirm application quit using dialog.");
7467 ns_confirm_quit = Qnil;
7469 staticpro (&ns_display_name_list);
7470 ns_display_name_list = Qnil;
7472 DEFVAR_LISP ("ns-auto-hide-menu-bar", ns_auto_hide_menu_bar,
7473 doc: /* Non-nil means that the menu bar is hidden, but appears when the mouse is near.
7474 Only works on OSX 10.6 or later. */);
7475 ns_auto_hide_menu_bar = Qnil;
7477 DEFVAR_BOOL ("ns-use-native-fullscreen", ns_use_native_fullscreen,
7478 doc: /*Non-nil means to use native fullscreen on OSX >= 10.7.
7479 Nil means use fullscreen the old (< 10.7) way. The old way works better with
7480 multiple monitors, but lacks tool bar. This variable is ignored on OSX < 10.7.
7481 Default is t for OSX >= 10.7, nil otherwise. */);
7482 #ifdef HAVE_NATIVE_FS
7483 ns_use_native_fullscreen = YES;
7485 ns_use_native_fullscreen = NO;
7487 ns_last_use_native_fullscreen = ns_use_native_fullscreen;
7489 /* TODO: move to common code */
7490 DEFVAR_LISP ("x-toolkit-scroll-bars", Vx_toolkit_scroll_bars,
7491 doc: /* Which toolkit scroll bars Emacs uses, if any.
7492 A value of nil means Emacs doesn't use toolkit scroll bars.
7493 With the X Window system
, the value is a symbol describing the
7494 X toolkit. Possible values are
: gtk
, motif
, xaw
, or xaw3d.
7495 With MS Windows or Nextstep
, the value is t. */
);
7496 Vx_toolkit_scroll_bars
= Qt
;
7498 DEFVAR_BOOL
("x
-use
-underline
-position
-properties"
,
7499 x_use_underline_position_properties
,
7500 doc: /*Non-nil means make use of UNDERLINE_POSITION font properties.
7501 A value of nil means ignore them. If you encounter fonts with bogus
7502 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
7503 to 4.1, set this to nil. */);
7504 x_use_underline_position_properties
= 0;
7506 DEFVAR_BOOL
("x
-underline
-at
-descent
-line"
,
7507 x_underline_at_descent_line
,
7508 doc: /* Non-nil means to draw the underline at the same place as the descent line.
7509 A value of nil means to draw the underline according to the value of the
7510 variable `x-use-underline-position-properties', which is usually at the
7511 baseline level. The default value is nil. */);
7512 x_underline_at_descent_line
= 0;
7514 /* Tell Emacs about this window system. */
7515 Fprovide
(Qns
, Qnil
);
7518 #ifdef NS_IMPL_COCOA
7519 #
if MAC_OS_X_VERSION_MAX_ALLOWED
>= 1050