Fix misworded comment.
[emacs.git] / src / nsfns.m
bloba09011d84615e471142c1b9f939c160337d9c296
1 /* Functions for the NeXT/Open/GNUstep and MacOSX window system.
3 Copyright (C) 1989, 1992-1994, 2005-2006, 2008-2011
4   Free Software 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 <signal.h>
34 #include <math.h>
35 #include <setjmp.h>
37 #include "lisp.h"
38 #include "blockinput.h"
39 #include "nsterm.h"
40 #include "window.h"
41 #include "buffer.h"
42 #include "keyboard.h"
43 #include "termhooks.h"
44 #include "fontset.h"
45 #include "character.h"
46 #include "font.h"
48 #if 0
49 int fns_trace_num = 1;
50 #define NSTRACE(x)        fprintf (stderr, "%s:%d: [%d] " #x "\n",        \
51                                   __FILE__, __LINE__, ++fns_trace_num)
52 #else
53 #define NSTRACE(x)
54 #endif
56 #ifdef HAVE_NS
58 extern NSArray *ns_send_types, *ns_return_types, *ns_drag_types;
60 extern Lisp_Object Qforeground_color;
61 extern Lisp_Object Qbackground_color;
62 extern Lisp_Object Qcursor_color;
63 extern Lisp_Object Qinternal_border_width;
64 extern Lisp_Object Qvisibility;
65 extern Lisp_Object Qcursor_type;
66 extern Lisp_Object Qicon_type;
67 extern Lisp_Object Qicon_name;
68 extern Lisp_Object Qicon_left;
69 extern Lisp_Object Qicon_top;
70 extern Lisp_Object Qleft;
71 extern Lisp_Object Qright;
72 extern Lisp_Object Qtop;
73 extern Lisp_Object Qdisplay;
74 extern Lisp_Object Qvertical_scroll_bars;
75 extern Lisp_Object Qauto_raise;
76 extern Lisp_Object Qauto_lower;
77 extern Lisp_Object Qbox;
78 extern Lisp_Object Qscroll_bar_width;
79 extern Lisp_Object Qx_resource_name;
80 extern Lisp_Object Qface_set_after_frame_default;
81 extern Lisp_Object Qunderline, Qundefined;
82 extern Lisp_Object Qheight, Qminibuffer, Qname, Qonly, Qwidth;
83 extern Lisp_Object Qunsplittable, Qmenu_bar_lines, Qbuffer_predicate, Qtitle;
84 extern Lisp_Object Qnone;
87 Lisp_Object Qbuffered;
88 Lisp_Object Qfontsize;
90 /* hack for OS X file panels */
91 char panelOK = 0;
93 EmacsTooltip *ns_tooltip;
95 /* Need forward declaration here to preserve organizational integrity of file */
96 Lisp_Object Fx_open_connection (Lisp_Object, Lisp_Object, Lisp_Object);
98 extern BOOL ns_in_resize;
100 /* Static variables to handle applescript execution.  */
101 static Lisp_Object as_script, *as_result;
102 static int as_status;
104 /* ==========================================================================
106     Internal utility functions
108    ========================================================================== */
111 void
112 check_ns (void)
114  if (NSApp == nil)
115    error ("OpenStep is not in use or not initialized");
119 /* Nonzero if we can use mouse menus. */
121 have_menus_p (void)
123   return NSApp != nil;
127 /* Extract a frame as a FRAME_PTR, defaulting to the selected frame
128    and checking validity for NS.  */
129 static FRAME_PTR
130 check_ns_frame (Lisp_Object frame)
132   FRAME_PTR f;
134   if (NILP (frame))
135       f = SELECTED_FRAME ();
136   else
137     {
138       CHECK_LIVE_FRAME (frame);
139       f = XFRAME (frame);
140     }
141   if (! FRAME_NS_P (f))
142     error ("non-Nextstep frame used");
143   return f;
147 /* Let the user specify an Nextstep display with a frame.
148    nil stands for the selected frame--or, if that is not an Nextstep frame,
149    the first Nextstep display on the list.  */
150 static struct ns_display_info *
151 check_ns_display_info (Lisp_Object frame)
153   if (NILP (frame))
154     {
155       struct frame *f = SELECTED_FRAME ();
156       if (FRAME_NS_P (f) && FRAME_LIVE_P (f) )
157         return FRAME_NS_DISPLAY_INFO (f);
158       else if (x_display_list != 0)
159         return x_display_list;
160       else
161         error ("Nextstep windows are not in use or not initialized");
162     }
163   else if (INTEGERP (frame))
164     {
165       struct terminal *t = get_terminal (frame, 1);
167       if (t->type != output_ns)
168         error ("Terminal %ld is not a Nextstep display", (long) XINT (frame));
170       return t->display_info.ns;
171     }
172   else if (STRINGP (frame))
173     return ns_display_info_for_name (frame);
174   else
175     {
176       FRAME_PTR f;
178       CHECK_LIVE_FRAME (frame);
179       f = XFRAME (frame);
180       if (! FRAME_NS_P (f))
181         error ("non-Nextstep frame used");
182       return FRAME_NS_DISPLAY_INFO (f);
183     }
184   return NULL;  /* shut compiler up */
188 static id
189 ns_get_window (Lisp_Object maybeFrame)
191   id view =nil, window =nil;
193   if (!FRAMEP (maybeFrame) || !FRAME_NS_P (XFRAME (maybeFrame)))
194     maybeFrame = selected_frame;/*wrong_type_argument (Qframep, maybeFrame); */
196   if (!NILP (maybeFrame))
197     view = FRAME_NS_VIEW (XFRAME (maybeFrame));
198   if (view) window =[view window];
200   return window;
204 static NSScreen *
205 ns_get_screen (Lisp_Object screen)
207   struct frame *f;
208   struct terminal *terminal;
210   if (EQ (Qt, screen)) /* not documented */
211     return [NSScreen mainScreen];
213   terminal = get_terminal (screen, 1);
214   if (terminal->type != output_ns)
215     return NULL;
217   if (NILP (screen))
218     f = SELECTED_FRAME ();
219   else if (FRAMEP (screen))
220     f = XFRAME (screen);
221   else
222     {
223       struct ns_display_info *dpyinfo = terminal->display_info.ns;
224       f = dpyinfo->x_focus_frame
225         ? dpyinfo->x_focus_frame : dpyinfo->x_highlight_frame;
226     }
228   return ((f && FRAME_NS_P (f)) ? [[FRAME_NS_VIEW (f) window] screen]
229           : NULL);
233 /* Return the X display structure for the display named NAME.
234    Open a new connection if necessary.  */
235 struct ns_display_info *
236 ns_display_info_for_name (Lisp_Object name)
238   Lisp_Object names;
239   struct ns_display_info *dpyinfo;
241   CHECK_STRING (name);
243   for (dpyinfo = x_display_list, names = ns_display_name_list;
244        dpyinfo;
245        dpyinfo = dpyinfo->next, names = XCDR (names))
246     {
247       Lisp_Object tem;
248       tem = Fstring_equal (XCAR (XCAR (names)), name);
249       if (!NILP (tem))
250         return dpyinfo;
251     }
253   error ("Emacs for OpenStep does not yet support multi-display.");
255   Fx_open_connection (name, Qnil, Qnil);
256   dpyinfo = x_display_list;
258   if (dpyinfo == 0)
259     error ("OpenStep on %s not responding.\n", SDATA (name));
261   return dpyinfo;
265 static Lisp_Object
266 interpret_services_menu (NSMenu *menu, Lisp_Object prefix, Lisp_Object old)
267 /* --------------------------------------------------------------------------
268    Turn the input menu (an NSMenu) into a lisp list for tracking on lisp side
269    -------------------------------------------------------------------------- */
271   int i, count;
272   NSMenuItem *item;
273   const char *name;
274   Lisp_Object nameStr;
275   unsigned short key;
276   NSString *keys;
277   Lisp_Object res;
279   count = [menu numberOfItems];
280   for (i = 0; i<count; i++)
281     {
282       item = [menu itemAtIndex: i];
283       name = [[item title] UTF8String];
284       if (!name) continue;
286       nameStr = build_string (name);
288       if ([item hasSubmenu])
289         {
290           old = interpret_services_menu ([item submenu],
291                                         Fcons (nameStr, prefix), old);
292         }
293       else
294         {
295           keys = [item keyEquivalent];
296           if (keys && [keys length] )
297             {
298               key = [keys characterAtIndex: 0];
299               res = make_number (key|super_modifier);
300             }
301           else
302             {
303               res = Qundefined;
304             }
305           old = Fcons (Fcons (res,
306                             Freverse (Fcons (nameStr,
307                                            prefix))),
308                     old);
309         }
310     }
311   return old;
316 /* ==========================================================================
318     Frame parameter setters
320    ========================================================================== */
323 static void
324 x_set_foreground_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
326   NSColor *col;
327   CGFloat r, g, b, alpha;
329   if (ns_lisp_to_color (arg, &col))
330     {
331       store_frame_param (f, Qforeground_color, oldval);
332       error ("Unknown color");
333     }
335   [col retain];
336   [f->output_data.ns->foreground_color release];
337   f->output_data.ns->foreground_color = col;
339   [col getRed: &r green: &g blue: &b alpha: &alpha];
340   FRAME_FOREGROUND_PIXEL (f) =
341     ARGB_TO_ULONG ((int)(alpha*0xff), (int)(r*0xff), (int)(g*0xff), (int)(b*0xff));
343   if (FRAME_NS_VIEW (f))
344     {
345       update_face_from_frame_parameter (f, Qforeground_color, arg);
346       /*recompute_basic_faces (f); */
347       if (FRAME_VISIBLE_P (f))
348         redraw_frame (f);
349     }
353 static void
354 x_set_background_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
356   struct face *face;
357   NSColor *col;
358   NSView *view = FRAME_NS_VIEW (f);
359   CGFloat r, g, b, alpha;
361   if (ns_lisp_to_color (arg, &col))
362     {
363       store_frame_param (f, Qbackground_color, oldval);
364       error ("Unknown color");
365     }
367   /* clear the frame; in some instances the NS-internal GC appears not to
368      update, or it does update and cannot clear old text properly */
369   if (FRAME_VISIBLE_P (f))
370     ns_clear_frame (f);
372   [col retain];
373   [f->output_data.ns->background_color release];
374   f->output_data.ns->background_color = col;
376   [col getRed: &r green: &g blue: &b alpha: &alpha];
377   FRAME_BACKGROUND_PIXEL (f) =
378     ARGB_TO_ULONG ((int)(alpha*0xff), (int)(r*0xff), (int)(g*0xff), (int)(b*0xff));
380   if (view != nil)
381     {
382       [[view window] setBackgroundColor: col];
384       if (alpha != 1.0)
385           [[view window] setOpaque: NO];
386       else
387           [[view window] setOpaque: YES];
389       face = FRAME_DEFAULT_FACE (f);
390       if (face)
391         {
392           col = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f);
393           face->background
394              = (EMACS_UINT) [[col colorWithAlphaComponent: alpha] retain];
395           [col release];
397           update_face_from_frame_parameter (f, Qbackground_color, arg);
398         }
400       if (FRAME_VISIBLE_P (f))
401         redraw_frame (f);
402     }
406 static void
407 x_set_cursor_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
409   NSColor *col;
411   if (ns_lisp_to_color (arg, &col))
412     {
413       store_frame_param (f, Qcursor_color, oldval);
414       error ("Unknown color");
415     }
417   [FRAME_CURSOR_COLOR (f) release];
418   FRAME_CURSOR_COLOR (f) = [col retain];
420   if (FRAME_VISIBLE_P (f))
421     {
422       x_update_cursor (f, 0);
423       x_update_cursor (f, 1);
424     }
425   update_face_from_frame_parameter (f, Qcursor_color, arg);
429 static void
430 x_set_icon_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
432   NSView *view = FRAME_NS_VIEW (f);
433   NSTRACE (x_set_icon_name);
435   if (ns_in_resize)
436     return;
438   /* see if it's changed */
439   if (STRINGP (arg))
440     {
441       if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
442         return;
443     }
444   else if (!STRINGP (oldval) && EQ (oldval, Qnil) == EQ (arg, Qnil))
445     return;
447   f->icon_name = arg;
449   if (NILP (arg))
450     {
451       if (!NILP (f->title))
452         arg = f->title;
453       else
454         /* explicit name and no icon-name -> explicit_name */
455         if (f->explicit_name)
456           arg = f->name;
457         else
458           {
459             /* no explicit name and no icon-name ->
460                name has to be rebuild from icon_title_format */
461             windows_or_buffers_changed++;
462             return;
463           }
464     }
466   /* Don't change the name if it's already NAME.  */
467   if ([[view window] miniwindowTitle] &&
468       ([[[view window] miniwindowTitle]
469              isEqualToString: [NSString stringWithUTF8String:
470                                            SDATA (arg)]]))
471     return;
473   [[view window] setMiniwindowTitle:
474         [NSString stringWithUTF8String: SDATA (arg)]];
477 static void
478 ns_set_name_internal (FRAME_PTR f, Lisp_Object name)
480   struct gcpro gcpro1;
481   Lisp_Object encoded_name, encoded_icon_name;
482   NSString *str;
483   NSView *view = FRAME_NS_VIEW (f);
485   GCPRO1 (name);
486   encoded_name = ENCODE_UTF_8 (name);
487   UNGCPRO;
489   str = [NSString stringWithUTF8String: SDATA (encoded_name)];
491   /* Don't change the name if it's already NAME.  */
492   if (! [[[view window] title] isEqualToString: str])
493     [[view window] setTitle: str];
495   if (!STRINGP (f->icon_name))
496     encoded_icon_name = encoded_name;
497   else
498     encoded_icon_name = ENCODE_UTF_8 (f->icon_name);
500   str = [NSString stringWithUTF8String: SDATA (encoded_icon_name)];
502   if ([[view window] miniwindowTitle] &&
503       ! [[[view window] miniwindowTitle] isEqualToString: str])
504     [[view window] setMiniwindowTitle: str];
508 static void
509 ns_set_name (struct frame *f, Lisp_Object name, int explicit)
511   NSView *view;
512   NSTRACE (ns_set_name);
514   if (ns_in_resize)
515     return;
517   /* Make sure that requests from lisp code override requests from
518      Emacs redisplay code.  */
519   if (explicit)
520     {
521       /* If we're switching from explicit to implicit, we had better
522          update the mode lines and thereby update the title.  */
523       if (f->explicit_name && NILP (name))
524         update_mode_lines = 1;
526       f->explicit_name = ! NILP (name);
527     }
528   else if (f->explicit_name)
529     return;
531   if (NILP (name))
532     name = build_string([ns_app_name UTF8String]);
533   else
534     CHECK_STRING (name);
536   /* Don't change the name if it's already NAME.  */
537   if (! NILP (Fstring_equal (name, f->name)))
538     return;
540   f->name = name;
542   /* title overrides explicit name */
543   if (! NILP (f->title))
544     name = f->title;
546   ns_set_name_internal (f, name);
550 /* This function should be called when the user's lisp code has
551    specified a name for the frame; the name will override any set by the
552    redisplay code.  */
553 static void
554 x_explicitly_set_name (FRAME_PTR f, Lisp_Object arg, Lisp_Object oldval)
556   NSTRACE (x_explicitly_set_name);
557   ns_set_name (f, arg, 1);
561 /* This function should be called by Emacs redisplay code to set the
562    name; names set this way will never override names set by the user's
563    lisp code.  */
564 void
565 x_implicitly_set_name (FRAME_PTR f, Lisp_Object arg, Lisp_Object oldval)
567   NSTRACE (x_implicitly_set_name);
569   /* Deal with NS specific format t.  */
570   if (FRAME_NS_P (f) && ((FRAME_ICONIFIED_P (f) && EQ (Vicon_title_format, Qt))
571                          || EQ (Vframe_title_format, Qt)))
572     ns_set_name_as_filename (f);
573   else
574     ns_set_name (f, arg, 0);
578 /* Change the title of frame F to NAME.
579    If NAME is nil, use the frame name as the title.  */
581 static void
582 x_set_title (struct frame *f, Lisp_Object name, Lisp_Object old_name)
584   NSTRACE (x_set_title);
585   /* Don't change the title if it's already NAME.  */
586   if (EQ (name, f->title))
587     return;
589   update_mode_lines = 1;
591   f->title = name;
593   if (NILP (name))
594     name = f->name;
595   else
596     CHECK_STRING (name);
598   ns_set_name_internal (f, name);
602 void
603 ns_set_name_as_filename (struct frame *f)
605   NSView *view;
606   Lisp_Object name, filename;
607   Lisp_Object buf = XWINDOW (f->selected_window)->buffer;
608   const char *title;
609   NSAutoreleasePool *pool;
610   struct gcpro gcpro1;
611   Lisp_Object encoded_name, encoded_filename;
612   NSString *str;
613   NSTRACE (ns_set_name_as_filename);
615   if (f->explicit_name || ! NILP (f->title) || ns_in_resize)
616     return;
618   BLOCK_INPUT;
619   pool = [[NSAutoreleasePool alloc] init];
620   filename = BVAR (XBUFFER (buf), filename);
621   name = BVAR (XBUFFER (buf), name);
623   if (NILP (name))
624     {
625       if (! NILP (filename))
626         name = Ffile_name_nondirectory (filename);
627       else
628         name = build_string ([ns_app_name UTF8String]);
629     }
631   GCPRO1 (name);
632   encoded_name = ENCODE_UTF_8 (name);
633   UNGCPRO;
635   view = FRAME_NS_VIEW (f);
637   title = FRAME_ICONIFIED_P (f) ? [[[view window] miniwindowTitle] UTF8String]
638                                 : [[[view window] title] UTF8String];
640   if (title && (! strcmp (title, SDATA (encoded_name))))
641     {
642       [pool release];
643       UNBLOCK_INPUT;
644       return;
645     }
647   str = [NSString stringWithUTF8String: SDATA (encoded_name)];
648   if (str == nil) str = @"Bad coding";
650   if (FRAME_ICONIFIED_P (f))
651     [[view window] setMiniwindowTitle: str];
652   else
653     {
654       NSString *fstr;
656       if (! NILP (filename))
657         {
658           GCPRO1 (filename);
659           encoded_filename = ENCODE_UTF_8 (filename);
660           UNGCPRO;
662           fstr = [NSString stringWithUTF8String: SDATA (encoded_filename)];
663           if (fstr == nil) fstr = @"";
664 #ifdef NS_IMPL_COCOA
665           /* work around a bug observed on 10.3 and later where
666              setTitleWithRepresentedFilename does not clear out previous state
667              if given filename does not exist */
668           if (! [[NSFileManager defaultManager] fileExistsAtPath: fstr])
669             [[view window] setRepresentedFilename: @""];
670 #endif
671         }
672       else
673         fstr = @"";
675       [[view window] setRepresentedFilename: fstr];
676       [[view window] setTitle: str];
677       f->name = name;
678     }
680   [pool release];
681   UNBLOCK_INPUT;
685 void
686 ns_set_doc_edited (struct frame *f, Lisp_Object arg)
688   NSView *view = FRAME_NS_VIEW (f);
689   NSAutoreleasePool *pool;
690   if (!MINI_WINDOW_P (XWINDOW (f->selected_window)))
691     {
692       BLOCK_INPUT;
693       pool = [[NSAutoreleasePool alloc] init];
694       [[view window] setDocumentEdited: !NILP (arg)];
695       [pool release];
696       UNBLOCK_INPUT;
697     }
701 void
702 x_set_menu_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
704   int nlines;
705   int olines = FRAME_MENU_BAR_LINES (f);
706   if (FRAME_MINIBUF_ONLY_P (f))
707     return;
709   if (INTEGERP (value))
710     nlines = XINT (value);
711   else
712     nlines = 0;
714   FRAME_MENU_BAR_LINES (f) = 0;
715   if (nlines)
716     {
717       FRAME_EXTERNAL_MENU_BAR (f) = 1;
718       /* does for all frames, whereas we just want for one frame
719          [NSMenu setMenuBarVisible: YES]; */
720     }
721   else
722     {
723       if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
724         free_frame_menubar (f);
725       /*      [NSMenu setMenuBarVisible: NO]; */
726       FRAME_EXTERNAL_MENU_BAR (f) = 0;
727     }
731 /* toolbar support */
732 void
733 x_set_tool_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
735   int nlines;
736   Lisp_Object root_window;
738   if (FRAME_MINIBUF_ONLY_P (f))
739     return;
741   if (INTEGERP (value) && XINT (value) >= 0)
742     nlines = XFASTINT (value);
743   else
744     nlines = 0;
746   if (nlines)
747     {
748       FRAME_EXTERNAL_TOOL_BAR (f) = 1;
749       update_frame_tool_bar (f);
750     }
751   else
752     {
753       if (FRAME_EXTERNAL_TOOL_BAR (f))
754         {
755           free_frame_tool_bar (f);
756           FRAME_EXTERNAL_TOOL_BAR (f) = 0;
757         }
758     }
760   x_set_window_size (f, 0, f->text_cols, f->text_lines);
764 void
765 ns_implicitly_set_icon_type (struct frame *f)
767   Lisp_Object tem;
768   EmacsView *view = FRAME_NS_VIEW (f);
769   id image =nil;
770   Lisp_Object chain, elt;
771   NSAutoreleasePool *pool;
772   BOOL setMini = YES;
774   NSTRACE (ns_implicitly_set_icon_type);
776   BLOCK_INPUT;
777   pool = [[NSAutoreleasePool alloc] init];
778   if (f->output_data.ns->miniimage
779       && [[NSString stringWithUTF8String: SDATA (f->name)]
780                isEqualToString: [(NSImage *)f->output_data.ns->miniimage name]])
781     {
782       [pool release];
783       UNBLOCK_INPUT;
784       return;
785     }
787   tem = assq_no_quit (Qicon_type, f->param_alist);
788   if (CONSP (tem) && ! NILP (XCDR (tem)))
789     {
790       [pool release];
791       UNBLOCK_INPUT;
792       return;
793     }
795   for (chain = Vns_icon_type_alist;
796        (image = nil) && CONSP (chain);
797        chain = XCDR (chain))
798     {
799       elt = XCAR (chain);
800       /* special case: 't' means go by file type */
801       if (SYMBOLP (elt) && EQ (elt, Qt) && SDATA (f->name)[0] == '/')
802         {
803           NSString *str
804              = [NSString stringWithUTF8String: SDATA (f->name)];
805           if ([[NSFileManager defaultManager] fileExistsAtPath: str])
806             image = [[[NSWorkspace sharedWorkspace] iconForFile: str] retain];
807         }
808       else if (CONSP (elt) &&
809                STRINGP (XCAR (elt)) &&
810                STRINGP (XCDR (elt)) &&
811                fast_string_match (XCAR (elt), f->name) >= 0)
812         {
813           image = [EmacsImage allocInitFromFile: XCDR (elt)];
814           if (image == nil)
815             image = [[NSImage imageNamed:
816                                [NSString stringWithUTF8String:
817                                             SDATA (XCDR (elt))]] retain];
818         }
819     }
821   if (image == nil)
822     {
823       image = [[[NSWorkspace sharedWorkspace] iconForFileType: @"text"] retain];
824       setMini = NO;
825     }
827   [f->output_data.ns->miniimage release];
828   f->output_data.ns->miniimage = image;
829   [view setMiniwindowImage: setMini];
830   [pool release];
831   UNBLOCK_INPUT;
835 static void
836 x_set_icon_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
838   EmacsView *view = FRAME_NS_VIEW (f);
839   id image = nil;
840   BOOL setMini = YES;
842   NSTRACE (x_set_icon_type);
844   if (!NILP (arg) && SYMBOLP (arg))
845     {
846       arg =build_string (SDATA (SYMBOL_NAME (arg)));
847       store_frame_param (f, Qicon_type, arg);
848     }
850   /* do it the implicit way */
851   if (NILP (arg))
852     {
853       ns_implicitly_set_icon_type (f);
854       return;
855     }
857   CHECK_STRING (arg);
859   image = [EmacsImage allocInitFromFile: arg];
860   if (image == nil)
861     image =[NSImage imageNamed: [NSString stringWithUTF8String:
862                                             SDATA (arg)]];
864   if (image == nil)
865     {
866       image = [NSImage imageNamed: @"text"];
867       setMini = NO;
868     }
870   f->output_data.ns->miniimage = image;
871   [view setMiniwindowImage: setMini];
875 /* Xism; we stub out (we do implement this in ns-win.el) */
877 XParseGeometry (char *string, int *x, int *y,
878                 unsigned int *width, unsigned int *height)
880   message1 ("Warning: XParseGeometry not supported under NS.\n");
881   return 0;
885 /* TODO: move to nsterm? */
887 ns_lisp_to_cursor_type (Lisp_Object arg)
889   char *str;
890   if (XTYPE (arg) == Lisp_String)
891     str = SDATA (arg);
892   else if (XTYPE (arg) == Lisp_Symbol)
893     str = SDATA (SYMBOL_NAME (arg));
894   else return -1;
895   if (!strcmp (str, "box"))     return FILLED_BOX_CURSOR;
896   if (!strcmp (str, "hollow"))  return HOLLOW_BOX_CURSOR;
897   if (!strcmp (str, "hbar"))    return HBAR_CURSOR;
898   if (!strcmp (str, "bar"))     return BAR_CURSOR;
899   if (!strcmp (str, "no"))      return NO_CURSOR;
900   return -1;
904 Lisp_Object
905 ns_cursor_type_to_lisp (int arg)
907   switch (arg)
908     {
909     case FILLED_BOX_CURSOR: return Qbox;
910     case HOLLOW_BOX_CURSOR: return intern ("hollow");
911     case HBAR_CURSOR:       return intern ("hbar");
912     case BAR_CURSOR:        return intern ("bar");
913     case NO_CURSOR:
914     default:                return intern ("no");
915     }
918 /* This is the same as the xfns.c definition.  */
919 void
920 x_set_cursor_type (FRAME_PTR f, Lisp_Object arg, Lisp_Object oldval)
922   set_frame_cursor_types (f, arg);
924   /* Make sure the cursor gets redrawn.  */
925   cursor_type_changed = 1;
929 /* called to set mouse pointer color, but all other terms use it to
930    initialize pointer types (and don't set the color ;) */
931 static void
932 x_set_mouse_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
934   /* don't think we can do this on Nextstep */
938 #define Str(x) #x
939 #define Xstr(x) Str(x)
941 static Lisp_Object
942 ns_appkit_version_str (void)
944   char tmp[80];
946 #ifdef NS_IMPL_GNUSTEP
947   sprintf(tmp, "gnustep-gui-%s", Xstr(GNUSTEP_GUI_VERSION));
948 #elif defined(NS_IMPL_COCOA)
949   sprintf(tmp, "apple-appkit-%.2f", NSAppKitVersionNumber);
950 #else
951   tmp = "ns-unknown";
952 #endif
953   return build_string (tmp);
957 /* This is for use by x-server-version and collapses all version info we
958    have into a single int.  For a better picture of the implementation
959    running, use ns_appkit_version_str.*/
960 static int
961 ns_appkit_version_int (void)
963 #ifdef NS_IMPL_GNUSTEP
964   return GNUSTEP_GUI_MAJOR_VERSION * 100 + GNUSTEP_GUI_MINOR_VERSION;
965 #elif defined(NS_IMPL_COCOA)
966   return (int)NSAppKitVersionNumber;
967 #endif
968   return 0;
972 static void
973 x_icon (struct frame *f, Lisp_Object parms)
974 /* --------------------------------------------------------------------------
975    Strangely-named function to set icon position parameters in frame.
976    This is irrelevant under OS X, but might be needed under GNUstep,
977    depending on the window manager used.  Note, this is not a standard
978    frame parameter-setter; it is called directly from x-create-frame.
979    -------------------------------------------------------------------------- */
981   Lisp_Object icon_x, icon_y;
982   struct ns_display_info *dpyinfo = check_ns_display_info (Qnil);
984   f->output_data.ns->icon_top = Qnil;
985   f->output_data.ns->icon_left = Qnil;
987   /* Set the position of the icon.  */
988   icon_x = x_get_arg (dpyinfo, parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
989   icon_y = x_get_arg (dpyinfo, parms, Qicon_top, 0, 0,  RES_TYPE_NUMBER);
990   if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
991     {
992       CHECK_NUMBER (icon_x);
993       CHECK_NUMBER (icon_y);
994       f->output_data.ns->icon_top = icon_y;
995       f->output_data.ns->icon_left = icon_x;
996     }
997   else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
998     error ("Both left and top icon corners of icon must be specified");
1002 /* Note: see frame.c for template, also where generic functions are impl */
1003 frame_parm_handler ns_frame_parm_handlers[] =
1005   x_set_autoraise, /* generic OK */
1006   x_set_autolower, /* generic OK */
1007   x_set_background_color,
1008   0, /* x_set_border_color,  may be impossible under Nextstep */
1009   0, /* x_set_border_width,  may be impossible under Nextstep */
1010   x_set_cursor_color,
1011   x_set_cursor_type,
1012   x_set_font, /* generic OK */
1013   x_set_foreground_color,
1014   x_set_icon_name,
1015   x_set_icon_type,
1016   x_set_internal_border_width, /* generic OK */
1017   x_set_menu_bar_lines,
1018   x_set_mouse_color,
1019   x_explicitly_set_name,
1020   x_set_scroll_bar_width, /* generic OK */
1021   x_set_title,
1022   x_set_unsplittable, /* generic OK */
1023   x_set_vertical_scroll_bars, /* generic OK */
1024   x_set_visibility, /* generic OK */
1025   x_set_tool_bar_lines,
1026   0, /* x_set_scroll_bar_foreground, will ignore (not possible on NS) */
1027   0, /* x_set_scroll_bar_background,  will ignore (not possible on NS) */
1028   x_set_screen_gamma, /* generic OK */
1029   x_set_line_spacing, /* generic OK, sets f->extra_line_spacing to int */
1030   x_set_fringe_width, /* generic OK */
1031   x_set_fringe_width, /* generic OK */
1032   0, /* x_set_wait_for_wm, will ignore */
1033   0,  /* x_set_fullscreen will ignore */
1034   x_set_font_backend, /* generic OK */
1035   x_set_alpha,
1036   0, /* x_set_sticky */
1037   0, /* x_set_tool_bar_position */
1042 /* ==========================================================================
1044     Lisp definitions
1046    ========================================================================== */
1048 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
1049        1, 1, 0,
1050        doc: /* Make a new Nextstep window, called a \"frame\" in Emacs terms.
1051 Return an Emacs frame object.
1052 PARMS is an alist of frame parameters.
1053 If the parameters specify that the frame should not have a minibuffer,
1054 and do not specify a specific minibuffer window to use,
1055 then `default-minibuffer-frame' must be a frame whose minibuffer can
1056 be shared by the new frame.  */)
1057      (Lisp_Object parms)
1059   static int desc_ctr = 1;
1060   struct frame *f;
1061   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1062   Lisp_Object frame, tem;
1063   Lisp_Object name;
1064   int minibuffer_only = 0;
1065   int count = specpdl_ptr - specpdl;
1066   Lisp_Object display;
1067   struct ns_display_info *dpyinfo = NULL;
1068   Lisp_Object parent;
1069   struct kboard *kb;
1070   Lisp_Object tfont, tfontsize;
1071   int window_prompting = 0;
1072   int width, height;
1074   check_ns ();
1076   /* Seems a little strange, but other terms do it. Perhaps the code below
1077      is modifying something? */
1078   parms = Fcopy_alist (parms);
1080   display = x_get_arg (dpyinfo, parms, Qterminal, 0, 0, RES_TYPE_STRING);
1081   if (EQ (display, Qunbound))
1082     display = Qnil;
1083   dpyinfo = check_ns_display_info (display);
1085   if (!dpyinfo->terminal->name)
1086     error ("Terminal is not live, can't create new frames on it");
1088   kb = dpyinfo->terminal->kboard;
1090   name = x_get_arg (dpyinfo, parms, Qname, 0, 0, RES_TYPE_STRING);
1091   if (!STRINGP (name)
1092       && ! EQ (name, Qunbound)
1093       && ! NILP (name))
1094     error ("Invalid frame name--not a string or nil");
1096   if (STRINGP (name))
1097     Vx_resource_name = name;
1098   else
1099     Vx_resource_name = Vinvocation_name;
1101   parent = x_get_arg (dpyinfo, parms, Qparent_id, 0, 0, RES_TYPE_NUMBER);
1102   if (EQ (parent, Qunbound))
1103     parent = Qnil;
1104   if (! NILP (parent))
1105     CHECK_NUMBER (parent);
1107   frame = Qnil;
1108   GCPRO4 (parms, parent, name, frame);
1110   tem = x_get_arg (dpyinfo, parms, Qminibuffer, "minibuffer", "Minibuffer",
1111                   RES_TYPE_SYMBOL);
1112   if (EQ (tem, Qnone) || NILP (tem))
1113     {
1114       f = make_frame_without_minibuffer (Qnil, kb, display);
1115     }
1116   else if (EQ (tem, Qonly))
1117     {
1118       f = make_minibuffer_frame ();
1119       minibuffer_only = 1;
1120     }
1121   else if (WINDOWP (tem))
1122     {
1123       f = make_frame_without_minibuffer (tem, kb, display);
1124     }
1125   else
1126     {
1127       f = make_frame (1);
1128     }
1130   /* Set the name; the functions to which we pass f expect the name to
1131      be set.  */
1132   if (EQ (name, Qunbound) || NILP (name) || (XTYPE (name) != Lisp_String))
1133     {
1134       f->name = build_string ([ns_app_name UTF8String]);
1135       f->explicit_name =0;
1136     }
1137   else
1138     {
1139       f->name = name;
1140       f->explicit_name = 1;
1141       specbind (Qx_resource_name, name);
1142     }
1144   XSETFRAME (frame, f);
1145   FRAME_CAN_HAVE_SCROLL_BARS (f) = 1;
1147   f->terminal = dpyinfo->terminal;
1148   f->terminal->reference_count++;
1150   f->output_method = output_ns;
1151   f->output_data.ns = (struct ns_output *)xmalloc (sizeof *(f->output_data.ns));
1152   memset (f->output_data.ns, 0, sizeof (*(f->output_data.ns)));
1154   FRAME_FONTSET (f) = -1;
1156   /* record_unwind_protect (unwind_create_frame, frame); safety; maybe later? */
1158   f->icon_name = x_get_arg (dpyinfo, parms, Qicon_name, "iconName", "Title",
1159                             RES_TYPE_STRING);
1160   if (! STRINGP (f->icon_name))
1161     f->icon_name = Qnil;
1163   FRAME_NS_DISPLAY_INFO (f) = dpyinfo;
1165   f->output_data.ns->window_desc = desc_ctr++;
1166   if (!NILP (parent))
1167     {
1168       f->output_data.ns->parent_desc = (Window) XFASTINT (parent);
1169       f->output_data.ns->explicit_parent = 1;
1170     }
1171   else
1172     {
1173       f->output_data.ns->parent_desc = FRAME_NS_DISPLAY_INFO (f)->root_window;
1174       f->output_data.ns->explicit_parent = 0;
1175     }
1177   f->resx = dpyinfo->resx;
1178   f->resy = dpyinfo->resy;
1180   BLOCK_INPUT;
1181   register_font_driver (&nsfont_driver, f);
1182   x_default_parameter (f, parms, Qfont_backend, Qnil,
1183                         "fontBackend", "FontBackend", RES_TYPE_STRING);
1185   {
1186     /* use for default font name */
1187     id font = [NSFont userFixedPitchFontOfSize: -1.0]; /* default */
1188     tfontsize = x_default_parameter (f, parms, Qfontsize,
1189                                     make_number (0 /*(int)[font pointSize]*/),
1190                                     "fontSize", "FontSize", RES_TYPE_NUMBER);
1191     tfont = x_default_parameter (f, parms, Qfont,
1192                                  build_string ([[font fontName] UTF8String]),
1193                                  "font", "Font", RES_TYPE_STRING);
1194   }
1195   UNBLOCK_INPUT;
1197   x_default_parameter (f, parms, Qborder_width, make_number (0),
1198                        "borderwidth", "BorderWidth", RES_TYPE_NUMBER);
1199   x_default_parameter (f, parms, Qinternal_border_width, make_number (2),
1200                       "internalBorderWidth", "InternalBorderWidth",
1201                       RES_TYPE_NUMBER);
1203   /* default scrollbars on right on Mac */
1204   {
1205       Lisp_Object spos
1206 #ifdef NS_IMPL_GNUSTEP
1207           = Qt;
1208 #else
1209           = Qright;
1210 #endif
1211       x_default_parameter (f, parms, Qvertical_scroll_bars, spos,
1212                            "verticalScrollBars", "VerticalScrollBars",
1213                            RES_TYPE_SYMBOL);
1214   }
1215   x_default_parameter (f, parms, Qforeground_color, build_string ("Black"),
1216                       "foreground", "Foreground", RES_TYPE_STRING);
1217   x_default_parameter (f, parms, Qbackground_color, build_string ("White"),
1218                       "background", "Background", RES_TYPE_STRING);
1219   /* FIXME: not suppported yet in Nextstep */
1220   x_default_parameter (f, parms, Qline_spacing, Qnil,
1221                        "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
1222   x_default_parameter (f, parms, Qleft_fringe, Qnil,
1223                        "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
1224   x_default_parameter (f, parms, Qright_fringe, Qnil,
1225                        "rightFringe", "RightFringe", RES_TYPE_NUMBER);
1226   /* end PENDING */
1228   init_frame_faces (f);
1230   /* The X resources controlling the menu-bar and tool-bar are
1231      processed specially at startup, and reflected in the mode
1232      variables; ignore them here.  */
1233   x_default_parameter (f, parms, Qmenu_bar_lines,
1234                        NILP (Vmenu_bar_mode)
1235                        ? make_number (0) : make_number (1),
1236                        NULL, NULL, RES_TYPE_NUMBER);
1237   x_default_parameter (f, parms, Qtool_bar_lines,
1238                        NILP (Vtool_bar_mode)
1239                        ? make_number (0) : make_number (1),
1240                        NULL, NULL, RES_TYPE_NUMBER);
1242   x_default_parameter (f, parms, Qbuffer_predicate, Qnil, "bufferPredicate",
1243                        "BufferPredicate", RES_TYPE_SYMBOL);
1244   x_default_parameter (f, parms, Qtitle, Qnil, "title", "Title",
1245                        RES_TYPE_STRING);
1247 /* TODO: other terms seem to get away w/o this complexity.. */
1248   if (NILP (Fassq (Qwidth, parms)))
1249     {
1250       Lisp_Object value
1251          = x_get_arg (dpyinfo, parms, Qwidth, "width", "Width",
1252                       RES_TYPE_NUMBER);
1253       if (! EQ (value, Qunbound))
1254         parms = Fcons (Fcons (Qwidth, value), parms);
1255     }
1256   if (NILP (Fassq (Qheight, parms)))
1257     {
1258       Lisp_Object value
1259          = x_get_arg (dpyinfo, parms, Qheight, "height", "Height",
1260                       RES_TYPE_NUMBER);
1261       if (! EQ (value, Qunbound))
1262         parms = Fcons (Fcons (Qheight, value), parms);
1263     }
1264   if (NILP (Fassq (Qleft, parms)))
1265     {
1266       Lisp_Object value
1267          = x_get_arg (dpyinfo, parms, Qleft, "left", "Left", RES_TYPE_NUMBER);
1268       if (! EQ (value, Qunbound))
1269         parms = Fcons (Fcons (Qleft, value), parms);
1270     }
1271   if (NILP (Fassq (Qtop, parms)))
1272     {
1273       Lisp_Object value
1274          = x_get_arg (dpyinfo, parms, Qtop, "top", "Top", RES_TYPE_NUMBER);
1275       if (! EQ (value, Qunbound))
1276         parms = Fcons (Fcons (Qtop, value), parms);
1277     }
1279   window_prompting = x_figure_window_size (f, parms, 1);
1281   tem = x_get_arg (dpyinfo, parms, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
1282   f->no_split = minibuffer_only || (!EQ (tem, Qunbound) && !EQ (tem, Qnil));
1284   /* NOTE: on other terms, this is done in set_mouse_color, however this
1285      was not getting called under Nextstep */
1286   f->output_data.ns->text_cursor = [NSCursor IBeamCursor];
1287   f->output_data.ns->nontext_cursor = [NSCursor arrowCursor];
1288   f->output_data.ns->modeline_cursor = [NSCursor pointingHandCursor];
1289   f->output_data.ns->hand_cursor = [NSCursor pointingHandCursor];
1290   f->output_data.ns->hourglass_cursor = [NSCursor disappearingItemCursor];
1291   f->output_data.ns->horizontal_drag_cursor = [NSCursor resizeLeftRightCursor];
1292   FRAME_NS_DISPLAY_INFO (f)->vertical_scroll_bar_cursor
1293      = [NSCursor arrowCursor];
1294   f->output_data.ns->current_pointer = f->output_data.ns->text_cursor;
1296   [[EmacsView alloc] initFrameFromEmacs: f];
1298   x_icon (f, parms);
1300   /* It is now ok to make the frame official even if we get an error below.
1301      The frame needs to be on Vframe_list or making it visible won't work. */
1302   Vframe_list = Fcons (frame, Vframe_list);
1303   /*FRAME_NS_DISPLAY_INFO (f)->reference_count++; */
1305   x_default_parameter (f, parms, Qicon_type, Qnil, "bitmapIcon", "BitmapIcon",
1306                       RES_TYPE_SYMBOL);
1307   x_default_parameter (f, parms, Qauto_raise, Qnil, "autoRaise", "AutoRaiseLower",
1308                       RES_TYPE_BOOLEAN);
1309   x_default_parameter (f, parms, Qauto_lower, Qnil, "autoLower", "AutoLower",
1310                       RES_TYPE_BOOLEAN);
1311   x_default_parameter (f, parms, Qcursor_type, Qbox, "cursorType", "CursorType",
1312                       RES_TYPE_SYMBOL);
1313   x_default_parameter (f, parms, Qscroll_bar_width, Qnil, "scrollBarWidth",
1314                       "ScrollBarWidth", RES_TYPE_NUMBER);
1315   x_default_parameter (f, parms, Qalpha, Qnil, "alpha", "Alpha",
1316                       RES_TYPE_NUMBER);
1318   width = FRAME_COLS (f);
1319   height = FRAME_LINES (f);
1321   SET_FRAME_COLS (f, 0);
1322   FRAME_LINES (f) = 0;
1323   change_frame_size (f, height, width, 1, 0, 0);
1325   if (! f->output_data.ns->explicit_parent)
1326     {
1327       tem = x_get_arg (dpyinfo, parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
1328       if (EQ (tem, Qunbound))
1329         tem = Qt;
1330       x_set_visibility (f, tem, Qnil);
1331       if (EQ (tem, Qicon))
1332         x_iconify_frame (f);
1333       else if (! NILP (tem))
1334         {
1335           x_make_frame_visible (f);
1336           f->async_visible = 1;
1337           [[FRAME_NS_VIEW (f) window] makeKeyWindow];
1338         }
1339       else
1340           f->async_visible = 0;
1341     }
1343   if (FRAME_HAS_MINIBUF_P (f)
1344       && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
1345           || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
1346     KVAR (kb, Vdefault_minibuffer_frame) = frame;
1348   /* All remaining specified parameters, which have not been "used"
1349      by x_get_arg and friends, now go in the misc. alist of the frame.  */
1350   for (tem = parms; CONSP (tem); tem = XCDR (tem))
1351     if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
1352       f->param_alist = Fcons (XCAR (tem), f->param_alist);
1354   UNGCPRO;
1355   Vwindow_list = Qnil;
1357   return unbind_to (count, frame);
1361 DEFUN ("x-focus-frame", Fx_focus_frame, Sx_focus_frame, 1, 1, 0,
1362        doc: /* Set the input focus to FRAME.
1363 FRAME nil means use the selected frame.  */)
1364      (Lisp_Object frame)
1366   struct frame *f = check_ns_frame (frame);
1367   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1369   if (dpyinfo->x_focus_frame != f)
1370     {
1371       EmacsView *view = FRAME_NS_VIEW (f);
1372       BLOCK_INPUT;
1373       [NSApp activateIgnoringOtherApps: YES];
1374       [[view window] makeKeyAndOrderFront: view];
1375       UNBLOCK_INPUT;
1376     }
1378   return Qnil;
1382 DEFUN ("ns-popup-font-panel", Fns_popup_font_panel, Sns_popup_font_panel,
1383        0, 1, "",
1384        doc: /* Pop up the font panel. */)
1385      (Lisp_Object frame)
1387   id fm;
1388   struct frame *f;
1390   check_ns ();
1391   fm = [NSFontManager sharedFontManager];
1392   if (NILP (frame))
1393     f = SELECTED_FRAME ();
1394   else
1395     {
1396       CHECK_FRAME (frame);
1397       f = XFRAME (frame);
1398     }
1400   [fm setSelectedFont: ((struct nsfont_info *)f->output_data.ns->font)->nsfont
1401            isMultiple: NO];
1402   [fm orderFrontFontPanel: NSApp];
1403   return Qnil;
1407 DEFUN ("ns-popup-color-panel", Fns_popup_color_panel, Sns_popup_color_panel,
1408        0, 1, "",
1409        doc: /* Pop up the color panel.  */)
1410      (Lisp_Object frame)
1412   struct frame *f;
1414   check_ns ();
1415   if (NILP (frame))
1416     f = SELECTED_FRAME ();
1417   else
1418     {
1419       CHECK_FRAME (frame);
1420       f = XFRAME (frame);
1421     }
1423   [NSApp orderFrontColorPanel: NSApp];
1424   return Qnil;
1428 DEFUN ("ns-read-file-name", Fns_read_file_name, Sns_read_file_name, 1, 4, 0,
1429        doc: /* Use a graphical panel to read a file name, using prompt PROMPT.
1430 Optional arg DIR, if non-nil, supplies a default directory.
1431 Optional arg MUSTMATCH, if non-nil, means the returned file or
1432 directory must exist.
1433 Optional arg INIT, if non-nil, provides a default file name to use.  */)
1434      (Lisp_Object prompt, Lisp_Object dir, Lisp_Object mustmatch, Lisp_Object init)
1436   static id fileDelegate = nil;
1437   int ret;
1438   id panel;
1439   Lisp_Object fname;
1441   NSString *promptS = NILP (prompt) || !STRINGP (prompt) ? nil :
1442     [NSString stringWithUTF8String: SDATA (prompt)];
1443   NSString *dirS = NILP (dir) || !STRINGP (dir) ?
1444     [NSString stringWithUTF8String: SDATA (BVAR (current_buffer, directory))] :
1445     [NSString stringWithUTF8String: SDATA (dir)];
1446   NSString *initS = NILP (init) || !STRINGP (init) ? nil :
1447     [NSString stringWithUTF8String: SDATA (init)];
1449   check_ns ();
1451   if (fileDelegate == nil)
1452     fileDelegate = [EmacsFileDelegate new];
1454   [NSCursor setHiddenUntilMouseMoves: NO];
1456   if ([dirS characterAtIndex: 0] == '~')
1457     dirS = [dirS stringByExpandingTildeInPath];
1459   panel = NILP (mustmatch) ?
1460     (id)[EmacsSavePanel savePanel] : (id)[EmacsOpenPanel openPanel];
1462   [panel setTitle: promptS];
1464   /* Puma (10.1) does not have */
1465   if ([panel respondsToSelector: @selector (setAllowsOtherFileTypes:)])
1466     [panel setAllowsOtherFileTypes: YES];
1468   [panel setTreatsFilePackagesAsDirectories: YES];
1469   [panel setDelegate: fileDelegate];
1471   panelOK = 0;
1472   BLOCK_INPUT;
1473   if (NILP (mustmatch))
1474     {
1475       ret = [panel runModalForDirectory: dirS file: initS];
1476     }
1477   else
1478     {
1479       [panel setCanChooseDirectories: YES];
1480       ret = [panel runModalForDirectory: dirS file: initS types: nil];
1481     }
1483   ret = (ret == NSOKButton) || panelOK;
1485   if (ret)
1486     fname = build_string ([[panel filename] UTF8String]);
1488   [[FRAME_NS_VIEW (SELECTED_FRAME ()) window] makeKeyWindow];
1489   UNBLOCK_INPUT;
1491   return ret ? fname : Qnil;
1495 DEFUN ("ns-get-resource", Fns_get_resource, Sns_get_resource, 2, 2, 0,
1496        doc: /* Return the value of the property NAME of OWNER from the defaults database.
1497 If OWNER is nil, Emacs is assumed.  */)
1498      (Lisp_Object owner, Lisp_Object name)
1500   const char *value;
1502   check_ns ();
1503   if (NILP (owner))
1504     owner = build_string([ns_app_name UTF8String]);
1505   CHECK_STRING (name);
1506 /*fprintf (stderr, "ns-get-resource checking resource '%s'\n", SDATA (name)); */
1508   value =[[[NSUserDefaults standardUserDefaults]
1509             objectForKey: [NSString stringWithUTF8String: SDATA (name)]]
1510            UTF8String];
1512   if (value)
1513     return build_string (value);
1514   return Qnil;
1518 DEFUN ("ns-set-resource", Fns_set_resource, Sns_set_resource, 3, 3, 0,
1519        doc: /* Set property NAME of OWNER to VALUE, from the defaults database.
1520 If OWNER is nil, Emacs is assumed.
1521 If VALUE is nil, the default is removed.  */)
1522      (Lisp_Object owner, Lisp_Object name, Lisp_Object value)
1524   check_ns ();
1525   if (NILP (owner))
1526     owner = build_string ([ns_app_name UTF8String]);
1527   CHECK_STRING (name);
1528   if (NILP (value))
1529     {
1530       [[NSUserDefaults standardUserDefaults] removeObjectForKey:
1531                          [NSString stringWithUTF8String: SDATA (name)]];
1532     }
1533   else
1534     {
1535       CHECK_STRING (value);
1536       [[NSUserDefaults standardUserDefaults] setObject:
1537                 [NSString stringWithUTF8String: SDATA (value)]
1538                                         forKey: [NSString stringWithUTF8String:
1539                                                          SDATA (name)]];
1540     }
1542   return Qnil;
1546 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
1547        Sx_server_max_request_size,
1548        0, 1, 0,
1549        doc: /* This function is a no-op.  It is only present for completeness.  */)
1550      (Lisp_Object display)
1552   check_ns ();
1553   /* This function has no real equivalent under NeXTstep.  Return nil to
1554      indicate this. */
1555   return Qnil;
1559 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
1560        doc: /* Return the vendor ID string of Nextstep display server DISPLAY.
1561 DISPLAY should be either a frame or a display name (a string).
1562 If omitted or nil, the selected frame's display is used.  */)
1563      (Lisp_Object display)
1565 #ifdef NS_IMPL_GNUSTEP
1566   return build_string ("GNU");
1567 #else
1568   return build_string ("Apple");
1569 #endif
1573 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
1574        doc: /* Return the version numbers of the server of DISPLAY.
1575 The value is a list of three integers: the major and minor
1576 version numbers of the X Protocol in use, and the distributor-specific
1577 release number.  See also the function `x-server-vendor'.
1579 The optional argument DISPLAY specifies which display to ask about.
1580 DISPLAY should be either a frame or a display name (a string).
1581 If omitted or nil, that stands for the selected frame's display.  */)
1582      (Lisp_Object display)
1584   /*NOTE: it is unclear what would best correspond with "protocol";
1585           we return 10.3, meaning Panther, since this is roughly the
1586           level that GNUstep's APIs correspond to.
1587           The last number is where we distinguish between the Apple
1588           and GNUstep implementations ("distributor-specific release
1589           number") and give int'ized versions of major.minor. */
1590   return Fcons (make_number (10),
1591                 Fcons (make_number (3),
1592                        Fcons (make_number (ns_appkit_version_int()), Qnil)));
1596 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
1597        doc: /* Return the number of screens on Nextstep display server DISPLAY.
1598 DISPLAY should be a frame, the display name as a string, or a terminal ID.
1599 If omitted or nil, the selected frame's display is used.  */)
1600      (Lisp_Object display)
1602   int num;
1604   check_ns ();
1605   num = [[NSScreen screens] count];
1607   return (num != 0) ? make_number (num) : Qnil;
1611 DEFUN ("x-display-mm-height", Fx_display_mm_height, Sx_display_mm_height,
1612        0, 1, 0,
1613        doc: /* Return the height of Nextstep display server DISPLAY, in millimeters.
1614 DISPLAY should be a frame, the display name as a string, or a terminal ID.
1615 If omitted or nil, the selected frame's display is used.  */)
1616      (Lisp_Object display)
1618   check_ns ();
1619   return make_number ((int)
1620                      ([ns_get_screen (display) frame].size.height/(92.0/25.4)));
1624 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width,
1625        0, 1, 0,
1626        doc: /* Return the width of Nextstep display server DISPLAY, in millimeters.
1627 DISPLAY should be a frame, the display name as a string, or a terminal ID.
1628 If omitted or nil, the selected frame's display is used.  */)
1629      (Lisp_Object display)
1631   check_ns ();
1632   return make_number ((int)
1633                      ([ns_get_screen (display) frame].size.width/(92.0/25.4)));
1637 DEFUN ("x-display-backing-store", Fx_display_backing_store,
1638        Sx_display_backing_store, 0, 1, 0,
1639        doc: /* Return whether the Nexstep display DISPLAY supports backing store.
1640 The value may be `buffered', `retained', or `non-retained'.
1641 DISPLAY should be a frame, the display name as a string, or a terminal ID.
1642 If omitted or nil, the selected frame's display is used.  */)
1643      (Lisp_Object display)
1645   check_ns ();
1646   switch ([ns_get_window (display) backingType])
1647     {
1648     case NSBackingStoreBuffered:
1649       return intern ("buffered");
1650     case NSBackingStoreRetained:
1651       return intern ("retained");
1652     case NSBackingStoreNonretained:
1653       return intern ("non-retained");
1654     default:
1655       error ("Strange value for backingType parameter of frame");
1656     }
1657   return Qnil;  /* not reached, shut compiler up */
1661 DEFUN ("x-display-visual-class", Fx_display_visual_class,
1662        Sx_display_visual_class, 0, 1, 0,
1663        doc: /* Return the visual class of the Nextstep display server DISPLAY.
1664 The value is one of the symbols `static-gray', `gray-scale',
1665 `static-color', `pseudo-color', `true-color', or `direct-color'.
1666 DISPLAY should be a frame, the display name as a string, or a terminal ID.
1667 If omitted or nil, the selected frame's display is used.  */)
1668      (Lisp_Object display)
1670   NSWindowDepth depth;
1671   check_ns ();
1672   depth = [ns_get_screen (display) depth];
1674   if ( depth == NSBestDepth (NSCalibratedWhiteColorSpace, 2, 2, YES, NULL))
1675     return intern ("static-gray");
1676   else if (depth == NSBestDepth (NSCalibratedWhiteColorSpace, 8, 8, YES, NULL))
1677     return intern ("gray-scale");
1678   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 8, 8, YES, NULL))
1679     return intern ("pseudo-color");
1680   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 4, 12, NO, NULL))
1681     return intern ("true-color");
1682   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 8, 24, NO, NULL))
1683     return intern ("direct-color");
1684   else
1685     /* color mgmt as far as we do it is really handled by Nextstep itself anyway */
1686     return intern ("direct-color");
1690 DEFUN ("x-display-save-under", Fx_display_save_under,
1691        Sx_display_save_under, 0, 1, 0,
1692        doc: /* Return t if DISPLAY supports the save-under feature.
1693 The optional argument DISPLAY specifies which display to ask about.
1694 DISPLAY should be a frame, the display name as a string, or a terminal ID.
1695 If omitted or nil, the selected frame's display is used.  */)
1696      (Lisp_Object display)
1698   check_ns ();
1699   switch ([ns_get_window (display) backingType])
1700     {
1701     case NSBackingStoreBuffered:
1702       return Qt;
1704     case NSBackingStoreRetained:
1705     case NSBackingStoreNonretained:
1706       return Qnil;
1708     default:
1709       error ("Strange value for backingType parameter of frame");
1710     }
1711   return Qnil;  /* not reached, shut compiler up */
1715 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
1716        1, 3, 0,
1717        doc: /* Open a connection to a display server.
1718 DISPLAY is the name of the display to connect to.
1719 Optional second arg XRM-STRING is a string of resources in xrdb format.
1720 If the optional third arg MUST-SUCCEED is non-nil,
1721 terminate Emacs if we can't open the connection.
1722 \(In the Nextstep version, the last two arguments are currently ignored.)  */)
1723      (Lisp_Object display, Lisp_Object resource_string, Lisp_Object must_succeed)
1725   struct ns_display_info *dpyinfo;
1727   CHECK_STRING (display);
1729   nxatoms_of_nsselect ();
1730   dpyinfo = ns_term_init (display);
1731   if (dpyinfo == 0)
1732     {
1733       if (!NILP (must_succeed))
1734         fatal ("OpenStep on %s not responding.\n",
1735                SDATA (display));
1736       else
1737         error ("OpenStep on %s not responding.\n",
1738                SDATA (display));
1739     }
1741   /* Register our external input/output types, used for determining
1742      applicable services and also drag/drop eligibility. */
1743   ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
1744   ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
1745                       retain];
1746   ns_drag_types = [[NSArray arrayWithObjects:
1747                             NSStringPboardType,
1748                             NSTabularTextPboardType,
1749                             NSFilenamesPboardType,
1750                             NSURLPboardType,
1751                             NSColorPboardType,
1752                             NSFontPboardType, nil] retain];
1754   return Qnil;
1758 DEFUN ("x-close-connection", Fx_close_connection, Sx_close_connection,
1759        1, 1, 0,
1760        doc: /* Close the connection to the current Nextstep display server.
1761 The argument DISPLAY is currently ignored.  */)
1762      (Lisp_Object display)
1764   check_ns ();
1765   /*ns_delete_terminal (dpyinfo->terminal); */
1766   [NSApp terminate: NSApp];
1767   return Qnil;
1771 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
1772        doc: /* Return the list of display names that Emacs has connections to.  */)
1773      (void)
1775   Lisp_Object tail, result;
1777   result = Qnil;
1778   for (tail = ns_display_name_list; CONSP (tail); tail = XCDR (tail))
1779     result = Fcons (XCAR (XCAR (tail)), result);
1781   return result;
1785 DEFUN ("ns-hide-others", Fns_hide_others, Sns_hide_others,
1786        0, 0, 0,
1787        doc: /* Hides all applications other than Emacs.  */)
1788      (void)
1790   check_ns ();
1791   [NSApp hideOtherApplications: NSApp];
1792   return Qnil;
1795 DEFUN ("ns-hide-emacs", Fns_hide_emacs, Sns_hide_emacs,
1796        1, 1, 0,
1797        doc: /* If ON is non-nil, the entire Emacs application is hidden.
1798 Otherwise if Emacs is hidden, it is unhidden.
1799 If ON is equal to `activate', Emacs is unhidden and becomes
1800 the active application.  */)
1801      (Lisp_Object on)
1803   check_ns ();
1804   if (EQ (on, intern ("activate")))
1805     {
1806       [NSApp unhide: NSApp];
1807       [NSApp activateIgnoringOtherApps: YES];
1808     }
1809   else if (NILP (on))
1810     [NSApp unhide: NSApp];
1811   else
1812     [NSApp hide: NSApp];
1813   return Qnil;
1817 DEFUN ("ns-emacs-info-panel", Fns_emacs_info_panel, Sns_emacs_info_panel,
1818        0, 0, 0,
1819        doc: /* Shows the 'Info' or 'About' panel for Emacs.  */)
1820      (void)
1822   check_ns ();
1823   [NSApp orderFrontStandardAboutPanel: nil];
1824   return Qnil;
1828 DEFUN ("ns-font-name", Fns_font_name, Sns_font_name, 1, 1, 0,
1829        doc: /* Determine font postscript or family name for font NAME.
1830 NAME should be a string containing either the font name or an XLFD
1831 font descriptor.  If string contains `fontset' and not
1832 `fontset-startup', it is left alone. */)
1833      (Lisp_Object name)
1835   char *nm;
1836   CHECK_STRING (name);
1837   nm = SDATA (name);
1839   if (nm[0] != '-')
1840     return name;
1841   if (strstr (nm, "fontset") && !strstr (nm, "fontset-startup"))
1842     return name;
1844   return build_string (ns_xlfd_to_fontname (SDATA (name)));
1848 DEFUN ("ns-list-colors", Fns_list_colors, Sns_list_colors, 0, 1, 0,
1849        doc: /* Return a list of all available colors.
1850 The optional argument FRAME is currently ignored.  */)
1851      (Lisp_Object frame)
1853   Lisp_Object list = Qnil;
1854   NSEnumerator *colorlists;
1855   NSColorList *clist;
1857   if (!NILP (frame))
1858     {
1859       CHECK_FRAME (frame);
1860       if (! FRAME_NS_P (XFRAME (frame)))
1861         error ("non-Nextstep frame used in `ns-list-colors'");
1862     }
1864   BLOCK_INPUT;
1866   colorlists = [[NSColorList availableColorLists] objectEnumerator];
1867   while (clist = [colorlists nextObject])
1868     {
1869       if ([[clist name] length] < 7 ||
1870           [[clist name] rangeOfString: @"PANTONE"].location == 0)
1871         {
1872           NSEnumerator *cnames = [[clist allKeys] reverseObjectEnumerator];
1873           NSString *cname;
1874           while (cname = [cnames nextObject])
1875             list = Fcons (build_string ([cname UTF8String]), list);
1876 /*           for (i = [[clist allKeys] count] - 1; i >= 0; i--)
1877                list = Fcons (build_string ([[[clist allKeys] objectAtIndex: i]
1878                                              UTF8String]), list); */
1879         }
1880     }
1882   UNBLOCK_INPUT;
1884   return list;
1888 DEFUN ("ns-list-services", Fns_list_services, Sns_list_services, 0, 0, 0,
1889        doc: /* List available Nextstep services by querying NSApp.  */)
1890      (void)
1892 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
1893   /* You can't get services like this in 10.6+.  */
1894   return Qnil;
1895 #else
1896   Lisp_Object ret = Qnil;
1897   NSMenu *svcs;
1898   id delegate;
1900   check_ns ();
1901   svcs = [[NSMenu alloc] initWithTitle: @"Services"];
1902   [NSApp setServicesMenu: svcs];  /* this and next rebuild on <10.4 */
1903   [NSApp registerServicesMenuSendTypes: ns_send_types
1904                            returnTypes: ns_return_types];
1906 /* On Tiger, services menu updating was made lazier (waits for user to
1907    actually click on the menu), so we have to force things along: */
1908 #ifdef NS_IMPL_COCOA
1909   if (NSAppKitVersionNumber >= 744.0)
1910     {
1911       delegate = [svcs delegate];
1912       if (delegate != nil)
1913         {
1914           if ([delegate respondsToSelector: @selector (menuNeedsUpdate:)])
1915               [delegate menuNeedsUpdate: svcs];
1916           if ([delegate respondsToSelector:
1917                             @selector (menu:updateItem:atIndex:shouldCancel:)])
1918             {
1919               int i, len = [delegate numberOfItemsInMenu: svcs];
1920               for (i =0; i<len; i++)
1921                   [svcs addItemWithTitle: @"" action: NULL keyEquivalent: @""];
1922               for (i =0; i<len; i++)
1923                   if (![delegate menu: svcs
1924                            updateItem: (NSMenuItem *)[svcs itemAtIndex: i]
1925                               atIndex: i shouldCancel: NO])
1926                     break;
1927             }
1928         }
1929     }
1930 #endif
1932   [svcs setAutoenablesItems: NO];
1933 #ifdef NS_IMPL_COCOA
1934   [svcs update]; /* on OS X, converts from '/' structure */
1935 #endif
1937   ret = interpret_services_menu (svcs, Qnil, ret);
1938   return ret;
1939 #endif
1943 DEFUN ("ns-perform-service", Fns_perform_service, Sns_perform_service,
1944        2, 2, 0,
1945        doc: /* Perform Nextstep SERVICE on SEND.
1946 SEND should be either a string or nil.
1947 The return value is the result of the service, as string, or nil if
1948 there was no result.  */)
1949      (Lisp_Object service, Lisp_Object send)
1951   id pb;
1952   NSString *svcName;
1953   char *utfStr;
1954   int len;
1956   CHECK_STRING (service);
1957   check_ns ();
1959   utfStr = SDATA (service);
1960   svcName = [NSString stringWithUTF8String: utfStr];
1962   pb =[NSPasteboard pasteboardWithUniqueName];
1963   ns_string_to_pasteboard (pb, send);
1965   if (NSPerformService (svcName, pb) == NO)
1966     Fsignal (Qquit, Fcons (build_string ("service not available"), Qnil));
1968   if ([[pb types] count] == 0)
1969     return build_string ("");
1970   return ns_string_from_pasteboard (pb);
1974 DEFUN ("ns-convert-utf8-nfd-to-nfc", Fns_convert_utf8_nfd_to_nfc,
1975        Sns_convert_utf8_nfd_to_nfc, 1, 1, 0,
1976        doc: /* Return an NFC string that matches the UTF-8 NFD string STR.  */)
1977      (Lisp_Object str)
1979 /* TODO: If GNUstep ever implements precomposedStringWithCanonicalMapping,
1980          remove this. */
1981   NSString *utfStr;
1983   CHECK_STRING (str);
1984   utfStr = [NSString stringWithUTF8String: SDATA (str)];
1985   if (![utfStr respondsToSelector:
1986                  @selector (precomposedStringWithCanonicalMapping)])
1987     {
1988       message1
1989         ("Warning: ns-convert-utf8-nfd-to-nfc unsupported under GNUstep.\n");
1990       return Qnil;
1991     }
1992   else
1993     utfStr = [utfStr precomposedStringWithCanonicalMapping];
1994   return build_string ([utfStr UTF8String]);
1998 #ifdef NS_IMPL_COCOA
2000 /* Compile and execute the AppleScript SCRIPT and return the error
2001    status as function value.  A zero is returned if compilation and
2002    execution is successful, in which case *RESULT is set to a Lisp
2003    string or a number containing the resulting script value.  Otherwise,
2004    1 is returned. */
2005 static int
2006 ns_do_applescript (Lisp_Object script, Lisp_Object *result)
2008   NSAppleEventDescriptor *desc;
2009   NSDictionary* errorDict;
2010   NSAppleEventDescriptor* returnDescriptor = NULL;
2012   NSAppleScript* scriptObject =
2013     [[NSAppleScript alloc] initWithSource:
2014                              [NSString stringWithUTF8String: SDATA (script)]];
2016   returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
2017   [scriptObject release];
2019   *result = Qnil;
2021   if (returnDescriptor != NULL)
2022     {
2023       // successful execution
2024       if (kAENullEvent != [returnDescriptor descriptorType])
2025         {
2026           *result = Qt;
2027           // script returned an AppleScript result
2028           if ((typeUnicodeText == [returnDescriptor descriptorType]) ||
2029 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
2030               (typeUTF16ExternalRepresentation
2031                == [returnDescriptor descriptorType]) ||
2032 #endif
2033               (typeUTF8Text == [returnDescriptor descriptorType]) ||
2034               (typeCString == [returnDescriptor descriptorType]))
2035             {
2036               desc = [returnDescriptor coerceToDescriptorType: typeUTF8Text];
2037               if (desc)
2038                 *result = build_string([[desc stringValue] UTF8String]);
2039             }
2040           else
2041             {
2042               /* use typeUTF16ExternalRepresentation? */
2043               // coerce the result to the appropriate ObjC type
2044               desc = [returnDescriptor coerceToDescriptorType: typeUTF8Text];
2045               if (desc)
2046                 *result = make_number([desc int32Value]);
2047             }
2048         }
2049     }
2050   else
2051     {
2052       // no script result, return error
2053       return 1;
2054     }
2055   return 0;
2058 /* Helper function called from sendEvent to run applescript
2059    from within the main event loop.  */
2061 void
2062 ns_run_ascript (void)
2064   as_status = ns_do_applescript (as_script, as_result);
2067 DEFUN ("ns-do-applescript", Fns_do_applescript, Sns_do_applescript, 1, 1, 0,
2068        doc: /* Execute AppleScript SCRIPT and return the result.
2069 If compilation and execution are successful, the resulting script value
2070 is returned as a string, a number or, in the case of other constructs, t.
2071 In case the execution fails, an error is signaled. */)
2072      (Lisp_Object script)
2074   Lisp_Object result;
2075   int status;
2076   NSEvent *nxev;
2078   CHECK_STRING (script);
2079   check_ns ();
2081   BLOCK_INPUT;
2083   as_script = script;
2084   as_result = &result;
2086   /* executing apple script requires the event loop to run, otherwise
2087      errors aren't returned and executeAndReturnError hangs forever.
2088      Post an event that runs applescript and then start the event loop.
2089      The event loop is exited when the script is done.  */
2090   nxev = [NSEvent otherEventWithType: NSApplicationDefined
2091                             location: NSMakePoint (0, 0)
2092                        modifierFlags: 0
2093                            timestamp: 0
2094                         windowNumber: [[NSApp mainWindow] windowNumber]
2095                              context: [NSApp context]
2096                              subtype: 0
2097                                data1: 0
2098                                data2: NSAPP_DATA2_RUNASSCRIPT];
2100   [NSApp postEvent: nxev atStart: NO];
2101   [NSApp run];
2103   status = as_status;
2104   as_status = 0;
2105   as_script = Qnil;
2106   as_result = 0;
2107   UNBLOCK_INPUT;
2108   if (status == 0)
2109     return result;
2110   else if (!STRINGP (result))
2111     error ("AppleScript error %d", status);
2112   else
2113     error ("%s", SDATA (result));
2115 #endif
2119 /* ==========================================================================
2121     Miscellaneous functions not called through hooks
2123    ========================================================================== */
2126 /* called from image.c */
2127 FRAME_PTR
2128 check_x_frame (Lisp_Object frame)
2130   return check_ns_frame (frame);
2134 /* called from frame.c */
2135 struct ns_display_info *
2136 check_x_display_info (Lisp_Object frame)
2138   return check_ns_display_info (frame);
2142 void
2143 x_set_scroll_bar_default_width (struct frame *f)
2145   int wid = FRAME_COLUMN_WIDTH (f);
2146   FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = NS_SCROLL_BAR_WIDTH_DEFAULT;
2147   FRAME_CONFIG_SCROLL_BAR_COLS (f) = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) +
2148                                       wid - 1) / wid;
2152 /* terms impl this instead of x-get-resource directly */
2153 const char *
2154 x_get_string_resource (XrmDatabase rdb, char *name, char *class)
2156   /* remove appname prefix; TODO: allow for !="Emacs" */
2157   char *toCheck = class + (!strncmp (class, "Emacs.", 6) ? 6 : 0);
2158   const char *res;
2159   check_ns ();
2161   if (inhibit_x_resources)
2162     /* --quick was passed, so this is a no-op.  */
2163     return NULL;
2165   res = [[[NSUserDefaults standardUserDefaults] objectForKey:
2166             [NSString stringWithUTF8String: toCheck]] UTF8String];
2167   return !res ? NULL :
2168       (!strncasecmp (res, "YES", 3) ? "true" :
2169           (!strncasecmp (res, "NO", 2) ? "false" : res));
2173 Lisp_Object
2174 x_get_focus_frame (struct frame *frame)
2176   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
2177   Lisp_Object nsfocus;
2179   if (!dpyinfo->x_focus_frame)
2180     return Qnil;
2182   XSETFRAME (nsfocus, dpyinfo->x_focus_frame);
2183   return nsfocus;
2188 x_pixel_width (struct frame *f)
2190   return FRAME_PIXEL_WIDTH (f);
2195 x_pixel_height (struct frame *f)
2197   return FRAME_PIXEL_HEIGHT (f);
2202 x_char_width (struct frame *f)
2204   return FRAME_COLUMN_WIDTH (f);
2209 x_char_height (struct frame *f)
2211   return FRAME_LINE_HEIGHT (f);
2216 x_screen_planes (struct frame *f)
2218   return FRAME_NS_DISPLAY_INFO (f)->n_planes;
2222 void
2223 x_sync (struct frame *f)
2225   /* XXX Not implemented XXX */
2226   return;
2231 /* ==========================================================================
2233     Lisp definitions that, for whatever reason, we can't alias as 'ns-XXX'.
2235    ========================================================================== */
2238 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
2239        doc: /* Internal function called by `color-defined-p', which see.
2240 \(Note that the Nextstep version of this function ignores FRAME.)  */)
2241      (Lisp_Object color, Lisp_Object frame)
2243   NSColor * col;
2244   check_ns ();
2245   return ns_lisp_to_color (color, &col) ? Qnil : Qt;
2249 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
2250        doc: /* Internal function called by `color-values', which see.  */)
2251      (Lisp_Object color, Lisp_Object frame)
2253   NSColor * col;
2254   CGFloat red, green, blue, alpha;
2256   check_ns ();
2257   CHECK_STRING (color);
2259   if (ns_lisp_to_color (color, &col))
2260     return Qnil;
2262   [[col colorUsingColorSpaceName: NSCalibratedRGBColorSpace]
2263         getRed: &red green: &green blue: &blue alpha: &alpha];
2264   return list3 (make_number (lrint (red*65280)),
2265                 make_number (lrint (green*65280)),
2266                 make_number (lrint (blue*65280)));
2270 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
2271        doc: /* Internal function called by `display-color-p', which see.  */)
2272      (Lisp_Object display)
2274   NSWindowDepth depth;
2275   NSString *colorSpace;
2276   check_ns ();
2277   depth = [ns_get_screen (display) depth];
2278   colorSpace = NSColorSpaceFromDepth (depth);
2280   return    [colorSpace isEqualToString: NSDeviceWhiteColorSpace]
2281          || [colorSpace isEqualToString: NSCalibratedWhiteColorSpace]
2282       ? Qnil : Qt;
2286 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
2287        Sx_display_grayscale_p, 0, 1, 0,
2288        doc: /* Return t if the Nextstep display supports shades of gray.
2289 Note that color displays do support shades of gray.
2290 The optional argument DISPLAY specifies which display to ask about.
2291 DISPLAY should be either a frame, a display name (a string), or terminal ID.
2292 If omitted or nil, that stands for the selected frame's display. */)
2293      (Lisp_Object display)
2295   NSWindowDepth depth;
2296   check_ns ();
2297   depth = [ns_get_screen (display) depth];
2299   return NSBitsPerPixelFromDepth (depth) > 1 ? Qt : Qnil;
2303 DEFUN ("x-display-pixel-width", Fx_display_pixel_width, Sx_display_pixel_width,
2304        0, 1, 0,
2305        doc: /* Return the width in pixels of the Nextstep display DISPLAY.
2306 The optional argument DISPLAY specifies which display to ask about.
2307 DISPLAY should be either a frame, a display name (a string), or terminal ID.
2308 If omitted or nil, that stands for the selected frame's display.  */)
2309      (Lisp_Object display)
2311   check_ns ();
2312   return make_number ((int) [ns_get_screen (display) frame].size.width);
2316 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
2317        Sx_display_pixel_height, 0, 1, 0,
2318        doc: /* Return the height in pixels of the Nextstep display DISPLAY.
2319 The optional argument DISPLAY specifies which display to ask about.
2320 DISPLAY should be either a frame, a display name (a string), or terminal ID.
2321 If omitted or nil, that stands for the selected frame's display.  */)
2322      (Lisp_Object display)
2324   check_ns ();
2325   return make_number ((int) [ns_get_screen (display) frame].size.height);
2329 DEFUN ("display-usable-bounds", Fns_display_usable_bounds,
2330        Sns_display_usable_bounds, 0, 1, 0,
2331        doc: /* Return the bounds of the usable part of the screen.
2332 The return value is a list of integers (LEFT TOP WIDTH HEIGHT), which
2333 are the boundaries of the usable part of the screen, excluding areas
2334 reserved for the Mac menu, dock, and so forth.
2336 The screen queried corresponds to DISPLAY, which should be either a
2337 frame, a display name (a string), or terminal ID.  If omitted or nil,
2338 that stands for the selected frame's display. */)
2339      (Lisp_Object display)
2341   int top;
2342   NSScreen *screen;
2343   NSRect vScreen;
2345   check_ns ();
2346   screen = ns_get_screen (display);
2347   if (!screen)
2348     return Qnil;
2350   vScreen = [screen visibleFrame];
2352   /* NS coordinate system is upside-down.
2353      Transform to screen-specific coordinates. */
2354   return list4 (make_number ((int) vScreen.origin.x),
2355                 make_number ((int) [screen frame].size.height
2356                              - vScreen.size.height - vScreen.origin.y),
2357                 make_number ((int) vScreen.size.width),
2358                 make_number ((int) vScreen.size.height));
2362 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
2363        0, 1, 0,
2364        doc: /* Return the number of bitplanes of the Nextstep display DISPLAY.
2365 The optional argument DISPLAY specifies which display to ask about.
2366 DISPLAY should be either a frame, a display name (a string), or terminal ID.
2367 If omitted or nil, that stands for the selected frame's display.  */)
2368      (Lisp_Object display)
2370   check_ns ();
2371   return make_number
2372     (NSBitsPerPixelFromDepth ([ns_get_screen (display) depth]));
2376 DEFUN ("x-display-color-cells", Fx_display_color_cells,
2377        Sx_display_color_cells, 0, 1, 0,
2378        doc: /* Returns the number of color cells of the Nextstep display DISPLAY.
2379 The optional argument DISPLAY specifies which display to ask about.
2380 DISPLAY should be either a frame, a display name (a string), or terminal ID.
2381 If omitted or nil, that stands for the selected frame's display.  */)
2382      (Lisp_Object display)
2384   struct ns_display_info *dpyinfo;
2385   check_ns ();
2387   dpyinfo = check_ns_display_info (display);
2388   /* We force 24+ bit depths to 24-bit to prevent an overflow.  */
2389   return make_number (1 << min (dpyinfo->n_planes, 24));
2393 /* Unused dummy def needed for compatibility. */
2394 Lisp_Object tip_frame;
2396 /* TODO: move to xdisp or similar */
2397 static void
2398 compute_tip_xy (struct frame *f,
2399                 Lisp_Object parms,
2400                 Lisp_Object dx,
2401                 Lisp_Object dy,
2402                 int width,
2403                 int height,
2404                 int *root_x,
2405                 int *root_y)
2407   Lisp_Object left, top;
2408   EmacsView *view = FRAME_NS_VIEW (f);
2409   NSPoint pt;
2411   /* Start with user-specified or mouse position.  */
2412   left = Fcdr (Fassq (Qleft, parms));
2413   top = Fcdr (Fassq (Qtop, parms));
2415   if (!INTEGERP (left) || !INTEGERP (top))
2416     {
2417       pt = last_mouse_motion_position;
2418       /* Convert to screen coordinates */
2419       pt = [view convertPoint: pt toView: nil];
2420       pt = [[view window] convertBaseToScreen: pt];
2421     }
2422   else
2423     {
2424       /* Absolute coordinates.  */
2425       pt.x = XINT (left);
2426       pt.y = x_display_pixel_height (FRAME_NS_DISPLAY_INFO (f)) - XINT (top)
2427         - height;
2428     }
2430   /* Ensure in bounds.  (Note, screen origin = lower left.) */
2431   if (INTEGERP (left))
2432     *root_x = pt.x;
2433   else if (pt.x + XINT (dx) <= 0)
2434     *root_x = 0; /* Can happen for negative dx */
2435   else if (pt.x + XINT (dx) + width
2436            <= x_display_pixel_width (FRAME_NS_DISPLAY_INFO (f)))
2437     /* It fits to the right of the pointer.  */
2438     *root_x = pt.x + XINT (dx);
2439   else if (width + XINT (dx) <= pt.x)
2440     /* It fits to the left of the pointer.  */
2441     *root_x = pt.x - width - XINT (dx);
2442   else
2443     /* Put it left justified on the screen -- it ought to fit that way.  */
2444     *root_x = 0;
2446   if (INTEGERP (top))
2447     *root_y = pt.y;
2448   else if (pt.y - XINT (dy) - height >= 0)
2449     /* It fits below the pointer.  */
2450     *root_y = pt.y - height - XINT (dy);
2451   else if (pt.y + XINT (dy) + height
2452            <= x_display_pixel_height (FRAME_NS_DISPLAY_INFO (f)))
2453     /* It fits above the pointer */
2454       *root_y = pt.y + XINT (dy);
2455   else
2456     /* Put it on the top.  */
2457     *root_y = x_display_pixel_height (FRAME_NS_DISPLAY_INFO (f)) - height;
2461 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
2462        doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
2463 A tooltip window is a small window displaying a string.
2465 This is an internal function; Lisp code should call `tooltip-show'.
2467 FRAME nil or omitted means use the selected frame.
2469 PARMS is an optional list of frame parameters which can be used to
2470 change the tooltip's appearance.
2472 Automatically hide the tooltip after TIMEOUT seconds.  TIMEOUT nil
2473 means use the default timeout of 5 seconds.
2475 If the list of frame parameters PARMS contains a `left' parameter,
2476 the tooltip is displayed at that x-position.  Otherwise it is
2477 displayed at the mouse position, with offset DX added (default is 5 if
2478 DX isn't specified).  Likewise for the y-position; if a `top' frame
2479 parameter is specified, it determines the y-position of the tooltip
2480 window, otherwise it is displayed at the mouse position, with offset
2481 DY added (default is -10).
2483 A tooltip's maximum size is specified by `x-max-tooltip-size'.
2484 Text larger than the specified size is clipped.  */)
2485      (Lisp_Object string, Lisp_Object frame, Lisp_Object parms, Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
2487   int root_x, root_y;
2488   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2489   int count = SPECPDL_INDEX ();
2490   struct frame *f;
2491   char *str;
2492   NSSize size;
2494   specbind (Qinhibit_redisplay, Qt);
2496   GCPRO4 (string, parms, frame, timeout);
2498   CHECK_STRING (string);
2499   str = SDATA (string);
2500   f = check_x_frame (frame);
2501   if (NILP (timeout))
2502     timeout = make_number (5);
2503   else
2504     CHECK_NATNUM (timeout);
2506   if (NILP (dx))
2507     dx = make_number (5);
2508   else
2509     CHECK_NUMBER (dx);
2511   if (NILP (dy))
2512     dy = make_number (-10);
2513   else
2514     CHECK_NUMBER (dy);
2516   BLOCK_INPUT;
2517   if (ns_tooltip == nil)
2518     ns_tooltip = [[EmacsTooltip alloc] init];
2519   else
2520     Fx_hide_tip ();
2522   [ns_tooltip setText: str];
2523   size = [ns_tooltip frame].size;
2525   /* Move the tooltip window where the mouse pointer is.  Resize and
2526      show it.  */
2527   compute_tip_xy (f, parms, dx, dy, (int)size.width, (int)size.height,
2528                   &root_x, &root_y);
2530   [ns_tooltip showAtX: root_x Y: root_y for: XINT (timeout)];
2531   UNBLOCK_INPUT;
2533   UNGCPRO;
2534   return unbind_to (count, Qnil);
2538 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
2539        doc: /* Hide the current tooltip window, if there is any.
2540 Value is t if tooltip was open, nil otherwise.  */)
2541      (void)
2543   if (ns_tooltip == nil || ![ns_tooltip isActive])
2544     return Qnil;
2545   [ns_tooltip hide];
2546   return Qt;
2550 /* ==========================================================================
2552     Class implementations
2554    ========================================================================== */
2557 @implementation EmacsSavePanel
2558 #ifdef NS_IMPL_COCOA
2559 /* --------------------------------------------------------------------------
2560    These are overridden to intercept on OS X: ending panel restarts NSApp
2561    event loop if it is stopped.  Not sure if this is correct behavior,
2562    perhaps should check if running and if so send an appdefined.
2563    -------------------------------------------------------------------------- */
2564 - (void) ok: (id)sender
2566   [super ok: sender];
2567   panelOK = 1;
2568   [NSApp stop: self];
2570 - (void) cancel: (id)sender
2572   [super cancel: sender];
2573   [NSApp stop: self];
2575 #endif
2576 @end
2579 @implementation EmacsOpenPanel
2580 #ifdef NS_IMPL_COCOA
2581 /* --------------------------------------------------------------------------
2582    These are overridden to intercept on OS X: ending panel restarts NSApp
2583    event loop if it is stopped.  Not sure if this is correct behavior,
2584    perhaps should check if running and if so send an appdefined.
2585    -------------------------------------------------------------------------- */
2586 - (void) ok: (id)sender
2588   [super ok: sender];
2589   panelOK = 1;
2590   [NSApp stop: self];
2592 - (void) cancel: (id)sender
2594   [super cancel: sender];
2595   [NSApp stop: self];
2597 #endif
2598 @end
2601 @implementation EmacsFileDelegate
2602 /* --------------------------------------------------------------------------
2603    Delegate methods for Open/Save panels
2604    -------------------------------------------------------------------------- */
2605 - (BOOL)panel: (id)sender isValidFilename: (NSString *)filename
2607   return YES;
2609 - (BOOL)panel: (id)sender shouldShowFilename: (NSString *)filename
2611   return YES;
2613 - (NSString *)panel: (id)sender userEnteredFilename: (NSString *)filename
2614           confirmed: (BOOL)okFlag
2616   return filename;
2618 @end
2620 #endif
2623 /* ==========================================================================
2625     Lisp interface declaration
2627    ========================================================================== */
2630 void
2631 syms_of_nsfns (void)
2633   int i;
2635   Qfontsize = intern_c_string ("fontsize");
2636   staticpro (&Qfontsize);
2638   DEFVAR_LISP ("ns-icon-type-alist", Vns_icon_type_alist,
2639                doc: /* Alist of elements (REGEXP . IMAGE) for images of icons associated to frames.
2640 If the title of a frame matches REGEXP, then IMAGE.tiff is
2641 selected as the image of the icon representing the frame when it's
2642 miniaturized.  If an element is t, then Emacs tries to select an icon
2643 based on the filetype of the visited file.
2645 The images have to be installed in a folder called English.lproj in the
2646 Emacs folder.  You have to restart Emacs after installing new icons.
2648 Example: Install an icon Gnus.tiff and execute the following code
2650   (setq ns-icon-type-alist
2651         (append ns-icon-type-alist
2652                 '((\"^\\\\*\\\\(Group\\\\*$\\\\|Summary \\\\|Article\\\\*$\\\\)\"
2653                    . \"Gnus\"))))
2655 When you miniaturize a Group, Summary or Article frame, Gnus.tiff will
2656 be used as the image of the icon representing the frame.  */);
2657   Vns_icon_type_alist = Fcons (Qt, Qnil);
2659   DEFVAR_LISP ("ns-version-string", Vns_version_string,
2660                doc: /* Toolkit version for NS Windowing.  */);
2661   Vns_version_string = ns_appkit_version_str ();
2663   defsubr (&Sns_read_file_name);
2664   defsubr (&Sns_get_resource);
2665   defsubr (&Sns_set_resource);
2666   defsubr (&Sxw_display_color_p); /* this and next called directly by C code */
2667   defsubr (&Sx_display_grayscale_p);
2668   defsubr (&Sns_font_name);
2669   defsubr (&Sns_list_colors);
2670 #ifdef NS_IMPL_COCOA
2671   defsubr (&Sns_do_applescript);
2672 #endif
2673   defsubr (&Sxw_color_defined_p);
2674   defsubr (&Sxw_color_values);
2675   defsubr (&Sx_server_max_request_size);
2676   defsubr (&Sx_server_vendor);
2677   defsubr (&Sx_server_version);
2678   defsubr (&Sx_display_pixel_width);
2679   defsubr (&Sx_display_pixel_height);
2680   defsubr (&Sns_display_usable_bounds);
2681   defsubr (&Sx_display_mm_width);
2682   defsubr (&Sx_display_mm_height);
2683   defsubr (&Sx_display_screens);
2684   defsubr (&Sx_display_planes);
2685   defsubr (&Sx_display_color_cells);
2686   defsubr (&Sx_display_visual_class);
2687   defsubr (&Sx_display_backing_store);
2688   defsubr (&Sx_display_save_under);
2689   defsubr (&Sx_create_frame);
2690   defsubr (&Sx_open_connection);
2691   defsubr (&Sx_close_connection);
2692   defsubr (&Sx_display_list);
2694   defsubr (&Sns_hide_others);
2695   defsubr (&Sns_hide_emacs);
2696   defsubr (&Sns_emacs_info_panel);
2697   defsubr (&Sns_list_services);
2698   defsubr (&Sns_perform_service);
2699   defsubr (&Sns_convert_utf8_nfd_to_nfc);
2700   defsubr (&Sx_focus_frame);
2701   defsubr (&Sns_popup_font_panel);
2702   defsubr (&Sns_popup_color_panel);
2704   defsubr (&Sx_show_tip);
2705   defsubr (&Sx_hide_tip);
2707   /* used only in fontset.c */
2708   check_window_system_func = check_ns;
2710   as_status = 0;
2711   as_script = Qnil;
2712   as_result = 0;