Backport Tramp changes from trunk.
[emacs.git] / src / nsfns.m
blob4fa62f5685172e6a4e427177be4cdfccf5a2bc8c
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 Qleft;
77 extern Lisp_Object Qright;
78 extern Lisp_Object Qtop;
79 extern Lisp_Object Qdisplay;
80 extern Lisp_Object Qvertical_scroll_bars;
81 extern Lisp_Object Qauto_raise;
82 extern Lisp_Object Qauto_lower;
83 extern Lisp_Object Qbox;
84 extern Lisp_Object Qscroll_bar_width;
85 extern Lisp_Object Qx_resource_name;
86 extern Lisp_Object Qface_set_after_frame_default;
87 extern Lisp_Object Qunderline, Qundefined;
88 extern Lisp_Object Qheight, Qminibuffer, Qname, Qonly, Qwidth;
89 extern Lisp_Object Qunsplittable, Qmenu_bar_lines, Qbuffer_predicate, Qtitle;
92 Lisp_Object Qbuffered;
93 Lisp_Object Qfontsize;
95 EmacsTooltip *ns_tooltip = nil;
97 /* Need forward declaration here to preserve organizational integrity of file */
98 Lisp_Object Fx_open_connection (Lisp_Object, Lisp_Object, Lisp_Object);
100 /* Static variables to handle applescript execution.  */
101 static Lisp_Object as_script, *as_result;
102 static int as_status;
104 #ifdef GLYPH_DEBUG
105 static ptrdiff_t image_cache_refcount;
106 #endif
109 /* ==========================================================================
111     Internal utility functions
113    ========================================================================== */
115 /* Let the user specify a Nextstep display with a Lisp object.
116    OBJECT may be nil, a frame or a terminal object.
117    nil stands for the selected frame--or, if that is not a Nextstep frame,
118    the first Nextstep display on the list.  */
120 static struct ns_display_info *
121 check_ns_display_info (Lisp_Object object)
123   struct ns_display_info *dpyinfo = NULL;
125   if (NILP (object))
126     {
127       struct frame *sf = XFRAME (selected_frame);
129       if (FRAME_NS_P (sf) && FRAME_LIVE_P (sf))
130         dpyinfo = FRAME_DISPLAY_INFO (sf);
131       else if (x_display_list != 0)
132         dpyinfo = x_display_list;
133       else
134         error ("Nextstep windows are not in use or not initialized");
135     }
136   else if (TERMINALP (object))
137     {
138       struct terminal *t = get_terminal (object, 1);
140       if (t->type != output_ns)
141         error ("Terminal %d is not a Nextstep display", t->id);
143       dpyinfo = t->display_info.ns;
144     }
145   else if (STRINGP (object))
146     dpyinfo = ns_display_info_for_name (object);
147   else
148     {
149       struct frame *f = decode_window_system_frame (object);
150       dpyinfo = FRAME_DISPLAY_INFO (f);
151     }
153   return dpyinfo;
157 static id
158 ns_get_window (Lisp_Object maybeFrame)
160   id view =nil, window =nil;
162   if (!FRAMEP (maybeFrame) || !FRAME_NS_P (XFRAME (maybeFrame)))
163     maybeFrame = selected_frame;/*wrong_type_argument (Qframep, maybeFrame); */
165   if (!NILP (maybeFrame))
166     view = FRAME_NS_VIEW (XFRAME (maybeFrame));
167   if (view) window =[view window];
169   return window;
173 /* Return the X display structure for the display named NAME.
174    Open a new connection if necessary.  */
175 struct ns_display_info *
176 ns_display_info_for_name (Lisp_Object name)
178   struct ns_display_info *dpyinfo;
180   CHECK_STRING (name);
182   for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
183     if (!NILP (Fstring_equal (XCAR (dpyinfo->name_list_element), name)))
184       return dpyinfo;
186   error ("Emacs for Nextstep does not yet support multi-display");
188   Fx_open_connection (name, Qnil, Qnil);
189   dpyinfo = x_display_list;
191   if (dpyinfo == 0)
192     error ("Display on %s not responding.\n", SDATA (name));
194   return dpyinfo;
197 static NSString *
198 ns_filename_from_panel (NSSavePanel *panel)
200 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
201   NSURL *url = [panel URL];
202   NSString *str = [url path];
203   return str;
204 #else
205   return [panel filename];
206 #endif
209 static NSString *
210 ns_directory_from_panel (NSSavePanel *panel)
212 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
213   NSURL *url = [panel directoryURL];
214   NSString *str = [url path];
215   return str;
216 #else
217   return [panel directory];
218 #endif
221 static Lisp_Object
222 interpret_services_menu (NSMenu *menu, Lisp_Object prefix, Lisp_Object old)
223 /* --------------------------------------------------------------------------
224    Turn the input menu (an NSMenu) into a lisp list for tracking on lisp side
225    -------------------------------------------------------------------------- */
227   int i, count;
228   NSMenuItem *item;
229   const char *name;
230   Lisp_Object nameStr;
231   unsigned short key;
232   NSString *keys;
233   Lisp_Object res;
235   count = [menu numberOfItems];
236   for (i = 0; i<count; i++)
237     {
238       item = [menu itemAtIndex: i];
239       name = [[item title] UTF8String];
240       if (!name) continue;
242       nameStr = build_string (name);
244       if ([item hasSubmenu])
245         {
246           old = interpret_services_menu ([item submenu],
247                                         Fcons (nameStr, prefix), old);
248         }
249       else
250         {
251           keys = [item keyEquivalent];
252           if (keys && [keys length] )
253             {
254               key = [keys characterAtIndex: 0];
255               res = make_number (key|super_modifier);
256             }
257           else
258             {
259               res = Qundefined;
260             }
261           old = Fcons (Fcons (res,
262                             Freverse (Fcons (nameStr,
263                                            prefix))),
264                     old);
265         }
266     }
267   return old;
272 /* ==========================================================================
274     Frame parameter setters
276    ========================================================================== */
279 static void
280 x_set_foreground_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
282   NSColor *col;
283   EmacsCGFloat r, g, b, alpha;
285   if (ns_lisp_to_color (arg, &col))
286     {
287       store_frame_param (f, Qforeground_color, oldval);
288       error ("Unknown color");
289     }
291   [col retain];
292   [f->output_data.ns->foreground_color release];
293   f->output_data.ns->foreground_color = col;
295   [col getRed: &r green: &g blue: &b alpha: &alpha];
296   FRAME_FOREGROUND_PIXEL (f) =
297     ARGB_TO_ULONG ((int)(alpha*0xff), (int)(r*0xff), (int)(g*0xff), (int)(b*0xff));
299   if (FRAME_NS_VIEW (f))
300     {
301       update_face_from_frame_parameter (f, Qforeground_color, arg);
302       /*recompute_basic_faces (f); */
303       if (FRAME_VISIBLE_P (f))
304         redraw_frame (f);
305     }
309 static void
310 x_set_background_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
312   struct face *face;
313   NSColor *col;
314   NSView *view = FRAME_NS_VIEW (f);
315   EmacsCGFloat r, g, b, alpha;
317   if (ns_lisp_to_color (arg, &col))
318     {
319       store_frame_param (f, Qbackground_color, oldval);
320       error ("Unknown color");
321     }
323   /* clear the frame; in some instances the NS-internal GC appears not to
324      update, or it does update and cannot clear old text properly */
325   if (FRAME_VISIBLE_P (f))
326     ns_clear_frame (f);
328   [col retain];
329   [f->output_data.ns->background_color release];
330   f->output_data.ns->background_color = col;
332   [col getRed: &r green: &g blue: &b alpha: &alpha];
333   FRAME_BACKGROUND_PIXEL (f) =
334     ARGB_TO_ULONG ((int)(alpha*0xff), (int)(r*0xff), (int)(g*0xff), (int)(b*0xff));
336   if (view != nil)
337     {
338       [[view window] setBackgroundColor: col];
340       if (alpha != (EmacsCGFloat) 1.0)
341           [[view window] setOpaque: NO];
342       else
343           [[view window] setOpaque: YES];
345       face = FRAME_DEFAULT_FACE (f);
346       if (face)
347         {
348           col = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f);
349           face->background = ns_index_color
350             ([col colorWithAlphaComponent: alpha], f);
352           update_face_from_frame_parameter (f, Qbackground_color, arg);
353         }
355       if (FRAME_VISIBLE_P (f))
356         redraw_frame (f);
357     }
361 static void
362 x_set_cursor_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
364   NSColor *col;
366   if (ns_lisp_to_color (arg, &col))
367     {
368       store_frame_param (f, Qcursor_color, oldval);
369       error ("Unknown color");
370     }
372   [FRAME_CURSOR_COLOR (f) release];
373   FRAME_CURSOR_COLOR (f) = [col retain];
375   if (FRAME_VISIBLE_P (f))
376     {
377       x_update_cursor (f, 0);
378       x_update_cursor (f, 1);
379     }
380   update_face_from_frame_parameter (f, Qcursor_color, arg);
384 static void
385 x_set_icon_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
387   NSView *view = FRAME_NS_VIEW (f);
388   NSTRACE (x_set_icon_name);
390   /* see if it's changed */
391   if (STRINGP (arg))
392     {
393       if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
394         return;
395     }
396   else if (!STRINGP (oldval) && EQ (oldval, Qnil) == EQ (arg, Qnil))
397     return;
399   fset_icon_name (f, arg);
401   if (NILP (arg))
402     {
403       if (!NILP (f->title))
404         arg = f->title;
405       else
406         /* Explicit name and no icon-name -> explicit_name.  */
407         if (f->explicit_name)
408           arg = f->name;
409         else
410           {
411             /* No explicit name and no icon-name ->
412                name has to be rebuild from icon_title_format.  */
413             windows_or_buffers_changed = 62;
414             return;
415           }
416     }
418   /* Don't change the name if it's already NAME.  */
419   if ([[view window] miniwindowTitle]
420       && ([[[view window] miniwindowTitle]
421              isEqualToString: [NSString stringWithUTF8String:
422                                           SSDATA (arg)]]))
423     return;
425   [[view window] setMiniwindowTitle:
426         [NSString stringWithUTF8String: SSDATA (arg)]];
429 static void
430 ns_set_name_internal (struct frame *f, Lisp_Object name)
432   struct gcpro gcpro1;
433   Lisp_Object encoded_name, encoded_icon_name;
434   NSString *str;
435   NSView *view = FRAME_NS_VIEW (f);
437   GCPRO1 (name);
438   encoded_name = ENCODE_UTF_8 (name);
439   UNGCPRO;
441   str = [NSString stringWithUTF8String: SSDATA (encoded_name)];
443   /* Don't change the name if it's already NAME.  */
444   if (! [[[view window] title] isEqualToString: str])
445     [[view window] setTitle: str];
447   if (!STRINGP (f->icon_name))
448     encoded_icon_name = encoded_name;
449   else
450     encoded_icon_name = ENCODE_UTF_8 (f->icon_name);
452   str = [NSString stringWithUTF8String: SSDATA (encoded_icon_name)];
454   if ([[view window] miniwindowTitle]
455       && ! [[[view window] miniwindowTitle] isEqualToString: str])
456     [[view window] setMiniwindowTitle: str];
460 static void
461 ns_set_name (struct frame *f, Lisp_Object name, int explicit)
463   NSTRACE (ns_set_name);
465   /* Make sure that requests from lisp code override requests from
466      Emacs redisplay code.  */
467   if (explicit)
468     {
469       /* If we're switching from explicit to implicit, we had better
470          update the mode lines and thereby update the title.  */
471       if (f->explicit_name && NILP (name))
472         update_mode_lines = 21;
474       f->explicit_name = ! NILP (name);
475     }
476   else if (f->explicit_name)
477     return;
479   if (NILP (name))
480     name = build_string ([ns_app_name UTF8String]);
481   else
482     CHECK_STRING (name);
484   /* Don't change the name if it's already NAME.  */
485   if (! NILP (Fstring_equal (name, f->name)))
486     return;
488   fset_name (f, name);
490   /* Title overrides explicit name.  */
491   if (! NILP (f->title))
492     name = f->title;
494   ns_set_name_internal (f, name);
498 /* This function should be called when the user's lisp code has
499    specified a name for the frame; the name will override any set by the
500    redisplay code.  */
501 static void
502 x_explicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
504   NSTRACE (x_explicitly_set_name);
505   ns_set_name (f, arg, 1);
509 /* This function should be called by Emacs redisplay code to set the
510    name; names set this way will never override names set by the user's
511    lisp code.  */
512 void
513 x_implicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
515   NSTRACE (x_implicitly_set_name);
517   /* Deal with NS specific format t.  */
518   if (FRAME_NS_P (f) && ((FRAME_ICONIFIED_P (f) && EQ (Vicon_title_format, Qt))
519                          || EQ (Vframe_title_format, Qt)))
520     ns_set_name_as_filename (f);
521   else
522     ns_set_name (f, arg, 0);
526 /* Change the title of frame F to NAME.
527    If NAME is nil, use the frame name as the title.  */
529 static void
530 x_set_title (struct frame *f, Lisp_Object name, Lisp_Object old_name)
532   NSTRACE (x_set_title);
533   /* Don't change the title if it's already NAME.  */
534   if (EQ (name, f->title))
535     return;
537   update_mode_lines = 22;
539   fset_title (f, name);
541   if (NILP (name))
542     name = f->name;
543   else
544     CHECK_STRING (name);
546   ns_set_name_internal (f, name);
550 void
551 ns_set_name_as_filename (struct frame *f)
553   NSView *view;
554   Lisp_Object name, filename;
555   Lisp_Object buf = XWINDOW (f->selected_window)->contents;
556   const char *title;
557   NSAutoreleasePool *pool;
558   struct gcpro gcpro1;
559   Lisp_Object encoded_name, encoded_filename;
560   NSString *str;
561   NSTRACE (ns_set_name_as_filename);
563   if (f->explicit_name || ! NILP (f->title))
564     return;
566   block_input ();
567   pool = [[NSAutoreleasePool alloc] init];
568   filename = BVAR (XBUFFER (buf), filename);
569   name = BVAR (XBUFFER (buf), name);
571   if (NILP (name))
572     {
573       if (! NILP (filename))
574         name = Ffile_name_nondirectory (filename);
575       else
576         name = build_string ([ns_app_name UTF8String]);
577     }
579   GCPRO1 (name);
580   encoded_name = ENCODE_UTF_8 (name);
581   UNGCPRO;
583   view = FRAME_NS_VIEW (f);
585   title = FRAME_ICONIFIED_P (f) ? [[[view window] miniwindowTitle] UTF8String]
586                                 : [[[view window] title] UTF8String];
588   if (title && (! strcmp (title, SSDATA (encoded_name))))
589     {
590       [pool release];
591       unblock_input ();
592       return;
593     }
595   str = [NSString stringWithUTF8String: SSDATA (encoded_name)];
596   if (str == nil) str = @"Bad coding";
598   if (FRAME_ICONIFIED_P (f))
599     [[view window] setMiniwindowTitle: str];
600   else
601     {
602       NSString *fstr;
604       if (! NILP (filename))
605         {
606           GCPRO1 (filename);
607           encoded_filename = ENCODE_UTF_8 (filename);
608           UNGCPRO;
610           fstr = [NSString stringWithUTF8String: SSDATA (encoded_filename)];
611           if (fstr == nil) fstr = @"";
612 #ifdef NS_IMPL_COCOA
613           /* work around a bug observed on 10.3 and later where
614              setTitleWithRepresentedFilename does not clear out previous state
615              if given filename does not exist */
616           if (! [[NSFileManager defaultManager] fileExistsAtPath: fstr])
617             [[view window] setRepresentedFilename: @""];
618 #endif
619         }
620       else
621         fstr = @"";
623       [[view window] setRepresentedFilename: fstr];
624       [[view window] setTitle: str];
625       fset_name (f, name);
626     }
628   [pool release];
629   unblock_input ();
633 void
634 ns_set_doc_edited (void)
636   NSAutoreleasePool *pool;
637   Lisp_Object tail, frame;
638   block_input ();
639   pool = [[NSAutoreleasePool alloc] init];
640   FOR_EACH_FRAME (tail, frame)
641     {
642       BOOL edited = NO;
643       struct frame *f = XFRAME (frame);
644       struct window *w = XWINDOW (FRAME_SELECTED_WINDOW (f));
645       NSView *view = FRAME_NS_VIEW (f);
646       if (!MINI_WINDOW_P (w))
647         edited = ! NILP (Fbuffer_modified_p (w->contents)) &&
648           ! NILP (Fbuffer_file_name (w->contents));
649       [[view window] setDocumentEdited: edited];
650     }
652   [pool release];
653   unblock_input ();
657 void
658 x_set_menu_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
660   int nlines;
661   if (FRAME_MINIBUF_ONLY_P (f))
662     return;
664   if (TYPE_RANGED_INTEGERP (int, value))
665     nlines = XINT (value);
666   else
667     nlines = 0;
669   FRAME_MENU_BAR_LINES (f) = 0;
670   if (nlines)
671     {
672       FRAME_EXTERNAL_MENU_BAR (f) = 1;
673       /* does for all frames, whereas we just want for one frame
674          [NSMenu setMenuBarVisible: YES]; */
675     }
676   else
677     {
678       if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
679         free_frame_menubar (f);
680       /*      [NSMenu setMenuBarVisible: NO]; */
681       FRAME_EXTERNAL_MENU_BAR (f) = 0;
682     }
686 /* toolbar support */
687 void
688 x_set_tool_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
690   int nlines;
692   if (FRAME_MINIBUF_ONLY_P (f))
693     return;
695   if (RANGED_INTEGERP (0, value, INT_MAX))
696     nlines = XFASTINT (value);
697   else
698     nlines = 0;
700   if (nlines)
701     {
702       FRAME_EXTERNAL_TOOL_BAR (f) = 1;
703       update_frame_tool_bar (f);
704     }
705   else
706     {
707       if (FRAME_EXTERNAL_TOOL_BAR (f))
708         {
709           free_frame_tool_bar (f);
710           FRAME_EXTERNAL_TOOL_BAR (f) = 0;
711         }
712     }
714   x_set_window_size (f, 0, f->text_cols, f->text_lines, 0);
718 static void
719 ns_implicitly_set_icon_type (struct frame *f)
721   Lisp_Object tem;
722   EmacsView *view = FRAME_NS_VIEW (f);
723   id image = nil;
724   Lisp_Object chain, elt;
725   NSAutoreleasePool *pool;
726   BOOL setMini = YES;
728   NSTRACE (ns_implicitly_set_icon_type);
730   block_input ();
731   pool = [[NSAutoreleasePool alloc] init];
732   if (f->output_data.ns->miniimage
733       && [[NSString stringWithUTF8String: SSDATA (f->name)]
734                isEqualToString: [(NSImage *)f->output_data.ns->miniimage name]])
735     {
736       [pool release];
737       unblock_input ();
738       return;
739     }
741   tem = assq_no_quit (Qicon_type, f->param_alist);
742   if (CONSP (tem) && ! NILP (XCDR (tem)))
743     {
744       [pool release];
745       unblock_input ();
746       return;
747     }
749   for (chain = Vns_icon_type_alist;
750        image == nil && CONSP (chain);
751        chain = XCDR (chain))
752     {
753       elt = XCAR (chain);
754       /* special case: 't' means go by file type */
755       if (SYMBOLP (elt) && EQ (elt, Qt) && SSDATA (f->name)[0] == '/')
756         {
757           NSString *str
758              = [NSString stringWithUTF8String: SSDATA (f->name)];
759           if ([[NSFileManager defaultManager] fileExistsAtPath: str])
760             image = [[[NSWorkspace sharedWorkspace] iconForFile: str] retain];
761         }
762       else if (CONSP (elt) &&
763                STRINGP (XCAR (elt)) &&
764                STRINGP (XCDR (elt)) &&
765                fast_string_match (XCAR (elt), f->name) >= 0)
766         {
767           image = [EmacsImage allocInitFromFile: XCDR (elt)];
768           if (image == nil)
769             image = [[NSImage imageNamed:
770                                [NSString stringWithUTF8String:
771                                             SSDATA (XCDR (elt))]] retain];
772         }
773     }
775   if (image == nil)
776     {
777       image = [[[NSWorkspace sharedWorkspace] iconForFileType: @"text"] retain];
778       setMini = NO;
779     }
781   [f->output_data.ns->miniimage release];
782   f->output_data.ns->miniimage = image;
783   [view setMiniwindowImage: setMini];
784   [pool release];
785   unblock_input ();
789 static void
790 x_set_icon_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
792   EmacsView *view = FRAME_NS_VIEW (f);
793   id image = nil;
794   BOOL setMini = YES;
796   NSTRACE (x_set_icon_type);
798   if (!NILP (arg) && SYMBOLP (arg))
799     {
800       arg =build_string (SSDATA (SYMBOL_NAME (arg)));
801       store_frame_param (f, Qicon_type, arg);
802     }
804   /* do it the implicit way */
805   if (NILP (arg))
806     {
807       ns_implicitly_set_icon_type (f);
808       return;
809     }
811   CHECK_STRING (arg);
813   image = [EmacsImage allocInitFromFile: arg];
814   if (image == nil)
815     image =[NSImage imageNamed: [NSString stringWithUTF8String:
816                                             SSDATA (arg)]];
818   if (image == nil)
819     {
820       image = [NSImage imageNamed: @"text"];
821       setMini = NO;
822     }
824   f->output_data.ns->miniimage = image;
825   [view setMiniwindowImage: setMini];
829 /* TODO: move to nsterm? */
831 ns_lisp_to_cursor_type (Lisp_Object arg)
833   char *str;
834   if (XTYPE (arg) == Lisp_String)
835     str = SSDATA (arg);
836   else if (XTYPE (arg) == Lisp_Symbol)
837     str = SSDATA (SYMBOL_NAME (arg));
838   else return -1;
839   if (!strcmp (str, "box"))     return FILLED_BOX_CURSOR;
840   if (!strcmp (str, "hollow"))  return HOLLOW_BOX_CURSOR;
841   if (!strcmp (str, "hbar"))    return HBAR_CURSOR;
842   if (!strcmp (str, "bar"))     return BAR_CURSOR;
843   if (!strcmp (str, "no"))      return NO_CURSOR;
844   return -1;
848 Lisp_Object
849 ns_cursor_type_to_lisp (int arg)
851   switch (arg)
852     {
853     case FILLED_BOX_CURSOR: return Qbox;
854     case HOLLOW_BOX_CURSOR: return intern ("hollow");
855     case HBAR_CURSOR:       return intern ("hbar");
856     case BAR_CURSOR:        return intern ("bar");
857     case NO_CURSOR:
858     default:                return intern ("no");
859     }
862 /* This is the same as the xfns.c definition.  */
863 static void
864 x_set_cursor_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
866   set_frame_cursor_types (f, arg);
869 /* called to set mouse pointer color, but all other terms use it to
870    initialize pointer types (and don't set the color ;) */
871 static void
872 x_set_mouse_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
874   /* don't think we can do this on Nextstep */
878 #define Str(x) #x
879 #define Xstr(x) Str(x)
881 static Lisp_Object
882 ns_appkit_version_str (void)
884   char tmp[80];
886 #ifdef NS_IMPL_GNUSTEP
887   sprintf(tmp, "gnustep-gui-%s", Xstr(GNUSTEP_GUI_VERSION));
888 #elif defined (NS_IMPL_COCOA)
889   sprintf(tmp, "apple-appkit-%.2f", NSAppKitVersionNumber);
890 #else
891   tmp = "ns-unknown";
892 #endif
893   return build_string (tmp);
897 /* This is for use by x-server-version and collapses all version info we
898    have into a single int.  For a better picture of the implementation
899    running, use ns_appkit_version_str.*/
900 static int
901 ns_appkit_version_int (void)
903 #ifdef NS_IMPL_GNUSTEP
904   return GNUSTEP_GUI_MAJOR_VERSION * 100 + GNUSTEP_GUI_MINOR_VERSION;
905 #elif defined (NS_IMPL_COCOA)
906   return (int)NSAppKitVersionNumber;
907 #endif
908   return 0;
912 static void
913 x_icon (struct frame *f, Lisp_Object parms)
914 /* --------------------------------------------------------------------------
915    Strangely-named function to set icon position parameters in frame.
916    This is irrelevant under OS X, but might be needed under GNUstep,
917    depending on the window manager used.  Note, this is not a standard
918    frame parameter-setter; it is called directly from x-create-frame.
919    -------------------------------------------------------------------------- */
921   Lisp_Object icon_x, icon_y;
922   struct ns_display_info *dpyinfo = check_ns_display_info (Qnil);
924   f->output_data.ns->icon_top = -1;
925   f->output_data.ns->icon_left = -1;
927   /* Set the position of the icon.  */
928   icon_x = x_get_arg (dpyinfo, parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
929   icon_y = x_get_arg (dpyinfo, parms, Qicon_top, 0, 0,  RES_TYPE_NUMBER);
930   if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
931     {
932       CHECK_NUMBER (icon_x);
933       CHECK_NUMBER (icon_y);
934       f->output_data.ns->icon_top = XINT (icon_y);
935       f->output_data.ns->icon_left = XINT (icon_x);
936     }
937   else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
938     error ("Both left and top icon corners of icon must be specified");
942 /* Note: see frame.c for template, also where generic functions are impl */
943 frame_parm_handler ns_frame_parm_handlers[] =
945   x_set_autoraise, /* generic OK */
946   x_set_autolower, /* generic OK */
947   x_set_background_color,
948   0, /* x_set_border_color,  may be impossible under Nextstep */
949   0, /* x_set_border_width,  may be impossible under Nextstep */
950   x_set_cursor_color,
951   x_set_cursor_type,
952   x_set_font, /* generic OK */
953   x_set_foreground_color,
954   x_set_icon_name,
955   x_set_icon_type,
956   x_set_internal_border_width, /* generic OK */
957   0, /* x_set_right_divider_width */
958   0, /* x_set_bottom_divider_width */
959   x_set_menu_bar_lines,
960   x_set_mouse_color,
961   x_explicitly_set_name,
962   x_set_scroll_bar_width, /* generic OK */
963   x_set_title,
964   x_set_unsplittable, /* generic OK */
965   x_set_vertical_scroll_bars, /* generic OK */
966   x_set_visibility, /* generic OK */
967   x_set_tool_bar_lines,
968   0, /* x_set_scroll_bar_foreground, will ignore (not possible on NS) */
969   0, /* x_set_scroll_bar_background,  will ignore (not possible on NS) */
970   x_set_screen_gamma, /* generic OK */
971   x_set_line_spacing, /* generic OK, sets f->extra_line_spacing to int */
972   x_set_fringe_width, /* generic OK */
973   x_set_fringe_width, /* generic OK */
974   0, /* x_set_wait_for_wm, will ignore */
975   x_set_fullscreen, /* generic OK */
976   x_set_font_backend, /* generic OK */
977   x_set_alpha,
978   0, /* x_set_sticky */
979   0, /* x_set_tool_bar_position */
983 /* Handler for signals raised during x_create_frame.
984    FRAME is the frame which is partially constructed.  */
986 static void
987 unwind_create_frame (Lisp_Object frame)
989   struct frame *f = XFRAME (frame);
991   /* If frame is already dead, nothing to do.  This can happen if the
992      display is disconnected after the frame has become official, but
993      before x_create_frame removes the unwind protect.  */
994   if (!FRAME_LIVE_P (f))
995     return;
997   /* If frame is ``official'', nothing to do.  */
998   if (NILP (Fmemq (frame, Vframe_list)))
999     {
1000 #if defined GLYPH_DEBUG && defined ENABLE_CHECKING
1001       struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1002 #endif
1004       x_free_frame_resources (f);
1005       free_glyphs (f);
1007 #ifdef GLYPH_DEBUG
1008       /* Check that reference counts are indeed correct.  */
1009       eassert (dpyinfo->terminal->image_cache->refcount == image_cache_refcount);
1010 #endif
1011     }
1015  * Read geometry related parameters from preferences if not in PARMS.
1016  * Returns the union of parms and any preferences read.
1017  */
1019 static Lisp_Object
1020 get_geometry_from_preferences (struct ns_display_info *dpyinfo,
1021                                Lisp_Object parms)
1023   struct {
1024     const char *val;
1025     const char *cls;
1026     Lisp_Object tem;
1027   } r[] = {
1028     { "width",  "Width", Qwidth },
1029     { "height", "Height", Qheight },
1030     { "left", "Left", Qleft },
1031     { "top", "Top", Qtop },
1032   };
1034   int i;
1035   for (i = 0; i < sizeof (r)/sizeof (r[0]); ++i)
1036     {
1037       if (NILP (Fassq (r[i].tem, parms)))
1038         {
1039           Lisp_Object value
1040             = x_get_arg (dpyinfo, parms, r[i].tem, r[i].val, r[i].cls,
1041                          RES_TYPE_NUMBER);
1042           if (! EQ (value, Qunbound))
1043             parms = Fcons (Fcons (r[i].tem, value), parms);
1044         }
1045     }
1047   return parms;
1050 /* ==========================================================================
1052     Lisp definitions
1054    ========================================================================== */
1056 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
1057        1, 1, 0,
1058        doc: /* Make a new Nextstep window, called a "frame" in Emacs terms.
1059 Return an Emacs frame object.
1060 PARMS is an alist of frame parameters.
1061 If the parameters specify that the frame should not have a minibuffer,
1062 and do not specify a specific minibuffer window to use,
1063 then `default-minibuffer-frame' must be a frame whose minibuffer can
1064 be shared by the new frame.
1066 This function is an internal primitive--use `make-frame' instead.  */)
1067      (Lisp_Object parms)
1069   struct frame *f;
1070   Lisp_Object frame, tem;
1071   Lisp_Object name;
1072   int minibuffer_only = 0;
1073   long window_prompting = 0;
1074   int width, height;
1075   ptrdiff_t count = specpdl_ptr - specpdl;
1076   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1077   Lisp_Object display;
1078   struct ns_display_info *dpyinfo = NULL;
1079   Lisp_Object parent;
1080   struct kboard *kb;
1081   static int desc_ctr = 1;
1083   /* x_get_arg modifies parms.  */
1084   parms = Fcopy_alist (parms);
1086   /* Use this general default value to start with
1087      until we know if this frame has a specified name.  */
1088   Vx_resource_name = Vinvocation_name;
1090   display = x_get_arg (dpyinfo, parms, Qterminal, 0, 0, RES_TYPE_STRING);
1091   if (EQ (display, Qunbound))
1092     display = Qnil;
1093   dpyinfo = check_ns_display_info (display);
1094   kb = dpyinfo->terminal->kboard;
1096   if (!dpyinfo->terminal->name)
1097     error ("Terminal is not live, can't create new frames on it");
1099   name = x_get_arg (dpyinfo, parms, Qname, 0, 0, RES_TYPE_STRING);
1100   if (!STRINGP (name)
1101       && ! EQ (name, Qunbound)
1102       && ! NILP (name))
1103     error ("Invalid frame name--not a string or nil");
1105   if (STRINGP (name))
1106     Vx_resource_name = name;
1108   parent = x_get_arg (dpyinfo, parms, Qparent_id, 0, 0, RES_TYPE_NUMBER);
1109   if (EQ (parent, Qunbound))
1110     parent = Qnil;
1111   if (! NILP (parent))
1112     CHECK_NUMBER (parent);
1114   /* make_frame_without_minibuffer can run Lisp code and garbage collect.  */
1115   /* No need to protect DISPLAY because that's not used after passing
1116      it to make_frame_without_minibuffer.  */
1117   frame = Qnil;
1118   GCPRO4 (parms, parent, name, frame);
1119   tem = x_get_arg (dpyinfo, parms, Qminibuffer, "minibuffer", "Minibuffer",
1120                   RES_TYPE_SYMBOL);
1121   if (EQ (tem, Qnone) || NILP (tem))
1122       f = make_frame_without_minibuffer (Qnil, kb, display);
1123   else if (EQ (tem, Qonly))
1124     {
1125       f = make_minibuffer_frame ();
1126       minibuffer_only = 1;
1127     }
1128   else if (WINDOWP (tem))
1129       f = make_frame_without_minibuffer (tem, kb, display);
1130   else
1131       f = make_frame (1);
1133   XSETFRAME (frame, f);
1135   f->terminal = dpyinfo->terminal;
1137   f->output_method = output_ns;
1138   f->output_data.ns = xzalloc (sizeof *f->output_data.ns);
1140   FRAME_FONTSET (f) = -1;
1142   fset_icon_name (f, x_get_arg (dpyinfo, parms, Qicon_name,
1143                                 "iconName", "Title",
1144                                 RES_TYPE_STRING));
1145   if (! STRINGP (f->icon_name))
1146     fset_icon_name (f, Qnil);
1148   FRAME_DISPLAY_INFO (f) = dpyinfo;
1150   /* With FRAME_DISPLAY_INFO set up, this unwind-protect is safe.  */
1151   record_unwind_protect (unwind_create_frame, frame);
1153   f->output_data.ns->window_desc = desc_ctr++;
1154   if (TYPE_RANGED_INTEGERP (Window, parent))
1155     {
1156       f->output_data.ns->parent_desc = XFASTINT (parent);
1157       f->output_data.ns->explicit_parent = 1;
1158     }
1159   else
1160     {
1161       f->output_data.ns->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
1162       f->output_data.ns->explicit_parent = 0;
1163     }
1165   /* Set the name; the functions to which we pass f expect the name to
1166      be set.  */
1167   if (EQ (name, Qunbound) || NILP (name) || ! STRINGP (name))
1168     {
1169       fset_name (f, build_string ([ns_app_name UTF8String]));
1170       f->explicit_name = 0;
1171     }
1172   else
1173     {
1174       fset_name (f, name);
1175       f->explicit_name = 1;
1176       specbind (Qx_resource_name, name);
1177     }
1179   block_input ();
1181 #ifdef NS_IMPL_COCOA
1182 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
1183   if (CTGetCoreTextVersion != NULL
1184       && CTGetCoreTextVersion () >= kCTVersionNumber10_5)
1185     mac_register_font_driver (f);
1186 #endif
1187 #endif
1188   register_font_driver (&nsfont_driver, f);
1190   x_default_parameter (f, parms, Qfont_backend, Qnil,
1191                         "fontBackend", "FontBackend", RES_TYPE_STRING);
1193   {
1194     /* use for default font name */
1195     id font = [NSFont userFixedPitchFontOfSize: -1.0]; /* default */
1196     x_default_parameter (f, parms, Qfontsize,
1197                                     make_number (0 /*(int)[font pointSize]*/),
1198                                     "fontSize", "FontSize", RES_TYPE_NUMBER);
1199     // Remove ' Regular', not handled by backends.
1200     char *fontname = xstrdup ([[font displayName] UTF8String]);
1201     int len = strlen (fontname);
1202     if (len > 8 && strcmp (fontname + len - 8, " Regular") == 0)
1203       fontname[len-8] = '\0';
1204     x_default_parameter (f, parms, Qfont,
1205                                  build_string (fontname),
1206                                  "font", "Font", RES_TYPE_STRING);
1207     xfree (fontname);
1208   }
1209   unblock_input ();
1211   x_default_parameter (f, parms, Qborder_width, make_number (0),
1212                        "borderwidth", "BorderWidth", RES_TYPE_NUMBER);
1213   x_default_parameter (f, parms, Qinternal_border_width, make_number (2),
1214                       "internalBorderWidth", "InternalBorderWidth",
1215                       RES_TYPE_NUMBER);
1217   /* default scrollbars on right on Mac */
1218   {
1219       Lisp_Object spos
1220 #ifdef NS_IMPL_GNUSTEP
1221           = Qt;
1222 #else
1223           = Qright;
1224 #endif
1225       x_default_parameter (f, parms, Qvertical_scroll_bars, spos,
1226                            "verticalScrollBars", "VerticalScrollBars",
1227                            RES_TYPE_SYMBOL);
1228   }
1229   x_default_parameter (f, parms, Qforeground_color, build_string ("Black"),
1230                       "foreground", "Foreground", RES_TYPE_STRING);
1231   x_default_parameter (f, parms, Qbackground_color, build_string ("White"),
1232                       "background", "Background", RES_TYPE_STRING);
1233   /* FIXME: not supported yet in Nextstep */
1234   x_default_parameter (f, parms, Qline_spacing, Qnil,
1235                        "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
1236   x_default_parameter (f, parms, Qleft_fringe, Qnil,
1237                        "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
1238   x_default_parameter (f, parms, Qright_fringe, Qnil,
1239                        "rightFringe", "RightFringe", RES_TYPE_NUMBER);
1241 #ifdef GLYPH_DEBUG
1242   image_cache_refcount =
1243     FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
1244 #endif
1246   init_frame_faces (f);
1248   /* Read comment about this code in corresponding place in xfns.c.  */
1249   width = FRAME_TEXT_WIDTH (f);
1250   height = FRAME_TEXT_HEIGHT (f);
1251   FRAME_TEXT_HEIGHT (f) = 0;
1252   SET_FRAME_WIDTH (f, 0);
1253   change_frame_size (f, width, height, 1, 0, 0, 1);
1255   /* The resources controlling the menu-bar and tool-bar are
1256      processed specially at startup, and reflected in the mode
1257      variables; ignore them here.  */
1258   x_default_parameter (f, parms, Qmenu_bar_lines,
1259                        NILP (Vmenu_bar_mode)
1260                        ? make_number (0) : make_number (1),
1261                        NULL, NULL, RES_TYPE_NUMBER);
1262   x_default_parameter (f, parms, Qtool_bar_lines,
1263                        NILP (Vtool_bar_mode)
1264                        ? make_number (0) : make_number (1),
1265                        NULL, NULL, RES_TYPE_NUMBER);
1267   x_default_parameter (f, parms, Qbuffer_predicate, Qnil, "bufferPredicate",
1268                        "BufferPredicate", RES_TYPE_SYMBOL);
1269   x_default_parameter (f, parms, Qtitle, Qnil, "title", "Title",
1270                        RES_TYPE_STRING);
1272   parms = get_geometry_from_preferences (dpyinfo, parms);
1273   window_prompting = x_figure_window_size (f, parms, 1);
1275   tem = x_get_arg (dpyinfo, parms, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
1276   f->no_split = minibuffer_only || (!EQ (tem, Qunbound) && !EQ (tem, Qnil));
1278   /* NOTE: on other terms, this is done in set_mouse_color, however this
1279      was not getting called under Nextstep */
1280   f->output_data.ns->text_cursor = [NSCursor IBeamCursor];
1281   f->output_data.ns->nontext_cursor = [NSCursor arrowCursor];
1282   f->output_data.ns->modeline_cursor = [NSCursor pointingHandCursor];
1283   f->output_data.ns->hand_cursor = [NSCursor pointingHandCursor];
1284   f->output_data.ns->hourglass_cursor = [NSCursor disappearingItemCursor];
1285   f->output_data.ns->horizontal_drag_cursor = [NSCursor resizeLeftRightCursor];
1286   f->output_data.ns->vertical_drag_cursor = [NSCursor resizeUpDownCursor];
1287   FRAME_DISPLAY_INFO (f)->vertical_scroll_bar_cursor
1288      = [NSCursor arrowCursor];
1289   f->output_data.ns->current_pointer = f->output_data.ns->text_cursor;
1291   [[EmacsView alloc] initFrameFromEmacs: f];
1293   x_icon (f, parms);
1295   /* ns_display_info does not have a reference_count.  */
1296   f->terminal->reference_count++;
1298   /* It is now ok to make the frame official even if we get an error below.
1299      The frame needs to be on Vframe_list or making it visible won't work. */
1300   Vframe_list = Fcons (frame, Vframe_list);
1302   x_default_parameter (f, parms, Qicon_type, Qnil,
1303                        "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
1305   x_default_parameter (f, parms, Qauto_raise, Qnil,
1306                        "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
1307   x_default_parameter (f, parms, Qauto_lower, Qnil,
1308                        "autoLower", "AutoLower", RES_TYPE_BOOLEAN);
1309   x_default_parameter (f, parms, Qcursor_type, Qbox,
1310                        "cursorType", "CursorType", RES_TYPE_SYMBOL);
1311   x_default_parameter (f, parms, Qscroll_bar_width, Qnil,
1312                        "scrollBarWidth", "ScrollBarWidth",
1313                        RES_TYPE_NUMBER);
1314   x_default_parameter (f, parms, Qalpha, Qnil,
1315                        "alpha", "Alpha", RES_TYPE_NUMBER);
1316   x_default_parameter (f, parms, Qfullscreen, Qnil,
1317                        "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
1319   width = FRAME_TEXT_WIDTH (f);
1320   height = FRAME_TEXT_HEIGHT (f);
1321   FRAME_TEXT_HEIGHT (f) = 0;
1322   SET_FRAME_WIDTH (f, 0);
1323   change_frame_size (f, width, height, 1, 0, 0, 1);
1325   if (! f->output_data.ns->explicit_parent)
1326     {
1327       Lisp_Object visibility;
1329       visibility = x_get_arg (dpyinfo, parms, Qvisibility, 0, 0,
1330                               RES_TYPE_SYMBOL);
1331       if (EQ (visibility, Qunbound))
1332         visibility = Qt;
1334       if (EQ (visibility, Qicon))
1335         x_iconify_frame (f);
1336       else if (! NILP (visibility))
1337         {
1338           x_make_frame_visible (f);
1339           [[FRAME_NS_VIEW (f) window] makeKeyWindow];
1340         }
1341       else
1342         {
1343           /* Must have been Qnil.  */
1344         }
1345     }
1347   if (FRAME_HAS_MINIBUF_P (f)
1348       && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
1349           || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
1350     kset_default_minibuffer_frame (kb, frame);
1352   /* All remaining specified parameters, which have not been "used"
1353      by x_get_arg and friends, now go in the misc. alist of the frame.  */
1354   for (tem = parms; CONSP (tem); tem = XCDR (tem))
1355     if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
1356       fset_param_alist (f, Fcons (XCAR (tem), f->param_alist));
1358   UNGCPRO;
1360   if (window_prompting & USPosition)
1361     x_set_offset (f, f->left_pos, f->top_pos, 1);
1363   /* Make sure windows on this frame appear in calls to next-window
1364      and similar functions.  */
1365   Vwindow_list = Qnil;
1367   return unbind_to (count, frame);
1370 void
1371 x_focus_frame (struct frame *f)
1373   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1375   if (dpyinfo->x_focus_frame != f)
1376     {
1377       EmacsView *view = FRAME_NS_VIEW (f);
1378       block_input ();
1379       [NSApp activateIgnoringOtherApps: YES];
1380       [[view window] makeKeyAndOrderFront: view];
1381       unblock_input ();
1382     }
1386 DEFUN ("ns-popup-font-panel", Fns_popup_font_panel, Sns_popup_font_panel,
1387        0, 1, "",
1388        doc: /* Pop up the font panel. */)
1389      (Lisp_Object frame)
1391   struct frame *f = decode_window_system_frame (frame);
1392   id fm = [NSFontManager sharedFontManager];
1393   struct font *font = f->output_data.ns->font;
1394   NSFont *nsfont;
1395   if (EQ (font->driver->type, Qns))
1396     nsfont = ((struct nsfont_info *)font)->nsfont;
1397 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
1398   else
1399     nsfont = (NSFont *) macfont_get_nsctfont (font);
1400 #endif
1401   [fm setSelectedFont: nsfont isMultiple: NO];
1402   [fm orderFrontFontPanel: NSApp];
1403   return Qnil;
1407 DEFUN ("ns-popup-color-panel", Fns_popup_color_panel, Sns_popup_color_panel,
1408        0, 1, "",
1409        doc: /* Pop up the color panel.  */)
1410      (Lisp_Object frame)
1412   check_window_system (NULL);
1413   [NSApp orderFrontColorPanel: NSApp];
1414   return Qnil;
1417 static struct
1419   id panel;
1420   BOOL ret;
1421 #if ! defined (NS_IMPL_COCOA) || \
1422   MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
1423   NSString *dirS, *initS;
1424   BOOL no_types;
1425 #endif
1426 } ns_fd_data;
1428 void
1429 ns_run_file_dialog (void)
1431   if (ns_fd_data.panel == nil) return;
1432 #if defined (NS_IMPL_COCOA) && \
1433   MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
1434   ns_fd_data.ret = [ns_fd_data.panel runModal];
1435 #else
1436   if (ns_fd_data.no_types)
1437     {
1438       ns_fd_data.ret = [ns_fd_data.panel
1439                            runModalForDirectory: ns_fd_data.dirS
1440                            file: ns_fd_data.initS];
1441     }
1442   else
1443     {
1444       ns_fd_data.ret = [ns_fd_data.panel
1445                            runModalForDirectory: ns_fd_data.dirS
1446                            file: ns_fd_data.initS
1447                            types: nil];
1448     }
1449 #endif
1450   ns_fd_data.panel = nil;
1453 DEFUN ("ns-read-file-name", Fns_read_file_name, Sns_read_file_name, 1, 5, 0,
1454        doc: /* Use a graphical panel to read a file name, using prompt PROMPT.
1455 Optional arg DIR, if non-nil, supplies a default directory.
1456 Optional arg MUSTMATCH, if non-nil, means the returned file or
1457 directory must exist.
1458 Optional arg INIT, if non-nil, provides a default file name to use.
1459 Optional arg DIR_ONLY_P, if non-nil, means choose only directories.  */)
1460   (Lisp_Object prompt, Lisp_Object dir, Lisp_Object mustmatch,
1461    Lisp_Object init, Lisp_Object dir_only_p)
1463   static id fileDelegate = nil;
1464   BOOL ret;
1465   BOOL isSave = NILP (mustmatch) && NILP (dir_only_p);
1466   id panel;
1467   Lisp_Object fname;
1469   NSString *promptS = NILP (prompt) || !STRINGP (prompt) ? nil :
1470     [NSString stringWithUTF8String: SSDATA (prompt)];
1471   NSString *dirS = NILP (dir) || !STRINGP (dir) ?
1472     [NSString stringWithUTF8String: SSDATA (BVAR (current_buffer, directory))] :
1473     [NSString stringWithUTF8String: SSDATA (dir)];
1474   NSString *initS = NILP (init) || !STRINGP (init) ? nil :
1475     [NSString stringWithUTF8String: SSDATA (init)];
1476   NSEvent *nxev;
1478   check_window_system (NULL);
1480   if (fileDelegate == nil)
1481     fileDelegate = [EmacsFileDelegate new];
1483   [NSCursor setHiddenUntilMouseMoves: NO];
1485   if ([dirS characterAtIndex: 0] == '~')
1486     dirS = [dirS stringByExpandingTildeInPath];
1488   panel = isSave ?
1489     (id)[EmacsSavePanel savePanel] : (id)[EmacsOpenPanel openPanel];
1491   [panel setTitle: promptS];
1493   [panel setAllowsOtherFileTypes: YES];
1494   [panel setTreatsFilePackagesAsDirectories: YES];
1495   [panel setDelegate: fileDelegate];
1497   if (! NILP (dir_only_p))
1498     {
1499       [panel setCanChooseDirectories: YES];
1500       [panel setCanChooseFiles: NO];
1501     }
1502   else if (! isSave)
1503     {
1504       /* This is not quite what the documentation says, but it is compatible
1505          with the Gtk+ code.  Also, the menu entry says "Open File...".  */
1506       [panel setCanChooseDirectories: NO];
1507       [panel setCanChooseFiles: YES];
1508     }
1510   block_input ();
1511   ns_fd_data.panel = panel;
1512   ns_fd_data.ret = NO;
1513 #if defined (NS_IMPL_COCOA) && \
1514   MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
1515   if (! NILP (mustmatch) || ! NILP (dir_only_p))
1516     [panel setAllowedFileTypes: nil];
1517   if (dirS) [panel setDirectoryURL: [NSURL fileURLWithPath: dirS]];
1518   if (initS && NILP (Ffile_directory_p (init)))
1519     [panel setNameFieldStringValue: [initS lastPathComponent]];
1520   else
1521     [panel setNameFieldStringValue: @""];
1523 #else
1524   ns_fd_data.no_types = NILP (mustmatch) && NILP (dir_only_p);
1525   ns_fd_data.dirS = dirS;
1526   ns_fd_data.initS = initS;
1527 #endif
1529   /* runModalForDirectory/runModal restarts the main event loop when done,
1530      so we must start an event loop and then pop up the file dialog.
1531      The file dialog may pop up a confirm dialog after Ok has been pressed,
1532      so we can not simply pop down on the Ok/Cancel press.
1533    */
1534   nxev = [NSEvent otherEventWithType: NSApplicationDefined
1535                             location: NSMakePoint (0, 0)
1536                        modifierFlags: 0
1537                            timestamp: 0
1538                         windowNumber: [[NSApp mainWindow] windowNumber]
1539                              context: [NSApp context]
1540                              subtype: 0
1541                                data1: 0
1542                                data2: NSAPP_DATA2_RUNFILEDIALOG];
1544   [NSApp postEvent: nxev atStart: NO];
1545   while (ns_fd_data.panel != nil)
1546     [NSApp run];
1548   ret = (ns_fd_data.ret == NSOKButton);
1550   if (ret)
1551     {
1552       NSString *str = ns_filename_from_panel (panel);
1553       if (! str) str = ns_directory_from_panel (panel);
1554       if (! str) ret = NO;
1555       else fname = build_string ([str UTF8String]);
1556     }
1558   [[FRAME_NS_VIEW (SELECTED_FRAME ()) window] makeKeyWindow];
1559   unblock_input ();
1561   return ret ? fname : Qnil;
1564 const char *
1565 ns_get_defaults_value (const char *key)
1567   NSObject *obj = [[NSUserDefaults standardUserDefaults]
1568                     objectForKey: [NSString stringWithUTF8String: key]];
1570   if (!obj) return NULL;
1572   return [[NSString stringWithFormat: @"%@", obj] UTF8String];
1576 DEFUN ("ns-get-resource", Fns_get_resource, Sns_get_resource, 2, 2, 0,
1577        doc: /* Return the value of the property NAME of OWNER from the defaults database.
1578 If OWNER is nil, Emacs is assumed.  */)
1579      (Lisp_Object owner, Lisp_Object name)
1581   const char *value;
1583   check_window_system (NULL);
1584   if (NILP (owner))
1585     owner = build_string([ns_app_name UTF8String]);
1586   CHECK_STRING (name);
1588   value = ns_get_defaults_value (SSDATA (name));
1590   if (value)
1591     return build_string (value);
1592   return Qnil;
1596 DEFUN ("ns-set-resource", Fns_set_resource, Sns_set_resource, 3, 3, 0,
1597        doc: /* Set property NAME of OWNER to VALUE, from the defaults database.
1598 If OWNER is nil, Emacs is assumed.
1599 If VALUE is nil, the default is removed.  */)
1600      (Lisp_Object owner, Lisp_Object name, Lisp_Object value)
1602   check_window_system (NULL);
1603   if (NILP (owner))
1604     owner = build_string ([ns_app_name UTF8String]);
1605   CHECK_STRING (name);
1606   if (NILP (value))
1607     {
1608       [[NSUserDefaults standardUserDefaults] removeObjectForKey:
1609                          [NSString stringWithUTF8String: SSDATA (name)]];
1610     }
1611   else
1612     {
1613       CHECK_STRING (value);
1614       [[NSUserDefaults standardUserDefaults] setObject:
1615                 [NSString stringWithUTF8String: SSDATA (value)]
1616                                         forKey: [NSString stringWithUTF8String:
1617                                                          SSDATA (name)]];
1618     }
1620   return Qnil;
1624 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
1625        Sx_server_max_request_size,
1626        0, 1, 0,
1627        doc: /* This function is a no-op.  It is only present for completeness.  */)
1628      (Lisp_Object terminal)
1630   check_ns_display_info (terminal);
1631   /* This function has no real equivalent under NeXTstep.  Return nil to
1632      indicate this. */
1633   return Qnil;
1637 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
1638        doc: /* Return the "vendor ID" string of Nextstep display server TERMINAL.
1639 \(Labeling every distributor as a "vendor" embodies the false assumption
1640 that operating systems cannot be developed and distributed noncommercially.)
1641 The optional argument TERMINAL specifies which display to ask about.
1642 TERMINAL should be a terminal object, a frame or a display name (a string).
1643 If omitted or nil, that stands for the selected frame's display.  */)
1644   (Lisp_Object terminal)
1646   check_ns_display_info (terminal);
1647 #ifdef NS_IMPL_GNUSTEP
1648   return build_string ("GNU");
1649 #else
1650   return build_string ("Apple");
1651 #endif
1655 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
1656        doc: /* Return the version numbers of the server of display TERMINAL.
1657 The value is a list of three integers: the major and minor
1658 version numbers of the X Protocol in use, and the distributor-specific release
1659 number.  See also the function `x-server-vendor'.
1661 The optional argument TERMINAL specifies which display to ask about.
1662 TERMINAL should be a terminal object, a frame or a display name (a string).
1663 If omitted or nil, that stands for the selected frame's display.  */)
1664   (Lisp_Object terminal)
1666   check_ns_display_info (terminal);
1667   /*NOTE: it is unclear what would best correspond with "protocol";
1668           we return 10.3, meaning Panther, since this is roughly the
1669           level that GNUstep's APIs correspond to.
1670           The last number is where we distinguish between the Apple
1671           and GNUstep implementations ("distributor-specific release
1672           number") and give int'ized versions of major.minor. */
1673   return list3i (10, 3, ns_appkit_version_int ());
1677 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
1678        doc: /* Return the number of screens on Nextstep display server TERMINAL.
1679 The optional argument TERMINAL specifies which display to ask about.
1680 TERMINAL should be a terminal object, a frame or a display name (a string).
1681 If omitted or nil, that stands for the selected frame's display.
1683 Note: "screen" here is not in Nextstep terminology but in X11's.  For
1684 the number of physical monitors, use `(length
1685 (display-monitor-attributes-list TERMINAL))' instead.  */)
1686   (Lisp_Object terminal)
1688   check_ns_display_info (terminal);
1689   return make_number (1);
1693 DEFUN ("x-display-mm-height", Fx_display_mm_height, Sx_display_mm_height, 0, 1, 0,
1694        doc: /* Return the height in millimeters of the Nextstep display TERMINAL.
1695 The optional argument TERMINAL specifies which display to ask about.
1696 TERMINAL should be a terminal object, a frame or a display name (a string).
1697 If omitted or nil, that stands for the selected frame's display.
1699 On \"multi-monitor\" setups this refers to the height in millimeters for
1700 all physical monitors associated with TERMINAL.  To get information
1701 for each physical monitor, use `display-monitor-attributes-list'.  */)
1702   (Lisp_Object terminal)
1704   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
1706   return make_number (x_display_pixel_height (dpyinfo) / (92.0/25.4));
1710 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
1711        doc: /* Return the width in millimeters of the Nextstep display TERMINAL.
1712 The optional argument TERMINAL specifies which display to ask about.
1713 TERMINAL should be a terminal object, a frame or a display name (a string).
1714 If omitted or nil, that stands for the selected frame's display.
1716 On \"multi-monitor\" setups this refers to the width in millimeters for
1717 all physical monitors associated with TERMINAL.  To get information
1718 for each physical monitor, use `display-monitor-attributes-list'.  */)
1719   (Lisp_Object terminal)
1721   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
1723   return make_number (x_display_pixel_width (dpyinfo) / (92.0/25.4));
1727 DEFUN ("x-display-backing-store", Fx_display_backing_store,
1728        Sx_display_backing_store, 0, 1, 0,
1729        doc: /* Return an indication of whether the Nextstep display TERMINAL does backing store.
1730 The value may be `buffered', `retained', or `non-retained'.
1731 The optional argument TERMINAL specifies which display to ask about.
1732 TERMINAL should be a terminal object, a frame or a display name (a string).
1733 If omitted or nil, that stands for the selected frame's display.  */)
1734   (Lisp_Object terminal)
1736   check_ns_display_info (terminal);
1737   switch ([ns_get_window (terminal) backingType])
1738     {
1739     case NSBackingStoreBuffered:
1740       return intern ("buffered");
1741     case NSBackingStoreRetained:
1742       return intern ("retained");
1743     case NSBackingStoreNonretained:
1744       return intern ("non-retained");
1745     default:
1746       error ("Strange value for backingType parameter of frame");
1747     }
1748   return Qnil;  /* not reached, shut compiler up */
1752 DEFUN ("x-display-visual-class", Fx_display_visual_class,
1753        Sx_display_visual_class, 0, 1, 0,
1754        doc: /* Return the visual class of the Nextstep display TERMINAL.
1755 The value is one of the symbols `static-gray', `gray-scale',
1756 `static-color', `pseudo-color', `true-color', or `direct-color'.
1758 The optional argument TERMINAL specifies which display to ask about.
1759 TERMINAL should a terminal object, a frame or a display name (a string).
1760 If omitted or nil, that stands for the selected frame's display.  */)
1761   (Lisp_Object terminal)
1763   NSWindowDepth depth;
1765   check_ns_display_info (terminal);
1766   depth = [[[NSScreen screens] objectAtIndex:0] depth];
1768   if ( depth == NSBestDepth (NSCalibratedWhiteColorSpace, 2, 2, YES, NULL))
1769     return intern ("static-gray");
1770   else if (depth == NSBestDepth (NSCalibratedWhiteColorSpace, 8, 8, YES, NULL))
1771     return intern ("gray-scale");
1772   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 8, 8, YES, NULL))
1773     return intern ("pseudo-color");
1774   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 4, 12, NO, NULL))
1775     return intern ("true-color");
1776   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 8, 24, NO, NULL))
1777     return intern ("direct-color");
1778   else
1779     /* color mgmt as far as we do it is really handled by Nextstep itself anyway */
1780     return intern ("direct-color");
1784 DEFUN ("x-display-save-under", Fx_display_save_under,
1785        Sx_display_save_under, 0, 1, 0,
1786        doc: /* Return t if TERMINAL supports the save-under feature.
1787 The optional argument TERMINAL specifies which display to ask about.
1788 TERMINAL should be a terminal object, a frame or a display name (a string).
1789 If omitted or nil, that stands for the selected frame's display.  */)
1790   (Lisp_Object terminal)
1792   check_ns_display_info (terminal);
1793   switch ([ns_get_window (terminal) backingType])
1794     {
1795     case NSBackingStoreBuffered:
1796       return Qt;
1798     case NSBackingStoreRetained:
1799     case NSBackingStoreNonretained:
1800       return Qnil;
1802     default:
1803       error ("Strange value for backingType parameter of frame");
1804     }
1805   return Qnil;  /* not reached, shut compiler up */
1809 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
1810        1, 3, 0,
1811        doc: /* Open a connection to a display server.
1812 DISPLAY is the name of the display to connect to.
1813 Optional second arg XRM-STRING is a string of resources in xrdb format.
1814 If the optional third arg MUST-SUCCEED is non-nil,
1815 terminate Emacs if we can't open the connection.
1816 \(In the Nextstep version, the last two arguments are currently ignored.)  */)
1817      (Lisp_Object display, Lisp_Object resource_string, Lisp_Object must_succeed)
1819   struct ns_display_info *dpyinfo;
1821   CHECK_STRING (display);
1823   nxatoms_of_nsselect ();
1824   dpyinfo = ns_term_init (display);
1825   if (dpyinfo == 0)
1826     {
1827       if (!NILP (must_succeed))
1828         fatal ("Display on %s not responding.\n",
1829                SSDATA (display));
1830       else
1831         error ("Display on %s not responding.\n",
1832                SSDATA (display));
1833     }
1835   return Qnil;
1839 DEFUN ("x-close-connection", Fx_close_connection, Sx_close_connection,
1840        1, 1, 0,
1841        doc: /* Close the connection to TERMINAL's Nextstep display server.
1842 For TERMINAL, specify a terminal object, a frame or a display name (a
1843 string).  If TERMINAL is nil, that stands for the selected frame's
1844 terminal.  */)
1845      (Lisp_Object terminal)
1847   check_ns_display_info (terminal);
1848   [NSApp terminate: NSApp];
1849   return Qnil;
1853 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
1854        doc: /* Return the list of display names that Emacs has connections to.  */)
1855      (void)
1857   Lisp_Object result = Qnil;
1858   struct ns_display_info *ndi;
1860   for (ndi = x_display_list; ndi; ndi = ndi->next)
1861     result = Fcons (XCAR (ndi->name_list_element), result);
1863   return result;
1867 DEFUN ("ns-hide-others", Fns_hide_others, Sns_hide_others,
1868        0, 0, 0,
1869        doc: /* Hides all applications other than Emacs.  */)
1870      (void)
1872   check_window_system (NULL);
1873   [NSApp hideOtherApplications: NSApp];
1874   return Qnil;
1877 DEFUN ("ns-hide-emacs", Fns_hide_emacs, Sns_hide_emacs,
1878        1, 1, 0,
1879        doc: /* If ON is non-nil, the entire Emacs application is hidden.
1880 Otherwise if Emacs is hidden, it is unhidden.
1881 If ON is equal to `activate', Emacs is unhidden and becomes
1882 the active application.  */)
1883      (Lisp_Object on)
1885   check_window_system (NULL);
1886   if (EQ (on, intern ("activate")))
1887     {
1888       [NSApp unhide: NSApp];
1889       [NSApp activateIgnoringOtherApps: YES];
1890     }
1891   else if (NILP (on))
1892     [NSApp unhide: NSApp];
1893   else
1894     [NSApp hide: NSApp];
1895   return Qnil;
1899 DEFUN ("ns-emacs-info-panel", Fns_emacs_info_panel, Sns_emacs_info_panel,
1900        0, 0, 0,
1901        doc: /* Shows the 'Info' or 'About' panel for Emacs.  */)
1902      (void)
1904   check_window_system (NULL);
1905   [NSApp orderFrontStandardAboutPanel: nil];
1906   return Qnil;
1910 DEFUN ("ns-font-name", Fns_font_name, Sns_font_name, 1, 1, 0,
1911        doc: /* Determine font PostScript or family name for font NAME.
1912 NAME should be a string containing either the font name or an XLFD
1913 font descriptor.  If string contains `fontset' and not
1914 `fontset-startup', it is left alone. */)
1915      (Lisp_Object name)
1917   char *nm;
1918   CHECK_STRING (name);
1919   nm = SSDATA (name);
1921   if (nm[0] != '-')
1922     return name;
1923   if (strstr (nm, "fontset") && !strstr (nm, "fontset-startup"))
1924     return name;
1926   return build_string (ns_xlfd_to_fontname (SSDATA (name)));
1930 DEFUN ("ns-list-colors", Fns_list_colors, Sns_list_colors, 0, 1, 0,
1931        doc: /* Return a list of all available colors.
1932 The optional argument FRAME is currently ignored.  */)
1933      (Lisp_Object frame)
1935   Lisp_Object list = Qnil;
1936   NSEnumerator *colorlists;
1937   NSColorList *clist;
1939   if (!NILP (frame))
1940     {
1941       CHECK_FRAME (frame);
1942       if (! FRAME_NS_P (XFRAME (frame)))
1943         error ("non-Nextstep frame used in `ns-list-colors'");
1944     }
1946   block_input ();
1948   colorlists = [[NSColorList availableColorLists] objectEnumerator];
1949   while ((clist = [colorlists nextObject]))
1950     {
1951       if ([[clist name] length] < 7 ||
1952           [[clist name] rangeOfString: @"PANTONE"].location == 0)
1953         {
1954           NSEnumerator *cnames = [[clist allKeys] reverseObjectEnumerator];
1955           NSString *cname;
1956           while ((cname = [cnames nextObject]))
1957             list = Fcons (build_string ([cname UTF8String]), list);
1958 /*           for (i = [[clist allKeys] count] - 1; i >= 0; i--)
1959                list = Fcons (build_string ([[[clist allKeys] objectAtIndex: i]
1960                                              UTF8String]), list); */
1961         }
1962     }
1964   unblock_input ();
1966   return list;
1970 DEFUN ("ns-list-services", Fns_list_services, Sns_list_services, 0, 0, 0,
1971        doc: /* List available Nextstep services by querying NSApp.  */)
1972      (void)
1974 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
1975   /* You can't get services like this in 10.6+.  */
1976   return Qnil;
1977 #else
1978   Lisp_Object ret = Qnil;
1979   NSMenu *svcs;
1980 #ifdef NS_IMPL_COCOA
1981   id delegate;
1982 #endif
1984   check_window_system (NULL);
1985   svcs = [[NSMenu alloc] initWithTitle: @"Services"];
1986   [NSApp setServicesMenu: svcs];
1987   [NSApp registerServicesMenuSendTypes: ns_send_types
1988                            returnTypes: ns_return_types];
1990 /* On Tiger, services menu updating was made lazier (waits for user to
1991    actually click on the menu), so we have to force things along: */
1992 #ifdef NS_IMPL_COCOA
1993   delegate = [svcs delegate];
1994   if (delegate != nil)
1995     {
1996       if ([delegate respondsToSelector: @selector (menuNeedsUpdate:)])
1997         [delegate menuNeedsUpdate: svcs];
1998       if ([delegate respondsToSelector:
1999                        @selector (menu:updateItem:atIndex:shouldCancel:)])
2000         {
2001           int i, len = [delegate numberOfItemsInMenu: svcs];
2002           for (i =0; i<len; i++)
2003             [svcs addItemWithTitle: @"" action: NULL keyEquivalent: @""];
2004           for (i =0; i<len; i++)
2005             if (![delegate menu: svcs
2006                      updateItem: (NSMenuItem *)[svcs itemAtIndex: i]
2007                         atIndex: i shouldCancel: NO])
2008               break;
2009         }
2010     }
2011 #endif
2013   [svcs setAutoenablesItems: NO];
2014 #ifdef NS_IMPL_COCOA
2015   [svcs update]; /* on OS X, converts from '/' structure */
2016 #endif
2018   ret = interpret_services_menu (svcs, Qnil, ret);
2019   return ret;
2020 #endif
2024 DEFUN ("ns-perform-service", Fns_perform_service, Sns_perform_service,
2025        2, 2, 0,
2026        doc: /* Perform Nextstep SERVICE on SEND.
2027 SEND should be either a string or nil.
2028 The return value is the result of the service, as string, or nil if
2029 there was no result.  */)
2030      (Lisp_Object service, Lisp_Object send)
2032   id pb;
2033   NSString *svcName;
2034   char *utfStr;
2036   CHECK_STRING (service);
2037   check_window_system (NULL);
2039   utfStr = SSDATA (service);
2040   svcName = [NSString stringWithUTF8String: utfStr];
2042   pb =[NSPasteboard pasteboardWithUniqueName];
2043   ns_string_to_pasteboard (pb, send);
2045   if (NSPerformService (svcName, pb) == NO)
2046     Fsignal (Qquit, list1 (build_string ("service not available")));
2048   if ([[pb types] count] == 0)
2049     return build_string ("");
2050   return ns_string_from_pasteboard (pb);
2054 DEFUN ("ns-convert-utf8-nfd-to-nfc", Fns_convert_utf8_nfd_to_nfc,
2055        Sns_convert_utf8_nfd_to_nfc, 1, 1, 0,
2056        doc: /* Return an NFC string that matches the UTF-8 NFD string STR.  */)
2057      (Lisp_Object str)
2059 /* TODO: If GNUstep ever implements precomposedStringWithCanonicalMapping,
2060          remove this. */
2061   NSString *utfStr;
2062   Lisp_Object ret = Qnil;
2063   NSAutoreleasePool *pool;
2065   CHECK_STRING (str);
2066   pool = [[NSAutoreleasePool alloc] init];
2067   utfStr = [NSString stringWithUTF8String: SSDATA (str)];
2068 #ifdef NS_IMPL_COCOA
2069   if (utfStr)
2070     utfStr = [utfStr precomposedStringWithCanonicalMapping];
2071 #endif
2072   if (utfStr)
2073     {
2074       const char *cstr = [utfStr UTF8String];
2075       if (cstr)
2076         ret = build_string (cstr);
2077     }
2079   [pool release];
2080   if (NILP (ret))
2081     error ("Invalid UTF-8");
2083   return ret;
2087 #ifdef NS_IMPL_COCOA
2089 /* Compile and execute the AppleScript SCRIPT and return the error
2090    status as function value.  A zero is returned if compilation and
2091    execution is successful, in which case *RESULT is set to a Lisp
2092    string or a number containing the resulting script value.  Otherwise,
2093    1 is returned. */
2094 static int
2095 ns_do_applescript (Lisp_Object script, Lisp_Object *result)
2097   NSAppleEventDescriptor *desc;
2098   NSDictionary* errorDict;
2099   NSAppleEventDescriptor* returnDescriptor = NULL;
2101   NSAppleScript* scriptObject =
2102     [[NSAppleScript alloc] initWithSource:
2103                              [NSString stringWithUTF8String: SSDATA (script)]];
2105   returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
2106   [scriptObject release];
2108   *result = Qnil;
2110   if (returnDescriptor != NULL)
2111     {
2112       // successful execution
2113       if (kAENullEvent != [returnDescriptor descriptorType])
2114         {
2115           *result = Qt;
2116           // script returned an AppleScript result
2117           if ((typeUnicodeText == [returnDescriptor descriptorType]) ||
2118 #if defined (NS_IMPL_COCOA)
2119               (typeUTF16ExternalRepresentation
2120                == [returnDescriptor descriptorType]) ||
2121 #endif
2122               (typeUTF8Text == [returnDescriptor descriptorType]) ||
2123               (typeCString == [returnDescriptor descriptorType]))
2124             {
2125               desc = [returnDescriptor coerceToDescriptorType: typeUTF8Text];
2126               if (desc)
2127                 *result = build_string([[desc stringValue] UTF8String]);
2128             }
2129           else
2130             {
2131               /* use typeUTF16ExternalRepresentation? */
2132               // coerce the result to the appropriate ObjC type
2133               desc = [returnDescriptor coerceToDescriptorType: typeUTF8Text];
2134               if (desc)
2135                 *result = make_number([desc int32Value]);
2136             }
2137         }
2138     }
2139   else
2140     {
2141       // no script result, return error
2142       return 1;
2143     }
2144   return 0;
2147 /* Helper function called from sendEvent to run applescript
2148    from within the main event loop.  */
2150 void
2151 ns_run_ascript (void)
2153   if (! NILP (as_script))
2154     as_status = ns_do_applescript (as_script, as_result);
2155   as_script = Qnil;
2158 DEFUN ("ns-do-applescript", Fns_do_applescript, Sns_do_applescript, 1, 1, 0,
2159        doc: /* Execute AppleScript SCRIPT and return the result.
2160 If compilation and execution are successful, the resulting script value
2161 is returned as a string, a number or, in the case of other constructs, t.
2162 In case the execution fails, an error is signaled. */)
2163      (Lisp_Object script)
2165   Lisp_Object result;
2166   int status;
2167   NSEvent *nxev;
2169   CHECK_STRING (script);
2170   check_window_system (NULL);
2172   block_input ();
2174   as_script = script;
2175   as_result = &result;
2177   /* executing apple script requires the event loop to run, otherwise
2178      errors aren't returned and executeAndReturnError hangs forever.
2179      Post an event that runs applescript and then start the event loop.
2180      The event loop is exited when the script is done.  */
2181   nxev = [NSEvent otherEventWithType: NSApplicationDefined
2182                             location: NSMakePoint (0, 0)
2183                        modifierFlags: 0
2184                            timestamp: 0
2185                         windowNumber: [[NSApp mainWindow] windowNumber]
2186                              context: [NSApp context]
2187                              subtype: 0
2188                                data1: 0
2189                                data2: NSAPP_DATA2_RUNASSCRIPT];
2191   [NSApp postEvent: nxev atStart: NO];
2193   // If there are other events, the event loop may exit.  Keep running
2194   // until the script has been handled.  */
2195   while (! NILP (as_script))
2196     [NSApp run];
2198   status = as_status;
2199   as_status = 0;
2200   as_result = 0;
2201   unblock_input ();
2202   if (status == 0)
2203     return result;
2204   else if (!STRINGP (result))
2205     error ("AppleScript error %d", status);
2206   else
2207     error ("%s", SSDATA (result));
2209 #endif
2213 /* ==========================================================================
2215     Miscellaneous functions not called through hooks
2217    ========================================================================== */
2219 /* called from frame.c */
2220 struct ns_display_info *
2221 check_x_display_info (Lisp_Object frame)
2223   return check_ns_display_info (frame);
2227 void
2228 x_set_scroll_bar_default_width (struct frame *f)
2230   int wid = FRAME_COLUMN_WIDTH (f);
2231   FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = NS_SCROLL_BAR_WIDTH_DEFAULT;
2232   FRAME_CONFIG_SCROLL_BAR_COLS (f) = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) +
2233                                       wid - 1) / wid;
2236 /* terms impl this instead of x-get-resource directly */
2237 char *
2238 x_get_string_resource (XrmDatabase rdb, const char *name, const char *class)
2240   /* remove appname prefix; TODO: allow for !="Emacs" */
2241   const char *res, *toCheck = class + (!strncmp (class, "Emacs.", 6) ? 6 : 0);
2243   check_window_system (NULL);
2245   if (inhibit_x_resources)
2246     /* --quick was passed, so this is a no-op.  */
2247     return NULL;
2249   res = ns_get_defaults_value (toCheck);
2250   return (!res ? NULL :
2251           (!c_strncasecmp (res, "YES", 3) ? "true" :
2252            (!c_strncasecmp (res, "NO", 2) ? "false" : (char *) res)));
2256 Lisp_Object
2257 x_get_focus_frame (struct frame *frame)
2259   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
2260   Lisp_Object nsfocus;
2262   if (!dpyinfo->x_focus_frame)
2263     return Qnil;
2265   XSETFRAME (nsfocus, dpyinfo->x_focus_frame);
2266   return nsfocus;
2269 /* ==========================================================================
2271     Lisp definitions that, for whatever reason, we can't alias as 'ns-XXX'.
2273    ========================================================================== */
2276 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
2277        doc: /* Internal function called by `color-defined-p', which see.
2278 \(Note that the Nextstep version of this function ignores FRAME.)  */)
2279      (Lisp_Object color, Lisp_Object frame)
2281   NSColor * col;
2282   check_window_system (NULL);
2283   return ns_lisp_to_color (color, &col) ? Qnil : Qt;
2287 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
2288        doc: /* Internal function called by `color-values', which see.  */)
2289      (Lisp_Object color, Lisp_Object frame)
2291   NSColor * col;
2292   EmacsCGFloat red, green, blue, alpha;
2294   check_window_system (NULL);
2295   CHECK_STRING (color);
2297   if (ns_lisp_to_color (color, &col))
2298     return Qnil;
2300   [[col colorUsingDefaultColorSpace]
2301         getRed: &red green: &green blue: &blue alpha: &alpha];
2302   return list3i (lrint (red * 65280), lrint (green * 65280),
2303                  lrint (blue * 65280));
2307 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
2308        doc: /* Internal function called by `display-color-p', which see.  */)
2309      (Lisp_Object terminal)
2311   NSWindowDepth depth;
2312   NSString *colorSpace;
2314   check_ns_display_info (terminal);
2315   depth = [[[NSScreen screens] objectAtIndex:0] depth];
2316   colorSpace = NSColorSpaceFromDepth (depth);
2318   return    [colorSpace isEqualToString: NSDeviceWhiteColorSpace]
2319          || [colorSpace isEqualToString: NSCalibratedWhiteColorSpace]
2320       ? Qnil : Qt;
2324 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p, Sx_display_grayscale_p,
2325        0, 1, 0,
2326        doc: /* Return t if the Nextstep display supports shades of gray.
2327 Note that color displays do support shades of gray.
2328 The optional argument TERMINAL specifies which display to ask about.
2329 TERMINAL should be a terminal object, a frame or a display name (a string).
2330 If omitted or nil, that stands for the selected frame's display.  */)
2331   (Lisp_Object terminal)
2333   NSWindowDepth depth;
2335   check_ns_display_info (terminal);
2336   depth = [[[NSScreen screens] objectAtIndex:0] depth];
2338   return NSBitsPerPixelFromDepth (depth) > 1 ? Qt : Qnil;
2342 DEFUN ("x-display-pixel-width", Fx_display_pixel_width, Sx_display_pixel_width,
2343        0, 1, 0,
2344        doc: /* Return the width in pixels of the Nextstep display TERMINAL.
2345 The optional argument TERMINAL specifies which display to ask about.
2346 TERMINAL should be a terminal object, a frame or a display name (a string).
2347 If omitted or nil, that stands for the selected frame's display.
2349 On \"multi-monitor\" setups this refers to the pixel width for all
2350 physical monitors associated with TERMINAL.  To get information for
2351 each physical monitor, use `display-monitor-attributes-list'.  */)
2352   (Lisp_Object terminal)
2354   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
2356   return make_number (x_display_pixel_width (dpyinfo));
2360 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
2361        Sx_display_pixel_height, 0, 1, 0,
2362        doc: /* Return the height in pixels of the Nextstep display TERMINAL.
2363 The optional argument TERMINAL specifies which display to ask about.
2364 TERMINAL should be a terminal object, a frame or a display name (a string).
2365 If omitted or nil, that stands for the selected frame's display.
2367 On \"multi-monitor\" setups this refers to the pixel height for all
2368 physical monitors associated with TERMINAL.  To get information for
2369 each physical monitor, use `display-monitor-attributes-list'.  */)
2370   (Lisp_Object terminal)
2372   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
2374   return make_number (x_display_pixel_height (dpyinfo));
2377 #ifdef NS_IMPL_COCOA
2379 /* Returns the name for the screen that OBJ represents, or NULL.
2380    Caller must free return value.
2383 static char *
2384 ns_get_name_from_ioreg (io_object_t obj)
2386   char *name = NULL;
2388   NSDictionary *info = (NSDictionary *)
2389     IODisplayCreateInfoDictionary (obj, kIODisplayOnlyPreferredName);
2390   NSDictionary *names = [info objectForKey:
2391                                 [NSString stringWithUTF8String:
2392                                             kDisplayProductName]];
2394   if ([names count] > 0)
2395     {
2396       NSString *n = [names objectForKey: [[names allKeys]
2397                                                  objectAtIndex:0]];
2398       if (n != nil) name = xstrdup ([n UTF8String]);
2399     }
2401   [info release];
2403   return name;
2406 /* Returns the name for the screen that DID came from, or NULL.
2407    Caller must free return value.
2410 static char *
2411 ns_screen_name (CGDirectDisplayID did)
2413   char *name = NULL;
2415 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
2416   mach_port_t masterPort;
2417   io_iterator_t it;
2418   io_object_t obj;
2420   // CGDisplayIOServicePort is deprecated.  Do it another (harder) way.
2422   if (IOMasterPort (MACH_PORT_NULL, &masterPort) != kIOReturnSuccess
2423       || IOServiceGetMatchingServices (masterPort,
2424                                        IOServiceMatching ("IONDRVDevice"),
2425                                        &it) != kIOReturnSuccess)
2426     return name;
2428   /* Must loop until we find a name.  Many devices can have the same unit
2429      number (represents different GPU parts), but only one has a name.  */
2430   while (! name && (obj = IOIteratorNext (it)))
2431     {
2432       CFMutableDictionaryRef props;
2433       const void *val;
2435       if (IORegistryEntryCreateCFProperties (obj,
2436                                              &props,
2437                                              kCFAllocatorDefault,
2438                                              kNilOptions) == kIOReturnSuccess
2439           && props != nil
2440           && (val = CFDictionaryGetValue(props, @"IOFBDependentIndex")))
2441         {
2442           unsigned nr = [(NSNumber *)val unsignedIntegerValue];
2443           if (nr == CGDisplayUnitNumber (did))
2444             name = ns_get_name_from_ioreg (obj);
2445         }
2447       CFRelease (props);
2448       IOObjectRelease (obj);
2449     }
2451   IOObjectRelease (it);
2453 #else
2455   name = ns_get_name_from_ioreg (CGDisplayIOServicePort (did));
2457 #endif
2458   return name;
2460 #endif
2462 static Lisp_Object
2463 ns_make_monitor_attribute_list (struct MonitorInfo *monitors,
2464                                 int n_monitors,
2465                                 int primary_monitor,
2466                                 const char *source)
2468   Lisp_Object monitor_frames = Fmake_vector (make_number (n_monitors), Qnil);
2469   Lisp_Object frame, rest;
2470   NSArray *screens = [NSScreen screens];
2471   int i;
2473   FOR_EACH_FRAME (rest, frame)
2474     {
2475       struct frame *f = XFRAME (frame);
2477       if (FRAME_NS_P (f))
2478         {
2479           NSView *view = FRAME_NS_VIEW (f);
2480           NSScreen *screen = [[view window] screen];
2481           NSUInteger k;
2483           i = -1;
2484           for (k = 0; i == -1 && k < [screens count]; ++k)
2485             {
2486               if ([screens objectAtIndex: k] == screen)
2487                 i = (int)k;
2488             }
2490           if (i > -1)
2491             ASET (monitor_frames, i, Fcons (frame, AREF (monitor_frames, i)));
2492         }
2493     }
2495   return make_monitor_attribute_list (monitors, n_monitors, primary_monitor,
2496                                       monitor_frames, source);
2499 DEFUN ("ns-display-monitor-attributes-list",
2500        Fns_display_monitor_attributes_list,
2501        Sns_display_monitor_attributes_list,
2502        0, 1, 0,
2503        doc: /* Return a list of physical monitor attributes on the X display TERMINAL.
2505 The optional argument TERMINAL specifies which display to ask about.
2506 TERMINAL should be a terminal object, a frame or a display name (a string).
2507 If omitted or nil, that stands for the selected frame's display.
2509 In addition to the standard attribute keys listed in
2510 `display-monitor-attributes-list', the following keys are contained in
2511 the attributes:
2513  source -- String describing the source from which multi-monitor
2514            information is obtained, \"NS\" is always the source."
2516 Internal use only, use `display-monitor-attributes-list' instead.  */)
2517   (Lisp_Object terminal)
2519   struct terminal *term = get_terminal (terminal, 1);
2520   NSArray *screens;
2521   NSUInteger i, n_monitors;
2522   struct MonitorInfo *monitors;
2523   Lisp_Object attributes_list = Qnil;
2524   CGFloat primary_display_height = 0;
2526   if (term->type != output_ns)
2527     return Qnil;
2529   screens = [NSScreen screens];
2530   n_monitors = [screens count];
2531   if (n_monitors == 0)
2532     return Qnil;
2534   monitors = xzalloc (n_monitors * sizeof *monitors);
2536   for (i = 0; i < [screens count]; ++i)
2537     {
2538       NSScreen *s = [screens objectAtIndex:i];
2539       struct MonitorInfo *m = &monitors[i];
2540       NSRect fr = [s frame];
2541       NSRect vfr = [s visibleFrame];
2542       short y, vy;
2544 #ifdef NS_IMPL_COCOA
2545       NSDictionary *dict = [s deviceDescription];
2546       NSNumber *nid = [dict objectForKey:@"NSScreenNumber"];
2547       CGDirectDisplayID did = [nid unsignedIntValue];
2548 #endif
2549       if (i == 0)
2550         {
2551           primary_display_height = fr.size.height;
2552           y = (short) fr.origin.y;
2553           vy = (short) vfr.origin.y;
2554         }
2555       else
2556         {
2557           // Flip y coordinate as NS has y starting from the bottom.
2558           y = (short) (primary_display_height - fr.size.height - fr.origin.y);
2559           vy = (short) (primary_display_height -
2560                         vfr.size.height - vfr.origin.y);
2561         }
2563       m->geom.x = (short) fr.origin.x;
2564       m->geom.y = y;
2565       m->geom.width = (unsigned short) fr.size.width;
2566       m->geom.height = (unsigned short) fr.size.height;
2568       m->work.x = (short) vfr.origin.x;
2569       // y is flipped on NS, so vy - y are pixels missing at the bottom,
2570       // and fr.size.height - vfr.size.height are pixels missing in total.
2571       // Pixels missing at top are
2572       // fr.size.height - vfr.size.height - vy + y.
2573       // work.y is then pixels missing at top + y.
2574       m->work.y = (short) (fr.size.height - vfr.size.height) - vy + y + y;
2575       m->work.width = (unsigned short) vfr.size.width;
2576       m->work.height = (unsigned short) vfr.size.height;
2578 #ifdef NS_IMPL_COCOA
2579       m->name = ns_screen_name (did);
2581       {
2582         CGSize mms = CGDisplayScreenSize (did);
2583         m->mm_width = (int) mms.width;
2584         m->mm_height = (int) mms.height;
2585       }
2587 #else
2588       // Assume 92 dpi as x-display-mm-height/x-display-mm-width does.
2589       m->mm_width = (int) (25.4 * fr.size.width / 92.0);
2590       m->mm_height = (int) (25.4 * fr.size.height / 92.0);
2591 #endif
2592     }
2594   // Primary monitor is always first for NS.
2595   attributes_list = ns_make_monitor_attribute_list (monitors, n_monitors,
2596                                                     0, "NS");
2598   free_monitors (monitors, n_monitors);
2599   return attributes_list;
2603 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
2604        0, 1, 0,
2605        doc: /* Return the number of bitplanes of the Nextstep display TERMINAL.
2606 The optional argument TERMINAL specifies which display to ask about.
2607 TERMINAL should be a terminal object, a frame or a display name (a string).
2608 If omitted or nil, that stands for the selected frame's display.  */)
2609   (Lisp_Object terminal)
2611   check_ns_display_info (terminal);
2612   return make_number
2613     (NSBitsPerPixelFromDepth ([[[NSScreen screens] objectAtIndex:0] depth]));
2617 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
2618        0, 1, 0,
2619        doc: /* Returns the number of color cells of the Nextstep display TERMINAL.
2620 The optional argument TERMINAL specifies which display to ask about.
2621 TERMINAL should be a terminal object, a frame or a display name (a string).
2622 If omitted or nil, that stands for the selected frame's display.  */)
2623   (Lisp_Object terminal)
2625   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
2626   /* We force 24+ bit depths to 24-bit to prevent an overflow.  */
2627   return make_number (1 << min (dpyinfo->n_planes, 24));
2631 /* Unused dummy def needed for compatibility. */
2632 Lisp_Object tip_frame;
2634 /* TODO: move to xdisp or similar */
2635 static void
2636 compute_tip_xy (struct frame *f,
2637                 Lisp_Object parms,
2638                 Lisp_Object dx,
2639                 Lisp_Object dy,
2640                 int width,
2641                 int height,
2642                 int *root_x,
2643                 int *root_y)
2645   Lisp_Object left, top;
2646   EmacsView *view = FRAME_NS_VIEW (f);
2647   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2648   NSPoint pt;
2650   /* Start with user-specified or mouse position.  */
2651   left = Fcdr (Fassq (Qleft, parms));
2652   top = Fcdr (Fassq (Qtop, parms));
2654   if (!INTEGERP (left) || !INTEGERP (top))
2655     {
2656       pt.x = dpyinfo->last_mouse_motion_x;
2657       pt.y = dpyinfo->last_mouse_motion_y;
2658       /* Convert to screen coordinates */
2659       pt = [view convertPoint: pt toView: nil];
2660       pt = [[view window] convertBaseToScreen: pt];
2661     }
2662   else
2663     {
2664       /* Absolute coordinates.  */
2665       pt.x = XINT (left);
2666       pt.y = x_display_pixel_height (FRAME_DISPLAY_INFO (f)) - XINT (top)
2667         - height;
2668     }
2670   /* Ensure in bounds.  (Note, screen origin = lower left.) */
2671   if (INTEGERP (left))
2672     *root_x = pt.x;
2673   else if (pt.x + XINT (dx) <= 0)
2674     *root_x = 0; /* Can happen for negative dx */
2675   else if (pt.x + XINT (dx) + width
2676            <= x_display_pixel_width (FRAME_DISPLAY_INFO (f)))
2677     /* It fits to the right of the pointer.  */
2678     *root_x = pt.x + XINT (dx);
2679   else if (width + XINT (dx) <= pt.x)
2680     /* It fits to the left of the pointer.  */
2681     *root_x = pt.x - width - XINT (dx);
2682   else
2683     /* Put it left justified on the screen -- it ought to fit that way.  */
2684     *root_x = 0;
2686   if (INTEGERP (top))
2687     *root_y = pt.y;
2688   else if (pt.y - XINT (dy) - height >= 0)
2689     /* It fits below the pointer.  */
2690     *root_y = pt.y - height - XINT (dy);
2691   else if (pt.y + XINT (dy) + height
2692            <= x_display_pixel_height (FRAME_DISPLAY_INFO (f)))
2693     /* It fits above the pointer */
2694       *root_y = pt.y + XINT (dy);
2695   else
2696     /* Put it on the top.  */
2697     *root_y = x_display_pixel_height (FRAME_DISPLAY_INFO (f)) - height;
2701 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
2702        doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
2703 A tooltip window is a small window displaying a string.
2705 This is an internal function; Lisp code should call `tooltip-show'.
2707 FRAME nil or omitted means use the selected frame.
2709 PARMS is an optional list of frame parameters which can be used to
2710 change the tooltip's appearance.
2712 Automatically hide the tooltip after TIMEOUT seconds.  TIMEOUT nil
2713 means use the default timeout of 5 seconds.
2715 If the list of frame parameters PARMS contains a `left' parameter,
2716 the tooltip is displayed at that x-position.  Otherwise it is
2717 displayed at the mouse position, with offset DX added (default is 5 if
2718 DX isn't specified).  Likewise for the y-position; if a `top' frame
2719 parameter is specified, it determines the y-position of the tooltip
2720 window, otherwise it is displayed at the mouse position, with offset
2721 DY added (default is -10).
2723 A tooltip's maximum size is specified by `x-max-tooltip-size'.
2724 Text larger than the specified size is clipped.  */)
2725      (Lisp_Object string, Lisp_Object frame, Lisp_Object parms, Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
2727   int root_x, root_y;
2728   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2729   ptrdiff_t count = SPECPDL_INDEX ();
2730   struct frame *f;
2731   char *str;
2732   NSSize size;
2734   specbind (Qinhibit_redisplay, Qt);
2736   GCPRO4 (string, parms, frame, timeout);
2738   CHECK_STRING (string);
2739   str = SSDATA (string);
2740   f = decode_window_system_frame (frame);
2741   if (NILP (timeout))
2742     timeout = make_number (5);
2743   else
2744     CHECK_NATNUM (timeout);
2746   if (NILP (dx))
2747     dx = make_number (5);
2748   else
2749     CHECK_NUMBER (dx);
2751   if (NILP (dy))
2752     dy = make_number (-10);
2753   else
2754     CHECK_NUMBER (dy);
2756   block_input ();
2757   if (ns_tooltip == nil)
2758     ns_tooltip = [[EmacsTooltip alloc] init];
2759   else
2760     Fx_hide_tip ();
2762   [ns_tooltip setText: str];
2763   size = [ns_tooltip frame].size;
2765   /* Move the tooltip window where the mouse pointer is.  Resize and
2766      show it.  */
2767   compute_tip_xy (f, parms, dx, dy, (int)size.width, (int)size.height,
2768                   &root_x, &root_y);
2770   [ns_tooltip showAtX: root_x Y: root_y for: XINT (timeout)];
2771   unblock_input ();
2773   UNGCPRO;
2774   return unbind_to (count, Qnil);
2778 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
2779        doc: /* Hide the current tooltip window, if there is any.
2780 Value is t if tooltip was open, nil otherwise.  */)
2781      (void)
2783   if (ns_tooltip == nil || ![ns_tooltip isActive])
2784     return Qnil;
2785   [ns_tooltip hide];
2786   return Qt;
2790 /* ==========================================================================
2792     Class implementations
2794    ========================================================================== */
2797   Handle arrow/function/control keys and copy/paste/cut in file dialogs.
2798   Return YES if handled, NO if not.
2799  */
2800 static BOOL
2801 handlePanelKeys (NSSavePanel *panel, NSEvent *theEvent)
2803   NSString *s;
2804   int i;
2805   BOOL ret = NO;
2807   if ([theEvent type] != NSKeyDown) return NO;
2808   s = [theEvent characters];
2810   for (i = 0; i < [s length]; ++i)
2811     {
2812       int ch = (int) [s characterAtIndex: i];
2813       switch (ch)
2814         {
2815         case NSHomeFunctionKey:
2816         case NSDownArrowFunctionKey:
2817         case NSUpArrowFunctionKey:
2818         case NSLeftArrowFunctionKey:
2819         case NSRightArrowFunctionKey:
2820         case NSPageUpFunctionKey:
2821         case NSPageDownFunctionKey:
2822         case NSEndFunctionKey:
2823           /* Don't send command modified keys, as those are handled in the
2824              performKeyEquivalent method of the super class.
2825           */
2826           if (! ([theEvent modifierFlags] & NSCommandKeyMask))
2827             {
2828               [panel sendEvent: theEvent];
2829               ret = YES;
2830             }
2831           break;
2832           /* As we don't have the standard key commands for
2833              copy/paste/cut/select-all in our edit menu, we must handle
2834              them here.  TODO: handle Emacs key bindings for copy/cut/select-all
2835              here, paste works, because we have that in our Edit menu.
2836              I.e. refactor out code in nsterm.m, keyDown: to figure out the
2837              correct modifier.
2838           */
2839         case 'x': // Cut
2840         case 'c': // Copy
2841         case 'v': // Paste
2842         case 'a': // Select all
2843           if ([theEvent modifierFlags] & NSCommandKeyMask)
2844             {
2845               [NSApp sendAction:
2846                        (ch == 'x'
2847                         ? @selector(cut:)
2848                         : (ch == 'c'
2849                            ? @selector(copy:)
2850                            : (ch == 'v'
2851                               ? @selector(paste:)
2852                               : @selector(selectAll:))))
2853                              to:nil from:panel];
2854               ret = YES;
2855             }
2856         default:
2857           // Send all control keys, as the text field supports C-a, C-f, C-e
2858           // C-b and more.
2859           if ([theEvent modifierFlags] & NSControlKeyMask)
2860             {
2861               [panel sendEvent: theEvent];
2862               ret = YES;
2863             }
2864           break;
2865         }
2866     }
2869   return ret;
2872 @implementation EmacsSavePanel
2873 - (BOOL)performKeyEquivalent:(NSEvent *)theEvent
2875   BOOL ret = handlePanelKeys (self, theEvent);
2876   if (! ret)
2877     ret = [super performKeyEquivalent:theEvent];
2878   return ret;
2880 @end
2883 @implementation EmacsOpenPanel
2884 - (BOOL)performKeyEquivalent:(NSEvent *)theEvent
2886   // NSOpenPanel inherits NSSavePanel, so passing self is OK.
2887   BOOL ret = handlePanelKeys (self, theEvent);
2888   if (! ret)
2889     ret = [super performKeyEquivalent:theEvent];
2890   return ret;
2892 @end
2895 @implementation EmacsFileDelegate
2896 /* --------------------------------------------------------------------------
2897    Delegate methods for Open/Save panels
2898    -------------------------------------------------------------------------- */
2899 - (BOOL)panel: (id)sender isValidFilename: (NSString *)filename
2901   return YES;
2903 - (BOOL)panel: (id)sender shouldShowFilename: (NSString *)filename
2905   return YES;
2907 - (NSString *)panel: (id)sender userEnteredFilename: (NSString *)filename
2908           confirmed: (BOOL)okFlag
2910   return filename;
2912 @end
2914 #endif
2917 /* ==========================================================================
2919     Lisp interface declaration
2921    ========================================================================== */
2924 void
2925 syms_of_nsfns (void)
2927   Qfontsize = intern_c_string ("fontsize");
2928   staticpro (&Qfontsize);
2930   DEFVAR_LISP ("ns-icon-type-alist", Vns_icon_type_alist,
2931                doc: /* Alist of elements (REGEXP . IMAGE) for images of icons associated to frames.
2932 If the title of a frame matches REGEXP, then IMAGE.tiff is
2933 selected as the image of the icon representing the frame when it's
2934 miniaturized.  If an element is t, then Emacs tries to select an icon
2935 based on the filetype of the visited file.
2937 The images have to be installed in a folder called English.lproj in the
2938 Emacs folder.  You have to restart Emacs after installing new icons.
2940 Example: Install an icon Gnus.tiff and execute the following code
2942   (setq ns-icon-type-alist
2943         (append ns-icon-type-alist
2944                 '((\"^\\\\*\\\\(Group\\\\*$\\\\|Summary \\\\|Article\\\\*$\\\\)\"
2945                    . \"Gnus\"))))
2947 When you miniaturize a Group, Summary or Article frame, Gnus.tiff will
2948 be used as the image of the icon representing the frame.  */);
2949   Vns_icon_type_alist = list1 (Qt);
2951   DEFVAR_LISP ("ns-version-string", Vns_version_string,
2952                doc: /* Toolkit version for NS Windowing.  */);
2953   Vns_version_string = ns_appkit_version_str ();
2955   defsubr (&Sns_read_file_name);
2956   defsubr (&Sns_get_resource);
2957   defsubr (&Sns_set_resource);
2958   defsubr (&Sxw_display_color_p); /* this and next called directly by C code */
2959   defsubr (&Sx_display_grayscale_p);
2960   defsubr (&Sns_font_name);
2961   defsubr (&Sns_list_colors);
2962 #ifdef NS_IMPL_COCOA
2963   defsubr (&Sns_do_applescript);
2964 #endif
2965   defsubr (&Sxw_color_defined_p);
2966   defsubr (&Sxw_color_values);
2967   defsubr (&Sx_server_max_request_size);
2968   defsubr (&Sx_server_vendor);
2969   defsubr (&Sx_server_version);
2970   defsubr (&Sx_display_pixel_width);
2971   defsubr (&Sx_display_pixel_height);
2972   defsubr (&Sns_display_monitor_attributes_list);
2973   defsubr (&Sx_display_mm_width);
2974   defsubr (&Sx_display_mm_height);
2975   defsubr (&Sx_display_screens);
2976   defsubr (&Sx_display_planes);
2977   defsubr (&Sx_display_color_cells);
2978   defsubr (&Sx_display_visual_class);
2979   defsubr (&Sx_display_backing_store);
2980   defsubr (&Sx_display_save_under);
2981   defsubr (&Sx_create_frame);
2982   defsubr (&Sx_open_connection);
2983   defsubr (&Sx_close_connection);
2984   defsubr (&Sx_display_list);
2986   defsubr (&Sns_hide_others);
2987   defsubr (&Sns_hide_emacs);
2988   defsubr (&Sns_emacs_info_panel);
2989   defsubr (&Sns_list_services);
2990   defsubr (&Sns_perform_service);
2991   defsubr (&Sns_convert_utf8_nfd_to_nfc);
2992   defsubr (&Sns_popup_font_panel);
2993   defsubr (&Sns_popup_color_panel);
2995   defsubr (&Sx_show_tip);
2996   defsubr (&Sx_hide_tip);
2998   as_status = 0;
2999   as_script = Qnil;
3000   as_result = 0;