Adapt shadowfile.el for Tramp (Bug#4526, Bug#4846)
[emacs.git] / src / nsfns.m
blobbd1e2283a0cd953bd0c20759a7360fd17772cb06
1 /* Functions for the NeXT/Open/GNUstep and macOS window system.
3 Copyright (C) 1989, 1992-1994, 2005-2006, 2008-2018 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);
1237   x_default_parameter (f, parms, Qright_divider_width, make_number (0),
1238                        NULL, NULL, RES_TYPE_NUMBER);
1239   x_default_parameter (f, parms, Qbottom_divider_width, make_number (0),
1240                        NULL, NULL, RES_TYPE_NUMBER);
1242   /* default vertical scrollbars on right on Mac */
1243   {
1244       Lisp_Object spos
1245 #ifdef NS_IMPL_GNUSTEP
1246           = Qt;
1247 #else
1248           = Qright;
1249 #endif
1250       x_default_parameter (f, parms, Qvertical_scroll_bars, spos,
1251                            "verticalScrollBars", "VerticalScrollBars",
1252                            RES_TYPE_SYMBOL);
1253   }
1254   x_default_parameter (f, parms, Qhorizontal_scroll_bars, Qnil,
1255                        "horizontalScrollBars", "HorizontalScrollBars",
1256                        RES_TYPE_SYMBOL);
1257   x_default_parameter (f, parms, Qforeground_color, build_string ("Black"),
1258                       "foreground", "Foreground", RES_TYPE_STRING);
1259   x_default_parameter (f, parms, Qbackground_color, build_string ("White"),
1260                       "background", "Background", RES_TYPE_STRING);
1261   /* FIXME: not supported yet in Nextstep */
1262   x_default_parameter (f, parms, Qline_spacing, Qnil,
1263                        "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
1264   x_default_parameter (f, parms, Qleft_fringe, Qnil,
1265                        "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
1266   x_default_parameter (f, parms, Qright_fringe, Qnil,
1267                        "rightFringe", "RightFringe", RES_TYPE_NUMBER);
1268   x_default_parameter (f, parms, Qno_special_glyphs, Qnil,
1269                        NULL, NULL, RES_TYPE_BOOLEAN);
1271   init_frame_faces (f);
1273   /* Read comment about this code in corresponding place in xfns.c.  */
1274   tem = x_get_arg (dpyinfo, parms, Qmin_width, NULL, NULL, RES_TYPE_NUMBER);
1275   if (NUMBERP (tem))
1276     store_frame_param (f, Qmin_width, tem);
1277   tem = x_get_arg (dpyinfo, parms, Qmin_height, NULL, NULL, RES_TYPE_NUMBER);
1278   if (NUMBERP (tem))
1279     store_frame_param (f, Qmin_height, tem);
1280   adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
1281                      FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 5, 1,
1282                      Qx_create_frame_1);
1284   tem = x_get_arg (dpyinfo, parms, Qundecorated, NULL, NULL, RES_TYPE_BOOLEAN);
1285   FRAME_UNDECORATED (f) = !NILP (tem) && !EQ (tem, Qunbound);
1286   store_frame_param (f, Qundecorated, FRAME_UNDECORATED (f) ? Qt : Qnil);
1288 #ifdef NS_IMPL_COCOA
1289   tem = x_get_arg (dpyinfo, parms, Qns_appearance, NULL, NULL, RES_TYPE_SYMBOL);
1290   FRAME_NS_APPEARANCE (f) = EQ (tem, Qdark)
1291     ? ns_appearance_vibrant_dark : ns_appearance_aqua;
1292   store_frame_param (f, Qns_appearance, tem);
1294   tem = x_get_arg (dpyinfo, parms, Qns_transparent_titlebar,
1295                    NULL, NULL, RES_TYPE_BOOLEAN);
1296   FRAME_NS_TRANSPARENT_TITLEBAR (f) = !NILP (tem) && !EQ (tem, Qunbound);
1297   store_frame_param (f, Qns_transparent_titlebar, tem);
1298 #endif
1300   parent_frame = x_get_arg (dpyinfo, parms, Qparent_frame, NULL, NULL,
1301                             RES_TYPE_SYMBOL);
1302   /* Accept parent-frame iff parent-id was not specified.  */
1303   if (!NILP (parent)
1304       || EQ (parent_frame, Qunbound)
1305       || NILP (parent_frame)
1306       || !FRAMEP (parent_frame)
1307       || !FRAME_LIVE_P (XFRAME (parent_frame)))
1308     parent_frame = Qnil;
1310   fset_parent_frame (f, parent_frame);
1311   store_frame_param (f, Qparent_frame, parent_frame);
1313   x_default_parameter (f, parms, Qz_group, Qnil, NULL, NULL, RES_TYPE_SYMBOL);
1314   x_default_parameter (f, parms, Qno_focus_on_map, Qnil,
1315                        NULL, NULL, RES_TYPE_BOOLEAN);
1316   x_default_parameter (f, parms, Qno_accept_focus, Qnil,
1317                        NULL, NULL, RES_TYPE_BOOLEAN);
1319   /* The resources controlling the menu-bar and tool-bar are
1320      processed specially at startup, and reflected in the mode
1321      variables; ignore them here.  */
1322   x_default_parameter (f, parms, Qmenu_bar_lines,
1323                        NILP (Vmenu_bar_mode)
1324                        ? make_number (0) : make_number (1),
1325                        NULL, NULL, RES_TYPE_NUMBER);
1326   x_default_parameter (f, parms, Qtool_bar_lines,
1327                        NILP (Vtool_bar_mode)
1328                        ? make_number (0) : make_number (1),
1329                        NULL, NULL, RES_TYPE_NUMBER);
1331   x_default_parameter (f, parms, Qbuffer_predicate, Qnil, "bufferPredicate",
1332                        "BufferPredicate", RES_TYPE_SYMBOL);
1333   x_default_parameter (f, parms, Qtitle, Qnil, "title", "Title",
1334                        RES_TYPE_STRING);
1336   parms = get_geometry_from_preferences (dpyinfo, parms);
1337   window_prompting = x_figure_window_size (f, parms, true, &x_width, &x_height);
1339   tem = x_get_arg (dpyinfo, parms, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
1340   f->no_split = minibuffer_only || (!EQ (tem, Qunbound) && !EQ (tem, Qnil));
1342   /* NOTE: on other terms, this is done in set_mouse_color, however this
1343      was not getting called under Nextstep */
1344   f->output_data.ns->text_cursor = [NSCursor IBeamCursor];
1345   f->output_data.ns->nontext_cursor = [NSCursor arrowCursor];
1346   f->output_data.ns->modeline_cursor = [NSCursor pointingHandCursor];
1347   f->output_data.ns->hand_cursor = [NSCursor pointingHandCursor];
1348   f->output_data.ns->hourglass_cursor = [NSCursor disappearingItemCursor];
1349   f->output_data.ns->horizontal_drag_cursor = [NSCursor resizeLeftRightCursor];
1350   f->output_data.ns->vertical_drag_cursor = [NSCursor resizeUpDownCursor];
1351   f->output_data.ns->left_edge_cursor = [NSCursor resizeLeftRightCursor];
1352   f->output_data.ns->top_left_corner_cursor = [NSCursor arrowCursor];
1353   f->output_data.ns->top_edge_cursor = [NSCursor resizeUpDownCursor];
1354   f->output_data.ns->top_right_corner_cursor = [NSCursor arrowCursor];
1355   f->output_data.ns->right_edge_cursor = [NSCursor resizeLeftRightCursor];
1356   f->output_data.ns->bottom_right_corner_cursor = [NSCursor arrowCursor];
1357   f->output_data.ns->bottom_edge_cursor = [NSCursor resizeUpDownCursor];
1358   f->output_data.ns->bottom_left_corner_cursor = [NSCursor arrowCursor];
1360   FRAME_DISPLAY_INFO (f)->vertical_scroll_bar_cursor
1361      = [NSCursor arrowCursor];
1362   FRAME_DISPLAY_INFO (f)->horizontal_scroll_bar_cursor
1363      = [NSCursor arrowCursor];
1364   f->output_data.ns->current_pointer = f->output_data.ns->text_cursor;
1366   f->output_data.ns->in_animation = NO;
1368   [[EmacsView alloc] initFrameFromEmacs: f];
1370   x_icon (f, parms);
1372   /* ns_display_info does not have a reference_count.  */
1373   f->terminal->reference_count++;
1375   /* It is now ok to make the frame official even if we get an error below.
1376      The frame needs to be on Vframe_list or making it visible won't work. */
1377   Vframe_list = Fcons (frame, Vframe_list);
1379   x_default_parameter (f, parms, Qicon_type, Qnil,
1380                        "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
1382   x_default_parameter (f, parms, Qauto_raise, Qnil,
1383                        "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
1384   x_default_parameter (f, parms, Qauto_lower, Qnil,
1385                        "autoLower", "AutoLower", RES_TYPE_BOOLEAN);
1386   x_default_parameter (f, parms, Qcursor_type, Qbox,
1387                        "cursorType", "CursorType", RES_TYPE_SYMBOL);
1388   x_default_parameter (f, parms, Qscroll_bar_width, Qnil,
1389                        "scrollBarWidth", "ScrollBarWidth",
1390                        RES_TYPE_NUMBER);
1391   x_default_parameter (f, parms, Qscroll_bar_height, Qnil,
1392                        "scrollBarHeight", "ScrollBarHeight",
1393                        RES_TYPE_NUMBER);
1394   x_default_parameter (f, parms, Qalpha, Qnil,
1395                        "alpha", "Alpha", RES_TYPE_NUMBER);
1396   x_default_parameter (f, parms, Qfullscreen, Qnil,
1397                        "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
1399   /* Allow x_set_window_size, now.  */
1400   f->can_x_set_window_size = true;
1402   if (x_width > 0)
1403     SET_FRAME_WIDTH (f, x_width);
1404   if (x_height > 0)
1405     SET_FRAME_HEIGHT (f, x_height);
1407   adjust_frame_size (f, FRAME_TEXT_WIDTH (f), FRAME_TEXT_HEIGHT (f), 0, 1,
1408                      Qx_create_frame_2);
1410   if (! f->output_data.ns->explicit_parent)
1411     {
1412       Lisp_Object visibility;
1414       visibility = x_get_arg (dpyinfo, parms, Qvisibility, 0, 0,
1415                               RES_TYPE_SYMBOL);
1416       if (EQ (visibility, Qunbound))
1417         visibility = Qt;
1419       if (EQ (visibility, Qicon))
1420         x_iconify_frame (f);
1421       else if (! NILP (visibility))
1422         {
1423           x_make_frame_visible (f);
1424           [[FRAME_NS_VIEW (f) window] makeKeyWindow];
1425         }
1426       else
1427         {
1428           /* Must have been Qnil.  */
1429         }
1430     }
1432   if (FRAME_HAS_MINIBUF_P (f)
1433       && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
1434           || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
1435     kset_default_minibuffer_frame (kb, frame);
1437   /* All remaining specified parameters, which have not been "used"
1438      by x_get_arg and friends, now go in the misc. alist of the frame.  */
1439   for (tem = parms; CONSP (tem); tem = XCDR (tem))
1440     if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
1441       fset_param_alist (f, Fcons (XCAR (tem), f->param_alist));
1443   if (window_prompting & USPosition)
1444     x_set_offset (f, f->left_pos, f->top_pos, 1);
1446   /* Make sure windows on this frame appear in calls to next-window
1447      and similar functions.  */
1448   Vwindow_list = Qnil;
1450   return unbind_to (count, frame);
1453 void
1454 x_focus_frame (struct frame *f, bool noactivate)
1456   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1458   if (dpyinfo->x_focus_frame != f)
1459     {
1460       EmacsView *view = FRAME_NS_VIEW (f);
1461       block_input ();
1462       [NSApp activateIgnoringOtherApps: YES];
1463       [[view window] makeKeyAndOrderFront: view];
1464       unblock_input ();
1465     }
1468 static BOOL
1469 ns_window_is_ancestor (NSWindow *win, NSWindow *candidate)
1470 /* Test whether CANDIDATE is an ancestor window of WIN. */
1472   if (candidate == NULL)
1473     return NO;
1474   else if (win == candidate)
1475     return YES;
1476   else
1477     return ns_window_is_ancestor(win, [candidate parentWindow]);
1480 DEFUN ("ns-frame-list-z-order", Fns_frame_list_z_order,
1481        Sns_frame_list_z_order, 0, 1, 0,
1482        doc: /* Return list of Emacs' frames, in Z (stacking) order.
1483 If TERMINAL is non-nil and specifies a live frame, return the child
1484 frames of that frame in Z (stacking) order.
1486 Frames are listed from topmost (first) to bottommost (last).  */)
1487   (Lisp_Object terminal)
1489   Lisp_Object frames = Qnil;
1490   NSWindow *parent = nil;
1492   if (FRAMEP (terminal) && FRAME_LIVE_P (XFRAME (terminal)))
1493     parent = [FRAME_NS_VIEW (XFRAME (terminal)) window];
1495   for (NSWindow *win in [[NSApp orderedWindows] reverseObjectEnumerator])
1496     {
1497       Lisp_Object frame;
1499       /* Check against [win parentWindow] so that it doesn't match itself. */
1500       if ([[win delegate] isKindOfClass:[EmacsView class]]
1501           && (parent == nil || ns_window_is_ancestor (parent, [win parentWindow])))
1502         {
1503           XSETFRAME (frame, ((EmacsView *)[win delegate])->emacsframe);
1504           frames = Fcons(frame, frames);
1505         }
1506     }
1508   return frames;
1511 DEFUN ("ns-frame-restack", Fns_frame_restack, Sns_frame_restack, 2, 3, 0,
1512        doc: /* Restack FRAME1 below FRAME2.
1513 This means that if both frames are visible and the display areas of
1514 these frames overlap, FRAME2 (partially) obscures FRAME1.  If optional
1515 third argument ABOVE is non-nil, restack FRAME1 above FRAME2.  This
1516 means that if both frames are visible and the display areas of these
1517 frames overlap, FRAME1 (partially) obscures FRAME2.
1519 Some window managers may refuse to restack windows.  */)
1520      (Lisp_Object frame1, Lisp_Object frame2, Lisp_Object above)
1522   struct frame *f1 = decode_live_frame (frame1);
1523   struct frame *f2 = decode_live_frame (frame2);
1525   if (FRAME_NS_VIEW (f1) && FRAME_NS_VIEW (f2))
1526     {
1527       NSWindow *window = [FRAME_NS_VIEW (f1) window];
1528       NSInteger window2 = [[FRAME_NS_VIEW (f2) window] windowNumber];
1529       NSWindowOrderingMode flag = NILP (above) ? NSWindowBelow : NSWindowAbove;
1531       [window orderWindow: flag
1532                relativeTo: window2];
1534       return Qt;
1535     }
1536   else
1537     {
1538       error ("Cannot restack frames");
1539       return Qnil;
1540     }
1543 DEFUN ("ns-popup-font-panel", Fns_popup_font_panel, Sns_popup_font_panel,
1544        0, 1, "",
1545        doc: /* Pop up the font panel. */)
1546      (Lisp_Object frame)
1548   struct frame *f = decode_window_system_frame (frame);
1549   id fm = [NSFontManager sharedFontManager];
1550   struct font *font = f->output_data.ns->font;
1551   NSFont *nsfont;
1552 #ifdef NS_IMPL_GNUSTEP
1553   nsfont = ((struct nsfont_info *)font)->nsfont;
1554 #endif
1555 #ifdef NS_IMPL_COCOA
1556   nsfont = (NSFont *) macfont_get_nsctfont (font);
1557 #endif
1558   [fm setSelectedFont: nsfont isMultiple: NO];
1559   [fm orderFrontFontPanel: NSApp];
1560   return Qnil;
1564 DEFUN ("ns-popup-color-panel", Fns_popup_color_panel, Sns_popup_color_panel,
1565        0, 1, "",
1566        doc: /* Pop up the color panel.  */)
1567      (Lisp_Object frame)
1569   check_window_system (NULL);
1570   [NSApp orderFrontColorPanel: NSApp];
1571   return Qnil;
1574 static struct
1576   id panel;
1577   BOOL ret;
1578 #ifdef NS_IMPL_GNUSTEP
1579   NSString *dirS, *initS;
1580   BOOL no_types;
1581 #endif
1582 } ns_fd_data;
1584 void
1585 ns_run_file_dialog (void)
1587   if (ns_fd_data.panel == nil) return;
1588 #ifdef NS_IMPL_COCOA
1589   ns_fd_data.ret = [ns_fd_data.panel runModal];
1590 #else
1591   if (ns_fd_data.no_types)
1592     {
1593       ns_fd_data.ret = [ns_fd_data.panel
1594                            runModalForDirectory: ns_fd_data.dirS
1595                            file: ns_fd_data.initS];
1596     }
1597   else
1598     {
1599       ns_fd_data.ret = [ns_fd_data.panel
1600                            runModalForDirectory: ns_fd_data.dirS
1601                            file: ns_fd_data.initS
1602                            types: nil];
1603     }
1604 #endif
1605   ns_fd_data.panel = nil;
1608 #ifdef NS_IMPL_COCOA
1609 #if MAC_OS_X_VERSION_MAX_ALLOWED > 1090
1610 #define MODAL_OK_RESPONSE NSModalResponseOK
1611 #endif
1612 #endif
1613 #ifndef MODAL_OK_RESPONSE
1614 #define MODAL_OK_RESPONSE NSOKButton
1615 #endif
1617 DEFUN ("ns-read-file-name", Fns_read_file_name, Sns_read_file_name, 1, 5, 0,
1618        doc: /* Use a graphical panel to read a file name, using prompt PROMPT.
1619 Optional arg DIR, if non-nil, supplies a default directory.
1620 Optional arg MUSTMATCH, if non-nil, means the returned file or
1621 directory must exist.
1622 Optional arg INIT, if non-nil, provides a default file name to use.
1623 Optional arg DIR_ONLY_P, if non-nil, means choose only directories.  */)
1624   (Lisp_Object prompt, Lisp_Object dir, Lisp_Object mustmatch,
1625    Lisp_Object init, Lisp_Object dir_only_p)
1627   static id fileDelegate = nil;
1628   BOOL isSave = NILP (mustmatch) && NILP (dir_only_p);
1629   id panel;
1630   Lisp_Object fname = Qnil;
1632   NSString *promptS = NILP (prompt) || !STRINGP (prompt) ? nil :
1633     [NSString stringWithUTF8String: SSDATA (prompt)];
1634   NSString *dirS = NILP (dir) || !STRINGP (dir) ?
1635     [NSString stringWithUTF8String: SSDATA (BVAR (current_buffer, directory))] :
1636     [NSString stringWithUTF8String: SSDATA (dir)];
1637   NSString *initS = NILP (init) || !STRINGP (init) ? nil :
1638     [NSString stringWithUTF8String: SSDATA (init)];
1639   NSEvent *nxev;
1641   check_window_system (NULL);
1643   if (fileDelegate == nil)
1644     fileDelegate = [EmacsFileDelegate new];
1646   [NSCursor setHiddenUntilMouseMoves: NO];
1648   if ([dirS characterAtIndex: 0] == '~')
1649     dirS = [dirS stringByExpandingTildeInPath];
1651   panel = isSave ?
1652     (id)[EmacsSavePanel savePanel] : (id)[EmacsOpenPanel openPanel];
1654   [panel setTitle: promptS];
1656   [panel setAllowsOtherFileTypes: YES];
1657   [panel setTreatsFilePackagesAsDirectories: YES];
1658   [panel setDelegate: fileDelegate];
1660   if (! NILP (dir_only_p))
1661     {
1662       [panel setCanChooseDirectories: YES];
1663       [panel setCanChooseFiles: NO];
1664     }
1665   else if (! isSave)
1666     {
1667       /* This is not quite what the documentation says, but it is compatible
1668          with the Gtk+ code.  Also, the menu entry says "Open File...".  */
1669       [panel setCanChooseDirectories: NO];
1670       [panel setCanChooseFiles: YES];
1671     }
1673   block_input ();
1674   ns_fd_data.panel = panel;
1675   ns_fd_data.ret = NO;
1676 #ifdef NS_IMPL_COCOA
1677   if (! NILP (mustmatch) || ! NILP (dir_only_p))
1678     [panel setAllowedFileTypes: nil];
1679   if (dirS) [panel setDirectoryURL: [NSURL fileURLWithPath: dirS]];
1680   if (initS && NILP (Ffile_directory_p (init)))
1681     [panel setNameFieldStringValue: [initS lastPathComponent]];
1682   else
1683     [panel setNameFieldStringValue: @""];
1685 #else
1686   ns_fd_data.no_types = NILP (mustmatch) && NILP (dir_only_p);
1687   ns_fd_data.dirS = dirS;
1688   ns_fd_data.initS = initS;
1689 #endif
1691   /* runModalForDirectory/runModal restarts the main event loop when done,
1692      so we must start an event loop and then pop up the file dialog.
1693      The file dialog may pop up a confirm dialog after Ok has been pressed,
1694      so we can not simply pop down on the Ok/Cancel press.
1695    */
1696   nxev = [NSEvent otherEventWithType: NSEventTypeApplicationDefined
1697                             location: NSMakePoint (0, 0)
1698                        modifierFlags: 0
1699                            timestamp: 0
1700                         windowNumber: [[NSApp mainWindow] windowNumber]
1701                              context: [NSApp context]
1702                              subtype: 0
1703                                data1: 0
1704                                data2: NSAPP_DATA2_RUNFILEDIALOG];
1706   [NSApp postEvent: nxev atStart: NO];
1707   while (ns_fd_data.panel != nil)
1708     [NSApp run];
1710   if (ns_fd_data.ret == MODAL_OK_RESPONSE)
1711     {
1712       NSString *str = ns_filename_from_panel (panel);
1713       if (! str) str = ns_directory_from_panel (panel);
1714       if (str) fname = build_string ([str UTF8String]);
1715     }
1717   [[FRAME_NS_VIEW (SELECTED_FRAME ()) window] makeKeyWindow];
1718   unblock_input ();
1720   return fname;
1723 const char *
1724 ns_get_defaults_value (const char *key)
1726   NSObject *obj = [[NSUserDefaults standardUserDefaults]
1727                     objectForKey: [NSString stringWithUTF8String: key]];
1729   if (!obj) return NULL;
1731   return [[NSString stringWithFormat: @"%@", obj] UTF8String];
1735 DEFUN ("ns-get-resource", Fns_get_resource, Sns_get_resource, 2, 2, 0,
1736        doc: /* Return the value of the property NAME of OWNER from the defaults database.
1737 If OWNER is nil, Emacs is assumed.  */)
1738      (Lisp_Object owner, Lisp_Object name)
1740   const char *value;
1742   check_window_system (NULL);
1743   if (NILP (owner))
1744     owner = build_string([ns_app_name UTF8String]);
1745   CHECK_STRING (name);
1747   value = ns_get_defaults_value (SSDATA (name));
1749   if (value)
1750     return build_string (value);
1751   return Qnil;
1755 DEFUN ("ns-set-resource", Fns_set_resource, Sns_set_resource, 3, 3, 0,
1756        doc: /* Set property NAME of OWNER to VALUE, from the defaults database.
1757 If OWNER is nil, Emacs is assumed.
1758 If VALUE is nil, the default is removed.  */)
1759      (Lisp_Object owner, Lisp_Object name, Lisp_Object value)
1761   check_window_system (NULL);
1762   if (NILP (owner))
1763     owner = build_string ([ns_app_name UTF8String]);
1764   CHECK_STRING (name);
1765   if (NILP (value))
1766     {
1767       [[NSUserDefaults standardUserDefaults] removeObjectForKey:
1768                          [NSString stringWithUTF8String: SSDATA (name)]];
1769     }
1770   else
1771     {
1772       CHECK_STRING (value);
1773       [[NSUserDefaults standardUserDefaults] setObject:
1774                 [NSString stringWithUTF8String: SSDATA (value)]
1775                                         forKey: [NSString stringWithUTF8String:
1776                                                          SSDATA (name)]];
1777     }
1779   return Qnil;
1783 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
1784        Sx_server_max_request_size,
1785        0, 1, 0,
1786        doc: /* This function is a no-op.  It is only present for completeness.  */)
1787      (Lisp_Object terminal)
1789   check_ns_display_info (terminal);
1790   /* This function has no real equivalent under NeXTstep.  Return nil to
1791      indicate this. */
1792   return Qnil;
1796 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
1797        doc: /* Return the "vendor ID" string of Nextstep display server TERMINAL.
1798 \(Labeling every distributor as a "vendor" embodies the false assumption
1799 that operating systems cannot be developed and distributed noncommercially.)
1800 The optional argument TERMINAL specifies which display to ask about.
1801 TERMINAL should be a terminal object, a frame or a display name (a string).
1802 If omitted or nil, that stands for the selected frame's display.  */)
1803   (Lisp_Object terminal)
1805   check_ns_display_info (terminal);
1806 #ifdef NS_IMPL_GNUSTEP
1807   return build_string ("GNU");
1808 #else
1809   return build_string ("Apple");
1810 #endif
1814 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
1815        doc: /* Return the version numbers of the server of display TERMINAL.
1816 The value is a list of three integers: the major and minor
1817 version numbers of the X Protocol in use, and the distributor-specific release
1818 number.  See also the function `x-server-vendor'.
1820 The optional argument TERMINAL specifies which display to ask about.
1821 TERMINAL should be a terminal object, a frame or a display name (a string).
1822 If omitted or nil, that stands for the selected frame's display.  */)
1823   (Lisp_Object terminal)
1825   check_ns_display_info (terminal);
1826   /*NOTE: it is unclear what would best correspond with "protocol";
1827           we return 10.3, meaning Panther, since this is roughly the
1828           level that GNUstep's APIs correspond to.
1829           The last number is where we distinguish between the Apple
1830           and GNUstep implementations ("distributor-specific release
1831           number") and give int'ized versions of major.minor. */
1832   return list3i (10, 3, ns_appkit_version_int ());
1836 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
1837        doc: /* Return the number of screens on Nextstep display server TERMINAL.
1838 The optional argument TERMINAL specifies which display to ask about.
1839 TERMINAL should be a terminal object, a frame or a display name (a string).
1840 If omitted or nil, that stands for the selected frame's display.
1842 Note: "screen" here is not in Nextstep terminology but in X11's.  For
1843 the number of physical monitors, use `(length
1844 \(display-monitor-attributes-list TERMINAL))' instead.  */)
1845   (Lisp_Object terminal)
1847   check_ns_display_info (terminal);
1848   return make_number (1);
1852 DEFUN ("x-display-mm-height", Fx_display_mm_height, Sx_display_mm_height, 0, 1, 0,
1853        doc: /* Return the height in millimeters of the Nextstep display TERMINAL.
1854 The optional argument TERMINAL specifies which display to ask about.
1855 TERMINAL should be a terminal object, a frame or a display name (a string).
1856 If omitted or nil, that stands for the selected frame's display.
1858 On \"multi-monitor\" setups this refers to the height in millimeters for
1859 all physical monitors associated with TERMINAL.  To get information
1860 for each physical monitor, use `display-monitor-attributes-list'.  */)
1861   (Lisp_Object terminal)
1863   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
1865   return make_number (x_display_pixel_height (dpyinfo) / (92.0/25.4));
1869 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
1870        doc: /* Return the width in millimeters of the Nextstep display TERMINAL.
1871 The optional argument TERMINAL specifies which display to ask about.
1872 TERMINAL should be a terminal object, a frame or a display name (a string).
1873 If omitted or nil, that stands for the selected frame's display.
1875 On \"multi-monitor\" setups this refers to the width in millimeters for
1876 all physical monitors associated with TERMINAL.  To get information
1877 for each physical monitor, use `display-monitor-attributes-list'.  */)
1878   (Lisp_Object terminal)
1880   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
1882   return make_number (x_display_pixel_width (dpyinfo) / (92.0/25.4));
1886 DEFUN ("x-display-backing-store", Fx_display_backing_store,
1887        Sx_display_backing_store, 0, 1, 0,
1888        doc: /* Return an indication of whether the Nextstep display TERMINAL does backing store.
1889 The value may be `buffered', `retained', or `non-retained'.
1890 The optional argument TERMINAL specifies which display to ask about.
1891 TERMINAL should be a terminal object, a frame or a display name (a string).
1892 If omitted or nil, that stands for the selected frame's display.  */)
1893   (Lisp_Object terminal)
1895   check_ns_display_info (terminal);
1896   switch ([ns_get_window (terminal) backingType])
1897     {
1898     case NSBackingStoreBuffered:
1899       return intern ("buffered");
1900     case NSBackingStoreRetained:
1901       return intern ("retained");
1902     case NSBackingStoreNonretained:
1903       return intern ("non-retained");
1904     default:
1905       error ("Strange value for backingType parameter of frame");
1906     }
1907   return Qnil;  /* not reached, shut compiler up */
1911 DEFUN ("x-display-visual-class", Fx_display_visual_class,
1912        Sx_display_visual_class, 0, 1, 0,
1913        doc: /* Return the visual class of the Nextstep display TERMINAL.
1914 The value is one of the symbols `static-gray', `gray-scale',
1915 `static-color', `pseudo-color', `true-color', or `direct-color'.
1917 The optional argument TERMINAL specifies which display to ask about.
1918 TERMINAL should a terminal object, a frame or a display name (a string).
1919 If omitted or nil, that stands for the selected frame's display.  */)
1920   (Lisp_Object terminal)
1922   NSWindowDepth depth;
1924   check_ns_display_info (terminal);
1925   depth = [[[NSScreen screens] objectAtIndex:0] depth];
1927   if ( depth == NSBestDepth (NSCalibratedWhiteColorSpace, 2, 2, YES, NULL))
1928     return intern ("static-gray");
1929   else if (depth == NSBestDepth (NSCalibratedWhiteColorSpace, 8, 8, YES, NULL))
1930     return intern ("gray-scale");
1931   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 8, 8, YES, NULL))
1932     return intern ("pseudo-color");
1933   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 4, 12, NO, NULL))
1934     return intern ("true-color");
1935   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 8, 24, NO, NULL))
1936     return intern ("direct-color");
1937   else
1938     /* color mgmt as far as we do it is really handled by Nextstep itself anyway */
1939     return intern ("direct-color");
1943 DEFUN ("x-display-save-under", Fx_display_save_under,
1944        Sx_display_save_under, 0, 1, 0,
1945        doc: /* Return t if TERMINAL supports the save-under feature.
1946 The optional argument TERMINAL specifies which display to ask about.
1947 TERMINAL should be a terminal object, a frame or a display name (a string).
1948 If omitted or nil, that stands for the selected frame's display.  */)
1949   (Lisp_Object terminal)
1951   check_ns_display_info (terminal);
1952   switch ([ns_get_window (terminal) backingType])
1953     {
1954     case NSBackingStoreBuffered:
1955       return Qt;
1957     case NSBackingStoreRetained:
1958     case NSBackingStoreNonretained:
1959       return Qnil;
1961     default:
1962       error ("Strange value for backingType parameter of frame");
1963     }
1964   return Qnil;  /* not reached, shut compiler up */
1968 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
1969        1, 3, 0,
1970        doc: /* Open a connection to a display server.
1971 DISPLAY is the name of the display to connect to.
1972 Optional second arg XRM-STRING is a string of resources in xrdb format.
1973 If the optional third arg MUST-SUCCEED is non-nil,
1974 terminate Emacs if we can't open the connection.
1975 \(In the Nextstep version, the last two arguments are currently ignored.)  */)
1976      (Lisp_Object display, Lisp_Object resource_string, Lisp_Object must_succeed)
1978   struct ns_display_info *dpyinfo;
1980   CHECK_STRING (display);
1982   nxatoms_of_nsselect ();
1983   dpyinfo = ns_term_init (display);
1984   if (dpyinfo == 0)
1985     {
1986       if (!NILP (must_succeed))
1987         fatal ("Display on %s not responding.\n",
1988                SSDATA (display));
1989       else
1990         error ("Display on %s not responding.\n",
1991                SSDATA (display));
1992     }
1994   return Qnil;
1998 DEFUN ("x-close-connection", Fx_close_connection, Sx_close_connection,
1999        1, 1, 0,
2000        doc: /* Close the connection to TERMINAL's Nextstep display server.
2001 For TERMINAL, specify a terminal object, a frame or a display name (a
2002 string).  If TERMINAL is nil, that stands for the selected frame's
2003 terminal.  */)
2004      (Lisp_Object terminal)
2006   check_ns_display_info (terminal);
2007   [NSApp terminate: NSApp];
2008   return Qnil;
2012 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
2013        doc: /* Return the list of display names that Emacs has connections to.  */)
2014      (void)
2016   Lisp_Object result = Qnil;
2017   struct ns_display_info *ndi;
2019   for (ndi = x_display_list; ndi; ndi = ndi->next)
2020     result = Fcons (XCAR (ndi->name_list_element), result);
2022   return result;
2026 DEFUN ("ns-hide-others", Fns_hide_others, Sns_hide_others,
2027        0, 0, 0,
2028        doc: /* Hides all applications other than Emacs.  */)
2029      (void)
2031   check_window_system (NULL);
2032   [NSApp hideOtherApplications: NSApp];
2033   return Qnil;
2036 DEFUN ("ns-hide-emacs", Fns_hide_emacs, Sns_hide_emacs,
2037        1, 1, 0,
2038        doc: /* If ON is non-nil, the entire Emacs application is hidden.
2039 Otherwise if Emacs is hidden, it is unhidden.
2040 If ON is equal to `activate', Emacs is unhidden and becomes
2041 the active application.  */)
2042      (Lisp_Object on)
2044   check_window_system (NULL);
2045   if (EQ (on, intern ("activate")))
2046     {
2047       [NSApp unhide: NSApp];
2048       [NSApp activateIgnoringOtherApps: YES];
2049     }
2050   else if (NILP (on))
2051     [NSApp unhide: NSApp];
2052   else
2053     [NSApp hide: NSApp];
2054   return Qnil;
2058 DEFUN ("ns-emacs-info-panel", Fns_emacs_info_panel, Sns_emacs_info_panel,
2059        0, 0, 0,
2060        doc: /* Shows the 'Info' or 'About' panel for Emacs.  */)
2061      (void)
2063   check_window_system (NULL);
2064   [NSApp orderFrontStandardAboutPanel: nil];
2065   return Qnil;
2069 DEFUN ("ns-font-name", Fns_font_name, Sns_font_name, 1, 1, 0,
2070        doc: /* Determine font PostScript or family name for font NAME.
2071 NAME should be a string containing either the font name or an XLFD
2072 font descriptor.  If string contains `fontset' and not
2073 `fontset-startup', it is left alone. */)
2074      (Lisp_Object name)
2076   char *nm;
2077   CHECK_STRING (name);
2078   nm = SSDATA (name);
2080   if (nm[0] != '-')
2081     return name;
2082   if (strstr (nm, "fontset") && !strstr (nm, "fontset-startup"))
2083     return name;
2085   return build_string (ns_xlfd_to_fontname (SSDATA (name)));
2089 DEFUN ("ns-list-colors", Fns_list_colors, Sns_list_colors, 0, 1, 0,
2090        doc: /* Return a list of all available colors.
2091 The optional argument FRAME is currently ignored.  */)
2092      (Lisp_Object frame)
2094   Lisp_Object list = Qnil;
2095   NSEnumerator *colorlists;
2096   NSColorList *clist;
2098   if (!NILP (frame))
2099     {
2100       CHECK_FRAME (frame);
2101       if (! FRAME_NS_P (XFRAME (frame)))
2102         error ("non-Nextstep frame used in `ns-list-colors'");
2103     }
2105   block_input ();
2107   colorlists = [[NSColorList availableColorLists] objectEnumerator];
2108   while ((clist = [colorlists nextObject]))
2109     {
2110       if ([[clist name] length] < 7 ||
2111           [[clist name] rangeOfString: @"PANTONE"].location == 0)
2112         {
2113           NSEnumerator *cnames = [[clist allKeys] reverseObjectEnumerator];
2114           NSString *cname;
2115           while ((cname = [cnames nextObject]))
2116             list = Fcons (build_string ([cname UTF8String]), list);
2117 /*           for (i = [[clist allKeys] count] - 1; i >= 0; i--)
2118                list = Fcons (build_string ([[[clist allKeys] objectAtIndex: i]
2119                                              UTF8String]), list); */
2120         }
2121     }
2123   unblock_input ();
2125   return list;
2129 DEFUN ("ns-list-services", Fns_list_services, Sns_list_services, 0, 0, 0,
2130        doc: /* List available Nextstep services by querying NSApp.  */)
2131      (void)
2133 #ifdef NS_IMPL_COCOA
2134   /* You can't get services like this in 10.6+.  */
2135   return Qnil;
2136 #else
2137   Lisp_Object ret = Qnil;
2138   NSMenu *svcs;
2140   check_window_system (NULL);
2141   svcs = [[NSMenu alloc] initWithTitle: @"Services"];
2142   [NSApp setServicesMenu: svcs];
2143   [NSApp registerServicesMenuSendTypes: ns_send_types
2144                            returnTypes: ns_return_types];
2146   [svcs setAutoenablesItems: NO];
2148   ret = interpret_services_menu (svcs, Qnil, ret);
2149   return ret;
2150 #endif
2154 DEFUN ("ns-perform-service", Fns_perform_service, Sns_perform_service,
2155        2, 2, 0,
2156        doc: /* Perform Nextstep SERVICE on SEND.
2157 SEND should be either a string or nil.
2158 The return value is the result of the service, as string, or nil if
2159 there was no result.  */)
2160      (Lisp_Object service, Lisp_Object send)
2162   id pb;
2163   NSString *svcName;
2164   char *utfStr;
2166   CHECK_STRING (service);
2167   check_window_system (NULL);
2169   utfStr = SSDATA (service);
2170   svcName = [NSString stringWithUTF8String: utfStr];
2172   pb =[NSPasteboard pasteboardWithUniqueName];
2173   ns_string_to_pasteboard (pb, send);
2175   if (NSPerformService (svcName, pb) == NO)
2176     Fsignal (Qquit, list1 (build_string ("service not available")));
2178   if ([[pb types] count] == 0)
2179     return build_string ("");
2180   return ns_string_from_pasteboard (pb);
2184 #ifdef NS_IMPL_COCOA
2186 /* Compile and execute the AppleScript SCRIPT and return the error
2187    status as function value.  A zero is returned if compilation and
2188    execution is successful, in which case *RESULT is set to a Lisp
2189    string or a number containing the resulting script value.  Otherwise,
2190    1 is returned. */
2191 static int
2192 ns_do_applescript (Lisp_Object script, Lisp_Object *result)
2194   NSAppleEventDescriptor *desc;
2195   NSDictionary *errorDict;
2196   NSAppleEventDescriptor *returnDescriptor = NULL;
2198   NSAppleScript *scriptObject =
2199     [[NSAppleScript alloc] initWithSource:
2200                              [NSString stringWithUTF8String: SSDATA (script)]];
2202   returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
2203   [scriptObject release];
2204   *result = Qnil;
2206   if (returnDescriptor != NULL)
2207     {
2208       // successful execution
2209       if (kAENullEvent != [returnDescriptor descriptorType])
2210         {
2211           *result = Qt;
2212           // script returned an AppleScript result
2213           if ((typeUnicodeText == [returnDescriptor descriptorType]) ||
2214 #if defined (NS_IMPL_COCOA)
2215               (typeUTF16ExternalRepresentation
2216                == [returnDescriptor descriptorType]) ||
2217 #endif
2218               (typeUTF8Text == [returnDescriptor descriptorType]) ||
2219               (typeCString == [returnDescriptor descriptorType]))
2220             {
2221               desc = [returnDescriptor coerceToDescriptorType: typeUTF8Text];
2222               if (desc)
2223                 *result = build_string([[desc stringValue] UTF8String]);
2224             }
2225           else
2226             {
2227               /* use typeUTF16ExternalRepresentation? */
2228               // coerce the result to the appropriate ObjC type
2229               desc = [returnDescriptor coerceToDescriptorType: typeUTF8Text];
2230               if (desc)
2231                 *result = make_number([desc int32Value]);
2232             }
2233         }
2234     }
2235   else
2236     {
2237       // no script result, return error
2238       return 1;
2239     }
2240   return 0;
2243 /* Helper function called from sendEvent to run applescript
2244    from within the main event loop.  */
2246 void
2247 ns_run_ascript (void)
2249   if (! NILP (as_script))
2250     as_status = ns_do_applescript (as_script, as_result);
2251   as_script = Qnil;
2254 DEFUN ("ns-do-applescript", Fns_do_applescript, Sns_do_applescript, 1, 1, 0,
2255        doc: /* Execute AppleScript SCRIPT and return the result.
2256 If compilation and execution are successful, the resulting script value
2257 is returned as a string, a number or, in the case of other constructs, t.
2258 In case the execution fails, an error is signaled. */)
2259      (Lisp_Object script)
2261   Lisp_Object result;
2262   int status;
2263   NSEvent *nxev;
2264   struct input_event ev;
2266   CHECK_STRING (script);
2267   check_window_system (NULL);
2269   block_input ();
2271   as_script = script;
2272   as_result = &result;
2274   /* executing apple script requires the event loop to run, otherwise
2275      errors aren't returned and executeAndReturnError hangs forever.
2276      Post an event that runs applescript and then start the event loop.
2277      The event loop is exited when the script is done.  */
2278   nxev = [NSEvent otherEventWithType: NSEventTypeApplicationDefined
2279                             location: NSMakePoint (0, 0)
2280                        modifierFlags: 0
2281                            timestamp: 0
2282                         windowNumber: [[NSApp mainWindow] windowNumber]
2283                              context: [NSApp context]
2284                              subtype: 0
2285                                data1: 0
2286                                data2: NSAPP_DATA2_RUNASSCRIPT];
2288   [NSApp postEvent: nxev atStart: NO];
2290   // If there are other events, the event loop may exit.  Keep running
2291   // until the script has been handled.  */
2292   ns_init_events (&ev);
2293   while (! NILP (as_script))
2294     [NSApp run];
2295   ns_finish_events ();
2297   status = as_status;
2298   as_status = 0;
2299   as_result = 0;
2300   unblock_input ();
2301   if (status == 0)
2302     return result;
2303   else if (!STRINGP (result))
2304     error ("AppleScript error %d", status);
2305   else
2306     error ("%s", SSDATA (result));
2308 #endif
2312 /* ==========================================================================
2314     Miscellaneous functions not called through hooks
2316    ========================================================================== */
2318 /* called from frame.c */
2319 struct ns_display_info *
2320 check_x_display_info (Lisp_Object frame)
2322   return check_ns_display_info (frame);
2326 void
2327 x_set_scroll_bar_default_width (struct frame *f)
2329   int wid = FRAME_COLUMN_WIDTH (f);
2330   FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = NS_SCROLL_BAR_WIDTH_DEFAULT;
2331   FRAME_CONFIG_SCROLL_BAR_COLS (f) = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) +
2332                                       wid - 1) / wid;
2335 void
2336 x_set_scroll_bar_default_height (struct frame *f)
2338   int height = FRAME_LINE_HEIGHT (f);
2339   FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) = NS_SCROLL_BAR_WIDTH_DEFAULT;
2340   FRAME_CONFIG_SCROLL_BAR_LINES (f) = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) +
2341                                        height - 1) / height;
2344 /* terms impl this instead of x-get-resource directly */
2345 char *
2346 x_get_string_resource (XrmDatabase rdb, const char *name, const char *class)
2348   /* remove appname prefix; TODO: allow for !="Emacs" */
2349   const char *res, *toCheck = class + (!strncmp (class, "Emacs.", 6) ? 6 : 0);
2351   check_window_system (NULL);
2353   if (inhibit_x_resources)
2354     /* --quick was passed, so this is a no-op.  */
2355     return NULL;
2357   res = ns_get_defaults_value (toCheck);
2358   return (char *) (!res ? NULL
2359                    : !c_strncasecmp (res, "YES", 3) ? "true"
2360                    : !c_strncasecmp (res, "NO", 2) ? "false"
2361                    : res);
2365 Lisp_Object
2366 x_get_focus_frame (struct frame *frame)
2368   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
2369   Lisp_Object nsfocus;
2371   if (!dpyinfo->x_focus_frame)
2372     return Qnil;
2374   XSETFRAME (nsfocus, dpyinfo->x_focus_frame);
2375   return nsfocus;
2378 /* ==========================================================================
2380     Lisp definitions that, for whatever reason, we can't alias as 'ns-XXX'.
2382    ========================================================================== */
2385 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
2386        doc: /* Internal function called by `color-defined-p', which see.
2387 \(Note that the Nextstep version of this function ignores FRAME.)  */)
2388      (Lisp_Object color, Lisp_Object frame)
2390   NSColor * col;
2391   check_window_system (NULL);
2392   return ns_lisp_to_color (color, &col) ? Qnil : Qt;
2396 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
2397        doc: /* Internal function called by `color-values', which see.  */)
2398      (Lisp_Object color, Lisp_Object frame)
2400   NSColor * col;
2401   EmacsCGFloat red, green, blue, alpha;
2403   check_window_system (NULL);
2404   CHECK_STRING (color);
2406   block_input ();
2407   if (ns_lisp_to_color (color, &col))
2408     {
2409       unblock_input ();
2410       return Qnil;
2411     }
2413   [[col colorUsingDefaultColorSpace]
2414         getRed: &red green: &green blue: &blue alpha: &alpha];
2415   unblock_input ();
2416   return list3i (lrint (red * 65280), lrint (green * 65280),
2417                  lrint (blue * 65280));
2421 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
2422        doc: /* Internal function called by `display-color-p', which see.  */)
2423      (Lisp_Object terminal)
2425   NSWindowDepth depth;
2426   NSString *colorSpace;
2428   check_ns_display_info (terminal);
2429   depth = [[[NSScreen screens] objectAtIndex:0] depth];
2430   colorSpace = NSColorSpaceFromDepth (depth);
2432   return    [colorSpace isEqualToString: NSDeviceWhiteColorSpace]
2433          || [colorSpace isEqualToString: NSCalibratedWhiteColorSpace]
2434       ? Qnil : Qt;
2438 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p, Sx_display_grayscale_p,
2439        0, 1, 0,
2440        doc: /* Return t if the Nextstep display supports shades of gray.
2441 Note that color displays do support shades of gray.
2442 The optional argument TERMINAL specifies which display to ask about.
2443 TERMINAL should be a terminal object, a frame or a display name (a string).
2444 If omitted or nil, that stands for the selected frame's display.  */)
2445   (Lisp_Object terminal)
2447   NSWindowDepth depth;
2449   check_ns_display_info (terminal);
2450   depth = [[[NSScreen screens] objectAtIndex:0] depth];
2452   return NSBitsPerPixelFromDepth (depth) > 1 ? Qt : Qnil;
2456 DEFUN ("x-display-pixel-width", Fx_display_pixel_width, Sx_display_pixel_width,
2457        0, 1, 0,
2458        doc: /* Return the width in pixels of the Nextstep display TERMINAL.
2459 The optional argument TERMINAL specifies which display to ask about.
2460 TERMINAL should be a terminal object, a frame or a display name (a string).
2461 If omitted or nil, that stands for the selected frame's display.
2463 On \"multi-monitor\" setups this refers to the pixel width for all
2464 physical monitors associated with TERMINAL.  To get information for
2465 each physical monitor, use `display-monitor-attributes-list'.  */)
2466   (Lisp_Object terminal)
2468   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
2470   return make_number (x_display_pixel_width (dpyinfo));
2474 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
2475        Sx_display_pixel_height, 0, 1, 0,
2476        doc: /* Return the height in pixels of the Nextstep display TERMINAL.
2477 The optional argument TERMINAL specifies which display to ask about.
2478 TERMINAL should be a terminal object, a frame or a display name (a string).
2479 If omitted or nil, that stands for the selected frame's display.
2481 On \"multi-monitor\" setups this refers to the pixel height for all
2482 physical monitors associated with TERMINAL.  To get information for
2483 each physical monitor, use `display-monitor-attributes-list'.  */)
2484   (Lisp_Object terminal)
2486   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
2488   return make_number (x_display_pixel_height (dpyinfo));
2491 #ifdef NS_IMPL_COCOA
2493 /* Returns the name for the screen that OBJ represents, or NULL.
2494    Caller must free return value.
2497 static char *
2498 ns_get_name_from_ioreg (io_object_t obj)
2500   char *name = NULL;
2502   NSDictionary *info = (NSDictionary *)
2503     IODisplayCreateInfoDictionary (obj, kIODisplayOnlyPreferredName);
2504   NSDictionary *names = [info objectForKey:
2505                                 [NSString stringWithUTF8String:
2506                                             kDisplayProductName]];
2508   if ([names count] > 0)
2509     {
2510       NSString *n = [names objectForKey: [[names allKeys]
2511                                                  objectAtIndex:0]];
2512       if (n != nil) name = xstrdup ([n UTF8String]);
2513     }
2515   [info release];
2517   return name;
2520 /* Returns the name for the screen that DID came from, or NULL.
2521    Caller must free return value.
2524 static char *
2525 ns_screen_name (CGDirectDisplayID did)
2527   char *name = NULL;
2529 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1090
2530 #if MAC_OS_X_VERSION_MIN_REQUIRED < 1090
2531   if (CGDisplayIOServicePort == NULL)
2532 #endif
2533     {
2534       mach_port_t masterPort;
2535       io_iterator_t it;
2536       io_object_t obj;
2538       /* CGDisplayIOServicePort is deprecated.  Do it another (harder) way.
2540          Is this code OK for macOS < 10.9, and GNUstep?  I suspect it is,
2541          in which case is it worth keeping the other method in here? */
2543       if (IOMasterPort (MACH_PORT_NULL, &masterPort) != kIOReturnSuccess
2544           || IOServiceGetMatchingServices (masterPort,
2545                                            IOServiceMatching ("IONDRVDevice"),
2546                                            &it) != kIOReturnSuccess)
2547         return name;
2549       /* Must loop until we find a name.  Many devices can have the same unit
2550          number (represents different GPU parts), but only one has a name.  */
2551       while (! name && (obj = IOIteratorNext (it)))
2552         {
2553           CFMutableDictionaryRef props;
2554           const void *val;
2556           if (IORegistryEntryCreateCFProperties (obj,
2557                                                  &props,
2558                                                  kCFAllocatorDefault,
2559                                                  kNilOptions) == kIOReturnSuccess
2560               && props != nil
2561               && (val = CFDictionaryGetValue(props, @"IOFBDependentIndex")))
2562             {
2563               unsigned nr = [(NSNumber *)val unsignedIntegerValue];
2564               if (nr == CGDisplayUnitNumber (did))
2565                 name = ns_get_name_from_ioreg (obj);
2566             }
2568           CFRelease (props);
2569           IOObjectRelease (obj);
2570         }
2572       IOObjectRelease (it);
2573     }
2574 #if MAC_OS_X_VERSION_MIN_REQUIRED < 1090
2575   else
2576 #endif
2577 #endif /* #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1090 */
2578 #if MAC_OS_X_VERSION_MIN_REQUIRED < 1090
2579     name = ns_get_name_from_ioreg (CGDisplayIOServicePort (did));
2580 #endif
2581   return name;
2583 #endif /* NS_IMPL_COCOA */
2585 static Lisp_Object
2586 ns_make_monitor_attribute_list (struct MonitorInfo *monitors,
2587                                 int n_monitors,
2588                                 int primary_monitor,
2589                                 const char *source)
2591   Lisp_Object monitor_frames = Fmake_vector (make_number (n_monitors), Qnil);
2592   Lisp_Object frame, rest;
2593   NSArray *screens = [NSScreen screens];
2594   int i;
2596   FOR_EACH_FRAME (rest, frame)
2597     {
2598       struct frame *f = XFRAME (frame);
2600       if (FRAME_NS_P (f))
2601         {
2602           NSView *view = FRAME_NS_VIEW (f);
2603           NSScreen *screen = [[view window] screen];
2604           NSUInteger k;
2606           i = -1;
2607           for (k = 0; i == -1 && k < [screens count]; ++k)
2608             {
2609               if ([screens objectAtIndex: k] == screen)
2610                 i = (int)k;
2611             }
2613           if (i > -1)
2614             ASET (monitor_frames, i, Fcons (frame, AREF (monitor_frames, i)));
2615         }
2616     }
2618   return make_monitor_attribute_list (monitors, n_monitors, primary_monitor,
2619                                       monitor_frames, source);
2622 DEFUN ("ns-display-monitor-attributes-list",
2623        Fns_display_monitor_attributes_list,
2624        Sns_display_monitor_attributes_list,
2625        0, 1, 0,
2626        doc: /* Return a list of physical monitor attributes on the X display TERMINAL.
2628 The optional argument TERMINAL specifies which display to ask about.
2629 TERMINAL should be a terminal object, a frame or a display name (a string).
2630 If omitted or nil, that stands for the selected frame's display.
2632 In addition to the standard attribute keys listed in
2633 `display-monitor-attributes-list', the following keys are contained in
2634 the attributes:
2636  source -- String describing the source from which multi-monitor
2637            information is obtained, \"NS\" is always the source."
2639 Internal use only, use `display-monitor-attributes-list' instead.  */)
2640   (Lisp_Object terminal)
2642   struct terminal *term = decode_live_terminal (terminal);
2643   NSArray *screens;
2644   NSUInteger i, n_monitors;
2645   struct MonitorInfo *monitors;
2646   Lisp_Object attributes_list = Qnil;
2647   CGFloat primary_display_height = 0;
2649   if (term->type != output_ns)
2650     return Qnil;
2652   screens = [NSScreen screens];
2653   n_monitors = [screens count];
2654   if (n_monitors == 0)
2655     return Qnil;
2657   monitors = xzalloc (n_monitors * sizeof *monitors);
2659   for (i = 0; i < [screens count]; ++i)
2660     {
2661       NSScreen *s = [screens objectAtIndex:i];
2662       struct MonitorInfo *m = &monitors[i];
2663       NSRect fr = [s frame];
2664       NSRect vfr = [s visibleFrame];
2665       short y, vy;
2667 #ifdef NS_IMPL_COCOA
2668       NSDictionary *dict = [s deviceDescription];
2669       NSNumber *nid = [dict objectForKey:@"NSScreenNumber"];
2670       CGDirectDisplayID did = [nid unsignedIntValue];
2671 #endif
2672       if (i == 0)
2673         {
2674           primary_display_height = fr.size.height;
2675           y = (short) fr.origin.y;
2676           vy = (short) vfr.origin.y;
2677         }
2678       else
2679         {
2680           // Flip y coordinate as NS has y starting from the bottom.
2681           y = (short) (primary_display_height - fr.size.height - fr.origin.y);
2682           vy = (short) (primary_display_height -
2683                         vfr.size.height - vfr.origin.y);
2684         }
2686       m->geom.x = (short) fr.origin.x;
2687       m->geom.y = y;
2688       m->geom.width = (unsigned short) fr.size.width;
2689       m->geom.height = (unsigned short) fr.size.height;
2691       m->work.x = (short) vfr.origin.x;
2692       // y is flipped on NS, so vy - y are pixels missing at the bottom,
2693       // and fr.size.height - vfr.size.height are pixels missing in total.
2694       // Pixels missing at top are
2695       // fr.size.height - vfr.size.height - vy + y.
2696       // work.y is then pixels missing at top + y.
2697       m->work.y = (short) (fr.size.height - vfr.size.height) - vy + y + y;
2698       m->work.width = (unsigned short) vfr.size.width;
2699       m->work.height = (unsigned short) vfr.size.height;
2701 #ifdef NS_IMPL_COCOA
2702       m->name = ns_screen_name (did);
2704       {
2705         CGSize mms = CGDisplayScreenSize (did);
2706         m->mm_width = (int) mms.width;
2707         m->mm_height = (int) mms.height;
2708       }
2710 #else
2711       // Assume 92 dpi as x-display-mm-height/x-display-mm-width does.
2712       m->mm_width = (int) (25.4 * fr.size.width / 92.0);
2713       m->mm_height = (int) (25.4 * fr.size.height / 92.0);
2714 #endif
2715     }
2717   // Primary monitor is always first for NS.
2718   attributes_list = ns_make_monitor_attribute_list (monitors, n_monitors,
2719                                                     0, "NS");
2721   free_monitors (monitors, n_monitors);
2722   return attributes_list;
2726 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
2727        0, 1, 0,
2728        doc: /* Return the number of bitplanes of the Nextstep display TERMINAL.
2729 The optional argument TERMINAL specifies which display to ask about.
2730 TERMINAL should be a terminal object, a frame or a display name (a string).
2731 If omitted or nil, that stands for the selected frame's display.  */)
2732   (Lisp_Object terminal)
2734   check_ns_display_info (terminal);
2735   return make_number
2736     (NSBitsPerPixelFromDepth ([[[NSScreen screens] objectAtIndex:0] depth]));
2740 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
2741        0, 1, 0,
2742        doc: /* Returns the number of color cells of the Nextstep display TERMINAL.
2743 The optional argument TERMINAL specifies which display to ask about.
2744 TERMINAL should be a terminal object, a frame or a display name (a string).
2745 If omitted or nil, that stands for the selected frame's display.  */)
2746   (Lisp_Object terminal)
2748   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
2749   /* We force 24+ bit depths to 24-bit to prevent an overflow.  */
2750   return make_number (1 << min (dpyinfo->n_planes, 24));
2754 /* Unused dummy def needed for compatibility. */
2755 Lisp_Object tip_frame;
2757 /* TODO: move to xdisp or similar */
2758 static void
2759 compute_tip_xy (struct frame *f,
2760                 Lisp_Object parms,
2761                 Lisp_Object dx,
2762                 Lisp_Object dy,
2763                 int width,
2764                 int height,
2765                 int *root_x,
2766                 int *root_y)
2768   Lisp_Object left, top, right, bottom;
2769   NSPoint pt;
2770   NSScreen *screen;
2772   /* Start with user-specified or mouse position.  */
2773   left = Fcdr (Fassq (Qleft, parms));
2774   top = Fcdr (Fassq (Qtop, parms));
2775   right = Fcdr (Fassq (Qright, parms));
2776   bottom = Fcdr (Fassq (Qbottom, parms));
2778   if ((!INTEGERP (left) && !INTEGERP (right))
2779       || (!INTEGERP (top) && !INTEGERP (bottom)))
2780     pt = [NSEvent mouseLocation];
2781   else
2782     {
2783       /* Absolute coordinates.  */
2784       pt.x = INTEGERP (left) ? XINT (left) : XINT (right);
2785       pt.y = (x_display_pixel_height (FRAME_DISPLAY_INFO (f))
2786               - (INTEGERP (top) ? XINT (top) : XINT (bottom))
2787               - height);
2788     }
2790   /* Find the screen that pt is on. */
2791   for (screen in [NSScreen screens])
2792     if (pt.x >= screen.frame.origin.x
2793         && pt.x < screen.frame.origin.x + screen.frame.size.width
2794         && pt.y >= screen.frame.origin.y
2795         && pt.y < screen.frame.origin.y + screen.frame.size.height)
2796       break;
2798   /* We could use this instead of the if above:
2800          if (CGRectContainsPoint ([screen frame], pt))
2802      which would be neater, but it causes problems building on old
2803      versions of macOS and in GNUstep. */
2805   /* Ensure in bounds.  (Note, screen origin = lower left.) */
2806   if (INTEGERP (left) || INTEGERP (right))
2807     *root_x = pt.x;
2808   else if (pt.x + XINT (dx) <= screen.frame.origin.x)
2809     *root_x = screen.frame.origin.x; /* Can happen for negative dx */
2810   else if (pt.x + XINT (dx) + width
2811            <= screen.frame.origin.x + screen.frame.size.width)
2812     /* It fits to the right of the pointer.  */
2813     *root_x = pt.x + XINT (dx);
2814   else if (width + XINT (dx) <= pt.x)
2815     /* It fits to the left of the pointer.  */
2816     *root_x = pt.x - width - XINT (dx);
2817   else
2818     /* Put it left justified on the screen -- it ought to fit that way.  */
2819     *root_x = screen.frame.origin.x;
2821   if (INTEGERP (top) || INTEGERP (bottom))
2822     *root_y = pt.y;
2823   else if (pt.y - XINT (dy) - height >= screen.frame.origin.y)
2824     /* It fits below the pointer.  */
2825     *root_y = pt.y - height - XINT (dy);
2826   else if (pt.y + XINT (dy) + height
2827            <= screen.frame.origin.y + screen.frame.size.height)
2828     /* It fits above the pointer */
2829       *root_y = pt.y + XINT (dy);
2830   else
2831     /* Put it on the top.  */
2832     *root_y = screen.frame.origin.y + screen.frame.size.height - height;
2836 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
2837        doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
2838 A tooltip window is a small window displaying a string.
2840 This is an internal function; Lisp code should call `tooltip-show'.
2842 FRAME nil or omitted means use the selected frame.
2844 PARMS is an optional list of frame parameters which can be used to
2845 change the tooltip's appearance.
2847 Automatically hide the tooltip after TIMEOUT seconds.  TIMEOUT nil
2848 means use the default timeout of 5 seconds.
2850 If the list of frame parameters PARMS contains a `left' parameter,
2851 display the tooltip at that x-position.  If the list of frame parameters
2852 PARMS contains no `left' but a `right' parameter, display the tooltip
2853 right-adjusted at that x-position. Otherwise display it at the
2854 x-position of the mouse, with offset DX added (default is 5 if DX isn't
2855 specified).
2857 Likewise for the y-position: If a `top' frame parameter is specified, it
2858 determines the position of the upper edge of the tooltip window.  If a
2859 `bottom' parameter but no `top' frame parameter is specified, it
2860 determines the position of the lower edge of the tooltip window.
2861 Otherwise display the tooltip window at the y-position of the mouse,
2862 with offset DY added (default is -10).
2864 A tooltip's maximum size is specified by `x-max-tooltip-size'.
2865 Text larger than the specified size is clipped.  */)
2866      (Lisp_Object string, Lisp_Object frame, Lisp_Object parms, Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
2868   int root_x, root_y;
2869   ptrdiff_t count = SPECPDL_INDEX ();
2870   struct frame *f;
2871   char *str;
2872   NSSize size;
2874   specbind (Qinhibit_redisplay, Qt);
2876   CHECK_STRING (string);
2877   str = SSDATA (string);
2878   f = decode_window_system_frame (frame);
2879   if (NILP (timeout))
2880     timeout = make_number (5);
2881   else
2882     CHECK_NATNUM (timeout);
2884   if (NILP (dx))
2885     dx = make_number (5);
2886   else
2887     CHECK_NUMBER (dx);
2889   if (NILP (dy))
2890     dy = make_number (-10);
2891   else
2892     CHECK_NUMBER (dy);
2894   block_input ();
2895   if (ns_tooltip == nil)
2896     ns_tooltip = [[EmacsTooltip alloc] init];
2897   else
2898     Fx_hide_tip ();
2900   [ns_tooltip setText: str];
2901   size = [ns_tooltip frame].size;
2903   /* Move the tooltip window where the mouse pointer is.  Resize and
2904      show it.  */
2905   compute_tip_xy (f, parms, dx, dy, (int)size.width, (int)size.height,
2906                   &root_x, &root_y);
2908   [ns_tooltip showAtX: root_x Y: root_y for: XINT (timeout)];
2909   unblock_input ();
2911   return unbind_to (count, Qnil);
2915 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
2916        doc: /* Hide the current tooltip window, if there is any.
2917 Value is t if tooltip was open, nil otherwise.  */)
2918      (void)
2920   if (ns_tooltip == nil || ![ns_tooltip isActive])
2921     return Qnil;
2922   [ns_tooltip hide];
2923   return Qt;
2926 /* Return geometric attributes of FRAME.  According to the value of
2927    ATTRIBUTES return the outer edges of FRAME (Qouter_edges), the inner
2928    edges of FRAME, the root window edges of frame (Qroot_edges).  Any
2929    other value means to return the geometry as returned by
2930    Fx_frame_geometry.  */
2931 static Lisp_Object
2932 frame_geometry (Lisp_Object frame, Lisp_Object attribute)
2934   struct frame *f = decode_live_frame (frame);
2935   Lisp_Object fullscreen_symbol = Fframe_parameter (frame, Qfullscreen);
2936   bool fullscreen = (EQ (fullscreen_symbol, Qfullboth)
2937                      || EQ (fullscreen_symbol, Qfullscreen));
2938   int border = fullscreen ? 0 : f->border_width;
2939   int title_height = fullscreen ? 0 : FRAME_NS_TITLEBAR_HEIGHT (f);
2940   int native_width = FRAME_PIXEL_WIDTH (f);
2941   int native_height = FRAME_PIXEL_HEIGHT (f);
2942   int outer_width = native_width + 2 * border;
2943   int outer_height = native_height + 2 * border + title_height;
2944   int native_left = f->left_pos + border;
2945   int native_top = f->top_pos + border + title_height;
2946   int native_right = f->left_pos + outer_width - border;
2947   int native_bottom = f->top_pos + outer_height - border;
2948   int internal_border_width = FRAME_INTERNAL_BORDER_WIDTH (f);
2949   int tool_bar_height = FRAME_TOOLBAR_HEIGHT (f);
2950   int tool_bar_width = (tool_bar_height
2951                         ? outer_width - 2 * internal_border_width
2952                         : 0);
2954   /* Construct list.  */
2955   if (EQ (attribute, Qouter_edges))
2956     return list4 (make_number (f->left_pos), make_number (f->top_pos),
2957                   make_number (f->left_pos + outer_width),
2958                   make_number (f->top_pos + outer_height));
2959   else if (EQ (attribute, Qnative_edges))
2960     return list4 (make_number (native_left), make_number (native_top),
2961                   make_number (native_right), make_number (native_bottom));
2962   else if (EQ (attribute, Qinner_edges))
2963     return list4 (make_number (native_left + internal_border_width),
2964                   make_number (native_top
2965                                + tool_bar_height
2966                                + internal_border_width),
2967                   make_number (native_right - internal_border_width),
2968                   make_number (native_bottom - internal_border_width));
2969   else
2970     return
2971       listn (CONSTYPE_HEAP, 10,
2972              Fcons (Qouter_position,
2973                     Fcons (make_number (f->left_pos),
2974                            make_number (f->top_pos))),
2975              Fcons (Qouter_size,
2976                     Fcons (make_number (outer_width),
2977                            make_number (outer_height))),
2978              Fcons (Qexternal_border_size,
2979                     (fullscreen
2980                      ? Fcons (make_number (0), make_number (0))
2981                      : Fcons (make_number (border), make_number (border)))),
2982              Fcons (Qtitle_bar_size,
2983                     Fcons (make_number (0), make_number (title_height))),
2984              Fcons (Qmenu_bar_external, Qnil),
2985              Fcons (Qmenu_bar_size, Fcons (make_number (0), make_number (0))),
2986              Fcons (Qtool_bar_external,
2987                     FRAME_EXTERNAL_TOOL_BAR (f) ? Qt : Qnil),
2988              Fcons (Qtool_bar_position, FRAME_TOOL_BAR_POSITION (f)),
2989              Fcons (Qtool_bar_size,
2990                     Fcons (make_number (tool_bar_width),
2991                            make_number (tool_bar_height))),
2992              Fcons (Qinternal_border_width,
2993                     make_number (internal_border_width)));
2996 DEFUN ("ns-frame-geometry", Fns_frame_geometry, Sns_frame_geometry, 0, 1, 0,
2997        doc: /* Return geometric attributes of FRAME.
2998 FRAME must be a live frame and defaults to the selected one.  The return
2999 value is an association list of the attributes listed below.  All height
3000 and width values are in pixels.
3002 `outer-position' is a cons of the outer left and top edges of FRAME
3003   relative to the origin - the position (0, 0) - of FRAME's display.
3005 `outer-size' is a cons of the outer width and height of FRAME.  The
3006   outer size includes the title bar and the external borders as well as
3007   any menu and/or tool bar of frame.
3009 `external-border-size' is a cons of the horizontal and vertical width of
3010   FRAME's external borders as supplied by the window manager.
3012 `title-bar-size' is a cons of the width and height of the title bar of
3013   FRAME as supplied by the window manager.  If both of them are zero,
3014   FRAME has no title bar.  If only the width is zero, Emacs was not
3015   able to retrieve the width information.
3017 `menu-bar-external', if non-nil, means the menu bar is external (never
3018   included in the inner edges of FRAME).
3020 `menu-bar-size' is a cons of the width and height of the menu bar of
3021   FRAME.
3023 `tool-bar-external', if non-nil, means the tool bar is external (never
3024   included in the inner edges of FRAME).
3026 `tool-bar-position' tells on which side the tool bar on FRAME is and can
3027   be one of `left', `top', `right' or `bottom'.  If this is nil, FRAME
3028   has no tool bar.
3030 `tool-bar-size' is a cons of the width and height of the tool bar of
3031   FRAME.
3033 `internal-border-width' is the width of the internal border of
3034   FRAME.  */)
3035   (Lisp_Object frame)
3037   return frame_geometry (frame, Qnil);
3040 DEFUN ("ns-frame-edges", Fns_frame_edges, Sns_frame_edges, 0, 2, 0,
3041        doc: /* Return edge coordinates of FRAME.
3042 FRAME must be a live frame and defaults to the selected one.  The return
3043 value is a list of the form (LEFT, TOP, RIGHT, BOTTOM).  All values are
3044 in pixels relative to the origin - the position (0, 0) - of FRAME's
3045 display.
3047 If optional argument TYPE is the symbol `outer-edges', return the outer
3048 edges of FRAME.  The outer edges comprise the decorations of the window
3049 manager (like the title bar or external borders) as well as any external
3050 menu or tool bar of FRAME.  If optional argument TYPE is the symbol
3051 `native-edges' or nil, return the native edges of FRAME.  The native
3052 edges exclude the decorations of the window manager and any external
3053 menu or tool bar of FRAME.  If TYPE is the symbol `inner-edges', return
3054 the inner edges of FRAME.  These edges exclude title bar, any borders,
3055 menu bar or tool bar of FRAME.  */)
3056   (Lisp_Object frame, Lisp_Object type)
3058   return frame_geometry (frame, ((EQ (type, Qouter_edges)
3059                                   || EQ (type, Qinner_edges))
3060                                  ? type
3061                                  : Qnative_edges));
3064 DEFUN ("ns-set-mouse-absolute-pixel-position",
3065        Fns_set_mouse_absolute_pixel_position,
3066        Sns_set_mouse_absolute_pixel_position, 2, 2, 0,
3067        doc: /* Move mouse pointer to absolute pixel position (X, Y).
3068 The coordinates X and Y are interpreted in pixels relative to a position
3069 \(0, 0) of the selected frame's display.  */)
3070        (Lisp_Object x, Lisp_Object y)
3072 #ifdef NS_IMPL_COCOA
3073   /* GNUstep doesn't support CGWarpMouseCursorPosition, so none of
3074      this will work. */
3075   struct frame *f = SELECTED_FRAME ();
3076   EmacsView *view = FRAME_NS_VIEW (f);
3077   NSScreen *screen = [[view window] screen];
3078   NSRect screen_frame = [screen frame];
3079   int mouse_x, mouse_y;
3081   NSScreen *primary_screen = [[NSScreen screens] objectAtIndex:0];
3082   NSRect primary_screen_frame = [primary_screen frame];
3083   CGFloat primary_screen_height = primary_screen_frame.size.height;
3085   if (FRAME_INITIAL_P (f) || !FRAME_NS_P (f))
3086     return Qnil;
3088   CHECK_TYPE_RANGED_INTEGER (int, x);
3089   CHECK_TYPE_RANGED_INTEGER (int, y);
3091   mouse_x = screen_frame.origin.x + XINT (x);
3093   if (screen == primary_screen)
3094     mouse_y = screen_frame.origin.y + XINT (y);
3095   else
3096     mouse_y = (primary_screen_height - screen_frame.size.height
3097                - screen_frame.origin.y) + XINT (y);
3099   CGPoint mouse_pos = CGPointMake(mouse_x, mouse_y);
3100   CGWarpMouseCursorPosition (mouse_pos);
3101 #endif /* NS_IMPL_COCOA */
3103   return Qnil;
3106 DEFUN ("ns-mouse-absolute-pixel-position",
3107        Fns_mouse_absolute_pixel_position,
3108        Sns_mouse_absolute_pixel_position, 0, 0, 0,
3109        doc: /* Return absolute position of mouse cursor in pixels.
3110 The position is returned as a cons cell (X . Y) of the
3111 coordinates of the mouse cursor position in pixels relative to a
3112 position (0, 0) of the selected frame's terminal. */)
3113      (void)
3115   struct frame *f = SELECTED_FRAME ();
3116   EmacsView *view = FRAME_NS_VIEW (f);
3117   NSScreen *screen = [[view window] screen];
3118   NSPoint pt = [NSEvent mouseLocation];
3120   return Fcons(make_number(pt.x - screen.frame.origin.x),
3121                make_number(screen.frame.size.height -
3122                            (pt.y - screen.frame.origin.y)));
3125 /* ==========================================================================
3127     Class implementations
3129    ========================================================================== */
3132   Handle arrow/function/control keys and copy/paste/cut in file dialogs.
3133   Return YES if handled, NO if not.
3134  */
3135 static BOOL
3136 handlePanelKeys (NSSavePanel *panel, NSEvent *theEvent)
3138   NSString *s;
3139   int i;
3140   BOOL ret = NO;
3142   if ([theEvent type] != NSEventTypeKeyDown) return NO;
3143   s = [theEvent characters];
3145   for (i = 0; i < [s length]; ++i)
3146     {
3147       int ch = (int) [s characterAtIndex: i];
3148       switch (ch)
3149         {
3150         case NSHomeFunctionKey:
3151         case NSDownArrowFunctionKey:
3152         case NSUpArrowFunctionKey:
3153         case NSLeftArrowFunctionKey:
3154         case NSRightArrowFunctionKey:
3155         case NSPageUpFunctionKey:
3156         case NSPageDownFunctionKey:
3157         case NSEndFunctionKey:
3158           /* Don't send command modified keys, as those are handled in the
3159              performKeyEquivalent method of the super class.
3160           */
3161           if (! ([theEvent modifierFlags] & NSEventModifierFlagCommand))
3162             {
3163               [panel sendEvent: theEvent];
3164               ret = YES;
3165             }
3166           break;
3167           /* As we don't have the standard key commands for
3168              copy/paste/cut/select-all in our edit menu, we must handle
3169              them here.  TODO: handle Emacs key bindings for copy/cut/select-all
3170              here, paste works, because we have that in our Edit menu.
3171              I.e. refactor out code in nsterm.m, keyDown: to figure out the
3172              correct modifier.
3173           */
3174         case 'x': // Cut
3175         case 'c': // Copy
3176         case 'v': // Paste
3177         case 'a': // Select all
3178           if ([theEvent modifierFlags] & NSEventModifierFlagCommand)
3179             {
3180               [NSApp sendAction:
3181                        (ch == 'x'
3182                         ? @selector(cut:)
3183                         : (ch == 'c'
3184                            ? @selector(copy:)
3185                            : (ch == 'v'
3186                               ? @selector(paste:)
3187                               : @selector(selectAll:))))
3188                              to:nil from:panel];
3189               ret = YES;
3190             }
3191         default:
3192           // Send all control keys, as the text field supports C-a, C-f, C-e
3193           // C-b and more.
3194           if ([theEvent modifierFlags] & NSEventModifierFlagControl)
3195             {
3196               [panel sendEvent: theEvent];
3197               ret = YES;
3198             }
3199           break;
3200         }
3201     }
3204   return ret;
3207 @implementation EmacsSavePanel
3208 - (BOOL)performKeyEquivalent:(NSEvent *)theEvent
3210   BOOL ret = handlePanelKeys (self, theEvent);
3211   if (! ret)
3212     ret = [super performKeyEquivalent:theEvent];
3213   return ret;
3215 @end
3218 @implementation EmacsOpenPanel
3219 - (BOOL)performKeyEquivalent:(NSEvent *)theEvent
3221   // NSOpenPanel inherits NSSavePanel, so passing self is OK.
3222   BOOL ret = handlePanelKeys (self, theEvent);
3223   if (! ret)
3224     ret = [super performKeyEquivalent:theEvent];
3225   return ret;
3227 @end
3230 @implementation EmacsFileDelegate
3231 /* --------------------------------------------------------------------------
3232    Delegate methods for Open/Save panels
3233    -------------------------------------------------------------------------- */
3234 - (BOOL)panel: (id)sender isValidFilename: (NSString *)filename
3236   return YES;
3238 - (BOOL)panel: (id)sender shouldShowFilename: (NSString *)filename
3240   return YES;
3242 - (NSString *)panel: (id)sender userEnteredFilename: (NSString *)filename
3243           confirmed: (BOOL)okFlag
3245   return filename;
3247 @end
3249 #endif
3252 /* ==========================================================================
3254     Lisp interface declaration
3256    ========================================================================== */
3259 void
3260 syms_of_nsfns (void)
3262   DEFSYM (Qfontsize, "fontsize");
3263   DEFSYM (Qframe_title_format, "frame-title-format");
3264   DEFSYM (Qicon_title_format, "icon-title-format");
3265   DEFSYM (Qdark, "dark");
3267   DEFVAR_LISP ("ns-icon-type-alist", Vns_icon_type_alist,
3268                doc: /* Alist of elements (REGEXP . IMAGE) for images of icons associated to frames.
3269 If the title of a frame matches REGEXP, then IMAGE.tiff is
3270 selected as the image of the icon representing the frame when it's
3271 miniaturized.  If an element is t, then Emacs tries to select an icon
3272 based on the filetype of the visited file.
3274 The images have to be installed in a folder called English.lproj in the
3275 Emacs folder.  You have to restart Emacs after installing new icons.
3277 Example: Install an icon Gnus.tiff and execute the following code
3279   (setq ns-icon-type-alist
3280         (append ns-icon-type-alist
3281                 \\='((\"^\\\\*\\\\(Group\\\\*$\\\\|Summary \\\\|Article\\\\*$\\\\)\"
3282                    . \"Gnus\"))))
3284 When you miniaturize a Group, Summary or Article frame, Gnus.tiff will
3285 be used as the image of the icon representing the frame.  */);
3286   Vns_icon_type_alist = list1 (Qt);
3288   DEFVAR_LISP ("ns-version-string", Vns_version_string,
3289                doc: /* Toolkit version for NS Windowing.  */);
3290   Vns_version_string = ns_appkit_version_str ();
3292   defsubr (&Sns_read_file_name);
3293   defsubr (&Sns_get_resource);
3294   defsubr (&Sns_set_resource);
3295   defsubr (&Sxw_display_color_p); /* this and next called directly by C code */
3296   defsubr (&Sx_display_grayscale_p);
3297   defsubr (&Sns_font_name);
3298   defsubr (&Sns_list_colors);
3299 #ifdef NS_IMPL_COCOA
3300   defsubr (&Sns_do_applescript);
3301 #endif
3302   defsubr (&Sxw_color_defined_p);
3303   defsubr (&Sxw_color_values);
3304   defsubr (&Sx_server_max_request_size);
3305   defsubr (&Sx_server_vendor);
3306   defsubr (&Sx_server_version);
3307   defsubr (&Sx_display_pixel_width);
3308   defsubr (&Sx_display_pixel_height);
3309   defsubr (&Sns_display_monitor_attributes_list);
3310   defsubr (&Sns_frame_geometry);
3311   defsubr (&Sns_frame_edges);
3312   defsubr (&Sns_frame_list_z_order);
3313   defsubr (&Sns_frame_restack);
3314   defsubr (&Sns_set_mouse_absolute_pixel_position);
3315   defsubr (&Sns_mouse_absolute_pixel_position);
3316   defsubr (&Sx_display_mm_width);
3317   defsubr (&Sx_display_mm_height);
3318   defsubr (&Sx_display_screens);
3319   defsubr (&Sx_display_planes);
3320   defsubr (&Sx_display_color_cells);
3321   defsubr (&Sx_display_visual_class);
3322   defsubr (&Sx_display_backing_store);
3323   defsubr (&Sx_display_save_under);
3324   defsubr (&Sx_create_frame);
3325   defsubr (&Sx_open_connection);
3326   defsubr (&Sx_close_connection);
3327   defsubr (&Sx_display_list);
3329   defsubr (&Sns_hide_others);
3330   defsubr (&Sns_hide_emacs);
3331   defsubr (&Sns_emacs_info_panel);
3332   defsubr (&Sns_list_services);
3333   defsubr (&Sns_perform_service);
3334   defsubr (&Sns_popup_font_panel);
3335   defsubr (&Sns_popup_color_panel);
3337   defsubr (&Sx_show_tip);
3338   defsubr (&Sx_hide_tip);
3340   as_status = 0;
3341   as_script = Qnil;
3342   as_result = 0;