Support for packages in Python shell.
[emacs.git] / src / nsfns.m
blob8f1a45d03f1279ceeb9f5ca37a19db2f3f75d867
1 /* Functions for the NeXT/Open/GNUstep and MacOSX window system.
3 Copyright (C) 1989, 1992-1994, 2005-2006, 2008-2014 Free Software
4 Foundation, Inc.
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. */
31 #include <config.h>
33 #include <math.h>
34 #include <c-strcase.h>
36 #include "lisp.h"
37 #include "blockinput.h"
38 #include "nsterm.h"
39 #include "window.h"
40 #include "character.h"
41 #include "buffer.h"
42 #include "keyboard.h"
43 #include "termhooks.h"
44 #include "fontset.h"
45 #include "font.h"
47 #ifdef NS_IMPL_COCOA
48 #include <IOKit/graphics/IOGraphicsLib.h>
49 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
50 #include "macfont.h"
51 #endif
52 #endif
54 #if 0
55 int fns_trace_num = 1;
56 #define NSTRACE(x)        fprintf (stderr, "%s:%d: [%d] " #x "\n",        \
57                                   __FILE__, __LINE__, ++fns_trace_num)
58 #else
59 #define NSTRACE(x)
60 #endif
62 #ifdef HAVE_NS
64 extern NSArray *ns_send_types, *ns_return_types, *ns_drag_types;
66 extern Lisp_Object Qforeground_color;
67 extern Lisp_Object Qbackground_color;
68 extern Lisp_Object Qcursor_color;
69 extern Lisp_Object Qinternal_border_width;
70 extern Lisp_Object Qvisibility;
71 extern Lisp_Object Qcursor_type;
72 extern Lisp_Object Qicon_type;
73 extern Lisp_Object Qicon_name;
74 extern Lisp_Object Qicon_left;
75 extern Lisp_Object Qicon_top;
76 extern Lisp_Object Qtop;
77 extern Lisp_Object Qdisplay;
78 extern Lisp_Object Qvertical_scroll_bars;
79 extern Lisp_Object Qauto_raise;
80 extern Lisp_Object Qauto_lower;
81 extern Lisp_Object Qbox;
82 extern Lisp_Object Qscroll_bar_width;
83 extern Lisp_Object Qx_resource_name;
84 extern Lisp_Object Qface_set_after_frame_default;
85 extern Lisp_Object Qunderline, Qundefined;
86 extern Lisp_Object Qheight, Qminibuffer, Qname, Qonly, Qwidth;
87 extern Lisp_Object Qunsplittable, Qmenu_bar_lines, Qbuffer_predicate, Qtitle;
90 Lisp_Object Qbuffered;
91 Lisp_Object Qfontsize;
93 EmacsTooltip *ns_tooltip = nil;
95 /* Need forward declaration here to preserve organizational integrity of file */
96 Lisp_Object Fx_open_connection (Lisp_Object, Lisp_Object, Lisp_Object);
98 /* Static variables to handle applescript execution.  */
99 static Lisp_Object as_script, *as_result;
100 static int as_status;
102 #ifdef GLYPH_DEBUG
103 static ptrdiff_t image_cache_refcount;
104 #endif
107 /* ==========================================================================
109     Internal utility functions
111    ========================================================================== */
113 /* Let the user specify a Nextstep display with a Lisp object.
114    OBJECT may be nil, a frame or a terminal object.
115    nil stands for the selected frame--or, if that is not a Nextstep frame,
116    the first Nextstep display on the list.  */
118 static struct ns_display_info *
119 check_ns_display_info (Lisp_Object object)
121   struct ns_display_info *dpyinfo = NULL;
123   if (NILP (object))
124     {
125       struct frame *sf = XFRAME (selected_frame);
127       if (FRAME_NS_P (sf) && FRAME_LIVE_P (sf))
128         dpyinfo = FRAME_DISPLAY_INFO (sf);
129       else if (x_display_list != 0)
130         dpyinfo = x_display_list;
131       else
132         error ("Nextstep windows are not in use or not initialized");
133     }
134   else if (TERMINALP (object))
135     {
136       struct terminal *t = get_terminal (object, 1);
138       if (t->type != output_ns)
139         error ("Terminal %d is not a Nextstep display", t->id);
141       dpyinfo = t->display_info.ns;
142     }
143   else if (STRINGP (object))
144     dpyinfo = ns_display_info_for_name (object);
145   else
146     {
147       struct frame *f = decode_window_system_frame (object);
148       dpyinfo = FRAME_DISPLAY_INFO (f);
149     }
151   return dpyinfo;
155 static id
156 ns_get_window (Lisp_Object maybeFrame)
158   id view =nil, window =nil;
160   if (!FRAMEP (maybeFrame) || !FRAME_NS_P (XFRAME (maybeFrame)))
161     maybeFrame = selected_frame;/*wrong_type_argument (Qframep, maybeFrame); */
163   if (!NILP (maybeFrame))
164     view = FRAME_NS_VIEW (XFRAME (maybeFrame));
165   if (view) window =[view window];
167   return window;
171 /* Return the X display structure for the display named NAME.
172    Open a new connection if necessary.  */
173 struct ns_display_info *
174 ns_display_info_for_name (Lisp_Object name)
176   struct ns_display_info *dpyinfo;
178   CHECK_STRING (name);
180   for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
181     if (!NILP (Fstring_equal (XCAR (dpyinfo->name_list_element), name)))
182       return dpyinfo;
184   error ("Emacs for Nextstep does not yet support multi-display");
186   Fx_open_connection (name, Qnil, Qnil);
187   dpyinfo = x_display_list;
189   if (dpyinfo == 0)
190     error ("Display on %s not responding.\n", SDATA (name));
192   return dpyinfo;
195 static NSString *
196 ns_filename_from_panel (NSSavePanel *panel)
198 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
199   NSURL *url = [panel URL];
200   NSString *str = [url path];
201   return str;
202 #else
203   return [panel filename];
204 #endif
207 static NSString *
208 ns_directory_from_panel (NSSavePanel *panel)
210 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
211   NSURL *url = [panel directoryURL];
212   NSString *str = [url path];
213   return str;
214 #else
215   return [panel directory];
216 #endif
219 static Lisp_Object
220 interpret_services_menu (NSMenu *menu, Lisp_Object prefix, Lisp_Object old)
221 /* --------------------------------------------------------------------------
222    Turn the input menu (an NSMenu) into a lisp list for tracking on lisp side
223    -------------------------------------------------------------------------- */
225   int i, count;
226   NSMenuItem *item;
227   const char *name;
228   Lisp_Object nameStr;
229   unsigned short key;
230   NSString *keys;
231   Lisp_Object res;
233   count = [menu numberOfItems];
234   for (i = 0; i<count; i++)
235     {
236       item = [menu itemAtIndex: i];
237       name = [[item title] UTF8String];
238       if (!name) continue;
240       nameStr = build_string (name);
242       if ([item hasSubmenu])
243         {
244           old = interpret_services_menu ([item submenu],
245                                         Fcons (nameStr, prefix), old);
246         }
247       else
248         {
249           keys = [item keyEquivalent];
250           if (keys && [keys length] )
251             {
252               key = [keys characterAtIndex: 0];
253               res = make_number (key|super_modifier);
254             }
255           else
256             {
257               res = Qundefined;
258             }
259           old = Fcons (Fcons (res,
260                             Freverse (Fcons (nameStr,
261                                            prefix))),
262                     old);
263         }
264     }
265   return old;
270 /* ==========================================================================
272     Frame parameter setters
274    ========================================================================== */
277 static void
278 x_set_foreground_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
280   NSColor *col;
281   EmacsCGFloat r, g, b, alpha;
283   if (ns_lisp_to_color (arg, &col))
284     {
285       store_frame_param (f, Qforeground_color, oldval);
286       error ("Unknown color");
287     }
289   [col retain];
290   [f->output_data.ns->foreground_color release];
291   f->output_data.ns->foreground_color = col;
293   [col getRed: &r green: &g blue: &b alpha: &alpha];
294   FRAME_FOREGROUND_PIXEL (f) =
295     ARGB_TO_ULONG ((int)(alpha*0xff), (int)(r*0xff), (int)(g*0xff), (int)(b*0xff));
297   if (FRAME_NS_VIEW (f))
298     {
299       update_face_from_frame_parameter (f, Qforeground_color, arg);
300       /*recompute_basic_faces (f); */
301       if (FRAME_VISIBLE_P (f))
302         redraw_frame (f);
303     }
307 static void
308 x_set_background_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
310   struct face *face;
311   NSColor *col;
312   NSView *view = FRAME_NS_VIEW (f);
313   EmacsCGFloat r, g, b, alpha;
315   if (ns_lisp_to_color (arg, &col))
316     {
317       store_frame_param (f, Qbackground_color, oldval);
318       error ("Unknown color");
319     }
321   /* clear the frame; in some instances the NS-internal GC appears not to
322      update, or it does update and cannot clear old text properly */
323   if (FRAME_VISIBLE_P (f))
324     ns_clear_frame (f);
326   [col retain];
327   [f->output_data.ns->background_color release];
328   f->output_data.ns->background_color = col;
330   [col getRed: &r green: &g blue: &b alpha: &alpha];
331   FRAME_BACKGROUND_PIXEL (f) =
332     ARGB_TO_ULONG ((int)(alpha*0xff), (int)(r*0xff), (int)(g*0xff), (int)(b*0xff));
334   if (view != nil)
335     {
336       [[view window] setBackgroundColor: col];
338       if (alpha != (EmacsCGFloat) 1.0)
339           [[view window] setOpaque: NO];
340       else
341           [[view window] setOpaque: YES];
343       face = FRAME_DEFAULT_FACE (f);
344       if (face)
345         {
346           col = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f);
347           face->background = ns_index_color
348             ([col colorWithAlphaComponent: alpha], f);
350           update_face_from_frame_parameter (f, Qbackground_color, arg);
351         }
353       if (FRAME_VISIBLE_P (f))
354         redraw_frame (f);
355     }
359 static void
360 x_set_cursor_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
362   NSColor *col;
364   if (ns_lisp_to_color (arg, &col))
365     {
366       store_frame_param (f, Qcursor_color, oldval);
367       error ("Unknown color");
368     }
370   [FRAME_CURSOR_COLOR (f) release];
371   FRAME_CURSOR_COLOR (f) = [col retain];
373   if (FRAME_VISIBLE_P (f))
374     {
375       x_update_cursor (f, 0);
376       x_update_cursor (f, 1);
377     }
378   update_face_from_frame_parameter (f, Qcursor_color, arg);
382 static void
383 x_set_icon_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
385   NSView *view = FRAME_NS_VIEW (f);
386   NSTRACE (x_set_icon_name);
388   /* see if it's changed */
389   if (STRINGP (arg))
390     {
391       if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
392         return;
393     }
394   else if (!STRINGP (oldval) && EQ (oldval, Qnil) == EQ (arg, Qnil))
395     return;
397   fset_icon_name (f, arg);
399   if (NILP (arg))
400     {
401       if (!NILP (f->title))
402         arg = f->title;
403       else
404         /* Explicit name and no icon-name -> explicit_name.  */
405         if (f->explicit_name)
406           arg = f->name;
407         else
408           {
409             /* No explicit name and no icon-name ->
410                name has to be rebuild from icon_title_format.  */
411             windows_or_buffers_changed = 62;
412             return;
413           }
414     }
416   /* Don't change the name if it's already NAME.  */
417   if ([[view window] miniwindowTitle]
418       && ([[[view window] miniwindowTitle]
419              isEqualToString: [NSString stringWithUTF8String:
420                                           SSDATA (arg)]]))
421     return;
423   [[view window] setMiniwindowTitle:
424         [NSString stringWithUTF8String: SSDATA (arg)]];
427 static void
428 ns_set_name_internal (struct frame *f, Lisp_Object name)
430   struct gcpro gcpro1;
431   Lisp_Object encoded_name, encoded_icon_name;
432   NSString *str;
433   NSView *view = FRAME_NS_VIEW (f);
435   GCPRO1 (name);
436   encoded_name = ENCODE_UTF_8 (name);
437   UNGCPRO;
439   str = [NSString stringWithUTF8String: SSDATA (encoded_name)];
441   /* Don't change the name if it's already NAME.  */
442   if (! [[[view window] title] isEqualToString: str])
443     [[view window] setTitle: str];
445   if (!STRINGP (f->icon_name))
446     encoded_icon_name = encoded_name;
447   else
448     encoded_icon_name = ENCODE_UTF_8 (f->icon_name);
450   str = [NSString stringWithUTF8String: SSDATA (encoded_icon_name)];
452   if ([[view window] miniwindowTitle]
453       && ! [[[view window] miniwindowTitle] isEqualToString: str])
454     [[view window] setMiniwindowTitle: str];
458 static void
459 ns_set_name (struct frame *f, Lisp_Object name, int explicit)
461   NSTRACE (ns_set_name);
463   /* Make sure that requests from lisp code override requests from
464      Emacs redisplay code.  */
465   if (explicit)
466     {
467       /* If we're switching from explicit to implicit, we had better
468          update the mode lines and thereby update the title.  */
469       if (f->explicit_name && NILP (name))
470         update_mode_lines = 21;
472       f->explicit_name = ! NILP (name);
473     }
474   else if (f->explicit_name)
475     return;
477   if (NILP (name))
478     name = build_string ([ns_app_name UTF8String]);
479   else
480     CHECK_STRING (name);
482   /* Don't change the name if it's already NAME.  */
483   if (! NILP (Fstring_equal (name, f->name)))
484     return;
486   fset_name (f, name);
488   /* Title overrides explicit name.  */
489   if (! NILP (f->title))
490     name = f->title;
492   ns_set_name_internal (f, name);
496 /* This function should be called when the user's lisp code has
497    specified a name for the frame; the name will override any set by the
498    redisplay code.  */
499 static void
500 x_explicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
502   NSTRACE (x_explicitly_set_name);
503   ns_set_name (f, arg, 1);
507 /* This function should be called by Emacs redisplay code to set the
508    name; names set this way will never override names set by the user's
509    lisp code.  */
510 void
511 x_implicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
513   NSTRACE (x_implicitly_set_name);
515   /* Deal with NS specific format t.  */
516   if (FRAME_NS_P (f) && ((FRAME_ICONIFIED_P (f) && EQ (Vicon_title_format, Qt))
517                          || EQ (Vframe_title_format, Qt)))
518     ns_set_name_as_filename (f);
519   else
520     ns_set_name (f, arg, 0);
524 /* Change the title of frame F to NAME.
525    If NAME is nil, use the frame name as the title.  */
527 static void
528 x_set_title (struct frame *f, Lisp_Object name, Lisp_Object old_name)
530   NSTRACE (x_set_title);
531   /* Don't change the title if it's already NAME.  */
532   if (EQ (name, f->title))
533     return;
535   update_mode_lines = 22;
537   fset_title (f, name);
539   if (NILP (name))
540     name = f->name;
541   else
542     CHECK_STRING (name);
544   ns_set_name_internal (f, name);
548 void
549 ns_set_name_as_filename (struct frame *f)
551   NSView *view;
552   Lisp_Object name, filename;
553   Lisp_Object buf = XWINDOW (f->selected_window)->contents;
554   const char *title;
555   NSAutoreleasePool *pool;
556   struct gcpro gcpro1;
557   Lisp_Object encoded_name, encoded_filename;
558   NSString *str;
559   NSTRACE (ns_set_name_as_filename);
561   if (f->explicit_name || ! NILP (f->title))
562     return;
564   block_input ();
565   pool = [[NSAutoreleasePool alloc] init];
566   filename = BVAR (XBUFFER (buf), filename);
567   name = BVAR (XBUFFER (buf), name);
569   if (NILP (name))
570     {
571       if (! NILP (filename))
572         name = Ffile_name_nondirectory (filename);
573       else
574         name = build_string ([ns_app_name UTF8String]);
575     }
577   GCPRO1 (name);
578   encoded_name = ENCODE_UTF_8 (name);
579   UNGCPRO;
581   view = FRAME_NS_VIEW (f);
583   title = FRAME_ICONIFIED_P (f) ? [[[view window] miniwindowTitle] UTF8String]
584                                 : [[[view window] title] UTF8String];
586   if (title && (! strcmp (title, SSDATA (encoded_name))))
587     {
588       [pool release];
589       unblock_input ();
590       return;
591     }
593   str = [NSString stringWithUTF8String: SSDATA (encoded_name)];
594   if (str == nil) str = @"Bad coding";
596   if (FRAME_ICONIFIED_P (f))
597     [[view window] setMiniwindowTitle: str];
598   else
599     {
600       NSString *fstr;
602       if (! NILP (filename))
603         {
604           GCPRO1 (filename);
605           encoded_filename = ENCODE_UTF_8 (filename);
606           UNGCPRO;
608           fstr = [NSString stringWithUTF8String: SSDATA (encoded_filename)];
609           if (fstr == nil) fstr = @"";
610 #ifdef NS_IMPL_COCOA
611           /* work around a bug observed on 10.3 and later where
612              setTitleWithRepresentedFilename does not clear out previous state
613              if given filename does not exist */
614           if (! [[NSFileManager defaultManager] fileExistsAtPath: fstr])
615             [[view window] setRepresentedFilename: @""];
616 #endif
617         }
618       else
619         fstr = @"";
621       [[view window] setRepresentedFilename: fstr];
622       [[view window] setTitle: str];
623       fset_name (f, name);
624     }
626   [pool release];
627   unblock_input ();
631 void
632 ns_set_doc_edited (struct frame *f, Lisp_Object arg)
634   NSView *view = FRAME_NS_VIEW (f);
635   NSAutoreleasePool *pool;
636   if (!MINI_WINDOW_P (XWINDOW (f->selected_window)))
637     {
638       block_input ();
639       pool = [[NSAutoreleasePool alloc] init];
640       [[view window] setDocumentEdited: !NILP (arg)];
641       [pool release];
642       unblock_input ();
643     }
647 void
648 x_set_menu_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
650   int nlines;
651   if (FRAME_MINIBUF_ONLY_P (f))
652     return;
654   if (TYPE_RANGED_INTEGERP (int, value))
655     nlines = XINT (value);
656   else
657     nlines = 0;
659   FRAME_MENU_BAR_LINES (f) = 0;
660   if (nlines)
661     {
662       FRAME_EXTERNAL_MENU_BAR (f) = 1;
663       /* does for all frames, whereas we just want for one frame
664          [NSMenu setMenuBarVisible: YES]; */
665     }
666   else
667     {
668       if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
669         free_frame_menubar (f);
670       /*      [NSMenu setMenuBarVisible: NO]; */
671       FRAME_EXTERNAL_MENU_BAR (f) = 0;
672     }
676 /* toolbar support */
677 void
678 x_set_tool_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
680   int nlines;
682   if (FRAME_MINIBUF_ONLY_P (f))
683     return;
685   if (RANGED_INTEGERP (0, value, INT_MAX))
686     nlines = XFASTINT (value);
687   else
688     nlines = 0;
690   if (nlines)
691     {
692       FRAME_EXTERNAL_TOOL_BAR (f) = 1;
693       update_frame_tool_bar (f);
694     }
695   else
696     {
697       if (FRAME_EXTERNAL_TOOL_BAR (f))
698         {
699           free_frame_tool_bar (f);
700           FRAME_EXTERNAL_TOOL_BAR (f) = 0;
701         }
702     }
704   x_set_window_size (f, 0, f->text_cols, f->text_lines, 0);
708 static void
709 ns_implicitly_set_icon_type (struct frame *f)
711   Lisp_Object tem;
712   EmacsView *view = FRAME_NS_VIEW (f);
713   id image = nil;
714   Lisp_Object chain, elt;
715   NSAutoreleasePool *pool;
716   BOOL setMini = YES;
718   NSTRACE (ns_implicitly_set_icon_type);
720   block_input ();
721   pool = [[NSAutoreleasePool alloc] init];
722   if (f->output_data.ns->miniimage
723       && [[NSString stringWithUTF8String: SSDATA (f->name)]
724                isEqualToString: [(NSImage *)f->output_data.ns->miniimage name]])
725     {
726       [pool release];
727       unblock_input ();
728       return;
729     }
731   tem = assq_no_quit (Qicon_type, f->param_alist);
732   if (CONSP (tem) && ! NILP (XCDR (tem)))
733     {
734       [pool release];
735       unblock_input ();
736       return;
737     }
739   for (chain = Vns_icon_type_alist;
740        image == nil && CONSP (chain);
741        chain = XCDR (chain))
742     {
743       elt = XCAR (chain);
744       /* special case: 't' means go by file type */
745       if (SYMBOLP (elt) && EQ (elt, Qt) && SSDATA (f->name)[0] == '/')
746         {
747           NSString *str
748              = [NSString stringWithUTF8String: SSDATA (f->name)];
749           if ([[NSFileManager defaultManager] fileExistsAtPath: str])
750             image = [[[NSWorkspace sharedWorkspace] iconForFile: str] retain];
751         }
752       else if (CONSP (elt) &&
753                STRINGP (XCAR (elt)) &&
754                STRINGP (XCDR (elt)) &&
755                fast_string_match (XCAR (elt), f->name) >= 0)
756         {
757           image = [EmacsImage allocInitFromFile: XCDR (elt)];
758           if (image == nil)
759             image = [[NSImage imageNamed:
760                                [NSString stringWithUTF8String:
761                                             SSDATA (XCDR (elt))]] retain];
762         }
763     }
765   if (image == nil)
766     {
767       image = [[[NSWorkspace sharedWorkspace] iconForFileType: @"text"] retain];
768       setMini = NO;
769     }
771   [f->output_data.ns->miniimage release];
772   f->output_data.ns->miniimage = image;
773   [view setMiniwindowImage: setMini];
774   [pool release];
775   unblock_input ();
779 static void
780 x_set_icon_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
782   EmacsView *view = FRAME_NS_VIEW (f);
783   id image = nil;
784   BOOL setMini = YES;
786   NSTRACE (x_set_icon_type);
788   if (!NILP (arg) && SYMBOLP (arg))
789     {
790       arg =build_string (SSDATA (SYMBOL_NAME (arg)));
791       store_frame_param (f, Qicon_type, arg);
792     }
794   /* do it the implicit way */
795   if (NILP (arg))
796     {
797       ns_implicitly_set_icon_type (f);
798       return;
799     }
801   CHECK_STRING (arg);
803   image = [EmacsImage allocInitFromFile: arg];
804   if (image == nil)
805     image =[NSImage imageNamed: [NSString stringWithUTF8String:
806                                             SSDATA (arg)]];
808   if (image == nil)
809     {
810       image = [NSImage imageNamed: @"text"];
811       setMini = NO;
812     }
814   f->output_data.ns->miniimage = image;
815   [view setMiniwindowImage: setMini];
819 /* TODO: move to nsterm? */
821 ns_lisp_to_cursor_type (Lisp_Object arg)
823   char *str;
824   if (XTYPE (arg) == Lisp_String)
825     str = SSDATA (arg);
826   else if (XTYPE (arg) == Lisp_Symbol)
827     str = SSDATA (SYMBOL_NAME (arg));
828   else return -1;
829   if (!strcmp (str, "box"))     return FILLED_BOX_CURSOR;
830   if (!strcmp (str, "hollow"))  return HOLLOW_BOX_CURSOR;
831   if (!strcmp (str, "hbar"))    return HBAR_CURSOR;
832   if (!strcmp (str, "bar"))     return BAR_CURSOR;
833   if (!strcmp (str, "no"))      return NO_CURSOR;
834   return -1;
838 Lisp_Object
839 ns_cursor_type_to_lisp (int arg)
841   switch (arg)
842     {
843     case FILLED_BOX_CURSOR: return Qbox;
844     case HOLLOW_BOX_CURSOR: return intern ("hollow");
845     case HBAR_CURSOR:       return intern ("hbar");
846     case BAR_CURSOR:        return intern ("bar");
847     case NO_CURSOR:
848     default:                return intern ("no");
849     }
852 /* This is the same as the xfns.c definition.  */
853 static void
854 x_set_cursor_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
856   set_frame_cursor_types (f, arg);
859 /* called to set mouse pointer color, but all other terms use it to
860    initialize pointer types (and don't set the color ;) */
861 static void
862 x_set_mouse_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
864   /* don't think we can do this on Nextstep */
868 #define Str(x) #x
869 #define Xstr(x) Str(x)
871 static Lisp_Object
872 ns_appkit_version_str (void)
874   char tmp[256];
876 #ifdef NS_IMPL_GNUSTEP
877   sprintf(tmp, "gnustep-gui-%s", Xstr(GNUSTEP_GUI_VERSION));
878 #elif defined (NS_IMPL_COCOA)
879   NSString *osversion
880     = [[NSProcessInfo processInfo] operatingSystemVersionString];
881   sprintf(tmp, "appkit-%.2f %s",
882           NSAppKitVersionNumber,
883           [osversion UTF8String]);
884 #else
885   tmp = "ns-unknown";
886 #endif
887   return build_string (tmp);
891 /* This is for use by x-server-version and collapses all version info we
892    have into a single int.  For a better picture of the implementation
893    running, use ns_appkit_version_str.*/
894 static int
895 ns_appkit_version_int (void)
897 #ifdef NS_IMPL_GNUSTEP
898   return GNUSTEP_GUI_MAJOR_VERSION * 100 + GNUSTEP_GUI_MINOR_VERSION;
899 #elif defined (NS_IMPL_COCOA)
900   return (int)NSAppKitVersionNumber;
901 #endif
902   return 0;
906 static void
907 x_icon (struct frame *f, Lisp_Object parms)
908 /* --------------------------------------------------------------------------
909    Strangely-named function to set icon position parameters in frame.
910    This is irrelevant under OS X, but might be needed under GNUstep,
911    depending on the window manager used.  Note, this is not a standard
912    frame parameter-setter; it is called directly from x-create-frame.
913    -------------------------------------------------------------------------- */
915   Lisp_Object icon_x, icon_y;
916   struct ns_display_info *dpyinfo = check_ns_display_info (Qnil);
918   f->output_data.ns->icon_top = Qnil;
919   f->output_data.ns->icon_left = Qnil;
921   /* Set the position of the icon.  */
922   icon_x = x_get_arg (dpyinfo, parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
923   icon_y = x_get_arg (dpyinfo, parms, Qicon_top, 0, 0,  RES_TYPE_NUMBER);
924   if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
925     {
926       CHECK_NUMBER (icon_x);
927       CHECK_NUMBER (icon_y);
928       f->output_data.ns->icon_top = icon_y;
929       f->output_data.ns->icon_left = icon_x;
930     }
931   else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
932     error ("Both left and top icon corners of icon must be specified");
936 /* Note: see frame.c for template, also where generic functions are impl */
937 frame_parm_handler ns_frame_parm_handlers[] =
939   x_set_autoraise, /* generic OK */
940   x_set_autolower, /* generic OK */
941   x_set_background_color,
942   0, /* x_set_border_color,  may be impossible under Nextstep */
943   0, /* x_set_border_width,  may be impossible under Nextstep */
944   x_set_cursor_color,
945   x_set_cursor_type,
946   x_set_font, /* generic OK */
947   x_set_foreground_color,
948   x_set_icon_name,
949   x_set_icon_type,
950   x_set_internal_border_width, /* generic OK */
951   0, /* x_set_right_divider_width */
952   0, /* x_set_bottom_divider_width */
953   x_set_menu_bar_lines,
954   x_set_mouse_color,
955   x_explicitly_set_name,
956   x_set_scroll_bar_width, /* generic OK */
957   x_set_title,
958   x_set_unsplittable, /* generic OK */
959   x_set_vertical_scroll_bars, /* generic OK */
960   x_set_visibility, /* generic OK */
961   x_set_tool_bar_lines,
962   0, /* x_set_scroll_bar_foreground, will ignore (not possible on NS) */
963   0, /* x_set_scroll_bar_background,  will ignore (not possible on NS) */
964   x_set_screen_gamma, /* generic OK */
965   x_set_line_spacing, /* generic OK, sets f->extra_line_spacing to int */
966   x_set_fringe_width, /* generic OK */
967   x_set_fringe_width, /* generic OK */
968   0, /* x_set_wait_for_wm, will ignore */
969   x_set_fullscreen, /* generic OK */
970   x_set_font_backend, /* generic OK */
971   x_set_alpha,
972   0, /* x_set_sticky */
973   0, /* x_set_tool_bar_position */
977 /* Handler for signals raised during x_create_frame.
978    FRAME is the frame which is partially constructed.  */
980 static void
981 unwind_create_frame (Lisp_Object frame)
983   struct frame *f = XFRAME (frame);
985   /* If frame is already dead, nothing to do.  This can happen if the
986      display is disconnected after the frame has become official, but
987      before x_create_frame removes the unwind protect.  */
988   if (!FRAME_LIVE_P (f))
989     return;
991   /* If frame is ``official'', nothing to do.  */
992   if (NILP (Fmemq (frame, Vframe_list)))
993     {
994 #if defined GLYPH_DEBUG && defined ENABLE_CHECKING
995       struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
996 #endif
998       x_free_frame_resources (f);
999       free_glyphs (f);
1001 #ifdef GLYPH_DEBUG
1002       /* Check that reference counts are indeed correct.  */
1003       eassert (dpyinfo->terminal->image_cache->refcount == image_cache_refcount);
1004 #endif
1005     }
1009  * Read geometry related parameters from preferences if not in PARMS.
1010  * Returns the union of parms and any preferences read.
1011  */
1013 static Lisp_Object
1014 get_geometry_from_preferences (struct ns_display_info *dpyinfo,
1015                                Lisp_Object parms)
1017   struct {
1018     const char *val;
1019     const char *cls;
1020     Lisp_Object tem;
1021   } r[] = {
1022     { "width",  "Width", Qwidth },
1023     { "height", "Height", Qheight },
1024     { "left", "Left", Qleft },
1025     { "top", "Top", Qtop },
1026   };
1028   int i;
1029   for (i = 0; i < ARRAYELTS (r); ++i)
1030     {
1031       if (NILP (Fassq (r[i].tem, parms)))
1032         {
1033           Lisp_Object value
1034             = x_get_arg (dpyinfo, parms, r[i].tem, r[i].val, r[i].cls,
1035                          RES_TYPE_NUMBER);
1036           if (! EQ (value, Qunbound))
1037             parms = Fcons (Fcons (r[i].tem, value), parms);
1038         }
1039     }
1041   return parms;
1044 /* ==========================================================================
1046     Lisp definitions
1048    ========================================================================== */
1050 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
1051        1, 1, 0,
1052        doc: /* Make a new Nextstep window, called a "frame" in Emacs terms.
1053 Return an Emacs frame object.
1054 PARMS is an alist of frame parameters.
1055 If the parameters specify that the frame should not have a minibuffer,
1056 and do not specify a specific minibuffer window to use,
1057 then `default-minibuffer-frame' must be a frame whose minibuffer can
1058 be shared by the new frame.
1060 This function is an internal primitive--use `make-frame' instead.  */)
1061      (Lisp_Object parms)
1063   struct frame *f;
1064   Lisp_Object frame, tem;
1065   Lisp_Object name;
1066   int minibuffer_only = 0;
1067   long window_prompting = 0;
1068   int width, height;
1069   ptrdiff_t count = specpdl_ptr - specpdl;
1070   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1071   Lisp_Object display;
1072   struct ns_display_info *dpyinfo = NULL;
1073   Lisp_Object parent;
1074   struct kboard *kb;
1075   static int desc_ctr = 1;
1077   /* x_get_arg modifies parms.  */
1078   parms = Fcopy_alist (parms);
1080   /* Use this general default value to start with
1081      until we know if this frame has a specified name.  */
1082   Vx_resource_name = Vinvocation_name;
1084   display = x_get_arg (dpyinfo, parms, Qterminal, 0, 0, RES_TYPE_STRING);
1085   if (EQ (display, Qunbound))
1086     display = Qnil;
1087   dpyinfo = check_ns_display_info (display);
1088   kb = dpyinfo->terminal->kboard;
1090   if (!dpyinfo->terminal->name)
1091     error ("Terminal is not live, can't create new frames on it");
1093   name = x_get_arg (dpyinfo, parms, Qname, 0, 0, RES_TYPE_STRING);
1094   if (!STRINGP (name)
1095       && ! EQ (name, Qunbound)
1096       && ! NILP (name))
1097     error ("Invalid frame name--not a string or nil");
1099   if (STRINGP (name))
1100     Vx_resource_name = name;
1102   parent = x_get_arg (dpyinfo, parms, Qparent_id, 0, 0, RES_TYPE_NUMBER);
1103   if (EQ (parent, Qunbound))
1104     parent = Qnil;
1105   if (! NILP (parent))
1106     CHECK_NUMBER (parent);
1108   /* make_frame_without_minibuffer can run Lisp code and garbage collect.  */
1109   /* No need to protect DISPLAY because that's not used after passing
1110      it to make_frame_without_minibuffer.  */
1111   frame = Qnil;
1112   GCPRO4 (parms, parent, name, frame);
1113   tem = x_get_arg (dpyinfo, parms, Qminibuffer, "minibuffer", "Minibuffer",
1114                   RES_TYPE_SYMBOL);
1115   if (EQ (tem, Qnone) || NILP (tem))
1116       f = make_frame_without_minibuffer (Qnil, kb, display);
1117   else if (EQ (tem, Qonly))
1118     {
1119       f = make_minibuffer_frame ();
1120       minibuffer_only = 1;
1121     }
1122   else if (WINDOWP (tem))
1123       f = make_frame_without_minibuffer (tem, kb, display);
1124   else
1125       f = make_frame (1);
1127   XSETFRAME (frame, f);
1129   f->terminal = dpyinfo->terminal;
1131   f->output_method = output_ns;
1132   f->output_data.ns = xzalloc (sizeof *f->output_data.ns);
1134   FRAME_FONTSET (f) = -1;
1136   fset_icon_name (f, x_get_arg (dpyinfo, parms, Qicon_name,
1137                                 "iconName", "Title",
1138                                 RES_TYPE_STRING));
1139   if (! STRINGP (f->icon_name))
1140     fset_icon_name (f, Qnil);
1142   FRAME_DISPLAY_INFO (f) = dpyinfo;
1144   /* With FRAME_DISPLAY_INFO set up, this unwind-protect is safe.  */
1145   record_unwind_protect (unwind_create_frame, frame);
1147   f->output_data.ns->window_desc = desc_ctr++;
1148   if (TYPE_RANGED_INTEGERP (Window, parent))
1149     {
1150       f->output_data.ns->parent_desc = XFASTINT (parent);
1151       f->output_data.ns->explicit_parent = 1;
1152     }
1153   else
1154     {
1155       f->output_data.ns->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
1156       f->output_data.ns->explicit_parent = 0;
1157     }
1159   /* Set the name; the functions to which we pass f expect the name to
1160      be set.  */
1161   if (EQ (name, Qunbound) || NILP (name) || ! STRINGP (name))
1162     {
1163       fset_name (f, build_string ([ns_app_name UTF8String]));
1164       f->explicit_name = 0;
1165     }
1166   else
1167     {
1168       fset_name (f, name);
1169       f->explicit_name = 1;
1170       specbind (Qx_resource_name, name);
1171     }
1173   block_input ();
1175 #ifdef NS_IMPL_COCOA
1176 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
1177   if (CTGetCoreTextVersion != NULL
1178       && CTGetCoreTextVersion () >= kCTVersionNumber10_5)
1179     mac_register_font_driver (f);
1180 #endif
1181 #endif
1182   register_font_driver (&nsfont_driver, f);
1184   x_default_parameter (f, parms, Qfont_backend, Qnil,
1185                         "fontBackend", "FontBackend", RES_TYPE_STRING);
1187   {
1188     /* use for default font name */
1189     id font = [NSFont userFixedPitchFontOfSize: -1.0]; /* default */
1190     x_default_parameter (f, parms, Qfontsize,
1191                                     make_number (0 /*(int)[font pointSize]*/),
1192                                     "fontSize", "FontSize", RES_TYPE_NUMBER);
1193     // Remove ' Regular', not handled by backends.
1194     char *fontname = xstrdup ([[font displayName] UTF8String]);
1195     int len = strlen (fontname);
1196     if (len > 8 && strcmp (fontname + len - 8, " Regular") == 0)
1197       fontname[len-8] = '\0';
1198     x_default_parameter (f, parms, Qfont,
1199                                  build_string (fontname),
1200                                  "font", "Font", RES_TYPE_STRING);
1201     xfree (fontname);
1202   }
1203   unblock_input ();
1205   x_default_parameter (f, parms, Qborder_width, make_number (0),
1206                        "borderwidth", "BorderWidth", RES_TYPE_NUMBER);
1207   x_default_parameter (f, parms, Qinternal_border_width, make_number (2),
1208                       "internalBorderWidth", "InternalBorderWidth",
1209                       RES_TYPE_NUMBER);
1211   /* default scrollbars on right on Mac */
1212   {
1213       Lisp_Object spos
1214 #ifdef NS_IMPL_GNUSTEP
1215           = Qt;
1216 #else
1217           = Qright;
1218 #endif
1219       x_default_parameter (f, parms, Qvertical_scroll_bars, spos,
1220                            "verticalScrollBars", "VerticalScrollBars",
1221                            RES_TYPE_SYMBOL);
1222   }
1223   x_default_parameter (f, parms, Qforeground_color, build_string ("Black"),
1224                       "foreground", "Foreground", RES_TYPE_STRING);
1225   x_default_parameter (f, parms, Qbackground_color, build_string ("White"),
1226                       "background", "Background", RES_TYPE_STRING);
1227   /* FIXME: not supported yet in Nextstep */
1228   x_default_parameter (f, parms, Qline_spacing, Qnil,
1229                        "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
1230   x_default_parameter (f, parms, Qleft_fringe, Qnil,
1231                        "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
1232   x_default_parameter (f, parms, Qright_fringe, Qnil,
1233                        "rightFringe", "RightFringe", RES_TYPE_NUMBER);
1235 #ifdef GLYPH_DEBUG
1236   image_cache_refcount =
1237     FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
1238 #endif
1240   init_frame_faces (f);
1242   /* Read comment about this code in corresponding place in xfns.c.  */
1243   width = FRAME_TEXT_WIDTH (f);
1244   height = FRAME_TEXT_HEIGHT (f);
1245   FRAME_TEXT_HEIGHT (f) = 0;
1246   SET_FRAME_WIDTH (f, 0);
1247   change_frame_size (f, width, height, 1, 0, 0, 1);
1249   /* The resources controlling the menu-bar and tool-bar are
1250      processed specially at startup, and reflected in the mode
1251      variables; ignore them here.  */
1252   x_default_parameter (f, parms, Qmenu_bar_lines,
1253                        NILP (Vmenu_bar_mode)
1254                        ? make_number (0) : make_number (1),
1255                        NULL, NULL, RES_TYPE_NUMBER);
1256   x_default_parameter (f, parms, Qtool_bar_lines,
1257                        NILP (Vtool_bar_mode)
1258                        ? make_number (0) : make_number (1),
1259                        NULL, NULL, RES_TYPE_NUMBER);
1261   x_default_parameter (f, parms, Qbuffer_predicate, Qnil, "bufferPredicate",
1262                        "BufferPredicate", RES_TYPE_SYMBOL);
1263   x_default_parameter (f, parms, Qtitle, Qnil, "title", "Title",
1264                        RES_TYPE_STRING);
1266   parms = get_geometry_from_preferences (dpyinfo, parms);
1267   window_prompting = x_figure_window_size (f, parms, 1);
1269   tem = x_get_arg (dpyinfo, parms, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
1270   f->no_split = minibuffer_only || (!EQ (tem, Qunbound) && !EQ (tem, Qnil));
1272   /* NOTE: on other terms, this is done in set_mouse_color, however this
1273      was not getting called under Nextstep */
1274   f->output_data.ns->text_cursor = [NSCursor IBeamCursor];
1275   f->output_data.ns->nontext_cursor = [NSCursor arrowCursor];
1276   f->output_data.ns->modeline_cursor = [NSCursor pointingHandCursor];
1277   f->output_data.ns->hand_cursor = [NSCursor pointingHandCursor];
1278   f->output_data.ns->hourglass_cursor = [NSCursor disappearingItemCursor];
1279   f->output_data.ns->horizontal_drag_cursor = [NSCursor resizeLeftRightCursor];
1280   f->output_data.ns->vertical_drag_cursor = [NSCursor resizeUpDownCursor];
1281   FRAME_DISPLAY_INFO (f)->vertical_scroll_bar_cursor
1282      = [NSCursor arrowCursor];
1283   f->output_data.ns->current_pointer = f->output_data.ns->text_cursor;
1285   [[EmacsView alloc] initFrameFromEmacs: f];
1287   x_icon (f, parms);
1289   /* ns_display_info does not have a reference_count.  */
1290   f->terminal->reference_count++;
1292   /* It is now ok to make the frame official even if we get an error below.
1293      The frame needs to be on Vframe_list or making it visible won't work. */
1294   Vframe_list = Fcons (frame, Vframe_list);
1296   x_default_parameter (f, parms, Qicon_type, Qnil,
1297                        "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
1299   x_default_parameter (f, parms, Qauto_raise, Qnil,
1300                        "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
1301   x_default_parameter (f, parms, Qauto_lower, Qnil,
1302                        "autoLower", "AutoLower", RES_TYPE_BOOLEAN);
1303   x_default_parameter (f, parms, Qcursor_type, Qbox,
1304                        "cursorType", "CursorType", RES_TYPE_SYMBOL);
1305   x_default_parameter (f, parms, Qscroll_bar_width, Qnil,
1306                        "scrollBarWidth", "ScrollBarWidth",
1307                        RES_TYPE_NUMBER);
1308   x_default_parameter (f, parms, Qalpha, Qnil,
1309                        "alpha", "Alpha", RES_TYPE_NUMBER);
1310   x_default_parameter (f, parms, Qfullscreen, Qnil,
1311                        "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
1313   width = FRAME_TEXT_WIDTH (f);
1314   height = FRAME_TEXT_HEIGHT (f);
1315   FRAME_TEXT_HEIGHT (f) = 0;
1316   SET_FRAME_WIDTH (f, 0);
1317   change_frame_size (f, width, height, 1, 0, 0, 1);
1319   if (! f->output_data.ns->explicit_parent)
1320     {
1321       Lisp_Object visibility;
1323       visibility = x_get_arg (dpyinfo, parms, Qvisibility, 0, 0,
1324                               RES_TYPE_SYMBOL);
1325       if (EQ (visibility, Qunbound))
1326         visibility = Qt;
1328       if (EQ (visibility, Qicon))
1329         x_iconify_frame (f);
1330       else if (! NILP (visibility))
1331         {
1332           x_make_frame_visible (f);
1333           [[FRAME_NS_VIEW (f) window] makeKeyWindow];
1334         }
1335       else
1336         {
1337           /* Must have been Qnil.  */
1338         }
1339     }
1341   if (FRAME_HAS_MINIBUF_P (f)
1342       && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
1343           || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
1344     kset_default_minibuffer_frame (kb, frame);
1346   /* All remaining specified parameters, which have not been "used"
1347      by x_get_arg and friends, now go in the misc. alist of the frame.  */
1348   for (tem = parms; CONSP (tem); tem = XCDR (tem))
1349     if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
1350       fset_param_alist (f, Fcons (XCAR (tem), f->param_alist));
1352   UNGCPRO;
1354   if (window_prompting & USPosition)
1355     x_set_offset (f, f->left_pos, f->top_pos, 1);
1357   /* Make sure windows on this frame appear in calls to next-window
1358      and similar functions.  */
1359   Vwindow_list = Qnil;
1361   return unbind_to (count, frame);
1364 void
1365 x_focus_frame (struct frame *f)
1367   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1369   if (dpyinfo->x_focus_frame != f)
1370     {
1371       EmacsView *view = FRAME_NS_VIEW (f);
1372       block_input ();
1373       [NSApp activateIgnoringOtherApps: YES];
1374       [[view window] makeKeyAndOrderFront: view];
1375       unblock_input ();
1376     }
1380 DEFUN ("ns-popup-font-panel", Fns_popup_font_panel, Sns_popup_font_panel,
1381        0, 1, "",
1382        doc: /* Pop up the font panel. */)
1383      (Lisp_Object frame)
1385   struct frame *f = decode_window_system_frame (frame);
1386   id fm = [NSFontManager sharedFontManager];
1387   struct font *font = f->output_data.ns->font;
1388   NSFont *nsfont;
1389   if (EQ (font->driver->type, Qns))
1390     nsfont = ((struct nsfont_info *)font)->nsfont;
1391 #ifdef NS_IMPL_COCOA
1392 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
1393   else
1394     nsfont = (NSFont *) macfont_get_nsctfont (font);
1395 #endif
1396 #endif
1397   [fm setSelectedFont: nsfont isMultiple: NO];
1398   [fm orderFrontFontPanel: NSApp];
1399   return Qnil;
1403 DEFUN ("ns-popup-color-panel", Fns_popup_color_panel, Sns_popup_color_panel,
1404        0, 1, "",
1405        doc: /* Pop up the color panel.  */)
1406      (Lisp_Object frame)
1408   check_window_system (NULL);
1409   [NSApp orderFrontColorPanel: NSApp];
1410   return Qnil;
1413 static struct
1415   id panel;
1416   BOOL ret;
1417 #if ! defined (NS_IMPL_COCOA) || \
1418   MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
1419   NSString *dirS, *initS;
1420   BOOL no_types;
1421 #endif
1422 } ns_fd_data;
1424 void
1425 ns_run_file_dialog (void)
1427   if (ns_fd_data.panel == nil) return;
1428 #if defined (NS_IMPL_COCOA) && \
1429   MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
1430   ns_fd_data.ret = [ns_fd_data.panel runModal];
1431 #else
1432   if (ns_fd_data.no_types)
1433     {
1434       ns_fd_data.ret = [ns_fd_data.panel
1435                            runModalForDirectory: ns_fd_data.dirS
1436                            file: ns_fd_data.initS];
1437     }
1438   else
1439     {
1440       ns_fd_data.ret = [ns_fd_data.panel
1441                            runModalForDirectory: ns_fd_data.dirS
1442                            file: ns_fd_data.initS
1443                            types: nil];
1444     }
1445 #endif
1446   ns_fd_data.panel = nil;
1449 DEFUN ("ns-read-file-name", Fns_read_file_name, Sns_read_file_name, 1, 5, 0,
1450        doc: /* Use a graphical panel to read a file name, using prompt PROMPT.
1451 Optional arg DIR, if non-nil, supplies a default directory.
1452 Optional arg MUSTMATCH, if non-nil, means the returned file or
1453 directory must exist.
1454 Optional arg INIT, if non-nil, provides a default file name to use.
1455 Optional arg DIR_ONLY_P, if non-nil, means choose only directories.  */)
1456   (Lisp_Object prompt, Lisp_Object dir, Lisp_Object mustmatch,
1457    Lisp_Object init, Lisp_Object dir_only_p)
1459   static id fileDelegate = nil;
1460   BOOL ret;
1461   BOOL isSave = NILP (mustmatch) && NILP (dir_only_p);
1462   id panel;
1463   Lisp_Object fname;
1465   NSString *promptS = NILP (prompt) || !STRINGP (prompt) ? nil :
1466     [NSString stringWithUTF8String: SSDATA (prompt)];
1467   NSString *dirS = NILP (dir) || !STRINGP (dir) ?
1468     [NSString stringWithUTF8String: SSDATA (BVAR (current_buffer, directory))] :
1469     [NSString stringWithUTF8String: SSDATA (dir)];
1470   NSString *initS = NILP (init) || !STRINGP (init) ? nil :
1471     [NSString stringWithUTF8String: SSDATA (init)];
1472   NSEvent *nxev;
1474   check_window_system (NULL);
1476   if (fileDelegate == nil)
1477     fileDelegate = [EmacsFileDelegate new];
1479   [NSCursor setHiddenUntilMouseMoves: NO];
1481   if ([dirS characterAtIndex: 0] == '~')
1482     dirS = [dirS stringByExpandingTildeInPath];
1484   panel = isSave ?
1485     (id)[EmacsSavePanel savePanel] : (id)[EmacsOpenPanel openPanel];
1487   [panel setTitle: promptS];
1489   [panel setAllowsOtherFileTypes: YES];
1490   [panel setTreatsFilePackagesAsDirectories: YES];
1491   [panel setDelegate: fileDelegate];
1493   if (! NILP (dir_only_p))
1494     {
1495       [panel setCanChooseDirectories: YES];
1496       [panel setCanChooseFiles: NO];
1497     }
1498   else if (! isSave)
1499     {
1500       /* This is not quite what the documentation says, but it is compatible
1501          with the Gtk+ code.  Also, the menu entry says "Open File...".  */
1502       [panel setCanChooseDirectories: NO];
1503       [panel setCanChooseFiles: YES];
1504     }
1506   block_input ();
1507   ns_fd_data.panel = panel;
1508   ns_fd_data.ret = NO;
1509 #if defined (NS_IMPL_COCOA) && \
1510   MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
1511   if (! NILP (mustmatch) || ! NILP (dir_only_p))
1512     [panel setAllowedFileTypes: nil];
1513   if (dirS) [panel setDirectoryURL: [NSURL fileURLWithPath: dirS]];
1514   if (initS && NILP (Ffile_directory_p (init)))
1515     [panel setNameFieldStringValue: [initS lastPathComponent]];
1516   else
1517     [panel setNameFieldStringValue: @""];
1519 #else
1520   ns_fd_data.no_types = NILP (mustmatch) && NILP (dir_only_p);
1521   ns_fd_data.dirS = dirS;
1522   ns_fd_data.initS = initS;
1523 #endif
1525   /* runModalForDirectory/runModal restarts the main event loop when done,
1526      so we must start an event loop and then pop up the file dialog.
1527      The file dialog may pop up a confirm dialog after Ok has been pressed,
1528      so we can not simply pop down on the Ok/Cancel press.
1529    */
1530   nxev = [NSEvent otherEventWithType: NSApplicationDefined
1531                             location: NSMakePoint (0, 0)
1532                        modifierFlags: 0
1533                            timestamp: 0
1534                         windowNumber: [[NSApp mainWindow] windowNumber]
1535                              context: [NSApp context]
1536                              subtype: 0
1537                                data1: 0
1538                                data2: NSAPP_DATA2_RUNFILEDIALOG];
1540   [NSApp postEvent: nxev atStart: NO];
1541   while (ns_fd_data.panel != nil)
1542     [NSApp run];
1544   ret = (ns_fd_data.ret == NSOKButton);
1546   if (ret)
1547     {
1548       NSString *str = ns_filename_from_panel (panel);
1549       if (! str) str = ns_directory_from_panel (panel);
1550       if (! str) ret = NO;
1551       else fname = build_string ([str UTF8String]);
1552     }
1554   [[FRAME_NS_VIEW (SELECTED_FRAME ()) window] makeKeyWindow];
1555   unblock_input ();
1557   return ret ? fname : Qnil;
1560 const char *
1561 ns_get_defaults_value (const char *key)
1563   NSObject *obj = [[NSUserDefaults standardUserDefaults]
1564                     objectForKey: [NSString stringWithUTF8String: key]];
1566   if (!obj) return NULL;
1568   return [[NSString stringWithFormat: @"%@", obj] UTF8String];
1572 DEFUN ("ns-get-resource", Fns_get_resource, Sns_get_resource, 2, 2, 0,
1573        doc: /* Return the value of the property NAME of OWNER from the defaults database.
1574 If OWNER is nil, Emacs is assumed.  */)
1575      (Lisp_Object owner, Lisp_Object name)
1577   const char *value;
1579   check_window_system (NULL);
1580   if (NILP (owner))
1581     owner = build_string([ns_app_name UTF8String]);
1582   CHECK_STRING (name);
1584   value = ns_get_defaults_value (SSDATA (name));
1586   if (value)
1587     return build_string (value);
1588   return Qnil;
1592 DEFUN ("ns-set-resource", Fns_set_resource, Sns_set_resource, 3, 3, 0,
1593        doc: /* Set property NAME of OWNER to VALUE, from the defaults database.
1594 If OWNER is nil, Emacs is assumed.
1595 If VALUE is nil, the default is removed.  */)
1596      (Lisp_Object owner, Lisp_Object name, Lisp_Object value)
1598   check_window_system (NULL);
1599   if (NILP (owner))
1600     owner = build_string ([ns_app_name UTF8String]);
1601   CHECK_STRING (name);
1602   if (NILP (value))
1603     {
1604       [[NSUserDefaults standardUserDefaults] removeObjectForKey:
1605                          [NSString stringWithUTF8String: SSDATA (name)]];
1606     }
1607   else
1608     {
1609       CHECK_STRING (value);
1610       [[NSUserDefaults standardUserDefaults] setObject:
1611                 [NSString stringWithUTF8String: SSDATA (value)]
1612                                         forKey: [NSString stringWithUTF8String:
1613                                                          SSDATA (name)]];
1614     }
1616   return Qnil;
1620 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
1621        Sx_server_max_request_size,
1622        0, 1, 0,
1623        doc: /* This function is a no-op.  It is only present for completeness.  */)
1624      (Lisp_Object terminal)
1626   check_ns_display_info (terminal);
1627   /* This function has no real equivalent under NeXTstep.  Return nil to
1628      indicate this. */
1629   return Qnil;
1633 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
1634        doc: /* Return the "vendor ID" string of Nextstep display server TERMINAL.
1635 \(Labeling every distributor as a "vendor" embodies the false assumption
1636 that operating systems cannot be developed and distributed noncommercially.)
1637 The optional argument TERMINAL specifies which display to ask about.
1638 TERMINAL should be a terminal object, a frame or a display name (a string).
1639 If omitted or nil, that stands for the selected frame's display.  */)
1640   (Lisp_Object terminal)
1642   check_ns_display_info (terminal);
1643 #ifdef NS_IMPL_GNUSTEP
1644   return build_string ("GNU");
1645 #else
1646   return build_string ("Apple");
1647 #endif
1651 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
1652        doc: /* Return the version numbers of the server of display TERMINAL.
1653 The value is a list of three integers: the major and minor
1654 version numbers of the X Protocol in use, and the distributor-specific release
1655 number.  See also the function `x-server-vendor'.
1657 The optional argument TERMINAL specifies which display to ask about.
1658 TERMINAL should be a terminal object, a frame or a display name (a string).
1659 If omitted or nil, that stands for the selected frame's display.  */)
1660   (Lisp_Object terminal)
1662   check_ns_display_info (terminal);
1663   /*NOTE: it is unclear what would best correspond with "protocol";
1664           we return 10.3, meaning Panther, since this is roughly the
1665           level that GNUstep's APIs correspond to.
1666           The last number is where we distinguish between the Apple
1667           and GNUstep implementations ("distributor-specific release
1668           number") and give int'ized versions of major.minor. */
1669   return list3i (10, 3, ns_appkit_version_int ());
1673 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
1674        doc: /* Return the number of screens on Nextstep display server TERMINAL.
1675 The optional argument TERMINAL specifies which display to ask about.
1676 TERMINAL should be a terminal object, a frame or a display name (a string).
1677 If omitted or nil, that stands for the selected frame's display.
1679 Note: "screen" here is not in Nextstep terminology but in X11's.  For
1680 the number of physical monitors, use `(length
1681 (display-monitor-attributes-list TERMINAL))' instead.  */)
1682   (Lisp_Object terminal)
1684   check_ns_display_info (terminal);
1685   return make_number (1);
1689 DEFUN ("x-display-mm-height", Fx_display_mm_height, Sx_display_mm_height, 0, 1, 0,
1690        doc: /* Return the height in millimeters of the Nextstep display TERMINAL.
1691 The optional argument TERMINAL specifies which display to ask about.
1692 TERMINAL should be a terminal object, a frame or a display name (a string).
1693 If omitted or nil, that stands for the selected frame's display.
1695 On \"multi-monitor\" setups this refers to the height in millimeters for
1696 all physical monitors associated with TERMINAL.  To get information
1697 for each physical monitor, use `display-monitor-attributes-list'.  */)
1698   (Lisp_Object terminal)
1700   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
1702   return make_number (x_display_pixel_height (dpyinfo) / (92.0/25.4));
1706 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
1707        doc: /* Return the width in millimeters of the Nextstep display TERMINAL.
1708 The optional argument TERMINAL specifies which display to ask about.
1709 TERMINAL should be a terminal object, a frame or a display name (a string).
1710 If omitted or nil, that stands for the selected frame's display.
1712 On \"multi-monitor\" setups this refers to the width in millimeters for
1713 all physical monitors associated with TERMINAL.  To get information
1714 for each physical monitor, use `display-monitor-attributes-list'.  */)
1715   (Lisp_Object terminal)
1717   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
1719   return make_number (x_display_pixel_width (dpyinfo) / (92.0/25.4));
1723 DEFUN ("x-display-backing-store", Fx_display_backing_store,
1724        Sx_display_backing_store, 0, 1, 0,
1725        doc: /* Return an indication of whether the Nextstep display TERMINAL does backing store.
1726 The value may be `buffered', `retained', or `non-retained'.
1727 The optional argument TERMINAL specifies which display to ask about.
1728 TERMINAL should be a terminal object, a frame or a display name (a string).
1729 If omitted or nil, that stands for the selected frame's display.  */)
1730   (Lisp_Object terminal)
1732   check_ns_display_info (terminal);
1733   switch ([ns_get_window (terminal) backingType])
1734     {
1735     case NSBackingStoreBuffered:
1736       return intern ("buffered");
1737     case NSBackingStoreRetained:
1738       return intern ("retained");
1739     case NSBackingStoreNonretained:
1740       return intern ("non-retained");
1741     default:
1742       error ("Strange value for backingType parameter of frame");
1743     }
1744   return Qnil;  /* not reached, shut compiler up */
1748 DEFUN ("x-display-visual-class", Fx_display_visual_class,
1749        Sx_display_visual_class, 0, 1, 0,
1750        doc: /* Return the visual class of the Nextstep display TERMINAL.
1751 The value is one of the symbols `static-gray', `gray-scale',
1752 `static-color', `pseudo-color', `true-color', or `direct-color'.
1754 The optional argument TERMINAL specifies which display to ask about.
1755 TERMINAL should a terminal object, a frame or a display name (a string).
1756 If omitted or nil, that stands for the selected frame's display.  */)
1757   (Lisp_Object terminal)
1759   NSWindowDepth depth;
1761   check_ns_display_info (terminal);
1762   depth = [[[NSScreen screens] objectAtIndex:0] depth];
1764   if ( depth == NSBestDepth (NSCalibratedWhiteColorSpace, 2, 2, YES, NULL))
1765     return intern ("static-gray");
1766   else if (depth == NSBestDepth (NSCalibratedWhiteColorSpace, 8, 8, YES, NULL))
1767     return intern ("gray-scale");
1768   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 8, 8, YES, NULL))
1769     return intern ("pseudo-color");
1770   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 4, 12, NO, NULL))
1771     return intern ("true-color");
1772   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 8, 24, NO, NULL))
1773     return intern ("direct-color");
1774   else
1775     /* color mgmt as far as we do it is really handled by Nextstep itself anyway */
1776     return intern ("direct-color");
1780 DEFUN ("x-display-save-under", Fx_display_save_under,
1781        Sx_display_save_under, 0, 1, 0,
1782        doc: /* Return t if TERMINAL supports the save-under feature.
1783 The optional argument TERMINAL specifies which display to ask about.
1784 TERMINAL should be a terminal object, a frame or a display name (a string).
1785 If omitted or nil, that stands for the selected frame's display.  */)
1786   (Lisp_Object terminal)
1788   check_ns_display_info (terminal);
1789   switch ([ns_get_window (terminal) backingType])
1790     {
1791     case NSBackingStoreBuffered:
1792       return Qt;
1794     case NSBackingStoreRetained:
1795     case NSBackingStoreNonretained:
1796       return Qnil;
1798     default:
1799       error ("Strange value for backingType parameter of frame");
1800     }
1801   return Qnil;  /* not reached, shut compiler up */
1805 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
1806        1, 3, 0,
1807        doc: /* Open a connection to a display server.
1808 DISPLAY is the name of the display to connect to.
1809 Optional second arg XRM-STRING is a string of resources in xrdb format.
1810 If the optional third arg MUST-SUCCEED is non-nil,
1811 terminate Emacs if we can't open the connection.
1812 \(In the Nextstep version, the last two arguments are currently ignored.)  */)
1813      (Lisp_Object display, Lisp_Object resource_string, Lisp_Object must_succeed)
1815   struct ns_display_info *dpyinfo;
1817   CHECK_STRING (display);
1819   nxatoms_of_nsselect ();
1820   dpyinfo = ns_term_init (display);
1821   if (dpyinfo == 0)
1822     {
1823       if (!NILP (must_succeed))
1824         fatal ("Display on %s not responding.\n",
1825                SSDATA (display));
1826       else
1827         error ("Display on %s not responding.\n",
1828                SSDATA (display));
1829     }
1831   return Qnil;
1835 DEFUN ("x-close-connection", Fx_close_connection, Sx_close_connection,
1836        1, 1, 0,
1837        doc: /* Close the connection to TERMINAL's Nextstep display server.
1838 For TERMINAL, specify a terminal object, a frame or a display name (a
1839 string).  If TERMINAL is nil, that stands for the selected frame's
1840 terminal.  */)
1841      (Lisp_Object terminal)
1843   check_ns_display_info (terminal);
1844   [NSApp terminate: NSApp];
1845   return Qnil;
1849 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
1850        doc: /* Return the list of display names that Emacs has connections to.  */)
1851      (void)
1853   Lisp_Object result = Qnil;
1854   struct ns_display_info *ndi;
1856   for (ndi = x_display_list; ndi; ndi = ndi->next)
1857     result = Fcons (XCAR (ndi->name_list_element), result);
1859   return result;
1863 DEFUN ("ns-hide-others", Fns_hide_others, Sns_hide_others,
1864        0, 0, 0,
1865        doc: /* Hides all applications other than Emacs.  */)
1866      (void)
1868   check_window_system (NULL);
1869   [NSApp hideOtherApplications: NSApp];
1870   return Qnil;
1873 DEFUN ("ns-hide-emacs", Fns_hide_emacs, Sns_hide_emacs,
1874        1, 1, 0,
1875        doc: /* If ON is non-nil, the entire Emacs application is hidden.
1876 Otherwise if Emacs is hidden, it is unhidden.
1877 If ON is equal to `activate', Emacs is unhidden and becomes
1878 the active application.  */)
1879      (Lisp_Object on)
1881   check_window_system (NULL);
1882   if (EQ (on, intern ("activate")))
1883     {
1884       [NSApp unhide: NSApp];
1885       [NSApp activateIgnoringOtherApps: YES];
1886     }
1887   else if (NILP (on))
1888     [NSApp unhide: NSApp];
1889   else
1890     [NSApp hide: NSApp];
1891   return Qnil;
1895 DEFUN ("ns-emacs-info-panel", Fns_emacs_info_panel, Sns_emacs_info_panel,
1896        0, 0, 0,
1897        doc: /* Shows the 'Info' or 'About' panel for Emacs.  */)
1898      (void)
1900   check_window_system (NULL);
1901   [NSApp orderFrontStandardAboutPanel: nil];
1902   return Qnil;
1906 DEFUN ("ns-font-name", Fns_font_name, Sns_font_name, 1, 1, 0,
1907        doc: /* Determine font PostScript or family name for font NAME.
1908 NAME should be a string containing either the font name or an XLFD
1909 font descriptor.  If string contains `fontset' and not
1910 `fontset-startup', it is left alone. */)
1911      (Lisp_Object name)
1913   char *nm;
1914   CHECK_STRING (name);
1915   nm = SSDATA (name);
1917   if (nm[0] != '-')
1918     return name;
1919   if (strstr (nm, "fontset") && !strstr (nm, "fontset-startup"))
1920     return name;
1922   return build_string (ns_xlfd_to_fontname (SSDATA (name)));
1926 DEFUN ("ns-list-colors", Fns_list_colors, Sns_list_colors, 0, 1, 0,
1927        doc: /* Return a list of all available colors.
1928 The optional argument FRAME is currently ignored.  */)
1929      (Lisp_Object frame)
1931   Lisp_Object list = Qnil;
1932   NSEnumerator *colorlists;
1933   NSColorList *clist;
1935   if (!NILP (frame))
1936     {
1937       CHECK_FRAME (frame);
1938       if (! FRAME_NS_P (XFRAME (frame)))
1939         error ("non-Nextstep frame used in `ns-list-colors'");
1940     }
1942   block_input ();
1944   colorlists = [[NSColorList availableColorLists] objectEnumerator];
1945   while ((clist = [colorlists nextObject]))
1946     {
1947       if ([[clist name] length] < 7 ||
1948           [[clist name] rangeOfString: @"PANTONE"].location == 0)
1949         {
1950           NSEnumerator *cnames = [[clist allKeys] reverseObjectEnumerator];
1951           NSString *cname;
1952           while ((cname = [cnames nextObject]))
1953             list = Fcons (build_string ([cname UTF8String]), list);
1954 /*           for (i = [[clist allKeys] count] - 1; i >= 0; i--)
1955                list = Fcons (build_string ([[[clist allKeys] objectAtIndex: i]
1956                                              UTF8String]), list); */
1957         }
1958     }
1960   unblock_input ();
1962   return list;
1966 DEFUN ("ns-list-services", Fns_list_services, Sns_list_services, 0, 0, 0,
1967        doc: /* List available Nextstep services by querying NSApp.  */)
1968      (void)
1970 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
1971   /* You can't get services like this in 10.6+.  */
1972   return Qnil;
1973 #else
1974   Lisp_Object ret = Qnil;
1975   NSMenu *svcs;
1976 #ifdef NS_IMPL_COCOA
1977   id delegate;
1978 #endif
1980   check_window_system (NULL);
1981   svcs = [[NSMenu alloc] initWithTitle: @"Services"];
1982   [NSApp setServicesMenu: svcs];
1983   [NSApp registerServicesMenuSendTypes: ns_send_types
1984                            returnTypes: ns_return_types];
1986 /* On Tiger, services menu updating was made lazier (waits for user to
1987    actually click on the menu), so we have to force things along: */
1988 #ifdef NS_IMPL_COCOA
1989   delegate = [svcs delegate];
1990   if (delegate != nil)
1991     {
1992       if ([delegate respondsToSelector: @selector (menuNeedsUpdate:)])
1993         [delegate menuNeedsUpdate: svcs];
1994       if ([delegate respondsToSelector:
1995                        @selector (menu:updateItem:atIndex:shouldCancel:)])
1996         {
1997           int i, len = [delegate numberOfItemsInMenu: svcs];
1998           for (i =0; i<len; i++)
1999             [svcs addItemWithTitle: @"" action: NULL keyEquivalent: @""];
2000           for (i =0; i<len; i++)
2001             if (![delegate menu: svcs
2002                      updateItem: (NSMenuItem *)[svcs itemAtIndex: i]
2003                         atIndex: i shouldCancel: NO])
2004               break;
2005         }
2006     }
2007 #endif
2009   [svcs setAutoenablesItems: NO];
2010 #ifdef NS_IMPL_COCOA
2011   [svcs update]; /* on OS X, converts from '/' structure */
2012 #endif
2014   ret = interpret_services_menu (svcs, Qnil, ret);
2015   return ret;
2016 #endif
2020 DEFUN ("ns-perform-service", Fns_perform_service, Sns_perform_service,
2021        2, 2, 0,
2022        doc: /* Perform Nextstep SERVICE on SEND.
2023 SEND should be either a string or nil.
2024 The return value is the result of the service, as string, or nil if
2025 there was no result.  */)
2026      (Lisp_Object service, Lisp_Object send)
2028   id pb;
2029   NSString *svcName;
2030   char *utfStr;
2032   CHECK_STRING (service);
2033   check_window_system (NULL);
2035   utfStr = SSDATA (service);
2036   svcName = [NSString stringWithUTF8String: utfStr];
2038   pb =[NSPasteboard pasteboardWithUniqueName];
2039   ns_string_to_pasteboard (pb, send);
2041   if (NSPerformService (svcName, pb) == NO)
2042     Fsignal (Qquit, list1 (build_string ("service not available")));
2044   if ([[pb types] count] == 0)
2045     return build_string ("");
2046   return ns_string_from_pasteboard (pb);
2050 DEFUN ("ns-convert-utf8-nfd-to-nfc", Fns_convert_utf8_nfd_to_nfc,
2051        Sns_convert_utf8_nfd_to_nfc, 1, 1, 0,
2052        doc: /* Return an NFC string that matches the UTF-8 NFD string STR.  */)
2053      (Lisp_Object str)
2055 /* TODO: If GNUstep ever implements precomposedStringWithCanonicalMapping,
2056          remove this. */
2057   NSString *utfStr;
2058   Lisp_Object ret = Qnil;
2059   NSAutoreleasePool *pool;
2061   CHECK_STRING (str);
2062   pool = [[NSAutoreleasePool alloc] init];
2063   utfStr = [NSString stringWithUTF8String: SSDATA (str)];
2064 #ifdef NS_IMPL_COCOA
2065   if (utfStr)
2066     utfStr = [utfStr precomposedStringWithCanonicalMapping];
2067 #endif
2068   if (utfStr)
2069     {
2070       const char *cstr = [utfStr UTF8String];
2071       if (cstr)
2072         ret = build_string (cstr);
2073     }
2075   [pool release];
2076   if (NILP (ret))
2077     error ("Invalid UTF-8");
2079   return ret;
2083 #ifdef NS_IMPL_COCOA
2085 /* Compile and execute the AppleScript SCRIPT and return the error
2086    status as function value.  A zero is returned if compilation and
2087    execution is successful, in which case *RESULT is set to a Lisp
2088    string or a number containing the resulting script value.  Otherwise,
2089    1 is returned. */
2090 static int
2091 ns_do_applescript (Lisp_Object script, Lisp_Object *result)
2093   NSAppleEventDescriptor *desc;
2094   NSDictionary* errorDict;
2095   NSAppleEventDescriptor* returnDescriptor = NULL;
2097   NSAppleScript* scriptObject =
2098     [[NSAppleScript alloc] initWithSource:
2099                              [NSString stringWithUTF8String: SSDATA (script)]];
2101   returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
2102   [scriptObject release];
2103   *result = Qnil;
2105   if (returnDescriptor != NULL)
2106     {
2107       // successful execution
2108       if (kAENullEvent != [returnDescriptor descriptorType])
2109         {
2110           *result = Qt;
2111           // script returned an AppleScript result
2112           if ((typeUnicodeText == [returnDescriptor descriptorType]) ||
2113 #if defined (NS_IMPL_COCOA)
2114               (typeUTF16ExternalRepresentation
2115                == [returnDescriptor descriptorType]) ||
2116 #endif
2117               (typeUTF8Text == [returnDescriptor descriptorType]) ||
2118               (typeCString == [returnDescriptor descriptorType]))
2119             {
2120               desc = [returnDescriptor coerceToDescriptorType: typeUTF8Text];
2121               if (desc)
2122                 *result = build_string([[desc stringValue] UTF8String]);
2123             }
2124           else
2125             {
2126               /* use typeUTF16ExternalRepresentation? */
2127               // coerce the result to the appropriate ObjC type
2128               desc = [returnDescriptor coerceToDescriptorType: typeUTF8Text];
2129               if (desc)
2130                 *result = make_number([desc int32Value]);
2131             }
2132         }
2133     }
2134   else
2135     {
2136       // no script result, return error
2137       return 1;
2138     }
2139   return 0;
2142 /* Helper function called from sendEvent to run applescript
2143    from within the main event loop.  */
2145 void
2146 ns_run_ascript (void)
2148   if (! NILP (as_script))
2149     as_status = ns_do_applescript (as_script, as_result);
2150   as_script = Qnil;
2153 DEFUN ("ns-do-applescript", Fns_do_applescript, Sns_do_applescript, 1, 1, 0,
2154        doc: /* Execute AppleScript SCRIPT and return the result.
2155 If compilation and execution are successful, the resulting script value
2156 is returned as a string, a number or, in the case of other constructs, t.
2157 In case the execution fails, an error is signaled. */)
2158      (Lisp_Object script)
2160   Lisp_Object result;
2161   int status;
2162   NSEvent *nxev;
2163   struct input_event ev;
2165   CHECK_STRING (script);
2166   check_window_system (NULL);
2168   block_input ();
2170   as_script = script;
2171   as_result = &result;
2173   /* executing apple script requires the event loop to run, otherwise
2174      errors aren't returned and executeAndReturnError hangs forever.
2175      Post an event that runs applescript and then start the event loop.
2176      The event loop is exited when the script is done.  */
2177   nxev = [NSEvent otherEventWithType: NSApplicationDefined
2178                             location: NSMakePoint (0, 0)
2179                        modifierFlags: 0
2180                            timestamp: 0
2181                         windowNumber: [[NSApp mainWindow] windowNumber]
2182                              context: [NSApp context]
2183                              subtype: 0
2184                                data1: 0
2185                                data2: NSAPP_DATA2_RUNASSCRIPT];
2187   [NSApp postEvent: nxev atStart: NO];
2189   // If there are other events, the event loop may exit.  Keep running
2190   // until the script has been handled.  */
2191   ns_init_events (&ev);
2192   while (! NILP (as_script))
2193     [NSApp run];
2194   ns_finish_events ();
2196   status = as_status;
2197   as_status = 0;
2198   as_result = 0;
2199   unblock_input ();
2200   if (status == 0)
2201     return result;
2202   else if (!STRINGP (result))
2203     error ("AppleScript error %d", status);
2204   else
2205     error ("%s", SSDATA (result));
2207 #endif
2211 /* ==========================================================================
2213     Miscellaneous functions not called through hooks
2215    ========================================================================== */
2217 /* called from frame.c */
2218 struct ns_display_info *
2219 check_x_display_info (Lisp_Object frame)
2221   return check_ns_display_info (frame);
2225 void
2226 x_set_scroll_bar_default_width (struct frame *f)
2228   int wid = FRAME_COLUMN_WIDTH (f);
2229   FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = NS_SCROLL_BAR_WIDTH_DEFAULT;
2230   FRAME_CONFIG_SCROLL_BAR_COLS (f) = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) +
2231                                       wid - 1) / wid;
2234 /* terms impl this instead of x-get-resource directly */
2235 char *
2236 x_get_string_resource (XrmDatabase rdb, const char *name, const char *class)
2238   /* remove appname prefix; TODO: allow for !="Emacs" */
2239   const char *res, *toCheck = class + (!strncmp (class, "Emacs.", 6) ? 6 : 0);
2241   check_window_system (NULL);
2243   if (inhibit_x_resources)
2244     /* --quick was passed, so this is a no-op.  */
2245     return NULL;
2247   res = ns_get_defaults_value (toCheck);
2248   return (!res ? NULL :
2249           (!c_strncasecmp (res, "YES", 3) ? "true" :
2250            (!c_strncasecmp (res, "NO", 2) ? "false" : (char *) res)));
2254 Lisp_Object
2255 x_get_focus_frame (struct frame *frame)
2257   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
2258   Lisp_Object nsfocus;
2260   if (!dpyinfo->x_focus_frame)
2261     return Qnil;
2263   XSETFRAME (nsfocus, dpyinfo->x_focus_frame);
2264   return nsfocus;
2267 /* ==========================================================================
2269     Lisp definitions that, for whatever reason, we can't alias as 'ns-XXX'.
2271    ========================================================================== */
2274 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
2275        doc: /* Internal function called by `color-defined-p', which see.
2276 \(Note that the Nextstep version of this function ignores FRAME.)  */)
2277      (Lisp_Object color, Lisp_Object frame)
2279   NSColor * col;
2280   check_window_system (NULL);
2281   return ns_lisp_to_color (color, &col) ? Qnil : Qt;
2285 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
2286        doc: /* Internal function called by `color-values', which see.  */)
2287      (Lisp_Object color, Lisp_Object frame)
2289   NSColor * col;
2290   EmacsCGFloat red, green, blue, alpha;
2292   check_window_system (NULL);
2293   CHECK_STRING (color);
2295   if (ns_lisp_to_color (color, &col))
2296     return Qnil;
2298   [[col colorUsingDefaultColorSpace]
2299         getRed: &red green: &green blue: &blue alpha: &alpha];
2300   return list3i (lrint (red * 65280), lrint (green * 65280),
2301                  lrint (blue * 65280));
2305 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
2306        doc: /* Internal function called by `display-color-p', which see.  */)
2307      (Lisp_Object terminal)
2309   NSWindowDepth depth;
2310   NSString *colorSpace;
2312   check_ns_display_info (terminal);
2313   depth = [[[NSScreen screens] objectAtIndex:0] depth];
2314   colorSpace = NSColorSpaceFromDepth (depth);
2316   return    [colorSpace isEqualToString: NSDeviceWhiteColorSpace]
2317          || [colorSpace isEqualToString: NSCalibratedWhiteColorSpace]
2318       ? Qnil : Qt;
2322 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p, Sx_display_grayscale_p,
2323        0, 1, 0,
2324        doc: /* Return t if the Nextstep display supports shades of gray.
2325 Note that color displays do support shades of gray.
2326 The optional argument TERMINAL specifies which display to ask about.
2327 TERMINAL should be a terminal object, a frame or a display name (a string).
2328 If omitted or nil, that stands for the selected frame's display.  */)
2329   (Lisp_Object terminal)
2331   NSWindowDepth depth;
2333   check_ns_display_info (terminal);
2334   depth = [[[NSScreen screens] objectAtIndex:0] depth];
2336   return NSBitsPerPixelFromDepth (depth) > 1 ? Qt : Qnil;
2340 DEFUN ("x-display-pixel-width", Fx_display_pixel_width, Sx_display_pixel_width,
2341        0, 1, 0,
2342        doc: /* Return the width in pixels of the Nextstep display TERMINAL.
2343 The optional argument TERMINAL specifies which display to ask about.
2344 TERMINAL should be a terminal object, a frame or a display name (a string).
2345 If omitted or nil, that stands for the selected frame's display.
2347 On \"multi-monitor\" setups this refers to the pixel width for all
2348 physical monitors associated with TERMINAL.  To get information for
2349 each physical monitor, use `display-monitor-attributes-list'.  */)
2350   (Lisp_Object terminal)
2352   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
2354   return make_number (x_display_pixel_width (dpyinfo));
2358 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
2359        Sx_display_pixel_height, 0, 1, 0,
2360        doc: /* Return the height in pixels of the Nextstep display TERMINAL.
2361 The optional argument TERMINAL specifies which display to ask about.
2362 TERMINAL should be a terminal object, a frame or a display name (a string).
2363 If omitted or nil, that stands for the selected frame's display.
2365 On \"multi-monitor\" setups this refers to the pixel height for all
2366 physical monitors associated with TERMINAL.  To get information for
2367 each physical monitor, use `display-monitor-attributes-list'.  */)
2368   (Lisp_Object terminal)
2370   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
2372   return make_number (x_display_pixel_height (dpyinfo));
2375 #ifdef NS_IMPL_COCOA
2377 /* Returns the name for the screen that OBJ represents, or NULL.
2378    Caller must free return value.
2381 static char *
2382 ns_get_name_from_ioreg (io_object_t obj)
2384   char *name = NULL;
2386   NSDictionary *info = (NSDictionary *)
2387     IODisplayCreateInfoDictionary (obj, kIODisplayOnlyPreferredName);
2388   NSDictionary *names = [info objectForKey:
2389                                 [NSString stringWithUTF8String:
2390                                             kDisplayProductName]];
2392   if ([names count] > 0)
2393     {
2394       NSString *n = [names objectForKey: [[names allKeys]
2395                                                  objectAtIndex:0]];
2396       if (n != nil) name = xstrdup ([n UTF8String]);
2397     }
2399   [info release];
2401   return name;
2404 /* Returns the name for the screen that DID came from, or NULL.
2405    Caller must free return value.
2408 static char *
2409 ns_screen_name (CGDirectDisplayID did)
2411   char *name = NULL;
2413 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
2414   mach_port_t masterPort;
2415   io_iterator_t it;
2416   io_object_t obj;
2418   // CGDisplayIOServicePort is deprecated.  Do it another (harder) way.
2420   if (IOMasterPort (MACH_PORT_NULL, &masterPort) != kIOReturnSuccess
2421       || IOServiceGetMatchingServices (masterPort,
2422                                        IOServiceMatching ("IONDRVDevice"),
2423                                        &it) != kIOReturnSuccess)
2424     return name;
2426   /* Must loop until we find a name.  Many devices can have the same unit
2427      number (represents different GPU parts), but only one has a name.  */
2428   while (! name && (obj = IOIteratorNext (it)))
2429     {
2430       CFMutableDictionaryRef props;
2431       const void *val;
2433       if (IORegistryEntryCreateCFProperties (obj,
2434                                              &props,
2435                                              kCFAllocatorDefault,
2436                                              kNilOptions) == kIOReturnSuccess
2437           && props != nil
2438           && (val = CFDictionaryGetValue(props, @"IOFBDependentIndex")))
2439         {
2440           unsigned nr = [(NSNumber *)val unsignedIntegerValue];
2441           if (nr == CGDisplayUnitNumber (did))
2442             name = ns_get_name_from_ioreg (obj);
2443         }
2445       CFRelease (props);
2446       IOObjectRelease (obj);
2447     }
2449   IOObjectRelease (it);
2451 #else
2453   name = ns_get_name_from_ioreg (CGDisplayIOServicePort (did));
2455 #endif
2456   return name;
2458 #endif
2460 static Lisp_Object
2461 ns_make_monitor_attribute_list (struct MonitorInfo *monitors,
2462                                 int n_monitors,
2463                                 int primary_monitor,
2464                                 const char *source)
2466   Lisp_Object monitor_frames = Fmake_vector (make_number (n_monitors), Qnil);
2467   Lisp_Object frame, rest;
2468   NSArray *screens = [NSScreen screens];
2469   int i;
2471   FOR_EACH_FRAME (rest, frame)
2472     {
2473       struct frame *f = XFRAME (frame);
2475       if (FRAME_NS_P (f))
2476         {
2477           NSView *view = FRAME_NS_VIEW (f);
2478           NSScreen *screen = [[view window] screen];
2479           NSUInteger k;
2481           i = -1;
2482           for (k = 0; i == -1 && k < [screens count]; ++k)
2483             {
2484               if ([screens objectAtIndex: k] == screen)
2485                 i = (int)k;
2486             }
2488           if (i > -1)
2489             ASET (monitor_frames, i, Fcons (frame, AREF (monitor_frames, i)));
2490         }
2491     }
2493   return make_monitor_attribute_list (monitors, n_monitors, primary_monitor,
2494                                       monitor_frames, source);
2497 DEFUN ("ns-display-monitor-attributes-list",
2498        Fns_display_monitor_attributes_list,
2499        Sns_display_monitor_attributes_list,
2500        0, 1, 0,
2501        doc: /* Return a list of physical monitor attributes on the X display TERMINAL.
2503 The optional argument TERMINAL specifies which display to ask about.
2504 TERMINAL should be a terminal object, a frame or a display name (a string).
2505 If omitted or nil, that stands for the selected frame's display.
2507 In addition to the standard attribute keys listed in
2508 `display-monitor-attributes-list', the following keys are contained in
2509 the attributes:
2511  source -- String describing the source from which multi-monitor
2512            information is obtained, \"NS\" is always the source."
2514 Internal use only, use `display-monitor-attributes-list' instead.  */)
2515   (Lisp_Object terminal)
2517   struct terminal *term = get_terminal (terminal, 1);
2518   NSArray *screens;
2519   NSUInteger i, n_monitors;
2520   struct MonitorInfo *monitors;
2521   Lisp_Object attributes_list = Qnil;
2522   CGFloat primary_display_height = 0;
2524   if (term->type != output_ns)
2525     return Qnil;
2527   screens = [NSScreen screens];
2528   n_monitors = [screens count];
2529   if (n_monitors == 0)
2530     return Qnil;
2532   monitors = xzalloc (n_monitors * sizeof *monitors);
2534   for (i = 0; i < [screens count]; ++i)
2535     {
2536       NSScreen *s = [screens objectAtIndex:i];
2537       struct MonitorInfo *m = &monitors[i];
2538       NSRect fr = [s frame];
2539       NSRect vfr = [s visibleFrame];
2540       short y, vy;
2542 #ifdef NS_IMPL_COCOA
2543       NSDictionary *dict = [s deviceDescription];
2544       NSNumber *nid = [dict objectForKey:@"NSScreenNumber"];
2545       CGDirectDisplayID did = [nid unsignedIntValue];
2546 #endif
2547       if (i == 0)
2548         {
2549           primary_display_height = fr.size.height;
2550           y = (short) fr.origin.y;
2551           vy = (short) vfr.origin.y;
2552         }
2553       else
2554         {
2555           // Flip y coordinate as NS has y starting from the bottom.
2556           y = (short) (primary_display_height - fr.size.height - fr.origin.y);
2557           vy = (short) (primary_display_height -
2558                         vfr.size.height - vfr.origin.y);
2559         }
2561       m->geom.x = (short) fr.origin.x;
2562       m->geom.y = y;
2563       m->geom.width = (unsigned short) fr.size.width;
2564       m->geom.height = (unsigned short) fr.size.height;
2566       m->work.x = (short) vfr.origin.x;
2567       // y is flipped on NS, so vy - y are pixels missing at the bottom,
2568       // and fr.size.height - vfr.size.height are pixels missing in total.
2569       // Pixels missing at top are
2570       // fr.size.height - vfr.size.height - vy + y.
2571       // work.y is then pixels missing at top + y.
2572       m->work.y = (short) (fr.size.height - vfr.size.height) - vy + y + y;
2573       m->work.width = (unsigned short) vfr.size.width;
2574       m->work.height = (unsigned short) vfr.size.height;
2576 #ifdef NS_IMPL_COCOA
2577       m->name = ns_screen_name (did);
2579       {
2580         CGSize mms = CGDisplayScreenSize (did);
2581         m->mm_width = (int) mms.width;
2582         m->mm_height = (int) mms.height;
2583       }
2585 #else
2586       // Assume 92 dpi as x-display-mm-height/x-display-mm-width does.
2587       m->mm_width = (int) (25.4 * fr.size.width / 92.0);
2588       m->mm_height = (int) (25.4 * fr.size.height / 92.0);
2589 #endif
2590     }
2592   // Primary monitor is always first for NS.
2593   attributes_list = ns_make_monitor_attribute_list (monitors, n_monitors,
2594                                                     0, "NS");
2596   free_monitors (monitors, n_monitors);
2597   return attributes_list;
2601 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
2602        0, 1, 0,
2603        doc: /* Return the number of bitplanes of the Nextstep display TERMINAL.
2604 The optional argument TERMINAL specifies which display to ask about.
2605 TERMINAL should be a terminal object, a frame or a display name (a string).
2606 If omitted or nil, that stands for the selected frame's display.  */)
2607   (Lisp_Object terminal)
2609   check_ns_display_info (terminal);
2610   return make_number
2611     (NSBitsPerPixelFromDepth ([[[NSScreen screens] objectAtIndex:0] depth]));
2615 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
2616        0, 1, 0,
2617        doc: /* Returns the number of color cells of the Nextstep display TERMINAL.
2618 The optional argument TERMINAL specifies which display to ask about.
2619 TERMINAL should be a terminal object, a frame or a display name (a string).
2620 If omitted or nil, that stands for the selected frame's display.  */)
2621   (Lisp_Object terminal)
2623   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
2624   /* We force 24+ bit depths to 24-bit to prevent an overflow.  */
2625   return make_number (1 << min (dpyinfo->n_planes, 24));
2629 /* Unused dummy def needed for compatibility. */
2630 Lisp_Object tip_frame;
2632 /* TODO: move to xdisp or similar */
2633 static void
2634 compute_tip_xy (struct frame *f,
2635                 Lisp_Object parms,
2636                 Lisp_Object dx,
2637                 Lisp_Object dy,
2638                 int width,
2639                 int height,
2640                 int *root_x,
2641                 int *root_y)
2643   Lisp_Object left, top;
2644   EmacsView *view = FRAME_NS_VIEW (f);
2645   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2646   NSPoint pt;
2648   /* Start with user-specified or mouse position.  */
2649   left = Fcdr (Fassq (Qleft, parms));
2650   top = Fcdr (Fassq (Qtop, parms));
2652   if (!INTEGERP (left) || !INTEGERP (top))
2653     {
2654       pt.x = dpyinfo->last_mouse_motion_x;
2655       pt.y = dpyinfo->last_mouse_motion_y;
2656       /* Convert to screen coordinates */
2657       pt = [view convertPoint: pt toView: nil];
2658       pt = [[view window] convertBaseToScreen: pt];
2659     }
2660   else
2661     {
2662       /* Absolute coordinates.  */
2663       pt.x = XINT (left);
2664       pt.y = x_display_pixel_height (FRAME_DISPLAY_INFO (f)) - XINT (top)
2665         - height;
2666     }
2668   /* Ensure in bounds.  (Note, screen origin = lower left.) */
2669   if (INTEGERP (left))
2670     *root_x = pt.x;
2671   else if (pt.x + XINT (dx) <= 0)
2672     *root_x = 0; /* Can happen for negative dx */
2673   else if (pt.x + XINT (dx) + width
2674            <= x_display_pixel_width (FRAME_DISPLAY_INFO (f)))
2675     /* It fits to the right of the pointer.  */
2676     *root_x = pt.x + XINT (dx);
2677   else if (width + XINT (dx) <= pt.x)
2678     /* It fits to the left of the pointer.  */
2679     *root_x = pt.x - width - XINT (dx);
2680   else
2681     /* Put it left justified on the screen -- it ought to fit that way.  */
2682     *root_x = 0;
2684   if (INTEGERP (top))
2685     *root_y = pt.y;
2686   else if (pt.y - XINT (dy) - height >= 0)
2687     /* It fits below the pointer.  */
2688     *root_y = pt.y - height - XINT (dy);
2689   else if (pt.y + XINT (dy) + height
2690            <= x_display_pixel_height (FRAME_DISPLAY_INFO (f)))
2691     /* It fits above the pointer */
2692       *root_y = pt.y + XINT (dy);
2693   else
2694     /* Put it on the top.  */
2695     *root_y = x_display_pixel_height (FRAME_DISPLAY_INFO (f)) - height;
2699 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
2700        doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
2701 A tooltip window is a small window displaying a string.
2703 This is an internal function; Lisp code should call `tooltip-show'.
2705 FRAME nil or omitted means use the selected frame.
2707 PARMS is an optional list of frame parameters which can be used to
2708 change the tooltip's appearance.
2710 Automatically hide the tooltip after TIMEOUT seconds.  TIMEOUT nil
2711 means use the default timeout of 5 seconds.
2713 If the list of frame parameters PARMS contains a `left' parameter,
2714 the tooltip is displayed at that x-position.  Otherwise it is
2715 displayed at the mouse position, with offset DX added (default is 5 if
2716 DX isn't specified).  Likewise for the y-position; if a `top' frame
2717 parameter is specified, it determines the y-position of the tooltip
2718 window, otherwise it is displayed at the mouse position, with offset
2719 DY added (default is -10).
2721 A tooltip's maximum size is specified by `x-max-tooltip-size'.
2722 Text larger than the specified size is clipped.  */)
2723      (Lisp_Object string, Lisp_Object frame, Lisp_Object parms, Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
2725   int root_x, root_y;
2726   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2727   ptrdiff_t count = SPECPDL_INDEX ();
2728   struct frame *f;
2729   char *str;
2730   NSSize size;
2732   specbind (Qinhibit_redisplay, Qt);
2734   GCPRO4 (string, parms, frame, timeout);
2736   CHECK_STRING (string);
2737   str = SSDATA (string);
2738   f = decode_window_system_frame (frame);
2739   if (NILP (timeout))
2740     timeout = make_number (5);
2741   else
2742     CHECK_NATNUM (timeout);
2744   if (NILP (dx))
2745     dx = make_number (5);
2746   else
2747     CHECK_NUMBER (dx);
2749   if (NILP (dy))
2750     dy = make_number (-10);
2751   else
2752     CHECK_NUMBER (dy);
2754   block_input ();
2755   if (ns_tooltip == nil)
2756     ns_tooltip = [[EmacsTooltip alloc] init];
2757   else
2758     Fx_hide_tip ();
2760   [ns_tooltip setText: str];
2761   size = [ns_tooltip frame].size;
2763   /* Move the tooltip window where the mouse pointer is.  Resize and
2764      show it.  */
2765   compute_tip_xy (f, parms, dx, dy, (int)size.width, (int)size.height,
2766                   &root_x, &root_y);
2768   [ns_tooltip showAtX: root_x Y: root_y for: XINT (timeout)];
2769   unblock_input ();
2771   UNGCPRO;
2772   return unbind_to (count, Qnil);
2776 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
2777        doc: /* Hide the current tooltip window, if there is any.
2778 Value is t if tooltip was open, nil otherwise.  */)
2779      (void)
2781   if (ns_tooltip == nil || ![ns_tooltip isActive])
2782     return Qnil;
2783   [ns_tooltip hide];
2784   return Qt;
2788 /* ==========================================================================
2790     Class implementations
2792    ========================================================================== */
2795   Handle arrow/function/control keys and copy/paste/cut in file dialogs.
2796   Return YES if handled, NO if not.
2797  */
2798 static BOOL
2799 handlePanelKeys (NSSavePanel *panel, NSEvent *theEvent)
2801   NSString *s;
2802   int i;
2803   BOOL ret = NO;
2805   if ([theEvent type] != NSKeyDown) return NO;
2806   s = [theEvent characters];
2808   for (i = 0; i < [s length]; ++i)
2809     {
2810       int ch = (int) [s characterAtIndex: i];
2811       switch (ch)
2812         {
2813         case NSHomeFunctionKey:
2814         case NSDownArrowFunctionKey:
2815         case NSUpArrowFunctionKey:
2816         case NSLeftArrowFunctionKey:
2817         case NSRightArrowFunctionKey:
2818         case NSPageUpFunctionKey:
2819         case NSPageDownFunctionKey:
2820         case NSEndFunctionKey:
2821           /* Don't send command modified keys, as those are handled in the
2822              performKeyEquivalent method of the super class.
2823           */
2824           if (! ([theEvent modifierFlags] & NSCommandKeyMask))
2825             {
2826               [panel sendEvent: theEvent];
2827               ret = YES;
2828             }
2829           break;
2830           /* As we don't have the standard key commands for
2831              copy/paste/cut/select-all in our edit menu, we must handle
2832              them here.  TODO: handle Emacs key bindings for copy/cut/select-all
2833              here, paste works, because we have that in our Edit menu.
2834              I.e. refactor out code in nsterm.m, keyDown: to figure out the
2835              correct modifier.
2836           */
2837         case 'x': // Cut
2838         case 'c': // Copy
2839         case 'v': // Paste
2840         case 'a': // Select all
2841           if ([theEvent modifierFlags] & NSCommandKeyMask)
2842             {
2843               [NSApp sendAction:
2844                        (ch == 'x'
2845                         ? @selector(cut:)
2846                         : (ch == 'c'
2847                            ? @selector(copy:)
2848                            : (ch == 'v'
2849                               ? @selector(paste:)
2850                               : @selector(selectAll:))))
2851                              to:nil from:panel];
2852               ret = YES;
2853             }
2854         default:
2855           // Send all control keys, as the text field supports C-a, C-f, C-e
2856           // C-b and more.
2857           if ([theEvent modifierFlags] & NSControlKeyMask)
2858             {
2859               [panel sendEvent: theEvent];
2860               ret = YES;
2861             }
2862           break;
2863         }
2864     }
2867   return ret;
2870 @implementation EmacsSavePanel
2871 - (BOOL)performKeyEquivalent:(NSEvent *)theEvent
2873   BOOL ret = handlePanelKeys (self, theEvent);
2874   if (! ret)
2875     ret = [super performKeyEquivalent:theEvent];
2876   return ret;
2878 @end
2881 @implementation EmacsOpenPanel
2882 - (BOOL)performKeyEquivalent:(NSEvent *)theEvent
2884   // NSOpenPanel inherits NSSavePanel, so passing self is OK.
2885   BOOL ret = handlePanelKeys (self, theEvent);
2886   if (! ret)
2887     ret = [super performKeyEquivalent:theEvent];
2888   return ret;
2890 @end
2893 @implementation EmacsFileDelegate
2894 /* --------------------------------------------------------------------------
2895    Delegate methods for Open/Save panels
2896    -------------------------------------------------------------------------- */
2897 - (BOOL)panel: (id)sender isValidFilename: (NSString *)filename
2899   return YES;
2901 - (BOOL)panel: (id)sender shouldShowFilename: (NSString *)filename
2903   return YES;
2905 - (NSString *)panel: (id)sender userEnteredFilename: (NSString *)filename
2906           confirmed: (BOOL)okFlag
2908   return filename;
2910 @end
2912 #endif
2915 /* ==========================================================================
2917     Lisp interface declaration
2919    ========================================================================== */
2922 void
2923 syms_of_nsfns (void)
2925   Qfontsize = intern_c_string ("fontsize");
2926   staticpro (&Qfontsize);
2928   DEFVAR_LISP ("ns-icon-type-alist", Vns_icon_type_alist,
2929                doc: /* Alist of elements (REGEXP . IMAGE) for images of icons associated to frames.
2930 If the title of a frame matches REGEXP, then IMAGE.tiff is
2931 selected as the image of the icon representing the frame when it's
2932 miniaturized.  If an element is t, then Emacs tries to select an icon
2933 based on the filetype of the visited file.
2935 The images have to be installed in a folder called English.lproj in the
2936 Emacs folder.  You have to restart Emacs after installing new icons.
2938 Example: Install an icon Gnus.tiff and execute the following code
2940   (setq ns-icon-type-alist
2941         (append ns-icon-type-alist
2942                 '((\"^\\\\*\\\\(Group\\\\*$\\\\|Summary \\\\|Article\\\\*$\\\\)\"
2943                    . \"Gnus\"))))
2945 When you miniaturize a Group, Summary or Article frame, Gnus.tiff will
2946 be used as the image of the icon representing the frame.  */);
2947   Vns_icon_type_alist = list1 (Qt);
2949   DEFVAR_LISP ("ns-version-string", Vns_version_string,
2950                doc: /* Toolkit version for NS Windowing.  */);
2951   Vns_version_string = ns_appkit_version_str ();
2953   defsubr (&Sns_read_file_name);
2954   defsubr (&Sns_get_resource);
2955   defsubr (&Sns_set_resource);
2956   defsubr (&Sxw_display_color_p); /* this and next called directly by C code */
2957   defsubr (&Sx_display_grayscale_p);
2958   defsubr (&Sns_font_name);
2959   defsubr (&Sns_list_colors);
2960 #ifdef NS_IMPL_COCOA
2961   defsubr (&Sns_do_applescript);
2962 #endif
2963   defsubr (&Sxw_color_defined_p);
2964   defsubr (&Sxw_color_values);
2965   defsubr (&Sx_server_max_request_size);
2966   defsubr (&Sx_server_vendor);
2967   defsubr (&Sx_server_version);
2968   defsubr (&Sx_display_pixel_width);
2969   defsubr (&Sx_display_pixel_height);
2970   defsubr (&Sns_display_monitor_attributes_list);
2971   defsubr (&Sx_display_mm_width);
2972   defsubr (&Sx_display_mm_height);
2973   defsubr (&Sx_display_screens);
2974   defsubr (&Sx_display_planes);
2975   defsubr (&Sx_display_color_cells);
2976   defsubr (&Sx_display_visual_class);
2977   defsubr (&Sx_display_backing_store);
2978   defsubr (&Sx_display_save_under);
2979   defsubr (&Sx_create_frame);
2980   defsubr (&Sx_open_connection);
2981   defsubr (&Sx_close_connection);
2982   defsubr (&Sx_display_list);
2984   defsubr (&Sns_hide_others);
2985   defsubr (&Sns_hide_emacs);
2986   defsubr (&Sns_emacs_info_panel);
2987   defsubr (&Sns_list_services);
2988   defsubr (&Sns_perform_service);
2989   defsubr (&Sns_convert_utf8_nfd_to_nfc);
2990   defsubr (&Sns_popup_font_panel);
2991   defsubr (&Sns_popup_color_panel);
2993   defsubr (&Sx_show_tip);
2994   defsubr (&Sx_hide_tip);
2996   as_status = 0;
2997   as_script = Qnil;
2998   as_result = 0;