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