Fix bug #18588 by making bug-reference-bug-regexp more lenient
[emacs.git] / src / nsfns.m
blobedc02e8350b20971733c3d224f6a299fae042a6b
1 /* Functions for the NeXT/Open/GNUstep and MacOSX window system.
3 Copyright (C) 1989, 1992-1994, 2005-2006, 2008-2015 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
11 (at 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 extern NSArray *ns_send_types, *ns_return_types, *ns_drag_types;
57 EmacsTooltip *ns_tooltip = nil;
59 /* Need forward declaration here to preserve organizational integrity of file */
60 Lisp_Object Fx_open_connection (Lisp_Object, Lisp_Object, Lisp_Object);
62 /* Static variables to handle applescript execution.  */
63 static Lisp_Object as_script, *as_result;
64 static int as_status;
66 static ptrdiff_t image_cache_refcount;
69 /* ==========================================================================
71     Internal utility functions
73    ========================================================================== */
75 /* Let the user specify a Nextstep display with a Lisp object.
76    OBJECT may be nil, a frame or a terminal object.
77    nil stands for the selected frame--or, if that is not a Nextstep frame,
78    the first Nextstep display on the list.  */
80 static struct ns_display_info *
81 check_ns_display_info (Lisp_Object object)
83   struct ns_display_info *dpyinfo = NULL;
85   if (NILP (object))
86     {
87       struct frame *sf = XFRAME (selected_frame);
89       if (FRAME_NS_P (sf) && FRAME_LIVE_P (sf))
90         dpyinfo = FRAME_DISPLAY_INFO (sf);
91       else if (x_display_list != 0)
92         dpyinfo = x_display_list;
93       else
94         error ("Nextstep windows are not in use or not initialized");
95     }
96   else if (TERMINALP (object))
97     {
98       struct terminal *t = decode_live_terminal (object);
100       if (t->type != output_ns)
101         error ("Terminal %d is not a Nextstep display", t->id);
103       dpyinfo = t->display_info.ns;
104     }
105   else if (STRINGP (object))
106     dpyinfo = ns_display_info_for_name (object);
107   else
108     {
109       struct frame *f = decode_window_system_frame (object);
110       dpyinfo = FRAME_DISPLAY_INFO (f);
111     }
113   return dpyinfo;
117 static id
118 ns_get_window (Lisp_Object maybeFrame)
120   id view =nil, window =nil;
122   if (!FRAMEP (maybeFrame) || !FRAME_NS_P (XFRAME (maybeFrame)))
123     maybeFrame = selected_frame;/*wrong_type_argument (Qframep, maybeFrame); */
125   if (!NILP (maybeFrame))
126     view = FRAME_NS_VIEW (XFRAME (maybeFrame));
127   if (view) window =[view window];
129   return window;
133 /* Return the X display structure for the display named NAME.
134    Open a new connection if necessary.  */
135 struct ns_display_info *
136 ns_display_info_for_name (Lisp_Object name)
138   struct ns_display_info *dpyinfo;
140   CHECK_STRING (name);
142   for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
143     if (!NILP (Fstring_equal (XCAR (dpyinfo->name_list_element), name)))
144       return dpyinfo;
146   error ("Emacs for Nextstep does not yet support multi-display");
148   Fx_open_connection (name, Qnil, Qnil);
149   dpyinfo = x_display_list;
151   if (dpyinfo == 0)
152     error ("Display on %s not responding.\n", SDATA (name));
154   return dpyinfo;
157 static NSString *
158 ns_filename_from_panel (NSSavePanel *panel)
160 #ifdef NS_IMPL_COCOA
161   NSURL *url = [panel URL];
162   NSString *str = [url path];
163   return str;
164 #else
165   return [panel filename];
166 #endif
169 static NSString *
170 ns_directory_from_panel (NSSavePanel *panel)
172 #ifdef NS_IMPL_COCOA
173   NSURL *url = [panel directoryURL];
174   NSString *str = [url path];
175   return str;
176 #else
177   return [panel directory];
178 #endif
181 static Lisp_Object
182 interpret_services_menu (NSMenu *menu, Lisp_Object prefix, Lisp_Object old)
183 /* --------------------------------------------------------------------------
184    Turn the input menu (an NSMenu) into a lisp list for tracking on lisp side
185    -------------------------------------------------------------------------- */
187   int i, count;
188   NSMenuItem *item;
189   const char *name;
190   Lisp_Object nameStr;
191   unsigned short key;
192   NSString *keys;
193   Lisp_Object res;
195   count = [menu numberOfItems];
196   for (i = 0; i<count; i++)
197     {
198       item = [menu itemAtIndex: i];
199       name = [[item title] UTF8String];
200       if (!name) continue;
202       nameStr = build_string (name);
204       if ([item hasSubmenu])
205         {
206           old = interpret_services_menu ([item submenu],
207                                         Fcons (nameStr, prefix), old);
208         }
209       else
210         {
211           keys = [item keyEquivalent];
212           if (keys && [keys length] )
213             {
214               key = [keys characterAtIndex: 0];
215               res = make_number (key|super_modifier);
216             }
217           else
218             {
219               res = Qundefined;
220             }
221           old = Fcons (Fcons (res,
222                             Freverse (Fcons (nameStr,
223                                            prefix))),
224                     old);
225         }
226     }
227   return old;
232 /* ==========================================================================
234     Frame parameter setters
236    ========================================================================== */
239 static void
240 x_set_foreground_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
242   NSColor *col;
243   EmacsCGFloat r, g, b, alpha;
245   /* Must block_input, because ns_lisp_to_color does block/unblock_input
246      which means that col may be deallocated in its unblock_input if there
247      is user input, unless we also block_input.  */
248   block_input ();
249   if (ns_lisp_to_color (arg, &col))
250     {
251       store_frame_param (f, Qforeground_color, oldval);
252       unblock_input ();
253       error ("Unknown color");
254     }
256   [col retain];
257   [f->output_data.ns->foreground_color release];
258   f->output_data.ns->foreground_color = col;
260   [col getRed: &r green: &g blue: &b alpha: &alpha];
261   FRAME_FOREGROUND_PIXEL (f) =
262     ARGB_TO_ULONG ((int)(alpha*0xff), (int)(r*0xff), (int)(g*0xff), (int)(b*0xff));
264   if (FRAME_NS_VIEW (f))
265     {
266       update_face_from_frame_parameter (f, Qforeground_color, arg);
267       /*recompute_basic_faces (f); */
268       if (FRAME_VISIBLE_P (f))
269         SET_FRAME_GARBAGED (f);
270     }
271   unblock_input ();
275 static void
276 x_set_background_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
278   struct face *face;
279   NSColor *col;
280   NSView *view = FRAME_NS_VIEW (f);
281   EmacsCGFloat r, g, b, alpha;
283   block_input ();
284   if (ns_lisp_to_color (arg, &col))
285     {
286       store_frame_param (f, Qbackground_color, oldval);
287       unblock_input ();
288       error ("Unknown color");
289     }
291   /* clear the frame; in some instances the NS-internal GC appears not to
292      update, or it does update and cannot clear old text properly */
293   if (FRAME_VISIBLE_P (f))
294     ns_clear_frame (f);
296   [col retain];
297   [f->output_data.ns->background_color release];
298   f->output_data.ns->background_color = col;
300   [col getRed: &r green: &g blue: &b alpha: &alpha];
301   FRAME_BACKGROUND_PIXEL (f) =
302     ARGB_TO_ULONG ((int)(alpha*0xff), (int)(r*0xff), (int)(g*0xff), (int)(b*0xff));
304   if (view != nil)
305     {
306       [[view window] setBackgroundColor: col];
308       if (alpha != (EmacsCGFloat) 1.0)
309           [[view window] setOpaque: NO];
310       else
311           [[view window] setOpaque: YES];
313       face = FRAME_DEFAULT_FACE (f);
314       if (face)
315         {
316           col = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f);
317           face->background = ns_index_color
318             ([col colorWithAlphaComponent: alpha], f);
320           update_face_from_frame_parameter (f, Qbackground_color, arg);
321         }
323       if (FRAME_VISIBLE_P (f))
324         SET_FRAME_GARBAGED (f);
325     }
326   unblock_input ();
330 static void
331 x_set_cursor_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
333   NSColor *col;
335   block_input ();
336   if (ns_lisp_to_color (arg, &col))
337     {
338       store_frame_param (f, Qcursor_color, oldval);
339       unblock_input ();
340       error ("Unknown color");
341     }
343   [FRAME_CURSOR_COLOR (f) release];
344   FRAME_CURSOR_COLOR (f) = [col retain];
346   if (FRAME_VISIBLE_P (f))
347     {
348       x_update_cursor (f, 0);
349       x_update_cursor (f, 1);
350     }
351   update_face_from_frame_parameter (f, Qcursor_color, arg);
352   unblock_input ();
356 static void
357 x_set_icon_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
359   NSView *view = FRAME_NS_VIEW (f);
360   NSTRACE ("x_set_icon_name");
362   /* see if it's changed */
363   if (STRINGP (arg))
364     {
365       if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
366         return;
367     }
368   else if (!STRINGP (oldval) && EQ (oldval, Qnil) == EQ (arg, Qnil))
369     return;
371   fset_icon_name (f, arg);
373   if (NILP (arg))
374     {
375       if (!NILP (f->title))
376         arg = f->title;
377       else
378         /* Explicit name and no icon-name -> explicit_name.  */
379         if (f->explicit_name)
380           arg = f->name;
381         else
382           {
383             /* No explicit name and no icon-name ->
384                name has to be rebuild from icon_title_format.  */
385             windows_or_buffers_changed = 62;
386             return;
387           }
388     }
390   /* Don't change the name if it's already NAME.  */
391   if ([[view window] miniwindowTitle]
392       && ([[[view window] miniwindowTitle]
393              isEqualToString: [NSString stringWithUTF8String:
394                                           SSDATA (arg)]]))
395     return;
397   [[view window] setMiniwindowTitle:
398         [NSString stringWithUTF8String: SSDATA (arg)]];
401 static void
402 ns_set_name_internal (struct frame *f, Lisp_Object name)
404   Lisp_Object encoded_name, encoded_icon_name;
405   NSString *str;
406   NSView *view = FRAME_NS_VIEW (f);
409   encoded_name = ENCODE_UTF_8 (name);
411   str = [NSString stringWithUTF8String: SSDATA (encoded_name)];
414   /* Don't change the name if it's already NAME.  */
415   if (! [[[view window] title] isEqualToString: str])
416     [[view window] setTitle: str];
418   if (!STRINGP (f->icon_name))
419     encoded_icon_name = encoded_name;
420   else
421     encoded_icon_name = ENCODE_UTF_8 (f->icon_name);
423   str = [NSString stringWithUTF8String: SSDATA (encoded_icon_name)];
425   if ([[view window] miniwindowTitle]
426       && ! [[[view window] miniwindowTitle] isEqualToString: str])
427     [[view window] setMiniwindowTitle: str];
431 static void
432 ns_set_name (struct frame *f, Lisp_Object name, int explicit)
434   NSTRACE ("ns_set_name");
436   /* Make sure that requests from lisp code override requests from
437      Emacs redisplay code.  */
438   if (explicit)
439     {
440       /* If we're switching from explicit to implicit, we had better
441          update the mode lines and thereby update the title.  */
442       if (f->explicit_name && NILP (name))
443         update_mode_lines = 21;
445       f->explicit_name = ! NILP (name);
446     }
447   else if (f->explicit_name)
448     return;
450   if (NILP (name))
451     name = build_string ([ns_app_name UTF8String]);
452   else
453     CHECK_STRING (name);
455   /* Don't change the name if it's already NAME.  */
456   if (! NILP (Fstring_equal (name, f->name)))
457     return;
459   fset_name (f, name);
461   /* Title overrides explicit name.  */
462   if (! NILP (f->title))
463     name = f->title;
465   ns_set_name_internal (f, name);
469 /* This function should be called when the user's lisp code has
470    specified a name for the frame; the name will override any set by the
471    redisplay code.  */
472 static void
473 x_explicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
475   NSTRACE ("x_explicitly_set_name");
476   ns_set_name (f, arg, 1);
480 /* This function should be called by Emacs redisplay code to set the
481    name; names set this way will never override names set by the user's
482    lisp code.  */
483 void
484 x_implicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
486   NSTRACE ("x_implicitly_set_name");
488   Lisp_Object frame_title = buffer_local_value
489     (Qframe_title_format, XWINDOW (f->selected_window)->contents);
490   Lisp_Object icon_title = buffer_local_value
491     (Qicon_title_format, XWINDOW (f->selected_window)->contents);
493   /* Deal with NS specific format t.  */
494   if (FRAME_NS_P (f) && ((FRAME_ICONIFIED_P (f) && EQ (icon_title, Qt))
495                          || EQ (frame_title, Qt)))
496     ns_set_name_as_filename (f);
497   else
498     ns_set_name (f, arg, 0);
502 /* Change the title of frame F to NAME.
503    If NAME is nil, use the frame name as the title.  */
505 static void
506 x_set_title (struct frame *f, Lisp_Object name, Lisp_Object old_name)
508   NSTRACE ("x_set_title");
509   /* Don't change the title if it's already NAME.  */
510   if (EQ (name, f->title))
511     return;
513   update_mode_lines = 22;
515   fset_title (f, name);
517   if (NILP (name))
518     name = f->name;
519   else
520     CHECK_STRING (name);
522   ns_set_name_internal (f, name);
526 void
527 ns_set_name_as_filename (struct frame *f)
529   NSView *view;
530   Lisp_Object name, filename;
531   Lisp_Object buf = XWINDOW (f->selected_window)->contents;
532   const char *title;
533   NSAutoreleasePool *pool;
534   Lisp_Object encoded_name, encoded_filename;
535   NSString *str;
536   NSTRACE ("ns_set_name_as_filename");
538   if (f->explicit_name || ! NILP (f->title))
539     return;
541   block_input ();
542   pool = [[NSAutoreleasePool alloc] init];
543   filename = BVAR (XBUFFER (buf), filename);
544   name = BVAR (XBUFFER (buf), name);
546   if (NILP (name))
547     {
548       if (! NILP (filename))
549         name = Ffile_name_nondirectory (filename);
550       else
551         name = build_string ([ns_app_name UTF8String]);
552     }
554   encoded_name = ENCODE_UTF_8 (name);
556   view = FRAME_NS_VIEW (f);
558   title = FRAME_ICONIFIED_P (f) ? [[[view window] miniwindowTitle] UTF8String]
559                                 : [[[view window] title] UTF8String];
561   if (title && (! strcmp (title, SSDATA (encoded_name))))
562     {
563       [pool release];
564       unblock_input ();
565       return;
566     }
568   str = [NSString stringWithUTF8String: SSDATA (encoded_name)];
569   if (str == nil) str = @"Bad coding";
571   if (FRAME_ICONIFIED_P (f))
572     [[view window] setMiniwindowTitle: str];
573   else
574     {
575       NSString *fstr;
577       if (! NILP (filename))
578         {
579           encoded_filename = ENCODE_UTF_8 (filename);
581           fstr = [NSString stringWithUTF8String: SSDATA (encoded_filename)];
582           if (fstr == nil) fstr = @"";
583         }
584       else
585         fstr = @"";
587       ns_set_represented_filename (fstr, f);
588       [[view window] setTitle: str];
589       fset_name (f, name);
590     }
592   [pool release];
593   unblock_input ();
597 void
598 ns_set_doc_edited (void)
600   NSAutoreleasePool *pool;
601   Lisp_Object tail, frame;
602   block_input ();
603   pool = [[NSAutoreleasePool alloc] init];
604   FOR_EACH_FRAME (tail, frame)
605     {
606       BOOL edited = NO;
607       struct frame *f = XFRAME (frame);
608       struct window *w;
609       NSView *view;
611       if (! FRAME_NS_P (f)) continue;
612       w = XWINDOW (FRAME_SELECTED_WINDOW (f));
613       view = FRAME_NS_VIEW (f);
614       if (!MINI_WINDOW_P (w))
615         edited = ! NILP (Fbuffer_modified_p (w->contents)) &&
616           ! NILP (Fbuffer_file_name (w->contents));
617       [[view window] setDocumentEdited: edited];
618     }
620   [pool release];
621   unblock_input ();
625 void
626 x_set_menu_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
628   int nlines;
629   if (FRAME_MINIBUF_ONLY_P (f))
630     return;
632   if (TYPE_RANGED_INTEGERP (int, value))
633     nlines = XINT (value);
634   else
635     nlines = 0;
637   FRAME_MENU_BAR_LINES (f) = 0;
638   if (nlines)
639     {
640       FRAME_EXTERNAL_MENU_BAR (f) = 1;
641       /* does for all frames, whereas we just want for one frame
642          [NSMenu setMenuBarVisible: YES]; */
643     }
644   else
645     {
646       if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
647         free_frame_menubar (f);
648       /*      [NSMenu setMenuBarVisible: NO]; */
649       FRAME_EXTERNAL_MENU_BAR (f) = 0;
650     }
654 /* toolbar support */
655 void
656 x_set_tool_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
658   /* Currently, when the tool bar change state, the frame is resized.
660      TODO: It would be better if this didn't occur when 1) the frame
661      is full height or maximized or 2) when specified by
662      `frame-inhibit-implied-resize'. */
663   int nlines;
665   NSTRACE ("x_set_tool_bar_lines");
667   if (FRAME_MINIBUF_ONLY_P (f))
668     return;
670   if (RANGED_INTEGERP (0, value, INT_MAX))
671     nlines = XFASTINT (value);
672   else
673     nlines = 0;
675   if (nlines)
676     {
677       FRAME_EXTERNAL_TOOL_BAR (f) = 1;
678       update_frame_tool_bar (f);
679     }
680   else
681     {
682       if (FRAME_EXTERNAL_TOOL_BAR (f))
683         {
684           free_frame_tool_bar (f);
685           FRAME_EXTERNAL_TOOL_BAR (f) = 0;
687           {
688             EmacsView *view = FRAME_NS_VIEW (f);
689             int fs_state = [view fullscreenState];
691             if (fs_state == FULLSCREEN_MAXIMIZED)
692               {
693                 [view setFSValue:FULLSCREEN_WIDTH];
694               }
695             else if (fs_state == FULLSCREEN_HEIGHT)
696               {
697                 [view setFSValue:FULLSCREEN_NONE];
698               }
699           }
700        }
701     }
703   {
704     int inhibit
705       = ((f->after_make_frame
706           && !f->tool_bar_resized
707           && (EQ (frame_inhibit_implied_resize, Qt)
708               || (CONSP (frame_inhibit_implied_resize)
709                   && !NILP (Fmemq (Qtool_bar_lines,
710                                    frame_inhibit_implied_resize))))
711           && NILP (get_frame_param (f, Qfullscreen)))
712          ? 0
713          : 2);
715     NSTRACE_MSG ("inhibit:%d", inhibit);
717     frame_size_history_add (f, Qupdate_frame_tool_bar, 0, 0, Qnil);
718     adjust_frame_size (f, -1, -1, inhibit, 0, Qtool_bar_lines);
719   }
723 void
724 x_set_internal_border_width (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
726   int old_width = FRAME_INTERNAL_BORDER_WIDTH (f);
728   CHECK_TYPE_RANGED_INTEGER (int, arg);
729   FRAME_INTERNAL_BORDER_WIDTH (f) = XINT (arg);
730   if (FRAME_INTERNAL_BORDER_WIDTH (f) < 0)
731     FRAME_INTERNAL_BORDER_WIDTH (f) = 0;
733   if (FRAME_INTERNAL_BORDER_WIDTH (f) == old_width)
734     return;
736   if (FRAME_X_WINDOW (f) != 0)
737     adjust_frame_size (f, -1, -1, 3, 0, Qinternal_border_width);
739   SET_FRAME_GARBAGED (f);
743 static void
744 ns_implicitly_set_icon_type (struct frame *f)
746   Lisp_Object tem;
747   EmacsView *view = FRAME_NS_VIEW (f);
748   id image = nil;
749   Lisp_Object chain, elt;
750   NSAutoreleasePool *pool;
751   BOOL setMini = YES;
753   NSTRACE ("ns_implicitly_set_icon_type");
755   block_input ();
756   pool = [[NSAutoreleasePool alloc] init];
757   if (f->output_data.ns->miniimage
758       && [[NSString stringWithUTF8String: SSDATA (f->name)]
759                isEqualToString: [(NSImage *)f->output_data.ns->miniimage name]])
760     {
761       [pool release];
762       unblock_input ();
763       return;
764     }
766   tem = assq_no_quit (Qicon_type, f->param_alist);
767   if (CONSP (tem) && ! NILP (XCDR (tem)))
768     {
769       [pool release];
770       unblock_input ();
771       return;
772     }
774   for (chain = Vns_icon_type_alist;
775        image == nil && CONSP (chain);
776        chain = XCDR (chain))
777     {
778       elt = XCAR (chain);
779       /* special case: t means go by file type */
780       if (SYMBOLP (elt) && EQ (elt, Qt) && SSDATA (f->name)[0] == '/')
781         {
782           NSString *str
783              = [NSString stringWithUTF8String: SSDATA (f->name)];
784           if ([[NSFileManager defaultManager] fileExistsAtPath: str])
785             image = [[[NSWorkspace sharedWorkspace] iconForFile: str] retain];
786         }
787       else if (CONSP (elt) &&
788                STRINGP (XCAR (elt)) &&
789                STRINGP (XCDR (elt)) &&
790                fast_string_match (XCAR (elt), f->name) >= 0)
791         {
792           image = [EmacsImage allocInitFromFile: XCDR (elt)];
793           if (image == nil)
794             image = [[NSImage imageNamed:
795                                [NSString stringWithUTF8String:
796                                             SSDATA (XCDR (elt))]] retain];
797         }
798     }
800   if (image == nil)
801     {
802       image = [[[NSWorkspace sharedWorkspace] iconForFileType: @"text"] retain];
803       setMini = NO;
804     }
806   [f->output_data.ns->miniimage release];
807   f->output_data.ns->miniimage = image;
808   [view setMiniwindowImage: setMini];
809   [pool release];
810   unblock_input ();
814 static void
815 x_set_icon_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
817   EmacsView *view = FRAME_NS_VIEW (f);
818   id image = nil;
819   BOOL setMini = YES;
821   NSTRACE ("x_set_icon_type");
823   if (!NILP (arg) && SYMBOLP (arg))
824     {
825       arg =build_string (SSDATA (SYMBOL_NAME (arg)));
826       store_frame_param (f, Qicon_type, arg);
827     }
829   /* do it the implicit way */
830   if (NILP (arg))
831     {
832       ns_implicitly_set_icon_type (f);
833       return;
834     }
836   CHECK_STRING (arg);
838   image = [EmacsImage allocInitFromFile: arg];
839   if (image == nil)
840     image =[NSImage imageNamed: [NSString stringWithUTF8String:
841                                             SSDATA (arg)]];
843   if (image == nil)
844     {
845       image = [NSImage imageNamed: @"text"];
846       setMini = NO;
847     }
849   f->output_data.ns->miniimage = image;
850   [view setMiniwindowImage: setMini];
854 /* TODO: move to nsterm? */
856 ns_lisp_to_cursor_type (Lisp_Object arg)
858   char *str;
859   if (XTYPE (arg) == Lisp_String)
860     str = SSDATA (arg);
861   else if (XTYPE (arg) == Lisp_Symbol)
862     str = SSDATA (SYMBOL_NAME (arg));
863   else return -1;
864   if (!strcmp (str, "box"))     return FILLED_BOX_CURSOR;
865   if (!strcmp (str, "hollow"))  return HOLLOW_BOX_CURSOR;
866   if (!strcmp (str, "hbar"))    return HBAR_CURSOR;
867   if (!strcmp (str, "bar"))     return BAR_CURSOR;
868   if (!strcmp (str, "no"))      return NO_CURSOR;
869   return -1;
873 Lisp_Object
874 ns_cursor_type_to_lisp (int arg)
876   switch (arg)
877     {
878     case FILLED_BOX_CURSOR: return Qbox;
879     case HOLLOW_BOX_CURSOR: return Qhollow;
880     case HBAR_CURSOR:       return Qhbar;
881     case BAR_CURSOR:        return Qbar;
882     case NO_CURSOR:
883     default:                return intern ("no");
884     }
887 /* This is the same as the xfns.c definition.  */
888 static void
889 x_set_cursor_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
891   set_frame_cursor_types (f, arg);
894 /* called to set mouse pointer color, but all other terms use it to
895    initialize pointer types (and don't set the color ;) */
896 static void
897 x_set_mouse_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
899   /* don't think we can do this on Nextstep */
903 #define Str(x) #x
904 #define Xstr(x) Str(x)
906 static Lisp_Object
907 ns_appkit_version_str (void)
909   char tmp[256];
911 #ifdef NS_IMPL_GNUSTEP
912   sprintf(tmp, "gnustep-gui-%s", Xstr(GNUSTEP_GUI_VERSION));
913 #elif defined (NS_IMPL_COCOA)
914   NSString *osversion
915     = [[NSProcessInfo processInfo] operatingSystemVersionString];
916   sprintf(tmp, "appkit-%.2f %s",
917           NSAppKitVersionNumber,
918           [osversion UTF8String]);
919 #else
920   tmp = "ns-unknown";
921 #endif
922   return build_string (tmp);
926 /* This is for use by x-server-version and collapses all version info we
927    have into a single int.  For a better picture of the implementation
928    running, use ns_appkit_version_str.*/
929 static int
930 ns_appkit_version_int (void)
932 #ifdef NS_IMPL_GNUSTEP
933   return GNUSTEP_GUI_MAJOR_VERSION * 100 + GNUSTEP_GUI_MINOR_VERSION;
934 #elif defined (NS_IMPL_COCOA)
935   return (int)NSAppKitVersionNumber;
936 #endif
937   return 0;
941 static void
942 x_icon (struct frame *f, Lisp_Object parms)
943 /* --------------------------------------------------------------------------
944    Strangely-named function to set icon position parameters in frame.
945    This is irrelevant under OS X, but might be needed under GNUstep,
946    depending on the window manager used.  Note, this is not a standard
947    frame parameter-setter; it is called directly from x-create-frame.
948    -------------------------------------------------------------------------- */
950   Lisp_Object icon_x, icon_y;
951   struct ns_display_info *dpyinfo = check_ns_display_info (Qnil);
953   f->output_data.ns->icon_top = -1;
954   f->output_data.ns->icon_left = -1;
956   /* Set the position of the icon.  */
957   icon_x = x_get_arg (dpyinfo, parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
958   icon_y = x_get_arg (dpyinfo, parms, Qicon_top, 0, 0,  RES_TYPE_NUMBER);
959   if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
960     {
961       CHECK_NUMBER (icon_x);
962       CHECK_NUMBER (icon_y);
963       f->output_data.ns->icon_top = XINT (icon_y);
964       f->output_data.ns->icon_left = XINT (icon_x);
965     }
966   else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
967     error ("Both left and top icon corners of icon must be specified");
971 /* Note: see frame.c for template, also where generic functions are impl */
972 frame_parm_handler ns_frame_parm_handlers[] =
974   x_set_autoraise, /* generic OK */
975   x_set_autolower, /* generic OK */
976   x_set_background_color,
977   0, /* x_set_border_color,  may be impossible under Nextstep */
978   0, /* x_set_border_width,  may be impossible under Nextstep */
979   x_set_cursor_color,
980   x_set_cursor_type,
981   x_set_font, /* generic OK */
982   x_set_foreground_color,
983   x_set_icon_name,
984   x_set_icon_type,
985   x_set_internal_border_width, /* generic OK */
986   0, /* x_set_right_divider_width */
987   0, /* x_set_bottom_divider_width */
988   x_set_menu_bar_lines,
989   x_set_mouse_color,
990   x_explicitly_set_name,
991   x_set_scroll_bar_width, /* generic OK */
992   x_set_scroll_bar_height, /* generic OK */
993   x_set_title,
994   x_set_unsplittable, /* generic OK */
995   x_set_vertical_scroll_bars, /* generic OK */
996   x_set_horizontal_scroll_bars, /* generic OK */
997   x_set_visibility, /* generic OK */
998   x_set_tool_bar_lines,
999   0, /* x_set_scroll_bar_foreground, will ignore (not possible on NS) */
1000   0, /* x_set_scroll_bar_background,  will ignore (not possible on NS) */
1001   x_set_screen_gamma, /* generic OK */
1002   x_set_line_spacing, /* generic OK, sets f->extra_line_spacing to int */
1003   x_set_left_fringe, /* generic OK */
1004   x_set_right_fringe, /* generic OK */
1005   0, /* x_set_wait_for_wm, will ignore */
1006   x_set_fullscreen, /* generic OK */
1007   x_set_font_backend, /* generic OK */
1008   x_set_alpha,
1009   0, /* x_set_sticky */
1010   0, /* x_set_tool_bar_position */
1014 /* Handler for signals raised during x_create_frame.
1015    FRAME is the frame which is partially constructed.  */
1017 static void
1018 unwind_create_frame (Lisp_Object frame)
1020   struct frame *f = XFRAME (frame);
1022   /* If frame is already dead, nothing to do.  This can happen if the
1023      display is disconnected after the frame has become official, but
1024      before x_create_frame removes the unwind protect.  */
1025   if (!FRAME_LIVE_P (f))
1026     return;
1028   /* If frame is ``official'', nothing to do.  */
1029   if (NILP (Fmemq (frame, Vframe_list)))
1030     {
1031 #if defined GLYPH_DEBUG && defined ENABLE_CHECKING
1032       struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1033 #endif
1035       /* If the frame's image cache refcount is still the same as our
1036          private shadow variable, it means we are unwinding a frame
1037          for which we didn't yet call init_frame_faces, where the
1038          refcount is incremented.  Therefore, we increment it here, so
1039          that free_frame_faces, called in x_free_frame_resources
1040          below, will not mistakenly decrement the counter that was not
1041          incremented yet to account for this new frame.  */
1042       if (FRAME_IMAGE_CACHE (f) != NULL
1043           && FRAME_IMAGE_CACHE (f)->refcount == image_cache_refcount)
1044         FRAME_IMAGE_CACHE (f)->refcount++;
1046       x_free_frame_resources (f);
1047       free_glyphs (f);
1049 #if defined GLYPH_DEBUG && defined ENABLE_CHECKING
1050       /* Check that reference counts are indeed correct.  */
1051       eassert (dpyinfo->terminal->image_cache->refcount == image_cache_refcount);
1052 #endif
1053     }
1057  * Read geometry related parameters from preferences if not in PARMS.
1058  * Returns the union of parms and any preferences read.
1059  */
1061 static Lisp_Object
1062 get_geometry_from_preferences (struct ns_display_info *dpyinfo,
1063                                Lisp_Object parms)
1065   struct {
1066     const char *val;
1067     const char *cls;
1068     Lisp_Object tem;
1069   } r[] = {
1070     { "width",  "Width", Qwidth },
1071     { "height", "Height", Qheight },
1072     { "left", "Left", Qleft },
1073     { "top", "Top", Qtop },
1074   };
1076   int i;
1077   for (i = 0; i < ARRAYELTS (r); ++i)
1078     {
1079       if (NILP (Fassq (r[i].tem, parms)))
1080         {
1081           Lisp_Object value
1082             = x_get_arg (dpyinfo, parms, r[i].tem, r[i].val, r[i].cls,
1083                          RES_TYPE_NUMBER);
1084           if (! EQ (value, Qunbound))
1085             parms = Fcons (Fcons (r[i].tem, value), parms);
1086         }
1087     }
1089   return parms;
1092 /* ==========================================================================
1094     Lisp definitions
1096    ========================================================================== */
1098 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
1099        1, 1, 0,
1100        doc: /* Make a new Nextstep window, called a "frame" in Emacs terms.
1101 Return an Emacs frame object.
1102 PARMS is an alist of frame parameters.
1103 If the parameters specify that the frame should not have a minibuffer,
1104 and do not specify a specific minibuffer window to use,
1105 then `default-minibuffer-frame' must be a frame whose minibuffer can
1106 be shared by the new frame.
1108 This function is an internal primitive--use `make-frame' instead.  */)
1109      (Lisp_Object parms)
1111   struct frame *f;
1112   Lisp_Object frame, tem;
1113   Lisp_Object name;
1114   int minibuffer_only = 0;
1115   long window_prompting = 0;
1116   ptrdiff_t count = specpdl_ptr - specpdl;
1117   Lisp_Object display;
1118   struct ns_display_info *dpyinfo = NULL;
1119   Lisp_Object parent;
1120   struct kboard *kb;
1121   static int desc_ctr = 1;
1122   int x_width = 0, x_height = 0;
1124   /* x_get_arg modifies parms.  */
1125   parms = Fcopy_alist (parms);
1127   /* Use this general default value to start with
1128      until we know if this frame has a specified name.  */
1129   Vx_resource_name = Vinvocation_name;
1131   display = x_get_arg (dpyinfo, parms, Qterminal, 0, 0, RES_TYPE_STRING);
1132   if (EQ (display, Qunbound))
1133     display = Qnil;
1134   dpyinfo = check_ns_display_info (display);
1135   kb = dpyinfo->terminal->kboard;
1137   if (!dpyinfo->terminal->name)
1138     error ("Terminal is not live, can't create new frames on it");
1140   name = x_get_arg (dpyinfo, parms, Qname, 0, 0, RES_TYPE_STRING);
1141   if (!STRINGP (name)
1142       && ! EQ (name, Qunbound)
1143       && ! NILP (name))
1144     error ("Invalid frame name--not a string or nil");
1146   if (STRINGP (name))
1147     Vx_resource_name = name;
1149   parent = x_get_arg (dpyinfo, parms, Qparent_id, 0, 0, RES_TYPE_NUMBER);
1150   if (EQ (parent, Qunbound))
1151     parent = Qnil;
1152   if (! NILP (parent))
1153     CHECK_NUMBER (parent);
1155   /* make_frame_without_minibuffer can run Lisp code and garbage collect.  */
1156   /* No need to protect DISPLAY because that's not used after passing
1157      it to make_frame_without_minibuffer.  */
1158   frame = Qnil;
1159   tem = x_get_arg (dpyinfo, parms, Qminibuffer, "minibuffer", "Minibuffer",
1160                   RES_TYPE_SYMBOL);
1161   if (EQ (tem, Qnone) || NILP (tem))
1162       f = make_frame_without_minibuffer (Qnil, kb, display);
1163   else if (EQ (tem, Qonly))
1164     {
1165       f = make_minibuffer_frame ();
1166       minibuffer_only = 1;
1167     }
1168   else if (WINDOWP (tem))
1169       f = make_frame_without_minibuffer (tem, kb, display);
1170   else
1171       f = make_frame (1);
1173   XSETFRAME (frame, f);
1175   f->terminal = dpyinfo->terminal;
1177   f->output_method = output_ns;
1178   f->output_data.ns = xzalloc (sizeof *f->output_data.ns);
1180   FRAME_FONTSET (f) = -1;
1182   fset_icon_name (f, x_get_arg (dpyinfo, parms, Qicon_name,
1183                                 "iconName", "Title",
1184                                 RES_TYPE_STRING));
1185   if (! STRINGP (f->icon_name))
1186     fset_icon_name (f, Qnil);
1188   FRAME_DISPLAY_INFO (f) = dpyinfo;
1190   /* With FRAME_DISPLAY_INFO set up, this unwind-protect is safe.  */
1191   record_unwind_protect (unwind_create_frame, frame);
1193   f->output_data.ns->window_desc = desc_ctr++;
1194   if (TYPE_RANGED_INTEGERP (Window, parent))
1195     {
1196       f->output_data.ns->parent_desc = XFASTINT (parent);
1197       f->output_data.ns->explicit_parent = 1;
1198     }
1199   else
1200     {
1201       f->output_data.ns->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
1202       f->output_data.ns->explicit_parent = 0;
1203     }
1205   /* Set the name; the functions to which we pass f expect the name to
1206      be set.  */
1207   if (EQ (name, Qunbound) || NILP (name) || ! STRINGP (name))
1208     {
1209       fset_name (f, build_string ([ns_app_name UTF8String]));
1210       f->explicit_name = 0;
1211     }
1212   else
1213     {
1214       fset_name (f, name);
1215       f->explicit_name = 1;
1216       specbind (Qx_resource_name, name);
1217     }
1219   block_input ();
1221 #ifdef NS_IMPL_COCOA
1222     mac_register_font_driver (f);
1223 #else
1224     register_font_driver (&nsfont_driver, f);
1225 #endif
1227   image_cache_refcount =
1228     FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
1230   x_default_parameter (f, parms, Qfont_backend, Qnil,
1231                         "fontBackend", "FontBackend", RES_TYPE_STRING);
1233   {
1234     /* use for default font name */
1235     id font = [NSFont userFixedPitchFontOfSize: -1.0]; /* default */
1236     x_default_parameter (f, parms, Qfontsize,
1237                                     make_number (0 /*(int)[font pointSize]*/),
1238                                     "fontSize", "FontSize", RES_TYPE_NUMBER);
1239     // Remove ' Regular', not handled by backends.
1240     char *fontname = xstrdup ([[font displayName] UTF8String]);
1241     int len = strlen (fontname);
1242     if (len > 8 && strcmp (fontname + len - 8, " Regular") == 0)
1243       fontname[len-8] = '\0';
1244     x_default_parameter (f, parms, Qfont,
1245                                  build_string (fontname),
1246                                  "font", "Font", RES_TYPE_STRING);
1247     xfree (fontname);
1248   }
1249   unblock_input ();
1251   x_default_parameter (f, parms, Qborder_width, make_number (0),
1252                        "borderwidth", "BorderWidth", RES_TYPE_NUMBER);
1253   x_default_parameter (f, parms, Qinternal_border_width, make_number (2),
1254                       "internalBorderWidth", "InternalBorderWidth",
1255                       RES_TYPE_NUMBER);
1257   /* default vertical scrollbars on right on Mac */
1258   {
1259       Lisp_Object spos
1260 #ifdef NS_IMPL_GNUSTEP
1261           = Qt;
1262 #else
1263           = Qright;
1264 #endif
1265       x_default_parameter (f, parms, Qvertical_scroll_bars, spos,
1266                            "verticalScrollBars", "VerticalScrollBars",
1267                            RES_TYPE_SYMBOL);
1268   }
1269   x_default_parameter (f, parms, Qhorizontal_scroll_bars, Qnil,
1270                        "horizontalScrollBars", "HorizontalScrollBars",
1271                        RES_TYPE_SYMBOL);
1272   x_default_parameter (f, parms, Qforeground_color, build_string ("Black"),
1273                       "foreground", "Foreground", RES_TYPE_STRING);
1274   x_default_parameter (f, parms, Qbackground_color, build_string ("White"),
1275                       "background", "Background", RES_TYPE_STRING);
1276   /* FIXME: not supported yet in Nextstep */
1277   x_default_parameter (f, parms, Qline_spacing, Qnil,
1278                        "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
1279   x_default_parameter (f, parms, Qleft_fringe, Qnil,
1280                        "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
1281   x_default_parameter (f, parms, Qright_fringe, Qnil,
1282                        "rightFringe", "RightFringe", RES_TYPE_NUMBER);
1284   init_frame_faces (f);
1286   /* Read comment about this code in corresponding place in xfns.c.  */
1287   adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
1288                      FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 5, 1,
1289                      Qx_create_frame_1);
1291   /* The resources controlling the menu-bar and tool-bar are
1292      processed specially at startup, and reflected in the mode
1293      variables; ignore them here.  */
1294   x_default_parameter (f, parms, Qmenu_bar_lines,
1295                        NILP (Vmenu_bar_mode)
1296                        ? make_number (0) : make_number (1),
1297                        NULL, NULL, RES_TYPE_NUMBER);
1298   x_default_parameter (f, parms, Qtool_bar_lines,
1299                        NILP (Vtool_bar_mode)
1300                        ? make_number (0) : make_number (1),
1301                        NULL, NULL, RES_TYPE_NUMBER);
1303   x_default_parameter (f, parms, Qbuffer_predicate, Qnil, "bufferPredicate",
1304                        "BufferPredicate", RES_TYPE_SYMBOL);
1305   x_default_parameter (f, parms, Qtitle, Qnil, "title", "Title",
1306                        RES_TYPE_STRING);
1308   parms = get_geometry_from_preferences (dpyinfo, parms);
1309   window_prompting = x_figure_window_size (f, parms, true, &x_width, &x_height);
1311   tem = x_get_arg (dpyinfo, parms, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
1312   f->no_split = minibuffer_only || (!EQ (tem, Qunbound) && !EQ (tem, Qnil));
1314   /* NOTE: on other terms, this is done in set_mouse_color, however this
1315      was not getting called under Nextstep */
1316   f->output_data.ns->text_cursor = [NSCursor IBeamCursor];
1317   f->output_data.ns->nontext_cursor = [NSCursor arrowCursor];
1318   f->output_data.ns->modeline_cursor = [NSCursor pointingHandCursor];
1319   f->output_data.ns->hand_cursor = [NSCursor pointingHandCursor];
1320   f->output_data.ns->hourglass_cursor = [NSCursor disappearingItemCursor];
1321   f->output_data.ns->horizontal_drag_cursor = [NSCursor resizeLeftRightCursor];
1322   f->output_data.ns->vertical_drag_cursor = [NSCursor resizeUpDownCursor];
1323   FRAME_DISPLAY_INFO (f)->vertical_scroll_bar_cursor
1324      = [NSCursor arrowCursor];
1325   FRAME_DISPLAY_INFO (f)->horizontal_scroll_bar_cursor
1326      = [NSCursor arrowCursor];
1327   f->output_data.ns->current_pointer = f->output_data.ns->text_cursor;
1329   f->output_data.ns->in_animation = NO;
1331   [[EmacsView alloc] initFrameFromEmacs: f];
1333   x_icon (f, parms);
1335   /* ns_display_info does not have a reference_count.  */
1336   f->terminal->reference_count++;
1338   /* It is now ok to make the frame official even if we get an error below.
1339      The frame needs to be on Vframe_list or making it visible won't work. */
1340   Vframe_list = Fcons (frame, Vframe_list);
1342   x_default_parameter (f, parms, Qicon_type, Qnil,
1343                        "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
1345   x_default_parameter (f, parms, Qauto_raise, Qnil,
1346                        "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
1347   x_default_parameter (f, parms, Qauto_lower, Qnil,
1348                        "autoLower", "AutoLower", RES_TYPE_BOOLEAN);
1349   x_default_parameter (f, parms, Qcursor_type, Qbox,
1350                        "cursorType", "CursorType", RES_TYPE_SYMBOL);
1351   x_default_parameter (f, parms, Qscroll_bar_width, Qnil,
1352                        "scrollBarWidth", "ScrollBarWidth",
1353                        RES_TYPE_NUMBER);
1354   x_default_parameter (f, parms, Qscroll_bar_height, Qnil,
1355                        "scrollBarHeight", "ScrollBarHeight",
1356                        RES_TYPE_NUMBER);
1357   x_default_parameter (f, parms, Qalpha, Qnil,
1358                        "alpha", "Alpha", RES_TYPE_NUMBER);
1359   x_default_parameter (f, parms, Qfullscreen, Qnil,
1360                        "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
1362   /* Allow x_set_window_size, now.  */
1363   f->can_x_set_window_size = true;
1365   if (x_width > 0)
1366     SET_FRAME_WIDTH (f, x_width);
1367   if (x_height > 0)
1368     SET_FRAME_HEIGHT (f, x_height);
1370   adjust_frame_size (f, FRAME_TEXT_WIDTH (f), FRAME_TEXT_HEIGHT (f), 0, 1,
1371                      Qx_create_frame_2);
1373   if (! f->output_data.ns->explicit_parent)
1374     {
1375       Lisp_Object visibility;
1377       visibility = x_get_arg (dpyinfo, parms, Qvisibility, 0, 0,
1378                               RES_TYPE_SYMBOL);
1379       if (EQ (visibility, Qunbound))
1380         visibility = Qt;
1382       if (EQ (visibility, Qicon))
1383         x_iconify_frame (f);
1384       else if (! NILP (visibility))
1385         {
1386           x_make_frame_visible (f);
1387           [[FRAME_NS_VIEW (f) window] makeKeyWindow];
1388         }
1389       else
1390         {
1391           /* Must have been Qnil.  */
1392         }
1393     }
1395   if (FRAME_HAS_MINIBUF_P (f)
1396       && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
1397           || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
1398     kset_default_minibuffer_frame (kb, frame);
1400   /* All remaining specified parameters, which have not been "used"
1401      by x_get_arg and friends, now go in the misc. alist of the frame.  */
1402   for (tem = parms; CONSP (tem); tem = XCDR (tem))
1403     if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
1404       fset_param_alist (f, Fcons (XCAR (tem), f->param_alist));
1406   if (window_prompting & USPosition)
1407     x_set_offset (f, f->left_pos, f->top_pos, 1);
1409   /* Make sure windows on this frame appear in calls to next-window
1410      and similar functions.  */
1411   Vwindow_list = Qnil;
1413   return unbind_to (count, frame);
1416 void
1417 x_focus_frame (struct frame *f)
1419   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1421   if (dpyinfo->x_focus_frame != f)
1422     {
1423       EmacsView *view = FRAME_NS_VIEW (f);
1424       block_input ();
1425       [NSApp activateIgnoringOtherApps: YES];
1426       [[view window] makeKeyAndOrderFront: view];
1427       unblock_input ();
1428     }
1432 DEFUN ("ns-popup-font-panel", Fns_popup_font_panel, Sns_popup_font_panel,
1433        0, 1, "",
1434        doc: /* Pop up the font panel. */)
1435      (Lisp_Object frame)
1437   struct frame *f = decode_window_system_frame (frame);
1438   id fm = [NSFontManager sharedFontManager];
1439   struct font *font = f->output_data.ns->font;
1440   NSFont *nsfont;
1441 #ifdef NS_IMPL_GNUSTEP
1442   nsfont = ((struct nsfont_info *)font)->nsfont;
1443 #endif
1444 #ifdef NS_IMPL_COCOA
1445   nsfont = (NSFont *) macfont_get_nsctfont (font);
1446 #endif
1447   [fm setSelectedFont: nsfont isMultiple: NO];
1448   [fm orderFrontFontPanel: NSApp];
1449   return Qnil;
1453 DEFUN ("ns-popup-color-panel", Fns_popup_color_panel, Sns_popup_color_panel,
1454        0, 1, "",
1455        doc: /* Pop up the color panel.  */)
1456      (Lisp_Object frame)
1458   check_window_system (NULL);
1459   [NSApp orderFrontColorPanel: NSApp];
1460   return Qnil;
1463 static struct
1465   id panel;
1466   BOOL ret;
1467 #ifdef NS_IMPL_GNUSTEP
1468   NSString *dirS, *initS;
1469   BOOL no_types;
1470 #endif
1471 } ns_fd_data;
1473 void
1474 ns_run_file_dialog (void)
1476   if (ns_fd_data.panel == nil) return;
1477 #ifdef NS_IMPL_COCOA
1478   ns_fd_data.ret = [ns_fd_data.panel runModal];
1479 #else
1480   if (ns_fd_data.no_types)
1481     {
1482       ns_fd_data.ret = [ns_fd_data.panel
1483                            runModalForDirectory: ns_fd_data.dirS
1484                            file: ns_fd_data.initS];
1485     }
1486   else
1487     {
1488       ns_fd_data.ret = [ns_fd_data.panel
1489                            runModalForDirectory: ns_fd_data.dirS
1490                            file: ns_fd_data.initS
1491                            types: nil];
1492     }
1493 #endif
1494   ns_fd_data.panel = nil;
1497 #ifdef NS_IMPL_COCOA
1498 #if MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_9
1499 #define MODAL_OK_RESPONSE NSModalResponseOK
1500 #endif
1501 #endif
1502 #ifndef MODAL_OK_RESPONSE
1503 #define MODAL_OK_RESPONSE NSOKButton
1504 #endif
1506 DEFUN ("ns-read-file-name", Fns_read_file_name, Sns_read_file_name, 1, 5, 0,
1507        doc: /* Use a graphical panel to read a file name, using prompt PROMPT.
1508 Optional arg DIR, if non-nil, supplies a default directory.
1509 Optional arg MUSTMATCH, if non-nil, means the returned file or
1510 directory must exist.
1511 Optional arg INIT, if non-nil, provides a default file name to use.
1512 Optional arg DIR_ONLY_P, if non-nil, means choose only directories.  */)
1513   (Lisp_Object prompt, Lisp_Object dir, Lisp_Object mustmatch,
1514    Lisp_Object init, Lisp_Object dir_only_p)
1516   static id fileDelegate = nil;
1517   BOOL isSave = NILP (mustmatch) && NILP (dir_only_p);
1518   id panel;
1519   Lisp_Object fname = Qnil;
1521   NSString *promptS = NILP (prompt) || !STRINGP (prompt) ? nil :
1522     [NSString stringWithUTF8String: SSDATA (prompt)];
1523   NSString *dirS = NILP (dir) || !STRINGP (dir) ?
1524     [NSString stringWithUTF8String: SSDATA (BVAR (current_buffer, directory))] :
1525     [NSString stringWithUTF8String: SSDATA (dir)];
1526   NSString *initS = NILP (init) || !STRINGP (init) ? nil :
1527     [NSString stringWithUTF8String: SSDATA (init)];
1528   NSEvent *nxev;
1530   check_window_system (NULL);
1532   if (fileDelegate == nil)
1533     fileDelegate = [EmacsFileDelegate new];
1535   [NSCursor setHiddenUntilMouseMoves: NO];
1537   if ([dirS characterAtIndex: 0] == '~')
1538     dirS = [dirS stringByExpandingTildeInPath];
1540   panel = isSave ?
1541     (id)[EmacsSavePanel savePanel] : (id)[EmacsOpenPanel openPanel];
1543   [panel setTitle: promptS];
1545   [panel setAllowsOtherFileTypes: YES];
1546   [panel setTreatsFilePackagesAsDirectories: YES];
1547   [panel setDelegate: fileDelegate];
1549   if (! NILP (dir_only_p))
1550     {
1551       [panel setCanChooseDirectories: YES];
1552       [panel setCanChooseFiles: NO];
1553     }
1554   else if (! isSave)
1555     {
1556       /* This is not quite what the documentation says, but it is compatible
1557          with the Gtk+ code.  Also, the menu entry says "Open File...".  */
1558       [panel setCanChooseDirectories: NO];
1559       [panel setCanChooseFiles: YES];
1560     }
1562   block_input ();
1563   ns_fd_data.panel = panel;
1564   ns_fd_data.ret = NO;
1565 #ifdef NS_IMPL_COCOA
1566   if (! NILP (mustmatch) || ! NILP (dir_only_p))
1567     [panel setAllowedFileTypes: nil];
1568   if (dirS) [panel setDirectoryURL: [NSURL fileURLWithPath: dirS]];
1569   if (initS && NILP (Ffile_directory_p (init)))
1570     [panel setNameFieldStringValue: [initS lastPathComponent]];
1571   else
1572     [panel setNameFieldStringValue: @""];
1574 #else
1575   ns_fd_data.no_types = NILP (mustmatch) && NILP (dir_only_p);
1576   ns_fd_data.dirS = dirS;
1577   ns_fd_data.initS = initS;
1578 #endif
1580   /* runModalForDirectory/runModal restarts the main event loop when done,
1581      so we must start an event loop and then pop up the file dialog.
1582      The file dialog may pop up a confirm dialog after Ok has been pressed,
1583      so we can not simply pop down on the Ok/Cancel press.
1584    */
1585   nxev = [NSEvent otherEventWithType: NSApplicationDefined
1586                             location: NSMakePoint (0, 0)
1587                        modifierFlags: 0
1588                            timestamp: 0
1589                         windowNumber: [[NSApp mainWindow] windowNumber]
1590                              context: [NSApp context]
1591                              subtype: 0
1592                                data1: 0
1593                                data2: NSAPP_DATA2_RUNFILEDIALOG];
1595   [NSApp postEvent: nxev atStart: NO];
1596   while (ns_fd_data.panel != nil)
1597     [NSApp run];
1599   if (ns_fd_data.ret == MODAL_OK_RESPONSE)
1600     {
1601       NSString *str = ns_filename_from_panel (panel);
1602       if (! str) str = ns_directory_from_panel (panel);
1603       if (str) fname = build_string ([str UTF8String]);
1604     }
1606   [[FRAME_NS_VIEW (SELECTED_FRAME ()) window] makeKeyWindow];
1607   unblock_input ();
1609   return fname;
1612 const char *
1613 ns_get_defaults_value (const char *key)
1615   NSObject *obj = [[NSUserDefaults standardUserDefaults]
1616                     objectForKey: [NSString stringWithUTF8String: key]];
1618   if (!obj) return NULL;
1620   return [[NSString stringWithFormat: @"%@", obj] UTF8String];
1624 DEFUN ("ns-get-resource", Fns_get_resource, Sns_get_resource, 2, 2, 0,
1625        doc: /* Return the value of the property NAME of OWNER from the defaults database.
1626 If OWNER is nil, Emacs is assumed.  */)
1627      (Lisp_Object owner, Lisp_Object name)
1629   const char *value;
1631   check_window_system (NULL);
1632   if (NILP (owner))
1633     owner = build_string([ns_app_name UTF8String]);
1634   CHECK_STRING (name);
1636   value = ns_get_defaults_value (SSDATA (name));
1638   if (value)
1639     return build_string (value);
1640   return Qnil;
1644 DEFUN ("ns-set-resource", Fns_set_resource, Sns_set_resource, 3, 3, 0,
1645        doc: /* Set property NAME of OWNER to VALUE, from the defaults database.
1646 If OWNER is nil, Emacs is assumed.
1647 If VALUE is nil, the default is removed.  */)
1648      (Lisp_Object owner, Lisp_Object name, Lisp_Object value)
1650   check_window_system (NULL);
1651   if (NILP (owner))
1652     owner = build_string ([ns_app_name UTF8String]);
1653   CHECK_STRING (name);
1654   if (NILP (value))
1655     {
1656       [[NSUserDefaults standardUserDefaults] removeObjectForKey:
1657                          [NSString stringWithUTF8String: SSDATA (name)]];
1658     }
1659   else
1660     {
1661       CHECK_STRING (value);
1662       [[NSUserDefaults standardUserDefaults] setObject:
1663                 [NSString stringWithUTF8String: SSDATA (value)]
1664                                         forKey: [NSString stringWithUTF8String:
1665                                                          SSDATA (name)]];
1666     }
1668   return Qnil;
1672 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
1673        Sx_server_max_request_size,
1674        0, 1, 0,
1675        doc: /* This function is a no-op.  It is only present for completeness.  */)
1676      (Lisp_Object terminal)
1678   check_ns_display_info (terminal);
1679   /* This function has no real equivalent under NeXTstep.  Return nil to
1680      indicate this. */
1681   return Qnil;
1685 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
1686        doc: /* Return the "vendor ID" string of Nextstep display server TERMINAL.
1687 (Labeling every distributor as a "vendor" embodies the false assumption
1688 that operating systems cannot be developed and distributed noncommercially.)
1689 The optional argument TERMINAL specifies which display to ask about.
1690 TERMINAL should be a terminal object, a frame or a display name (a string).
1691 If omitted or nil, that stands for the selected frame's display.  */)
1692   (Lisp_Object terminal)
1694   check_ns_display_info (terminal);
1695 #ifdef NS_IMPL_GNUSTEP
1696   return build_string ("GNU");
1697 #else
1698   return build_string ("Apple");
1699 #endif
1703 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
1704        doc: /* Return the version numbers of the server of display TERMINAL.
1705 The value is a list of three integers: the major and minor
1706 version numbers of the X Protocol in use, and the distributor-specific release
1707 number.  See also the function `x-server-vendor'.
1709 The optional argument TERMINAL specifies which display to ask about.
1710 TERMINAL should be a terminal object, a frame or a display name (a string).
1711 If omitted or nil, that stands for the selected frame's display.  */)
1712   (Lisp_Object terminal)
1714   check_ns_display_info (terminal);
1715   /*NOTE: it is unclear what would best correspond with "protocol";
1716           we return 10.3, meaning Panther, since this is roughly the
1717           level that GNUstep's APIs correspond to.
1718           The last number is where we distinguish between the Apple
1719           and GNUstep implementations ("distributor-specific release
1720           number") and give int'ized versions of major.minor. */
1721   return list3i (10, 3, ns_appkit_version_int ());
1725 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
1726        doc: /* Return the number of screens on Nextstep display server TERMINAL.
1727 The optional argument TERMINAL specifies which display to ask about.
1728 TERMINAL should be a terminal object, a frame or a display name (a string).
1729 If omitted or nil, that stands for the selected frame's display.
1731 Note: "screen" here is not in Nextstep terminology but in X11's.  For
1732 the number of physical monitors, use `(length
1733 (display-monitor-attributes-list TERMINAL))' instead.  */)
1734   (Lisp_Object terminal)
1736   check_ns_display_info (terminal);
1737   return make_number (1);
1741 DEFUN ("x-display-mm-height", Fx_display_mm_height, Sx_display_mm_height, 0, 1, 0,
1742        doc: /* Return the height in millimeters of the Nextstep display TERMINAL.
1743 The optional argument TERMINAL specifies which display to ask about.
1744 TERMINAL should be a terminal object, a frame or a display name (a string).
1745 If omitted or nil, that stands for the selected frame's display.
1747 On \"multi-monitor\" setups this refers to the height in millimeters for
1748 all physical monitors associated with TERMINAL.  To get information
1749 for each physical monitor, use `display-monitor-attributes-list'.  */)
1750   (Lisp_Object terminal)
1752   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
1754   return make_number (x_display_pixel_height (dpyinfo) / (92.0/25.4));
1758 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
1759        doc: /* Return the width in millimeters of the Nextstep display TERMINAL.
1760 The optional argument TERMINAL specifies which display to ask about.
1761 TERMINAL should be a terminal object, a frame or a display name (a string).
1762 If omitted or nil, that stands for the selected frame's display.
1764 On \"multi-monitor\" setups this refers to the width in millimeters for
1765 all physical monitors associated with TERMINAL.  To get information
1766 for each physical monitor, use `display-monitor-attributes-list'.  */)
1767   (Lisp_Object terminal)
1769   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
1771   return make_number (x_display_pixel_width (dpyinfo) / (92.0/25.4));
1775 DEFUN ("x-display-backing-store", Fx_display_backing_store,
1776        Sx_display_backing_store, 0, 1, 0,
1777        doc: /* Return an indication of whether the Nextstep display TERMINAL does backing store.
1778 The value may be `buffered', `retained', or `non-retained'.
1779 The optional argument TERMINAL specifies which display to ask about.
1780 TERMINAL should be a terminal object, a frame or a display name (a string).
1781 If omitted or nil, that stands for the selected frame's display.  */)
1782   (Lisp_Object terminal)
1784   check_ns_display_info (terminal);
1785   switch ([ns_get_window (terminal) backingType])
1786     {
1787     case NSBackingStoreBuffered:
1788       return intern ("buffered");
1789     case NSBackingStoreRetained:
1790       return intern ("retained");
1791     case NSBackingStoreNonretained:
1792       return intern ("non-retained");
1793     default:
1794       error ("Strange value for backingType parameter of frame");
1795     }
1796   return Qnil;  /* not reached, shut compiler up */
1800 DEFUN ("x-display-visual-class", Fx_display_visual_class,
1801        Sx_display_visual_class, 0, 1, 0,
1802        doc: /* Return the visual class of the Nextstep display TERMINAL.
1803 The value is one of the symbols `static-gray', `gray-scale',
1804 `static-color', `pseudo-color', `true-color', or `direct-color'.
1806 The optional argument TERMINAL specifies which display to ask about.
1807 TERMINAL should a terminal object, a frame or a display name (a string).
1808 If omitted or nil, that stands for the selected frame's display.  */)
1809   (Lisp_Object terminal)
1811   NSWindowDepth depth;
1813   check_ns_display_info (terminal);
1814   depth = [[[NSScreen screens] objectAtIndex:0] depth];
1816   if ( depth == NSBestDepth (NSCalibratedWhiteColorSpace, 2, 2, YES, NULL))
1817     return intern ("static-gray");
1818   else if (depth == NSBestDepth (NSCalibratedWhiteColorSpace, 8, 8, YES, NULL))
1819     return intern ("gray-scale");
1820   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 8, 8, YES, NULL))
1821     return intern ("pseudo-color");
1822   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 4, 12, NO, NULL))
1823     return intern ("true-color");
1824   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 8, 24, NO, NULL))
1825     return intern ("direct-color");
1826   else
1827     /* color mgmt as far as we do it is really handled by Nextstep itself anyway */
1828     return intern ("direct-color");
1832 DEFUN ("x-display-save-under", Fx_display_save_under,
1833        Sx_display_save_under, 0, 1, 0,
1834        doc: /* Return t if TERMINAL supports the save-under feature.
1835 The optional argument TERMINAL specifies which display to ask about.
1836 TERMINAL should be a terminal object, a frame or a display name (a string).
1837 If omitted or nil, that stands for the selected frame's display.  */)
1838   (Lisp_Object terminal)
1840   check_ns_display_info (terminal);
1841   switch ([ns_get_window (terminal) backingType])
1842     {
1843     case NSBackingStoreBuffered:
1844       return Qt;
1846     case NSBackingStoreRetained:
1847     case NSBackingStoreNonretained:
1848       return Qnil;
1850     default:
1851       error ("Strange value for backingType parameter of frame");
1852     }
1853   return Qnil;  /* not reached, shut compiler up */
1857 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
1858        1, 3, 0,
1859        doc: /* Open a connection to a display server.
1860 DISPLAY is the name of the display to connect to.
1861 Optional second arg XRM-STRING is a string of resources in xrdb format.
1862 If the optional third arg MUST-SUCCEED is non-nil,
1863 terminate Emacs if we can't open the connection.
1864 (In the Nextstep version, the last two arguments are currently ignored.)  */)
1865      (Lisp_Object display, Lisp_Object resource_string, Lisp_Object must_succeed)
1867   struct ns_display_info *dpyinfo;
1869   CHECK_STRING (display);
1871   nxatoms_of_nsselect ();
1872   dpyinfo = ns_term_init (display);
1873   if (dpyinfo == 0)
1874     {
1875       if (!NILP (must_succeed))
1876         fatal ("Display on %s not responding.\n",
1877                SSDATA (display));
1878       else
1879         error ("Display on %s not responding.\n",
1880                SSDATA (display));
1881     }
1883   return Qnil;
1887 DEFUN ("x-close-connection", Fx_close_connection, Sx_close_connection,
1888        1, 1, 0,
1889        doc: /* Close the connection to TERMINAL's Nextstep display server.
1890 For TERMINAL, specify a terminal object, a frame or a display name (a
1891 string).  If TERMINAL is nil, that stands for the selected frame's
1892 terminal.  */)
1893      (Lisp_Object terminal)
1895   check_ns_display_info (terminal);
1896   [NSApp terminate: NSApp];
1897   return Qnil;
1901 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
1902        doc: /* Return the list of display names that Emacs has connections to.  */)
1903      (void)
1905   Lisp_Object result = Qnil;
1906   struct ns_display_info *ndi;
1908   for (ndi = x_display_list; ndi; ndi = ndi->next)
1909     result = Fcons (XCAR (ndi->name_list_element), result);
1911   return result;
1915 DEFUN ("ns-hide-others", Fns_hide_others, Sns_hide_others,
1916        0, 0, 0,
1917        doc: /* Hides all applications other than Emacs.  */)
1918      (void)
1920   check_window_system (NULL);
1921   [NSApp hideOtherApplications: NSApp];
1922   return Qnil;
1925 DEFUN ("ns-hide-emacs", Fns_hide_emacs, Sns_hide_emacs,
1926        1, 1, 0,
1927        doc: /* If ON is non-nil, the entire Emacs application is hidden.
1928 Otherwise if Emacs is hidden, it is unhidden.
1929 If ON is equal to `activate', Emacs is unhidden and becomes
1930 the active application.  */)
1931      (Lisp_Object on)
1933   check_window_system (NULL);
1934   if (EQ (on, intern ("activate")))
1935     {
1936       [NSApp unhide: NSApp];
1937       [NSApp activateIgnoringOtherApps: YES];
1938     }
1939   else if (NILP (on))
1940     [NSApp unhide: NSApp];
1941   else
1942     [NSApp hide: NSApp];
1943   return Qnil;
1947 DEFUN ("ns-emacs-info-panel", Fns_emacs_info_panel, Sns_emacs_info_panel,
1948        0, 0, 0,
1949        doc: /* Shows the 'Info' or 'About' panel for Emacs.  */)
1950      (void)
1952   check_window_system (NULL);
1953   [NSApp orderFrontStandardAboutPanel: nil];
1954   return Qnil;
1958 DEFUN ("ns-font-name", Fns_font_name, Sns_font_name, 1, 1, 0,
1959        doc: /* Determine font PostScript or family name for font NAME.
1960 NAME should be a string containing either the font name or an XLFD
1961 font descriptor.  If string contains `fontset' and not
1962 `fontset-startup', it is left alone. */)
1963      (Lisp_Object name)
1965   char *nm;
1966   CHECK_STRING (name);
1967   nm = SSDATA (name);
1969   if (nm[0] != '-')
1970     return name;
1971   if (strstr (nm, "fontset") && !strstr (nm, "fontset-startup"))
1972     return name;
1974   return build_string (ns_xlfd_to_fontname (SSDATA (name)));
1978 DEFUN ("ns-list-colors", Fns_list_colors, Sns_list_colors, 0, 1, 0,
1979        doc: /* Return a list of all available colors.
1980 The optional argument FRAME is currently ignored.  */)
1981      (Lisp_Object frame)
1983   Lisp_Object list = Qnil;
1984   NSEnumerator *colorlists;
1985   NSColorList *clist;
1987   if (!NILP (frame))
1988     {
1989       CHECK_FRAME (frame);
1990       if (! FRAME_NS_P (XFRAME (frame)))
1991         error ("non-Nextstep frame used in `ns-list-colors'");
1992     }
1994   block_input ();
1996   colorlists = [[NSColorList availableColorLists] objectEnumerator];
1997   while ((clist = [colorlists nextObject]))
1998     {
1999       if ([[clist name] length] < 7 ||
2000           [[clist name] rangeOfString: @"PANTONE"].location == 0)
2001         {
2002           NSEnumerator *cnames = [[clist allKeys] reverseObjectEnumerator];
2003           NSString *cname;
2004           while ((cname = [cnames nextObject]))
2005             list = Fcons (build_string ([cname UTF8String]), list);
2006 /*           for (i = [[clist allKeys] count] - 1; i >= 0; i--)
2007                list = Fcons (build_string ([[[clist allKeys] objectAtIndex: i]
2008                                              UTF8String]), list); */
2009         }
2010     }
2012   unblock_input ();
2014   return list;
2018 DEFUN ("ns-list-services", Fns_list_services, Sns_list_services, 0, 0, 0,
2019        doc: /* List available Nextstep services by querying NSApp.  */)
2020      (void)
2022 #ifdef NS_IMPL_COCOA
2023   /* You can't get services like this in 10.6+.  */
2024   return Qnil;
2025 #else
2026   Lisp_Object ret = Qnil;
2027   NSMenu *svcs;
2028 #ifdef NS_IMPL_COCOA
2029   id delegate;
2030 #endif
2032   check_window_system (NULL);
2033   svcs = [[NSMenu alloc] initWithTitle: @"Services"];
2034   [NSApp setServicesMenu: svcs];
2035   [NSApp registerServicesMenuSendTypes: ns_send_types
2036                            returnTypes: ns_return_types];
2038 /* On Tiger, services menu updating was made lazier (waits for user to
2039    actually click on the menu), so we have to force things along: */
2040 #ifdef NS_IMPL_COCOA
2041   delegate = [svcs delegate];
2042   if (delegate != nil)
2043     {
2044       if ([delegate respondsToSelector: @selector (menuNeedsUpdate:)])
2045         [delegate menuNeedsUpdate: svcs];
2046       if ([delegate respondsToSelector:
2047                        @selector (menu:updateItem:atIndex:shouldCancel:)])
2048         {
2049           int i, len = [delegate numberOfItemsInMenu: svcs];
2050           for (i =0; i<len; i++)
2051             [svcs addItemWithTitle: @"" action: NULL keyEquivalent: @""];
2052           for (i =0; i<len; i++)
2053             if (![delegate menu: svcs
2054                      updateItem: (NSMenuItem *)[svcs itemAtIndex: i]
2055                         atIndex: i shouldCancel: NO])
2056               break;
2057         }
2058     }
2059 #endif
2061   [svcs setAutoenablesItems: NO];
2062 #ifdef NS_IMPL_COCOA
2063   [svcs update]; /* on OS X, converts from '/' structure */
2064 #endif
2066   ret = interpret_services_menu (svcs, Qnil, ret);
2067   return ret;
2068 #endif
2072 DEFUN ("ns-perform-service", Fns_perform_service, Sns_perform_service,
2073        2, 2, 0,
2074        doc: /* Perform Nextstep SERVICE on SEND.
2075 SEND should be either a string or nil.
2076 The return value is the result of the service, as string, or nil if
2077 there was no result.  */)
2078      (Lisp_Object service, Lisp_Object send)
2080   id pb;
2081   NSString *svcName;
2082   char *utfStr;
2084   CHECK_STRING (service);
2085   check_window_system (NULL);
2087   utfStr = SSDATA (service);
2088   svcName = [NSString stringWithUTF8String: utfStr];
2090   pb =[NSPasteboard pasteboardWithUniqueName];
2091   ns_string_to_pasteboard (pb, send);
2093   if (NSPerformService (svcName, pb) == NO)
2094     Fsignal (Qquit, list1 (build_string ("service not available")));
2096   if ([[pb types] count] == 0)
2097     return build_string ("");
2098   return ns_string_from_pasteboard (pb);
2102 DEFUN ("ns-convert-utf8-nfd-to-nfc", Fns_convert_utf8_nfd_to_nfc,
2103        Sns_convert_utf8_nfd_to_nfc, 1, 1, 0,
2104        doc: /* Return an NFC string that matches the UTF-8 NFD string STR.  */)
2105      (Lisp_Object str)
2107 /* TODO: If GNUstep ever implements precomposedStringWithCanonicalMapping,
2108          remove this. */
2109   NSString *utfStr;
2110   Lisp_Object ret = Qnil;
2111   NSAutoreleasePool *pool;
2113   CHECK_STRING (str);
2114   pool = [[NSAutoreleasePool alloc] init];
2115   utfStr = [NSString stringWithUTF8String: SSDATA (str)];
2116 #ifdef NS_IMPL_COCOA
2117   if (utfStr)
2118     utfStr = [utfStr precomposedStringWithCanonicalMapping];
2119 #endif
2120   if (utfStr)
2121     {
2122       const char *cstr = [utfStr UTF8String];
2123       if (cstr)
2124         ret = build_string (cstr);
2125     }
2127   [pool release];
2128   if (NILP (ret))
2129     error ("Invalid UTF-8");
2131   return ret;
2135 #ifdef NS_IMPL_COCOA
2137 /* Compile and execute the AppleScript SCRIPT and return the error
2138    status as function value.  A zero is returned if compilation and
2139    execution is successful, in which case *RESULT is set to a Lisp
2140    string or a number containing the resulting script value.  Otherwise,
2141    1 is returned. */
2142 static int
2143 ns_do_applescript (Lisp_Object script, Lisp_Object *result)
2145   NSAppleEventDescriptor *desc;
2146   NSDictionary* errorDict;
2147   NSAppleEventDescriptor* returnDescriptor = NULL;
2149   NSAppleScript* scriptObject =
2150     [[NSAppleScript alloc] initWithSource:
2151                              [NSString stringWithUTF8String: SSDATA (script)]];
2153   returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
2154   [scriptObject release];
2155   *result = Qnil;
2157   if (returnDescriptor != NULL)
2158     {
2159       // successful execution
2160       if (kAENullEvent != [returnDescriptor descriptorType])
2161         {
2162           *result = Qt;
2163           // script returned an AppleScript result
2164           if ((typeUnicodeText == [returnDescriptor descriptorType]) ||
2165 #if defined (NS_IMPL_COCOA)
2166               (typeUTF16ExternalRepresentation
2167                == [returnDescriptor descriptorType]) ||
2168 #endif
2169               (typeUTF8Text == [returnDescriptor descriptorType]) ||
2170               (typeCString == [returnDescriptor descriptorType]))
2171             {
2172               desc = [returnDescriptor coerceToDescriptorType: typeUTF8Text];
2173               if (desc)
2174                 *result = build_string([[desc stringValue] UTF8String]);
2175             }
2176           else
2177             {
2178               /* use typeUTF16ExternalRepresentation? */
2179               // coerce the result to the appropriate ObjC type
2180               desc = [returnDescriptor coerceToDescriptorType: typeUTF8Text];
2181               if (desc)
2182                 *result = make_number([desc int32Value]);
2183             }
2184         }
2185     }
2186   else
2187     {
2188       // no script result, return error
2189       return 1;
2190     }
2191   return 0;
2194 /* Helper function called from sendEvent to run applescript
2195    from within the main event loop.  */
2197 void
2198 ns_run_ascript (void)
2200   if (! NILP (as_script))
2201     as_status = ns_do_applescript (as_script, as_result);
2202   as_script = Qnil;
2205 DEFUN ("ns-do-applescript", Fns_do_applescript, Sns_do_applescript, 1, 1, 0,
2206        doc: /* Execute AppleScript SCRIPT and return the result.
2207 If compilation and execution are successful, the resulting script value
2208 is returned as a string, a number or, in the case of other constructs, t.
2209 In case the execution fails, an error is signaled. */)
2210      (Lisp_Object script)
2212   Lisp_Object result;
2213   int status;
2214   NSEvent *nxev;
2215   struct input_event ev;
2217   CHECK_STRING (script);
2218   check_window_system (NULL);
2220   block_input ();
2222   as_script = script;
2223   as_result = &result;
2225   /* executing apple script requires the event loop to run, otherwise
2226      errors aren't returned and executeAndReturnError hangs forever.
2227      Post an event that runs applescript and then start the event loop.
2228      The event loop is exited when the script is done.  */
2229   nxev = [NSEvent otherEventWithType: NSApplicationDefined
2230                             location: NSMakePoint (0, 0)
2231                        modifierFlags: 0
2232                            timestamp: 0
2233                         windowNumber: [[NSApp mainWindow] windowNumber]
2234                              context: [NSApp context]
2235                              subtype: 0
2236                                data1: 0
2237                                data2: NSAPP_DATA2_RUNASSCRIPT];
2239   [NSApp postEvent: nxev atStart: NO];
2241   // If there are other events, the event loop may exit.  Keep running
2242   // until the script has been handled.  */
2243   ns_init_events (&ev);
2244   while (! NILP (as_script))
2245     [NSApp run];
2246   ns_finish_events ();
2248   status = as_status;
2249   as_status = 0;
2250   as_result = 0;
2251   unblock_input ();
2252   if (status == 0)
2253     return result;
2254   else if (!STRINGP (result))
2255     error ("AppleScript error %d", status);
2256   else
2257     error ("%s", SSDATA (result));
2259 #endif
2263 /* ==========================================================================
2265     Miscellaneous functions not called through hooks
2267    ========================================================================== */
2269 /* called from frame.c */
2270 struct ns_display_info *
2271 check_x_display_info (Lisp_Object frame)
2273   return check_ns_display_info (frame);
2277 void
2278 x_set_scroll_bar_default_width (struct frame *f)
2280   int wid = FRAME_COLUMN_WIDTH (f);
2281   FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = NS_SCROLL_BAR_WIDTH_DEFAULT;
2282   FRAME_CONFIG_SCROLL_BAR_COLS (f) = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) +
2283                                       wid - 1) / wid;
2286 void
2287 x_set_scroll_bar_default_height (struct frame *f)
2289   int height = FRAME_LINE_HEIGHT (f);
2290   FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) = NS_SCROLL_BAR_WIDTH_DEFAULT;
2291   FRAME_CONFIG_SCROLL_BAR_LINES (f) = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) +
2292                                        height - 1) / height;
2295 /* terms impl this instead of x-get-resource directly */
2296 char *
2297 x_get_string_resource (XrmDatabase rdb, const char *name, const char *class)
2299   /* remove appname prefix; TODO: allow for !="Emacs" */
2300   const char *res, *toCheck = class + (!strncmp (class, "Emacs.", 6) ? 6 : 0);
2302   check_window_system (NULL);
2304   if (inhibit_x_resources)
2305     /* --quick was passed, so this is a no-op.  */
2306     return NULL;
2308   res = ns_get_defaults_value (toCheck);
2309   return (!res ? NULL :
2310           (!c_strncasecmp (res, "YES", 3) ? "true" :
2311            (!c_strncasecmp (res, "NO", 2) ? "false" : (char *) res)));
2315 Lisp_Object
2316 x_get_focus_frame (struct frame *frame)
2318   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
2319   Lisp_Object nsfocus;
2321   if (!dpyinfo->x_focus_frame)
2322     return Qnil;
2324   XSETFRAME (nsfocus, dpyinfo->x_focus_frame);
2325   return nsfocus;
2328 /* ==========================================================================
2330     Lisp definitions that, for whatever reason, we can't alias as 'ns-XXX'.
2332    ========================================================================== */
2335 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
2336        doc: /* Internal function called by `color-defined-p', which see.
2337 (Note that the Nextstep version of this function ignores FRAME.)  */)
2338      (Lisp_Object color, Lisp_Object frame)
2340   NSColor * col;
2341   check_window_system (NULL);
2342   return ns_lisp_to_color (color, &col) ? Qnil : Qt;
2346 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
2347        doc: /* Internal function called by `color-values', which see.  */)
2348      (Lisp_Object color, Lisp_Object frame)
2350   NSColor * col;
2351   EmacsCGFloat red, green, blue, alpha;
2353   check_window_system (NULL);
2354   CHECK_STRING (color);
2356   block_input ();
2357   if (ns_lisp_to_color (color, &col))
2358     {
2359       unblock_input ();
2360       return Qnil;
2361     }
2363   [[col colorUsingDefaultColorSpace]
2364         getRed: &red green: &green blue: &blue alpha: &alpha];
2365   unblock_input ();
2366   return list3i (lrint (red * 65280), lrint (green * 65280),
2367                  lrint (blue * 65280));
2371 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
2372        doc: /* Internal function called by `display-color-p', which see.  */)
2373      (Lisp_Object terminal)
2375   NSWindowDepth depth;
2376   NSString *colorSpace;
2378   check_ns_display_info (terminal);
2379   depth = [[[NSScreen screens] objectAtIndex:0] depth];
2380   colorSpace = NSColorSpaceFromDepth (depth);
2382   return    [colorSpace isEqualToString: NSDeviceWhiteColorSpace]
2383          || [colorSpace isEqualToString: NSCalibratedWhiteColorSpace]
2384       ? Qnil : Qt;
2388 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p, Sx_display_grayscale_p,
2389        0, 1, 0,
2390        doc: /* Return t if the Nextstep display supports shades of gray.
2391 Note that color displays do support shades of gray.
2392 The optional argument TERMINAL specifies which display to ask about.
2393 TERMINAL should be a terminal object, a frame or a display name (a string).
2394 If omitted or nil, that stands for the selected frame's display.  */)
2395   (Lisp_Object terminal)
2397   NSWindowDepth depth;
2399   check_ns_display_info (terminal);
2400   depth = [[[NSScreen screens] objectAtIndex:0] depth];
2402   return NSBitsPerPixelFromDepth (depth) > 1 ? Qt : Qnil;
2406 DEFUN ("x-display-pixel-width", Fx_display_pixel_width, Sx_display_pixel_width,
2407        0, 1, 0,
2408        doc: /* Return the width in pixels of the Nextstep display TERMINAL.
2409 The optional argument TERMINAL specifies which display to ask about.
2410 TERMINAL should be a terminal object, a frame or a display name (a string).
2411 If omitted or nil, that stands for the selected frame's display.
2413 On \"multi-monitor\" setups this refers to the pixel width for all
2414 physical monitors associated with TERMINAL.  To get information for
2415 each physical monitor, use `display-monitor-attributes-list'.  */)
2416   (Lisp_Object terminal)
2418   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
2420   return make_number (x_display_pixel_width (dpyinfo));
2424 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
2425        Sx_display_pixel_height, 0, 1, 0,
2426        doc: /* Return the height in pixels of the Nextstep display TERMINAL.
2427 The optional argument TERMINAL specifies which display to ask about.
2428 TERMINAL should be a terminal object, a frame or a display name (a string).
2429 If omitted or nil, that stands for the selected frame's display.
2431 On \"multi-monitor\" setups this refers to the pixel height for all
2432 physical monitors associated with TERMINAL.  To get information for
2433 each physical monitor, use `display-monitor-attributes-list'.  */)
2434   (Lisp_Object terminal)
2436   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
2438   return make_number (x_display_pixel_height (dpyinfo));
2441 #ifdef NS_IMPL_COCOA
2443 /* Returns the name for the screen that OBJ represents, or NULL.
2444    Caller must free return value.
2447 static char *
2448 ns_get_name_from_ioreg (io_object_t obj)
2450   char *name = NULL;
2452   NSDictionary *info = (NSDictionary *)
2453     IODisplayCreateInfoDictionary (obj, kIODisplayOnlyPreferredName);
2454   NSDictionary *names = [info objectForKey:
2455                                 [NSString stringWithUTF8String:
2456                                             kDisplayProductName]];
2458   if ([names count] > 0)
2459     {
2460       NSString *n = [names objectForKey: [[names allKeys]
2461                                                  objectAtIndex:0]];
2462       if (n != nil) name = xstrdup ([n UTF8String]);
2463     }
2465   [info release];
2467   return name;
2470 /* Returns the name for the screen that DID came from, or NULL.
2471    Caller must free return value.
2474 static char *
2475 ns_screen_name (CGDirectDisplayID did)
2477   char *name = NULL;
2479 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
2480   mach_port_t masterPort;
2481   io_iterator_t it;
2482   io_object_t obj;
2484   // CGDisplayIOServicePort is deprecated.  Do it another (harder) way.
2486   if (IOMasterPort (MACH_PORT_NULL, &masterPort) != kIOReturnSuccess
2487       || IOServiceGetMatchingServices (masterPort,
2488                                        IOServiceMatching ("IONDRVDevice"),
2489                                        &it) != kIOReturnSuccess)
2490     return name;
2492   /* Must loop until we find a name.  Many devices can have the same unit
2493      number (represents different GPU parts), but only one has a name.  */
2494   while (! name && (obj = IOIteratorNext (it)))
2495     {
2496       CFMutableDictionaryRef props;
2497       const void *val;
2499       if (IORegistryEntryCreateCFProperties (obj,
2500                                              &props,
2501                                              kCFAllocatorDefault,
2502                                              kNilOptions) == kIOReturnSuccess
2503           && props != nil
2504           && (val = CFDictionaryGetValue(props, @"IOFBDependentIndex")))
2505         {
2506           unsigned nr = [(NSNumber *)val unsignedIntegerValue];
2507           if (nr == CGDisplayUnitNumber (did))
2508             name = ns_get_name_from_ioreg (obj);
2509         }
2511       CFRelease (props);
2512       IOObjectRelease (obj);
2513     }
2515   IOObjectRelease (it);
2517 #else
2519   name = ns_get_name_from_ioreg (CGDisplayIOServicePort (did));
2521 #endif
2522   return name;
2524 #endif
2526 static Lisp_Object
2527 ns_make_monitor_attribute_list (struct MonitorInfo *monitors,
2528                                 int n_monitors,
2529                                 int primary_monitor,
2530                                 const char *source)
2532   Lisp_Object monitor_frames = Fmake_vector (make_number (n_monitors), Qnil);
2533   Lisp_Object frame, rest;
2534   NSArray *screens = [NSScreen screens];
2535   int i;
2537   FOR_EACH_FRAME (rest, frame)
2538     {
2539       struct frame *f = XFRAME (frame);
2541       if (FRAME_NS_P (f))
2542         {
2543           NSView *view = FRAME_NS_VIEW (f);
2544           NSScreen *screen = [[view window] screen];
2545           NSUInteger k;
2547           i = -1;
2548           for (k = 0; i == -1 && k < [screens count]; ++k)
2549             {
2550               if ([screens objectAtIndex: k] == screen)
2551                 i = (int)k;
2552             }
2554           if (i > -1)
2555             ASET (monitor_frames, i, Fcons (frame, AREF (monitor_frames, i)));
2556         }
2557     }
2559   return make_monitor_attribute_list (monitors, n_monitors, primary_monitor,
2560                                       monitor_frames, source);
2563 DEFUN ("ns-display-monitor-attributes-list",
2564        Fns_display_monitor_attributes_list,
2565        Sns_display_monitor_attributes_list,
2566        0, 1, 0,
2567        doc: /* Return a list of physical monitor attributes on the X display TERMINAL.
2569 The optional argument TERMINAL specifies which display to ask about.
2570 TERMINAL should be a terminal object, a frame or a display name (a string).
2571 If omitted or nil, that stands for the selected frame's display.
2573 In addition to the standard attribute keys listed in
2574 `display-monitor-attributes-list', the following keys are contained in
2575 the attributes:
2577  source -- String describing the source from which multi-monitor
2578            information is obtained, \"NS\" is always the source."
2580 Internal use only, use `display-monitor-attributes-list' instead.  */)
2581   (Lisp_Object terminal)
2583   struct terminal *term = decode_live_terminal (terminal);
2584   NSArray *screens;
2585   NSUInteger i, n_monitors;
2586   struct MonitorInfo *monitors;
2587   Lisp_Object attributes_list = Qnil;
2588   CGFloat primary_display_height = 0;
2590   if (term->type != output_ns)
2591     return Qnil;
2593   screens = [NSScreen screens];
2594   n_monitors = [screens count];
2595   if (n_monitors == 0)
2596     return Qnil;
2598   monitors = xzalloc (n_monitors * sizeof *monitors);
2600   for (i = 0; i < [screens count]; ++i)
2601     {
2602       NSScreen *s = [screens objectAtIndex:i];
2603       struct MonitorInfo *m = &monitors[i];
2604       NSRect fr = [s frame];
2605       NSRect vfr = [s visibleFrame];
2606       short y, vy;
2608 #ifdef NS_IMPL_COCOA
2609       NSDictionary *dict = [s deviceDescription];
2610       NSNumber *nid = [dict objectForKey:@"NSScreenNumber"];
2611       CGDirectDisplayID did = [nid unsignedIntValue];
2612 #endif
2613       if (i == 0)
2614         {
2615           primary_display_height = fr.size.height;
2616           y = (short) fr.origin.y;
2617           vy = (short) vfr.origin.y;
2618         }
2619       else
2620         {
2621           // Flip y coordinate as NS has y starting from the bottom.
2622           y = (short) (primary_display_height - fr.size.height - fr.origin.y);
2623           vy = (short) (primary_display_height -
2624                         vfr.size.height - vfr.origin.y);
2625         }
2627       m->geom.x = (short) fr.origin.x;
2628       m->geom.y = y;
2629       m->geom.width = (unsigned short) fr.size.width;
2630       m->geom.height = (unsigned short) fr.size.height;
2632       m->work.x = (short) vfr.origin.x;
2633       // y is flipped on NS, so vy - y are pixels missing at the bottom,
2634       // and fr.size.height - vfr.size.height are pixels missing in total.
2635       // Pixels missing at top are
2636       // fr.size.height - vfr.size.height - vy + y.
2637       // work.y is then pixels missing at top + y.
2638       m->work.y = (short) (fr.size.height - vfr.size.height) - vy + y + y;
2639       m->work.width = (unsigned short) vfr.size.width;
2640       m->work.height = (unsigned short) vfr.size.height;
2642 #ifdef NS_IMPL_COCOA
2643       m->name = ns_screen_name (did);
2645       {
2646         CGSize mms = CGDisplayScreenSize (did);
2647         m->mm_width = (int) mms.width;
2648         m->mm_height = (int) mms.height;
2649       }
2651 #else
2652       // Assume 92 dpi as x-display-mm-height/x-display-mm-width does.
2653       m->mm_width = (int) (25.4 * fr.size.width / 92.0);
2654       m->mm_height = (int) (25.4 * fr.size.height / 92.0);
2655 #endif
2656     }
2658   // Primary monitor is always first for NS.
2659   attributes_list = ns_make_monitor_attribute_list (monitors, n_monitors,
2660                                                     0, "NS");
2662   free_monitors (monitors, n_monitors);
2663   return attributes_list;
2667 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
2668        0, 1, 0,
2669        doc: /* Return the number of bitplanes of the Nextstep display TERMINAL.
2670 The optional argument TERMINAL specifies which display to ask about.
2671 TERMINAL should be a terminal object, a frame or a display name (a string).
2672 If omitted or nil, that stands for the selected frame's display.  */)
2673   (Lisp_Object terminal)
2675   check_ns_display_info (terminal);
2676   return make_number
2677     (NSBitsPerPixelFromDepth ([[[NSScreen screens] objectAtIndex:0] depth]));
2681 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
2682        0, 1, 0,
2683        doc: /* Returns the number of color cells of the Nextstep display TERMINAL.
2684 The optional argument TERMINAL specifies which display to ask about.
2685 TERMINAL should be a terminal object, a frame or a display name (a string).
2686 If omitted or nil, that stands for the selected frame's display.  */)
2687   (Lisp_Object terminal)
2689   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
2690   /* We force 24+ bit depths to 24-bit to prevent an overflow.  */
2691   return make_number (1 << min (dpyinfo->n_planes, 24));
2695 /* Unused dummy def needed for compatibility. */
2696 Lisp_Object tip_frame;
2698 /* TODO: move to xdisp or similar */
2699 static void
2700 compute_tip_xy (struct frame *f,
2701                 Lisp_Object parms,
2702                 Lisp_Object dx,
2703                 Lisp_Object dy,
2704                 int width,
2705                 int height,
2706                 int *root_x,
2707                 int *root_y)
2709   Lisp_Object left, top, right, bottom;
2710   EmacsView *view = FRAME_NS_VIEW (f);
2711   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2712   NSPoint pt;
2714   /* Start with user-specified or mouse position.  */
2715   left = Fcdr (Fassq (Qleft, parms));
2716   top = Fcdr (Fassq (Qtop, parms));
2717   right = Fcdr (Fassq (Qright, parms));
2718   bottom = Fcdr (Fassq (Qbottom, parms));
2720   if ((!INTEGERP (left) && !INTEGERP (right))
2721       || (!INTEGERP (top) && !INTEGERP (bottom)))
2722     {
2723       pt.x = dpyinfo->last_mouse_motion_x;
2724       pt.y = dpyinfo->last_mouse_motion_y;
2725       /* Convert to screen coordinates */
2726       pt = [view convertPoint: pt toView: nil];
2727 #if !defined (NS_IMPL_COCOA) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
2728       pt = [[view window] convertBaseToScreen: pt];
2729 #else
2730       {
2731         NSRect r = NSMakeRect (pt.x, pt.y, 0, 0);
2732         r = [[view window] convertRectToScreen: r];
2733         pt.x = r.origin.x;
2734         pt.y = r.origin.y;
2735       }
2736 #endif
2737     }
2738   else
2739     {
2740       /* Absolute coordinates.  */
2741       pt.x = INTEGERP (left) ? XINT (left) : XINT (right);
2742       pt.y = (x_display_pixel_height (FRAME_DISPLAY_INFO (f))
2743               - (INTEGERP (top) ? XINT (top) : XINT (bottom))
2744               - height);
2745     }
2747   /* Ensure in bounds.  (Note, screen origin = lower left.) */
2748   if (INTEGERP (left) || INTEGERP (right))
2749     *root_x = pt.x;
2750   else if (pt.x + XINT (dx) <= 0)
2751     *root_x = 0; /* Can happen for negative dx */
2752   else if (pt.x + XINT (dx) + width
2753            <= x_display_pixel_width (FRAME_DISPLAY_INFO (f)))
2754     /* It fits to the right of the pointer.  */
2755     *root_x = pt.x + XINT (dx);
2756   else if (width + XINT (dx) <= pt.x)
2757     /* It fits to the left of the pointer.  */
2758     *root_x = pt.x - width - XINT (dx);
2759   else
2760     /* Put it left justified on the screen -- it ought to fit that way.  */
2761     *root_x = 0;
2763   if (INTEGERP (top) || INTEGERP (bottom))
2764     *root_y = pt.y;
2765   else if (pt.y - XINT (dy) - height >= 0)
2766     /* It fits below the pointer.  */
2767     *root_y = pt.y - height - XINT (dy);
2768   else if (pt.y + XINT (dy) + height
2769            <= x_display_pixel_height (FRAME_DISPLAY_INFO (f)))
2770     /* It fits above the pointer */
2771       *root_y = pt.y + XINT (dy);
2772   else
2773     /* Put it on the top.  */
2774     *root_y = x_display_pixel_height (FRAME_DISPLAY_INFO (f)) - height;
2778 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
2779        doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
2780 A tooltip window is a small window displaying a string.
2782 This is an internal function; Lisp code should call `tooltip-show'.
2784 FRAME nil or omitted means use the selected frame.
2786 PARMS is an optional list of frame parameters which can be used to
2787 change the tooltip's appearance.
2789 Automatically hide the tooltip after TIMEOUT seconds.  TIMEOUT nil
2790 means use the default timeout of 5 seconds.
2792 If the list of frame parameters PARMS contains a `left' parameter,
2793 display the tooltip at that x-position.  If the list of frame parameters
2794 PARMS contains no `left' but a `right' parameter, display the tooltip
2795 right-adjusted at that x-position. Otherwise display it at the
2796 x-position of the mouse, with offset DX added (default is 5 if DX isn't
2797 specified).
2799 Likewise for the y-position: If a `top' frame parameter is specified, it
2800 determines the position of the upper edge of the tooltip window.  If a
2801 `bottom' parameter but no `top' frame parameter is specified, it
2802 determines the position of the lower edge of the tooltip window.
2803 Otherwise display the tooltip window at the y-position of the mouse,
2804 with offset DY added (default is -10).
2806 A tooltip's maximum size is specified by `x-max-tooltip-size'.
2807 Text larger than the specified size is clipped.  */)
2808      (Lisp_Object string, Lisp_Object frame, Lisp_Object parms, Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
2810   int root_x, root_y;
2811   ptrdiff_t count = SPECPDL_INDEX ();
2812   struct frame *f;
2813   char *str;
2814   NSSize size;
2816   specbind (Qinhibit_redisplay, Qt);
2818   CHECK_STRING (string);
2819   str = SSDATA (string);
2820   f = decode_window_system_frame (frame);
2821   if (NILP (timeout))
2822     timeout = make_number (5);
2823   else
2824     CHECK_NATNUM (timeout);
2826   if (NILP (dx))
2827     dx = make_number (5);
2828   else
2829     CHECK_NUMBER (dx);
2831   if (NILP (dy))
2832     dy = make_number (-10);
2833   else
2834     CHECK_NUMBER (dy);
2836   block_input ();
2837   if (ns_tooltip == nil)
2838     ns_tooltip = [[EmacsTooltip alloc] init];
2839   else
2840     Fx_hide_tip ();
2842   [ns_tooltip setText: str];
2843   size = [ns_tooltip frame].size;
2845   /* Move the tooltip window where the mouse pointer is.  Resize and
2846      show it.  */
2847   compute_tip_xy (f, parms, dx, dy, (int)size.width, (int)size.height,
2848                   &root_x, &root_y);
2850   [ns_tooltip showAtX: root_x Y: root_y for: XINT (timeout)];
2851   unblock_input ();
2853   return unbind_to (count, Qnil);
2857 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
2858        doc: /* Hide the current tooltip window, if there is any.
2859 Value is t if tooltip was open, nil otherwise.  */)
2860      (void)
2862   if (ns_tooltip == nil || ![ns_tooltip isActive])
2863     return Qnil;
2864   [ns_tooltip hide];
2865   return Qt;
2868 /* Return geometric attributes of FRAME.  According to the value of
2869    ATTRIBUTES return the outer edges of FRAME (Qouter_edges), the inner
2870    edges of FRAME, the root window edges of frame (Qroot_edges).  Any
2871    other value means to return the geometry as returned by
2872    Fx_frame_geometry.  */
2873 static Lisp_Object
2874 frame_geometry (Lisp_Object frame, Lisp_Object attribute)
2876   struct frame *f = decode_live_frame (frame);
2877   Lisp_Object fullscreen_symbol = Fframe_parameter (frame, Qfullscreen);
2878   bool fullscreen = (EQ (fullscreen_symbol, Qfullboth)
2879                      || EQ (fullscreen_symbol, Qfullscreen));
2880   int border = fullscreen ? 0 : f->border_width;
2881   int title_height = fullscreen ? 0 : FRAME_NS_TITLEBAR_HEIGHT (f);
2882   int native_width = FRAME_PIXEL_WIDTH (f);
2883   int native_height = FRAME_PIXEL_HEIGHT (f);
2884   int outer_width = native_width + 2 * border;
2885   int outer_height = native_height + 2 * border + title_height;
2886   int native_left = f->left_pos + border;
2887   int native_top = f->top_pos + border + title_height;
2888   int native_right = f->left_pos + outer_width - border;
2889   int native_bottom = f->top_pos + outer_height - border;
2890   int internal_border_width = FRAME_INTERNAL_BORDER_WIDTH (f);
2891   int tool_bar_height = FRAME_TOOLBAR_HEIGHT (f);
2892   int tool_bar_width = (tool_bar_height
2893                         ? outer_width - 2 * internal_border_width
2894                         : 0);
2896   /* Construct list.  */
2897   if (EQ (attribute, Qouter_edges))
2898     return list4 (make_number (f->left_pos), make_number (f->top_pos),
2899                   make_number (f->left_pos + outer_width),
2900                   make_number (f->top_pos + outer_height));
2901   else if (EQ (attribute, Qnative_edges))
2902     return list4 (make_number (native_left), make_number (native_top),
2903                   make_number (native_right), make_number (native_bottom));
2904   else if (EQ (attribute, Qinner_edges))
2905     return list4 (make_number (native_left + internal_border_width),
2906                   make_number (native_top
2907                                + tool_bar_height
2908                                + internal_border_width),
2909                   make_number (native_right - internal_border_width),
2910                   make_number (native_bottom - internal_border_width));
2911   else
2912     return
2913       listn (CONSTYPE_HEAP, 10,
2914              Fcons (Qouter_position,
2915                     Fcons (make_number (f->left_pos),
2916                            make_number (f->top_pos))),
2917              Fcons (Qouter_size,
2918                     Fcons (make_number (outer_width),
2919                            make_number (outer_height))),
2920              Fcons (Qexternal_border_size,
2921                     (fullscreen
2922                      ? Fcons (make_number (0), make_number (0))
2923                      : Fcons (make_number (border), make_number (border)))),
2924              Fcons (Qtitle_bar_size,
2925                     Fcons (make_number (0), make_number (title_height))),
2926              Fcons (Qmenu_bar_external, Qnil),
2927              Fcons (Qmenu_bar_size, Fcons (make_number (0), make_number (0))),
2928              Fcons (Qtool_bar_external,
2929                     FRAME_EXTERNAL_TOOL_BAR (f) ? Qt : Qnil),
2930              Fcons (Qtool_bar_position, FRAME_TOOL_BAR_POSITION (f)),
2931              Fcons (Qtool_bar_size,
2932                     Fcons (make_number (tool_bar_width),
2933                            make_number (tool_bar_height))),
2934              Fcons (Qinternal_border_width,
2935                     make_number (internal_border_width)));
2938 DEFUN ("ns-frame-geometry", Fns_frame_geometry, Sns_frame_geometry, 0, 1, 0,
2939        doc: /* Return geometric attributes of FRAME.
2940 FRAME must be a live frame and defaults to the selected one.  The return
2941 value is an association list of the attributes listed below.  All height
2942 and width values are in pixels.
2944 `outer-position' is a cons of the outer left and top edges of FRAME
2945   relative to the origin - the position (0, 0) - of FRAME's display.
2947 `outer-size' is a cons of the outer width and height of FRAME.  The
2948   outer size includes the title bar and the external borders as well as
2949   any menu and/or tool bar of frame.
2951 `external-border-size' is a cons of the horizontal and vertical width of
2952   FRAME's external borders as supplied by the window manager.
2954 `title-bar-size' is a cons of the width and height of the title bar of
2955   FRAME as supplied by the window manager.  If both of them are zero,
2956   FRAME has no title bar.  If only the width is zero, Emacs was not
2957   able to retrieve the width information.
2959 `menu-bar-external', if non-nil, means the menu bar is external (never
2960   included in the inner edges of FRAME).
2962 `menu-bar-size' is a cons of the width and height of the menu bar of
2963   FRAME.
2965 `tool-bar-external', if non-nil, means the tool bar is external (never
2966   included in the inner edges of FRAME).
2968 `tool-bar-position' tells on which side the tool bar on FRAME is and can
2969   be one of `left', `top', `right' or `bottom'.  If this is nil, FRAME
2970   has no tool bar.
2972 `tool-bar-size' is a cons of the width and height of the tool bar of
2973   FRAME.
2975 `internal-border-width' is the width of the internal border of
2976   FRAME.  */)
2977   (Lisp_Object frame)
2979   return frame_geometry (frame, Qnil);
2982 DEFUN ("ns-frame-edges", Fns_frame_edges, Sns_frame_edges, 0, 2, 0,
2983        doc: /* Return edge coordinates of FRAME.
2984 FRAME must be a live frame and defaults to the selected one.  The return
2985 value is a list of the form (LEFT, TOP, RIGHT, BOTTOM).  All values are
2986 in pixels relative to the origin - the position (0, 0) - of FRAME's
2987 display.
2989 If optional argument TYPE is the symbol `outer-edges', return the outer
2990 edges of FRAME.  The outer edges comprise the decorations of the window
2991 manager (like the title bar or external borders) as well as any external
2992 menu or tool bar of FRAME.  If optional argument TYPE is the symbol
2993 `native-edges' or nil, return the native edges of FRAME.  The native
2994 edges exclude the decorations of the window manager and any external
2995 menu or tool bar of FRAME.  If TYPE is the symbol `inner-edges', return
2996 the inner edges of FRAME.  These edges exclude title bar, any borders,
2997 menu bar or tool bar of FRAME.  */)
2998   (Lisp_Object frame, Lisp_Object type)
3000   return frame_geometry (frame, ((EQ (type, Qouter_edges)
3001                                   || EQ (type, Qinner_edges))
3002                                  ? type
3003                                  : Qnative_edges));
3006 /* ==========================================================================
3008     Class implementations
3010    ========================================================================== */
3013   Handle arrow/function/control keys and copy/paste/cut in file dialogs.
3014   Return YES if handled, NO if not.
3015  */
3016 static BOOL
3017 handlePanelKeys (NSSavePanel *panel, NSEvent *theEvent)
3019   NSString *s;
3020   int i;
3021   BOOL ret = NO;
3023   if ([theEvent type] != NSKeyDown) return NO;
3024   s = [theEvent characters];
3026   for (i = 0; i < [s length]; ++i)
3027     {
3028       int ch = (int) [s characterAtIndex: i];
3029       switch (ch)
3030         {
3031         case NSHomeFunctionKey:
3032         case NSDownArrowFunctionKey:
3033         case NSUpArrowFunctionKey:
3034         case NSLeftArrowFunctionKey:
3035         case NSRightArrowFunctionKey:
3036         case NSPageUpFunctionKey:
3037         case NSPageDownFunctionKey:
3038         case NSEndFunctionKey:
3039           /* Don't send command modified keys, as those are handled in the
3040              performKeyEquivalent method of the super class.
3041           */
3042           if (! ([theEvent modifierFlags] & NSCommandKeyMask))
3043             {
3044               [panel sendEvent: theEvent];
3045               ret = YES;
3046             }
3047           break;
3048           /* As we don't have the standard key commands for
3049              copy/paste/cut/select-all in our edit menu, we must handle
3050              them here.  TODO: handle Emacs key bindings for copy/cut/select-all
3051              here, paste works, because we have that in our Edit menu.
3052              I.e. refactor out code in nsterm.m, keyDown: to figure out the
3053              correct modifier.
3054           */
3055         case 'x': // Cut
3056         case 'c': // Copy
3057         case 'v': // Paste
3058         case 'a': // Select all
3059           if ([theEvent modifierFlags] & NSCommandKeyMask)
3060             {
3061               [NSApp sendAction:
3062                        (ch == 'x'
3063                         ? @selector(cut:)
3064                         : (ch == 'c'
3065                            ? @selector(copy:)
3066                            : (ch == 'v'
3067                               ? @selector(paste:)
3068                               : @selector(selectAll:))))
3069                              to:nil from:panel];
3070               ret = YES;
3071             }
3072         default:
3073           // Send all control keys, as the text field supports C-a, C-f, C-e
3074           // C-b and more.
3075           if ([theEvent modifierFlags] & NSControlKeyMask)
3076             {
3077               [panel sendEvent: theEvent];
3078               ret = YES;
3079             }
3080           break;
3081         }
3082     }
3085   return ret;
3088 @implementation EmacsSavePanel
3089 - (BOOL)performKeyEquivalent:(NSEvent *)theEvent
3091   BOOL ret = handlePanelKeys (self, theEvent);
3092   if (! ret)
3093     ret = [super performKeyEquivalent:theEvent];
3094   return ret;
3096 @end
3099 @implementation EmacsOpenPanel
3100 - (BOOL)performKeyEquivalent:(NSEvent *)theEvent
3102   // NSOpenPanel inherits NSSavePanel, so passing self is OK.
3103   BOOL ret = handlePanelKeys (self, theEvent);
3104   if (! ret)
3105     ret = [super performKeyEquivalent:theEvent];
3106   return ret;
3108 @end
3111 @implementation EmacsFileDelegate
3112 /* --------------------------------------------------------------------------
3113    Delegate methods for Open/Save panels
3114    -------------------------------------------------------------------------- */
3115 - (BOOL)panel: (id)sender isValidFilename: (NSString *)filename
3117   return YES;
3119 - (BOOL)panel: (id)sender shouldShowFilename: (NSString *)filename
3121   return YES;
3123 - (NSString *)panel: (id)sender userEnteredFilename: (NSString *)filename
3124           confirmed: (BOOL)okFlag
3126   return filename;
3128 @end
3130 #endif
3133 /* ==========================================================================
3135     Lisp interface declaration
3137    ========================================================================== */
3140 void
3141 syms_of_nsfns (void)
3143   DEFSYM (Qfontsize, "fontsize");
3144   DEFSYM (Qframe_title_format, "frame-title-format");
3145   DEFSYM (Qicon_title_format, "icon-title-format");
3147   DEFVAR_LISP ("ns-icon-type-alist", Vns_icon_type_alist,
3148                doc: /* Alist of elements (REGEXP . IMAGE) for images of icons associated to frames.
3149 If the title of a frame matches REGEXP, then IMAGE.tiff is
3150 selected as the image of the icon representing the frame when it's
3151 miniaturized.  If an element is t, then Emacs tries to select an icon
3152 based on the filetype of the visited file.
3154 The images have to be installed in a folder called English.lproj in the
3155 Emacs folder.  You have to restart Emacs after installing new icons.
3157 Example: Install an icon Gnus.tiff and execute the following code
3159   (setq ns-icon-type-alist
3160         (append ns-icon-type-alist
3161                 '((\"^\\\\*\\\\(Group\\\\*$\\\\|Summary \\\\|Article\\\\*$\\\\)\"
3162                    . \"Gnus\"))))
3164 When you miniaturize a Group, Summary or Article frame, Gnus.tiff will
3165 be used as the image of the icon representing the frame.  */);
3166   Vns_icon_type_alist = list1 (Qt);
3168   DEFVAR_LISP ("ns-version-string", Vns_version_string,
3169                doc: /* Toolkit version for NS Windowing.  */);
3170   Vns_version_string = ns_appkit_version_str ();
3172   defsubr (&Sns_read_file_name);
3173   defsubr (&Sns_get_resource);
3174   defsubr (&Sns_set_resource);
3175   defsubr (&Sxw_display_color_p); /* this and next called directly by C code */
3176   defsubr (&Sx_display_grayscale_p);
3177   defsubr (&Sns_font_name);
3178   defsubr (&Sns_list_colors);
3179 #ifdef NS_IMPL_COCOA
3180   defsubr (&Sns_do_applescript);
3181 #endif
3182   defsubr (&Sxw_color_defined_p);
3183   defsubr (&Sxw_color_values);
3184   defsubr (&Sx_server_max_request_size);
3185   defsubr (&Sx_server_vendor);
3186   defsubr (&Sx_server_version);
3187   defsubr (&Sx_display_pixel_width);
3188   defsubr (&Sx_display_pixel_height);
3189   defsubr (&Sns_display_monitor_attributes_list);
3190   defsubr (&Sns_frame_geometry);
3191   defsubr (&Sns_frame_edges);
3192   defsubr (&Sx_display_mm_width);
3193   defsubr (&Sx_display_mm_height);
3194   defsubr (&Sx_display_screens);
3195   defsubr (&Sx_display_planes);
3196   defsubr (&Sx_display_color_cells);
3197   defsubr (&Sx_display_visual_class);
3198   defsubr (&Sx_display_backing_store);
3199   defsubr (&Sx_display_save_under);
3200   defsubr (&Sx_create_frame);
3201   defsubr (&Sx_open_connection);
3202   defsubr (&Sx_close_connection);
3203   defsubr (&Sx_display_list);
3205   defsubr (&Sns_hide_others);
3206   defsubr (&Sns_hide_emacs);
3207   defsubr (&Sns_emacs_info_panel);
3208   defsubr (&Sns_list_services);
3209   defsubr (&Sns_perform_service);
3210   defsubr (&Sns_convert_utf8_nfd_to_nfc);
3211   defsubr (&Sns_popup_font_panel);
3212   defsubr (&Sns_popup_color_panel);
3214   defsubr (&Sx_show_tip);
3215   defsubr (&Sx_hide_tip);
3217   as_status = 0;
3218   as_script = Qnil;
3219   as_result = 0;