Fix problems found by static checking --with-ns
[emacs.git] / src / nsfns.m
blobce2622c806238c69e2dbfe0053333a805bb4b1b2
1 /* Functions for the NeXT/Open/GNUstep and MacOSX window system.
3 Copyright (C) 1989, 1992-1994, 2005-2006, 2008-2016 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 MacOSX/Aqua port by Christophe de Dinechin (descubes@earthlink.net)
26 GNUstep port and post-20 update by Adrian Robert (arobert@cogsci.ucsd.edu)
29 /* This should be the first include, as it may set up #defines affecting
30    interpretation of even the system includes. */
31 #include <config.h>
33 #include <math.h>
34 #include <c-strcase.h>
36 #include "lisp.h"
37 #include "blockinput.h"
38 #include "nsterm.h"
39 #include "window.h"
40 #include "character.h"
41 #include "buffer.h"
42 #include "keyboard.h"
43 #include "termhooks.h"
44 #include "fontset.h"
45 #include "font.h"
47 #ifdef NS_IMPL_COCOA
48 #include <IOKit/graphics/IOGraphicsLib.h>
49 #include "macfont.h"
50 #endif
53 #ifdef HAVE_NS
55 static EmacsTooltip *ns_tooltip = nil;
57 /* Static variables to handle applescript execution.  */
58 static Lisp_Object as_script, *as_result;
59 static int as_status;
61 static ptrdiff_t image_cache_refcount;
63 static struct ns_display_info *ns_display_info_for_name (Lisp_Object);
64 static void ns_set_name_as_filename (struct frame *);
66 /* ==========================================================================
68     Internal utility functions
70    ========================================================================== */
72 /* Let the user specify a Nextstep display with a Lisp object.
73    OBJECT may be nil, a frame or a terminal object.
74    nil stands for the selected frame--or, if that is not a Nextstep frame,
75    the first Nextstep display on the list.  */
77 static struct ns_display_info *
78 check_ns_display_info (Lisp_Object object)
80   struct ns_display_info *dpyinfo = NULL;
82   if (NILP (object))
83     {
84       struct frame *sf = XFRAME (selected_frame);
86       if (FRAME_NS_P (sf) && FRAME_LIVE_P (sf))
87         dpyinfo = FRAME_DISPLAY_INFO (sf);
88       else if (x_display_list != 0)
89         dpyinfo = x_display_list;
90       else
91         error ("Nextstep windows are not in use or not initialized");
92     }
93   else if (TERMINALP (object))
94     {
95       struct terminal *t = decode_live_terminal (object);
97       if (t->type != output_ns)
98         error ("Terminal %d is not a Nextstep display", t->id);
100       dpyinfo = t->display_info.ns;
101     }
102   else if (STRINGP (object))
103     dpyinfo = ns_display_info_for_name (object);
104   else
105     {
106       struct frame *f = decode_window_system_frame (object);
107       dpyinfo = FRAME_DISPLAY_INFO (f);
108     }
110   return dpyinfo;
114 static id
115 ns_get_window (Lisp_Object maybeFrame)
117   id view =nil, window =nil;
119   if (!FRAMEP (maybeFrame) || !FRAME_NS_P (XFRAME (maybeFrame)))
120     maybeFrame = selected_frame;/*wrong_type_argument (Qframep, maybeFrame); */
122   if (!NILP (maybeFrame))
123     view = FRAME_NS_VIEW (XFRAME (maybeFrame));
124   if (view) window =[view window];
126   return window;
130 /* Return the X display structure for the display named NAME.
131    Open a new connection if necessary.  */
132 static struct ns_display_info *
133 ns_display_info_for_name (Lisp_Object name)
135   struct ns_display_info *dpyinfo;
137   CHECK_STRING (name);
139   for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
140     if (!NILP (Fstring_equal (XCAR (dpyinfo->name_list_element), name)))
141       return dpyinfo;
143   error ("Emacs for Nextstep does not yet support multi-display");
145   Fx_open_connection (name, Qnil, Qnil);
146   dpyinfo = x_display_list;
148   if (dpyinfo == 0)
149     error ("Display on %s not responding.\n", SDATA (name));
151   return dpyinfo;
154 static NSString *
155 ns_filename_from_panel (NSSavePanel *panel)
157 #ifdef NS_IMPL_COCOA
158   NSURL *url = [panel URL];
159   NSString *str = [url path];
160   return str;
161 #else
162   return [panel filename];
163 #endif
166 static NSString *
167 ns_directory_from_panel (NSSavePanel *panel)
169 #ifdef NS_IMPL_COCOA
170   NSURL *url = [panel directoryURL];
171   NSString *str = [url path];
172   return str;
173 #else
174   return [panel directory];
175 #endif
178 static Lisp_Object
179 interpret_services_menu (NSMenu *menu, Lisp_Object prefix, Lisp_Object old)
180 /* --------------------------------------------------------------------------
181    Turn the input menu (an NSMenu) into a lisp list for tracking on lisp side
182    -------------------------------------------------------------------------- */
184   int i, count;
185   NSMenuItem *item;
186   const char *name;
187   Lisp_Object nameStr;
188   unsigned short key;
189   NSString *keys;
190   Lisp_Object res;
192   count = [menu numberOfItems];
193   for (i = 0; i<count; i++)
194     {
195       item = [menu itemAtIndex: i];
196       name = [[item title] UTF8String];
197       if (!name) continue;
199       nameStr = build_string (name);
201       if ([item hasSubmenu])
202         {
203           old = interpret_services_menu ([item submenu],
204                                         Fcons (nameStr, prefix), old);
205         }
206       else
207         {
208           keys = [item keyEquivalent];
209           if (keys && [keys length] )
210             {
211               key = [keys characterAtIndex: 0];
212               res = make_number (key|super_modifier);
213             }
214           else
215             {
216               res = Qundefined;
217             }
218           old = Fcons (Fcons (res,
219                             Freverse (Fcons (nameStr,
220                                            prefix))),
221                     old);
222         }
223     }
224   return old;
229 /* ==========================================================================
231     Frame parameter setters
233    ========================================================================== */
236 static void
237 x_set_foreground_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
239   NSColor *col;
240   EmacsCGFloat r, g, b, alpha;
242   /* Must block_input, because ns_lisp_to_color does block/unblock_input
243      which means that col may be deallocated in its unblock_input if there
244      is user input, unless we also block_input.  */
245   block_input ();
246   if (ns_lisp_to_color (arg, &col))
247     {
248       store_frame_param (f, Qforeground_color, oldval);
249       unblock_input ();
250       error ("Unknown color");
251     }
253   [col retain];
254   [f->output_data.ns->foreground_color release];
255   f->output_data.ns->foreground_color = col;
257   [col getRed: &r green: &g blue: &b alpha: &alpha];
258   FRAME_FOREGROUND_PIXEL (f) =
259     ARGB_TO_ULONG ((int)(alpha*0xff), (int)(r*0xff), (int)(g*0xff), (int)(b*0xff));
261   if (FRAME_NS_VIEW (f))
262     {
263       update_face_from_frame_parameter (f, Qforeground_color, arg);
264       /*recompute_basic_faces (f); */
265       if (FRAME_VISIBLE_P (f))
266         SET_FRAME_GARBAGED (f);
267     }
268   unblock_input ();
272 static void
273 x_set_background_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
275   struct face *face;
276   NSColor *col;
277   NSView *view = FRAME_NS_VIEW (f);
278   EmacsCGFloat r, g, b, alpha;
280   block_input ();
281   if (ns_lisp_to_color (arg, &col))
282     {
283       store_frame_param (f, Qbackground_color, oldval);
284       unblock_input ();
285       error ("Unknown color");
286     }
288   /* clear the frame; in some instances the NS-internal GC appears not to
289      update, or it does update and cannot clear old text properly */
290   if (FRAME_VISIBLE_P (f))
291     ns_clear_frame (f);
293   [col retain];
294   [f->output_data.ns->background_color release];
295   f->output_data.ns->background_color = col;
297   [col getRed: &r green: &g blue: &b alpha: &alpha];
298   FRAME_BACKGROUND_PIXEL (f) =
299     ARGB_TO_ULONG ((int)(alpha*0xff), (int)(r*0xff), (int)(g*0xff), (int)(b*0xff));
301   if (view != nil)
302     {
303       [[view window] setBackgroundColor: col];
305       if (alpha != (EmacsCGFloat) 1.0)
306           [[view window] setOpaque: NO];
307       else
308           [[view window] setOpaque: YES];
310       face = FRAME_DEFAULT_FACE (f);
311       if (face)
312         {
313           col = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f);
314           face->background = ns_index_color
315             ([col colorWithAlphaComponent: alpha], f);
317           update_face_from_frame_parameter (f, Qbackground_color, arg);
318         }
320       if (FRAME_VISIBLE_P (f))
321         SET_FRAME_GARBAGED (f);
322     }
323   unblock_input ();
327 static void
328 x_set_cursor_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
330   NSColor *col;
332   block_input ();
333   if (ns_lisp_to_color (arg, &col))
334     {
335       store_frame_param (f, Qcursor_color, oldval);
336       unblock_input ();
337       error ("Unknown color");
338     }
340   [FRAME_CURSOR_COLOR (f) release];
341   FRAME_CURSOR_COLOR (f) = [col retain];
343   if (FRAME_VISIBLE_P (f))
344     {
345       x_update_cursor (f, 0);
346       x_update_cursor (f, 1);
347     }
348   update_face_from_frame_parameter (f, Qcursor_color, arg);
349   unblock_input ();
353 static void
354 x_set_icon_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
356   NSView *view = FRAME_NS_VIEW (f);
357   NSTRACE ("x_set_icon_name");
359   /* see if it's changed */
360   if (STRINGP (arg))
361     {
362       if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
363         return;
364     }
365   else if (!STRINGP (oldval) && EQ (oldval, Qnil) == EQ (arg, Qnil))
366     return;
368   fset_icon_name (f, arg);
370   if (NILP (arg))
371     {
372       if (!NILP (f->title))
373         arg = f->title;
374       else
375         /* Explicit name and no icon-name -> explicit_name.  */
376         if (f->explicit_name)
377           arg = f->name;
378         else
379           {
380             /* No explicit name and no icon-name ->
381                name has to be rebuild from icon_title_format.  */
382             windows_or_buffers_changed = 62;
383             return;
384           }
385     }
387   /* Don't change the name if it's already NAME.  */
388   if ([[view window] miniwindowTitle]
389       && ([[[view window] miniwindowTitle]
390              isEqualToString: [NSString stringWithUTF8String:
391                                           SSDATA (arg)]]))
392     return;
394   [[view window] setMiniwindowTitle:
395         [NSString stringWithUTF8String: SSDATA (arg)]];
398 static void
399 ns_set_name_internal (struct frame *f, Lisp_Object name)
401   Lisp_Object encoded_name, encoded_icon_name;
402   NSString *str;
403   NSView *view = FRAME_NS_VIEW (f);
406   encoded_name = ENCODE_UTF_8 (name);
408   str = [NSString stringWithUTF8String: SSDATA (encoded_name)];
411   /* Don't change the name if it's already NAME.  */
412   if (! [[[view window] title] isEqualToString: str])
413     [[view window] setTitle: str];
415   if (!STRINGP (f->icon_name))
416     encoded_icon_name = encoded_name;
417   else
418     encoded_icon_name = ENCODE_UTF_8 (f->icon_name);
420   str = [NSString stringWithUTF8String: SSDATA (encoded_icon_name)];
422   if ([[view window] miniwindowTitle]
423       && ! [[[view window] miniwindowTitle] isEqualToString: str])
424     [[view window] setMiniwindowTitle: str];
428 static void
429 ns_set_name (struct frame *f, Lisp_Object name, int explicit)
431   NSTRACE ("ns_set_name");
433   /* Make sure that requests from lisp code override requests from
434      Emacs redisplay code.  */
435   if (explicit)
436     {
437       /* If we're switching from explicit to implicit, we had better
438          update the mode lines and thereby update the title.  */
439       if (f->explicit_name && NILP (name))
440         update_mode_lines = 21;
442       f->explicit_name = ! NILP (name);
443     }
444   else if (f->explicit_name)
445     return;
447   if (NILP (name))
448     name = build_string ([ns_app_name UTF8String]);
449   else
450     CHECK_STRING (name);
452   /* Don't change the name if it's already NAME.  */
453   if (! NILP (Fstring_equal (name, f->name)))
454     return;
456   fset_name (f, name);
458   /* Title overrides explicit name.  */
459   if (! NILP (f->title))
460     name = f->title;
462   ns_set_name_internal (f, name);
466 /* This function should be called when the user's lisp code has
467    specified a name for the frame; the name will override any set by the
468    redisplay code.  */
469 static void
470 x_explicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
472   NSTRACE ("x_explicitly_set_name");
473   ns_set_name (f, arg, 1);
477 /* This function should be called by Emacs redisplay code to set the
478    name; names set this way will never override names set by the user's
479    lisp code.  */
480 void
481 x_implicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
483   NSTRACE ("x_implicitly_set_name");
485   Lisp_Object frame_title = buffer_local_value
486     (Qframe_title_format, XWINDOW (f->selected_window)->contents);
487   Lisp_Object icon_title = buffer_local_value
488     (Qicon_title_format, XWINDOW (f->selected_window)->contents);
490   /* Deal with NS specific format t.  */
491   if (FRAME_NS_P (f) && ((FRAME_ICONIFIED_P (f) && EQ (icon_title, Qt))
492                          || EQ (frame_title, Qt)))
493     ns_set_name_as_filename (f);
494   else
495     ns_set_name (f, arg, 0);
499 /* Change the title of frame F to NAME.
500    If NAME is nil, use the frame name as the title.  */
502 static void
503 x_set_title (struct frame *f, Lisp_Object name, Lisp_Object old_name)
505   NSTRACE ("x_set_title");
506   /* Don't change the title if it's already NAME.  */
507   if (EQ (name, f->title))
508     return;
510   update_mode_lines = 22;
512   fset_title (f, name);
514   if (NILP (name))
515     name = f->name;
516   else
517     CHECK_STRING (name);
519   ns_set_name_internal (f, name);
523 static void
524 ns_set_name_as_filename (struct frame *f)
526   NSView *view;
527   Lisp_Object name, filename;
528   Lisp_Object buf = XWINDOW (f->selected_window)->contents;
529   const char *title;
530   NSAutoreleasePool *pool;
531   Lisp_Object encoded_name, encoded_filename;
532   NSString *str;
533   NSTRACE ("ns_set_name_as_filename");
535   if (f->explicit_name || ! NILP (f->title))
536     return;
538   block_input ();
539   pool = [[NSAutoreleasePool alloc] init];
540   filename = BVAR (XBUFFER (buf), filename);
541   name = BVAR (XBUFFER (buf), name);
543   if (NILP (name))
544     {
545       if (! NILP (filename))
546         name = Ffile_name_nondirectory (filename);
547       else
548         name = build_string ([ns_app_name UTF8String]);
549     }
551   encoded_name = ENCODE_UTF_8 (name);
553   view = FRAME_NS_VIEW (f);
555   title = FRAME_ICONIFIED_P (f) ? [[[view window] miniwindowTitle] UTF8String]
556                                 : [[[view window] title] UTF8String];
558   if (title && (! strcmp (title, SSDATA (encoded_name))))
559     {
560       [pool release];
561       unblock_input ();
562       return;
563     }
565   str = [NSString stringWithUTF8String: SSDATA (encoded_name)];
566   if (str == nil) str = @"Bad coding";
568   if (FRAME_ICONIFIED_P (f))
569     [[view window] setMiniwindowTitle: str];
570   else
571     {
572       NSString *fstr;
574       if (! NILP (filename))
575         {
576           encoded_filename = ENCODE_UTF_8 (filename);
578           fstr = [NSString stringWithUTF8String: SSDATA (encoded_filename)];
579           if (fstr == nil) fstr = @"";
580         }
581       else
582         fstr = @"";
584       ns_set_represented_filename (fstr, f);
585       [[view window] setTitle: str];
586       fset_name (f, name);
587     }
589   [pool release];
590   unblock_input ();
594 void
595 ns_set_doc_edited (void)
597   NSAutoreleasePool *pool;
598   Lisp_Object tail, frame;
599   block_input ();
600   pool = [[NSAutoreleasePool alloc] init];
601   FOR_EACH_FRAME (tail, frame)
602     {
603       BOOL edited = NO;
604       struct frame *f = XFRAME (frame);
605       struct window *w;
606       NSView *view;
608       if (! FRAME_NS_P (f)) continue;
609       w = XWINDOW (FRAME_SELECTED_WINDOW (f));
610       view = FRAME_NS_VIEW (f);
611       if (!MINI_WINDOW_P (w))
612         edited = ! NILP (Fbuffer_modified_p (w->contents)) &&
613           ! NILP (Fbuffer_file_name (w->contents));
614       [[view window] setDocumentEdited: edited];
615     }
617   [pool release];
618   unblock_input ();
622 static void
623 x_set_menu_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
625   int nlines;
626   if (FRAME_MINIBUF_ONLY_P (f))
627     return;
629   if (TYPE_RANGED_INTEGERP (int, value))
630     nlines = XINT (value);
631   else
632     nlines = 0;
634   FRAME_MENU_BAR_LINES (f) = 0;
635   if (nlines)
636     {
637       FRAME_EXTERNAL_MENU_BAR (f) = 1;
638       /* does for all frames, whereas we just want for one frame
639          [NSMenu setMenuBarVisible: YES]; */
640     }
641   else
642     {
643       if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
644         free_frame_menubar (f);
645       /*      [NSMenu setMenuBarVisible: NO]; */
646       FRAME_EXTERNAL_MENU_BAR (f) = 0;
647     }
651 /* toolbar support */
652 static void
653 x_set_tool_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
655   /* Currently, when the tool bar change state, the frame is resized.
657      TODO: It would be better if this didn't occur when 1) the frame
658      is full height or maximized or 2) when specified by
659      `frame-inhibit-implied-resize'. */
660   int nlines;
662   NSTRACE ("x_set_tool_bar_lines");
664   if (FRAME_MINIBUF_ONLY_P (f))
665     return;
667   if (RANGED_INTEGERP (0, value, INT_MAX))
668     nlines = XFASTINT (value);
669   else
670     nlines = 0;
672   if (nlines)
673     {
674       FRAME_EXTERNAL_TOOL_BAR (f) = 1;
675       update_frame_tool_bar (f);
676     }
677   else
678     {
679       if (FRAME_EXTERNAL_TOOL_BAR (f))
680         {
681           free_frame_tool_bar (f);
682           FRAME_EXTERNAL_TOOL_BAR (f) = 0;
684           {
685             EmacsView *view = FRAME_NS_VIEW (f);
686             int fs_state = [view fullscreenState];
688             if (fs_state == FULLSCREEN_MAXIMIZED)
689               {
690                 [view setFSValue:FULLSCREEN_WIDTH];
691               }
692             else if (fs_state == FULLSCREEN_HEIGHT)
693               {
694                 [view setFSValue:FULLSCREEN_NONE];
695               }
696           }
697        }
698     }
700   {
701     int inhibit
702       = ((f->after_make_frame
703           && !f->tool_bar_resized
704           && (EQ (frame_inhibit_implied_resize, Qt)
705               || (CONSP (frame_inhibit_implied_resize)
706                   && !NILP (Fmemq (Qtool_bar_lines,
707                                    frame_inhibit_implied_resize))))
708           && NILP (get_frame_param (f, Qfullscreen)))
709          ? 0
710          : 2);
712     NSTRACE_MSG ("inhibit:%d", inhibit);
714     frame_size_history_add (f, Qupdate_frame_tool_bar, 0, 0, Qnil);
715     adjust_frame_size (f, -1, -1, inhibit, 0, Qtool_bar_lines);
716   }
720 static void
721 x_set_internal_border_width (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
723   int old_width = FRAME_INTERNAL_BORDER_WIDTH (f);
725   CHECK_TYPE_RANGED_INTEGER (int, arg);
726   f->internal_border_width = XINT (arg);
727   if (FRAME_INTERNAL_BORDER_WIDTH (f) < 0)
728     f->internal_border_width = 0;
730   if (FRAME_INTERNAL_BORDER_WIDTH (f) == old_width)
731     return;
733   if (FRAME_X_WINDOW (f) != 0)
734     adjust_frame_size (f, -1, -1, 3, 0, Qinternal_border_width);
736   SET_FRAME_GARBAGED (f);
740 static void
741 ns_implicitly_set_icon_type (struct frame *f)
743   Lisp_Object tem;
744   EmacsView *view = FRAME_NS_VIEW (f);
745   id image = nil;
746   Lisp_Object chain, elt;
747   NSAutoreleasePool *pool;
748   BOOL setMini = YES;
750   NSTRACE ("ns_implicitly_set_icon_type");
752   block_input ();
753   pool = [[NSAutoreleasePool alloc] init];
754   if (f->output_data.ns->miniimage
755       && [[NSString stringWithUTF8String: SSDATA (f->name)]
756                isEqualToString: [(NSImage *)f->output_data.ns->miniimage name]])
757     {
758       [pool release];
759       unblock_input ();
760       return;
761     }
763   tem = assq_no_quit (Qicon_type, f->param_alist);
764   if (CONSP (tem) && ! NILP (XCDR (tem)))
765     {
766       [pool release];
767       unblock_input ();
768       return;
769     }
771   for (chain = Vns_icon_type_alist;
772        image == nil && CONSP (chain);
773        chain = XCDR (chain))
774     {
775       elt = XCAR (chain);
776       /* special case: t means go by file type */
777       if (SYMBOLP (elt) && EQ (elt, Qt) && SSDATA (f->name)[0] == '/')
778         {
779           NSString *str
780              = [NSString stringWithUTF8String: SSDATA (f->name)];
781           if ([[NSFileManager defaultManager] fileExistsAtPath: str])
782             image = [[[NSWorkspace sharedWorkspace] iconForFile: str] retain];
783         }
784       else if (CONSP (elt) &&
785                STRINGP (XCAR (elt)) &&
786                STRINGP (XCDR (elt)) &&
787                fast_string_match (XCAR (elt), f->name) >= 0)
788         {
789           image = [EmacsImage allocInitFromFile: XCDR (elt)];
790           if (image == nil)
791             image = [[NSImage imageNamed:
792                                [NSString stringWithUTF8String:
793                                             SSDATA (XCDR (elt))]] retain];
794         }
795     }
797   if (image == nil)
798     {
799       image = [[[NSWorkspace sharedWorkspace] iconForFileType: @"text"] retain];
800       setMini = NO;
801     }
803   [f->output_data.ns->miniimage release];
804   f->output_data.ns->miniimage = image;
805   [view setMiniwindowImage: setMini];
806   [pool release];
807   unblock_input ();
811 static void
812 x_set_icon_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
814   EmacsView *view = FRAME_NS_VIEW (f);
815   id image = nil;
816   BOOL setMini = YES;
818   NSTRACE ("x_set_icon_type");
820   if (!NILP (arg) && SYMBOLP (arg))
821     {
822       arg =build_string (SSDATA (SYMBOL_NAME (arg)));
823       store_frame_param (f, Qicon_type, arg);
824     }
826   /* do it the implicit way */
827   if (NILP (arg))
828     {
829       ns_implicitly_set_icon_type (f);
830       return;
831     }
833   CHECK_STRING (arg);
835   image = [EmacsImage allocInitFromFile: arg];
836   if (image == nil)
837     image =[NSImage imageNamed: [NSString stringWithUTF8String:
838                                             SSDATA (arg)]];
840   if (image == nil)
841     {
842       image = [NSImage imageNamed: @"text"];
843       setMini = NO;
844     }
846   f->output_data.ns->miniimage = image;
847   [view setMiniwindowImage: setMini];
850 /* This is the same as the xfns.c definition.  */
851 static void
852 x_set_cursor_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
854   set_frame_cursor_types (f, arg);
857 /* called to set mouse pointer color, but all other terms use it to
858    initialize pointer types (and don't set the color ;) */
859 static void
860 x_set_mouse_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
862   /* don't think we can do this on Nextstep */
866 #define Str(x) #x
867 #define Xstr(x) Str(x)
869 static Lisp_Object
870 ns_appkit_version_str (void)
872   char tmp[256];
874 #ifdef NS_IMPL_GNUSTEP
875   sprintf(tmp, "gnustep-gui-%s", Xstr(GNUSTEP_GUI_VERSION));
876 #elif defined (NS_IMPL_COCOA)
877   NSString *osversion
878     = [[NSProcessInfo processInfo] operatingSystemVersionString];
879   sprintf(tmp, "appkit-%.2f %s",
880           NSAppKitVersionNumber,
881           [osversion UTF8String]);
882 #else
883   tmp = "ns-unknown";
884 #endif
885   return build_string (tmp);
889 /* This is for use by x-server-version and collapses all version info we
890    have into a single int.  For a better picture of the implementation
891    running, use ns_appkit_version_str.*/
892 static int
893 ns_appkit_version_int (void)
895 #ifdef NS_IMPL_GNUSTEP
896   return GNUSTEP_GUI_MAJOR_VERSION * 100 + GNUSTEP_GUI_MINOR_VERSION;
897 #elif defined (NS_IMPL_COCOA)
898   return (int)NSAppKitVersionNumber;
899 #endif
900   return 0;
904 static void
905 x_icon (struct frame *f, Lisp_Object parms)
906 /* --------------------------------------------------------------------------
907    Strangely-named function to set icon position parameters in frame.
908    This is irrelevant under OS X, but might be needed under GNUstep,
909    depending on the window manager used.  Note, this is not a standard
910    frame parameter-setter; it is called directly from x-create-frame.
911    -------------------------------------------------------------------------- */
913   Lisp_Object icon_x, icon_y;
914   struct ns_display_info *dpyinfo = check_ns_display_info (Qnil);
916   f->output_data.ns->icon_top = -1;
917   f->output_data.ns->icon_left = -1;
919   /* Set the position of the icon.  */
920   icon_x = x_get_arg (dpyinfo, parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
921   icon_y = x_get_arg (dpyinfo, parms, Qicon_top, 0, 0,  RES_TYPE_NUMBER);
922   if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
923     {
924       CHECK_NUMBER (icon_x);
925       CHECK_NUMBER (icon_y);
926       f->output_data.ns->icon_top = XINT (icon_y);
927       f->output_data.ns->icon_left = XINT (icon_x);
928     }
929   else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
930     error ("Both left and top icon corners of icon must be specified");
934 /* Note: see frame.c for template, also where generic functions are impl */
935 frame_parm_handler ns_frame_parm_handlers[] =
937   x_set_autoraise, /* generic OK */
938   x_set_autolower, /* generic OK */
939   x_set_background_color,
940   0, /* x_set_border_color,  may be impossible under Nextstep */
941   0, /* x_set_border_width,  may be impossible under Nextstep */
942   x_set_cursor_color,
943   x_set_cursor_type,
944   x_set_font, /* generic OK */
945   x_set_foreground_color,
946   x_set_icon_name,
947   x_set_icon_type,
948   x_set_internal_border_width, /* generic OK */
949   x_set_right_divider_width,
950   x_set_bottom_divider_width,
951   x_set_menu_bar_lines,
952   x_set_mouse_color,
953   x_explicitly_set_name,
954   x_set_scroll_bar_width, /* generic OK */
955   x_set_scroll_bar_height, /* generic OK */
956   x_set_title,
957   x_set_unsplittable, /* generic OK */
958   x_set_vertical_scroll_bars, /* generic OK */
959   x_set_horizontal_scroll_bars, /* generic OK */
960   x_set_visibility, /* generic OK */
961   x_set_tool_bar_lines,
962   0, /* x_set_scroll_bar_foreground, will ignore (not possible on NS) */
963   0, /* x_set_scroll_bar_background,  will ignore (not possible on NS) */
964   x_set_screen_gamma, /* generic OK */
965   x_set_line_spacing, /* generic OK, sets f->extra_line_spacing to int */
966   x_set_left_fringe, /* generic OK */
967   x_set_right_fringe, /* generic OK */
968   0, /* x_set_wait_for_wm, will ignore */
969   x_set_fullscreen, /* generic OK */
970   x_set_font_backend, /* generic OK */
971   x_set_alpha,
972   0, /* x_set_sticky */
973   0, /* x_set_tool_bar_position */
977 /* Handler for signals raised during x_create_frame.
978    FRAME is the frame which is partially constructed.  */
980 static void
981 unwind_create_frame (Lisp_Object frame)
983   struct frame *f = XFRAME (frame);
985   /* If frame is already dead, nothing to do.  This can happen if the
986      display is disconnected after the frame has become official, but
987      before x_create_frame removes the unwind protect.  */
988   if (!FRAME_LIVE_P (f))
989     return;
991   /* If frame is ``official'', nothing to do.  */
992   if (NILP (Fmemq (frame, Vframe_list)))
993     {
994 #if defined GLYPH_DEBUG && defined ENABLE_CHECKING
995       struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
996 #endif
998       /* If the frame's image cache refcount is still the same as our
999          private shadow variable, it means we are unwinding a frame
1000          for which we didn't yet call init_frame_faces, where the
1001          refcount is incremented.  Therefore, we increment it here, so
1002          that free_frame_faces, called in x_free_frame_resources
1003          below, will not mistakenly decrement the counter that was not
1004          incremented yet to account for this new frame.  */
1005       if (FRAME_IMAGE_CACHE (f) != NULL
1006           && FRAME_IMAGE_CACHE (f)->refcount == image_cache_refcount)
1007         FRAME_IMAGE_CACHE (f)->refcount++;
1009       x_free_frame_resources (f);
1010       free_glyphs (f);
1012 #if defined GLYPH_DEBUG && defined ENABLE_CHECKING
1013       /* Check that reference counts are indeed correct.  */
1014       eassert (dpyinfo->terminal->image_cache->refcount == image_cache_refcount);
1015 #endif
1016     }
1020  * Read geometry related parameters from preferences if not in PARMS.
1021  * Returns the union of parms and any preferences read.
1022  */
1024 static Lisp_Object
1025 get_geometry_from_preferences (struct ns_display_info *dpyinfo,
1026                                Lisp_Object parms)
1028   struct {
1029     const char *val;
1030     const char *cls;
1031     Lisp_Object tem;
1032   } r[] = {
1033     { "width",  "Width", Qwidth },
1034     { "height", "Height", Qheight },
1035     { "left", "Left", Qleft },
1036     { "top", "Top", Qtop },
1037   };
1039   int i;
1040   for (i = 0; i < ARRAYELTS (r); ++i)
1041     {
1042       if (NILP (Fassq (r[i].tem, parms)))
1043         {
1044           Lisp_Object value
1045             = x_get_arg (dpyinfo, parms, r[i].tem, r[i].val, r[i].cls,
1046                          RES_TYPE_NUMBER);
1047           if (! EQ (value, Qunbound))
1048             parms = Fcons (Fcons (r[i].tem, value), parms);
1049         }
1050     }
1052   return parms;
1055 /* ==========================================================================
1057     Lisp definitions
1059    ========================================================================== */
1061 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
1062        1, 1, 0,
1063        doc: /* Make a new Nextstep window, called a "frame" in Emacs terms.
1064 Return an Emacs frame object.
1065 PARMS is an alist of frame parameters.
1066 If the parameters specify that the frame should not have a minibuffer,
1067 and do not specify a specific minibuffer window to use,
1068 then `default-minibuffer-frame' must be a frame whose minibuffer can
1069 be shared by the new frame.
1071 This function is an internal primitive--use `make-frame' instead.  */)
1072      (Lisp_Object parms)
1074   struct frame *f;
1075   Lisp_Object frame, tem;
1076   Lisp_Object name;
1077   int minibuffer_only = 0;
1078   long window_prompting = 0;
1079   ptrdiff_t count = specpdl_ptr - specpdl;
1080   Lisp_Object display;
1081   struct ns_display_info *dpyinfo = NULL;
1082   Lisp_Object parent;
1083   struct kboard *kb;
1084   static int desc_ctr = 1;
1085   int x_width = 0, x_height = 0;
1087   /* x_get_arg modifies parms.  */
1088   parms = Fcopy_alist (parms);
1090   /* Use this general default value to start with
1091      until we know if this frame has a specified name.  */
1092   Vx_resource_name = Vinvocation_name;
1094   display = x_get_arg (dpyinfo, parms, Qterminal, 0, 0, RES_TYPE_STRING);
1095   if (EQ (display, Qunbound))
1096     display = Qnil;
1097   dpyinfo = check_ns_display_info (display);
1098   kb = dpyinfo->terminal->kboard;
1100   if (!dpyinfo->terminal->name)
1101     error ("Terminal is not live, can't create new frames on it");
1103   name = x_get_arg (dpyinfo, parms, Qname, 0, 0, RES_TYPE_STRING);
1104   if (!STRINGP (name)
1105       && ! EQ (name, Qunbound)
1106       && ! NILP (name))
1107     error ("Invalid frame name--not a string or nil");
1109   if (STRINGP (name))
1110     Vx_resource_name = name;
1112   parent = x_get_arg (dpyinfo, parms, Qparent_id, 0, 0, RES_TYPE_NUMBER);
1113   if (EQ (parent, Qunbound))
1114     parent = Qnil;
1115   if (! NILP (parent))
1116     CHECK_NUMBER (parent);
1118   /* make_frame_without_minibuffer can run Lisp code and garbage collect.  */
1119   /* No need to protect DISPLAY because that's not used after passing
1120      it to make_frame_without_minibuffer.  */
1121   frame = Qnil;
1122   tem = x_get_arg (dpyinfo, parms, Qminibuffer, "minibuffer", "Minibuffer",
1123                   RES_TYPE_SYMBOL);
1124   if (EQ (tem, Qnone) || NILP (tem))
1125       f = make_frame_without_minibuffer (Qnil, kb, display);
1126   else if (EQ (tem, Qonly))
1127     {
1128       f = make_minibuffer_frame ();
1129       minibuffer_only = 1;
1130     }
1131   else if (WINDOWP (tem))
1132       f = make_frame_without_minibuffer (tem, kb, display);
1133   else
1134       f = make_frame (1);
1136   XSETFRAME (frame, f);
1138   f->terminal = dpyinfo->terminal;
1140   f->output_method = output_ns;
1141   f->output_data.ns = xzalloc (sizeof *f->output_data.ns);
1143   FRAME_FONTSET (f) = -1;
1145   fset_icon_name (f, x_get_arg (dpyinfo, parms, Qicon_name,
1146                                 "iconName", "Title",
1147                                 RES_TYPE_STRING));
1148   if (! STRINGP (f->icon_name))
1149     fset_icon_name (f, Qnil);
1151   FRAME_DISPLAY_INFO (f) = dpyinfo;
1153   /* With FRAME_DISPLAY_INFO set up, this unwind-protect is safe.  */
1154   record_unwind_protect (unwind_create_frame, frame);
1156   f->output_data.ns->window_desc = desc_ctr++;
1157   if (TYPE_RANGED_INTEGERP (Window, parent))
1158     {
1159       f->output_data.ns->parent_desc = XFASTINT (parent);
1160       f->output_data.ns->explicit_parent = 1;
1161     }
1162   else
1163     {
1164       f->output_data.ns->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
1165       f->output_data.ns->explicit_parent = 0;
1166     }
1168   /* Set the name; the functions to which we pass f expect the name to
1169      be set.  */
1170   if (EQ (name, Qunbound) || NILP (name) || ! STRINGP (name))
1171     {
1172       fset_name (f, build_string ([ns_app_name UTF8String]));
1173       f->explicit_name = 0;
1174     }
1175   else
1176     {
1177       fset_name (f, name);
1178       f->explicit_name = 1;
1179       specbind (Qx_resource_name, name);
1180     }
1182   block_input ();
1184 #ifdef NS_IMPL_COCOA
1185     mac_register_font_driver (f);
1186 #else
1187     register_font_driver (&nsfont_driver, f);
1188 #endif
1190   image_cache_refcount =
1191     FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
1193   x_default_parameter (f, parms, Qfont_backend, Qnil,
1194                         "fontBackend", "FontBackend", RES_TYPE_STRING);
1196   {
1197     /* use for default font name */
1198     id font = [NSFont userFixedPitchFontOfSize: -1.0]; /* default */
1199     x_default_parameter (f, parms, Qfontsize,
1200                                     make_number (0 /*(int)[font pointSize]*/),
1201                                     "fontSize", "FontSize", RES_TYPE_NUMBER);
1202     // Remove ' Regular', not handled by backends.
1203     char *fontname = xstrdup ([[font displayName] UTF8String]);
1204     int len = strlen (fontname);
1205     if (len > 8 && strcmp (fontname + len - 8, " Regular") == 0)
1206       fontname[len-8] = '\0';
1207     x_default_parameter (f, parms, Qfont,
1208                                  build_string (fontname),
1209                                  "font", "Font", RES_TYPE_STRING);
1210     xfree (fontname);
1211   }
1212   unblock_input ();
1214   x_default_parameter (f, parms, Qborder_width, make_number (0),
1215                        "borderwidth", "BorderWidth", RES_TYPE_NUMBER);
1216   x_default_parameter (f, parms, Qinternal_border_width, make_number (2),
1217                       "internalBorderWidth", "InternalBorderWidth",
1218                       RES_TYPE_NUMBER);
1220   /* default vertical scrollbars on right on Mac */
1221   {
1222       Lisp_Object spos
1223 #ifdef NS_IMPL_GNUSTEP
1224           = Qt;
1225 #else
1226           = Qright;
1227 #endif
1228       x_default_parameter (f, parms, Qvertical_scroll_bars, spos,
1229                            "verticalScrollBars", "VerticalScrollBars",
1230                            RES_TYPE_SYMBOL);
1231   }
1232   x_default_parameter (f, parms, Qhorizontal_scroll_bars, Qnil,
1233                        "horizontalScrollBars", "HorizontalScrollBars",
1234                        RES_TYPE_SYMBOL);
1235   x_default_parameter (f, parms, Qforeground_color, build_string ("Black"),
1236                       "foreground", "Foreground", RES_TYPE_STRING);
1237   x_default_parameter (f, parms, Qbackground_color, build_string ("White"),
1238                       "background", "Background", RES_TYPE_STRING);
1239   /* FIXME: not supported yet in Nextstep */
1240   x_default_parameter (f, parms, Qline_spacing, Qnil,
1241                        "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
1242   x_default_parameter (f, parms, Qleft_fringe, Qnil,
1243                        "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
1244   x_default_parameter (f, parms, Qright_fringe, Qnil,
1245                        "rightFringe", "RightFringe", RES_TYPE_NUMBER);
1247   init_frame_faces (f);
1249   /* Read comment about this code in corresponding place in xfns.c.  */
1250   adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
1251                      FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 5, 1,
1252                      Qx_create_frame_1);
1254   /* The resources controlling the menu-bar and tool-bar are
1255      processed specially at startup, and reflected in the mode
1256      variables; ignore them here.  */
1257   x_default_parameter (f, parms, Qmenu_bar_lines,
1258                        NILP (Vmenu_bar_mode)
1259                        ? make_number (0) : make_number (1),
1260                        NULL, NULL, RES_TYPE_NUMBER);
1261   x_default_parameter (f, parms, Qtool_bar_lines,
1262                        NILP (Vtool_bar_mode)
1263                        ? make_number (0) : make_number (1),
1264                        NULL, NULL, RES_TYPE_NUMBER);
1266   x_default_parameter (f, parms, Qbuffer_predicate, Qnil, "bufferPredicate",
1267                        "BufferPredicate", RES_TYPE_SYMBOL);
1268   x_default_parameter (f, parms, Qtitle, Qnil, "title", "Title",
1269                        RES_TYPE_STRING);
1271   parms = get_geometry_from_preferences (dpyinfo, parms);
1272   window_prompting = x_figure_window_size (f, parms, true, &x_width, &x_height);
1274   tem = x_get_arg (dpyinfo, parms, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
1275   f->no_split = minibuffer_only || (!EQ (tem, Qunbound) && !EQ (tem, Qnil));
1277   /* NOTE: on other terms, this is done in set_mouse_color, however this
1278      was not getting called under Nextstep */
1279   f->output_data.ns->text_cursor = [NSCursor IBeamCursor];
1280   f->output_data.ns->nontext_cursor = [NSCursor arrowCursor];
1281   f->output_data.ns->modeline_cursor = [NSCursor pointingHandCursor];
1282   f->output_data.ns->hand_cursor = [NSCursor pointingHandCursor];
1283   f->output_data.ns->hourglass_cursor = [NSCursor disappearingItemCursor];
1284   f->output_data.ns->horizontal_drag_cursor = [NSCursor resizeLeftRightCursor];
1285   f->output_data.ns->vertical_drag_cursor = [NSCursor resizeUpDownCursor];
1286   FRAME_DISPLAY_INFO (f)->vertical_scroll_bar_cursor
1287      = [NSCursor arrowCursor];
1288   FRAME_DISPLAY_INFO (f)->horizontal_scroll_bar_cursor
1289      = [NSCursor arrowCursor];
1290   f->output_data.ns->current_pointer = f->output_data.ns->text_cursor;
1292   f->output_data.ns->in_animation = NO;
1294   [[EmacsView alloc] initFrameFromEmacs: f];
1296   x_icon (f, parms);
1298   /* ns_display_info does not have a reference_count.  */
1299   f->terminal->reference_count++;
1301   /* It is now ok to make the frame official even if we get an error below.
1302      The frame needs to be on Vframe_list or making it visible won't work. */
1303   Vframe_list = Fcons (frame, Vframe_list);
1305   x_default_parameter (f, parms, Qicon_type, Qnil,
1306                        "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
1308   x_default_parameter (f, parms, Qauto_raise, Qnil,
1309                        "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
1310   x_default_parameter (f, parms, Qauto_lower, Qnil,
1311                        "autoLower", "AutoLower", RES_TYPE_BOOLEAN);
1312   x_default_parameter (f, parms, Qcursor_type, Qbox,
1313                        "cursorType", "CursorType", RES_TYPE_SYMBOL);
1314   x_default_parameter (f, parms, Qscroll_bar_width, Qnil,
1315                        "scrollBarWidth", "ScrollBarWidth",
1316                        RES_TYPE_NUMBER);
1317   x_default_parameter (f, parms, Qscroll_bar_height, Qnil,
1318                        "scrollBarHeight", "ScrollBarHeight",
1319                        RES_TYPE_NUMBER);
1320   x_default_parameter (f, parms, Qalpha, Qnil,
1321                        "alpha", "Alpha", RES_TYPE_NUMBER);
1322   x_default_parameter (f, parms, Qfullscreen, Qnil,
1323                        "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
1325   /* Allow x_set_window_size, now.  */
1326   f->can_x_set_window_size = true;
1328   if (x_width > 0)
1329     SET_FRAME_WIDTH (f, x_width);
1330   if (x_height > 0)
1331     SET_FRAME_HEIGHT (f, x_height);
1333   adjust_frame_size (f, FRAME_TEXT_WIDTH (f), FRAME_TEXT_HEIGHT (f), 0, 1,
1334                      Qx_create_frame_2);
1336   if (! f->output_data.ns->explicit_parent)
1337     {
1338       Lisp_Object visibility;
1340       visibility = x_get_arg (dpyinfo, parms, Qvisibility, 0, 0,
1341                               RES_TYPE_SYMBOL);
1342       if (EQ (visibility, Qunbound))
1343         visibility = Qt;
1345       if (EQ (visibility, Qicon))
1346         x_iconify_frame (f);
1347       else if (! NILP (visibility))
1348         {
1349           x_make_frame_visible (f);
1350           [[FRAME_NS_VIEW (f) window] makeKeyWindow];
1351         }
1352       else
1353         {
1354           /* Must have been Qnil.  */
1355         }
1356     }
1358   if (FRAME_HAS_MINIBUF_P (f)
1359       && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
1360           || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
1361     kset_default_minibuffer_frame (kb, frame);
1363   /* All remaining specified parameters, which have not been "used"
1364      by x_get_arg and friends, now go in the misc. alist of the frame.  */
1365   for (tem = parms; CONSP (tem); tem = XCDR (tem))
1366     if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
1367       fset_param_alist (f, Fcons (XCAR (tem), f->param_alist));
1369   if (window_prompting & USPosition)
1370     x_set_offset (f, f->left_pos, f->top_pos, 1);
1372   /* Make sure windows on this frame appear in calls to next-window
1373      and similar functions.  */
1374   Vwindow_list = Qnil;
1376   return unbind_to (count, frame);
1379 void
1380 x_focus_frame (struct frame *f)
1382   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1384   if (dpyinfo->x_focus_frame != f)
1385     {
1386       EmacsView *view = FRAME_NS_VIEW (f);
1387       block_input ();
1388       [NSApp activateIgnoringOtherApps: YES];
1389       [[view window] makeKeyAndOrderFront: view];
1390       unblock_input ();
1391     }
1395 DEFUN ("ns-popup-font-panel", Fns_popup_font_panel, Sns_popup_font_panel,
1396        0, 1, "",
1397        doc: /* Pop up the font panel. */)
1398      (Lisp_Object frame)
1400   struct frame *f = decode_window_system_frame (frame);
1401   id fm = [NSFontManager sharedFontManager];
1402   struct font *font = f->output_data.ns->font;
1403   NSFont *nsfont;
1404 #ifdef NS_IMPL_GNUSTEP
1405   nsfont = ((struct nsfont_info *)font)->nsfont;
1406 #endif
1407 #ifdef NS_IMPL_COCOA
1408   nsfont = (NSFont *) macfont_get_nsctfont (font);
1409 #endif
1410   [fm setSelectedFont: nsfont isMultiple: NO];
1411   [fm orderFrontFontPanel: NSApp];
1412   return Qnil;
1416 DEFUN ("ns-popup-color-panel", Fns_popup_color_panel, Sns_popup_color_panel,
1417        0, 1, "",
1418        doc: /* Pop up the color panel.  */)
1419      (Lisp_Object frame)
1421   check_window_system (NULL);
1422   [NSApp orderFrontColorPanel: NSApp];
1423   return Qnil;
1426 static struct
1428   id panel;
1429   BOOL ret;
1430 #ifdef NS_IMPL_GNUSTEP
1431   NSString *dirS, *initS;
1432   BOOL no_types;
1433 #endif
1434 } ns_fd_data;
1436 void
1437 ns_run_file_dialog (void)
1439   if (ns_fd_data.panel == nil) return;
1440 #ifdef NS_IMPL_COCOA
1441   ns_fd_data.ret = [ns_fd_data.panel runModal];
1442 #else
1443   if (ns_fd_data.no_types)
1444     {
1445       ns_fd_data.ret = [ns_fd_data.panel
1446                            runModalForDirectory: ns_fd_data.dirS
1447                            file: ns_fd_data.initS];
1448     }
1449   else
1450     {
1451       ns_fd_data.ret = [ns_fd_data.panel
1452                            runModalForDirectory: ns_fd_data.dirS
1453                            file: ns_fd_data.initS
1454                            types: nil];
1455     }
1456 #endif
1457   ns_fd_data.panel = nil;
1460 #ifdef NS_IMPL_COCOA
1461 #if MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_9
1462 #define MODAL_OK_RESPONSE NSModalResponseOK
1463 #endif
1464 #endif
1465 #ifndef MODAL_OK_RESPONSE
1466 #define MODAL_OK_RESPONSE NSOKButton
1467 #endif
1469 DEFUN ("ns-read-file-name", Fns_read_file_name, Sns_read_file_name, 1, 5, 0,
1470        doc: /* Use a graphical panel to read a file name, using prompt PROMPT.
1471 Optional arg DIR, if non-nil, supplies a default directory.
1472 Optional arg MUSTMATCH, if non-nil, means the returned file or
1473 directory must exist.
1474 Optional arg INIT, if non-nil, provides a default file name to use.
1475 Optional arg DIR_ONLY_P, if non-nil, means choose only directories.  */)
1476   (Lisp_Object prompt, Lisp_Object dir, Lisp_Object mustmatch,
1477    Lisp_Object init, Lisp_Object dir_only_p)
1479   static id fileDelegate = nil;
1480   BOOL isSave = NILP (mustmatch) && NILP (dir_only_p);
1481   id panel;
1482   Lisp_Object fname = Qnil;
1484   NSString *promptS = NILP (prompt) || !STRINGP (prompt) ? nil :
1485     [NSString stringWithUTF8String: SSDATA (prompt)];
1486   NSString *dirS = NILP (dir) || !STRINGP (dir) ?
1487     [NSString stringWithUTF8String: SSDATA (BVAR (current_buffer, directory))] :
1488     [NSString stringWithUTF8String: SSDATA (dir)];
1489   NSString *initS = NILP (init) || !STRINGP (init) ? nil :
1490     [NSString stringWithUTF8String: SSDATA (init)];
1491   NSEvent *nxev;
1493   check_window_system (NULL);
1495   if (fileDelegate == nil)
1496     fileDelegate = [EmacsFileDelegate new];
1498   [NSCursor setHiddenUntilMouseMoves: NO];
1500   if ([dirS characterAtIndex: 0] == '~')
1501     dirS = [dirS stringByExpandingTildeInPath];
1503   panel = isSave ?
1504     (id)[EmacsSavePanel savePanel] : (id)[EmacsOpenPanel openPanel];
1506   [panel setTitle: promptS];
1508   [panel setAllowsOtherFileTypes: YES];
1509   [panel setTreatsFilePackagesAsDirectories: YES];
1510   [panel setDelegate: fileDelegate];
1512   if (! NILP (dir_only_p))
1513     {
1514       [panel setCanChooseDirectories: YES];
1515       [panel setCanChooseFiles: NO];
1516     }
1517   else if (! isSave)
1518     {
1519       /* This is not quite what the documentation says, but it is compatible
1520          with the Gtk+ code.  Also, the menu entry says "Open File...".  */
1521       [panel setCanChooseDirectories: NO];
1522       [panel setCanChooseFiles: YES];
1523     }
1525   block_input ();
1526   ns_fd_data.panel = panel;
1527   ns_fd_data.ret = NO;
1528 #ifdef NS_IMPL_COCOA
1529   if (! NILP (mustmatch) || ! NILP (dir_only_p))
1530     [panel setAllowedFileTypes: nil];
1531   if (dirS) [panel setDirectoryURL: [NSURL fileURLWithPath: dirS]];
1532   if (initS && NILP (Ffile_directory_p (init)))
1533     [panel setNameFieldStringValue: [initS lastPathComponent]];
1534   else
1535     [panel setNameFieldStringValue: @""];
1537 #else
1538   ns_fd_data.no_types = NILP (mustmatch) && NILP (dir_only_p);
1539   ns_fd_data.dirS = dirS;
1540   ns_fd_data.initS = initS;
1541 #endif
1543   /* runModalForDirectory/runModal restarts the main event loop when done,
1544      so we must start an event loop and then pop up the file dialog.
1545      The file dialog may pop up a confirm dialog after Ok has been pressed,
1546      so we can not simply pop down on the Ok/Cancel press.
1547    */
1548   nxev = [NSEvent otherEventWithType: NSEventTypeApplicationDefined
1549                             location: NSMakePoint (0, 0)
1550                        modifierFlags: 0
1551                            timestamp: 0
1552                         windowNumber: [[NSApp mainWindow] windowNumber]
1553                              context: [NSApp context]
1554                              subtype: 0
1555                                data1: 0
1556                                data2: NSAPP_DATA2_RUNFILEDIALOG];
1558   [NSApp postEvent: nxev atStart: NO];
1559   while (ns_fd_data.panel != nil)
1560     [NSApp run];
1562   if (ns_fd_data.ret == MODAL_OK_RESPONSE)
1563     {
1564       NSString *str = ns_filename_from_panel (panel);
1565       if (! str) str = ns_directory_from_panel (panel);
1566       if (str) fname = build_string ([str UTF8String]);
1567     }
1569   [[FRAME_NS_VIEW (SELECTED_FRAME ()) window] makeKeyWindow];
1570   unblock_input ();
1572   return fname;
1575 const char *
1576 ns_get_defaults_value (const char *key)
1578   NSObject *obj = [[NSUserDefaults standardUserDefaults]
1579                     objectForKey: [NSString stringWithUTF8String: key]];
1581   if (!obj) return NULL;
1583   return [[NSString stringWithFormat: @"%@", obj] UTF8String];
1587 DEFUN ("ns-get-resource", Fns_get_resource, Sns_get_resource, 2, 2, 0,
1588        doc: /* Return the value of the property NAME of OWNER from the defaults database.
1589 If OWNER is nil, Emacs is assumed.  */)
1590      (Lisp_Object owner, Lisp_Object name)
1592   const char *value;
1594   check_window_system (NULL);
1595   if (NILP (owner))
1596     owner = build_string([ns_app_name UTF8String]);
1597   CHECK_STRING (name);
1599   value = ns_get_defaults_value (SSDATA (name));
1601   if (value)
1602     return build_string (value);
1603   return Qnil;
1607 DEFUN ("ns-set-resource", Fns_set_resource, Sns_set_resource, 3, 3, 0,
1608        doc: /* Set property NAME of OWNER to VALUE, from the defaults database.
1609 If OWNER is nil, Emacs is assumed.
1610 If VALUE is nil, the default is removed.  */)
1611      (Lisp_Object owner, Lisp_Object name, Lisp_Object value)
1613   check_window_system (NULL);
1614   if (NILP (owner))
1615     owner = build_string ([ns_app_name UTF8String]);
1616   CHECK_STRING (name);
1617   if (NILP (value))
1618     {
1619       [[NSUserDefaults standardUserDefaults] removeObjectForKey:
1620                          [NSString stringWithUTF8String: SSDATA (name)]];
1621     }
1622   else
1623     {
1624       CHECK_STRING (value);
1625       [[NSUserDefaults standardUserDefaults] setObject:
1626                 [NSString stringWithUTF8String: SSDATA (value)]
1627                                         forKey: [NSString stringWithUTF8String:
1628                                                          SSDATA (name)]];
1629     }
1631   return Qnil;
1635 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
1636        Sx_server_max_request_size,
1637        0, 1, 0,
1638        doc: /* This function is a no-op.  It is only present for completeness.  */)
1639      (Lisp_Object terminal)
1641   check_ns_display_info (terminal);
1642   /* This function has no real equivalent under NeXTstep.  Return nil to
1643      indicate this. */
1644   return Qnil;
1648 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
1649        doc: /* Return the "vendor ID" string of Nextstep display server TERMINAL.
1650 \(Labeling every distributor as a "vendor" embodies the false assumption
1651 that operating systems cannot be developed and distributed noncommercially.)
1652 The optional argument TERMINAL specifies which display to ask about.
1653 TERMINAL should be a terminal object, a frame or a display name (a string).
1654 If omitted or nil, that stands for the selected frame's display.  */)
1655   (Lisp_Object terminal)
1657   check_ns_display_info (terminal);
1658 #ifdef NS_IMPL_GNUSTEP
1659   return build_string ("GNU");
1660 #else
1661   return build_string ("Apple");
1662 #endif
1666 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
1667        doc: /* Return the version numbers of the server of display TERMINAL.
1668 The value is a list of three integers: the major and minor
1669 version numbers of the X Protocol in use, and the distributor-specific release
1670 number.  See also the function `x-server-vendor'.
1672 The optional argument TERMINAL specifies which display to ask about.
1673 TERMINAL should be a terminal object, a frame or a display name (a string).
1674 If omitted or nil, that stands for the selected frame's display.  */)
1675   (Lisp_Object terminal)
1677   check_ns_display_info (terminal);
1678   /*NOTE: it is unclear what would best correspond with "protocol";
1679           we return 10.3, meaning Panther, since this is roughly the
1680           level that GNUstep's APIs correspond to.
1681           The last number is where we distinguish between the Apple
1682           and GNUstep implementations ("distributor-specific release
1683           number") and give int'ized versions of major.minor. */
1684   return list3i (10, 3, ns_appkit_version_int ());
1688 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
1689        doc: /* Return the number of screens on Nextstep display server TERMINAL.
1690 The optional argument TERMINAL specifies which display to ask about.
1691 TERMINAL should be a terminal object, a frame or a display name (a string).
1692 If omitted or nil, that stands for the selected frame's display.
1694 Note: "screen" here is not in Nextstep terminology but in X11's.  For
1695 the number of physical monitors, use `(length
1696 \(display-monitor-attributes-list TERMINAL))' instead.  */)
1697   (Lisp_Object terminal)
1699   check_ns_display_info (terminal);
1700   return make_number (1);
1704 DEFUN ("x-display-mm-height", Fx_display_mm_height, Sx_display_mm_height, 0, 1, 0,
1705        doc: /* Return the height in millimeters of the Nextstep display TERMINAL.
1706 The optional argument TERMINAL specifies which display to ask about.
1707 TERMINAL should be a terminal object, a frame or a display name (a string).
1708 If omitted or nil, that stands for the selected frame's display.
1710 On \"multi-monitor\" setups this refers to the height in millimeters for
1711 all physical monitors associated with TERMINAL.  To get information
1712 for each physical monitor, use `display-monitor-attributes-list'.  */)
1713   (Lisp_Object terminal)
1715   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
1717   return make_number (x_display_pixel_height (dpyinfo) / (92.0/25.4));
1721 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
1722        doc: /* Return the width in millimeters of the Nextstep display TERMINAL.
1723 The optional argument TERMINAL specifies which display to ask about.
1724 TERMINAL should be a terminal object, a frame or a display name (a string).
1725 If omitted or nil, that stands for the selected frame's display.
1727 On \"multi-monitor\" setups this refers to the width in millimeters for
1728 all physical monitors associated with TERMINAL.  To get information
1729 for each physical monitor, use `display-monitor-attributes-list'.  */)
1730   (Lisp_Object terminal)
1732   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
1734   return make_number (x_display_pixel_width (dpyinfo) / (92.0/25.4));
1738 DEFUN ("x-display-backing-store", Fx_display_backing_store,
1739        Sx_display_backing_store, 0, 1, 0,
1740        doc: /* Return an indication of whether the Nextstep display TERMINAL does backing store.
1741 The value may be `buffered', `retained', or `non-retained'.
1742 The optional argument TERMINAL specifies which display to ask about.
1743 TERMINAL should be a terminal object, a frame or a display name (a string).
1744 If omitted or nil, that stands for the selected frame's display.  */)
1745   (Lisp_Object terminal)
1747   check_ns_display_info (terminal);
1748   switch ([ns_get_window (terminal) backingType])
1749     {
1750     case NSBackingStoreBuffered:
1751       return intern ("buffered");
1752     case NSBackingStoreRetained:
1753       return intern ("retained");
1754     case NSBackingStoreNonretained:
1755       return intern ("non-retained");
1756     default:
1757       error ("Strange value for backingType parameter of frame");
1758     }
1759   return Qnil;  /* not reached, shut compiler up */
1763 DEFUN ("x-display-visual-class", Fx_display_visual_class,
1764        Sx_display_visual_class, 0, 1, 0,
1765        doc: /* Return the visual class of the Nextstep display TERMINAL.
1766 The value is one of the symbols `static-gray', `gray-scale',
1767 `static-color', `pseudo-color', `true-color', or `direct-color'.
1769 The optional argument TERMINAL specifies which display to ask about.
1770 TERMINAL should a terminal object, a frame or a display name (a string).
1771 If omitted or nil, that stands for the selected frame's display.  */)
1772   (Lisp_Object terminal)
1774   NSWindowDepth depth;
1776   check_ns_display_info (terminal);
1777   depth = [[[NSScreen screens] objectAtIndex:0] depth];
1779   if ( depth == NSBestDepth (NSCalibratedWhiteColorSpace, 2, 2, YES, NULL))
1780     return intern ("static-gray");
1781   else if (depth == NSBestDepth (NSCalibratedWhiteColorSpace, 8, 8, YES, NULL))
1782     return intern ("gray-scale");
1783   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 8, 8, YES, NULL))
1784     return intern ("pseudo-color");
1785   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 4, 12, NO, NULL))
1786     return intern ("true-color");
1787   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 8, 24, NO, NULL))
1788     return intern ("direct-color");
1789   else
1790     /* color mgmt as far as we do it is really handled by Nextstep itself anyway */
1791     return intern ("direct-color");
1795 DEFUN ("x-display-save-under", Fx_display_save_under,
1796        Sx_display_save_under, 0, 1, 0,
1797        doc: /* Return t if TERMINAL supports the save-under feature.
1798 The optional argument TERMINAL specifies which display to ask about.
1799 TERMINAL should be a terminal object, a frame or a display name (a string).
1800 If omitted or nil, that stands for the selected frame's display.  */)
1801   (Lisp_Object terminal)
1803   check_ns_display_info (terminal);
1804   switch ([ns_get_window (terminal) backingType])
1805     {
1806     case NSBackingStoreBuffered:
1807       return Qt;
1809     case NSBackingStoreRetained:
1810     case NSBackingStoreNonretained:
1811       return Qnil;
1813     default:
1814       error ("Strange value for backingType parameter of frame");
1815     }
1816   return Qnil;  /* not reached, shut compiler up */
1820 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
1821        1, 3, 0,
1822        doc: /* Open a connection to a display server.
1823 DISPLAY is the name of the display to connect to.
1824 Optional second arg XRM-STRING is a string of resources in xrdb format.
1825 If the optional third arg MUST-SUCCEED is non-nil,
1826 terminate Emacs if we can't open the connection.
1827 \(In the Nextstep version, the last two arguments are currently ignored.)  */)
1828      (Lisp_Object display, Lisp_Object resource_string, Lisp_Object must_succeed)
1830   struct ns_display_info *dpyinfo;
1832   CHECK_STRING (display);
1834   nxatoms_of_nsselect ();
1835   dpyinfo = ns_term_init (display);
1836   if (dpyinfo == 0)
1837     {
1838       if (!NILP (must_succeed))
1839         fatal ("Display on %s not responding.\n",
1840                SSDATA (display));
1841       else
1842         error ("Display on %s not responding.\n",
1843                SSDATA (display));
1844     }
1846   return Qnil;
1850 DEFUN ("x-close-connection", Fx_close_connection, Sx_close_connection,
1851        1, 1, 0,
1852        doc: /* Close the connection to TERMINAL's Nextstep display server.
1853 For TERMINAL, specify a terminal object, a frame or a display name (a
1854 string).  If TERMINAL is nil, that stands for the selected frame's
1855 terminal.  */)
1856      (Lisp_Object terminal)
1858   check_ns_display_info (terminal);
1859   [NSApp terminate: NSApp];
1860   return Qnil;
1864 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
1865        doc: /* Return the list of display names that Emacs has connections to.  */)
1866      (void)
1868   Lisp_Object result = Qnil;
1869   struct ns_display_info *ndi;
1871   for (ndi = x_display_list; ndi; ndi = ndi->next)
1872     result = Fcons (XCAR (ndi->name_list_element), result);
1874   return result;
1878 DEFUN ("ns-hide-others", Fns_hide_others, Sns_hide_others,
1879        0, 0, 0,
1880        doc: /* Hides all applications other than Emacs.  */)
1881      (void)
1883   check_window_system (NULL);
1884   [NSApp hideOtherApplications: NSApp];
1885   return Qnil;
1888 DEFUN ("ns-hide-emacs", Fns_hide_emacs, Sns_hide_emacs,
1889        1, 1, 0,
1890        doc: /* If ON is non-nil, the entire Emacs application is hidden.
1891 Otherwise if Emacs is hidden, it is unhidden.
1892 If ON is equal to `activate', Emacs is unhidden and becomes
1893 the active application.  */)
1894      (Lisp_Object on)
1896   check_window_system (NULL);
1897   if (EQ (on, intern ("activate")))
1898     {
1899       [NSApp unhide: NSApp];
1900       [NSApp activateIgnoringOtherApps: YES];
1901     }
1902   else if (NILP (on))
1903     [NSApp unhide: NSApp];
1904   else
1905     [NSApp hide: NSApp];
1906   return Qnil;
1910 DEFUN ("ns-emacs-info-panel", Fns_emacs_info_panel, Sns_emacs_info_panel,
1911        0, 0, 0,
1912        doc: /* Shows the 'Info' or 'About' panel for Emacs.  */)
1913      (void)
1915   check_window_system (NULL);
1916   [NSApp orderFrontStandardAboutPanel: nil];
1917   return Qnil;
1921 DEFUN ("ns-font-name", Fns_font_name, Sns_font_name, 1, 1, 0,
1922        doc: /* Determine font PostScript or family name for font NAME.
1923 NAME should be a string containing either the font name or an XLFD
1924 font descriptor.  If string contains `fontset' and not
1925 `fontset-startup', it is left alone. */)
1926      (Lisp_Object name)
1928   char *nm;
1929   CHECK_STRING (name);
1930   nm = SSDATA (name);
1932   if (nm[0] != '-')
1933     return name;
1934   if (strstr (nm, "fontset") && !strstr (nm, "fontset-startup"))
1935     return name;
1937   return build_string (ns_xlfd_to_fontname (SSDATA (name)));
1941 DEFUN ("ns-list-colors", Fns_list_colors, Sns_list_colors, 0, 1, 0,
1942        doc: /* Return a list of all available colors.
1943 The optional argument FRAME is currently ignored.  */)
1944      (Lisp_Object frame)
1946   Lisp_Object list = Qnil;
1947   NSEnumerator *colorlists;
1948   NSColorList *clist;
1950   if (!NILP (frame))
1951     {
1952       CHECK_FRAME (frame);
1953       if (! FRAME_NS_P (XFRAME (frame)))
1954         error ("non-Nextstep frame used in `ns-list-colors'");
1955     }
1957   block_input ();
1959   colorlists = [[NSColorList availableColorLists] objectEnumerator];
1960   while ((clist = [colorlists nextObject]))
1961     {
1962       if ([[clist name] length] < 7 ||
1963           [[clist name] rangeOfString: @"PANTONE"].location == 0)
1964         {
1965           NSEnumerator *cnames = [[clist allKeys] reverseObjectEnumerator];
1966           NSString *cname;
1967           while ((cname = [cnames nextObject]))
1968             list = Fcons (build_string ([cname UTF8String]), list);
1969 /*           for (i = [[clist allKeys] count] - 1; i >= 0; i--)
1970                list = Fcons (build_string ([[[clist allKeys] objectAtIndex: i]
1971                                              UTF8String]), list); */
1972         }
1973     }
1975   unblock_input ();
1977   return list;
1981 DEFUN ("ns-list-services", Fns_list_services, Sns_list_services, 0, 0, 0,
1982        doc: /* List available Nextstep services by querying NSApp.  */)
1983      (void)
1985 #ifdef NS_IMPL_COCOA
1986   /* You can't get services like this in 10.6+.  */
1987   return Qnil;
1988 #else
1989   Lisp_Object ret = Qnil;
1990   NSMenu *svcs;
1991 #ifdef NS_IMPL_COCOA
1992   id delegate;
1993 #endif
1995   check_window_system (NULL);
1996   svcs = [[NSMenu alloc] initWithTitle: @"Services"];
1997   [NSApp setServicesMenu: svcs];
1998   [NSApp registerServicesMenuSendTypes: ns_send_types
1999                            returnTypes: ns_return_types];
2001 /* On Tiger, services menu updating was made lazier (waits for user to
2002    actually click on the menu), so we have to force things along: */
2003 #ifdef NS_IMPL_COCOA
2004   delegate = [svcs delegate];
2005   if (delegate != nil)
2006     {
2007       if ([delegate respondsToSelector: @selector (menuNeedsUpdate:)])
2008         [delegate menuNeedsUpdate: svcs];
2009       if ([delegate respondsToSelector:
2010                        @selector (menu:updateItem:atIndex:shouldCancel:)])
2011         {
2012           int i, len = [delegate numberOfItemsInMenu: svcs];
2013           for (i =0; i<len; i++)
2014             [svcs addItemWithTitle: @"" action: NULL keyEquivalent: @""];
2015           for (i =0; i<len; i++)
2016             if (![delegate menu: svcs
2017                      updateItem: (NSMenuItem *)[svcs itemAtIndex: i]
2018                         atIndex: i shouldCancel: NO])
2019               break;
2020         }
2021     }
2022 #endif
2024   [svcs setAutoenablesItems: NO];
2025 #ifdef NS_IMPL_COCOA
2026   [svcs update]; /* on OS X, converts from '/' structure */
2027 #endif
2029   ret = interpret_services_menu (svcs, Qnil, ret);
2030   return ret;
2031 #endif
2035 DEFUN ("ns-perform-service", Fns_perform_service, Sns_perform_service,
2036        2, 2, 0,
2037        doc: /* Perform Nextstep SERVICE on SEND.
2038 SEND should be either a string or nil.
2039 The return value is the result of the service, as string, or nil if
2040 there was no result.  */)
2041      (Lisp_Object service, Lisp_Object send)
2043   id pb;
2044   NSString *svcName;
2045   char *utfStr;
2047   CHECK_STRING (service);
2048   check_window_system (NULL);
2050   utfStr = SSDATA (service);
2051   svcName = [NSString stringWithUTF8String: utfStr];
2053   pb =[NSPasteboard pasteboardWithUniqueName];
2054   ns_string_to_pasteboard (pb, send);
2056   if (NSPerformService (svcName, pb) == NO)
2057     Fsignal (Qquit, list1 (build_string ("service not available")));
2059   if ([[pb types] count] == 0)
2060     return build_string ("");
2061   return ns_string_from_pasteboard (pb);
2065 #ifdef NS_IMPL_COCOA
2067 /* Compile and execute the AppleScript SCRIPT and return the error
2068    status as function value.  A zero is returned if compilation and
2069    execution is successful, in which case *RESULT is set to a Lisp
2070    string or a number containing the resulting script value.  Otherwise,
2071    1 is returned. */
2072 static int
2073 ns_do_applescript (Lisp_Object script, Lisp_Object *result)
2075   NSAppleEventDescriptor *desc;
2076   NSDictionary* errorDict;
2077   NSAppleEventDescriptor* returnDescriptor = NULL;
2079   NSAppleScript* scriptObject =
2080     [[NSAppleScript alloc] initWithSource:
2081                              [NSString stringWithUTF8String: SSDATA (script)]];
2083   returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
2084   [scriptObject release];
2085   *result = Qnil;
2087   if (returnDescriptor != NULL)
2088     {
2089       // successful execution
2090       if (kAENullEvent != [returnDescriptor descriptorType])
2091         {
2092           *result = Qt;
2093           // script returned an AppleScript result
2094           if ((typeUnicodeText == [returnDescriptor descriptorType]) ||
2095 #if defined (NS_IMPL_COCOA)
2096               (typeUTF16ExternalRepresentation
2097                == [returnDescriptor descriptorType]) ||
2098 #endif
2099               (typeUTF8Text == [returnDescriptor descriptorType]) ||
2100               (typeCString == [returnDescriptor descriptorType]))
2101             {
2102               desc = [returnDescriptor coerceToDescriptorType: typeUTF8Text];
2103               if (desc)
2104                 *result = build_string([[desc stringValue] UTF8String]);
2105             }
2106           else
2107             {
2108               /* use typeUTF16ExternalRepresentation? */
2109               // coerce the result to the appropriate ObjC type
2110               desc = [returnDescriptor coerceToDescriptorType: typeUTF8Text];
2111               if (desc)
2112                 *result = make_number([desc int32Value]);
2113             }
2114         }
2115     }
2116   else
2117     {
2118       // no script result, return error
2119       return 1;
2120     }
2121   return 0;
2124 /* Helper function called from sendEvent to run applescript
2125    from within the main event loop.  */
2127 void
2128 ns_run_ascript (void)
2130   if (! NILP (as_script))
2131     as_status = ns_do_applescript (as_script, as_result);
2132   as_script = Qnil;
2135 DEFUN ("ns-do-applescript", Fns_do_applescript, Sns_do_applescript, 1, 1, 0,
2136        doc: /* Execute AppleScript SCRIPT and return the result.
2137 If compilation and execution are successful, the resulting script value
2138 is returned as a string, a number or, in the case of other constructs, t.
2139 In case the execution fails, an error is signaled. */)
2140      (Lisp_Object script)
2142   Lisp_Object result;
2143   int status;
2144   NSEvent *nxev;
2145   struct input_event ev;
2147   CHECK_STRING (script);
2148   check_window_system (NULL);
2150   block_input ();
2152   as_script = script;
2153   as_result = &result;
2155   /* executing apple script requires the event loop to run, otherwise
2156      errors aren't returned and executeAndReturnError hangs forever.
2157      Post an event that runs applescript and then start the event loop.
2158      The event loop is exited when the script is done.  */
2159   nxev = [NSEvent otherEventWithType: NSEventTypeApplicationDefined
2160                             location: NSMakePoint (0, 0)
2161                        modifierFlags: 0
2162                            timestamp: 0
2163                         windowNumber: [[NSApp mainWindow] windowNumber]
2164                              context: [NSApp context]
2165                              subtype: 0
2166                                data1: 0
2167                                data2: NSAPP_DATA2_RUNASSCRIPT];
2169   [NSApp postEvent: nxev atStart: NO];
2171   // If there are other events, the event loop may exit.  Keep running
2172   // until the script has been handled.  */
2173   ns_init_events (&ev);
2174   while (! NILP (as_script))
2175     [NSApp run];
2176   ns_finish_events ();
2178   status = as_status;
2179   as_status = 0;
2180   as_result = 0;
2181   unblock_input ();
2182   if (status == 0)
2183     return result;
2184   else if (!STRINGP (result))
2185     error ("AppleScript error %d", status);
2186   else
2187     error ("%s", SSDATA (result));
2189 #endif
2193 /* ==========================================================================
2195     Miscellaneous functions not called through hooks
2197    ========================================================================== */
2199 /* called from frame.c */
2200 struct ns_display_info *
2201 check_x_display_info (Lisp_Object frame)
2203   return check_ns_display_info (frame);
2207 void
2208 x_set_scroll_bar_default_width (struct frame *f)
2210   int wid = FRAME_COLUMN_WIDTH (f);
2211   FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = NS_SCROLL_BAR_WIDTH_DEFAULT;
2212   FRAME_CONFIG_SCROLL_BAR_COLS (f) = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) +
2213                                       wid - 1) / wid;
2216 void
2217 x_set_scroll_bar_default_height (struct frame *f)
2219   int height = FRAME_LINE_HEIGHT (f);
2220   FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) = NS_SCROLL_BAR_WIDTH_DEFAULT;
2221   FRAME_CONFIG_SCROLL_BAR_LINES (f) = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) +
2222                                        height - 1) / height;
2225 /* terms impl this instead of x-get-resource directly */
2226 char *
2227 x_get_string_resource (XrmDatabase rdb, const char *name, const char *class)
2229   /* remove appname prefix; TODO: allow for !="Emacs" */
2230   const char *res, *toCheck = class + (!strncmp (class, "Emacs.", 6) ? 6 : 0);
2232   check_window_system (NULL);
2234   if (inhibit_x_resources)
2235     /* --quick was passed, so this is a no-op.  */
2236     return NULL;
2238   res = ns_get_defaults_value (toCheck);
2239   return (char *) (!res ? NULL
2240                    : !c_strncasecmp (res, "YES", 3) ? "true"
2241                    : !c_strncasecmp (res, "NO", 2) ? "false"
2242                    : res);
2246 Lisp_Object
2247 x_get_focus_frame (struct frame *frame)
2249   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
2250   Lisp_Object nsfocus;
2252   if (!dpyinfo->x_focus_frame)
2253     return Qnil;
2255   XSETFRAME (nsfocus, dpyinfo->x_focus_frame);
2256   return nsfocus;
2259 /* ==========================================================================
2261     Lisp definitions that, for whatever reason, we can't alias as 'ns-XXX'.
2263    ========================================================================== */
2266 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
2267        doc: /* Internal function called by `color-defined-p', which see.
2268 \(Note that the Nextstep version of this function ignores FRAME.)  */)
2269      (Lisp_Object color, Lisp_Object frame)
2271   NSColor * col;
2272   check_window_system (NULL);
2273   return ns_lisp_to_color (color, &col) ? Qnil : Qt;
2277 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
2278        doc: /* Internal function called by `color-values', which see.  */)
2279      (Lisp_Object color, Lisp_Object frame)
2281   NSColor * col;
2282   EmacsCGFloat red, green, blue, alpha;
2284   check_window_system (NULL);
2285   CHECK_STRING (color);
2287   block_input ();
2288   if (ns_lisp_to_color (color, &col))
2289     {
2290       unblock_input ();
2291       return Qnil;
2292     }
2294   [[col colorUsingDefaultColorSpace]
2295         getRed: &red green: &green blue: &blue alpha: &alpha];
2296   unblock_input ();
2297   return list3i (lrint (red * 65280), lrint (green * 65280),
2298                  lrint (blue * 65280));
2302 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
2303        doc: /* Internal function called by `display-color-p', which see.  */)
2304      (Lisp_Object terminal)
2306   NSWindowDepth depth;
2307   NSString *colorSpace;
2309   check_ns_display_info (terminal);
2310   depth = [[[NSScreen screens] objectAtIndex:0] depth];
2311   colorSpace = NSColorSpaceFromDepth (depth);
2313   return    [colorSpace isEqualToString: NSDeviceWhiteColorSpace]
2314          || [colorSpace isEqualToString: NSCalibratedWhiteColorSpace]
2315       ? Qnil : Qt;
2319 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p, Sx_display_grayscale_p,
2320        0, 1, 0,
2321        doc: /* Return t if the Nextstep display supports shades of gray.
2322 Note that color displays do support shades of gray.
2323 The optional argument TERMINAL specifies which display to ask about.
2324 TERMINAL should be a terminal object, a frame or a display name (a string).
2325 If omitted or nil, that stands for the selected frame's display.  */)
2326   (Lisp_Object terminal)
2328   NSWindowDepth depth;
2330   check_ns_display_info (terminal);
2331   depth = [[[NSScreen screens] objectAtIndex:0] depth];
2333   return NSBitsPerPixelFromDepth (depth) > 1 ? Qt : Qnil;
2337 DEFUN ("x-display-pixel-width", Fx_display_pixel_width, Sx_display_pixel_width,
2338        0, 1, 0,
2339        doc: /* Return the width in pixels of the Nextstep display TERMINAL.
2340 The optional argument TERMINAL specifies which display to ask about.
2341 TERMINAL should be a terminal object, a frame or a display name (a string).
2342 If omitted or nil, that stands for the selected frame's display.
2344 On \"multi-monitor\" setups this refers to the pixel width for all
2345 physical monitors associated with TERMINAL.  To get information for
2346 each physical monitor, use `display-monitor-attributes-list'.  */)
2347   (Lisp_Object terminal)
2349   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
2351   return make_number (x_display_pixel_width (dpyinfo));
2355 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
2356        Sx_display_pixel_height, 0, 1, 0,
2357        doc: /* Return the height in pixels of the Nextstep display TERMINAL.
2358 The optional argument TERMINAL specifies which display to ask about.
2359 TERMINAL should be a terminal object, a frame or a display name (a string).
2360 If omitted or nil, that stands for the selected frame's display.
2362 On \"multi-monitor\" setups this refers to the pixel height for all
2363 physical monitors associated with TERMINAL.  To get information for
2364 each physical monitor, use `display-monitor-attributes-list'.  */)
2365   (Lisp_Object terminal)
2367   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
2369   return make_number (x_display_pixel_height (dpyinfo));
2372 #ifdef NS_IMPL_COCOA
2374 /* Returns the name for the screen that OBJ represents, or NULL.
2375    Caller must free return value.
2378 static char *
2379 ns_get_name_from_ioreg (io_object_t obj)
2381   char *name = NULL;
2383   NSDictionary *info = (NSDictionary *)
2384     IODisplayCreateInfoDictionary (obj, kIODisplayOnlyPreferredName);
2385   NSDictionary *names = [info objectForKey:
2386                                 [NSString stringWithUTF8String:
2387                                             kDisplayProductName]];
2389   if ([names count] > 0)
2390     {
2391       NSString *n = [names objectForKey: [[names allKeys]
2392                                                  objectAtIndex:0]];
2393       if (n != nil) name = xstrdup ([n UTF8String]);
2394     }
2396   [info release];
2398   return name;
2401 /* Returns the name for the screen that DID came from, or NULL.
2402    Caller must free return value.
2405 static char *
2406 ns_screen_name (CGDirectDisplayID did)
2408   char *name = NULL;
2410 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
2411   mach_port_t masterPort;
2412   io_iterator_t it;
2413   io_object_t obj;
2415   // CGDisplayIOServicePort is deprecated.  Do it another (harder) way.
2417   if (IOMasterPort (MACH_PORT_NULL, &masterPort) != kIOReturnSuccess
2418       || IOServiceGetMatchingServices (masterPort,
2419                                        IOServiceMatching ("IONDRVDevice"),
2420                                        &it) != kIOReturnSuccess)
2421     return name;
2423   /* Must loop until we find a name.  Many devices can have the same unit
2424      number (represents different GPU parts), but only one has a name.  */
2425   while (! name && (obj = IOIteratorNext (it)))
2426     {
2427       CFMutableDictionaryRef props;
2428       const void *val;
2430       if (IORegistryEntryCreateCFProperties (obj,
2431                                              &props,
2432                                              kCFAllocatorDefault,
2433                                              kNilOptions) == kIOReturnSuccess
2434           && props != nil
2435           && (val = CFDictionaryGetValue(props, @"IOFBDependentIndex")))
2436         {
2437           unsigned nr = [(NSNumber *)val unsignedIntegerValue];
2438           if (nr == CGDisplayUnitNumber (did))
2439             name = ns_get_name_from_ioreg (obj);
2440         }
2442       CFRelease (props);
2443       IOObjectRelease (obj);
2444     }
2446   IOObjectRelease (it);
2448 #else
2450   name = ns_get_name_from_ioreg (CGDisplayIOServicePort (did));
2452 #endif
2453   return name;
2455 #endif
2457 static Lisp_Object
2458 ns_make_monitor_attribute_list (struct MonitorInfo *monitors,
2459                                 int n_monitors,
2460                                 int primary_monitor,
2461                                 const char *source)
2463   Lisp_Object monitor_frames = Fmake_vector (make_number (n_monitors), Qnil);
2464   Lisp_Object frame, rest;
2465   NSArray *screens = [NSScreen screens];
2466   int i;
2468   FOR_EACH_FRAME (rest, frame)
2469     {
2470       struct frame *f = XFRAME (frame);
2472       if (FRAME_NS_P (f))
2473         {
2474           NSView *view = FRAME_NS_VIEW (f);
2475           NSScreen *screen = [[view window] screen];
2476           NSUInteger k;
2478           i = -1;
2479           for (k = 0; i == -1 && k < [screens count]; ++k)
2480             {
2481               if ([screens objectAtIndex: k] == screen)
2482                 i = (int)k;
2483             }
2485           if (i > -1)
2486             ASET (monitor_frames, i, Fcons (frame, AREF (monitor_frames, i)));
2487         }
2488     }
2490   return make_monitor_attribute_list (monitors, n_monitors, primary_monitor,
2491                                       monitor_frames, source);
2494 DEFUN ("ns-display-monitor-attributes-list",
2495        Fns_display_monitor_attributes_list,
2496        Sns_display_monitor_attributes_list,
2497        0, 1, 0,
2498        doc: /* Return a list of physical monitor attributes on the X display TERMINAL.
2500 The optional argument TERMINAL specifies which display to ask about.
2501 TERMINAL should be a terminal object, a frame or a display name (a string).
2502 If omitted or nil, that stands for the selected frame's display.
2504 In addition to the standard attribute keys listed in
2505 `display-monitor-attributes-list', the following keys are contained in
2506 the attributes:
2508  source -- String describing the source from which multi-monitor
2509            information is obtained, \"NS\" is always the source."
2511 Internal use only, use `display-monitor-attributes-list' instead.  */)
2512   (Lisp_Object terminal)
2514   struct terminal *term = decode_live_terminal (terminal);
2515   NSArray *screens;
2516   NSUInteger i, n_monitors;
2517   struct MonitorInfo *monitors;
2518   Lisp_Object attributes_list = Qnil;
2519   CGFloat primary_display_height = 0;
2521   if (term->type != output_ns)
2522     return Qnil;
2524   screens = [NSScreen screens];
2525   n_monitors = [screens count];
2526   if (n_monitors == 0)
2527     return Qnil;
2529   monitors = xzalloc (n_monitors * sizeof *monitors);
2531   for (i = 0; i < [screens count]; ++i)
2532     {
2533       NSScreen *s = [screens objectAtIndex:i];
2534       struct MonitorInfo *m = &monitors[i];
2535       NSRect fr = [s frame];
2536       NSRect vfr = [s visibleFrame];
2537       short y, vy;
2539 #ifdef NS_IMPL_COCOA
2540       NSDictionary *dict = [s deviceDescription];
2541       NSNumber *nid = [dict objectForKey:@"NSScreenNumber"];
2542       CGDirectDisplayID did = [nid unsignedIntValue];
2543 #endif
2544       if (i == 0)
2545         {
2546           primary_display_height = fr.size.height;
2547           y = (short) fr.origin.y;
2548           vy = (short) vfr.origin.y;
2549         }
2550       else
2551         {
2552           // Flip y coordinate as NS has y starting from the bottom.
2553           y = (short) (primary_display_height - fr.size.height - fr.origin.y);
2554           vy = (short) (primary_display_height -
2555                         vfr.size.height - vfr.origin.y);
2556         }
2558       m->geom.x = (short) fr.origin.x;
2559       m->geom.y = y;
2560       m->geom.width = (unsigned short) fr.size.width;
2561       m->geom.height = (unsigned short) fr.size.height;
2563       m->work.x = (short) vfr.origin.x;
2564       // y is flipped on NS, so vy - y are pixels missing at the bottom,
2565       // and fr.size.height - vfr.size.height are pixels missing in total.
2566       // Pixels missing at top are
2567       // fr.size.height - vfr.size.height - vy + y.
2568       // work.y is then pixels missing at top + y.
2569       m->work.y = (short) (fr.size.height - vfr.size.height) - vy + y + y;
2570       m->work.width = (unsigned short) vfr.size.width;
2571       m->work.height = (unsigned short) vfr.size.height;
2573 #ifdef NS_IMPL_COCOA
2574       m->name = ns_screen_name (did);
2576       {
2577         CGSize mms = CGDisplayScreenSize (did);
2578         m->mm_width = (int) mms.width;
2579         m->mm_height = (int) mms.height;
2580       }
2582 #else
2583       // Assume 92 dpi as x-display-mm-height/x-display-mm-width does.
2584       m->mm_width = (int) (25.4 * fr.size.width / 92.0);
2585       m->mm_height = (int) (25.4 * fr.size.height / 92.0);
2586 #endif
2587     }
2589   // Primary monitor is always first for NS.
2590   attributes_list = ns_make_monitor_attribute_list (monitors, n_monitors,
2591                                                     0, "NS");
2593   free_monitors (monitors, n_monitors);
2594   return attributes_list;
2598 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
2599        0, 1, 0,
2600        doc: /* Return the number of bitplanes of the Nextstep display TERMINAL.
2601 The optional argument TERMINAL specifies which display to ask about.
2602 TERMINAL should be a terminal object, a frame or a display name (a string).
2603 If omitted or nil, that stands for the selected frame's display.  */)
2604   (Lisp_Object terminal)
2606   check_ns_display_info (terminal);
2607   return make_number
2608     (NSBitsPerPixelFromDepth ([[[NSScreen screens] objectAtIndex:0] depth]));
2612 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
2613        0, 1, 0,
2614        doc: /* Returns the number of color cells of the Nextstep display TERMINAL.
2615 The optional argument TERMINAL specifies which display to ask about.
2616 TERMINAL should be a terminal object, a frame or a display name (a string).
2617 If omitted or nil, that stands for the selected frame's display.  */)
2618   (Lisp_Object terminal)
2620   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
2621   /* We force 24+ bit depths to 24-bit to prevent an overflow.  */
2622   return make_number (1 << min (dpyinfo->n_planes, 24));
2626 /* Unused dummy def needed for compatibility. */
2627 Lisp_Object tip_frame;
2629 /* TODO: move to xdisp or similar */
2630 static void
2631 compute_tip_xy (struct frame *f,
2632                 Lisp_Object parms,
2633                 Lisp_Object dx,
2634                 Lisp_Object dy,
2635                 int width,
2636                 int height,
2637                 int *root_x,
2638                 int *root_y)
2640   Lisp_Object left, top, right, bottom;
2641   EmacsView *view = FRAME_NS_VIEW (f);
2642   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2643   NSPoint pt;
2645   /* Start with user-specified or mouse position.  */
2646   left = Fcdr (Fassq (Qleft, parms));
2647   top = Fcdr (Fassq (Qtop, parms));
2648   right = Fcdr (Fassq (Qright, parms));
2649   bottom = Fcdr (Fassq (Qbottom, parms));
2651   if ((!INTEGERP (left) && !INTEGERP (right))
2652       || (!INTEGERP (top) && !INTEGERP (bottom)))
2653     {
2654       pt.x = dpyinfo->last_mouse_motion_x;
2655       pt.y = dpyinfo->last_mouse_motion_y;
2656       /* Convert to screen coordinates */
2657       pt = [view convertPoint: pt toView: nil];
2658 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
2659       pt = [[view window] convertBaseToScreen: pt];
2660 #else
2661       {
2662         NSRect r = NSMakeRect (pt.x, pt.y, 0, 0);
2663         r = [[view window] convertRectToScreen: r];
2664         pt.x = r.origin.x;
2665         pt.y = r.origin.y;
2666       }
2667 #endif
2668     }
2669   else
2670     {
2671       /* Absolute coordinates.  */
2672       pt.x = INTEGERP (left) ? XINT (left) : XINT (right);
2673       pt.y = (x_display_pixel_height (FRAME_DISPLAY_INFO (f))
2674               - (INTEGERP (top) ? XINT (top) : XINT (bottom))
2675               - height);
2676     }
2678   /* Ensure in bounds.  (Note, screen origin = lower left.) */
2679   if (INTEGERP (left) || INTEGERP (right))
2680     *root_x = pt.x;
2681   else if (pt.x + XINT (dx) <= 0)
2682     *root_x = 0; /* Can happen for negative dx */
2683   else if (pt.x + XINT (dx) + width
2684            <= x_display_pixel_width (FRAME_DISPLAY_INFO (f)))
2685     /* It fits to the right of the pointer.  */
2686     *root_x = pt.x + XINT (dx);
2687   else if (width + XINT (dx) <= pt.x)
2688     /* It fits to the left of the pointer.  */
2689     *root_x = pt.x - width - XINT (dx);
2690   else
2691     /* Put it left justified on the screen -- it ought to fit that way.  */
2692     *root_x = 0;
2694   if (INTEGERP (top) || INTEGERP (bottom))
2695     *root_y = pt.y;
2696   else if (pt.y - XINT (dy) - height >= 0)
2697     /* It fits below the pointer.  */
2698     *root_y = pt.y - height - XINT (dy);
2699   else if (pt.y + XINT (dy) + height
2700            <= x_display_pixel_height (FRAME_DISPLAY_INFO (f)))
2701     /* It fits above the pointer */
2702       *root_y = pt.y + XINT (dy);
2703   else
2704     /* Put it on the top.  */
2705     *root_y = x_display_pixel_height (FRAME_DISPLAY_INFO (f)) - height;
2709 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
2710        doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
2711 A tooltip window is a small window displaying a string.
2713 This is an internal function; Lisp code should call `tooltip-show'.
2715 FRAME nil or omitted means use the selected frame.
2717 PARMS is an optional list of frame parameters which can be used to
2718 change the tooltip's appearance.
2720 Automatically hide the tooltip after TIMEOUT seconds.  TIMEOUT nil
2721 means use the default timeout of 5 seconds.
2723 If the list of frame parameters PARMS contains a `left' parameter,
2724 display the tooltip at that x-position.  If the list of frame parameters
2725 PARMS contains no `left' but a `right' parameter, display the tooltip
2726 right-adjusted at that x-position. Otherwise display it at the
2727 x-position of the mouse, with offset DX added (default is 5 if DX isn't
2728 specified).
2730 Likewise for the y-position: If a `top' frame parameter is specified, it
2731 determines the position of the upper edge of the tooltip window.  If a
2732 `bottom' parameter but no `top' frame parameter is specified, it
2733 determines the position of the lower edge of the tooltip window.
2734 Otherwise display the tooltip window at the y-position of the mouse,
2735 with offset DY added (default is -10).
2737 A tooltip's maximum size is specified by `x-max-tooltip-size'.
2738 Text larger than the specified size is clipped.  */)
2739      (Lisp_Object string, Lisp_Object frame, Lisp_Object parms, Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
2741   int root_x, root_y;
2742   ptrdiff_t count = SPECPDL_INDEX ();
2743   struct frame *f;
2744   char *str;
2745   NSSize size;
2747   specbind (Qinhibit_redisplay, Qt);
2749   CHECK_STRING (string);
2750   str = SSDATA (string);
2751   f = decode_window_system_frame (frame);
2752   if (NILP (timeout))
2753     timeout = make_number (5);
2754   else
2755     CHECK_NATNUM (timeout);
2757   if (NILP (dx))
2758     dx = make_number (5);
2759   else
2760     CHECK_NUMBER (dx);
2762   if (NILP (dy))
2763     dy = make_number (-10);
2764   else
2765     CHECK_NUMBER (dy);
2767   block_input ();
2768   if (ns_tooltip == nil)
2769     ns_tooltip = [[EmacsTooltip alloc] init];
2770   else
2771     Fx_hide_tip ();
2773   [ns_tooltip setText: str];
2774   size = [ns_tooltip frame].size;
2776   /* Move the tooltip window where the mouse pointer is.  Resize and
2777      show it.  */
2778   compute_tip_xy (f, parms, dx, dy, (int)size.width, (int)size.height,
2779                   &root_x, &root_y);
2781   [ns_tooltip showAtX: root_x Y: root_y for: XINT (timeout)];
2782   unblock_input ();
2784   return unbind_to (count, Qnil);
2788 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
2789        doc: /* Hide the current tooltip window, if there is any.
2790 Value is t if tooltip was open, nil otherwise.  */)
2791      (void)
2793   if (ns_tooltip == nil || ![ns_tooltip isActive])
2794     return Qnil;
2795   [ns_tooltip hide];
2796   return Qt;
2799 /* Return geometric attributes of FRAME.  According to the value of
2800    ATTRIBUTES return the outer edges of FRAME (Qouter_edges), the inner
2801    edges of FRAME, the root window edges of frame (Qroot_edges).  Any
2802    other value means to return the geometry as returned by
2803    Fx_frame_geometry.  */
2804 static Lisp_Object
2805 frame_geometry (Lisp_Object frame, Lisp_Object attribute)
2807   struct frame *f = decode_live_frame (frame);
2808   Lisp_Object fullscreen_symbol = Fframe_parameter (frame, Qfullscreen);
2809   bool fullscreen = (EQ (fullscreen_symbol, Qfullboth)
2810                      || EQ (fullscreen_symbol, Qfullscreen));
2811   int border = fullscreen ? 0 : f->border_width;
2812   int title_height = fullscreen ? 0 : FRAME_NS_TITLEBAR_HEIGHT (f);
2813   int native_width = FRAME_PIXEL_WIDTH (f);
2814   int native_height = FRAME_PIXEL_HEIGHT (f);
2815   int outer_width = native_width + 2 * border;
2816   int outer_height = native_height + 2 * border + title_height;
2817   int native_left = f->left_pos + border;
2818   int native_top = f->top_pos + border + title_height;
2819   int native_right = f->left_pos + outer_width - border;
2820   int native_bottom = f->top_pos + outer_height - border;
2821   int internal_border_width = FRAME_INTERNAL_BORDER_WIDTH (f);
2822   int tool_bar_height = FRAME_TOOLBAR_HEIGHT (f);
2823   int tool_bar_width = (tool_bar_height
2824                         ? outer_width - 2 * internal_border_width
2825                         : 0);
2827   /* Construct list.  */
2828   if (EQ (attribute, Qouter_edges))
2829     return list4 (make_number (f->left_pos), make_number (f->top_pos),
2830                   make_number (f->left_pos + outer_width),
2831                   make_number (f->top_pos + outer_height));
2832   else if (EQ (attribute, Qnative_edges))
2833     return list4 (make_number (native_left), make_number (native_top),
2834                   make_number (native_right), make_number (native_bottom));
2835   else if (EQ (attribute, Qinner_edges))
2836     return list4 (make_number (native_left + internal_border_width),
2837                   make_number (native_top
2838                                + tool_bar_height
2839                                + internal_border_width),
2840                   make_number (native_right - internal_border_width),
2841                   make_number (native_bottom - internal_border_width));
2842   else
2843     return
2844       listn (CONSTYPE_HEAP, 10,
2845              Fcons (Qouter_position,
2846                     Fcons (make_number (f->left_pos),
2847                            make_number (f->top_pos))),
2848              Fcons (Qouter_size,
2849                     Fcons (make_number (outer_width),
2850                            make_number (outer_height))),
2851              Fcons (Qexternal_border_size,
2852                     (fullscreen
2853                      ? Fcons (make_number (0), make_number (0))
2854                      : Fcons (make_number (border), make_number (border)))),
2855              Fcons (Qtitle_bar_size,
2856                     Fcons (make_number (0), make_number (title_height))),
2857              Fcons (Qmenu_bar_external, Qnil),
2858              Fcons (Qmenu_bar_size, Fcons (make_number (0), make_number (0))),
2859              Fcons (Qtool_bar_external,
2860                     FRAME_EXTERNAL_TOOL_BAR (f) ? Qt : Qnil),
2861              Fcons (Qtool_bar_position, FRAME_TOOL_BAR_POSITION (f)),
2862              Fcons (Qtool_bar_size,
2863                     Fcons (make_number (tool_bar_width),
2864                            make_number (tool_bar_height))),
2865              Fcons (Qinternal_border_width,
2866                     make_number (internal_border_width)));
2869 DEFUN ("ns-frame-geometry", Fns_frame_geometry, Sns_frame_geometry, 0, 1, 0,
2870        doc: /* Return geometric attributes of FRAME.
2871 FRAME must be a live frame and defaults to the selected one.  The return
2872 value is an association list of the attributes listed below.  All height
2873 and width values are in pixels.
2875 `outer-position' is a cons of the outer left and top edges of FRAME
2876   relative to the origin - the position (0, 0) - of FRAME's display.
2878 `outer-size' is a cons of the outer width and height of FRAME.  The
2879   outer size includes the title bar and the external borders as well as
2880   any menu and/or tool bar of frame.
2882 `external-border-size' is a cons of the horizontal and vertical width of
2883   FRAME's external borders as supplied by the window manager.
2885 `title-bar-size' is a cons of the width and height of the title bar of
2886   FRAME as supplied by the window manager.  If both of them are zero,
2887   FRAME has no title bar.  If only the width is zero, Emacs was not
2888   able to retrieve the width information.
2890 `menu-bar-external', if non-nil, means the menu bar is external (never
2891   included in the inner edges of FRAME).
2893 `menu-bar-size' is a cons of the width and height of the menu bar of
2894   FRAME.
2896 `tool-bar-external', if non-nil, means the tool bar is external (never
2897   included in the inner edges of FRAME).
2899 `tool-bar-position' tells on which side the tool bar on FRAME is and can
2900   be one of `left', `top', `right' or `bottom'.  If this is nil, FRAME
2901   has no tool bar.
2903 `tool-bar-size' is a cons of the width and height of the tool bar of
2904   FRAME.
2906 `internal-border-width' is the width of the internal border of
2907   FRAME.  */)
2908   (Lisp_Object frame)
2910   return frame_geometry (frame, Qnil);
2913 DEFUN ("ns-frame-edges", Fns_frame_edges, Sns_frame_edges, 0, 2, 0,
2914        doc: /* Return edge coordinates of FRAME.
2915 FRAME must be a live frame and defaults to the selected one.  The return
2916 value is a list of the form (LEFT, TOP, RIGHT, BOTTOM).  All values are
2917 in pixels relative to the origin - the position (0, 0) - of FRAME's
2918 display.
2920 If optional argument TYPE is the symbol `outer-edges', return the outer
2921 edges of FRAME.  The outer edges comprise the decorations of the window
2922 manager (like the title bar or external borders) as well as any external
2923 menu or tool bar of FRAME.  If optional argument TYPE is the symbol
2924 `native-edges' or nil, return the native edges of FRAME.  The native
2925 edges exclude the decorations of the window manager and any external
2926 menu or tool bar of FRAME.  If TYPE is the symbol `inner-edges', return
2927 the inner edges of FRAME.  These edges exclude title bar, any borders,
2928 menu bar or tool bar of FRAME.  */)
2929   (Lisp_Object frame, Lisp_Object type)
2931   return frame_geometry (frame, ((EQ (type, Qouter_edges)
2932                                   || EQ (type, Qinner_edges))
2933                                  ? type
2934                                  : Qnative_edges));
2937 /* ==========================================================================
2939     Class implementations
2941    ========================================================================== */
2944   Handle arrow/function/control keys and copy/paste/cut in file dialogs.
2945   Return YES if handled, NO if not.
2946  */
2947 static BOOL
2948 handlePanelKeys (NSSavePanel *panel, NSEvent *theEvent)
2950   NSString *s;
2951   int i;
2952   BOOL ret = NO;
2954   if ([theEvent type] != NSEventTypeKeyDown) return NO;
2955   s = [theEvent characters];
2957   for (i = 0; i < [s length]; ++i)
2958     {
2959       int ch = (int) [s characterAtIndex: i];
2960       switch (ch)
2961         {
2962         case NSHomeFunctionKey:
2963         case NSDownArrowFunctionKey:
2964         case NSUpArrowFunctionKey:
2965         case NSLeftArrowFunctionKey:
2966         case NSRightArrowFunctionKey:
2967         case NSPageUpFunctionKey:
2968         case NSPageDownFunctionKey:
2969         case NSEndFunctionKey:
2970           /* Don't send command modified keys, as those are handled in the
2971              performKeyEquivalent method of the super class.
2972           */
2973           if (! ([theEvent modifierFlags] & NSEventModifierFlagCommand))
2974             {
2975               [panel sendEvent: theEvent];
2976               ret = YES;
2977             }
2978           break;
2979           /* As we don't have the standard key commands for
2980              copy/paste/cut/select-all in our edit menu, we must handle
2981              them here.  TODO: handle Emacs key bindings for copy/cut/select-all
2982              here, paste works, because we have that in our Edit menu.
2983              I.e. refactor out code in nsterm.m, keyDown: to figure out the
2984              correct modifier.
2985           */
2986         case 'x': // Cut
2987         case 'c': // Copy
2988         case 'v': // Paste
2989         case 'a': // Select all
2990           if ([theEvent modifierFlags] & NSEventModifierFlagCommand)
2991             {
2992               [NSApp sendAction:
2993                        (ch == 'x'
2994                         ? @selector(cut:)
2995                         : (ch == 'c'
2996                            ? @selector(copy:)
2997                            : (ch == 'v'
2998                               ? @selector(paste:)
2999                               : @selector(selectAll:))))
3000                              to:nil from:panel];
3001               ret = YES;
3002             }
3003         default:
3004           // Send all control keys, as the text field supports C-a, C-f, C-e
3005           // C-b and more.
3006           if ([theEvent modifierFlags] & NSEventModifierFlagControl)
3007             {
3008               [panel sendEvent: theEvent];
3009               ret = YES;
3010             }
3011           break;
3012         }
3013     }
3016   return ret;
3019 @implementation EmacsSavePanel
3020 - (BOOL)performKeyEquivalent:(NSEvent *)theEvent
3022   BOOL ret = handlePanelKeys (self, theEvent);
3023   if (! ret)
3024     ret = [super performKeyEquivalent:theEvent];
3025   return ret;
3027 @end
3030 @implementation EmacsOpenPanel
3031 - (BOOL)performKeyEquivalent:(NSEvent *)theEvent
3033   // NSOpenPanel inherits NSSavePanel, so passing self is OK.
3034   BOOL ret = handlePanelKeys (self, theEvent);
3035   if (! ret)
3036     ret = [super performKeyEquivalent:theEvent];
3037   return ret;
3039 @end
3042 @implementation EmacsFileDelegate
3043 /* --------------------------------------------------------------------------
3044    Delegate methods for Open/Save panels
3045    -------------------------------------------------------------------------- */
3046 - (BOOL)panel: (id)sender isValidFilename: (NSString *)filename
3048   return YES;
3050 - (BOOL)panel: (id)sender shouldShowFilename: (NSString *)filename
3052   return YES;
3054 - (NSString *)panel: (id)sender userEnteredFilename: (NSString *)filename
3055           confirmed: (BOOL)okFlag
3057   return filename;
3059 @end
3061 #endif
3064 /* ==========================================================================
3066     Lisp interface declaration
3068    ========================================================================== */
3071 void
3072 syms_of_nsfns (void)
3074   DEFSYM (Qfontsize, "fontsize");
3075   DEFSYM (Qframe_title_format, "frame-title-format");
3076   DEFSYM (Qicon_title_format, "icon-title-format");
3078   DEFVAR_LISP ("ns-icon-type-alist", Vns_icon_type_alist,
3079                doc: /* Alist of elements (REGEXP . IMAGE) for images of icons associated to frames.
3080 If the title of a frame matches REGEXP, then IMAGE.tiff is
3081 selected as the image of the icon representing the frame when it's
3082 miniaturized.  If an element is t, then Emacs tries to select an icon
3083 based on the filetype of the visited file.
3085 The images have to be installed in a folder called English.lproj in the
3086 Emacs folder.  You have to restart Emacs after installing new icons.
3088 Example: Install an icon Gnus.tiff and execute the following code
3090   (setq ns-icon-type-alist
3091         (append ns-icon-type-alist
3092                 \\='((\"^\\\\*\\\\(Group\\\\*$\\\\|Summary \\\\|Article\\\\*$\\\\)\"
3093                    . \"Gnus\"))))
3095 When you miniaturize a Group, Summary or Article frame, Gnus.tiff will
3096 be used as the image of the icon representing the frame.  */);
3097   Vns_icon_type_alist = list1 (Qt);
3099   DEFVAR_LISP ("ns-version-string", Vns_version_string,
3100                doc: /* Toolkit version for NS Windowing.  */);
3101   Vns_version_string = ns_appkit_version_str ();
3103   defsubr (&Sns_read_file_name);
3104   defsubr (&Sns_get_resource);
3105   defsubr (&Sns_set_resource);
3106   defsubr (&Sxw_display_color_p); /* this and next called directly by C code */
3107   defsubr (&Sx_display_grayscale_p);
3108   defsubr (&Sns_font_name);
3109   defsubr (&Sns_list_colors);
3110 #ifdef NS_IMPL_COCOA
3111   defsubr (&Sns_do_applescript);
3112 #endif
3113   defsubr (&Sxw_color_defined_p);
3114   defsubr (&Sxw_color_values);
3115   defsubr (&Sx_server_max_request_size);
3116   defsubr (&Sx_server_vendor);
3117   defsubr (&Sx_server_version);
3118   defsubr (&Sx_display_pixel_width);
3119   defsubr (&Sx_display_pixel_height);
3120   defsubr (&Sns_display_monitor_attributes_list);
3121   defsubr (&Sns_frame_geometry);
3122   defsubr (&Sns_frame_edges);
3123   defsubr (&Sx_display_mm_width);
3124   defsubr (&Sx_display_mm_height);
3125   defsubr (&Sx_display_screens);
3126   defsubr (&Sx_display_planes);
3127   defsubr (&Sx_display_color_cells);
3128   defsubr (&Sx_display_visual_class);
3129   defsubr (&Sx_display_backing_store);
3130   defsubr (&Sx_display_save_under);
3131   defsubr (&Sx_create_frame);
3132   defsubr (&Sx_open_connection);
3133   defsubr (&Sx_close_connection);
3134   defsubr (&Sx_display_list);
3136   defsubr (&Sns_hide_others);
3137   defsubr (&Sns_hide_emacs);
3138   defsubr (&Sns_emacs_info_panel);
3139   defsubr (&Sns_list_services);
3140   defsubr (&Sns_perform_service);
3141   defsubr (&Sns_popup_font_panel);
3142   defsubr (&Sns_popup_color_panel);
3144   defsubr (&Sx_show_tip);
3145   defsubr (&Sx_hide_tip);
3147   as_status = 0;
3148   as_script = Qnil;
3149   as_result = 0;