Avoid crashes due to invalid error forms from sentinels/filters
[emacs.git] / src / nsfns.m
blobba363629686a334d572ca9f6f45c3a25ef7eedae
1 /* Functions for the NeXT/Open/GNUstep and macOS window system.
3 Copyright (C) 1989, 1992-1994, 2005-2006, 2008-2017 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 (at
11 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 <https://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 macOS/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 #include "macfont.h"
50 #endif
53 #ifdef HAVE_NS
55 static EmacsTooltip *ns_tooltip = nil;
57 /* Static variables to handle applescript execution.  */
58 static Lisp_Object as_script, *as_result;
59 static int as_status;
61 static ptrdiff_t image_cache_refcount;
63 static struct ns_display_info *ns_display_info_for_name (Lisp_Object);
64 static void ns_set_name_as_filename (struct frame *);
66 /* ==========================================================================
68     Internal utility functions
70    ========================================================================== */
72 /* Let the user specify a Nextstep display with a Lisp object.
73    OBJECT may be nil, a frame or a terminal object.
74    nil stands for the selected frame--or, if that is not a Nextstep frame,
75    the first Nextstep display on the list.  */
77 static struct ns_display_info *
78 check_ns_display_info (Lisp_Object object)
80   struct ns_display_info *dpyinfo = NULL;
82   if (NILP (object))
83     {
84       struct frame *sf = XFRAME (selected_frame);
86       if (FRAME_NS_P (sf) && FRAME_LIVE_P (sf))
87         dpyinfo = FRAME_DISPLAY_INFO (sf);
88       else if (x_display_list != 0)
89         dpyinfo = x_display_list;
90       else
91         error ("Nextstep windows are not in use or not initialized");
92     }
93   else if (TERMINALP (object))
94     {
95       struct terminal *t = decode_live_terminal (object);
97       if (t->type != output_ns)
98         error ("Terminal %d is not a Nextstep display", t->id);
100       dpyinfo = t->display_info.ns;
101     }
102   else if (STRINGP (object))
103     dpyinfo = ns_display_info_for_name (object);
104   else
105     {
106       struct frame *f = decode_window_system_frame (object);
107       dpyinfo = FRAME_DISPLAY_INFO (f);
108     }
110   return dpyinfo;
114 static id
115 ns_get_window (Lisp_Object maybeFrame)
117   id view =nil, window =nil;
119   if (!FRAMEP (maybeFrame) || !FRAME_NS_P (XFRAME (maybeFrame)))
120     maybeFrame = selected_frame;/*wrong_type_argument (Qframep, maybeFrame); */
122   if (!NILP (maybeFrame))
123     view = FRAME_NS_VIEW (XFRAME (maybeFrame));
124   if (view) window =[view window];
126   return window;
130 /* Return the X display structure for the display named NAME.
131    Open a new connection if necessary.  */
132 static struct ns_display_info *
133 ns_display_info_for_name (Lisp_Object name)
135   struct ns_display_info *dpyinfo;
137   CHECK_STRING (name);
139   for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
140     if (!NILP (Fstring_equal (XCAR (dpyinfo->name_list_element), name)))
141       return dpyinfo;
143   error ("Emacs for Nextstep does not yet support multi-display");
145   Fx_open_connection (name, Qnil, Qnil);
146   dpyinfo = x_display_list;
148   if (dpyinfo == 0)
149     error ("Display on %s not responding.\n", SDATA (name));
151   return dpyinfo;
154 static NSString *
155 ns_filename_from_panel (NSSavePanel *panel)
157 #ifdef NS_IMPL_COCOA
158   NSURL *url = [panel URL];
159   NSString *str = [url path];
160   return str;
161 #else
162   return [panel filename];
163 #endif
166 static NSString *
167 ns_directory_from_panel (NSSavePanel *panel)
169 #ifdef NS_IMPL_COCOA
170   NSURL *url = [panel directoryURL];
171   NSString *str = [url path];
172   return str;
173 #else
174   return [panel directory];
175 #endif
178 #ifndef NS_IMPL_COCOA
179 static Lisp_Object
180 interpret_services_menu (NSMenu *menu, Lisp_Object prefix, Lisp_Object old)
181 /* --------------------------------------------------------------------------
182    Turn the input menu (an NSMenu) into a lisp list for tracking on lisp side
183    -------------------------------------------------------------------------- */
185   int i, count;
186   NSMenuItem *item;
187   const char *name;
188   Lisp_Object nameStr;
189   unsigned short key;
190   NSString *keys;
191   Lisp_Object res;
193   count = [menu numberOfItems];
194   for (i = 0; i<count; i++)
195     {
196       item = [menu itemAtIndex: i];
197       name = [[item title] UTF8String];
198       if (!name) continue;
200       nameStr = build_string (name);
202       if ([item hasSubmenu])
203         {
204           old = interpret_services_menu ([item submenu],
205                                         Fcons (nameStr, prefix), old);
206         }
207       else
208         {
209           keys = [item keyEquivalent];
210           if (keys && [keys length] )
211             {
212               key = [keys characterAtIndex: 0];
213               res = make_number (key|super_modifier);
214             }
215           else
216             {
217               res = Qundefined;
218             }
219           old = Fcons (Fcons (res,
220                             Freverse (Fcons (nameStr,
221                                            prefix))),
222                     old);
223         }
224     }
225   return old;
227 #endif
230 /* ==========================================================================
232     Frame parameter setters
234    ========================================================================== */
237 static void
238 x_set_foreground_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
240   NSColor *col;
241   EmacsCGFloat r, g, b, alpha;
243   /* Must block_input, because ns_lisp_to_color does block/unblock_input
244      which means that col may be deallocated in its unblock_input if there
245      is user input, unless we also block_input.  */
246   block_input ();
247   if (ns_lisp_to_color (arg, &col))
248     {
249       store_frame_param (f, Qforeground_color, oldval);
250       unblock_input ();
251       error ("Unknown color");
252     }
254   [col retain];
255   [f->output_data.ns->foreground_color release];
256   f->output_data.ns->foreground_color = col;
258   [col getRed: &r green: &g blue: &b alpha: &alpha];
259   FRAME_FOREGROUND_PIXEL (f) =
260     ARGB_TO_ULONG ((int)(alpha*0xff), (int)(r*0xff), (int)(g*0xff), (int)(b*0xff));
262   if (FRAME_NS_VIEW (f))
263     {
264       update_face_from_frame_parameter (f, Qforeground_color, arg);
265       /*recompute_basic_faces (f); */
266       if (FRAME_VISIBLE_P (f))
267         SET_FRAME_GARBAGED (f);
268     }
269   unblock_input ();
273 static void
274 x_set_background_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
276   struct face *face;
277   NSColor *col;
278   NSView *view = FRAME_NS_VIEW (f);
279   EmacsCGFloat r, g, b, alpha;
281   block_input ();
282   if (ns_lisp_to_color (arg, &col))
283     {
284       store_frame_param (f, Qbackground_color, oldval);
285       unblock_input ();
286       error ("Unknown color");
287     }
289   /* clear the frame; in some instances the NS-internal GC appears not to
290      update, or it does update and cannot clear old text properly */
291   if (FRAME_VISIBLE_P (f))
292     ns_clear_frame (f);
294   [col retain];
295   [f->output_data.ns->background_color release];
296   f->output_data.ns->background_color = col;
298   [col getRed: &r green: &g blue: &b alpha: &alpha];
299   FRAME_BACKGROUND_PIXEL (f) =
300     ARGB_TO_ULONG ((int)(alpha*0xff), (int)(r*0xff), (int)(g*0xff), (int)(b*0xff));
302   if (view != nil)
303     {
304       [[view window] setBackgroundColor: col];
306       if (alpha != (EmacsCGFloat) 1.0)
307           [[view window] setOpaque: NO];
308       else
309           [[view window] setOpaque: YES];
311       face = FRAME_DEFAULT_FACE (f);
312       if (face)
313         {
314           col = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f);
315           face->background = ns_index_color
316             ([col colorWithAlphaComponent: alpha], f);
318           update_face_from_frame_parameter (f, Qbackground_color, arg);
319         }
321       if (FRAME_VISIBLE_P (f))
322         SET_FRAME_GARBAGED (f);
323     }
324   unblock_input ();
328 static void
329 x_set_cursor_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
331   NSColor *col;
333   block_input ();
334   if (ns_lisp_to_color (arg, &col))
335     {
336       store_frame_param (f, Qcursor_color, oldval);
337       unblock_input ();
338       error ("Unknown color");
339     }
341   [FRAME_CURSOR_COLOR (f) release];
342   FRAME_CURSOR_COLOR (f) = [col retain];
344   if (FRAME_VISIBLE_P (f))
345     {
346       x_update_cursor (f, 0);
347       x_update_cursor (f, 1);
348     }
349   update_face_from_frame_parameter (f, Qcursor_color, arg);
350   unblock_input ();
354 static void
355 x_set_icon_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
357   NSView *view = FRAME_NS_VIEW (f);
358   NSTRACE ("x_set_icon_name");
360   /* see if it's changed */
361   if (STRINGP (arg))
362     {
363       if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
364         return;
365     }
366   else if (!STRINGP (oldval) && EQ (oldval, Qnil) == EQ (arg, Qnil))
367     return;
369   fset_icon_name (f, arg);
371   if (NILP (arg))
372     {
373       if (!NILP (f->title))
374         arg = f->title;
375       else
376         /* Explicit name and no icon-name -> explicit_name.  */
377         if (f->explicit_name)
378           arg = f->name;
379         else
380           {
381             /* No explicit name and no icon-name ->
382                name has to be rebuild from icon_title_format.  */
383             windows_or_buffers_changed = 62;
384             return;
385           }
386     }
388   /* Don't change the name if it's already NAME.  */
389   if ([[view window] miniwindowTitle]
390       && ([[[view window] miniwindowTitle]
391              isEqualToString: [NSString stringWithUTF8String:
392                                           SSDATA (arg)]]))
393     return;
395   [[view window] setMiniwindowTitle:
396         [NSString stringWithUTF8String: SSDATA (arg)]];
399 static void
400 ns_set_name_internal (struct frame *f, Lisp_Object name)
402   Lisp_Object encoded_name, encoded_icon_name;
403   NSString *str;
404   NSView *view = FRAME_NS_VIEW (f);
407   encoded_name = ENCODE_UTF_8 (name);
409   str = [NSString stringWithUTF8String: SSDATA (encoded_name)];
412   /* Don't change the name if it's already NAME.  */
413   if (! [[[view window] title] isEqualToString: str])
414     [[view window] setTitle: str];
416   if (!STRINGP (f->icon_name))
417     encoded_icon_name = encoded_name;
418   else
419     encoded_icon_name = ENCODE_UTF_8 (f->icon_name);
421   str = [NSString stringWithUTF8String: SSDATA (encoded_icon_name)];
423   if ([[view window] miniwindowTitle]
424       && ! [[[view window] miniwindowTitle] isEqualToString: str])
425     [[view window] setMiniwindowTitle: str];
429 static void
430 ns_set_name (struct frame *f, Lisp_Object name, int explicit)
432   NSTRACE ("ns_set_name");
434   /* Make sure that requests from lisp code override requests from
435      Emacs redisplay code.  */
436   if (explicit)
437     {
438       /* If we're switching from explicit to implicit, we had better
439          update the mode lines and thereby update the title.  */
440       if (f->explicit_name && NILP (name))
441         update_mode_lines = 21;
443       f->explicit_name = ! NILP (name);
444     }
445   else if (f->explicit_name)
446     return;
448   if (NILP (name))
449     name = build_string ([ns_app_name UTF8String]);
450   else
451     CHECK_STRING (name);
453   /* Don't change the name if it's already NAME.  */
454   if (! NILP (Fstring_equal (name, f->name)))
455     return;
457   fset_name (f, name);
459   /* Title overrides explicit name.  */
460   if (! NILP (f->title))
461     name = f->title;
463   ns_set_name_internal (f, name);
467 /* This function should be called when the user's lisp code has
468    specified a name for the frame; the name will override any set by the
469    redisplay code.  */
470 static void
471 x_explicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
473   NSTRACE ("x_explicitly_set_name");
474   ns_set_name (f, arg, 1);
478 /* This function should be called by Emacs redisplay code to set the
479    name; names set this way will never override names set by the user's
480    lisp code.  */
481 void
482 x_implicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
484   NSTRACE ("x_implicitly_set_name");
486   Lisp_Object frame_title = buffer_local_value
487     (Qframe_title_format, XWINDOW (f->selected_window)->contents);
488   Lisp_Object icon_title = buffer_local_value
489     (Qicon_title_format, XWINDOW (f->selected_window)->contents);
491   /* Deal with NS specific format t.  */
492   if (FRAME_NS_P (f) && ((FRAME_ICONIFIED_P (f) && EQ (icon_title, Qt))
493                          || EQ (frame_title, Qt)))
494     ns_set_name_as_filename (f);
495   else
496     ns_set_name (f, arg, 0);
500 /* Change the title of frame F to NAME.
501    If NAME is nil, use the frame name as the title.  */
503 static void
504 x_set_title (struct frame *f, Lisp_Object name, Lisp_Object old_name)
506   NSTRACE ("x_set_title");
507   /* Don't change the title if it's already NAME.  */
508   if (EQ (name, f->title))
509     return;
511   update_mode_lines = 22;
513   fset_title (f, name);
515   if (NILP (name))
516     name = f->name;
517   else
518     CHECK_STRING (name);
520   ns_set_name_internal (f, name);
524 static void
525 ns_set_name_as_filename (struct frame *f)
527   NSView *view;
528   Lisp_Object name, filename;
529   Lisp_Object buf = XWINDOW (f->selected_window)->contents;
530   const char *title;
531   NSAutoreleasePool *pool;
532   Lisp_Object encoded_name, encoded_filename;
533   NSString *str;
534   NSTRACE ("ns_set_name_as_filename");
536   if (f->explicit_name || ! NILP (f->title))
537     return;
539   block_input ();
540   pool = [[NSAutoreleasePool alloc] init];
541   filename = BVAR (XBUFFER (buf), filename);
542   name = BVAR (XBUFFER (buf), name);
544   if (NILP (name))
545     {
546       if (! NILP (filename))
547         name = Ffile_name_nondirectory (filename);
548       else
549         name = build_string ([ns_app_name UTF8String]);
550     }
552   encoded_name = ENCODE_UTF_8 (name);
554   view = FRAME_NS_VIEW (f);
556   title = FRAME_ICONIFIED_P (f) ? [[[view window] miniwindowTitle] UTF8String]
557                                 : [[[view window] title] UTF8String];
559   if (title && (! strcmp (title, SSDATA (encoded_name))))
560     {
561       [pool release];
562       unblock_input ();
563       return;
564     }
566   str = [NSString stringWithUTF8String: SSDATA (encoded_name)];
567   if (str == nil) str = @"Bad coding";
569   if (FRAME_ICONIFIED_P (f))
570     [[view window] setMiniwindowTitle: str];
571   else
572     {
573       NSString *fstr;
575       if (! NILP (filename))
576         {
577           encoded_filename = ENCODE_UTF_8 (filename);
579           fstr = [NSString stringWithUTF8String: SSDATA (encoded_filename)];
580           if (fstr == nil) fstr = @"";
581         }
582       else
583         fstr = @"";
585       ns_set_represented_filename (fstr, f);
586       [[view window] setTitle: str];
587       fset_name (f, name);
588     }
590   [pool release];
591   unblock_input ();
595 void
596 ns_set_doc_edited (void)
598   NSAutoreleasePool *pool;
599   Lisp_Object tail, frame;
600   block_input ();
601   pool = [[NSAutoreleasePool alloc] init];
602   FOR_EACH_FRAME (tail, frame)
603     {
604       BOOL edited = NO;
605       struct frame *f = XFRAME (frame);
606       struct window *w;
607       NSView *view;
609       if (! FRAME_NS_P (f)) continue;
610       w = XWINDOW (FRAME_SELECTED_WINDOW (f));
611       view = FRAME_NS_VIEW (f);
612       if (!MINI_WINDOW_P (w))
613         edited = ! NILP (Fbuffer_modified_p (w->contents)) &&
614           ! NILP (Fbuffer_file_name (w->contents));
615       [[view window] setDocumentEdited: edited];
616     }
618   [pool release];
619   unblock_input ();
623 static void
624 x_set_menu_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
626   int nlines;
627   if (FRAME_MINIBUF_ONLY_P (f))
628     return;
630   if (TYPE_RANGED_INTEGERP (int, value))
631     nlines = XINT (value);
632   else
633     nlines = 0;
635   FRAME_MENU_BAR_LINES (f) = 0;
636   if (nlines)
637     {
638       FRAME_EXTERNAL_MENU_BAR (f) = 1;
639       /* does for all frames, whereas we just want for one frame
640          [NSMenu setMenuBarVisible: YES]; */
641     }
642   else
643     {
644       if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
645         free_frame_menubar (f);
646       /*      [NSMenu setMenuBarVisible: NO]; */
647       FRAME_EXTERNAL_MENU_BAR (f) = 0;
648     }
652 /* toolbar support */
653 static void
654 x_set_tool_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
656   /* Currently, when the tool bar change state, the frame is resized.
658      TODO: It would be better if this didn't occur when 1) the frame
659      is full height or maximized or 2) when specified by
660      `frame-inhibit-implied-resize'. */
661   int nlines;
663   NSTRACE ("x_set_tool_bar_lines");
665   if (FRAME_MINIBUF_ONLY_P (f))
666     return;
668   if (RANGED_INTEGERP (0, value, INT_MAX))
669     nlines = XFASTINT (value);
670   else
671     nlines = 0;
673   if (nlines)
674     {
675       FRAME_EXTERNAL_TOOL_BAR (f) = 1;
676       update_frame_tool_bar (f);
677     }
678   else
679     {
680       if (FRAME_EXTERNAL_TOOL_BAR (f))
681         {
682           free_frame_tool_bar (f);
683           FRAME_EXTERNAL_TOOL_BAR (f) = 0;
685           {
686             EmacsView *view = FRAME_NS_VIEW (f);
687             int fs_state = [view fullscreenState];
689             if (fs_state == FULLSCREEN_MAXIMIZED)
690               {
691                 [view setFSValue:FULLSCREEN_WIDTH];
692               }
693             else if (fs_state == FULLSCREEN_HEIGHT)
694               {
695                 [view setFSValue:FULLSCREEN_NONE];
696               }
697           }
698        }
699     }
701   {
702     int inhibit
703       = ((f->after_make_frame
704           && !f->tool_bar_resized
705           && (EQ (frame_inhibit_implied_resize, Qt)
706               || (CONSP (frame_inhibit_implied_resize)
707                   && !NILP (Fmemq (Qtool_bar_lines,
708                                    frame_inhibit_implied_resize))))
709           && NILP (get_frame_param (f, Qfullscreen)))
710          ? 0
711          : 2);
713     NSTRACE_MSG ("inhibit:%d", inhibit);
715     frame_size_history_add (f, Qupdate_frame_tool_bar, 0, 0, Qnil);
716     adjust_frame_size (f, -1, -1, inhibit, 0, Qtool_bar_lines);
717   }
721 static void
722 x_set_internal_border_width (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
724   int old_width = FRAME_INTERNAL_BORDER_WIDTH (f);
726   CHECK_TYPE_RANGED_INTEGER (int, arg);
727   f->internal_border_width = XINT (arg);
728   if (FRAME_INTERNAL_BORDER_WIDTH (f) < 0)
729     f->internal_border_width = 0;
731   if (FRAME_INTERNAL_BORDER_WIDTH (f) == old_width)
732     return;
734   if (FRAME_X_WINDOW (f) != 0)
735     adjust_frame_size (f, -1, -1, 3, 0, Qinternal_border_width);
737   SET_FRAME_GARBAGED (f);
741 static void
742 ns_implicitly_set_icon_type (struct frame *f)
744   Lisp_Object tem;
745   EmacsView *view = FRAME_NS_VIEW (f);
746   id image = nil;
747   Lisp_Object chain, elt;
748   NSAutoreleasePool *pool;
749   BOOL setMini = YES;
751   NSTRACE ("ns_implicitly_set_icon_type");
753   block_input ();
754   pool = [[NSAutoreleasePool alloc] init];
755   if (f->output_data.ns->miniimage
756       && [[NSString stringWithUTF8String: SSDATA (f->name)]
757                isEqualToString: [(NSImage *)f->output_data.ns->miniimage name]])
758     {
759       [pool release];
760       unblock_input ();
761       return;
762     }
764   tem = assq_no_quit (Qicon_type, f->param_alist);
765   if (CONSP (tem) && ! NILP (XCDR (tem)))
766     {
767       [pool release];
768       unblock_input ();
769       return;
770     }
772   for (chain = Vns_icon_type_alist;
773        image == nil && CONSP (chain);
774        chain = XCDR (chain))
775     {
776       elt = XCAR (chain);
777       /* special case: t means go by file type */
778       if (SYMBOLP (elt) && EQ (elt, Qt) && SSDATA (f->name)[0] == '/')
779         {
780           NSString *str
781              = [NSString stringWithUTF8String: SSDATA (f->name)];
782           if ([[NSFileManager defaultManager] fileExistsAtPath: str])
783             image = [[[NSWorkspace sharedWorkspace] iconForFile: str] retain];
784         }
785       else if (CONSP (elt) &&
786                STRINGP (XCAR (elt)) &&
787                STRINGP (XCDR (elt)) &&
788                fast_string_match (XCAR (elt), f->name) >= 0)
789         {
790           image = [EmacsImage allocInitFromFile: XCDR (elt)];
791           if (image == nil)
792             image = [[NSImage imageNamed:
793                                [NSString stringWithUTF8String:
794                                             SSDATA (XCDR (elt))]] retain];
795         }
796     }
798   if (image == nil)
799     {
800       image = [[[NSWorkspace sharedWorkspace] iconForFileType: @"text"] retain];
801       setMini = NO;
802     }
804   [f->output_data.ns->miniimage release];
805   f->output_data.ns->miniimage = image;
806   [view setMiniwindowImage: setMini];
807   [pool release];
808   unblock_input ();
812 static void
813 x_set_icon_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
815   EmacsView *view = FRAME_NS_VIEW (f);
816   id image = nil;
817   BOOL setMini = YES;
819   NSTRACE ("x_set_icon_type");
821   if (!NILP (arg) && SYMBOLP (arg))
822     {
823       arg =build_string (SSDATA (SYMBOL_NAME (arg)));
824       store_frame_param (f, Qicon_type, arg);
825     }
827   /* do it the implicit way */
828   if (NILP (arg))
829     {
830       ns_implicitly_set_icon_type (f);
831       return;
832     }
834   CHECK_STRING (arg);
836   image = [EmacsImage allocInitFromFile: arg];
837   if (image == nil)
838     image =[NSImage imageNamed: [NSString stringWithUTF8String:
839                                             SSDATA (arg)]];
841   if (image == nil)
842     {
843       image = [NSImage imageNamed: @"text"];
844       setMini = NO;
845     }
847   f->output_data.ns->miniimage = image;
848   [view setMiniwindowImage: setMini];
851 /* This is the same as the xfns.c definition.  */
852 static void
853 x_set_cursor_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
855   set_frame_cursor_types (f, arg);
858 /* called to set mouse pointer color, but all other terms use it to
859    initialize pointer types (and don't set the color ;) */
860 static void
861 x_set_mouse_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
863   /* don't think we can do this on Nextstep */
867 #define Str(x) #x
868 #define Xstr(x) Str(x)
870 static Lisp_Object
871 ns_appkit_version_str (void)
873   char tmp[256];
875 #ifdef NS_IMPL_GNUSTEP
876   sprintf(tmp, "gnustep-gui-%s", Xstr(GNUSTEP_GUI_VERSION));
877 #elif defined (NS_IMPL_COCOA)
878   NSString *osversion
879     = [[NSProcessInfo processInfo] operatingSystemVersionString];
880   sprintf(tmp, "appkit-%.2f %s",
881           NSAppKitVersionNumber,
882           [osversion UTF8String]);
883 #else
884   tmp = "ns-unknown";
885 #endif
886   return build_string (tmp);
890 /* This is for use by x-server-version and collapses all version info we
891    have into a single int.  For a better picture of the implementation
892    running, use ns_appkit_version_str.*/
893 static int
894 ns_appkit_version_int (void)
896 #ifdef NS_IMPL_GNUSTEP
897   return GNUSTEP_GUI_MAJOR_VERSION * 100 + GNUSTEP_GUI_MINOR_VERSION;
898 #elif defined (NS_IMPL_COCOA)
899   return (int)NSAppKitVersionNumber;
900 #endif
901   return 0;
905 static void
906 x_icon (struct frame *f, Lisp_Object parms)
907 /* --------------------------------------------------------------------------
908    Strangely-named function to set icon position parameters in frame.
909    This is irrelevant under macOS, but might be needed under GNUstep,
910    depending on the window manager used.  Note, this is not a standard
911    frame parameter-setter; it is called directly from x-create-frame.
912    -------------------------------------------------------------------------- */
914   Lisp_Object icon_x, icon_y;
915   struct ns_display_info *dpyinfo = check_ns_display_info (Qnil);
917   f->output_data.ns->icon_top = -1;
918   f->output_data.ns->icon_left = -1;
920   /* Set the position of the icon.  */
921   icon_x = x_get_arg (dpyinfo, parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
922   icon_y = x_get_arg (dpyinfo, parms, Qicon_top, 0, 0,  RES_TYPE_NUMBER);
923   if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
924     {
925       CHECK_NUMBER (icon_x);
926       CHECK_NUMBER (icon_y);
927       f->output_data.ns->icon_top = XINT (icon_y);
928       f->output_data.ns->icon_left = XINT (icon_x);
929     }
930   else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
931     error ("Both left and top icon corners of icon must be specified");
935 /* Note: see frame.c for template, also where generic functions are impl */
936 frame_parm_handler ns_frame_parm_handlers[] =
938   x_set_autoraise, /* generic OK */
939   x_set_autolower, /* generic OK */
940   x_set_background_color,
941   0, /* x_set_border_color,  may be impossible under Nextstep */
942   0, /* x_set_border_width,  may be impossible under Nextstep */
943   x_set_cursor_color,
944   x_set_cursor_type,
945   x_set_font, /* generic OK */
946   x_set_foreground_color,
947   x_set_icon_name,
948   x_set_icon_type,
949   x_set_internal_border_width, /* generic OK */
950   x_set_right_divider_width,
951   x_set_bottom_divider_width,
952   x_set_menu_bar_lines,
953   x_set_mouse_color,
954   x_explicitly_set_name,
955   x_set_scroll_bar_width, /* generic OK */
956   x_set_scroll_bar_height, /* generic OK */
957   x_set_title,
958   x_set_unsplittable, /* generic OK */
959   x_set_vertical_scroll_bars, /* generic OK */
960   x_set_horizontal_scroll_bars, /* generic OK */
961   x_set_visibility, /* generic OK */
962   x_set_tool_bar_lines,
963   0, /* x_set_scroll_bar_foreground, will ignore (not possible on NS) */
964   0, /* x_set_scroll_bar_background,  will ignore (not possible on NS) */
965   x_set_screen_gamma, /* generic OK */
966   x_set_line_spacing, /* generic OK, sets f->extra_line_spacing to int */
967   x_set_left_fringe, /* generic OK */
968   x_set_right_fringe, /* generic OK */
969   0, /* x_set_wait_for_wm, will ignore */
970   x_set_fullscreen, /* generic OK */
971   x_set_font_backend, /* generic OK */
972   x_set_alpha,
973   0, /* x_set_sticky */
974   0, /* x_set_tool_bar_position */
975   0, /* x_set_inhibit_double_buffering */
976 #ifdef NS_IMPL_COCOA
977   x_set_undecorated,
978 #else
979   0, /*x_set_undecorated */
980 #endif
981   x_set_parent_frame,
982   0, /* x_set_skip_taskbar */
983   x_set_no_focus_on_map,
984   x_set_no_accept_focus,
985   x_set_z_group, /* x_set_z_group */
986   0, /* x_set_override_redirect */
987   x_set_no_special_glyphs,
988 #ifdef NS_IMPL_COCOA
989   ns_set_appearance,
990   ns_set_transparent_titlebar,
991 #endif
995 /* Handler for signals raised during x_create_frame.
996    FRAME is the frame which is partially constructed.  */
998 static void
999 unwind_create_frame (Lisp_Object frame)
1001   struct frame *f = XFRAME (frame);
1003   /* If frame is already dead, nothing to do.  This can happen if the
1004      display is disconnected after the frame has become official, but
1005      before x_create_frame removes the unwind protect.  */
1006   if (!FRAME_LIVE_P (f))
1007     return;
1009   /* If frame is ``official'', nothing to do.  */
1010   if (NILP (Fmemq (frame, Vframe_list)))
1011     {
1012 #if defined GLYPH_DEBUG && defined ENABLE_CHECKING
1013       struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1014 #endif
1016       /* If the frame's image cache refcount is still the same as our
1017          private shadow variable, it means we are unwinding a frame
1018          for which we didn't yet call init_frame_faces, where the
1019          refcount is incremented.  Therefore, we increment it here, so
1020          that free_frame_faces, called in x_free_frame_resources
1021          below, will not mistakenly decrement the counter that was not
1022          incremented yet to account for this new frame.  */
1023       if (FRAME_IMAGE_CACHE (f) != NULL
1024           && FRAME_IMAGE_CACHE (f)->refcount == image_cache_refcount)
1025         FRAME_IMAGE_CACHE (f)->refcount++;
1027       x_free_frame_resources (f);
1028       free_glyphs (f);
1030 #if defined GLYPH_DEBUG && defined ENABLE_CHECKING
1031       /* Check that reference counts are indeed correct.  */
1032       eassert (dpyinfo->terminal->image_cache->refcount == image_cache_refcount);
1033 #endif
1034     }
1038  * Read geometry related parameters from preferences if not in PARMS.
1039  * Returns the union of parms and any preferences read.
1040  */
1042 static Lisp_Object
1043 get_geometry_from_preferences (struct ns_display_info *dpyinfo,
1044                                Lisp_Object parms)
1046   struct {
1047     const char *val;
1048     const char *cls;
1049     Lisp_Object tem;
1050   } r[] = {
1051     { "width",  "Width", Qwidth },
1052     { "height", "Height", Qheight },
1053     { "left", "Left", Qleft },
1054     { "top", "Top", Qtop },
1055   };
1057   int i;
1058   for (i = 0; i < ARRAYELTS (r); ++i)
1059     {
1060       if (NILP (Fassq (r[i].tem, parms)))
1061         {
1062           Lisp_Object value
1063             = x_get_arg (dpyinfo, parms, r[i].tem, r[i].val, r[i].cls,
1064                          RES_TYPE_NUMBER);
1065           if (! EQ (value, Qunbound))
1066             parms = Fcons (Fcons (r[i].tem, value), parms);
1067         }
1068     }
1070   return parms;
1073 /* ==========================================================================
1075     Lisp definitions
1077    ========================================================================== */
1079 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
1080        1, 1, 0,
1081        doc: /* Make a new Nextstep window, called a "frame" in Emacs terms.
1082 Return an Emacs frame object.
1083 PARMS is an alist of frame parameters.
1084 If the parameters specify that the frame should not have a minibuffer,
1085 and do not specify a specific minibuffer window to use,
1086 then `default-minibuffer-frame' must be a frame whose minibuffer can
1087 be shared by the new frame.
1089 This function is an internal primitive--use `make-frame' instead.  */)
1090      (Lisp_Object parms)
1092   struct frame *f;
1093   Lisp_Object frame, tem;
1094   Lisp_Object name;
1095   int minibuffer_only = 0;
1096   long window_prompting = 0;
1097   ptrdiff_t count = specpdl_ptr - specpdl;
1098   Lisp_Object display;
1099   struct ns_display_info *dpyinfo = NULL;
1100   Lisp_Object parent, parent_frame;
1101   struct kboard *kb;
1102   static int desc_ctr = 1;
1103   int x_width = 0, x_height = 0;
1105   /* x_get_arg modifies parms.  */
1106   parms = Fcopy_alist (parms);
1108   /* Use this general default value to start with
1109      until we know if this frame has a specified name.  */
1110   Vx_resource_name = Vinvocation_name;
1112   display = x_get_arg (dpyinfo, parms, Qterminal, 0, 0, RES_TYPE_STRING);
1113   if (EQ (display, Qunbound))
1114     display = Qnil;
1115   dpyinfo = check_ns_display_info (display);
1116   kb = dpyinfo->terminal->kboard;
1118   if (!dpyinfo->terminal->name)
1119     error ("Terminal is not live, can't create new frames on it");
1121   name = x_get_arg (dpyinfo, parms, Qname, 0, 0, RES_TYPE_STRING);
1122   if (!STRINGP (name)
1123       && ! EQ (name, Qunbound)
1124       && ! NILP (name))
1125     error ("Invalid frame name--not a string or nil");
1127   if (STRINGP (name))
1128     Vx_resource_name = name;
1130   parent = x_get_arg (dpyinfo, parms, Qparent_id, 0, 0, RES_TYPE_NUMBER);
1131   if (EQ (parent, Qunbound))
1132     parent = Qnil;
1133   if (! NILP (parent))
1134     CHECK_NUMBER (parent);
1136   /* make_frame_without_minibuffer can run Lisp code and garbage collect.  */
1137   /* No need to protect DISPLAY because that's not used after passing
1138      it to make_frame_without_minibuffer.  */
1139   frame = Qnil;
1140   tem = x_get_arg (dpyinfo, parms, Qminibuffer, "minibuffer", "Minibuffer",
1141                   RES_TYPE_SYMBOL);
1142   if (EQ (tem, Qnone) || NILP (tem))
1143       f = make_frame_without_minibuffer (Qnil, kb, display);
1144   else if (EQ (tem, Qonly))
1145     {
1146       f = make_minibuffer_frame ();
1147       minibuffer_only = 1;
1148     }
1149   else if (WINDOWP (tem))
1150       f = make_frame_without_minibuffer (tem, kb, display);
1151   else
1152       f = make_frame (1);
1154   XSETFRAME (frame, f);
1156   f->terminal = dpyinfo->terminal;
1158   f->output_method = output_ns;
1159   f->output_data.ns = xzalloc (sizeof *f->output_data.ns);
1161   FRAME_FONTSET (f) = -1;
1163   fset_icon_name (f, x_get_arg (dpyinfo, parms, Qicon_name,
1164                                 "iconName", "Title",
1165                                 RES_TYPE_STRING));
1166   if (! STRINGP (f->icon_name))
1167     fset_icon_name (f, Qnil);
1169   FRAME_DISPLAY_INFO (f) = dpyinfo;
1171   /* With FRAME_DISPLAY_INFO set up, this unwind-protect is safe.  */
1172   record_unwind_protect (unwind_create_frame, frame);
1174   f->output_data.ns->window_desc = desc_ctr++;
1175   if (TYPE_RANGED_INTEGERP (Window, parent))
1176     {
1177       f->output_data.ns->parent_desc = XFASTINT (parent);
1178       f->output_data.ns->explicit_parent = 1;
1179     }
1180   else
1181     {
1182       f->output_data.ns->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
1183       f->output_data.ns->explicit_parent = 0;
1184     }
1186   /* Set the name; the functions to which we pass f expect the name to
1187      be set.  */
1188   if (EQ (name, Qunbound) || NILP (name) || ! STRINGP (name))
1189     {
1190       fset_name (f, build_string ([ns_app_name UTF8String]));
1191       f->explicit_name = 0;
1192     }
1193   else
1194     {
1195       fset_name (f, name);
1196       f->explicit_name = 1;
1197       specbind (Qx_resource_name, name);
1198     }
1200   block_input ();
1202 #ifdef NS_IMPL_COCOA
1203     mac_register_font_driver (f);
1204 #else
1205     register_font_driver (&nsfont_driver, f);
1206 #endif
1208   image_cache_refcount =
1209     FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
1211   x_default_parameter (f, parms, Qfont_backend, Qnil,
1212                         "fontBackend", "FontBackend", RES_TYPE_STRING);
1214   {
1215     /* use for default font name */
1216     id font = [NSFont userFixedPitchFontOfSize: -1.0]; /* default */
1217     x_default_parameter (f, parms, Qfontsize,
1218                                     make_number (0 /*(int)[font pointSize]*/),
1219                                     "fontSize", "FontSize", RES_TYPE_NUMBER);
1220     // Remove ' Regular', not handled by backends.
1221     char *fontname = xstrdup ([[font displayName] UTF8String]);
1222     int len = strlen (fontname);
1223     if (len > 8 && strcmp (fontname + len - 8, " Regular") == 0)
1224       fontname[len-8] = '\0';
1225     x_default_parameter (f, parms, Qfont,
1226                                  build_string (fontname),
1227                                  "font", "Font", RES_TYPE_STRING);
1228     xfree (fontname);
1229   }
1230   unblock_input ();
1232   x_default_parameter (f, parms, Qborder_width, make_number (0),
1233                        "borderwidth", "BorderWidth", RES_TYPE_NUMBER);
1234   x_default_parameter (f, parms, Qinternal_border_width, make_number (2),
1235                       "internalBorderWidth", "InternalBorderWidth",
1236                       RES_TYPE_NUMBER);
1238   /* default vertical scrollbars on right on Mac */
1239   {
1240       Lisp_Object spos
1241 #ifdef NS_IMPL_GNUSTEP
1242           = Qt;
1243 #else
1244           = Qright;
1245 #endif
1246       x_default_parameter (f, parms, Qvertical_scroll_bars, spos,
1247                            "verticalScrollBars", "VerticalScrollBars",
1248                            RES_TYPE_SYMBOL);
1249   }
1250   x_default_parameter (f, parms, Qhorizontal_scroll_bars, Qnil,
1251                        "horizontalScrollBars", "HorizontalScrollBars",
1252                        RES_TYPE_SYMBOL);
1253   x_default_parameter (f, parms, Qforeground_color, build_string ("Black"),
1254                       "foreground", "Foreground", RES_TYPE_STRING);
1255   x_default_parameter (f, parms, Qbackground_color, build_string ("White"),
1256                       "background", "Background", RES_TYPE_STRING);
1257   /* FIXME: not supported yet in Nextstep */
1258   x_default_parameter (f, parms, Qline_spacing, Qnil,
1259                        "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
1260   x_default_parameter (f, parms, Qleft_fringe, Qnil,
1261                        "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
1262   x_default_parameter (f, parms, Qright_fringe, Qnil,
1263                        "rightFringe", "RightFringe", RES_TYPE_NUMBER);
1264   x_default_parameter (f, parms, Qno_special_glyphs, Qnil,
1265                        NULL, NULL, RES_TYPE_BOOLEAN);
1267   init_frame_faces (f);
1269   /* Read comment about this code in corresponding place in xfns.c.  */
1270   tem = x_get_arg (dpyinfo, parms, Qmin_width, NULL, NULL, RES_TYPE_NUMBER);
1271   if (NUMBERP (tem))
1272     store_frame_param (f, Qmin_width, tem);
1273   tem = x_get_arg (dpyinfo, parms, Qmin_height, NULL, NULL, RES_TYPE_NUMBER);
1274   if (NUMBERP (tem))
1275     store_frame_param (f, Qmin_height, tem);
1276   adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
1277                      FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 5, 1,
1278                      Qx_create_frame_1);
1280   tem = x_get_arg (dpyinfo, parms, Qundecorated, NULL, NULL, RES_TYPE_BOOLEAN);
1281   FRAME_UNDECORATED (f) = !NILP (tem) && !EQ (tem, Qunbound);
1282   store_frame_param (f, Qundecorated, FRAME_UNDECORATED (f) ? Qt : Qnil);
1284 #ifdef NS_IMPL_COCOA
1285   tem = x_get_arg (dpyinfo, parms, Qns_appearance, NULL, NULL, RES_TYPE_SYMBOL);
1286   FRAME_NS_APPEARANCE (f) = EQ (tem, Qdark)
1287     ? ns_appearance_vibrant_dark : ns_appearance_aqua;
1288   store_frame_param (f, Qns_appearance, tem);
1290   tem = x_get_arg (dpyinfo, parms, Qns_transparent_titlebar,
1291                    NULL, NULL, RES_TYPE_BOOLEAN);
1292   FRAME_NS_TRANSPARENT_TITLEBAR (f) = !NILP (tem) && !EQ (tem, Qunbound);
1293   store_frame_param (f, Qns_transparent_titlebar, tem);
1294 #endif
1296   parent_frame = x_get_arg (dpyinfo, parms, Qparent_frame, NULL, NULL,
1297                             RES_TYPE_SYMBOL);
1298   /* Accept parent-frame iff parent-id was not specified.  */
1299   if (!NILP (parent)
1300       || EQ (parent_frame, Qunbound)
1301       || NILP (parent_frame)
1302       || !FRAMEP (parent_frame)
1303       || !FRAME_LIVE_P (XFRAME (parent_frame)))
1304     parent_frame = Qnil;
1306   fset_parent_frame (f, parent_frame);
1307   store_frame_param (f, Qparent_frame, parent_frame);
1309   x_default_parameter (f, parms, Qz_group, Qnil, NULL, NULL, RES_TYPE_SYMBOL);
1310   x_default_parameter (f, parms, Qno_focus_on_map, Qnil,
1311                        NULL, NULL, RES_TYPE_BOOLEAN);
1312   x_default_parameter (f, parms, Qno_accept_focus, Qnil,
1313                        NULL, NULL, RES_TYPE_BOOLEAN);
1315   /* The resources controlling the menu-bar and tool-bar are
1316      processed specially at startup, and reflected in the mode
1317      variables; ignore them here.  */
1318   x_default_parameter (f, parms, Qmenu_bar_lines,
1319                        NILP (Vmenu_bar_mode)
1320                        ? make_number (0) : make_number (1),
1321                        NULL, NULL, RES_TYPE_NUMBER);
1322   x_default_parameter (f, parms, Qtool_bar_lines,
1323                        NILP (Vtool_bar_mode)
1324                        ? make_number (0) : make_number (1),
1325                        NULL, NULL, RES_TYPE_NUMBER);
1327   x_default_parameter (f, parms, Qbuffer_predicate, Qnil, "bufferPredicate",
1328                        "BufferPredicate", RES_TYPE_SYMBOL);
1329   x_default_parameter (f, parms, Qtitle, Qnil, "title", "Title",
1330                        RES_TYPE_STRING);
1332   parms = get_geometry_from_preferences (dpyinfo, parms);
1333   window_prompting = x_figure_window_size (f, parms, true, &x_width, &x_height);
1335   tem = x_get_arg (dpyinfo, parms, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
1336   f->no_split = minibuffer_only || (!EQ (tem, Qunbound) && !EQ (tem, Qnil));
1338   /* NOTE: on other terms, this is done in set_mouse_color, however this
1339      was not getting called under Nextstep */
1340   f->output_data.ns->text_cursor = [NSCursor IBeamCursor];
1341   f->output_data.ns->nontext_cursor = [NSCursor arrowCursor];
1342   f->output_data.ns->modeline_cursor = [NSCursor pointingHandCursor];
1343   f->output_data.ns->hand_cursor = [NSCursor pointingHandCursor];
1344   f->output_data.ns->hourglass_cursor = [NSCursor disappearingItemCursor];
1345   f->output_data.ns->horizontal_drag_cursor = [NSCursor resizeLeftRightCursor];
1346   f->output_data.ns->vertical_drag_cursor = [NSCursor resizeUpDownCursor];
1347   f->output_data.ns->left_edge_cursor = [NSCursor resizeLeftRightCursor];
1348   f->output_data.ns->top_left_corner_cursor = [NSCursor arrowCursor];
1349   f->output_data.ns->top_edge_cursor = [NSCursor resizeUpDownCursor];
1350   f->output_data.ns->top_right_corner_cursor = [NSCursor arrowCursor];
1351   f->output_data.ns->right_edge_cursor = [NSCursor resizeLeftRightCursor];
1352   f->output_data.ns->bottom_right_corner_cursor = [NSCursor arrowCursor];
1353   f->output_data.ns->bottom_edge_cursor = [NSCursor resizeUpDownCursor];
1354   f->output_data.ns->bottom_left_corner_cursor = [NSCursor arrowCursor];
1356   FRAME_DISPLAY_INFO (f)->vertical_scroll_bar_cursor
1357      = [NSCursor arrowCursor];
1358   FRAME_DISPLAY_INFO (f)->horizontal_scroll_bar_cursor
1359      = [NSCursor arrowCursor];
1360   f->output_data.ns->current_pointer = f->output_data.ns->text_cursor;
1362   f->output_data.ns->in_animation = NO;
1364   [[EmacsView alloc] initFrameFromEmacs: f];
1366   x_icon (f, parms);
1368   /* ns_display_info does not have a reference_count.  */
1369   f->terminal->reference_count++;
1371   /* It is now ok to make the frame official even if we get an error below.
1372      The frame needs to be on Vframe_list or making it visible won't work. */
1373   Vframe_list = Fcons (frame, Vframe_list);
1375   x_default_parameter (f, parms, Qicon_type, Qnil,
1376                        "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
1378   x_default_parameter (f, parms, Qauto_raise, Qnil,
1379                        "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
1380   x_default_parameter (f, parms, Qauto_lower, Qnil,
1381                        "autoLower", "AutoLower", RES_TYPE_BOOLEAN);
1382   x_default_parameter (f, parms, Qcursor_type, Qbox,
1383                        "cursorType", "CursorType", RES_TYPE_SYMBOL);
1384   x_default_parameter (f, parms, Qscroll_bar_width, Qnil,
1385                        "scrollBarWidth", "ScrollBarWidth",
1386                        RES_TYPE_NUMBER);
1387   x_default_parameter (f, parms, Qscroll_bar_height, Qnil,
1388                        "scrollBarHeight", "ScrollBarHeight",
1389                        RES_TYPE_NUMBER);
1390   x_default_parameter (f, parms, Qalpha, Qnil,
1391                        "alpha", "Alpha", RES_TYPE_NUMBER);
1392   x_default_parameter (f, parms, Qfullscreen, Qnil,
1393                        "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
1395   /* Allow x_set_window_size, now.  */
1396   f->can_x_set_window_size = true;
1398   if (x_width > 0)
1399     SET_FRAME_WIDTH (f, x_width);
1400   if (x_height > 0)
1401     SET_FRAME_HEIGHT (f, x_height);
1403   adjust_frame_size (f, FRAME_TEXT_WIDTH (f), FRAME_TEXT_HEIGHT (f), 0, 1,
1404                      Qx_create_frame_2);
1406   if (! f->output_data.ns->explicit_parent)
1407     {
1408       Lisp_Object visibility;
1410       visibility = x_get_arg (dpyinfo, parms, Qvisibility, 0, 0,
1411                               RES_TYPE_SYMBOL);
1412       if (EQ (visibility, Qunbound))
1413         visibility = Qt;
1415       if (EQ (visibility, Qicon))
1416         x_iconify_frame (f);
1417       else if (! NILP (visibility))
1418         {
1419           x_make_frame_visible (f);
1420           [[FRAME_NS_VIEW (f) window] makeKeyWindow];
1421         }
1422       else
1423         {
1424           /* Must have been Qnil.  */
1425         }
1426     }
1428   if (FRAME_HAS_MINIBUF_P (f)
1429       && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
1430           || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
1431     kset_default_minibuffer_frame (kb, frame);
1433   /* All remaining specified parameters, which have not been "used"
1434      by x_get_arg and friends, now go in the misc. alist of the frame.  */
1435   for (tem = parms; CONSP (tem); tem = XCDR (tem))
1436     if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
1437       fset_param_alist (f, Fcons (XCAR (tem), f->param_alist));
1439   if (window_prompting & USPosition)
1440     x_set_offset (f, f->left_pos, f->top_pos, 1);
1442   /* Make sure windows on this frame appear in calls to next-window
1443      and similar functions.  */
1444   Vwindow_list = Qnil;
1446   return unbind_to (count, frame);
1449 void
1450 x_focus_frame (struct frame *f, bool noactivate)
1452   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1454   if (dpyinfo->x_focus_frame != f)
1455     {
1456       EmacsView *view = FRAME_NS_VIEW (f);
1457       block_input ();
1458       [NSApp activateIgnoringOtherApps: YES];
1459       [[view window] makeKeyAndOrderFront: view];
1460       unblock_input ();
1461     }
1464 static BOOL
1465 ns_window_is_ancestor (NSWindow *win, NSWindow *candidate)
1466 /* Test whether CANDIDATE is an ancestor window of WIN. */
1468   if (candidate == NULL)
1469     return NO;
1470   else if (win == candidate)
1471     return YES;
1472   else
1473     return ns_window_is_ancestor(win, [candidate parentWindow]);
1476 DEFUN ("ns-frame-list-z-order", Fns_frame_list_z_order,
1477        Sns_frame_list_z_order, 0, 1, 0,
1478        doc: /* Return list of Emacs' frames, in Z (stacking) order.
1479 The optional argument TERMINAL specifies which display to ask about.
1480 TERMINAL should be either a frame or a display name (a string).  If
1481 omitted or nil, that stands for the selected frame's display.  Return
1482 nil if TERMINAL contains no Emacs frame.
1484 As a special case, if TERMINAL is non-nil and specifies a live frame,
1485 return the child frames of that frame in Z (stacking) order.
1487 Frames are listed from topmost (first) to bottommost (last).  */)
1488   (Lisp_Object terminal)
1490   Lisp_Object frames = Qnil;
1491   NSWindow *parent = nil;
1493   if (FRAMEP (terminal) && FRAME_LIVE_P (XFRAME (terminal)))
1494     parent = [FRAME_NS_VIEW (XFRAME (terminal)) window];
1495   else if (!NILP (terminal))
1496     return Qnil;
1498   for (NSWindow *win in [[NSApp orderedWindows] reverseObjectEnumerator])
1499     {
1500       Lisp_Object frame;
1502       /* Check against [win parentWindow] so that it doesn't match itself. */
1503       if (parent == nil || ns_window_is_ancestor (parent, [win parentWindow]))
1504         {
1505           XSETFRAME (frame, ((EmacsView *)[win delegate])->emacsframe);
1506           frames = Fcons(frame, frames);
1507         }
1508     }
1510   return frames;
1513 DEFUN ("ns-frame-restack", Fns_frame_restack, Sns_frame_restack, 2, 3, 0,
1514        doc: /* Restack FRAME1 below FRAME2.
1515 This means that if both frames are visible and the display areas of
1516 these frames overlap, FRAME2 (partially) obscures FRAME1.  If optional
1517 third argument ABOVE is non-nil, restack FRAME1 above FRAME2.  This
1518 means that if both frames are visible and the display areas of these
1519 frames overlap, FRAME1 (partially) obscures FRAME2.
1521 Some window managers may refuse to restack windows.  */)
1522      (Lisp_Object frame1, Lisp_Object frame2, Lisp_Object above)
1524   struct frame *f1 = decode_live_frame (frame1);
1525   struct frame *f2 = decode_live_frame (frame2);
1527   if (FRAME_NS_VIEW (f1) && FRAME_NS_VIEW (f2))
1528     {
1529       NSWindow *window = [FRAME_NS_VIEW (f1) window];
1530       NSInteger window2 = [[FRAME_NS_VIEW (f2) window] windowNumber];
1531       NSWindowOrderingMode flag = NILP (above) ? NSWindowBelow : NSWindowAbove;
1533       [window orderWindow: flag
1534                relativeTo: window2];
1536       return Qt;
1537     }
1538   else
1539     {
1540       error ("Cannot restack frames");
1541       return Qnil;
1542     }
1545 DEFUN ("ns-popup-font-panel", Fns_popup_font_panel, Sns_popup_font_panel,
1546        0, 1, "",
1547        doc: /* Pop up the font panel. */)
1548      (Lisp_Object frame)
1550   struct frame *f = decode_window_system_frame (frame);
1551   id fm = [NSFontManager sharedFontManager];
1552   struct font *font = f->output_data.ns->font;
1553   NSFont *nsfont;
1554 #ifdef NS_IMPL_GNUSTEP
1555   nsfont = ((struct nsfont_info *)font)->nsfont;
1556 #endif
1557 #ifdef NS_IMPL_COCOA
1558   nsfont = (NSFont *) macfont_get_nsctfont (font);
1559 #endif
1560   [fm setSelectedFont: nsfont isMultiple: NO];
1561   [fm orderFrontFontPanel: NSApp];
1562   return Qnil;
1566 DEFUN ("ns-popup-color-panel", Fns_popup_color_panel, Sns_popup_color_panel,
1567        0, 1, "",
1568        doc: /* Pop up the color panel.  */)
1569      (Lisp_Object frame)
1571   check_window_system (NULL);
1572   [NSApp orderFrontColorPanel: NSApp];
1573   return Qnil;
1576 static struct
1578   id panel;
1579   BOOL ret;
1580 #ifdef NS_IMPL_GNUSTEP
1581   NSString *dirS, *initS;
1582   BOOL no_types;
1583 #endif
1584 } ns_fd_data;
1586 void
1587 ns_run_file_dialog (void)
1589   if (ns_fd_data.panel == nil) return;
1590 #ifdef NS_IMPL_COCOA
1591   ns_fd_data.ret = [ns_fd_data.panel runModal];
1592 #else
1593   if (ns_fd_data.no_types)
1594     {
1595       ns_fd_data.ret = [ns_fd_data.panel
1596                            runModalForDirectory: ns_fd_data.dirS
1597                            file: ns_fd_data.initS];
1598     }
1599   else
1600     {
1601       ns_fd_data.ret = [ns_fd_data.panel
1602                            runModalForDirectory: ns_fd_data.dirS
1603                            file: ns_fd_data.initS
1604                            types: nil];
1605     }
1606 #endif
1607   ns_fd_data.panel = nil;
1610 #ifdef NS_IMPL_COCOA
1611 #if MAC_OS_X_VERSION_MAX_ALLOWED > 1090
1612 #define MODAL_OK_RESPONSE NSModalResponseOK
1613 #endif
1614 #endif
1615 #ifndef MODAL_OK_RESPONSE
1616 #define MODAL_OK_RESPONSE NSOKButton
1617 #endif
1619 DEFUN ("ns-read-file-name", Fns_read_file_name, Sns_read_file_name, 1, 5, 0,
1620        doc: /* Use a graphical panel to read a file name, using prompt PROMPT.
1621 Optional arg DIR, if non-nil, supplies a default directory.
1622 Optional arg MUSTMATCH, if non-nil, means the returned file or
1623 directory must exist.
1624 Optional arg INIT, if non-nil, provides a default file name to use.
1625 Optional arg DIR_ONLY_P, if non-nil, means choose only directories.  */)
1626   (Lisp_Object prompt, Lisp_Object dir, Lisp_Object mustmatch,
1627    Lisp_Object init, Lisp_Object dir_only_p)
1629   static id fileDelegate = nil;
1630   BOOL isSave = NILP (mustmatch) && NILP (dir_only_p);
1631   id panel;
1632   Lisp_Object fname = Qnil;
1634   NSString *promptS = NILP (prompt) || !STRINGP (prompt) ? nil :
1635     [NSString stringWithUTF8String: SSDATA (prompt)];
1636   NSString *dirS = NILP (dir) || !STRINGP (dir) ?
1637     [NSString stringWithUTF8String: SSDATA (BVAR (current_buffer, directory))] :
1638     [NSString stringWithUTF8String: SSDATA (dir)];
1639   NSString *initS = NILP (init) || !STRINGP (init) ? nil :
1640     [NSString stringWithUTF8String: SSDATA (init)];
1641   NSEvent *nxev;
1643   check_window_system (NULL);
1645   if (fileDelegate == nil)
1646     fileDelegate = [EmacsFileDelegate new];
1648   [NSCursor setHiddenUntilMouseMoves: NO];
1650   if ([dirS characterAtIndex: 0] == '~')
1651     dirS = [dirS stringByExpandingTildeInPath];
1653   panel = isSave ?
1654     (id)[EmacsSavePanel savePanel] : (id)[EmacsOpenPanel openPanel];
1656   [panel setTitle: promptS];
1658   [panel setAllowsOtherFileTypes: YES];
1659   [panel setTreatsFilePackagesAsDirectories: YES];
1660   [panel setDelegate: fileDelegate];
1662   if (! NILP (dir_only_p))
1663     {
1664       [panel setCanChooseDirectories: YES];
1665       [panel setCanChooseFiles: NO];
1666     }
1667   else if (! isSave)
1668     {
1669       /* This is not quite what the documentation says, but it is compatible
1670          with the Gtk+ code.  Also, the menu entry says "Open File...".  */
1671       [panel setCanChooseDirectories: NO];
1672       [panel setCanChooseFiles: YES];
1673     }
1675   block_input ();
1676   ns_fd_data.panel = panel;
1677   ns_fd_data.ret = NO;
1678 #ifdef NS_IMPL_COCOA
1679   if (! NILP (mustmatch) || ! NILP (dir_only_p))
1680     [panel setAllowedFileTypes: nil];
1681   if (dirS) [panel setDirectoryURL: [NSURL fileURLWithPath: dirS]];
1682   if (initS && NILP (Ffile_directory_p (init)))
1683     [panel setNameFieldStringValue: [initS lastPathComponent]];
1684   else
1685     [panel setNameFieldStringValue: @""];
1687 #else
1688   ns_fd_data.no_types = NILP (mustmatch) && NILP (dir_only_p);
1689   ns_fd_data.dirS = dirS;
1690   ns_fd_data.initS = initS;
1691 #endif
1693   /* runModalForDirectory/runModal restarts the main event loop when done,
1694      so we must start an event loop and then pop up the file dialog.
1695      The file dialog may pop up a confirm dialog after Ok has been pressed,
1696      so we can not simply pop down on the Ok/Cancel press.
1697    */
1698   nxev = [NSEvent otherEventWithType: NSEventTypeApplicationDefined
1699                             location: NSMakePoint (0, 0)
1700                        modifierFlags: 0
1701                            timestamp: 0
1702                         windowNumber: [[NSApp mainWindow] windowNumber]
1703                              context: [NSApp context]
1704                              subtype: 0
1705                                data1: 0
1706                                data2: NSAPP_DATA2_RUNFILEDIALOG];
1708   [NSApp postEvent: nxev atStart: NO];
1709   while (ns_fd_data.panel != nil)
1710     [NSApp run];
1712   if (ns_fd_data.ret == MODAL_OK_RESPONSE)
1713     {
1714       NSString *str = ns_filename_from_panel (panel);
1715       if (! str) str = ns_directory_from_panel (panel);
1716       if (str) fname = build_string ([str UTF8String]);
1717     }
1719   [[FRAME_NS_VIEW (SELECTED_FRAME ()) window] makeKeyWindow];
1720   unblock_input ();
1722   return fname;
1725 const char *
1726 ns_get_defaults_value (const char *key)
1728   NSObject *obj = [[NSUserDefaults standardUserDefaults]
1729                     objectForKey: [NSString stringWithUTF8String: key]];
1731   if (!obj) return NULL;
1733   return [[NSString stringWithFormat: @"%@", obj] UTF8String];
1737 DEFUN ("ns-get-resource", Fns_get_resource, Sns_get_resource, 2, 2, 0,
1738        doc: /* Return the value of the property NAME of OWNER from the defaults database.
1739 If OWNER is nil, Emacs is assumed.  */)
1740      (Lisp_Object owner, Lisp_Object name)
1742   const char *value;
1744   check_window_system (NULL);
1745   if (NILP (owner))
1746     owner = build_string([ns_app_name UTF8String]);
1747   CHECK_STRING (name);
1749   value = ns_get_defaults_value (SSDATA (name));
1751   if (value)
1752     return build_string (value);
1753   return Qnil;
1757 DEFUN ("ns-set-resource", Fns_set_resource, Sns_set_resource, 3, 3, 0,
1758        doc: /* Set property NAME of OWNER to VALUE, from the defaults database.
1759 If OWNER is nil, Emacs is assumed.
1760 If VALUE is nil, the default is removed.  */)
1761      (Lisp_Object owner, Lisp_Object name, Lisp_Object value)
1763   check_window_system (NULL);
1764   if (NILP (owner))
1765     owner = build_string ([ns_app_name UTF8String]);
1766   CHECK_STRING (name);
1767   if (NILP (value))
1768     {
1769       [[NSUserDefaults standardUserDefaults] removeObjectForKey:
1770                          [NSString stringWithUTF8String: SSDATA (name)]];
1771     }
1772   else
1773     {
1774       CHECK_STRING (value);
1775       [[NSUserDefaults standardUserDefaults] setObject:
1776                 [NSString stringWithUTF8String: SSDATA (value)]
1777                                         forKey: [NSString stringWithUTF8String:
1778                                                          SSDATA (name)]];
1779     }
1781   return Qnil;
1785 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
1786        Sx_server_max_request_size,
1787        0, 1, 0,
1788        doc: /* This function is a no-op.  It is only present for completeness.  */)
1789      (Lisp_Object terminal)
1791   check_ns_display_info (terminal);
1792   /* This function has no real equivalent under NeXTstep.  Return nil to
1793      indicate this. */
1794   return Qnil;
1798 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
1799        doc: /* Return the "vendor ID" string of Nextstep display server TERMINAL.
1800 \(Labeling every distributor as a "vendor" embodies the false assumption
1801 that operating systems cannot be developed and distributed noncommercially.)
1802 The optional argument TERMINAL specifies which display to ask about.
1803 TERMINAL should be a terminal object, a frame or a display name (a string).
1804 If omitted or nil, that stands for the selected frame's display.  */)
1805   (Lisp_Object terminal)
1807   check_ns_display_info (terminal);
1808 #ifdef NS_IMPL_GNUSTEP
1809   return build_string ("GNU");
1810 #else
1811   return build_string ("Apple");
1812 #endif
1816 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
1817        doc: /* Return the version numbers of the server of display TERMINAL.
1818 The value is a list of three integers: the major and minor
1819 version numbers of the X Protocol in use, and the distributor-specific release
1820 number.  See also the function `x-server-vendor'.
1822 The optional argument TERMINAL specifies which display to ask about.
1823 TERMINAL should be a terminal object, a frame or a display name (a string).
1824 If omitted or nil, that stands for the selected frame's display.  */)
1825   (Lisp_Object terminal)
1827   check_ns_display_info (terminal);
1828   /*NOTE: it is unclear what would best correspond with "protocol";
1829           we return 10.3, meaning Panther, since this is roughly the
1830           level that GNUstep's APIs correspond to.
1831           The last number is where we distinguish between the Apple
1832           and GNUstep implementations ("distributor-specific release
1833           number") and give int'ized versions of major.minor. */
1834   return list3i (10, 3, ns_appkit_version_int ());
1838 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
1839        doc: /* Return the number of screens on Nextstep display server TERMINAL.
1840 The optional argument TERMINAL specifies which display to ask about.
1841 TERMINAL should be a terminal object, a frame or a display name (a string).
1842 If omitted or nil, that stands for the selected frame's display.
1844 Note: "screen" here is not in Nextstep terminology but in X11's.  For
1845 the number of physical monitors, use `(length
1846 \(display-monitor-attributes-list TERMINAL))' instead.  */)
1847   (Lisp_Object terminal)
1849   check_ns_display_info (terminal);
1850   return make_number (1);
1854 DEFUN ("x-display-mm-height", Fx_display_mm_height, Sx_display_mm_height, 0, 1, 0,
1855        doc: /* Return the height in millimeters of the Nextstep display TERMINAL.
1856 The optional argument TERMINAL specifies which display to ask about.
1857 TERMINAL should be a terminal object, a frame or a display name (a string).
1858 If omitted or nil, that stands for the selected frame's display.
1860 On \"multi-monitor\" setups this refers to the height in millimeters for
1861 all physical monitors associated with TERMINAL.  To get information
1862 for each physical monitor, use `display-monitor-attributes-list'.  */)
1863   (Lisp_Object terminal)
1865   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
1867   return make_number (x_display_pixel_height (dpyinfo) / (92.0/25.4));
1871 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
1872        doc: /* Return the width in millimeters of the Nextstep display TERMINAL.
1873 The optional argument TERMINAL specifies which display to ask about.
1874 TERMINAL should be a terminal object, a frame or a display name (a string).
1875 If omitted or nil, that stands for the selected frame's display.
1877 On \"multi-monitor\" setups this refers to the width in millimeters for
1878 all physical monitors associated with TERMINAL.  To get information
1879 for each physical monitor, use `display-monitor-attributes-list'.  */)
1880   (Lisp_Object terminal)
1882   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
1884   return make_number (x_display_pixel_width (dpyinfo) / (92.0/25.4));
1888 DEFUN ("x-display-backing-store", Fx_display_backing_store,
1889        Sx_display_backing_store, 0, 1, 0,
1890        doc: /* Return an indication of whether the Nextstep display TERMINAL does backing store.
1891 The value may be `buffered', `retained', or `non-retained'.
1892 The optional argument TERMINAL specifies which display to ask about.
1893 TERMINAL should be a terminal object, a frame or a display name (a string).
1894 If omitted or nil, that stands for the selected frame's display.  */)
1895   (Lisp_Object terminal)
1897   check_ns_display_info (terminal);
1898   switch ([ns_get_window (terminal) backingType])
1899     {
1900     case NSBackingStoreBuffered:
1901       return intern ("buffered");
1902     case NSBackingStoreRetained:
1903       return intern ("retained");
1904     case NSBackingStoreNonretained:
1905       return intern ("non-retained");
1906     default:
1907       error ("Strange value for backingType parameter of frame");
1908     }
1909   return Qnil;  /* not reached, shut compiler up */
1913 DEFUN ("x-display-visual-class", Fx_display_visual_class,
1914        Sx_display_visual_class, 0, 1, 0,
1915        doc: /* Return the visual class of the Nextstep display TERMINAL.
1916 The value is one of the symbols `static-gray', `gray-scale',
1917 `static-color', `pseudo-color', `true-color', or `direct-color'.
1919 The optional argument TERMINAL specifies which display to ask about.
1920 TERMINAL should a terminal object, a frame or a display name (a string).
1921 If omitted or nil, that stands for the selected frame's display.  */)
1922   (Lisp_Object terminal)
1924   NSWindowDepth depth;
1926   check_ns_display_info (terminal);
1927   depth = [[[NSScreen screens] objectAtIndex:0] depth];
1929   if ( depth == NSBestDepth (NSCalibratedWhiteColorSpace, 2, 2, YES, NULL))
1930     return intern ("static-gray");
1931   else if (depth == NSBestDepth (NSCalibratedWhiteColorSpace, 8, 8, YES, NULL))
1932     return intern ("gray-scale");
1933   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 8, 8, YES, NULL))
1934     return intern ("pseudo-color");
1935   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 4, 12, NO, NULL))
1936     return intern ("true-color");
1937   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 8, 24, NO, NULL))
1938     return intern ("direct-color");
1939   else
1940     /* color mgmt as far as we do it is really handled by Nextstep itself anyway */
1941     return intern ("direct-color");
1945 DEFUN ("x-display-save-under", Fx_display_save_under,
1946        Sx_display_save_under, 0, 1, 0,
1947        doc: /* Return t if TERMINAL supports the save-under feature.
1948 The optional argument TERMINAL specifies which display to ask about.
1949 TERMINAL should be a terminal object, a frame or a display name (a string).
1950 If omitted or nil, that stands for the selected frame's display.  */)
1951   (Lisp_Object terminal)
1953   check_ns_display_info (terminal);
1954   switch ([ns_get_window (terminal) backingType])
1955     {
1956     case NSBackingStoreBuffered:
1957       return Qt;
1959     case NSBackingStoreRetained:
1960     case NSBackingStoreNonretained:
1961       return Qnil;
1963     default:
1964       error ("Strange value for backingType parameter of frame");
1965     }
1966   return Qnil;  /* not reached, shut compiler up */
1970 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
1971        1, 3, 0,
1972        doc: /* Open a connection to a display server.
1973 DISPLAY is the name of the display to connect to.
1974 Optional second arg XRM-STRING is a string of resources in xrdb format.
1975 If the optional third arg MUST-SUCCEED is non-nil,
1976 terminate Emacs if we can't open the connection.
1977 \(In the Nextstep version, the last two arguments are currently ignored.)  */)
1978      (Lisp_Object display, Lisp_Object resource_string, Lisp_Object must_succeed)
1980   struct ns_display_info *dpyinfo;
1982   CHECK_STRING (display);
1984   nxatoms_of_nsselect ();
1985   dpyinfo = ns_term_init (display);
1986   if (dpyinfo == 0)
1987     {
1988       if (!NILP (must_succeed))
1989         fatal ("Display on %s not responding.\n",
1990                SSDATA (display));
1991       else
1992         error ("Display on %s not responding.\n",
1993                SSDATA (display));
1994     }
1996   return Qnil;
2000 DEFUN ("x-close-connection", Fx_close_connection, Sx_close_connection,
2001        1, 1, 0,
2002        doc: /* Close the connection to TERMINAL's Nextstep display server.
2003 For TERMINAL, specify a terminal object, a frame or a display name (a
2004 string).  If TERMINAL is nil, that stands for the selected frame's
2005 terminal.  */)
2006      (Lisp_Object terminal)
2008   check_ns_display_info (terminal);
2009   [NSApp terminate: NSApp];
2010   return Qnil;
2014 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
2015        doc: /* Return the list of display names that Emacs has connections to.  */)
2016      (void)
2018   Lisp_Object result = Qnil;
2019   struct ns_display_info *ndi;
2021   for (ndi = x_display_list; ndi; ndi = ndi->next)
2022     result = Fcons (XCAR (ndi->name_list_element), result);
2024   return result;
2028 DEFUN ("ns-hide-others", Fns_hide_others, Sns_hide_others,
2029        0, 0, 0,
2030        doc: /* Hides all applications other than Emacs.  */)
2031      (void)
2033   check_window_system (NULL);
2034   [NSApp hideOtherApplications: NSApp];
2035   return Qnil;
2038 DEFUN ("ns-hide-emacs", Fns_hide_emacs, Sns_hide_emacs,
2039        1, 1, 0,
2040        doc: /* If ON is non-nil, the entire Emacs application is hidden.
2041 Otherwise if Emacs is hidden, it is unhidden.
2042 If ON is equal to `activate', Emacs is unhidden and becomes
2043 the active application.  */)
2044      (Lisp_Object on)
2046   check_window_system (NULL);
2047   if (EQ (on, intern ("activate")))
2048     {
2049       [NSApp unhide: NSApp];
2050       [NSApp activateIgnoringOtherApps: YES];
2051     }
2052   else if (NILP (on))
2053     [NSApp unhide: NSApp];
2054   else
2055     [NSApp hide: NSApp];
2056   return Qnil;
2060 DEFUN ("ns-emacs-info-panel", Fns_emacs_info_panel, Sns_emacs_info_panel,
2061        0, 0, 0,
2062        doc: /* Shows the 'Info' or 'About' panel for Emacs.  */)
2063      (void)
2065   check_window_system (NULL);
2066   [NSApp orderFrontStandardAboutPanel: nil];
2067   return Qnil;
2071 DEFUN ("ns-font-name", Fns_font_name, Sns_font_name, 1, 1, 0,
2072        doc: /* Determine font PostScript or family name for font NAME.
2073 NAME should be a string containing either the font name or an XLFD
2074 font descriptor.  If string contains `fontset' and not
2075 `fontset-startup', it is left alone. */)
2076      (Lisp_Object name)
2078   char *nm;
2079   CHECK_STRING (name);
2080   nm = SSDATA (name);
2082   if (nm[0] != '-')
2083     return name;
2084   if (strstr (nm, "fontset") && !strstr (nm, "fontset-startup"))
2085     return name;
2087   return build_string (ns_xlfd_to_fontname (SSDATA (name)));
2091 DEFUN ("ns-list-colors", Fns_list_colors, Sns_list_colors, 0, 1, 0,
2092        doc: /* Return a list of all available colors.
2093 The optional argument FRAME is currently ignored.  */)
2094      (Lisp_Object frame)
2096   Lisp_Object list = Qnil;
2097   NSEnumerator *colorlists;
2098   NSColorList *clist;
2100   if (!NILP (frame))
2101     {
2102       CHECK_FRAME (frame);
2103       if (! FRAME_NS_P (XFRAME (frame)))
2104         error ("non-Nextstep frame used in `ns-list-colors'");
2105     }
2107   block_input ();
2109   colorlists = [[NSColorList availableColorLists] objectEnumerator];
2110   while ((clist = [colorlists nextObject]))
2111     {
2112       if ([[clist name] length] < 7 ||
2113           [[clist name] rangeOfString: @"PANTONE"].location == 0)
2114         {
2115           NSEnumerator *cnames = [[clist allKeys] reverseObjectEnumerator];
2116           NSString *cname;
2117           while ((cname = [cnames nextObject]))
2118             list = Fcons (build_string ([cname UTF8String]), list);
2119 /*           for (i = [[clist allKeys] count] - 1; i >= 0; i--)
2120                list = Fcons (build_string ([[[clist allKeys] objectAtIndex: i]
2121                                              UTF8String]), list); */
2122         }
2123     }
2125   unblock_input ();
2127   return list;
2131 DEFUN ("ns-list-services", Fns_list_services, Sns_list_services, 0, 0, 0,
2132        doc: /* List available Nextstep services by querying NSApp.  */)
2133      (void)
2135 #ifdef NS_IMPL_COCOA
2136   /* You can't get services like this in 10.6+.  */
2137   return Qnil;
2138 #else
2139   Lisp_Object ret = Qnil;
2140   NSMenu *svcs;
2142   check_window_system (NULL);
2143   svcs = [[NSMenu alloc] initWithTitle: @"Services"];
2144   [NSApp setServicesMenu: svcs];
2145   [NSApp registerServicesMenuSendTypes: ns_send_types
2146                            returnTypes: ns_return_types];
2148   [svcs setAutoenablesItems: NO];
2150   ret = interpret_services_menu (svcs, Qnil, ret);
2151   return ret;
2152 #endif
2156 DEFUN ("ns-perform-service", Fns_perform_service, Sns_perform_service,
2157        2, 2, 0,
2158        doc: /* Perform Nextstep SERVICE on SEND.
2159 SEND should be either a string or nil.
2160 The return value is the result of the service, as string, or nil if
2161 there was no result.  */)
2162      (Lisp_Object service, Lisp_Object send)
2164   id pb;
2165   NSString *svcName;
2166   char *utfStr;
2168   CHECK_STRING (service);
2169   check_window_system (NULL);
2171   utfStr = SSDATA (service);
2172   svcName = [NSString stringWithUTF8String: utfStr];
2174   pb =[NSPasteboard pasteboardWithUniqueName];
2175   ns_string_to_pasteboard (pb, send);
2177   if (NSPerformService (svcName, pb) == NO)
2178     Fsignal (Qquit, list1 (build_string ("service not available")));
2180   if ([[pb types] count] == 0)
2181     return build_string ("");
2182   return ns_string_from_pasteboard (pb);
2186 #ifdef NS_IMPL_COCOA
2188 /* Compile and execute the AppleScript SCRIPT and return the error
2189    status as function value.  A zero is returned if compilation and
2190    execution is successful, in which case *RESULT is set to a Lisp
2191    string or a number containing the resulting script value.  Otherwise,
2192    1 is returned. */
2193 static int
2194 ns_do_applescript (Lisp_Object script, Lisp_Object *result)
2196   NSAppleEventDescriptor *desc;
2197   NSDictionary *errorDict;
2198   NSAppleEventDescriptor *returnDescriptor = NULL;
2200   NSAppleScript *scriptObject =
2201     [[NSAppleScript alloc] initWithSource:
2202                              [NSString stringWithUTF8String: SSDATA (script)]];
2204   returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
2205   [scriptObject release];
2206   *result = Qnil;
2208   if (returnDescriptor != NULL)
2209     {
2210       // successful execution
2211       if (kAENullEvent != [returnDescriptor descriptorType])
2212         {
2213           *result = Qt;
2214           // script returned an AppleScript result
2215           if ((typeUnicodeText == [returnDescriptor descriptorType]) ||
2216 #if defined (NS_IMPL_COCOA)
2217               (typeUTF16ExternalRepresentation
2218                == [returnDescriptor descriptorType]) ||
2219 #endif
2220               (typeUTF8Text == [returnDescriptor descriptorType]) ||
2221               (typeCString == [returnDescriptor descriptorType]))
2222             {
2223               desc = [returnDescriptor coerceToDescriptorType: typeUTF8Text];
2224               if (desc)
2225                 *result = build_string([[desc stringValue] UTF8String]);
2226             }
2227           else
2228             {
2229               /* use typeUTF16ExternalRepresentation? */
2230               // coerce the result to the appropriate ObjC type
2231               desc = [returnDescriptor coerceToDescriptorType: typeUTF8Text];
2232               if (desc)
2233                 *result = make_number([desc int32Value]);
2234             }
2235         }
2236     }
2237   else
2238     {
2239       // no script result, return error
2240       return 1;
2241     }
2242   return 0;
2245 /* Helper function called from sendEvent to run applescript
2246    from within the main event loop.  */
2248 void
2249 ns_run_ascript (void)
2251   if (! NILP (as_script))
2252     as_status = ns_do_applescript (as_script, as_result);
2253   as_script = Qnil;
2256 DEFUN ("ns-do-applescript", Fns_do_applescript, Sns_do_applescript, 1, 1, 0,
2257        doc: /* Execute AppleScript SCRIPT and return the result.
2258 If compilation and execution are successful, the resulting script value
2259 is returned as a string, a number or, in the case of other constructs, t.
2260 In case the execution fails, an error is signaled. */)
2261      (Lisp_Object script)
2263   Lisp_Object result;
2264   int status;
2265   NSEvent *nxev;
2266   struct input_event ev;
2268   CHECK_STRING (script);
2269   check_window_system (NULL);
2271   block_input ();
2273   as_script = script;
2274   as_result = &result;
2276   /* executing apple script requires the event loop to run, otherwise
2277      errors aren't returned and executeAndReturnError hangs forever.
2278      Post an event that runs applescript and then start the event loop.
2279      The event loop is exited when the script is done.  */
2280   nxev = [NSEvent otherEventWithType: NSEventTypeApplicationDefined
2281                             location: NSMakePoint (0, 0)
2282                        modifierFlags: 0
2283                            timestamp: 0
2284                         windowNumber: [[NSApp mainWindow] windowNumber]
2285                              context: [NSApp context]
2286                              subtype: 0
2287                                data1: 0
2288                                data2: NSAPP_DATA2_RUNASSCRIPT];
2290   [NSApp postEvent: nxev atStart: NO];
2292   // If there are other events, the event loop may exit.  Keep running
2293   // until the script has been handled.  */
2294   ns_init_events (&ev);
2295   while (! NILP (as_script))
2296     [NSApp run];
2297   ns_finish_events ();
2299   status = as_status;
2300   as_status = 0;
2301   as_result = 0;
2302   unblock_input ();
2303   if (status == 0)
2304     return result;
2305   else if (!STRINGP (result))
2306     error ("AppleScript error %d", status);
2307   else
2308     error ("%s", SSDATA (result));
2310 #endif
2314 /* ==========================================================================
2316     Miscellaneous functions not called through hooks
2318    ========================================================================== */
2320 /* called from frame.c */
2321 struct ns_display_info *
2322 check_x_display_info (Lisp_Object frame)
2324   return check_ns_display_info (frame);
2328 void
2329 x_set_scroll_bar_default_width (struct frame *f)
2331   int wid = FRAME_COLUMN_WIDTH (f);
2332   FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = NS_SCROLL_BAR_WIDTH_DEFAULT;
2333   FRAME_CONFIG_SCROLL_BAR_COLS (f) = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) +
2334                                       wid - 1) / wid;
2337 void
2338 x_set_scroll_bar_default_height (struct frame *f)
2340   int height = FRAME_LINE_HEIGHT (f);
2341   FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) = NS_SCROLL_BAR_WIDTH_DEFAULT;
2342   FRAME_CONFIG_SCROLL_BAR_LINES (f) = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) +
2343                                        height - 1) / height;
2346 /* terms impl this instead of x-get-resource directly */
2347 char *
2348 x_get_string_resource (XrmDatabase rdb, const char *name, const char *class)
2350   /* remove appname prefix; TODO: allow for !="Emacs" */
2351   const char *res, *toCheck = class + (!strncmp (class, "Emacs.", 6) ? 6 : 0);
2353   check_window_system (NULL);
2355   if (inhibit_x_resources)
2356     /* --quick was passed, so this is a no-op.  */
2357     return NULL;
2359   res = ns_get_defaults_value (toCheck);
2360   return (char *) (!res ? NULL
2361                    : !c_strncasecmp (res, "YES", 3) ? "true"
2362                    : !c_strncasecmp (res, "NO", 2) ? "false"
2363                    : res);
2367 Lisp_Object
2368 x_get_focus_frame (struct frame *frame)
2370   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
2371   Lisp_Object nsfocus;
2373   if (!dpyinfo->x_focus_frame)
2374     return Qnil;
2376   XSETFRAME (nsfocus, dpyinfo->x_focus_frame);
2377   return nsfocus;
2380 /* ==========================================================================
2382     Lisp definitions that, for whatever reason, we can't alias as 'ns-XXX'.
2384    ========================================================================== */
2387 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
2388        doc: /* Internal function called by `color-defined-p', which see.
2389 \(Note that the Nextstep version of this function ignores FRAME.)  */)
2390      (Lisp_Object color, Lisp_Object frame)
2392   NSColor * col;
2393   check_window_system (NULL);
2394   return ns_lisp_to_color (color, &col) ? Qnil : Qt;
2398 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
2399        doc: /* Internal function called by `color-values', which see.  */)
2400      (Lisp_Object color, Lisp_Object frame)
2402   NSColor * col;
2403   EmacsCGFloat red, green, blue, alpha;
2405   check_window_system (NULL);
2406   CHECK_STRING (color);
2408   block_input ();
2409   if (ns_lisp_to_color (color, &col))
2410     {
2411       unblock_input ();
2412       return Qnil;
2413     }
2415   [[col colorUsingDefaultColorSpace]
2416         getRed: &red green: &green blue: &blue alpha: &alpha];
2417   unblock_input ();
2418   return list3i (lrint (red * 65280), lrint (green * 65280),
2419                  lrint (blue * 65280));
2423 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
2424        doc: /* Internal function called by `display-color-p', which see.  */)
2425      (Lisp_Object terminal)
2427   NSWindowDepth depth;
2428   NSString *colorSpace;
2430   check_ns_display_info (terminal);
2431   depth = [[[NSScreen screens] objectAtIndex:0] depth];
2432   colorSpace = NSColorSpaceFromDepth (depth);
2434   return    [colorSpace isEqualToString: NSDeviceWhiteColorSpace]
2435          || [colorSpace isEqualToString: NSCalibratedWhiteColorSpace]
2436       ? Qnil : Qt;
2440 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p, Sx_display_grayscale_p,
2441        0, 1, 0,
2442        doc: /* Return t if the Nextstep display supports shades of gray.
2443 Note that color displays do support shades of gray.
2444 The optional argument TERMINAL specifies which display to ask about.
2445 TERMINAL should be a terminal object, a frame or a display name (a string).
2446 If omitted or nil, that stands for the selected frame's display.  */)
2447   (Lisp_Object terminal)
2449   NSWindowDepth depth;
2451   check_ns_display_info (terminal);
2452   depth = [[[NSScreen screens] objectAtIndex:0] depth];
2454   return NSBitsPerPixelFromDepth (depth) > 1 ? Qt : Qnil;
2458 DEFUN ("x-display-pixel-width", Fx_display_pixel_width, Sx_display_pixel_width,
2459        0, 1, 0,
2460        doc: /* Return the width in pixels of the Nextstep display TERMINAL.
2461 The optional argument TERMINAL specifies which display to ask about.
2462 TERMINAL should be a terminal object, a frame or a display name (a string).
2463 If omitted or nil, that stands for the selected frame's display.
2465 On \"multi-monitor\" setups this refers to the pixel width for all
2466 physical monitors associated with TERMINAL.  To get information for
2467 each physical monitor, use `display-monitor-attributes-list'.  */)
2468   (Lisp_Object terminal)
2470   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
2472   return make_number (x_display_pixel_width (dpyinfo));
2476 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
2477        Sx_display_pixel_height, 0, 1, 0,
2478        doc: /* Return the height in pixels of the Nextstep display TERMINAL.
2479 The optional argument TERMINAL specifies which display to ask about.
2480 TERMINAL should be a terminal object, a frame or a display name (a string).
2481 If omitted or nil, that stands for the selected frame's display.
2483 On \"multi-monitor\" setups this refers to the pixel height for all
2484 physical monitors associated with TERMINAL.  To get information for
2485 each physical monitor, use `display-monitor-attributes-list'.  */)
2486   (Lisp_Object terminal)
2488   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
2490   return make_number (x_display_pixel_height (dpyinfo));
2493 #ifdef NS_IMPL_COCOA
2495 /* Returns the name for the screen that OBJ represents, or NULL.
2496    Caller must free return value.
2499 static char *
2500 ns_get_name_from_ioreg (io_object_t obj)
2502   char *name = NULL;
2504   NSDictionary *info = (NSDictionary *)
2505     IODisplayCreateInfoDictionary (obj, kIODisplayOnlyPreferredName);
2506   NSDictionary *names = [info objectForKey:
2507                                 [NSString stringWithUTF8String:
2508                                             kDisplayProductName]];
2510   if ([names count] > 0)
2511     {
2512       NSString *n = [names objectForKey: [[names allKeys]
2513                                                  objectAtIndex:0]];
2514       if (n != nil) name = xstrdup ([n UTF8String]);
2515     }
2517   [info release];
2519   return name;
2522 /* Returns the name for the screen that DID came from, or NULL.
2523    Caller must free return value.
2526 static char *
2527 ns_screen_name (CGDirectDisplayID did)
2529   char *name = NULL;
2531 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1090
2532 #if MAC_OS_X_VERSION_MIN_REQUIRED < 1090
2533   if (CGDisplayIOServicePort == NULL)
2534 #endif
2535     {
2536       mach_port_t masterPort;
2537       io_iterator_t it;
2538       io_object_t obj;
2540       /* CGDisplayIOServicePort is deprecated.  Do it another (harder) way.
2542          Is this code OK for macOS < 10.9, and GNUstep?  I suspect it is,
2543          in which case is it worth keeping the other method in here? */
2545       if (IOMasterPort (MACH_PORT_NULL, &masterPort) != kIOReturnSuccess
2546           || IOServiceGetMatchingServices (masterPort,
2547                                            IOServiceMatching ("IONDRVDevice"),
2548                                            &it) != kIOReturnSuccess)
2549         return name;
2551       /* Must loop until we find a name.  Many devices can have the same unit
2552          number (represents different GPU parts), but only one has a name.  */
2553       while (! name && (obj = IOIteratorNext (it)))
2554         {
2555           CFMutableDictionaryRef props;
2556           const void *val;
2558           if (IORegistryEntryCreateCFProperties (obj,
2559                                                  &props,
2560                                                  kCFAllocatorDefault,
2561                                                  kNilOptions) == kIOReturnSuccess
2562               && props != nil
2563               && (val = CFDictionaryGetValue(props, @"IOFBDependentIndex")))
2564             {
2565               unsigned nr = [(NSNumber *)val unsignedIntegerValue];
2566               if (nr == CGDisplayUnitNumber (did))
2567                 name = ns_get_name_from_ioreg (obj);
2568             }
2570           CFRelease (props);
2571           IOObjectRelease (obj);
2572         }
2574       IOObjectRelease (it);
2575     }
2576 #if MAC_OS_X_VERSION_MIN_REQUIRED < 1090
2577   else
2578 #endif
2579 #endif /* #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1090 */
2580 #if MAC_OS_X_VERSION_MIN_REQUIRED < 1090
2581     name = ns_get_name_from_ioreg (CGDisplayIOServicePort (did));
2582 #endif
2583   return name;
2585 #endif /* NS_IMPL_COCOA */
2587 static Lisp_Object
2588 ns_make_monitor_attribute_list (struct MonitorInfo *monitors,
2589                                 int n_monitors,
2590                                 int primary_monitor,
2591                                 const char *source)
2593   Lisp_Object monitor_frames = Fmake_vector (make_number (n_monitors), Qnil);
2594   Lisp_Object frame, rest;
2595   NSArray *screens = [NSScreen screens];
2596   int i;
2598   FOR_EACH_FRAME (rest, frame)
2599     {
2600       struct frame *f = XFRAME (frame);
2602       if (FRAME_NS_P (f))
2603         {
2604           NSView *view = FRAME_NS_VIEW (f);
2605           NSScreen *screen = [[view window] screen];
2606           NSUInteger k;
2608           i = -1;
2609           for (k = 0; i == -1 && k < [screens count]; ++k)
2610             {
2611               if ([screens objectAtIndex: k] == screen)
2612                 i = (int)k;
2613             }
2615           if (i > -1)
2616             ASET (monitor_frames, i, Fcons (frame, AREF (monitor_frames, i)));
2617         }
2618     }
2620   return make_monitor_attribute_list (monitors, n_monitors, primary_monitor,
2621                                       monitor_frames, source);
2624 DEFUN ("ns-display-monitor-attributes-list",
2625        Fns_display_monitor_attributes_list,
2626        Sns_display_monitor_attributes_list,
2627        0, 1, 0,
2628        doc: /* Return a list of physical monitor attributes on the X display TERMINAL.
2630 The optional argument TERMINAL specifies which display to ask about.
2631 TERMINAL should be a terminal object, a frame or a display name (a string).
2632 If omitted or nil, that stands for the selected frame's display.
2634 In addition to the standard attribute keys listed in
2635 `display-monitor-attributes-list', the following keys are contained in
2636 the attributes:
2638  source -- String describing the source from which multi-monitor
2639            information is obtained, \"NS\" is always the source."
2641 Internal use only, use `display-monitor-attributes-list' instead.  */)
2642   (Lisp_Object terminal)
2644   struct terminal *term = decode_live_terminal (terminal);
2645   NSArray *screens;
2646   NSUInteger i, n_monitors;
2647   struct MonitorInfo *monitors;
2648   Lisp_Object attributes_list = Qnil;
2649   CGFloat primary_display_height = 0;
2651   if (term->type != output_ns)
2652     return Qnil;
2654   screens = [NSScreen screens];
2655   n_monitors = [screens count];
2656   if (n_monitors == 0)
2657     return Qnil;
2659   monitors = xzalloc (n_monitors * sizeof *monitors);
2661   for (i = 0; i < [screens count]; ++i)
2662     {
2663       NSScreen *s = [screens objectAtIndex:i];
2664       struct MonitorInfo *m = &monitors[i];
2665       NSRect fr = [s frame];
2666       NSRect vfr = [s visibleFrame];
2667       short y, vy;
2669 #ifdef NS_IMPL_COCOA
2670       NSDictionary *dict = [s deviceDescription];
2671       NSNumber *nid = [dict objectForKey:@"NSScreenNumber"];
2672       CGDirectDisplayID did = [nid unsignedIntValue];
2673 #endif
2674       if (i == 0)
2675         {
2676           primary_display_height = fr.size.height;
2677           y = (short) fr.origin.y;
2678           vy = (short) vfr.origin.y;
2679         }
2680       else
2681         {
2682           // Flip y coordinate as NS has y starting from the bottom.
2683           y = (short) (primary_display_height - fr.size.height - fr.origin.y);
2684           vy = (short) (primary_display_height -
2685                         vfr.size.height - vfr.origin.y);
2686         }
2688       m->geom.x = (short) fr.origin.x;
2689       m->geom.y = y;
2690       m->geom.width = (unsigned short) fr.size.width;
2691       m->geom.height = (unsigned short) fr.size.height;
2693       m->work.x = (short) vfr.origin.x;
2694       // y is flipped on NS, so vy - y are pixels missing at the bottom,
2695       // and fr.size.height - vfr.size.height are pixels missing in total.
2696       // Pixels missing at top are
2697       // fr.size.height - vfr.size.height - vy + y.
2698       // work.y is then pixels missing at top + y.
2699       m->work.y = (short) (fr.size.height - vfr.size.height) - vy + y + y;
2700       m->work.width = (unsigned short) vfr.size.width;
2701       m->work.height = (unsigned short) vfr.size.height;
2703 #ifdef NS_IMPL_COCOA
2704       m->name = ns_screen_name (did);
2706       {
2707         CGSize mms = CGDisplayScreenSize (did);
2708         m->mm_width = (int) mms.width;
2709         m->mm_height = (int) mms.height;
2710       }
2712 #else
2713       // Assume 92 dpi as x-display-mm-height/x-display-mm-width does.
2714       m->mm_width = (int) (25.4 * fr.size.width / 92.0);
2715       m->mm_height = (int) (25.4 * fr.size.height / 92.0);
2716 #endif
2717     }
2719   // Primary monitor is always first for NS.
2720   attributes_list = ns_make_monitor_attribute_list (monitors, n_monitors,
2721                                                     0, "NS");
2723   free_monitors (monitors, n_monitors);
2724   return attributes_list;
2728 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
2729        0, 1, 0,
2730        doc: /* Return the number of bitplanes of the Nextstep display TERMINAL.
2731 The optional argument TERMINAL specifies which display to ask about.
2732 TERMINAL should be a terminal object, a frame or a display name (a string).
2733 If omitted or nil, that stands for the selected frame's display.  */)
2734   (Lisp_Object terminal)
2736   check_ns_display_info (terminal);
2737   return make_number
2738     (NSBitsPerPixelFromDepth ([[[NSScreen screens] objectAtIndex:0] depth]));
2742 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
2743        0, 1, 0,
2744        doc: /* Returns the number of color cells of the Nextstep display TERMINAL.
2745 The optional argument TERMINAL specifies which display to ask about.
2746 TERMINAL should be a terminal object, a frame or a display name (a string).
2747 If omitted or nil, that stands for the selected frame's display.  */)
2748   (Lisp_Object terminal)
2750   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
2751   /* We force 24+ bit depths to 24-bit to prevent an overflow.  */
2752   return make_number (1 << min (dpyinfo->n_planes, 24));
2756 /* Unused dummy def needed for compatibility. */
2757 Lisp_Object tip_frame;
2759 /* TODO: move to xdisp or similar */
2760 static void
2761 compute_tip_xy (struct frame *f,
2762                 Lisp_Object parms,
2763                 Lisp_Object dx,
2764                 Lisp_Object dy,
2765                 int width,
2766                 int height,
2767                 int *root_x,
2768                 int *root_y)
2770   Lisp_Object left, top, right, bottom;
2771   NSPoint pt;
2772   NSScreen *screen;
2774   /* Start with user-specified or mouse position.  */
2775   left = Fcdr (Fassq (Qleft, parms));
2776   top = Fcdr (Fassq (Qtop, parms));
2777   right = Fcdr (Fassq (Qright, parms));
2778   bottom = Fcdr (Fassq (Qbottom, parms));
2780   if ((!INTEGERP (left) && !INTEGERP (right))
2781       || (!INTEGERP (top) && !INTEGERP (bottom)))
2782     pt = [NSEvent mouseLocation];
2783   else
2784     {
2785       /* Absolute coordinates.  */
2786       pt.x = INTEGERP (left) ? XINT (left) : XINT (right);
2787       pt.y = (x_display_pixel_height (FRAME_DISPLAY_INFO (f))
2788               - (INTEGERP (top) ? XINT (top) : XINT (bottom))
2789               - height);
2790     }
2792   /* Find the screen that pt is on. */
2793   for (screen in [NSScreen screens])
2794     if (pt.x >= screen.frame.origin.x
2795         && pt.x < screen.frame.origin.x + screen.frame.size.width
2796         && pt.y >= screen.frame.origin.y
2797         && pt.y < screen.frame.origin.y + screen.frame.size.height)
2798       break;
2800   /* We could use this instead of the if above:
2802          if (CGRectContainsPoint ([screen frame], pt))
2804      which would be neater, but it causes problems building on old
2805      versions of macOS and in GNUstep. */
2807   /* Ensure in bounds.  (Note, screen origin = lower left.) */
2808   if (INTEGERP (left) || INTEGERP (right))
2809     *root_x = pt.x;
2810   else if (pt.x + XINT (dx) <= screen.frame.origin.x)
2811     *root_x = screen.frame.origin.x; /* Can happen for negative dx */
2812   else if (pt.x + XINT (dx) + width
2813            <= screen.frame.origin.x + screen.frame.size.width)
2814     /* It fits to the right of the pointer.  */
2815     *root_x = pt.x + XINT (dx);
2816   else if (width + XINT (dx) <= pt.x)
2817     /* It fits to the left of the pointer.  */
2818     *root_x = pt.x - width - XINT (dx);
2819   else
2820     /* Put it left justified on the screen -- it ought to fit that way.  */
2821     *root_x = screen.frame.origin.x;
2823   if (INTEGERP (top) || INTEGERP (bottom))
2824     *root_y = pt.y;
2825   else if (pt.y - XINT (dy) - height >= screen.frame.origin.y)
2826     /* It fits below the pointer.  */
2827     *root_y = pt.y - height - XINT (dy);
2828   else if (pt.y + XINT (dy) + height
2829            <= screen.frame.origin.y + screen.frame.size.height)
2830     /* It fits above the pointer */
2831       *root_y = pt.y + XINT (dy);
2832   else
2833     /* Put it on the top.  */
2834     *root_y = screen.frame.origin.y + screen.frame.size.height - height;
2838 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
2839        doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
2840 A tooltip window is a small window displaying a string.
2842 This is an internal function; Lisp code should call `tooltip-show'.
2844 FRAME nil or omitted means use the selected frame.
2846 PARMS is an optional list of frame parameters which can be used to
2847 change the tooltip's appearance.
2849 Automatically hide the tooltip after TIMEOUT seconds.  TIMEOUT nil
2850 means use the default timeout of 5 seconds.
2852 If the list of frame parameters PARMS contains a `left' parameter,
2853 display the tooltip at that x-position.  If the list of frame parameters
2854 PARMS contains no `left' but a `right' parameter, display the tooltip
2855 right-adjusted at that x-position. Otherwise display it at the
2856 x-position of the mouse, with offset DX added (default is 5 if DX isn't
2857 specified).
2859 Likewise for the y-position: If a `top' frame parameter is specified, it
2860 determines the position of the upper edge of the tooltip window.  If a
2861 `bottom' parameter but no `top' frame parameter is specified, it
2862 determines the position of the lower edge of the tooltip window.
2863 Otherwise display the tooltip window at the y-position of the mouse,
2864 with offset DY added (default is -10).
2866 A tooltip's maximum size is specified by `x-max-tooltip-size'.
2867 Text larger than the specified size is clipped.  */)
2868      (Lisp_Object string, Lisp_Object frame, Lisp_Object parms, Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
2870   int root_x, root_y;
2871   ptrdiff_t count = SPECPDL_INDEX ();
2872   struct frame *f;
2873   char *str;
2874   NSSize size;
2876   specbind (Qinhibit_redisplay, Qt);
2878   CHECK_STRING (string);
2879   str = SSDATA (string);
2880   f = decode_window_system_frame (frame);
2881   if (NILP (timeout))
2882     timeout = make_number (5);
2883   else
2884     CHECK_NATNUM (timeout);
2886   if (NILP (dx))
2887     dx = make_number (5);
2888   else
2889     CHECK_NUMBER (dx);
2891   if (NILP (dy))
2892     dy = make_number (-10);
2893   else
2894     CHECK_NUMBER (dy);
2896   block_input ();
2897   if (ns_tooltip == nil)
2898     ns_tooltip = [[EmacsTooltip alloc] init];
2899   else
2900     Fx_hide_tip ();
2902   [ns_tooltip setText: str];
2903   size = [ns_tooltip frame].size;
2905   /* Move the tooltip window where the mouse pointer is.  Resize and
2906      show it.  */
2907   compute_tip_xy (f, parms, dx, dy, (int)size.width, (int)size.height,
2908                   &root_x, &root_y);
2910   [ns_tooltip showAtX: root_x Y: root_y for: XINT (timeout)];
2911   unblock_input ();
2913   return unbind_to (count, Qnil);
2917 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
2918        doc: /* Hide the current tooltip window, if there is any.
2919 Value is t if tooltip was open, nil otherwise.  */)
2920      (void)
2922   if (ns_tooltip == nil || ![ns_tooltip isActive])
2923     return Qnil;
2924   [ns_tooltip hide];
2925   return Qt;
2928 /* Return geometric attributes of FRAME.  According to the value of
2929    ATTRIBUTES return the outer edges of FRAME (Qouter_edges), the inner
2930    edges of FRAME, the root window edges of frame (Qroot_edges).  Any
2931    other value means to return the geometry as returned by
2932    Fx_frame_geometry.  */
2933 static Lisp_Object
2934 frame_geometry (Lisp_Object frame, Lisp_Object attribute)
2936   struct frame *f = decode_live_frame (frame);
2937   Lisp_Object fullscreen_symbol = Fframe_parameter (frame, Qfullscreen);
2938   bool fullscreen = (EQ (fullscreen_symbol, Qfullboth)
2939                      || EQ (fullscreen_symbol, Qfullscreen));
2940   int border = fullscreen ? 0 : f->border_width;
2941   int title_height = fullscreen ? 0 : FRAME_NS_TITLEBAR_HEIGHT (f);
2942   int native_width = FRAME_PIXEL_WIDTH (f);
2943   int native_height = FRAME_PIXEL_HEIGHT (f);
2944   int outer_width = native_width + 2 * border;
2945   int outer_height = native_height + 2 * border + title_height;
2946   int native_left = f->left_pos + border;
2947   int native_top = f->top_pos + border + title_height;
2948   int native_right = f->left_pos + outer_width - border;
2949   int native_bottom = f->top_pos + outer_height - border;
2950   int internal_border_width = FRAME_INTERNAL_BORDER_WIDTH (f);
2951   int tool_bar_height = FRAME_TOOLBAR_HEIGHT (f);
2952   int tool_bar_width = (tool_bar_height
2953                         ? outer_width - 2 * internal_border_width
2954                         : 0);
2956   /* Construct list.  */
2957   if (EQ (attribute, Qouter_edges))
2958     return list4 (make_number (f->left_pos), make_number (f->top_pos),
2959                   make_number (f->left_pos + outer_width),
2960                   make_number (f->top_pos + outer_height));
2961   else if (EQ (attribute, Qnative_edges))
2962     return list4 (make_number (native_left), make_number (native_top),
2963                   make_number (native_right), make_number (native_bottom));
2964   else if (EQ (attribute, Qinner_edges))
2965     return list4 (make_number (native_left + internal_border_width),
2966                   make_number (native_top
2967                                + tool_bar_height
2968                                + internal_border_width),
2969                   make_number (native_right - internal_border_width),
2970                   make_number (native_bottom - internal_border_width));
2971   else
2972     return
2973       listn (CONSTYPE_HEAP, 10,
2974              Fcons (Qouter_position,
2975                     Fcons (make_number (f->left_pos),
2976                            make_number (f->top_pos))),
2977              Fcons (Qouter_size,
2978                     Fcons (make_number (outer_width),
2979                            make_number (outer_height))),
2980              Fcons (Qexternal_border_size,
2981                     (fullscreen
2982                      ? Fcons (make_number (0), make_number (0))
2983                      : Fcons (make_number (border), make_number (border)))),
2984              Fcons (Qtitle_bar_size,
2985                     Fcons (make_number (0), make_number (title_height))),
2986              Fcons (Qmenu_bar_external, Qnil),
2987              Fcons (Qmenu_bar_size, Fcons (make_number (0), make_number (0))),
2988              Fcons (Qtool_bar_external,
2989                     FRAME_EXTERNAL_TOOL_BAR (f) ? Qt : Qnil),
2990              Fcons (Qtool_bar_position, FRAME_TOOL_BAR_POSITION (f)),
2991              Fcons (Qtool_bar_size,
2992                     Fcons (make_number (tool_bar_width),
2993                            make_number (tool_bar_height))),
2994              Fcons (Qinternal_border_width,
2995                     make_number (internal_border_width)));
2998 DEFUN ("ns-frame-geometry", Fns_frame_geometry, Sns_frame_geometry, 0, 1, 0,
2999        doc: /* Return geometric attributes of FRAME.
3000 FRAME must be a live frame and defaults to the selected one.  The return
3001 value is an association list of the attributes listed below.  All height
3002 and width values are in pixels.
3004 `outer-position' is a cons of the outer left and top edges of FRAME
3005   relative to the origin - the position (0, 0) - of FRAME's display.
3007 `outer-size' is a cons of the outer width and height of FRAME.  The
3008   outer size includes the title bar and the external borders as well as
3009   any menu and/or tool bar of frame.
3011 `external-border-size' is a cons of the horizontal and vertical width of
3012   FRAME's external borders as supplied by the window manager.
3014 `title-bar-size' is a cons of the width and height of the title bar of
3015   FRAME as supplied by the window manager.  If both of them are zero,
3016   FRAME has no title bar.  If only the width is zero, Emacs was not
3017   able to retrieve the width information.
3019 `menu-bar-external', if non-nil, means the menu bar is external (never
3020   included in the inner edges of FRAME).
3022 `menu-bar-size' is a cons of the width and height of the menu bar of
3023   FRAME.
3025 `tool-bar-external', if non-nil, means the tool bar is external (never
3026   included in the inner edges of FRAME).
3028 `tool-bar-position' tells on which side the tool bar on FRAME is and can
3029   be one of `left', `top', `right' or `bottom'.  If this is nil, FRAME
3030   has no tool bar.
3032 `tool-bar-size' is a cons of the width and height of the tool bar of
3033   FRAME.
3035 `internal-border-width' is the width of the internal border of
3036   FRAME.  */)
3037   (Lisp_Object frame)
3039   return frame_geometry (frame, Qnil);
3042 DEFUN ("ns-frame-edges", Fns_frame_edges, Sns_frame_edges, 0, 2, 0,
3043        doc: /* Return edge coordinates of FRAME.
3044 FRAME must be a live frame and defaults to the selected one.  The return
3045 value is a list of the form (LEFT, TOP, RIGHT, BOTTOM).  All values are
3046 in pixels relative to the origin - the position (0, 0) - of FRAME's
3047 display.
3049 If optional argument TYPE is the symbol `outer-edges', return the outer
3050 edges of FRAME.  The outer edges comprise the decorations of the window
3051 manager (like the title bar or external borders) as well as any external
3052 menu or tool bar of FRAME.  If optional argument TYPE is the symbol
3053 `native-edges' or nil, return the native edges of FRAME.  The native
3054 edges exclude the decorations of the window manager and any external
3055 menu or tool bar of FRAME.  If TYPE is the symbol `inner-edges', return
3056 the inner edges of FRAME.  These edges exclude title bar, any borders,
3057 menu bar or tool bar of FRAME.  */)
3058   (Lisp_Object frame, Lisp_Object type)
3060   return frame_geometry (frame, ((EQ (type, Qouter_edges)
3061                                   || EQ (type, Qinner_edges))
3062                                  ? type
3063                                  : Qnative_edges));
3066 DEFUN ("ns-set-mouse-absolute-pixel-position",
3067        Fns_set_mouse_absolute_pixel_position,
3068        Sns_set_mouse_absolute_pixel_position, 2, 2, 0,
3069        doc: /* Move mouse pointer to absolute pixel position (X, Y).
3070 The coordinates X and Y are interpreted in pixels relative to a position
3071 \(0, 0) of the selected frame's display.  */)
3072        (Lisp_Object x, Lisp_Object y)
3074 #ifdef NS_IMPL_COCOA
3075   /* GNUstep doesn't support CGWarpMouseCursorPosition, so none of
3076      this will work. */
3077   struct frame *f = SELECTED_FRAME ();
3078   EmacsView *view = FRAME_NS_VIEW (f);
3079   NSScreen *screen = [[view window] screen];
3080   NSRect screen_frame = [screen frame];
3081   int mouse_x, mouse_y;
3083   NSScreen *primary_screen = [[NSScreen screens] objectAtIndex:0];
3084   NSRect primary_screen_frame = [primary_screen frame];
3085   CGFloat primary_screen_height = primary_screen_frame.size.height;
3087   if (FRAME_INITIAL_P (f) || !FRAME_NS_P (f))
3088     return Qnil;
3090   CHECK_TYPE_RANGED_INTEGER (int, x);
3091   CHECK_TYPE_RANGED_INTEGER (int, y);
3093   mouse_x = screen_frame.origin.x + XINT (x);
3095   if (screen == primary_screen)
3096     mouse_y = screen_frame.origin.y + XINT (y);
3097   else
3098     mouse_y = (primary_screen_height - screen_frame.size.height
3099                - screen_frame.origin.y) + XINT (y);
3101   CGPoint mouse_pos = CGPointMake(mouse_x, mouse_y);
3102   CGWarpMouseCursorPosition (mouse_pos);
3103 #endif /* NS_IMPL_COCOA */
3105   return Qnil;
3108 DEFUN ("ns-mouse-absolute-pixel-position",
3109        Fns_mouse_absolute_pixel_position,
3110        Sns_mouse_absolute_pixel_position, 0, 0, 0,
3111        doc: /* Return absolute position of mouse cursor in pixels.
3112 The position is returned as a cons cell (X . Y) of the
3113 coordinates of the mouse cursor position in pixels relative to a
3114 position (0, 0) of the selected frame's terminal. */)
3115      (void)
3117   struct frame *f = SELECTED_FRAME ();
3118   EmacsView *view = FRAME_NS_VIEW (f);
3119   NSScreen *screen = [[view window] screen];
3120   NSPoint pt = [NSEvent mouseLocation];
3122   return Fcons(make_number(pt.x - screen.frame.origin.x),
3123                make_number(screen.frame.size.height -
3124                            (pt.y - screen.frame.origin.y)));
3127 /* ==========================================================================
3129     Class implementations
3131    ========================================================================== */
3134   Handle arrow/function/control keys and copy/paste/cut in file dialogs.
3135   Return YES if handled, NO if not.
3136  */
3137 static BOOL
3138 handlePanelKeys (NSSavePanel *panel, NSEvent *theEvent)
3140   NSString *s;
3141   int i;
3142   BOOL ret = NO;
3144   if ([theEvent type] != NSEventTypeKeyDown) return NO;
3145   s = [theEvent characters];
3147   for (i = 0; i < [s length]; ++i)
3148     {
3149       int ch = (int) [s characterAtIndex: i];
3150       switch (ch)
3151         {
3152         case NSHomeFunctionKey:
3153         case NSDownArrowFunctionKey:
3154         case NSUpArrowFunctionKey:
3155         case NSLeftArrowFunctionKey:
3156         case NSRightArrowFunctionKey:
3157         case NSPageUpFunctionKey:
3158         case NSPageDownFunctionKey:
3159         case NSEndFunctionKey:
3160           /* Don't send command modified keys, as those are handled in the
3161              performKeyEquivalent method of the super class.
3162           */
3163           if (! ([theEvent modifierFlags] & NSEventModifierFlagCommand))
3164             {
3165               [panel sendEvent: theEvent];
3166               ret = YES;
3167             }
3168           break;
3169           /* As we don't have the standard key commands for
3170              copy/paste/cut/select-all in our edit menu, we must handle
3171              them here.  TODO: handle Emacs key bindings for copy/cut/select-all
3172              here, paste works, because we have that in our Edit menu.
3173              I.e. refactor out code in nsterm.m, keyDown: to figure out the
3174              correct modifier.
3175           */
3176         case 'x': // Cut
3177         case 'c': // Copy
3178         case 'v': // Paste
3179         case 'a': // Select all
3180           if ([theEvent modifierFlags] & NSEventModifierFlagCommand)
3181             {
3182               [NSApp sendAction:
3183                        (ch == 'x'
3184                         ? @selector(cut:)
3185                         : (ch == 'c'
3186                            ? @selector(copy:)
3187                            : (ch == 'v'
3188                               ? @selector(paste:)
3189                               : @selector(selectAll:))))
3190                              to:nil from:panel];
3191               ret = YES;
3192             }
3193         default:
3194           // Send all control keys, as the text field supports C-a, C-f, C-e
3195           // C-b and more.
3196           if ([theEvent modifierFlags] & NSEventModifierFlagControl)
3197             {
3198               [panel sendEvent: theEvent];
3199               ret = YES;
3200             }
3201           break;
3202         }
3203     }
3206   return ret;
3209 @implementation EmacsSavePanel
3210 - (BOOL)performKeyEquivalent:(NSEvent *)theEvent
3212   BOOL ret = handlePanelKeys (self, theEvent);
3213   if (! ret)
3214     ret = [super performKeyEquivalent:theEvent];
3215   return ret;
3217 @end
3220 @implementation EmacsOpenPanel
3221 - (BOOL)performKeyEquivalent:(NSEvent *)theEvent
3223   // NSOpenPanel inherits NSSavePanel, so passing self is OK.
3224   BOOL ret = handlePanelKeys (self, theEvent);
3225   if (! ret)
3226     ret = [super performKeyEquivalent:theEvent];
3227   return ret;
3229 @end
3232 @implementation EmacsFileDelegate
3233 /* --------------------------------------------------------------------------
3234    Delegate methods for Open/Save panels
3235    -------------------------------------------------------------------------- */
3236 - (BOOL)panel: (id)sender isValidFilename: (NSString *)filename
3238   return YES;
3240 - (BOOL)panel: (id)sender shouldShowFilename: (NSString *)filename
3242   return YES;
3244 - (NSString *)panel: (id)sender userEnteredFilename: (NSString *)filename
3245           confirmed: (BOOL)okFlag
3247   return filename;
3249 @end
3251 #endif
3254 /* ==========================================================================
3256     Lisp interface declaration
3258    ========================================================================== */
3261 void
3262 syms_of_nsfns (void)
3264   DEFSYM (Qfontsize, "fontsize");
3265   DEFSYM (Qframe_title_format, "frame-title-format");
3266   DEFSYM (Qicon_title_format, "icon-title-format");
3267   DEFSYM (Qdark, "dark");
3269   DEFVAR_LISP ("ns-icon-type-alist", Vns_icon_type_alist,
3270                doc: /* Alist of elements (REGEXP . IMAGE) for images of icons associated to frames.
3271 If the title of a frame matches REGEXP, then IMAGE.tiff is
3272 selected as the image of the icon representing the frame when it's
3273 miniaturized.  If an element is t, then Emacs tries to select an icon
3274 based on the filetype of the visited file.
3276 The images have to be installed in a folder called English.lproj in the
3277 Emacs folder.  You have to restart Emacs after installing new icons.
3279 Example: Install an icon Gnus.tiff and execute the following code
3281   (setq ns-icon-type-alist
3282         (append ns-icon-type-alist
3283                 \\='((\"^\\\\*\\\\(Group\\\\*$\\\\|Summary \\\\|Article\\\\*$\\\\)\"
3284                    . \"Gnus\"))))
3286 When you miniaturize a Group, Summary or Article frame, Gnus.tiff will
3287 be used as the image of the icon representing the frame.  */);
3288   Vns_icon_type_alist = list1 (Qt);
3290   DEFVAR_LISP ("ns-version-string", Vns_version_string,
3291                doc: /* Toolkit version for NS Windowing.  */);
3292   Vns_version_string = ns_appkit_version_str ();
3294   defsubr (&Sns_read_file_name);
3295   defsubr (&Sns_get_resource);
3296   defsubr (&Sns_set_resource);
3297   defsubr (&Sxw_display_color_p); /* this and next called directly by C code */
3298   defsubr (&Sx_display_grayscale_p);
3299   defsubr (&Sns_font_name);
3300   defsubr (&Sns_list_colors);
3301 #ifdef NS_IMPL_COCOA
3302   defsubr (&Sns_do_applescript);
3303 #endif
3304   defsubr (&Sxw_color_defined_p);
3305   defsubr (&Sxw_color_values);
3306   defsubr (&Sx_server_max_request_size);
3307   defsubr (&Sx_server_vendor);
3308   defsubr (&Sx_server_version);
3309   defsubr (&Sx_display_pixel_width);
3310   defsubr (&Sx_display_pixel_height);
3311   defsubr (&Sns_display_monitor_attributes_list);
3312   defsubr (&Sns_frame_geometry);
3313   defsubr (&Sns_frame_edges);
3314   defsubr (&Sns_frame_list_z_order);
3315   defsubr (&Sns_frame_restack);
3316   defsubr (&Sns_set_mouse_absolute_pixel_position);
3317   defsubr (&Sns_mouse_absolute_pixel_position);
3318   defsubr (&Sx_display_mm_width);
3319   defsubr (&Sx_display_mm_height);
3320   defsubr (&Sx_display_screens);
3321   defsubr (&Sx_display_planes);
3322   defsubr (&Sx_display_color_cells);
3323   defsubr (&Sx_display_visual_class);
3324   defsubr (&Sx_display_backing_store);
3325   defsubr (&Sx_display_save_under);
3326   defsubr (&Sx_create_frame);
3327   defsubr (&Sx_open_connection);
3328   defsubr (&Sx_close_connection);
3329   defsubr (&Sx_display_list);
3331   defsubr (&Sns_hide_others);
3332   defsubr (&Sns_hide_emacs);
3333   defsubr (&Sns_emacs_info_panel);
3334   defsubr (&Sns_list_services);
3335   defsubr (&Sns_perform_service);
3336   defsubr (&Sns_popup_font_panel);
3337   defsubr (&Sns_popup_color_panel);
3339   defsubr (&Sx_show_tip);
3340   defsubr (&Sx_hide_tip);
3342   as_status = 0;
3343   as_script = Qnil;
3344   as_result = 0;