Add seq-set-equal-p to test for set equality
[emacs.git] / src / nsfns.m
blobcbe0ffb85804d424fecdc2f87ba83e4746fd4a27
1 /* Functions for the NeXT/Open/GNUstep and macOS window system.
3 Copyright (C) 1989, 1992-1994, 2005-2006, 2008-2017 Free Software
4 Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or (at
11 your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.  */
22 Originally by Carl Edman
23 Updated by Christian Limpach (chris@nice.ch)
24 OpenStep/Rhapsody port by Scott Bender (sbender@harmony-ds.com)
25 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 static Lisp_Object
179 interpret_services_menu (NSMenu *menu, Lisp_Object prefix, Lisp_Object old)
180 /* --------------------------------------------------------------------------
181    Turn the input menu (an NSMenu) into a lisp list for tracking on lisp side
182    -------------------------------------------------------------------------- */
184   int i, count;
185   NSMenuItem *item;
186   const char *name;
187   Lisp_Object nameStr;
188   unsigned short key;
189   NSString *keys;
190   Lisp_Object res;
192   count = [menu numberOfItems];
193   for (i = 0; i<count; i++)
194     {
195       item = [menu itemAtIndex: i];
196       name = [[item title] UTF8String];
197       if (!name) continue;
199       nameStr = build_string (name);
201       if ([item hasSubmenu])
202         {
203           old = interpret_services_menu ([item submenu],
204                                         Fcons (nameStr, prefix), old);
205         }
206       else
207         {
208           keys = [item keyEquivalent];
209           if (keys && [keys length] )
210             {
211               key = [keys characterAtIndex: 0];
212               res = make_number (key|super_modifier);
213             }
214           else
215             {
216               res = Qundefined;
217             }
218           old = Fcons (Fcons (res,
219                             Freverse (Fcons (nameStr,
220                                            prefix))),
221                     old);
222         }
223     }
224   return old;
229 /* ==========================================================================
231     Frame parameter setters
233    ========================================================================== */
236 static void
237 x_set_foreground_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
239   NSColor *col;
240   EmacsCGFloat r, g, b, alpha;
242   /* Must block_input, because ns_lisp_to_color does block/unblock_input
243      which means that col may be deallocated in its unblock_input if there
244      is user input, unless we also block_input.  */
245   block_input ();
246   if (ns_lisp_to_color (arg, &col))
247     {
248       store_frame_param (f, Qforeground_color, oldval);
249       unblock_input ();
250       error ("Unknown color");
251     }
253   [col retain];
254   [f->output_data.ns->foreground_color release];
255   f->output_data.ns->foreground_color = col;
257   [col getRed: &r green: &g blue: &b alpha: &alpha];
258   FRAME_FOREGROUND_PIXEL (f) =
259     ARGB_TO_ULONG ((int)(alpha*0xff), (int)(r*0xff), (int)(g*0xff), (int)(b*0xff));
261   if (FRAME_NS_VIEW (f))
262     {
263       update_face_from_frame_parameter (f, Qforeground_color, arg);
264       /*recompute_basic_faces (f); */
265       if (FRAME_VISIBLE_P (f))
266         SET_FRAME_GARBAGED (f);
267     }
268   unblock_input ();
272 static void
273 x_set_background_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
275   struct face *face;
276   NSColor *col;
277   NSView *view = FRAME_NS_VIEW (f);
278   EmacsCGFloat r, g, b, alpha;
280   block_input ();
281   if (ns_lisp_to_color (arg, &col))
282     {
283       store_frame_param (f, Qbackground_color, oldval);
284       unblock_input ();
285       error ("Unknown color");
286     }
288   /* clear the frame; in some instances the NS-internal GC appears not to
289      update, or it does update and cannot clear old text properly */
290   if (FRAME_VISIBLE_P (f))
291     ns_clear_frame (f);
293   [col retain];
294   [f->output_data.ns->background_color release];
295   f->output_data.ns->background_color = col;
297   [col getRed: &r green: &g blue: &b alpha: &alpha];
298   FRAME_BACKGROUND_PIXEL (f) =
299     ARGB_TO_ULONG ((int)(alpha*0xff), (int)(r*0xff), (int)(g*0xff), (int)(b*0xff));
301   if (view != nil)
302     {
303       [[view window] setBackgroundColor: col];
305       if (alpha != (EmacsCGFloat) 1.0)
306           [[view window] setOpaque: NO];
307       else
308           [[view window] setOpaque: YES];
310       face = FRAME_DEFAULT_FACE (f);
311       if (face)
312         {
313           col = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f);
314           face->background = ns_index_color
315             ([col colorWithAlphaComponent: alpha], f);
317           update_face_from_frame_parameter (f, Qbackground_color, arg);
318         }
320       if (FRAME_VISIBLE_P (f))
321         SET_FRAME_GARBAGED (f);
322     }
323   unblock_input ();
327 static void
328 x_set_cursor_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
330   NSColor *col;
332   block_input ();
333   if (ns_lisp_to_color (arg, &col))
334     {
335       store_frame_param (f, Qcursor_color, oldval);
336       unblock_input ();
337       error ("Unknown color");
338     }
340   [FRAME_CURSOR_COLOR (f) release];
341   FRAME_CURSOR_COLOR (f) = [col retain];
343   if (FRAME_VISIBLE_P (f))
344     {
345       x_update_cursor (f, 0);
346       x_update_cursor (f, 1);
347     }
348   update_face_from_frame_parameter (f, Qcursor_color, arg);
349   unblock_input ();
353 static void
354 x_set_icon_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
356   NSView *view = FRAME_NS_VIEW (f);
357   NSTRACE ("x_set_icon_name");
359   /* see if it's changed */
360   if (STRINGP (arg))
361     {
362       if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
363         return;
364     }
365   else if (!STRINGP (oldval) && EQ (oldval, Qnil) == EQ (arg, Qnil))
366     return;
368   fset_icon_name (f, arg);
370   if (NILP (arg))
371     {
372       if (!NILP (f->title))
373         arg = f->title;
374       else
375         /* Explicit name and no icon-name -> explicit_name.  */
376         if (f->explicit_name)
377           arg = f->name;
378         else
379           {
380             /* No explicit name and no icon-name ->
381                name has to be rebuild from icon_title_format.  */
382             windows_or_buffers_changed = 62;
383             return;
384           }
385     }
387   /* Don't change the name if it's already NAME.  */
388   if ([[view window] miniwindowTitle]
389       && ([[[view window] miniwindowTitle]
390              isEqualToString: [NSString stringWithUTF8String:
391                                           SSDATA (arg)]]))
392     return;
394   [[view window] setMiniwindowTitle:
395         [NSString stringWithUTF8String: SSDATA (arg)]];
398 static void
399 ns_set_name_internal (struct frame *f, Lisp_Object name)
401   Lisp_Object encoded_name, encoded_icon_name;
402   NSString *str;
403   NSView *view = FRAME_NS_VIEW (f);
406   encoded_name = ENCODE_UTF_8 (name);
408   str = [NSString stringWithUTF8String: SSDATA (encoded_name)];
411   /* Don't change the name if it's already NAME.  */
412   if (! [[[view window] title] isEqualToString: str])
413     [[view window] setTitle: str];
415   if (!STRINGP (f->icon_name))
416     encoded_icon_name = encoded_name;
417   else
418     encoded_icon_name = ENCODE_UTF_8 (f->icon_name);
420   str = [NSString stringWithUTF8String: SSDATA (encoded_icon_name)];
422   if ([[view window] miniwindowTitle]
423       && ! [[[view window] miniwindowTitle] isEqualToString: str])
424     [[view window] setMiniwindowTitle: str];
428 static void
429 ns_set_name (struct frame *f, Lisp_Object name, int explicit)
431   NSTRACE ("ns_set_name");
433   /* Make sure that requests from lisp code override requests from
434      Emacs redisplay code.  */
435   if (explicit)
436     {
437       /* If we're switching from explicit to implicit, we had better
438          update the mode lines and thereby update the title.  */
439       if (f->explicit_name && NILP (name))
440         update_mode_lines = 21;
442       f->explicit_name = ! NILP (name);
443     }
444   else if (f->explicit_name)
445     return;
447   if (NILP (name))
448     name = build_string ([ns_app_name UTF8String]);
449   else
450     CHECK_STRING (name);
452   /* Don't change the name if it's already NAME.  */
453   if (! NILP (Fstring_equal (name, f->name)))
454     return;
456   fset_name (f, name);
458   /* Title overrides explicit name.  */
459   if (! NILP (f->title))
460     name = f->title;
462   ns_set_name_internal (f, name);
466 /* This function should be called when the user's lisp code has
467    specified a name for the frame; the name will override any set by the
468    redisplay code.  */
469 static void
470 x_explicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
472   NSTRACE ("x_explicitly_set_name");
473   ns_set_name (f, arg, 1);
477 /* This function should be called by Emacs redisplay code to set the
478    name; names set this way will never override names set by the user's
479    lisp code.  */
480 void
481 x_implicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
483   NSTRACE ("x_implicitly_set_name");
485   Lisp_Object frame_title = buffer_local_value
486     (Qframe_title_format, XWINDOW (f->selected_window)->contents);
487   Lisp_Object icon_title = buffer_local_value
488     (Qicon_title_format, XWINDOW (f->selected_window)->contents);
490   /* Deal with NS specific format t.  */
491   if (FRAME_NS_P (f) && ((FRAME_ICONIFIED_P (f) && EQ (icon_title, Qt))
492                          || EQ (frame_title, Qt)))
493     ns_set_name_as_filename (f);
494   else
495     ns_set_name (f, arg, 0);
499 /* Change the title of frame F to NAME.
500    If NAME is nil, use the frame name as the title.  */
502 static void
503 x_set_title (struct frame *f, Lisp_Object name, Lisp_Object old_name)
505   NSTRACE ("x_set_title");
506   /* Don't change the title if it's already NAME.  */
507   if (EQ (name, f->title))
508     return;
510   update_mode_lines = 22;
512   fset_title (f, name);
514   if (NILP (name))
515     name = f->name;
516   else
517     CHECK_STRING (name);
519   ns_set_name_internal (f, name);
523 static void
524 ns_set_name_as_filename (struct frame *f)
526   NSView *view;
527   Lisp_Object name, filename;
528   Lisp_Object buf = XWINDOW (f->selected_window)->contents;
529   const char *title;
530   NSAutoreleasePool *pool;
531   Lisp_Object encoded_name, encoded_filename;
532   NSString *str;
533   NSTRACE ("ns_set_name_as_filename");
535   if (f->explicit_name || ! NILP (f->title))
536     return;
538   block_input ();
539   pool = [[NSAutoreleasePool alloc] init];
540   filename = BVAR (XBUFFER (buf), filename);
541   name = BVAR (XBUFFER (buf), name);
543   if (NILP (name))
544     {
545       if (! NILP (filename))
546         name = Ffile_name_nondirectory (filename);
547       else
548         name = build_string ([ns_app_name UTF8String]);
549     }
551   encoded_name = ENCODE_UTF_8 (name);
553   view = FRAME_NS_VIEW (f);
555   title = FRAME_ICONIFIED_P (f) ? [[[view window] miniwindowTitle] UTF8String]
556                                 : [[[view window] title] UTF8String];
558   if (title && (! strcmp (title, SSDATA (encoded_name))))
559     {
560       [pool release];
561       unblock_input ();
562       return;
563     }
565   str = [NSString stringWithUTF8String: SSDATA (encoded_name)];
566   if (str == nil) str = @"Bad coding";
568   if (FRAME_ICONIFIED_P (f))
569     [[view window] setMiniwindowTitle: str];
570   else
571     {
572       NSString *fstr;
574       if (! NILP (filename))
575         {
576           encoded_filename = ENCODE_UTF_8 (filename);
578           fstr = [NSString stringWithUTF8String: SSDATA (encoded_filename)];
579           if (fstr == nil) fstr = @"";
580         }
581       else
582         fstr = @"";
584       ns_set_represented_filename (fstr, f);
585       [[view window] setTitle: str];
586       fset_name (f, name);
587     }
589   [pool release];
590   unblock_input ();
594 void
595 ns_set_doc_edited (void)
597   NSAutoreleasePool *pool;
598   Lisp_Object tail, frame;
599   block_input ();
600   pool = [[NSAutoreleasePool alloc] init];
601   FOR_EACH_FRAME (tail, frame)
602     {
603       BOOL edited = NO;
604       struct frame *f = XFRAME (frame);
605       struct window *w;
606       NSView *view;
608       if (! FRAME_NS_P (f)) continue;
609       w = XWINDOW (FRAME_SELECTED_WINDOW (f));
610       view = FRAME_NS_VIEW (f);
611       if (!MINI_WINDOW_P (w))
612         edited = ! NILP (Fbuffer_modified_p (w->contents)) &&
613           ! NILP (Fbuffer_file_name (w->contents));
614       [[view window] setDocumentEdited: edited];
615     }
617   [pool release];
618   unblock_input ();
622 static void
623 x_set_menu_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
625   int nlines;
626   if (FRAME_MINIBUF_ONLY_P (f))
627     return;
629   if (TYPE_RANGED_INTEGERP (int, value))
630     nlines = XINT (value);
631   else
632     nlines = 0;
634   FRAME_MENU_BAR_LINES (f) = 0;
635   if (nlines)
636     {
637       FRAME_EXTERNAL_MENU_BAR (f) = 1;
638       /* does for all frames, whereas we just want for one frame
639          [NSMenu setMenuBarVisible: YES]; */
640     }
641   else
642     {
643       if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
644         free_frame_menubar (f);
645       /*      [NSMenu setMenuBarVisible: NO]; */
646       FRAME_EXTERNAL_MENU_BAR (f) = 0;
647     }
651 /* toolbar support */
652 static void
653 x_set_tool_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
655   /* Currently, when the tool bar change state, the frame is resized.
657      TODO: It would be better if this didn't occur when 1) the frame
658      is full height or maximized or 2) when specified by
659      `frame-inhibit-implied-resize'. */
660   int nlines;
662   NSTRACE ("x_set_tool_bar_lines");
664   if (FRAME_MINIBUF_ONLY_P (f))
665     return;
667   if (RANGED_INTEGERP (0, value, INT_MAX))
668     nlines = XFASTINT (value);
669   else
670     nlines = 0;
672   if (nlines)
673     {
674       FRAME_EXTERNAL_TOOL_BAR (f) = 1;
675       update_frame_tool_bar (f);
676     }
677   else
678     {
679       if (FRAME_EXTERNAL_TOOL_BAR (f))
680         {
681           free_frame_tool_bar (f);
682           FRAME_EXTERNAL_TOOL_BAR (f) = 0;
684           {
685             EmacsView *view = FRAME_NS_VIEW (f);
686             int fs_state = [view fullscreenState];
688             if (fs_state == FULLSCREEN_MAXIMIZED)
689               {
690                 [view setFSValue:FULLSCREEN_WIDTH];
691               }
692             else if (fs_state == FULLSCREEN_HEIGHT)
693               {
694                 [view setFSValue:FULLSCREEN_NONE];
695               }
696           }
697        }
698     }
700   {
701     int inhibit
702       = ((f->after_make_frame
703           && !f->tool_bar_resized
704           && (EQ (frame_inhibit_implied_resize, Qt)
705               || (CONSP (frame_inhibit_implied_resize)
706                   && !NILP (Fmemq (Qtool_bar_lines,
707                                    frame_inhibit_implied_resize))))
708           && NILP (get_frame_param (f, Qfullscreen)))
709          ? 0
710          : 2);
712     NSTRACE_MSG ("inhibit:%d", inhibit);
714     frame_size_history_add (f, Qupdate_frame_tool_bar, 0, 0, Qnil);
715     adjust_frame_size (f, -1, -1, inhibit, 0, Qtool_bar_lines);
716   }
720 static void
721 x_set_internal_border_width (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
723   int old_width = FRAME_INTERNAL_BORDER_WIDTH (f);
725   CHECK_TYPE_RANGED_INTEGER (int, arg);
726   f->internal_border_width = XINT (arg);
727   if (FRAME_INTERNAL_BORDER_WIDTH (f) < 0)
728     f->internal_border_width = 0;
730   if (FRAME_INTERNAL_BORDER_WIDTH (f) == old_width)
731     return;
733   if (FRAME_X_WINDOW (f) != 0)
734     adjust_frame_size (f, -1, -1, 3, 0, Qinternal_border_width);
736   SET_FRAME_GARBAGED (f);
740 static void
741 ns_implicitly_set_icon_type (struct frame *f)
743   Lisp_Object tem;
744   EmacsView *view = FRAME_NS_VIEW (f);
745   id image = nil;
746   Lisp_Object chain, elt;
747   NSAutoreleasePool *pool;
748   BOOL setMini = YES;
750   NSTRACE ("ns_implicitly_set_icon_type");
752   block_input ();
753   pool = [[NSAutoreleasePool alloc] init];
754   if (f->output_data.ns->miniimage
755       && [[NSString stringWithUTF8String: SSDATA (f->name)]
756                isEqualToString: [(NSImage *)f->output_data.ns->miniimage name]])
757     {
758       [pool release];
759       unblock_input ();
760       return;
761     }
763   tem = assq_no_quit (Qicon_type, f->param_alist);
764   if (CONSP (tem) && ! NILP (XCDR (tem)))
765     {
766       [pool release];
767       unblock_input ();
768       return;
769     }
771   for (chain = Vns_icon_type_alist;
772        image == nil && CONSP (chain);
773        chain = XCDR (chain))
774     {
775       elt = XCAR (chain);
776       /* special case: t means go by file type */
777       if (SYMBOLP (elt) && EQ (elt, Qt) && SSDATA (f->name)[0] == '/')
778         {
779           NSString *str
780              = [NSString stringWithUTF8String: SSDATA (f->name)];
781           if ([[NSFileManager defaultManager] fileExistsAtPath: str])
782             image = [[[NSWorkspace sharedWorkspace] iconForFile: str] retain];
783         }
784       else if (CONSP (elt) &&
785                STRINGP (XCAR (elt)) &&
786                STRINGP (XCDR (elt)) &&
787                fast_string_match (XCAR (elt), f->name) >= 0)
788         {
789           image = [EmacsImage allocInitFromFile: XCDR (elt)];
790           if (image == nil)
791             image = [[NSImage imageNamed:
792                                [NSString stringWithUTF8String:
793                                             SSDATA (XCDR (elt))]] retain];
794         }
795     }
797   if (image == nil)
798     {
799       image = [[[NSWorkspace sharedWorkspace] iconForFileType: @"text"] retain];
800       setMini = NO;
801     }
803   [f->output_data.ns->miniimage release];
804   f->output_data.ns->miniimage = image;
805   [view setMiniwindowImage: setMini];
806   [pool release];
807   unblock_input ();
811 static void
812 x_set_icon_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
814   EmacsView *view = FRAME_NS_VIEW (f);
815   id image = nil;
816   BOOL setMini = YES;
818   NSTRACE ("x_set_icon_type");
820   if (!NILP (arg) && SYMBOLP (arg))
821     {
822       arg =build_string (SSDATA (SYMBOL_NAME (arg)));
823       store_frame_param (f, Qicon_type, arg);
824     }
826   /* do it the implicit way */
827   if (NILP (arg))
828     {
829       ns_implicitly_set_icon_type (f);
830       return;
831     }
833   CHECK_STRING (arg);
835   image = [EmacsImage allocInitFromFile: arg];
836   if (image == nil)
837     image =[NSImage imageNamed: [NSString stringWithUTF8String:
838                                             SSDATA (arg)]];
840   if (image == nil)
841     {
842       image = [NSImage imageNamed: @"text"];
843       setMini = NO;
844     }
846   f->output_data.ns->miniimage = image;
847   [view setMiniwindowImage: setMini];
850 /* This is the same as the xfns.c definition.  */
851 static void
852 x_set_cursor_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
854   set_frame_cursor_types (f, arg);
857 /* called to set mouse pointer color, but all other terms use it to
858    initialize pointer types (and don't set the color ;) */
859 static void
860 x_set_mouse_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
862   /* don't think we can do this on Nextstep */
866 #define Str(x) #x
867 #define Xstr(x) Str(x)
869 static Lisp_Object
870 ns_appkit_version_str (void)
872   char tmp[256];
874 #ifdef NS_IMPL_GNUSTEP
875   sprintf(tmp, "gnustep-gui-%s", Xstr(GNUSTEP_GUI_VERSION));
876 #elif defined (NS_IMPL_COCOA)
877   NSString *osversion
878     = [[NSProcessInfo processInfo] operatingSystemVersionString];
879   sprintf(tmp, "appkit-%.2f %s",
880           NSAppKitVersionNumber,
881           [osversion UTF8String]);
882 #else
883   tmp = "ns-unknown";
884 #endif
885   return build_string (tmp);
889 /* This is for use by x-server-version and collapses all version info we
890    have into a single int.  For a better picture of the implementation
891    running, use ns_appkit_version_str.*/
892 static int
893 ns_appkit_version_int (void)
895 #ifdef NS_IMPL_GNUSTEP
896   return GNUSTEP_GUI_MAJOR_VERSION * 100 + GNUSTEP_GUI_MINOR_VERSION;
897 #elif defined (NS_IMPL_COCOA)
898   return (int)NSAppKitVersionNumber;
899 #endif
900   return 0;
904 static void
905 x_icon (struct frame *f, Lisp_Object parms)
906 /* --------------------------------------------------------------------------
907    Strangely-named function to set icon position parameters in frame.
908    This is irrelevant under macOS, but might be needed under GNUstep,
909    depending on the window manager used.  Note, this is not a standard
910    frame parameter-setter; it is called directly from x-create-frame.
911    -------------------------------------------------------------------------- */
913   Lisp_Object icon_x, icon_y;
914   struct ns_display_info *dpyinfo = check_ns_display_info (Qnil);
916   f->output_data.ns->icon_top = -1;
917   f->output_data.ns->icon_left = -1;
919   /* Set the position of the icon.  */
920   icon_x = x_get_arg (dpyinfo, parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
921   icon_y = x_get_arg (dpyinfo, parms, Qicon_top, 0, 0,  RES_TYPE_NUMBER);
922   if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
923     {
924       CHECK_NUMBER (icon_x);
925       CHECK_NUMBER (icon_y);
926       f->output_data.ns->icon_top = XINT (icon_y);
927       f->output_data.ns->icon_left = XINT (icon_x);
928     }
929   else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
930     error ("Both left and top icon corners of icon must be specified");
934 /* Note: see frame.c for template, also where generic functions are impl */
935 frame_parm_handler ns_frame_parm_handlers[] =
937   x_set_autoraise, /* generic OK */
938   x_set_autolower, /* generic OK */
939   x_set_background_color,
940   0, /* x_set_border_color,  may be impossible under Nextstep */
941   0, /* x_set_border_width,  may be impossible under Nextstep */
942   x_set_cursor_color,
943   x_set_cursor_type,
944   x_set_font, /* generic OK */
945   x_set_foreground_color,
946   x_set_icon_name,
947   x_set_icon_type,
948   x_set_internal_border_width, /* generic OK */
949   x_set_right_divider_width,
950   x_set_bottom_divider_width,
951   x_set_menu_bar_lines,
952   x_set_mouse_color,
953   x_explicitly_set_name,
954   x_set_scroll_bar_width, /* generic OK */
955   x_set_scroll_bar_height, /* generic OK */
956   x_set_title,
957   x_set_unsplittable, /* generic OK */
958   x_set_vertical_scroll_bars, /* generic OK */
959   x_set_horizontal_scroll_bars, /* generic OK */
960   x_set_visibility, /* generic OK */
961   x_set_tool_bar_lines,
962   0, /* x_set_scroll_bar_foreground, will ignore (not possible on NS) */
963   0, /* x_set_scroll_bar_background,  will ignore (not possible on NS) */
964   x_set_screen_gamma, /* generic OK */
965   x_set_line_spacing, /* generic OK, sets f->extra_line_spacing to int */
966   x_set_left_fringe, /* generic OK */
967   x_set_right_fringe, /* generic OK */
968   0, /* x_set_wait_for_wm, will ignore */
969   x_set_fullscreen, /* generic OK */
970   x_set_font_backend, /* generic OK */
971   x_set_alpha,
972   0, /* x_set_sticky */
973   0, /* x_set_tool_bar_position */
974   0, /* x_set_inhibit_double_buffering */
975 #ifdef NS_IMPL_COCOA
976   x_set_undecorated,
977 #else
978   0, /*x_set_undecorated */
979 #endif
980   x_set_parent_frame,
981   0, /* x_set_skip_taskbar */
982   0, /* x_set_no_focus_on_map */
983   x_set_no_accept_focus,
984   x_set_z_group, /* x_set_z_group */
985   0, /* x_set_override_redirect */
989 /* Handler for signals raised during x_create_frame.
990    FRAME is the frame which is partially constructed.  */
992 static void
993 unwind_create_frame (Lisp_Object frame)
995   struct frame *f = XFRAME (frame);
997   /* If frame is already dead, nothing to do.  This can happen if the
998      display is disconnected after the frame has become official, but
999      before x_create_frame removes the unwind protect.  */
1000   if (!FRAME_LIVE_P (f))
1001     return;
1003   /* If frame is ``official'', nothing to do.  */
1004   if (NILP (Fmemq (frame, Vframe_list)))
1005     {
1006 #if defined GLYPH_DEBUG && defined ENABLE_CHECKING
1007       struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1008 #endif
1010       /* If the frame's image cache refcount is still the same as our
1011          private shadow variable, it means we are unwinding a frame
1012          for which we didn't yet call init_frame_faces, where the
1013          refcount is incremented.  Therefore, we increment it here, so
1014          that free_frame_faces, called in x_free_frame_resources
1015          below, will not mistakenly decrement the counter that was not
1016          incremented yet to account for this new frame.  */
1017       if (FRAME_IMAGE_CACHE (f) != NULL
1018           && FRAME_IMAGE_CACHE (f)->refcount == image_cache_refcount)
1019         FRAME_IMAGE_CACHE (f)->refcount++;
1021       x_free_frame_resources (f);
1022       free_glyphs (f);
1024 #if defined GLYPH_DEBUG && defined ENABLE_CHECKING
1025       /* Check that reference counts are indeed correct.  */
1026       eassert (dpyinfo->terminal->image_cache->refcount == image_cache_refcount);
1027 #endif
1028     }
1032  * Read geometry related parameters from preferences if not in PARMS.
1033  * Returns the union of parms and any preferences read.
1034  */
1036 static Lisp_Object
1037 get_geometry_from_preferences (struct ns_display_info *dpyinfo,
1038                                Lisp_Object parms)
1040   struct {
1041     const char *val;
1042     const char *cls;
1043     Lisp_Object tem;
1044   } r[] = {
1045     { "width",  "Width", Qwidth },
1046     { "height", "Height", Qheight },
1047     { "left", "Left", Qleft },
1048     { "top", "Top", Qtop },
1049   };
1051   int i;
1052   for (i = 0; i < ARRAYELTS (r); ++i)
1053     {
1054       if (NILP (Fassq (r[i].tem, parms)))
1055         {
1056           Lisp_Object value
1057             = x_get_arg (dpyinfo, parms, r[i].tem, r[i].val, r[i].cls,
1058                          RES_TYPE_NUMBER);
1059           if (! EQ (value, Qunbound))
1060             parms = Fcons (Fcons (r[i].tem, value), parms);
1061         }
1062     }
1064   return parms;
1067 /* ==========================================================================
1069     Lisp definitions
1071    ========================================================================== */
1073 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
1074        1, 1, 0,
1075        doc: /* Make a new Nextstep window, called a "frame" in Emacs terms.
1076 Return an Emacs frame object.
1077 PARMS is an alist of frame parameters.
1078 If the parameters specify that the frame should not have a minibuffer,
1079 and do not specify a specific minibuffer window to use,
1080 then `default-minibuffer-frame' must be a frame whose minibuffer can
1081 be shared by the new frame.
1083 This function is an internal primitive--use `make-frame' instead.  */)
1084      (Lisp_Object parms)
1086   struct frame *f;
1087   Lisp_Object frame, tem;
1088   Lisp_Object name;
1089   int minibuffer_only = 0;
1090   long window_prompting = 0;
1091   ptrdiff_t count = specpdl_ptr - specpdl;
1092   Lisp_Object display;
1093   struct ns_display_info *dpyinfo = NULL;
1094   Lisp_Object parent, parent_frame;
1095   struct kboard *kb;
1096   static int desc_ctr = 1;
1097   int x_width = 0, x_height = 0;
1099   /* x_get_arg modifies parms.  */
1100   parms = Fcopy_alist (parms);
1102   /* Use this general default value to start with
1103      until we know if this frame has a specified name.  */
1104   Vx_resource_name = Vinvocation_name;
1106   display = x_get_arg (dpyinfo, parms, Qterminal, 0, 0, RES_TYPE_STRING);
1107   if (EQ (display, Qunbound))
1108     display = Qnil;
1109   dpyinfo = check_ns_display_info (display);
1110   kb = dpyinfo->terminal->kboard;
1112   if (!dpyinfo->terminal->name)
1113     error ("Terminal is not live, can't create new frames on it");
1115   name = x_get_arg (dpyinfo, parms, Qname, 0, 0, RES_TYPE_STRING);
1116   if (!STRINGP (name)
1117       && ! EQ (name, Qunbound)
1118       && ! NILP (name))
1119     error ("Invalid frame name--not a string or nil");
1121   if (STRINGP (name))
1122     Vx_resource_name = name;
1124   parent = x_get_arg (dpyinfo, parms, Qparent_id, 0, 0, RES_TYPE_NUMBER);
1125   if (EQ (parent, Qunbound))
1126     parent = Qnil;
1127   if (! NILP (parent))
1128     CHECK_NUMBER (parent);
1130   /* make_frame_without_minibuffer can run Lisp code and garbage collect.  */
1131   /* No need to protect DISPLAY because that's not used after passing
1132      it to make_frame_without_minibuffer.  */
1133   frame = Qnil;
1134   tem = x_get_arg (dpyinfo, parms, Qminibuffer, "minibuffer", "Minibuffer",
1135                   RES_TYPE_SYMBOL);
1136   if (EQ (tem, Qnone) || NILP (tem))
1137       f = make_frame_without_minibuffer (Qnil, kb, display);
1138   else if (EQ (tem, Qonly))
1139     {
1140       f = make_minibuffer_frame ();
1141       minibuffer_only = 1;
1142     }
1143   else if (WINDOWP (tem))
1144       f = make_frame_without_minibuffer (tem, kb, display);
1145   else
1146       f = make_frame (1);
1148   XSETFRAME (frame, f);
1150   f->terminal = dpyinfo->terminal;
1152   f->output_method = output_ns;
1153   f->output_data.ns = xzalloc (sizeof *f->output_data.ns);
1155   FRAME_FONTSET (f) = -1;
1157   fset_icon_name (f, x_get_arg (dpyinfo, parms, Qicon_name,
1158                                 "iconName", "Title",
1159                                 RES_TYPE_STRING));
1160   if (! STRINGP (f->icon_name))
1161     fset_icon_name (f, Qnil);
1163   FRAME_DISPLAY_INFO (f) = dpyinfo;
1165   /* With FRAME_DISPLAY_INFO set up, this unwind-protect is safe.  */
1166   record_unwind_protect (unwind_create_frame, frame);
1168   f->output_data.ns->window_desc = desc_ctr++;
1169   if (TYPE_RANGED_INTEGERP (Window, parent))
1170     {
1171       f->output_data.ns->parent_desc = XFASTINT (parent);
1172       f->output_data.ns->explicit_parent = 1;
1173     }
1174   else
1175     {
1176       f->output_data.ns->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
1177       f->output_data.ns->explicit_parent = 0;
1178     }
1180   /* Set the name; the functions to which we pass f expect the name to
1181      be set.  */
1182   if (EQ (name, Qunbound) || NILP (name) || ! STRINGP (name))
1183     {
1184       fset_name (f, build_string ([ns_app_name UTF8String]));
1185       f->explicit_name = 0;
1186     }
1187   else
1188     {
1189       fset_name (f, name);
1190       f->explicit_name = 1;
1191       specbind (Qx_resource_name, name);
1192     }
1194   block_input ();
1196 #ifdef NS_IMPL_COCOA
1197     mac_register_font_driver (f);
1198 #else
1199     register_font_driver (&nsfont_driver, f);
1200 #endif
1202   image_cache_refcount =
1203     FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
1205   x_default_parameter (f, parms, Qfont_backend, Qnil,
1206                         "fontBackend", "FontBackend", RES_TYPE_STRING);
1208   {
1209     /* use for default font name */
1210     id font = [NSFont userFixedPitchFontOfSize: -1.0]; /* default */
1211     x_default_parameter (f, parms, Qfontsize,
1212                                     make_number (0 /*(int)[font pointSize]*/),
1213                                     "fontSize", "FontSize", RES_TYPE_NUMBER);
1214     // Remove ' Regular', not handled by backends.
1215     char *fontname = xstrdup ([[font displayName] UTF8String]);
1216     int len = strlen (fontname);
1217     if (len > 8 && strcmp (fontname + len - 8, " Regular") == 0)
1218       fontname[len-8] = '\0';
1219     x_default_parameter (f, parms, Qfont,
1220                                  build_string (fontname),
1221                                  "font", "Font", RES_TYPE_STRING);
1222     xfree (fontname);
1223   }
1224   unblock_input ();
1226   x_default_parameter (f, parms, Qborder_width, make_number (0),
1227                        "borderwidth", "BorderWidth", RES_TYPE_NUMBER);
1228   x_default_parameter (f, parms, Qinternal_border_width, make_number (2),
1229                       "internalBorderWidth", "InternalBorderWidth",
1230                       RES_TYPE_NUMBER);
1232   /* default vertical scrollbars on right on Mac */
1233   {
1234       Lisp_Object spos
1235 #ifdef NS_IMPL_GNUSTEP
1236           = Qt;
1237 #else
1238           = Qright;
1239 #endif
1240       x_default_parameter (f, parms, Qvertical_scroll_bars, spos,
1241                            "verticalScrollBars", "VerticalScrollBars",
1242                            RES_TYPE_SYMBOL);
1243   }
1244   x_default_parameter (f, parms, Qhorizontal_scroll_bars, Qnil,
1245                        "horizontalScrollBars", "HorizontalScrollBars",
1246                        RES_TYPE_SYMBOL);
1247   x_default_parameter (f, parms, Qforeground_color, build_string ("Black"),
1248                       "foreground", "Foreground", RES_TYPE_STRING);
1249   x_default_parameter (f, parms, Qbackground_color, build_string ("White"),
1250                       "background", "Background", RES_TYPE_STRING);
1251   /* FIXME: not supported yet in Nextstep */
1252   x_default_parameter (f, parms, Qline_spacing, Qnil,
1253                        "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
1254   x_default_parameter (f, parms, Qleft_fringe, Qnil,
1255                        "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
1256   x_default_parameter (f, parms, Qright_fringe, Qnil,
1257                        "rightFringe", "RightFringe", RES_TYPE_NUMBER);
1259   init_frame_faces (f);
1261   /* Read comment about this code in corresponding place in xfns.c.  */
1262   tem = x_get_arg (dpyinfo, parms, Qmin_width, NULL, NULL, RES_TYPE_NUMBER);
1263   if (NUMBERP (tem))
1264     store_frame_param (f, Qmin_width, tem);
1265   tem = x_get_arg (dpyinfo, parms, Qmin_height, NULL, NULL, RES_TYPE_NUMBER);
1266   if (NUMBERP (tem))
1267     store_frame_param (f, Qmin_height, tem);
1268   adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
1269                      FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 5, 1,
1270                      Qx_create_frame_1);
1272   tem = x_get_arg (dpyinfo, parms, Qundecorated, NULL, NULL, RES_TYPE_BOOLEAN);
1273   FRAME_UNDECORATED (f) = !NILP (tem) && !EQ (tem, Qunbound);
1274   store_frame_param (f, Qundecorated, FRAME_UNDECORATED (f) ? Qt : Qnil);
1276   parent_frame = x_get_arg (dpyinfo, parms, Qparent_frame, NULL, NULL,
1277                             RES_TYPE_SYMBOL);
1278   /* Accept parent-frame iff parent-id was not specified.  */
1279   if (!NILP (parent)
1280       || EQ (parent_frame, Qunbound)
1281       || NILP (parent_frame)
1282       || !FRAMEP (parent_frame)
1283       || !FRAME_LIVE_P (XFRAME (parent_frame)))
1284     parent_frame = Qnil;
1286   fset_parent_frame (f, parent_frame);
1287   store_frame_param (f, Qparent_frame, parent_frame);
1289   x_default_parameter (f, parms, Qz_group, Qnil, NULL, NULL, RES_TYPE_SYMBOL);
1290   x_default_parameter (f, parms, Qno_accept_focus, Qnil,
1291                        NULL, NULL, RES_TYPE_BOOLEAN);
1293   /* The resources controlling the menu-bar and tool-bar are
1294      processed specially at startup, and reflected in the mode
1295      variables; ignore them here.  */
1296   x_default_parameter (f, parms, Qmenu_bar_lines,
1297                        NILP (Vmenu_bar_mode)
1298                        ? make_number (0) : make_number (1),
1299                        NULL, NULL, RES_TYPE_NUMBER);
1300   x_default_parameter (f, parms, Qtool_bar_lines,
1301                        NILP (Vtool_bar_mode)
1302                        ? make_number (0) : make_number (1),
1303                        NULL, NULL, RES_TYPE_NUMBER);
1305   x_default_parameter (f, parms, Qbuffer_predicate, Qnil, "bufferPredicate",
1306                        "BufferPredicate", RES_TYPE_SYMBOL);
1307   x_default_parameter (f, parms, Qtitle, Qnil, "title", "Title",
1308                        RES_TYPE_STRING);
1310   parms = get_geometry_from_preferences (dpyinfo, parms);
1311   window_prompting = x_figure_window_size (f, parms, true, &x_width, &x_height);
1313   tem = x_get_arg (dpyinfo, parms, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
1314   f->no_split = minibuffer_only || (!EQ (tem, Qunbound) && !EQ (tem, Qnil));
1316   /* NOTE: on other terms, this is done in set_mouse_color, however this
1317      was not getting called under Nextstep */
1318   f->output_data.ns->text_cursor = [NSCursor IBeamCursor];
1319   f->output_data.ns->nontext_cursor = [NSCursor arrowCursor];
1320   f->output_data.ns->modeline_cursor = [NSCursor pointingHandCursor];
1321   f->output_data.ns->hand_cursor = [NSCursor pointingHandCursor];
1322   f->output_data.ns->hourglass_cursor = [NSCursor disappearingItemCursor];
1323   f->output_data.ns->horizontal_drag_cursor = [NSCursor resizeLeftRightCursor];
1324   f->output_data.ns->vertical_drag_cursor = [NSCursor resizeUpDownCursor];
1325   FRAME_DISPLAY_INFO (f)->vertical_scroll_bar_cursor
1326      = [NSCursor arrowCursor];
1327   FRAME_DISPLAY_INFO (f)->horizontal_scroll_bar_cursor
1328      = [NSCursor arrowCursor];
1329   f->output_data.ns->current_pointer = f->output_data.ns->text_cursor;
1331   f->output_data.ns->in_animation = NO;
1333   [[EmacsView alloc] initFrameFromEmacs: f];
1335   x_icon (f, parms);
1337   /* ns_display_info does not have a reference_count.  */
1338   f->terminal->reference_count++;
1340   /* It is now ok to make the frame official even if we get an error below.
1341      The frame needs to be on Vframe_list or making it visible won't work. */
1342   Vframe_list = Fcons (frame, Vframe_list);
1344   x_default_parameter (f, parms, Qicon_type, Qnil,
1345                        "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
1347   x_default_parameter (f, parms, Qauto_raise, Qnil,
1348                        "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
1349   x_default_parameter (f, parms, Qauto_lower, Qnil,
1350                        "autoLower", "AutoLower", RES_TYPE_BOOLEAN);
1351   x_default_parameter (f, parms, Qcursor_type, Qbox,
1352                        "cursorType", "CursorType", RES_TYPE_SYMBOL);
1353   x_default_parameter (f, parms, Qscroll_bar_width, Qnil,
1354                        "scrollBarWidth", "ScrollBarWidth",
1355                        RES_TYPE_NUMBER);
1356   x_default_parameter (f, parms, Qscroll_bar_height, Qnil,
1357                        "scrollBarHeight", "ScrollBarHeight",
1358                        RES_TYPE_NUMBER);
1359   x_default_parameter (f, parms, Qalpha, Qnil,
1360                        "alpha", "Alpha", RES_TYPE_NUMBER);
1361   x_default_parameter (f, parms, Qfullscreen, Qnil,
1362                        "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
1364   /* Allow x_set_window_size, now.  */
1365   f->can_x_set_window_size = true;
1367   if (x_width > 0)
1368     SET_FRAME_WIDTH (f, x_width);
1369   if (x_height > 0)
1370     SET_FRAME_HEIGHT (f, x_height);
1372   adjust_frame_size (f, FRAME_TEXT_WIDTH (f), FRAME_TEXT_HEIGHT (f), 0, 1,
1373                      Qx_create_frame_2);
1375   if (! f->output_data.ns->explicit_parent)
1376     {
1377       Lisp_Object visibility;
1379       visibility = x_get_arg (dpyinfo, parms, Qvisibility, 0, 0,
1380                               RES_TYPE_SYMBOL);
1381       if (EQ (visibility, Qunbound))
1382         visibility = Qt;
1384       if (EQ (visibility, Qicon))
1385         x_iconify_frame (f);
1386       else if (! NILP (visibility))
1387         {
1388           x_make_frame_visible (f);
1389           [[FRAME_NS_VIEW (f) window] makeKeyWindow];
1390         }
1391       else
1392         {
1393           /* Must have been Qnil.  */
1394         }
1395     }
1397   if (FRAME_HAS_MINIBUF_P (f)
1398       && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
1399           || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
1400     kset_default_minibuffer_frame (kb, frame);
1402   /* All remaining specified parameters, which have not been "used"
1403      by x_get_arg and friends, now go in the misc. alist of the frame.  */
1404   for (tem = parms; CONSP (tem); tem = XCDR (tem))
1405     if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
1406       fset_param_alist (f, Fcons (XCAR (tem), f->param_alist));
1408   if (window_prompting & USPosition)
1409     x_set_offset (f, f->left_pos, f->top_pos, 1);
1411   /* Make sure windows on this frame appear in calls to next-window
1412      and similar functions.  */
1413   Vwindow_list = Qnil;
1415   return unbind_to (count, frame);
1418 void
1419 x_focus_frame (struct frame *f, bool noactivate)
1421   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1423   if (dpyinfo->x_focus_frame != f)
1424     {
1425       EmacsView *view = FRAME_NS_VIEW (f);
1426       block_input ();
1427       [NSApp activateIgnoringOtherApps: YES];
1428       [[view window] makeKeyAndOrderFront: view];
1429       unblock_input ();
1430     }
1433 static BOOL
1434 ns_window_is_ancestor (NSWindow *win, NSWindow *candidate)
1435 /* Test whether CANDIDATE is an ancestor window of WIN. */
1437   if (candidate == NULL)
1438     return NO;
1439   else if (win == candidate)
1440     return YES;
1441   else
1442     return ns_window_is_ancestor(win, [candidate parentWindow]);
1445 DEFUN ("ns-frame-list-z-order", Fns_frame_list_z_order,
1446        Sns_frame_list_z_order, 0, 1, 0,
1447        doc: /* Return list of Emacs' frames, in Z (stacking) order.
1448 The optional argument TERMINAL specifies which display to ask about.
1449 TERMINAL should be either a frame or a display name (a string).  If
1450 omitted or nil, that stands for the selected frame's display.  Return
1451 nil if TERMINAL contains no Emacs frame.
1453 As a special case, if TERMINAL is non-nil and specifies a live frame,
1454 return the child frames of that frame in Z (stacking) order.
1456 Frames are listed from topmost (first) to bottommost (last).  */)
1457   (Lisp_Object terminal)
1459   Lisp_Object frames = Qnil;
1460   NSWindow *parent = nil;
1462   if (FRAMEP (terminal) && FRAME_LIVE_P (XFRAME (terminal)))
1463     parent = [FRAME_NS_VIEW (XFRAME (terminal)) window];
1464   else if (!NILP (terminal))
1465     return Qnil;
1467   for (NSWindow *win in [[NSApp orderedWindows] reverseObjectEnumerator])
1468     {
1469       Lisp_Object frame;
1471       /* Check against [win parentWindow] so that it doesn't match itself. */
1472       if (parent == nil || ns_window_is_ancestor (parent, [win parentWindow]))
1473         {
1474           XSETFRAME (frame, ((EmacsView *)[win delegate])->emacsframe);
1475           frames = Fcons(frame, frames);
1476         }
1477     }
1479   return frames;
1482 DEFUN ("ns-frame-restack", Fns_frame_restack, Sns_frame_restack, 2, 3, 0,
1483        doc: /* Restack FRAME1 below FRAME2.
1484 This means that if both frames are visible and the display areas of
1485 these frames overlap, FRAME2 (partially) obscures FRAME1.  If optional
1486 third argument ABOVE is non-nil, restack FRAME1 above FRAME2.  This
1487 means that if both frames are visible and the display areas of these
1488 frames overlap, FRAME1 (partially) obscures FRAME2.
1490 Some window managers may refuse to restack windows.  */)
1491      (Lisp_Object frame1, Lisp_Object frame2, Lisp_Object above)
1493   struct frame *f1 = decode_live_frame (frame1);
1494   struct frame *f2 = decode_live_frame (frame2);
1496   if (FRAME_NS_VIEW (f1) && FRAME_NS_VIEW (f2))
1497     {
1498       NSWindow *window = [FRAME_NS_VIEW (f1) window];
1499       NSInteger window2 = [[FRAME_NS_VIEW (f2) window] windowNumber];
1500       NSWindowOrderingMode flag = NILP (above) ? NSWindowBelow : NSWindowAbove;
1502       [window orderWindow: flag
1503                relativeTo: window2];
1505       return Qt;
1506     }
1507   else
1508     {
1509       error ("Cannot restack frames");
1510       return Qnil;
1511     }
1514 DEFUN ("ns-popup-font-panel", Fns_popup_font_panel, Sns_popup_font_panel,
1515        0, 1, "",
1516        doc: /* Pop up the font panel. */)
1517      (Lisp_Object frame)
1519   struct frame *f = decode_window_system_frame (frame);
1520   id fm = [NSFontManager sharedFontManager];
1521   struct font *font = f->output_data.ns->font;
1522   NSFont *nsfont;
1523 #ifdef NS_IMPL_GNUSTEP
1524   nsfont = ((struct nsfont_info *)font)->nsfont;
1525 #endif
1526 #ifdef NS_IMPL_COCOA
1527   nsfont = (NSFont *) macfont_get_nsctfont (font);
1528 #endif
1529   [fm setSelectedFont: nsfont isMultiple: NO];
1530   [fm orderFrontFontPanel: NSApp];
1531   return Qnil;
1535 DEFUN ("ns-popup-color-panel", Fns_popup_color_panel, Sns_popup_color_panel,
1536        0, 1, "",
1537        doc: /* Pop up the color panel.  */)
1538      (Lisp_Object frame)
1540   check_window_system (NULL);
1541   [NSApp orderFrontColorPanel: NSApp];
1542   return Qnil;
1545 static struct
1547   id panel;
1548   BOOL ret;
1549 #ifdef NS_IMPL_GNUSTEP
1550   NSString *dirS, *initS;
1551   BOOL no_types;
1552 #endif
1553 } ns_fd_data;
1555 void
1556 ns_run_file_dialog (void)
1558   if (ns_fd_data.panel == nil) return;
1559 #ifdef NS_IMPL_COCOA
1560   ns_fd_data.ret = [ns_fd_data.panel runModal];
1561 #else
1562   if (ns_fd_data.no_types)
1563     {
1564       ns_fd_data.ret = [ns_fd_data.panel
1565                            runModalForDirectory: ns_fd_data.dirS
1566                            file: ns_fd_data.initS];
1567     }
1568   else
1569     {
1570       ns_fd_data.ret = [ns_fd_data.panel
1571                            runModalForDirectory: ns_fd_data.dirS
1572                            file: ns_fd_data.initS
1573                            types: nil];
1574     }
1575 #endif
1576   ns_fd_data.panel = nil;
1579 #ifdef NS_IMPL_COCOA
1580 #if MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_9
1581 #define MODAL_OK_RESPONSE NSModalResponseOK
1582 #endif
1583 #endif
1584 #ifndef MODAL_OK_RESPONSE
1585 #define MODAL_OK_RESPONSE NSOKButton
1586 #endif
1588 DEFUN ("ns-read-file-name", Fns_read_file_name, Sns_read_file_name, 1, 5, 0,
1589        doc: /* Use a graphical panel to read a file name, using prompt PROMPT.
1590 Optional arg DIR, if non-nil, supplies a default directory.
1591 Optional arg MUSTMATCH, if non-nil, means the returned file or
1592 directory must exist.
1593 Optional arg INIT, if non-nil, provides a default file name to use.
1594 Optional arg DIR_ONLY_P, if non-nil, means choose only directories.  */)
1595   (Lisp_Object prompt, Lisp_Object dir, Lisp_Object mustmatch,
1596    Lisp_Object init, Lisp_Object dir_only_p)
1598   static id fileDelegate = nil;
1599   BOOL isSave = NILP (mustmatch) && NILP (dir_only_p);
1600   id panel;
1601   Lisp_Object fname = Qnil;
1603   NSString *promptS = NILP (prompt) || !STRINGP (prompt) ? nil :
1604     [NSString stringWithUTF8String: SSDATA (prompt)];
1605   NSString *dirS = NILP (dir) || !STRINGP (dir) ?
1606     [NSString stringWithUTF8String: SSDATA (BVAR (current_buffer, directory))] :
1607     [NSString stringWithUTF8String: SSDATA (dir)];
1608   NSString *initS = NILP (init) || !STRINGP (init) ? nil :
1609     [NSString stringWithUTF8String: SSDATA (init)];
1610   NSEvent *nxev;
1612   check_window_system (NULL);
1614   if (fileDelegate == nil)
1615     fileDelegate = [EmacsFileDelegate new];
1617   [NSCursor setHiddenUntilMouseMoves: NO];
1619   if ([dirS characterAtIndex: 0] == '~')
1620     dirS = [dirS stringByExpandingTildeInPath];
1622   panel = isSave ?
1623     (id)[EmacsSavePanel savePanel] : (id)[EmacsOpenPanel openPanel];
1625   [panel setTitle: promptS];
1627   [panel setAllowsOtherFileTypes: YES];
1628   [panel setTreatsFilePackagesAsDirectories: YES];
1629   [panel setDelegate: fileDelegate];
1631   if (! NILP (dir_only_p))
1632     {
1633       [panel setCanChooseDirectories: YES];
1634       [panel setCanChooseFiles: NO];
1635     }
1636   else if (! isSave)
1637     {
1638       /* This is not quite what the documentation says, but it is compatible
1639          with the Gtk+ code.  Also, the menu entry says "Open File...".  */
1640       [panel setCanChooseDirectories: NO];
1641       [panel setCanChooseFiles: YES];
1642     }
1644   block_input ();
1645   ns_fd_data.panel = panel;
1646   ns_fd_data.ret = NO;
1647 #ifdef NS_IMPL_COCOA
1648   if (! NILP (mustmatch) || ! NILP (dir_only_p))
1649     [panel setAllowedFileTypes: nil];
1650   if (dirS) [panel setDirectoryURL: [NSURL fileURLWithPath: dirS]];
1651   if (initS && NILP (Ffile_directory_p (init)))
1652     [panel setNameFieldStringValue: [initS lastPathComponent]];
1653   else
1654     [panel setNameFieldStringValue: @""];
1656 #else
1657   ns_fd_data.no_types = NILP (mustmatch) && NILP (dir_only_p);
1658   ns_fd_data.dirS = dirS;
1659   ns_fd_data.initS = initS;
1660 #endif
1662   /* runModalForDirectory/runModal restarts the main event loop when done,
1663      so we must start an event loop and then pop up the file dialog.
1664      The file dialog may pop up a confirm dialog after Ok has been pressed,
1665      so we can not simply pop down on the Ok/Cancel press.
1666    */
1667   nxev = [NSEvent otherEventWithType: NSEventTypeApplicationDefined
1668                             location: NSMakePoint (0, 0)
1669                        modifierFlags: 0
1670                            timestamp: 0
1671                         windowNumber: [[NSApp mainWindow] windowNumber]
1672                              context: [NSApp context]
1673                              subtype: 0
1674                                data1: 0
1675                                data2: NSAPP_DATA2_RUNFILEDIALOG];
1677   [NSApp postEvent: nxev atStart: NO];
1678   while (ns_fd_data.panel != nil)
1679     [NSApp run];
1681   if (ns_fd_data.ret == MODAL_OK_RESPONSE)
1682     {
1683       NSString *str = ns_filename_from_panel (panel);
1684       if (! str) str = ns_directory_from_panel (panel);
1685       if (str) fname = build_string ([str UTF8String]);
1686     }
1688   [[FRAME_NS_VIEW (SELECTED_FRAME ()) window] makeKeyWindow];
1689   unblock_input ();
1691   return fname;
1694 const char *
1695 ns_get_defaults_value (const char *key)
1697   NSObject *obj = [[NSUserDefaults standardUserDefaults]
1698                     objectForKey: [NSString stringWithUTF8String: key]];
1700   if (!obj) return NULL;
1702   return [[NSString stringWithFormat: @"%@", obj] UTF8String];
1706 DEFUN ("ns-get-resource", Fns_get_resource, Sns_get_resource, 2, 2, 0,
1707        doc: /* Return the value of the property NAME of OWNER from the defaults database.
1708 If OWNER is nil, Emacs is assumed.  */)
1709      (Lisp_Object owner, Lisp_Object name)
1711   const char *value;
1713   check_window_system (NULL);
1714   if (NILP (owner))
1715     owner = build_string([ns_app_name UTF8String]);
1716   CHECK_STRING (name);
1718   value = ns_get_defaults_value (SSDATA (name));
1720   if (value)
1721     return build_string (value);
1722   return Qnil;
1726 DEFUN ("ns-set-resource", Fns_set_resource, Sns_set_resource, 3, 3, 0,
1727        doc: /* Set property NAME of OWNER to VALUE, from the defaults database.
1728 If OWNER is nil, Emacs is assumed.
1729 If VALUE is nil, the default is removed.  */)
1730      (Lisp_Object owner, Lisp_Object name, Lisp_Object value)
1732   check_window_system (NULL);
1733   if (NILP (owner))
1734     owner = build_string ([ns_app_name UTF8String]);
1735   CHECK_STRING (name);
1736   if (NILP (value))
1737     {
1738       [[NSUserDefaults standardUserDefaults] removeObjectForKey:
1739                          [NSString stringWithUTF8String: SSDATA (name)]];
1740     }
1741   else
1742     {
1743       CHECK_STRING (value);
1744       [[NSUserDefaults standardUserDefaults] setObject:
1745                 [NSString stringWithUTF8String: SSDATA (value)]
1746                                         forKey: [NSString stringWithUTF8String:
1747                                                          SSDATA (name)]];
1748     }
1750   return Qnil;
1754 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
1755        Sx_server_max_request_size,
1756        0, 1, 0,
1757        doc: /* This function is a no-op.  It is only present for completeness.  */)
1758      (Lisp_Object terminal)
1760   check_ns_display_info (terminal);
1761   /* This function has no real equivalent under NeXTstep.  Return nil to
1762      indicate this. */
1763   return Qnil;
1767 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
1768        doc: /* Return the "vendor ID" string of Nextstep display server TERMINAL.
1769 \(Labeling every distributor as a "vendor" embodies the false assumption
1770 that operating systems cannot be developed and distributed noncommercially.)
1771 The optional argument TERMINAL specifies which display to ask about.
1772 TERMINAL should be a terminal object, a frame or a display name (a string).
1773 If omitted or nil, that stands for the selected frame's display.  */)
1774   (Lisp_Object terminal)
1776   check_ns_display_info (terminal);
1777 #ifdef NS_IMPL_GNUSTEP
1778   return build_string ("GNU");
1779 #else
1780   return build_string ("Apple");
1781 #endif
1785 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
1786        doc: /* Return the version numbers of the server of display TERMINAL.
1787 The value is a list of three integers: the major and minor
1788 version numbers of the X Protocol in use, and the distributor-specific release
1789 number.  See also the function `x-server-vendor'.
1791 The optional argument TERMINAL specifies which display to ask about.
1792 TERMINAL should be a terminal object, a frame or a display name (a string).
1793 If omitted or nil, that stands for the selected frame's display.  */)
1794   (Lisp_Object terminal)
1796   check_ns_display_info (terminal);
1797   /*NOTE: it is unclear what would best correspond with "protocol";
1798           we return 10.3, meaning Panther, since this is roughly the
1799           level that GNUstep's APIs correspond to.
1800           The last number is where we distinguish between the Apple
1801           and GNUstep implementations ("distributor-specific release
1802           number") and give int'ized versions of major.minor. */
1803   return list3i (10, 3, ns_appkit_version_int ());
1807 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
1808        doc: /* Return the number of screens on Nextstep display server TERMINAL.
1809 The optional argument TERMINAL specifies which display to ask about.
1810 TERMINAL should be a terminal object, a frame or a display name (a string).
1811 If omitted or nil, that stands for the selected frame's display.
1813 Note: "screen" here is not in Nextstep terminology but in X11's.  For
1814 the number of physical monitors, use `(length
1815 \(display-monitor-attributes-list TERMINAL))' instead.  */)
1816   (Lisp_Object terminal)
1818   check_ns_display_info (terminal);
1819   return make_number (1);
1823 DEFUN ("x-display-mm-height", Fx_display_mm_height, Sx_display_mm_height, 0, 1, 0,
1824        doc: /* Return the height in millimeters of the Nextstep display TERMINAL.
1825 The optional argument TERMINAL specifies which display to ask about.
1826 TERMINAL should be a terminal object, a frame or a display name (a string).
1827 If omitted or nil, that stands for the selected frame's display.
1829 On \"multi-monitor\" setups this refers to the height in millimeters for
1830 all physical monitors associated with TERMINAL.  To get information
1831 for each physical monitor, use `display-monitor-attributes-list'.  */)
1832   (Lisp_Object terminal)
1834   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
1836   return make_number (x_display_pixel_height (dpyinfo) / (92.0/25.4));
1840 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
1841        doc: /* Return the width in millimeters of the Nextstep display TERMINAL.
1842 The optional argument TERMINAL specifies which display to ask about.
1843 TERMINAL should be a terminal object, a frame or a display name (a string).
1844 If omitted or nil, that stands for the selected frame's display.
1846 On \"multi-monitor\" setups this refers to the width in millimeters for
1847 all physical monitors associated with TERMINAL.  To get information
1848 for each physical monitor, use `display-monitor-attributes-list'.  */)
1849   (Lisp_Object terminal)
1851   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
1853   return make_number (x_display_pixel_width (dpyinfo) / (92.0/25.4));
1857 DEFUN ("x-display-backing-store", Fx_display_backing_store,
1858        Sx_display_backing_store, 0, 1, 0,
1859        doc: /* Return an indication of whether the Nextstep display TERMINAL does backing store.
1860 The value may be `buffered', `retained', or `non-retained'.
1861 The optional argument TERMINAL specifies which display to ask about.
1862 TERMINAL should be a terminal object, a frame or a display name (a string).
1863 If omitted or nil, that stands for the selected frame's display.  */)
1864   (Lisp_Object terminal)
1866   check_ns_display_info (terminal);
1867   switch ([ns_get_window (terminal) backingType])
1868     {
1869     case NSBackingStoreBuffered:
1870       return intern ("buffered");
1871     case NSBackingStoreRetained:
1872       return intern ("retained");
1873     case NSBackingStoreNonretained:
1874       return intern ("non-retained");
1875     default:
1876       error ("Strange value for backingType parameter of frame");
1877     }
1878   return Qnil;  /* not reached, shut compiler up */
1882 DEFUN ("x-display-visual-class", Fx_display_visual_class,
1883        Sx_display_visual_class, 0, 1, 0,
1884        doc: /* Return the visual class of the Nextstep display TERMINAL.
1885 The value is one of the symbols `static-gray', `gray-scale',
1886 `static-color', `pseudo-color', `true-color', or `direct-color'.
1888 The optional argument TERMINAL specifies which display to ask about.
1889 TERMINAL should a terminal object, a frame or a display name (a string).
1890 If omitted or nil, that stands for the selected frame's display.  */)
1891   (Lisp_Object terminal)
1893   NSWindowDepth depth;
1895   check_ns_display_info (terminal);
1896   depth = [[[NSScreen screens] objectAtIndex:0] depth];
1898   if ( depth == NSBestDepth (NSCalibratedWhiteColorSpace, 2, 2, YES, NULL))
1899     return intern ("static-gray");
1900   else if (depth == NSBestDepth (NSCalibratedWhiteColorSpace, 8, 8, YES, NULL))
1901     return intern ("gray-scale");
1902   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 8, 8, YES, NULL))
1903     return intern ("pseudo-color");
1904   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 4, 12, NO, NULL))
1905     return intern ("true-color");
1906   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 8, 24, NO, NULL))
1907     return intern ("direct-color");
1908   else
1909     /* color mgmt as far as we do it is really handled by Nextstep itself anyway */
1910     return intern ("direct-color");
1914 DEFUN ("x-display-save-under", Fx_display_save_under,
1915        Sx_display_save_under, 0, 1, 0,
1916        doc: /* Return t if TERMINAL supports the save-under feature.
1917 The optional argument TERMINAL specifies which display to ask about.
1918 TERMINAL should be 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   check_ns_display_info (terminal);
1923   switch ([ns_get_window (terminal) backingType])
1924     {
1925     case NSBackingStoreBuffered:
1926       return Qt;
1928     case NSBackingStoreRetained:
1929     case NSBackingStoreNonretained:
1930       return Qnil;
1932     default:
1933       error ("Strange value for backingType parameter of frame");
1934     }
1935   return Qnil;  /* not reached, shut compiler up */
1939 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
1940        1, 3, 0,
1941        doc: /* Open a connection to a display server.
1942 DISPLAY is the name of the display to connect to.
1943 Optional second arg XRM-STRING is a string of resources in xrdb format.
1944 If the optional third arg MUST-SUCCEED is non-nil,
1945 terminate Emacs if we can't open the connection.
1946 \(In the Nextstep version, the last two arguments are currently ignored.)  */)
1947      (Lisp_Object display, Lisp_Object resource_string, Lisp_Object must_succeed)
1949   struct ns_display_info *dpyinfo;
1951   CHECK_STRING (display);
1953   nxatoms_of_nsselect ();
1954   dpyinfo = ns_term_init (display);
1955   if (dpyinfo == 0)
1956     {
1957       if (!NILP (must_succeed))
1958         fatal ("Display on %s not responding.\n",
1959                SSDATA (display));
1960       else
1961         error ("Display on %s not responding.\n",
1962                SSDATA (display));
1963     }
1965   return Qnil;
1969 DEFUN ("x-close-connection", Fx_close_connection, Sx_close_connection,
1970        1, 1, 0,
1971        doc: /* Close the connection to TERMINAL's Nextstep display server.
1972 For TERMINAL, specify a terminal object, a frame or a display name (a
1973 string).  If TERMINAL is nil, that stands for the selected frame's
1974 terminal.  */)
1975      (Lisp_Object terminal)
1977   check_ns_display_info (terminal);
1978   [NSApp terminate: NSApp];
1979   return Qnil;
1983 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
1984        doc: /* Return the list of display names that Emacs has connections to.  */)
1985      (void)
1987   Lisp_Object result = Qnil;
1988   struct ns_display_info *ndi;
1990   for (ndi = x_display_list; ndi; ndi = ndi->next)
1991     result = Fcons (XCAR (ndi->name_list_element), result);
1993   return result;
1997 DEFUN ("ns-hide-others", Fns_hide_others, Sns_hide_others,
1998        0, 0, 0,
1999        doc: /* Hides all applications other than Emacs.  */)
2000      (void)
2002   check_window_system (NULL);
2003   [NSApp hideOtherApplications: NSApp];
2004   return Qnil;
2007 DEFUN ("ns-hide-emacs", Fns_hide_emacs, Sns_hide_emacs,
2008        1, 1, 0,
2009        doc: /* If ON is non-nil, the entire Emacs application is hidden.
2010 Otherwise if Emacs is hidden, it is unhidden.
2011 If ON is equal to `activate', Emacs is unhidden and becomes
2012 the active application.  */)
2013      (Lisp_Object on)
2015   check_window_system (NULL);
2016   if (EQ (on, intern ("activate")))
2017     {
2018       [NSApp unhide: NSApp];
2019       [NSApp activateIgnoringOtherApps: YES];
2020     }
2021   else if (NILP (on))
2022     [NSApp unhide: NSApp];
2023   else
2024     [NSApp hide: NSApp];
2025   return Qnil;
2029 DEFUN ("ns-emacs-info-panel", Fns_emacs_info_panel, Sns_emacs_info_panel,
2030        0, 0, 0,
2031        doc: /* Shows the 'Info' or 'About' panel for Emacs.  */)
2032      (void)
2034   check_window_system (NULL);
2035   [NSApp orderFrontStandardAboutPanel: nil];
2036   return Qnil;
2040 DEFUN ("ns-font-name", Fns_font_name, Sns_font_name, 1, 1, 0,
2041        doc: /* Determine font PostScript or family name for font NAME.
2042 NAME should be a string containing either the font name or an XLFD
2043 font descriptor.  If string contains `fontset' and not
2044 `fontset-startup', it is left alone. */)
2045      (Lisp_Object name)
2047   char *nm;
2048   CHECK_STRING (name);
2049   nm = SSDATA (name);
2051   if (nm[0] != '-')
2052     return name;
2053   if (strstr (nm, "fontset") && !strstr (nm, "fontset-startup"))
2054     return name;
2056   return build_string (ns_xlfd_to_fontname (SSDATA (name)));
2060 DEFUN ("ns-list-colors", Fns_list_colors, Sns_list_colors, 0, 1, 0,
2061        doc: /* Return a list of all available colors.
2062 The optional argument FRAME is currently ignored.  */)
2063      (Lisp_Object frame)
2065   Lisp_Object list = Qnil;
2066   NSEnumerator *colorlists;
2067   NSColorList *clist;
2069   if (!NILP (frame))
2070     {
2071       CHECK_FRAME (frame);
2072       if (! FRAME_NS_P (XFRAME (frame)))
2073         error ("non-Nextstep frame used in `ns-list-colors'");
2074     }
2076   block_input ();
2078   colorlists = [[NSColorList availableColorLists] objectEnumerator];
2079   while ((clist = [colorlists nextObject]))
2080     {
2081       if ([[clist name] length] < 7 ||
2082           [[clist name] rangeOfString: @"PANTONE"].location == 0)
2083         {
2084           NSEnumerator *cnames = [[clist allKeys] reverseObjectEnumerator];
2085           NSString *cname;
2086           while ((cname = [cnames nextObject]))
2087             list = Fcons (build_string ([cname UTF8String]), list);
2088 /*           for (i = [[clist allKeys] count] - 1; i >= 0; i--)
2089                list = Fcons (build_string ([[[clist allKeys] objectAtIndex: i]
2090                                              UTF8String]), list); */
2091         }
2092     }
2094   unblock_input ();
2096   return list;
2100 DEFUN ("ns-list-services", Fns_list_services, Sns_list_services, 0, 0, 0,
2101        doc: /* List available Nextstep services by querying NSApp.  */)
2102      (void)
2104 #ifdef NS_IMPL_COCOA
2105   /* You can't get services like this in 10.6+.  */
2106   return Qnil;
2107 #else
2108   Lisp_Object ret = Qnil;
2109   NSMenu *svcs;
2110 #ifdef NS_IMPL_COCOA
2111   id delegate;
2112 #endif
2114   check_window_system (NULL);
2115   svcs = [[NSMenu alloc] initWithTitle: @"Services"];
2116   [NSApp setServicesMenu: svcs];
2117   [NSApp registerServicesMenuSendTypes: ns_send_types
2118                            returnTypes: ns_return_types];
2120 /* On Tiger, services menu updating was made lazier (waits for user to
2121    actually click on the menu), so we have to force things along: */
2122 #ifdef NS_IMPL_COCOA
2123   delegate = [svcs delegate];
2124   if (delegate != nil)
2125     {
2126       if ([delegate respondsToSelector: @selector (menuNeedsUpdate:)])
2127         [delegate menuNeedsUpdate: svcs];
2128       if ([delegate respondsToSelector:
2129                        @selector (menu:updateItem:atIndex:shouldCancel:)])
2130         {
2131           int i, len = [delegate numberOfItemsInMenu: svcs];
2132           for (i =0; i<len; i++)
2133             [svcs addItemWithTitle: @"" action: NULL keyEquivalent: @""];
2134           for (i =0; i<len; i++)
2135             if (![delegate menu: svcs
2136                      updateItem: (NSMenuItem *)[svcs itemAtIndex: i]
2137                         atIndex: i shouldCancel: NO])
2138               break;
2139         }
2140     }
2141 #endif
2143   [svcs setAutoenablesItems: NO];
2144 #ifdef NS_IMPL_COCOA
2145   [svcs update]; /* on macOS, converts from '/' structure */
2146 #endif
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 >= MAC_OS_X_VERSION_10_9
2530   mach_port_t masterPort;
2531   io_iterator_t it;
2532   io_object_t obj;
2534   // CGDisplayIOServicePort is deprecated.  Do it another (harder) way.
2536   if (IOMasterPort (MACH_PORT_NULL, &masterPort) != kIOReturnSuccess
2537       || IOServiceGetMatchingServices (masterPort,
2538                                        IOServiceMatching ("IONDRVDevice"),
2539                                        &it) != kIOReturnSuccess)
2540     return name;
2542   /* Must loop until we find a name.  Many devices can have the same unit
2543      number (represents different GPU parts), but only one has a name.  */
2544   while (! name && (obj = IOIteratorNext (it)))
2545     {
2546       CFMutableDictionaryRef props;
2547       const void *val;
2549       if (IORegistryEntryCreateCFProperties (obj,
2550                                              &props,
2551                                              kCFAllocatorDefault,
2552                                              kNilOptions) == kIOReturnSuccess
2553           && props != nil
2554           && (val = CFDictionaryGetValue(props, @"IOFBDependentIndex")))
2555         {
2556           unsigned nr = [(NSNumber *)val unsignedIntegerValue];
2557           if (nr == CGDisplayUnitNumber (did))
2558             name = ns_get_name_from_ioreg (obj);
2559         }
2561       CFRelease (props);
2562       IOObjectRelease (obj);
2563     }
2565   IOObjectRelease (it);
2567 #else
2569   name = ns_get_name_from_ioreg (CGDisplayIOServicePort (did));
2571 #endif
2572   return name;
2574 #endif
2576 static Lisp_Object
2577 ns_make_monitor_attribute_list (struct MonitorInfo *monitors,
2578                                 int n_monitors,
2579                                 int primary_monitor,
2580                                 const char *source)
2582   Lisp_Object monitor_frames = Fmake_vector (make_number (n_monitors), Qnil);
2583   Lisp_Object frame, rest;
2584   NSArray *screens = [NSScreen screens];
2585   int i;
2587   FOR_EACH_FRAME (rest, frame)
2588     {
2589       struct frame *f = XFRAME (frame);
2591       if (FRAME_NS_P (f))
2592         {
2593           NSView *view = FRAME_NS_VIEW (f);
2594           NSScreen *screen = [[view window] screen];
2595           NSUInteger k;
2597           i = -1;
2598           for (k = 0; i == -1 && k < [screens count]; ++k)
2599             {
2600               if ([screens objectAtIndex: k] == screen)
2601                 i = (int)k;
2602             }
2604           if (i > -1)
2605             ASET (monitor_frames, i, Fcons (frame, AREF (monitor_frames, i)));
2606         }
2607     }
2609   return make_monitor_attribute_list (monitors, n_monitors, primary_monitor,
2610                                       monitor_frames, source);
2613 DEFUN ("ns-display-monitor-attributes-list",
2614        Fns_display_monitor_attributes_list,
2615        Sns_display_monitor_attributes_list,
2616        0, 1, 0,
2617        doc: /* Return a list of physical monitor attributes on the X display TERMINAL.
2619 The optional argument TERMINAL specifies which display to ask about.
2620 TERMINAL should be a terminal object, a frame or a display name (a string).
2621 If omitted or nil, that stands for the selected frame's display.
2623 In addition to the standard attribute keys listed in
2624 `display-monitor-attributes-list', the following keys are contained in
2625 the attributes:
2627  source -- String describing the source from which multi-monitor
2628            information is obtained, \"NS\" is always the source."
2630 Internal use only, use `display-monitor-attributes-list' instead.  */)
2631   (Lisp_Object terminal)
2633   struct terminal *term = decode_live_terminal (terminal);
2634   NSArray *screens;
2635   NSUInteger i, n_monitors;
2636   struct MonitorInfo *monitors;
2637   Lisp_Object attributes_list = Qnil;
2638   CGFloat primary_display_height = 0;
2640   if (term->type != output_ns)
2641     return Qnil;
2643   screens = [NSScreen screens];
2644   n_monitors = [screens count];
2645   if (n_monitors == 0)
2646     return Qnil;
2648   monitors = xzalloc (n_monitors * sizeof *monitors);
2650   for (i = 0; i < [screens count]; ++i)
2651     {
2652       NSScreen *s = [screens objectAtIndex:i];
2653       struct MonitorInfo *m = &monitors[i];
2654       NSRect fr = [s frame];
2655       NSRect vfr = [s visibleFrame];
2656       short y, vy;
2658 #ifdef NS_IMPL_COCOA
2659       NSDictionary *dict = [s deviceDescription];
2660       NSNumber *nid = [dict objectForKey:@"NSScreenNumber"];
2661       CGDirectDisplayID did = [nid unsignedIntValue];
2662 #endif
2663       if (i == 0)
2664         {
2665           primary_display_height = fr.size.height;
2666           y = (short) fr.origin.y;
2667           vy = (short) vfr.origin.y;
2668         }
2669       else
2670         {
2671           // Flip y coordinate as NS has y starting from the bottom.
2672           y = (short) (primary_display_height - fr.size.height - fr.origin.y);
2673           vy = (short) (primary_display_height -
2674                         vfr.size.height - vfr.origin.y);
2675         }
2677       m->geom.x = (short) fr.origin.x;
2678       m->geom.y = y;
2679       m->geom.width = (unsigned short) fr.size.width;
2680       m->geom.height = (unsigned short) fr.size.height;
2682       m->work.x = (short) vfr.origin.x;
2683       // y is flipped on NS, so vy - y are pixels missing at the bottom,
2684       // and fr.size.height - vfr.size.height are pixels missing in total.
2685       // Pixels missing at top are
2686       // fr.size.height - vfr.size.height - vy + y.
2687       // work.y is then pixels missing at top + y.
2688       m->work.y = (short) (fr.size.height - vfr.size.height) - vy + y + y;
2689       m->work.width = (unsigned short) vfr.size.width;
2690       m->work.height = (unsigned short) vfr.size.height;
2692 #ifdef NS_IMPL_COCOA
2693       m->name = ns_screen_name (did);
2695       {
2696         CGSize mms = CGDisplayScreenSize (did);
2697         m->mm_width = (int) mms.width;
2698         m->mm_height = (int) mms.height;
2699       }
2701 #else
2702       // Assume 92 dpi as x-display-mm-height/x-display-mm-width does.
2703       m->mm_width = (int) (25.4 * fr.size.width / 92.0);
2704       m->mm_height = (int) (25.4 * fr.size.height / 92.0);
2705 #endif
2706     }
2708   // Primary monitor is always first for NS.
2709   attributes_list = ns_make_monitor_attribute_list (monitors, n_monitors,
2710                                                     0, "NS");
2712   free_monitors (monitors, n_monitors);
2713   return attributes_list;
2717 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
2718        0, 1, 0,
2719        doc: /* Return the number of bitplanes of the Nextstep display TERMINAL.
2720 The optional argument TERMINAL specifies which display to ask about.
2721 TERMINAL should be a terminal object, a frame or a display name (a string).
2722 If omitted or nil, that stands for the selected frame's display.  */)
2723   (Lisp_Object terminal)
2725   check_ns_display_info (terminal);
2726   return make_number
2727     (NSBitsPerPixelFromDepth ([[[NSScreen screens] objectAtIndex:0] depth]));
2731 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
2732        0, 1, 0,
2733        doc: /* Returns the number of color cells of the Nextstep display TERMINAL.
2734 The optional argument TERMINAL specifies which display to ask about.
2735 TERMINAL should be a terminal object, a frame or a display name (a string).
2736 If omitted or nil, that stands for the selected frame's display.  */)
2737   (Lisp_Object terminal)
2739   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
2740   /* We force 24+ bit depths to 24-bit to prevent an overflow.  */
2741   return make_number (1 << min (dpyinfo->n_planes, 24));
2745 /* Unused dummy def needed for compatibility. */
2746 Lisp_Object tip_frame;
2748 /* TODO: move to xdisp or similar */
2749 static void
2750 compute_tip_xy (struct frame *f,
2751                 Lisp_Object parms,
2752                 Lisp_Object dx,
2753                 Lisp_Object dy,
2754                 int width,
2755                 int height,
2756                 int *root_x,
2757                 int *root_y)
2759   Lisp_Object left, top, right, bottom;
2760   EmacsView *view = FRAME_NS_VIEW (f);
2761   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2762   NSPoint pt;
2764   /* Start with user-specified or mouse position.  */
2765   left = Fcdr (Fassq (Qleft, parms));
2766   top = Fcdr (Fassq (Qtop, parms));
2767   right = Fcdr (Fassq (Qright, parms));
2768   bottom = Fcdr (Fassq (Qbottom, parms));
2770   if ((!INTEGERP (left) && !INTEGERP (right))
2771       || (!INTEGERP (top) && !INTEGERP (bottom)))
2772     {
2773       pt.x = dpyinfo->last_mouse_motion_x;
2774       pt.y = dpyinfo->last_mouse_motion_y;
2775       /* Convert to screen coordinates */
2776       pt = [view convertPoint: pt toView: nil];
2777 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
2778       pt = [[view window] convertBaseToScreen: pt];
2779 #else
2780       {
2781         NSRect r = NSMakeRect (pt.x, pt.y, 0, 0);
2782         r = [[view window] convertRectToScreen: r];
2783         pt.x = r.origin.x;
2784         pt.y = r.origin.y;
2785       }
2786 #endif
2787     }
2788   else
2789     {
2790       /* Absolute coordinates.  */
2791       pt.x = INTEGERP (left) ? XINT (left) : XINT (right);
2792       pt.y = (x_display_pixel_height (FRAME_DISPLAY_INFO (f))
2793               - (INTEGERP (top) ? XINT (top) : XINT (bottom))
2794               - height);
2795     }
2797   /* Ensure in bounds.  (Note, screen origin = lower left.) */
2798   if (INTEGERP (left) || INTEGERP (right))
2799     *root_x = pt.x;
2800   else if (pt.x + XINT (dx) <= 0)
2801     *root_x = 0; /* Can happen for negative dx */
2802   else if (pt.x + XINT (dx) + width
2803            <= x_display_pixel_width (FRAME_DISPLAY_INFO (f)))
2804     /* It fits to the right of the pointer.  */
2805     *root_x = pt.x + XINT (dx);
2806   else if (width + XINT (dx) <= pt.x)
2807     /* It fits to the left of the pointer.  */
2808     *root_x = pt.x - width - XINT (dx);
2809   else
2810     /* Put it left justified on the screen -- it ought to fit that way.  */
2811     *root_x = 0;
2813   if (INTEGERP (top) || INTEGERP (bottom))
2814     *root_y = pt.y;
2815   else if (pt.y - XINT (dy) - height >= 0)
2816     /* It fits below the pointer.  */
2817     *root_y = pt.y - height - XINT (dy);
2818   else if (pt.y + XINT (dy) + height
2819            <= x_display_pixel_height (FRAME_DISPLAY_INFO (f)))
2820     /* It fits above the pointer */
2821       *root_y = pt.y + XINT (dy);
2822   else
2823     /* Put it on the top.  */
2824     *root_y = x_display_pixel_height (FRAME_DISPLAY_INFO (f)) - height;
2828 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
2829        doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
2830 A tooltip window is a small window displaying a string.
2832 This is an internal function; Lisp code should call `tooltip-show'.
2834 FRAME nil or omitted means use the selected frame.
2836 PARMS is an optional list of frame parameters which can be used to
2837 change the tooltip's appearance.
2839 Automatically hide the tooltip after TIMEOUT seconds.  TIMEOUT nil
2840 means use the default timeout of 5 seconds.
2842 If the list of frame parameters PARMS contains a `left' parameter,
2843 display the tooltip at that x-position.  If the list of frame parameters
2844 PARMS contains no `left' but a `right' parameter, display the tooltip
2845 right-adjusted at that x-position. Otherwise display it at the
2846 x-position of the mouse, with offset DX added (default is 5 if DX isn't
2847 specified).
2849 Likewise for the y-position: If a `top' frame parameter is specified, it
2850 determines the position of the upper edge of the tooltip window.  If a
2851 `bottom' parameter but no `top' frame parameter is specified, it
2852 determines the position of the lower edge of the tooltip window.
2853 Otherwise display the tooltip window at the y-position of the mouse,
2854 with offset DY added (default is -10).
2856 A tooltip's maximum size is specified by `x-max-tooltip-size'.
2857 Text larger than the specified size is clipped.  */)
2858      (Lisp_Object string, Lisp_Object frame, Lisp_Object parms, Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
2860   int root_x, root_y;
2861   ptrdiff_t count = SPECPDL_INDEX ();
2862   struct frame *f;
2863   char *str;
2864   NSSize size;
2866   specbind (Qinhibit_redisplay, Qt);
2868   CHECK_STRING (string);
2869   str = SSDATA (string);
2870   f = decode_window_system_frame (frame);
2871   if (NILP (timeout))
2872     timeout = make_number (5);
2873   else
2874     CHECK_NATNUM (timeout);
2876   if (NILP (dx))
2877     dx = make_number (5);
2878   else
2879     CHECK_NUMBER (dx);
2881   if (NILP (dy))
2882     dy = make_number (-10);
2883   else
2884     CHECK_NUMBER (dy);
2886   block_input ();
2887   if (ns_tooltip == nil)
2888     ns_tooltip = [[EmacsTooltip alloc] init];
2889   else
2890     Fx_hide_tip ();
2892   [ns_tooltip setText: str];
2893   size = [ns_tooltip frame].size;
2895   /* Move the tooltip window where the mouse pointer is.  Resize and
2896      show it.  */
2897   compute_tip_xy (f, parms, dx, dy, (int)size.width, (int)size.height,
2898                   &root_x, &root_y);
2900   [ns_tooltip showAtX: root_x Y: root_y for: XINT (timeout)];
2901   unblock_input ();
2903   return unbind_to (count, Qnil);
2907 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
2908        doc: /* Hide the current tooltip window, if there is any.
2909 Value is t if tooltip was open, nil otherwise.  */)
2910      (void)
2912   if (ns_tooltip == nil || ![ns_tooltip isActive])
2913     return Qnil;
2914   [ns_tooltip hide];
2915   return Qt;
2918 /* Return geometric attributes of FRAME.  According to the value of
2919    ATTRIBUTES return the outer edges of FRAME (Qouter_edges), the inner
2920    edges of FRAME, the root window edges of frame (Qroot_edges).  Any
2921    other value means to return the geometry as returned by
2922    Fx_frame_geometry.  */
2923 static Lisp_Object
2924 frame_geometry (Lisp_Object frame, Lisp_Object attribute)
2926   struct frame *f = decode_live_frame (frame);
2927   Lisp_Object fullscreen_symbol = Fframe_parameter (frame, Qfullscreen);
2928   bool fullscreen = (EQ (fullscreen_symbol, Qfullboth)
2929                      || EQ (fullscreen_symbol, Qfullscreen));
2930   int border = fullscreen ? 0 : f->border_width;
2931   int title_height = fullscreen ? 0 : FRAME_NS_TITLEBAR_HEIGHT (f);
2932   int native_width = FRAME_PIXEL_WIDTH (f);
2933   int native_height = FRAME_PIXEL_HEIGHT (f);
2934   int outer_width = native_width + 2 * border;
2935   int outer_height = native_height + 2 * border + title_height;
2936   int native_left = f->left_pos + border;
2937   int native_top = f->top_pos + border + title_height;
2938   int native_right = f->left_pos + outer_width - border;
2939   int native_bottom = f->top_pos + outer_height - border;
2940   int internal_border_width = FRAME_INTERNAL_BORDER_WIDTH (f);
2941   int tool_bar_height = FRAME_TOOLBAR_HEIGHT (f);
2942   int tool_bar_width = (tool_bar_height
2943                         ? outer_width - 2 * internal_border_width
2944                         : 0);
2946   /* Construct list.  */
2947   if (EQ (attribute, Qouter_edges))
2948     return list4 (make_number (f->left_pos), make_number (f->top_pos),
2949                   make_number (f->left_pos + outer_width),
2950                   make_number (f->top_pos + outer_height));
2951   else if (EQ (attribute, Qnative_edges))
2952     return list4 (make_number (native_left), make_number (native_top),
2953                   make_number (native_right), make_number (native_bottom));
2954   else if (EQ (attribute, Qinner_edges))
2955     return list4 (make_number (native_left + internal_border_width),
2956                   make_number (native_top
2957                                + tool_bar_height
2958                                + internal_border_width),
2959                   make_number (native_right - internal_border_width),
2960                   make_number (native_bottom - internal_border_width));
2961   else
2962     return
2963       listn (CONSTYPE_HEAP, 10,
2964              Fcons (Qouter_position,
2965                     Fcons (make_number (f->left_pos),
2966                            make_number (f->top_pos))),
2967              Fcons (Qouter_size,
2968                     Fcons (make_number (outer_width),
2969                            make_number (outer_height))),
2970              Fcons (Qexternal_border_size,
2971                     (fullscreen
2972                      ? Fcons (make_number (0), make_number (0))
2973                      : Fcons (make_number (border), make_number (border)))),
2974              Fcons (Qtitle_bar_size,
2975                     Fcons (make_number (0), make_number (title_height))),
2976              Fcons (Qmenu_bar_external, Qnil),
2977              Fcons (Qmenu_bar_size, Fcons (make_number (0), make_number (0))),
2978              Fcons (Qtool_bar_external,
2979                     FRAME_EXTERNAL_TOOL_BAR (f) ? Qt : Qnil),
2980              Fcons (Qtool_bar_position, FRAME_TOOL_BAR_POSITION (f)),
2981              Fcons (Qtool_bar_size,
2982                     Fcons (make_number (tool_bar_width),
2983                            make_number (tool_bar_height))),
2984              Fcons (Qinternal_border_width,
2985                     make_number (internal_border_width)));
2988 DEFUN ("ns-frame-geometry", Fns_frame_geometry, Sns_frame_geometry, 0, 1, 0,
2989        doc: /* Return geometric attributes of FRAME.
2990 FRAME must be a live frame and defaults to the selected one.  The return
2991 value is an association list of the attributes listed below.  All height
2992 and width values are in pixels.
2994 `outer-position' is a cons of the outer left and top edges of FRAME
2995   relative to the origin - the position (0, 0) - of FRAME's display.
2997 `outer-size' is a cons of the outer width and height of FRAME.  The
2998   outer size includes the title bar and the external borders as well as
2999   any menu and/or tool bar of frame.
3001 `external-border-size' is a cons of the horizontal and vertical width of
3002   FRAME's external borders as supplied by the window manager.
3004 `title-bar-size' is a cons of the width and height of the title bar of
3005   FRAME as supplied by the window manager.  If both of them are zero,
3006   FRAME has no title bar.  If only the width is zero, Emacs was not
3007   able to retrieve the width information.
3009 `menu-bar-external', if non-nil, means the menu bar is external (never
3010   included in the inner edges of FRAME).
3012 `menu-bar-size' is a cons of the width and height of the menu bar of
3013   FRAME.
3015 `tool-bar-external', if non-nil, means the tool bar is external (never
3016   included in the inner edges of FRAME).
3018 `tool-bar-position' tells on which side the tool bar on FRAME is and can
3019   be one of `left', `top', `right' or `bottom'.  If this is nil, FRAME
3020   has no tool bar.
3022 `tool-bar-size' is a cons of the width and height of the tool bar of
3023   FRAME.
3025 `internal-border-width' is the width of the internal border of
3026   FRAME.  */)
3027   (Lisp_Object frame)
3029   return frame_geometry (frame, Qnil);
3032 DEFUN ("ns-frame-edges", Fns_frame_edges, Sns_frame_edges, 0, 2, 0,
3033        doc: /* Return edge coordinates of FRAME.
3034 FRAME must be a live frame and defaults to the selected one.  The return
3035 value is a list of the form (LEFT, TOP, RIGHT, BOTTOM).  All values are
3036 in pixels relative to the origin - the position (0, 0) - of FRAME's
3037 display.
3039 If optional argument TYPE is the symbol `outer-edges', return the outer
3040 edges of FRAME.  The outer edges comprise the decorations of the window
3041 manager (like the title bar or external borders) as well as any external
3042 menu or tool bar of FRAME.  If optional argument TYPE is the symbol
3043 `native-edges' or nil, return the native edges of FRAME.  The native
3044 edges exclude the decorations of the window manager and any external
3045 menu or tool bar of FRAME.  If TYPE is the symbol `inner-edges', return
3046 the inner edges of FRAME.  These edges exclude title bar, any borders,
3047 menu bar or tool bar of FRAME.  */)
3048   (Lisp_Object frame, Lisp_Object type)
3050   return frame_geometry (frame, ((EQ (type, Qouter_edges)
3051                                   || EQ (type, Qinner_edges))
3052                                  ? type
3053                                  : Qnative_edges));
3056 /* ==========================================================================
3058     Class implementations
3060    ========================================================================== */
3063   Handle arrow/function/control keys and copy/paste/cut in file dialogs.
3064   Return YES if handled, NO if not.
3065  */
3066 static BOOL
3067 handlePanelKeys (NSSavePanel *panel, NSEvent *theEvent)
3069   NSString *s;
3070   int i;
3071   BOOL ret = NO;
3073   if ([theEvent type] != NSEventTypeKeyDown) return NO;
3074   s = [theEvent characters];
3076   for (i = 0; i < [s length]; ++i)
3077     {
3078       int ch = (int) [s characterAtIndex: i];
3079       switch (ch)
3080         {
3081         case NSHomeFunctionKey:
3082         case NSDownArrowFunctionKey:
3083         case NSUpArrowFunctionKey:
3084         case NSLeftArrowFunctionKey:
3085         case NSRightArrowFunctionKey:
3086         case NSPageUpFunctionKey:
3087         case NSPageDownFunctionKey:
3088         case NSEndFunctionKey:
3089           /* Don't send command modified keys, as those are handled in the
3090              performKeyEquivalent method of the super class.
3091           */
3092           if (! ([theEvent modifierFlags] & NSEventModifierFlagCommand))
3093             {
3094               [panel sendEvent: theEvent];
3095               ret = YES;
3096             }
3097           break;
3098           /* As we don't have the standard key commands for
3099              copy/paste/cut/select-all in our edit menu, we must handle
3100              them here.  TODO: handle Emacs key bindings for copy/cut/select-all
3101              here, paste works, because we have that in our Edit menu.
3102              I.e. refactor out code in nsterm.m, keyDown: to figure out the
3103              correct modifier.
3104           */
3105         case 'x': // Cut
3106         case 'c': // Copy
3107         case 'v': // Paste
3108         case 'a': // Select all
3109           if ([theEvent modifierFlags] & NSEventModifierFlagCommand)
3110             {
3111               [NSApp sendAction:
3112                        (ch == 'x'
3113                         ? @selector(cut:)
3114                         : (ch == 'c'
3115                            ? @selector(copy:)
3116                            : (ch == 'v'
3117                               ? @selector(paste:)
3118                               : @selector(selectAll:))))
3119                              to:nil from:panel];
3120               ret = YES;
3121             }
3122         default:
3123           // Send all control keys, as the text field supports C-a, C-f, C-e
3124           // C-b and more.
3125           if ([theEvent modifierFlags] & NSEventModifierFlagControl)
3126             {
3127               [panel sendEvent: theEvent];
3128               ret = YES;
3129             }
3130           break;
3131         }
3132     }
3135   return ret;
3138 @implementation EmacsSavePanel
3139 - (BOOL)performKeyEquivalent:(NSEvent *)theEvent
3141   BOOL ret = handlePanelKeys (self, theEvent);
3142   if (! ret)
3143     ret = [super performKeyEquivalent:theEvent];
3144   return ret;
3146 @end
3149 @implementation EmacsOpenPanel
3150 - (BOOL)performKeyEquivalent:(NSEvent *)theEvent
3152   // NSOpenPanel inherits NSSavePanel, so passing self is OK.
3153   BOOL ret = handlePanelKeys (self, theEvent);
3154   if (! ret)
3155     ret = [super performKeyEquivalent:theEvent];
3156   return ret;
3158 @end
3161 @implementation EmacsFileDelegate
3162 /* --------------------------------------------------------------------------
3163    Delegate methods for Open/Save panels
3164    -------------------------------------------------------------------------- */
3165 - (BOOL)panel: (id)sender isValidFilename: (NSString *)filename
3167   return YES;
3169 - (BOOL)panel: (id)sender shouldShowFilename: (NSString *)filename
3171   return YES;
3173 - (NSString *)panel: (id)sender userEnteredFilename: (NSString *)filename
3174           confirmed: (BOOL)okFlag
3176   return filename;
3178 @end
3180 #endif
3183 /* ==========================================================================
3185     Lisp interface declaration
3187    ========================================================================== */
3190 void
3191 syms_of_nsfns (void)
3193   DEFSYM (Qfontsize, "fontsize");
3194   DEFSYM (Qframe_title_format, "frame-title-format");
3195   DEFSYM (Qicon_title_format, "icon-title-format");
3197   DEFVAR_LISP ("ns-icon-type-alist", Vns_icon_type_alist,
3198                doc: /* Alist of elements (REGEXP . IMAGE) for images of icons associated to frames.
3199 If the title of a frame matches REGEXP, then IMAGE.tiff is
3200 selected as the image of the icon representing the frame when it's
3201 miniaturized.  If an element is t, then Emacs tries to select an icon
3202 based on the filetype of the visited file.
3204 The images have to be installed in a folder called English.lproj in the
3205 Emacs folder.  You have to restart Emacs after installing new icons.
3207 Example: Install an icon Gnus.tiff and execute the following code
3209   (setq ns-icon-type-alist
3210         (append ns-icon-type-alist
3211                 \\='((\"^\\\\*\\\\(Group\\\\*$\\\\|Summary \\\\|Article\\\\*$\\\\)\"
3212                    . \"Gnus\"))))
3214 When you miniaturize a Group, Summary or Article frame, Gnus.tiff will
3215 be used as the image of the icon representing the frame.  */);
3216   Vns_icon_type_alist = list1 (Qt);
3218   DEFVAR_LISP ("ns-version-string", Vns_version_string,
3219                doc: /* Toolkit version for NS Windowing.  */);
3220   Vns_version_string = ns_appkit_version_str ();
3222   defsubr (&Sns_read_file_name);
3223   defsubr (&Sns_get_resource);
3224   defsubr (&Sns_set_resource);
3225   defsubr (&Sxw_display_color_p); /* this and next called directly by C code */
3226   defsubr (&Sx_display_grayscale_p);
3227   defsubr (&Sns_font_name);
3228   defsubr (&Sns_list_colors);
3229 #ifdef NS_IMPL_COCOA
3230   defsubr (&Sns_do_applescript);
3231 #endif
3232   defsubr (&Sxw_color_defined_p);
3233   defsubr (&Sxw_color_values);
3234   defsubr (&Sx_server_max_request_size);
3235   defsubr (&Sx_server_vendor);
3236   defsubr (&Sx_server_version);
3237   defsubr (&Sx_display_pixel_width);
3238   defsubr (&Sx_display_pixel_height);
3239   defsubr (&Sns_display_monitor_attributes_list);
3240   defsubr (&Sns_frame_geometry);
3241   defsubr (&Sns_frame_edges);
3242   defsubr (&Sns_frame_list_z_order);
3243   defsubr (&Sns_frame_restack);
3244   defsubr (&Sx_display_mm_width);
3245   defsubr (&Sx_display_mm_height);
3246   defsubr (&Sx_display_screens);
3247   defsubr (&Sx_display_planes);
3248   defsubr (&Sx_display_color_cells);
3249   defsubr (&Sx_display_visual_class);
3250   defsubr (&Sx_display_backing_store);
3251   defsubr (&Sx_display_save_under);
3252   defsubr (&Sx_create_frame);
3253   defsubr (&Sx_open_connection);
3254   defsubr (&Sx_close_connection);
3255   defsubr (&Sx_display_list);
3257   defsubr (&Sns_hide_others);
3258   defsubr (&Sns_hide_emacs);
3259   defsubr (&Sns_emacs_info_panel);
3260   defsubr (&Sns_list_services);
3261   defsubr (&Sns_perform_service);
3262   defsubr (&Sns_popup_font_panel);
3263   defsubr (&Sns_popup_color_panel);
3265   defsubr (&Sx_show_tip);
3266   defsubr (&Sx_hide_tip);
3268   as_status = 0;
3269   as_script = Qnil;
3270   as_result = 0;