Fix typos.
[emacs.git] / src / nsfns.m
blob0452086201ef4ad7a39f4e2d3eb48034398874ba
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;
101 /* ==========================================================================
103     Internal utility functions
105    ========================================================================== */
108 void
109 check_ns (void)
111  if (NSApp == nil)
112    error ("OpenStep is not in use or not initialized");
116 /* Nonzero if we can use mouse menus. */
118 have_menus_p (void)
120   return NSApp != nil;
124 /* Extract a frame as a FRAME_PTR, defaulting to the selected frame
125    and checking validity for NS.  */
126 static FRAME_PTR
127 check_ns_frame (Lisp_Object frame)
129   FRAME_PTR f;
131   if (NILP (frame))
132       f = SELECTED_FRAME ();
133   else
134     {
135       CHECK_LIVE_FRAME (frame);
136       f = XFRAME (frame);
137     }
138   if (! FRAME_NS_P (f))
139     error ("non-Nextstep frame used");
140   return f;
144 /* Let the user specify an Nextstep display with a frame.
145    nil stands for the selected frame--or, if that is not an Nextstep frame,
146    the first Nextstep display on the list.  */
147 static struct ns_display_info *
148 check_ns_display_info (Lisp_Object frame)
150   if (NILP (frame))
151     {
152       struct frame *f = SELECTED_FRAME ();
153       if (FRAME_NS_P (f) && FRAME_LIVE_P (f) )
154         return FRAME_NS_DISPLAY_INFO (f);
155       else if (x_display_list != 0)
156         return x_display_list;
157       else
158         error ("Nextstep windows are not in use or not initialized");
159     }
160   else if (INTEGERP (frame))
161     {
162       struct terminal *t = get_terminal (frame, 1);
164       if (t->type != output_ns)
165         error ("Terminal %ld is not a Nextstep display", (long) XINT (frame));
167       return t->display_info.ns;
168     }
169   else if (STRINGP (frame))
170     return ns_display_info_for_name (frame);
171   else
172     {
173       FRAME_PTR f;
175       CHECK_LIVE_FRAME (frame);
176       f = XFRAME (frame);
177       if (! FRAME_NS_P (f))
178         error ("non-Nextstep frame used");
179       return FRAME_NS_DISPLAY_INFO (f);
180     }
181   return NULL;  /* shut compiler up */
185 static id
186 ns_get_window (Lisp_Object maybeFrame)
188   id view =nil, window =nil;
190   if (!FRAMEP (maybeFrame) || !FRAME_NS_P (XFRAME (maybeFrame)))
191     maybeFrame = selected_frame;/*wrong_type_argument (Qframep, maybeFrame); */
193   if (!NILP (maybeFrame))
194     view = FRAME_NS_VIEW (XFRAME (maybeFrame));
195   if (view) window =[view window];
197   return window;
201 static NSScreen *
202 ns_get_screen (Lisp_Object screen)
204   struct frame *f;
205   struct terminal *terminal;
207   if (EQ (Qt, screen)) /* not documented */
208     return [NSScreen mainScreen];
210   terminal = get_terminal (screen, 1);
211   if (terminal->type != output_ns)
212     return NULL;
214   if (NILP (screen))
215     f = SELECTED_FRAME ();
216   else if (FRAMEP (screen))
217     f = XFRAME (screen);
218   else
219     {
220       struct ns_display_info *dpyinfo = terminal->display_info.ns;
221       f = dpyinfo->x_focus_frame
222         ? dpyinfo->x_focus_frame : dpyinfo->x_highlight_frame;
223     }
225   return ((f && FRAME_NS_P (f)) ? [[FRAME_NS_VIEW (f) window] screen]
226           : NULL);
230 /* Return the X display structure for the display named NAME.
231    Open a new connection if necessary.  */
232 struct ns_display_info *
233 ns_display_info_for_name (Lisp_Object name)
235   Lisp_Object names;
236   struct ns_display_info *dpyinfo;
238   CHECK_STRING (name);
240   for (dpyinfo = x_display_list, names = ns_display_name_list;
241        dpyinfo;
242        dpyinfo = dpyinfo->next, names = XCDR (names))
243     {
244       Lisp_Object tem;
245       tem = Fstring_equal (XCAR (XCAR (names)), name);
246       if (!NILP (tem))
247         return dpyinfo;
248     }
250   error ("Emacs for OpenStep does not yet support multi-display.");
252   Fx_open_connection (name, Qnil, Qnil);
253   dpyinfo = x_display_list;
255   if (dpyinfo == 0)
256     error ("OpenStep on %s not responding.\n", SDATA (name));
258   return dpyinfo;
262 static Lisp_Object
263 interpret_services_menu (NSMenu *menu, Lisp_Object prefix, Lisp_Object old)
264 /* --------------------------------------------------------------------------
265    Turn the input menu (an NSMenu) into a lisp list for tracking on lisp side
266    -------------------------------------------------------------------------- */
268   int i, count;
269   NSMenuItem *item;
270   const char *name;
271   Lisp_Object nameStr;
272   unsigned short key;
273   NSString *keys;
274   Lisp_Object res;
276   count = [menu numberOfItems];
277   for (i = 0; i<count; i++)
278     {
279       item = [menu itemAtIndex: i];
280       name = [[item title] UTF8String];
281       if (!name) continue;
283       nameStr = build_string (name);
285       if ([item hasSubmenu])
286         {
287           old = interpret_services_menu ([item submenu],
288                                         Fcons (nameStr, prefix), old);
289         }
290       else
291         {
292           keys = [item keyEquivalent];
293           if (keys && [keys length] )
294             {
295               key = [keys characterAtIndex: 0];
296               res = make_number (key|super_modifier);
297             }
298           else
299             {
300               res = Qundefined;
301             }
302           old = Fcons (Fcons (res,
303                             Freverse (Fcons (nameStr,
304                                            prefix))),
305                     old);
306         }
307     }
308   return old;
313 /* ==========================================================================
315     Frame parameter setters
317    ========================================================================== */
320 static void
321 x_set_foreground_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
323   NSColor *col;
325   if (ns_lisp_to_color (arg, &col))
326     {
327       store_frame_param (f, Qforeground_color, oldval);
328       error ("Unknown color");
329     }
331   [col retain];
332   [f->output_data.ns->foreground_color release];
333   f->output_data.ns->foreground_color = col;
335   if (FRAME_NS_VIEW (f))
336     {
337       update_face_from_frame_parameter (f, Qforeground_color, arg);
338       /*recompute_basic_faces (f); */
339       if (FRAME_VISIBLE_P (f))
340         redraw_frame (f);
341     }
345 static void
346 x_set_background_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
348   struct face *face;
349   NSColor *col;
350   NSView *view = FRAME_NS_VIEW (f);
351   float alpha;
353   if (ns_lisp_to_color (arg, &col))
354     {
355       store_frame_param (f, Qbackground_color, oldval);
356       error ("Unknown color");
357     }
359   /* clear the frame; in some instances the NS-internal GC appears not to
360      update, or it does update and cannot clear old text properly */
361   if (FRAME_VISIBLE_P (f))
362     ns_clear_frame (f);
364   [col retain];
365   [f->output_data.ns->background_color release];
366   f->output_data.ns->background_color = col;
367   if (view != nil)
368     {
369       [[view window] setBackgroundColor: col];
370       alpha = [col alphaComponent];
372       if (alpha != 1.0)
373           [[view window] setOpaque: NO];
374       else
375           [[view window] setOpaque: YES];
377       face = FRAME_DEFAULT_FACE (f);
378       if (face)
379         {
380           col = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f);
381           face->background
382              = (EMACS_UINT) [[col colorWithAlphaComponent: alpha] retain];
383           [col release];
385           update_face_from_frame_parameter (f, Qbackground_color, arg);
386         }
388       if (FRAME_VISIBLE_P (f))
389         redraw_frame (f);
390     }
394 static void
395 x_set_cursor_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
397   NSColor *col;
399   if (ns_lisp_to_color (arg, &col))
400     {
401       store_frame_param (f, Qcursor_color, oldval);
402       error ("Unknown color");
403     }
405   [FRAME_CURSOR_COLOR (f) release];
406   FRAME_CURSOR_COLOR (f) = [col retain];
408   if (FRAME_VISIBLE_P (f))
409     {
410       x_update_cursor (f, 0);
411       x_update_cursor (f, 1);
412     }
413   update_face_from_frame_parameter (f, Qcursor_color, arg);
417 static void
418 x_set_icon_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
420   NSView *view = FRAME_NS_VIEW (f);
421   NSTRACE (x_set_icon_name);
423   if (ns_in_resize)
424     return;
426   /* see if it's changed */
427   if (STRINGP (arg))
428     {
429       if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
430         return;
431     }
432   else if (!STRINGP (oldval) && EQ (oldval, Qnil) == EQ (arg, Qnil))
433     return;
435   f->icon_name = arg;
437   if (NILP (arg))
438     {
439       if (!NILP (f->title))
440         arg = f->title;
441       else
442         /* explicit name and no icon-name -> explicit_name */
443         if (f->explicit_name)
444           arg = f->name;
445         else
446           {
447             /* no explicit name and no icon-name ->
448                name has to be rebuild from icon_title_format */
449             windows_or_buffers_changed++;
450             return;
451           }
452     }
454   /* Don't change the name if it's already NAME.  */
455   if ([[view window] miniwindowTitle] &&
456       ([[[view window] miniwindowTitle]
457              isEqualToString: [NSString stringWithUTF8String:
458                                            SDATA (arg)]]))
459     return;
461   [[view window] setMiniwindowTitle:
462         [NSString stringWithUTF8String: SDATA (arg)]];
465 static void
466 ns_set_name_internal (FRAME_PTR f, Lisp_Object name)
468   struct gcpro gcpro1;
469   Lisp_Object encoded_name, encoded_icon_name;
470   NSString *str;
471   NSView *view = FRAME_NS_VIEW (f);
473   GCPRO1 (name);
474   encoded_name = ENCODE_UTF_8 (name);
475   UNGCPRO;
477   str = [NSString stringWithUTF8String: SDATA (encoded_name)];
479   /* Don't change the name if it's already NAME.  */
480   if (! [[[view window] title] isEqualToString: str])
481     [[view window] setTitle: str];
483   if (!STRINGP (f->icon_name))
484     encoded_icon_name = encoded_name;
485   else
486     encoded_icon_name = ENCODE_UTF_8 (f->icon_name);
488   str = [NSString stringWithUTF8String: SDATA (encoded_icon_name)];
490   if ([[view window] miniwindowTitle] &&
491       ! [[[view window] miniwindowTitle] isEqualToString: str])
492     [[view window] setMiniwindowTitle: str];
496 static void
497 ns_set_name (struct frame *f, Lisp_Object name, int explicit)
499   NSView *view;
500   NSTRACE (ns_set_name);
502   if (ns_in_resize)
503     return;
505   /* Make sure that requests from lisp code override requests from
506      Emacs redisplay code.  */
507   if (explicit)
508     {
509       /* If we're switching from explicit to implicit, we had better
510          update the mode lines and thereby update the title.  */
511       if (f->explicit_name && NILP (name))
512         update_mode_lines = 1;
514       f->explicit_name = ! NILP (name);
515     }
516   else if (f->explicit_name)
517     return;
519   if (NILP (name))
520     name = build_string([ns_app_name UTF8String]);
521   else
522     CHECK_STRING (name);
524   /* Don't change the name if it's already NAME.  */
525   if (! NILP (Fstring_equal (name, f->name)))
526     return;
528   f->name = name;
530   /* title overrides explicit name */
531   if (! NILP (f->title))
532     name = f->title;
534   ns_set_name_internal (f, name);
538 /* This function should be called when the user's lisp code has
539    specified a name for the frame; the name will override any set by the
540    redisplay code.  */
541 static void
542 x_explicitly_set_name (FRAME_PTR f, Lisp_Object arg, Lisp_Object oldval)
544   NSTRACE (x_explicitly_set_name);
545   ns_set_name (f, arg, 1);
549 /* This function should be called by Emacs redisplay code to set the
550    name; names set this way will never override names set by the user's
551    lisp code.  */
552 void
553 x_implicitly_set_name (FRAME_PTR f, Lisp_Object arg, Lisp_Object oldval)
555   NSTRACE (x_implicitly_set_name);
557   /* Deal with NS specific format t.  */
558   if (FRAME_NS_P (f) && ((FRAME_ICONIFIED_P (f) && EQ (Vicon_title_format, Qt))
559                          || EQ (Vframe_title_format, Qt)))
560     ns_set_name_as_filename (f);
561   else
562     ns_set_name (f, arg, 0);
566 /* Change the title of frame F to NAME.
567    If NAME is nil, use the frame name as the title.  */
569 static void
570 x_set_title (struct frame *f, Lisp_Object name, Lisp_Object old_name)
572   NSTRACE (x_set_title);
573   /* Don't change the title if it's already NAME.  */
574   if (EQ (name, f->title))
575     return;
577   update_mode_lines = 1;
579   f->title = name;
581   if (NILP (name))
582     name = f->name;
583   else
584     CHECK_STRING (name);
586   ns_set_name_internal (f, name);
590 void
591 ns_set_name_as_filename (struct frame *f)
593   NSView *view;
594   Lisp_Object name, filename;
595   Lisp_Object buf = XWINDOW (f->selected_window)->buffer;
596   const char *title;
597   NSAutoreleasePool *pool;
598   struct gcpro gcpro1;
599   Lisp_Object encoded_name, encoded_filename;
600   NSString *str;
601   NSTRACE (ns_set_name_as_filename);
603   if (f->explicit_name || ! NILP (f->title) || ns_in_resize)
604     return;
606   BLOCK_INPUT;
607   pool = [[NSAutoreleasePool alloc] init];
608   filename = BVAR (XBUFFER (buf), filename);
609   name = BVAR (XBUFFER (buf), name);
611   if (NILP (name))
612     {
613       if (! NILP (filename))
614         name = Ffile_name_nondirectory (filename);
615       else
616         name = build_string ([ns_app_name UTF8String]);
617     }
619   GCPRO1 (name);
620   encoded_name = ENCODE_UTF_8 (name);
621   UNGCPRO;
623   view = FRAME_NS_VIEW (f);
625   title = FRAME_ICONIFIED_P (f) ? [[[view window] miniwindowTitle] UTF8String]
626                                 : [[[view window] title] UTF8String];
628   if (title && (! strcmp (title, SDATA (encoded_name))))
629     {
630       [pool release];
631       UNBLOCK_INPUT;
632       return;
633     }
635   str = [NSString stringWithUTF8String: SDATA (encoded_name)];
636   if (str == nil) str = @"Bad coding";
638   if (FRAME_ICONIFIED_P (f))
639     [[view window] setMiniwindowTitle: str];
640   else
641     {
642       NSString *fstr;
644       if (! NILP (filename))
645         {
646           GCPRO1 (filename);
647           encoded_filename = ENCODE_UTF_8 (filename);
648           UNGCPRO;
650           fstr = [NSString stringWithUTF8String: SDATA (encoded_filename)];
651           if (fstr == nil) fstr = @"";
652 #ifdef NS_IMPL_COCOA
653           /* work around a bug observed on 10.3 and later where
654              setTitleWithRepresentedFilename does not clear out previous state
655              if given filename does not exist */
656           if (! [[NSFileManager defaultManager] fileExistsAtPath: fstr])
657             [[view window] setRepresentedFilename: @""];
658 #endif
659         }
660       else
661         fstr = @"";
663       [[view window] setRepresentedFilename: fstr];
664       [[view window] setTitle: str];
665       f->name = name;
666     }
668   [pool release];
669   UNBLOCK_INPUT;
673 void
674 ns_set_doc_edited (struct frame *f, Lisp_Object arg)
676   NSView *view = FRAME_NS_VIEW (f);
677   NSAutoreleasePool *pool;
678   if (!MINI_WINDOW_P (XWINDOW (f->selected_window)))
679     {
680       BLOCK_INPUT;
681       pool = [[NSAutoreleasePool alloc] init];
682       [[view window] setDocumentEdited: !NILP (arg)];
683       [pool release];
684       UNBLOCK_INPUT;
685     }
689 void
690 x_set_menu_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
692   int nlines;
693   int olines = FRAME_MENU_BAR_LINES (f);
694   if (FRAME_MINIBUF_ONLY_P (f))
695     return;
697   if (INTEGERP (value))
698     nlines = XINT (value);
699   else
700     nlines = 0;
702   FRAME_MENU_BAR_LINES (f) = 0;
703   if (nlines)
704     {
705       FRAME_EXTERNAL_MENU_BAR (f) = 1;
706       /* does for all frames, whereas we just want for one frame
707          [NSMenu setMenuBarVisible: YES]; */
708     }
709   else
710     {
711       if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
712         free_frame_menubar (f);
713       /*      [NSMenu setMenuBarVisible: NO]; */
714       FRAME_EXTERNAL_MENU_BAR (f) = 0;
715     }
719 /* toolbar support */
720 void
721 x_set_tool_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
723   int nlines;
724   Lisp_Object root_window;
726   if (FRAME_MINIBUF_ONLY_P (f))
727     return;
729   if (INTEGERP (value) && XINT (value) >= 0)
730     nlines = XFASTINT (value);
731   else
732     nlines = 0;
734   if (nlines)
735     {
736       FRAME_EXTERNAL_TOOL_BAR (f) = 1;
737       update_frame_tool_bar (f);
738     }
739   else
740     {
741       if (FRAME_EXTERNAL_TOOL_BAR (f))
742         {
743           free_frame_tool_bar (f);
744           FRAME_EXTERNAL_TOOL_BAR (f) = 0;
745         }
746     }
748   x_set_window_size (f, 0, f->text_cols, f->text_lines);
752 void
753 ns_implicitly_set_icon_type (struct frame *f)
755   Lisp_Object tem;
756   EmacsView *view = FRAME_NS_VIEW (f);
757   id image =nil;
758   Lisp_Object chain, elt;
759   NSAutoreleasePool *pool;
760   BOOL setMini = YES;
762   NSTRACE (ns_implicitly_set_icon_type);
764   BLOCK_INPUT;
765   pool = [[NSAutoreleasePool alloc] init];
766   if (f->output_data.ns->miniimage
767       && [[NSString stringWithUTF8String: SDATA (f->name)]
768                isEqualToString: [(NSImage *)f->output_data.ns->miniimage name]])
769     {
770       [pool release];
771       UNBLOCK_INPUT;
772       return;
773     }
775   tem = assq_no_quit (Qicon_type, f->param_alist);
776   if (CONSP (tem) && ! NILP (XCDR (tem)))
777     {
778       [pool release];
779       UNBLOCK_INPUT;
780       return;
781     }
783   for (chain = Vns_icon_type_alist;
784        (image = nil) && CONSP (chain);
785        chain = XCDR (chain))
786     {
787       elt = XCAR (chain);
788       /* special case: 't' means go by file type */
789       if (SYMBOLP (elt) && EQ (elt, Qt) && SDATA (f->name)[0] == '/')
790         {
791           NSString *str
792              = [NSString stringWithUTF8String: SDATA (f->name)];
793           if ([[NSFileManager defaultManager] fileExistsAtPath: str])
794             image = [[[NSWorkspace sharedWorkspace] iconForFile: str] retain];
795         }
796       else if (CONSP (elt) &&
797                STRINGP (XCAR (elt)) &&
798                STRINGP (XCDR (elt)) &&
799                fast_string_match (XCAR (elt), f->name) >= 0)
800         {
801           image = [EmacsImage allocInitFromFile: XCDR (elt)];
802           if (image == nil)
803             image = [[NSImage imageNamed:
804                                [NSString stringWithUTF8String:
805                                             SDATA (XCDR (elt))]] retain];
806         }
807     }
809   if (image == nil)
810     {
811       image = [[[NSWorkspace sharedWorkspace] iconForFileType: @"text"] retain];
812       setMini = NO;
813     }
815   [f->output_data.ns->miniimage release];
816   f->output_data.ns->miniimage = image;
817   [view setMiniwindowImage: setMini];
818   [pool release];
819   UNBLOCK_INPUT;
823 static void
824 x_set_icon_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
826   EmacsView *view = FRAME_NS_VIEW (f);
827   id image = nil;
828   BOOL setMini = YES;
830   NSTRACE (x_set_icon_type);
832   if (!NILP (arg) && SYMBOLP (arg))
833     {
834       arg =build_string (SDATA (SYMBOL_NAME (arg)));
835       store_frame_param (f, Qicon_type, arg);
836     }
838   /* do it the implicit way */
839   if (NILP (arg))
840     {
841       ns_implicitly_set_icon_type (f);
842       return;
843     }
845   CHECK_STRING (arg);
847   image = [EmacsImage allocInitFromFile: arg];
848   if (image == nil)
849     image =[NSImage imageNamed: [NSString stringWithUTF8String:
850                                             SDATA (arg)]];
852   if (image == nil)
853     {
854       image = [NSImage imageNamed: @"text"];
855       setMini = NO;
856     }
858   f->output_data.ns->miniimage = image;
859   [view setMiniwindowImage: setMini];
863 /* Xism; we stub out (we do implement this in ns-win.el) */
865 XParseGeometry (char *string, int *x, int *y,
866                 unsigned int *width, unsigned int *height)
868   message1 ("Warning: XParseGeometry not supported under NS.\n");
869   return 0;
873 /* TODO: move to nsterm? */
875 ns_lisp_to_cursor_type (Lisp_Object arg)
877   char *str;
878   if (XTYPE (arg) == Lisp_String)
879     str = SDATA (arg);
880   else if (XTYPE (arg) == Lisp_Symbol)
881     str = SDATA (SYMBOL_NAME (arg));
882   else return -1;
883   if (!strcmp (str, "box"))     return FILLED_BOX_CURSOR;
884   if (!strcmp (str, "hollow"))  return HOLLOW_BOX_CURSOR;
885   if (!strcmp (str, "hbar"))    return HBAR_CURSOR;
886   if (!strcmp (str, "bar"))     return BAR_CURSOR;
887   if (!strcmp (str, "no"))      return NO_CURSOR;
888   return -1;
892 Lisp_Object
893 ns_cursor_type_to_lisp (int arg)
895   switch (arg)
896     {
897     case FILLED_BOX_CURSOR: return Qbox;
898     case HOLLOW_BOX_CURSOR: return intern ("hollow");
899     case HBAR_CURSOR:       return intern ("hbar");
900     case BAR_CURSOR:        return intern ("bar");
901     case NO_CURSOR:
902     default:                return intern ("no");
903     }
906 /* This is the same as the xfns.c definition.  */
907 void
908 x_set_cursor_type (FRAME_PTR f, Lisp_Object arg, Lisp_Object oldval)
910   set_frame_cursor_types (f, arg);
912   /* Make sure the cursor gets redrawn.  */
913   cursor_type_changed = 1;
917 /* called to set mouse pointer color, but all other terms use it to
918    initialize pointer types (and don't set the color ;) */
919 static void
920 x_set_mouse_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
922   /* don't think we can do this on Nextstep */
926 #define Str(x) #x
927 #define Xstr(x) Str(x)
929 static Lisp_Object
930 ns_appkit_version_str (void)
932   char tmp[80];
934 #ifdef NS_IMPL_GNUSTEP
935   sprintf(tmp, "gnustep-gui-%s", Xstr(GNUSTEP_GUI_VERSION));
936 #elif defined(NS_IMPL_COCOA)
937   sprintf(tmp, "apple-appkit-%.2f", NSAppKitVersionNumber);
938 #else
939   tmp = "ns-unknown";
940 #endif
941   return build_string (tmp);
945 /* This is for use by x-server-version and collapses all version info we
946    have into a single int.  For a better picture of the implementation
947    running, use ns_appkit_version_str.*/
948 static int
949 ns_appkit_version_int (void)
951 #ifdef NS_IMPL_GNUSTEP
952   return GNUSTEP_GUI_MAJOR_VERSION * 100 + GNUSTEP_GUI_MINOR_VERSION;
953 #elif defined(NS_IMPL_COCOA)
954   return (int)NSAppKitVersionNumber;
955 #endif
956   return 0;
960 static void
961 x_icon (struct frame *f, Lisp_Object parms)
962 /* --------------------------------------------------------------------------
963    Strangely-named function to set icon position parameters in frame.
964    This is irrelevant under OS X, but might be needed under GNUstep,
965    depending on the window manager used.  Note, this is not a standard
966    frame parameter-setter; it is called directly from x-create-frame.
967    -------------------------------------------------------------------------- */
969   Lisp_Object icon_x, icon_y;
970   struct ns_display_info *dpyinfo = check_ns_display_info (Qnil);
972   f->output_data.ns->icon_top = Qnil;
973   f->output_data.ns->icon_left = Qnil;
975   /* Set the position of the icon.  */
976   icon_x = x_get_arg (dpyinfo, parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
977   icon_y = x_get_arg (dpyinfo, parms, Qicon_top, 0, 0,  RES_TYPE_NUMBER);
978   if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
979     {
980       CHECK_NUMBER (icon_x);
981       CHECK_NUMBER (icon_y);
982       f->output_data.ns->icon_top = icon_y;
983       f->output_data.ns->icon_left = icon_x;
984     }
985   else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
986     error ("Both left and top icon corners of icon must be specified");
990 /* Note: see frame.c for template, also where generic functions are impl */
991 frame_parm_handler ns_frame_parm_handlers[] =
993   x_set_autoraise, /* generic OK */
994   x_set_autolower, /* generic OK */
995   x_set_background_color,
996   0, /* x_set_border_color,  may be impossible under Nextstep */
997   0, /* x_set_border_width,  may be impossible under Nextstep */
998   x_set_cursor_color,
999   x_set_cursor_type,
1000   x_set_font, /* generic OK */
1001   x_set_foreground_color,
1002   x_set_icon_name,
1003   x_set_icon_type,
1004   x_set_internal_border_width, /* generic OK */
1005   x_set_menu_bar_lines,
1006   x_set_mouse_color,
1007   x_explicitly_set_name,
1008   x_set_scroll_bar_width, /* generic OK */
1009   x_set_title,
1010   x_set_unsplittable, /* generic OK */
1011   x_set_vertical_scroll_bars, /* generic OK */
1012   x_set_visibility, /* generic OK */
1013   x_set_tool_bar_lines,
1014   0, /* x_set_scroll_bar_foreground, will ignore (not possible on NS) */
1015   0, /* x_set_scroll_bar_background,  will ignore (not possible on NS) */
1016   x_set_screen_gamma, /* generic OK */
1017   x_set_line_spacing, /* generic OK, sets f->extra_line_spacing to int */
1018   x_set_fringe_width, /* generic OK */
1019   x_set_fringe_width, /* generic OK */
1020   0, /* x_set_wait_for_wm, will ignore */
1021   0,  /* x_set_fullscreen will ignore */
1022   x_set_font_backend, /* generic OK */
1023   x_set_alpha,
1024   0, /* x_set_sticky */
1025   0, /* x_set_tool_bar_position */
1030 /* ==========================================================================
1032     Lisp definitions
1034    ========================================================================== */
1036 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
1037        1, 1, 0,
1038        doc: /* Make a new Nextstep window, called a \"frame\" in Emacs terms.
1039 Return an Emacs frame object.
1040 PARMS is an alist of frame parameters.
1041 If the parameters specify that the frame should not have a minibuffer,
1042 and do not specify a specific minibuffer window to use,
1043 then `default-minibuffer-frame' must be a frame whose minibuffer can
1044 be shared by the new frame.  */)
1045      (Lisp_Object parms)
1047   static int desc_ctr = 1;
1048   struct frame *f;
1049   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1050   Lisp_Object frame, tem;
1051   Lisp_Object name;
1052   int minibuffer_only = 0;
1053   int count = specpdl_ptr - specpdl;
1054   Lisp_Object display;
1055   struct ns_display_info *dpyinfo = NULL;
1056   Lisp_Object parent;
1057   struct kboard *kb;
1058   Lisp_Object tfont, tfontsize;
1059   int window_prompting = 0;
1060   int width, height;
1062   check_ns ();
1064   /* Seems a little strange, but other terms do it. Perhaps the code below
1065      is modifying something? */
1066   parms = Fcopy_alist (parms);
1068   display = x_get_arg (dpyinfo, parms, Qterminal, 0, 0, RES_TYPE_STRING);
1069   if (EQ (display, Qunbound))
1070     display = Qnil;
1071   dpyinfo = check_ns_display_info (display);
1073   if (!dpyinfo->terminal->name)
1074     error ("Terminal is not live, can't create new frames on it");
1076   kb = dpyinfo->terminal->kboard;
1078   name = x_get_arg (dpyinfo, parms, Qname, 0, 0, RES_TYPE_STRING);
1079   if (!STRINGP (name)
1080       && ! EQ (name, Qunbound)
1081       && ! NILP (name))
1082     error ("Invalid frame name--not a string or nil");
1084   if (STRINGP (name))
1085     Vx_resource_name = name;
1086   else
1087     Vx_resource_name = Vinvocation_name;
1089   parent = x_get_arg (dpyinfo, parms, Qparent_id, 0, 0, RES_TYPE_NUMBER);
1090   if (EQ (parent, Qunbound))
1091     parent = Qnil;
1092   if (! NILP (parent))
1093     CHECK_NUMBER (parent);
1095   frame = Qnil;
1096   GCPRO4 (parms, parent, name, frame);
1098   tem = x_get_arg (dpyinfo, parms, Qminibuffer, "minibuffer", "Minibuffer",
1099                   RES_TYPE_SYMBOL);
1100   if (EQ (tem, Qnone) || NILP (tem))
1101     {
1102       f = make_frame_without_minibuffer (Qnil, kb, display);
1103     }
1104   else if (EQ (tem, Qonly))
1105     {
1106       f = make_minibuffer_frame ();
1107       minibuffer_only = 1;
1108     }
1109   else if (WINDOWP (tem))
1110     {
1111       f = make_frame_without_minibuffer (tem, kb, display);
1112     }
1113   else
1114     {
1115       f = make_frame (1);
1116     }
1118   /* Set the name; the functions to which we pass f expect the name to
1119      be set.  */
1120   if (EQ (name, Qunbound) || NILP (name) || (XTYPE (name) != Lisp_String))
1121     {
1122       f->name = build_string ([ns_app_name UTF8String]);
1123       f->explicit_name =0;
1124     }
1125   else
1126     {
1127       f->name = name;
1128       f->explicit_name = 1;
1129       specbind (Qx_resource_name, name);
1130     }
1132   XSETFRAME (frame, f);
1133   FRAME_CAN_HAVE_SCROLL_BARS (f) = 1;
1135   f->terminal = dpyinfo->terminal;
1136   f->terminal->reference_count++;
1138   f->output_method = output_ns;
1139   f->output_data.ns = (struct ns_output *)xmalloc (sizeof *(f->output_data.ns));
1140   memset (f->output_data.ns, 0, sizeof (*(f->output_data.ns)));
1142   FRAME_FONTSET (f) = -1;
1144   /* record_unwind_protect (unwind_create_frame, frame); safety; maybe later? */
1146   f->icon_name = x_get_arg (dpyinfo, parms, Qicon_name, "iconName", "Title",
1147                             RES_TYPE_STRING);
1148   if (! STRINGP (f->icon_name))
1149     f->icon_name = Qnil;
1151   FRAME_NS_DISPLAY_INFO (f) = dpyinfo;
1153   f->output_data.ns->window_desc = desc_ctr++;
1154   if (!NILP (parent))
1155     {
1156       f->output_data.ns->parent_desc = (Window) XFASTINT (parent);
1157       f->output_data.ns->explicit_parent = 1;
1158     }
1159   else
1160     {
1161       f->output_data.ns->parent_desc = FRAME_NS_DISPLAY_INFO (f)->root_window;
1162       f->output_data.ns->explicit_parent = 0;
1163     }
1165   f->resx = dpyinfo->resx;
1166   f->resy = dpyinfo->resy;
1168   BLOCK_INPUT;
1169   register_font_driver (&nsfont_driver, f);
1170   x_default_parameter (f, parms, Qfont_backend, Qnil,
1171                         "fontBackend", "FontBackend", RES_TYPE_STRING);
1173   {
1174     /* use for default font name */
1175     id font = [NSFont userFixedPitchFontOfSize: -1.0]; /* default */
1176     tfontsize = x_default_parameter (f, parms, Qfontsize,
1177                                     make_number (0 /*(int)[font pointSize]*/),
1178                                     "fontSize", "FontSize", RES_TYPE_NUMBER);
1179     tfont = x_default_parameter (f, parms, Qfont,
1180                                  build_string ([[font fontName] UTF8String]),
1181                                  "font", "Font", RES_TYPE_STRING);
1182   }
1183   UNBLOCK_INPUT;
1185   x_default_parameter (f, parms, Qborder_width, make_number (0),
1186                        "borderwidth", "BorderWidth", RES_TYPE_NUMBER);
1187   x_default_parameter (f, parms, Qinternal_border_width, make_number (2),
1188                       "internalBorderWidth", "InternalBorderWidth",
1189                       RES_TYPE_NUMBER);
1191   /* default scrollbars on right on Mac */
1192   {
1193       Lisp_Object spos
1194 #ifdef NS_IMPL_GNUSTEP
1195           = Qt;
1196 #else
1197           = Qright;
1198 #endif
1199       x_default_parameter (f, parms, Qvertical_scroll_bars, spos,
1200                            "verticalScrollBars", "VerticalScrollBars",
1201                            RES_TYPE_SYMBOL);
1202   }
1203   x_default_parameter (f, parms, Qforeground_color, build_string ("Black"),
1204                       "foreground", "Foreground", RES_TYPE_STRING);
1205   x_default_parameter (f, parms, Qbackground_color, build_string ("White"),
1206                       "background", "Background", RES_TYPE_STRING);
1207   /* FIXME: not suppported yet in Nextstep */
1208   x_default_parameter (f, parms, Qline_spacing, Qnil,
1209                        "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
1210   x_default_parameter (f, parms, Qleft_fringe, Qnil,
1211                        "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
1212   x_default_parameter (f, parms, Qright_fringe, Qnil,
1213                        "rightFringe", "RightFringe", RES_TYPE_NUMBER);
1214   /* end PENDING */
1216   init_frame_faces (f);
1218   /* The X resources controlling the menu-bar and tool-bar are
1219      processed specially at startup, and reflected in the mode
1220      variables; ignore them here.  */
1221   x_default_parameter (f, parms, Qmenu_bar_lines,
1222                        NILP (Vmenu_bar_mode)
1223                        ? make_number (0) : make_number (1),
1224                        NULL, NULL, RES_TYPE_NUMBER);
1225   x_default_parameter (f, parms, Qtool_bar_lines,
1226                        NILP (Vtool_bar_mode)
1227                        ? make_number (0) : make_number (1),
1228                        NULL, NULL, RES_TYPE_NUMBER);
1230   x_default_parameter (f, parms, Qbuffer_predicate, Qnil, "bufferPredicate",
1231                        "BufferPredicate", RES_TYPE_SYMBOL);
1232   x_default_parameter (f, parms, Qtitle, Qnil, "title", "Title",
1233                        RES_TYPE_STRING);
1235 /* TODO: other terms seem to get away w/o this complexity.. */
1236   if (NILP (Fassq (Qwidth, parms)))
1237     {
1238       Lisp_Object value
1239          = x_get_arg (dpyinfo, parms, Qwidth, "width", "Width",
1240                       RES_TYPE_NUMBER);
1241       if (! EQ (value, Qunbound))
1242         parms = Fcons (Fcons (Qwidth, value), parms);
1243     }
1244   if (NILP (Fassq (Qheight, parms)))
1245     {
1246       Lisp_Object value
1247          = x_get_arg (dpyinfo, parms, Qheight, "height", "Height",
1248                       RES_TYPE_NUMBER);
1249       if (! EQ (value, Qunbound))
1250         parms = Fcons (Fcons (Qheight, value), parms);
1251     }
1252   if (NILP (Fassq (Qleft, parms)))
1253     {
1254       Lisp_Object value
1255          = x_get_arg (dpyinfo, parms, Qleft, "left", "Left", RES_TYPE_NUMBER);
1256       if (! EQ (value, Qunbound))
1257         parms = Fcons (Fcons (Qleft, value), parms);
1258     }
1259   if (NILP (Fassq (Qtop, parms)))
1260     {
1261       Lisp_Object value
1262          = x_get_arg (dpyinfo, parms, Qtop, "top", "Top", RES_TYPE_NUMBER);
1263       if (! EQ (value, Qunbound))
1264         parms = Fcons (Fcons (Qtop, value), parms);
1265     }
1267   window_prompting = x_figure_window_size (f, parms, 1);
1269   tem = x_get_arg (dpyinfo, parms, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
1270   f->no_split = minibuffer_only || (!EQ (tem, Qunbound) && !EQ (tem, Qnil));
1272   /* NOTE: on other terms, this is done in set_mouse_color, however this
1273      was not getting called under Nextstep */
1274   f->output_data.ns->text_cursor = [NSCursor IBeamCursor];
1275   f->output_data.ns->nontext_cursor = [NSCursor arrowCursor];
1276   f->output_data.ns->modeline_cursor = [NSCursor pointingHandCursor];
1277   f->output_data.ns->hand_cursor = [NSCursor pointingHandCursor];
1278   f->output_data.ns->hourglass_cursor = [NSCursor disappearingItemCursor];
1279   f->output_data.ns->horizontal_drag_cursor = [NSCursor resizeLeftRightCursor];
1280   FRAME_NS_DISPLAY_INFO (f)->vertical_scroll_bar_cursor
1281      = [NSCursor arrowCursor];
1282   f->output_data.ns->current_pointer = f->output_data.ns->text_cursor;
1284   [[EmacsView alloc] initFrameFromEmacs: f];
1286   x_icon (f, parms);
1288   /* It is now ok to make the frame official even if we get an error below.
1289      The frame needs to be on Vframe_list or making it visible won't work. */
1290   Vframe_list = Fcons (frame, Vframe_list);
1291   /*FRAME_NS_DISPLAY_INFO (f)->reference_count++; */
1293   x_default_parameter (f, parms, Qicon_type, Qnil, "bitmapIcon", "BitmapIcon",
1294                       RES_TYPE_SYMBOL);
1295   x_default_parameter (f, parms, Qauto_raise, Qnil, "autoRaise", "AutoRaiseLower",
1296                       RES_TYPE_BOOLEAN);
1297   x_default_parameter (f, parms, Qauto_lower, Qnil, "autoLower", "AutoLower",
1298                       RES_TYPE_BOOLEAN);
1299   x_default_parameter (f, parms, Qcursor_type, Qbox, "cursorType", "CursorType",
1300                       RES_TYPE_SYMBOL);
1301   x_default_parameter (f, parms, Qscroll_bar_width, Qnil, "scrollBarWidth",
1302                       "ScrollBarWidth", RES_TYPE_NUMBER);
1303   x_default_parameter (f, parms, Qalpha, Qnil, "alpha", "Alpha",
1304                       RES_TYPE_NUMBER);
1306   width = FRAME_COLS (f);
1307   height = FRAME_LINES (f);
1309   SET_FRAME_COLS (f, 0);
1310   FRAME_LINES (f) = 0;
1311   change_frame_size (f, height, width, 1, 0, 0);
1313   if (! f->output_data.ns->explicit_parent)
1314     {
1315       tem = x_get_arg (dpyinfo, parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
1316       if (EQ (tem, Qunbound))
1317         tem = Qt;
1318       x_set_visibility (f, tem, Qnil);
1319       if (EQ (tem, Qicon))
1320         x_iconify_frame (f);
1321       else if (! NILP (tem))
1322         {
1323           x_make_frame_visible (f);
1324           f->async_visible = 1;
1325           [[FRAME_NS_VIEW (f) window] makeKeyWindow];
1326         }
1327       else
1328           f->async_visible = 0;
1329     }
1331   if (FRAME_HAS_MINIBUF_P (f)
1332       && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
1333           || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
1334     KVAR (kb, Vdefault_minibuffer_frame) = frame;
1336   /* All remaining specified parameters, which have not been "used"
1337      by x_get_arg and friends, now go in the misc. alist of the frame.  */
1338   for (tem = parms; CONSP (tem); tem = XCDR (tem))
1339     if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
1340       f->param_alist = Fcons (XCAR (tem), f->param_alist);
1342   UNGCPRO;
1343   Vwindow_list = Qnil;
1345   return unbind_to (count, frame);
1349 DEFUN ("x-focus-frame", Fx_focus_frame, Sx_focus_frame, 1, 1, 0,
1350        doc: /* Set the input focus to FRAME.
1351 FRAME nil means use the selected frame.  */)
1352      (Lisp_Object frame)
1354   struct frame *f = check_ns_frame (frame);
1355   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1357   if (dpyinfo->x_focus_frame != f)
1358     {
1359       EmacsView *view = FRAME_NS_VIEW (f);
1360       BLOCK_INPUT;
1361       [NSApp activateIgnoringOtherApps: YES];
1362       [[view window] makeKeyAndOrderFront: view];
1363       UNBLOCK_INPUT;
1364     }
1366   return Qnil;
1370 DEFUN ("ns-popup-font-panel", Fns_popup_font_panel, Sns_popup_font_panel,
1371        0, 1, "",
1372        doc: /* Pop up the font panel. */)
1373      (Lisp_Object frame)
1375   id fm;
1376   struct frame *f;
1378   check_ns ();
1379   fm = [NSFontManager sharedFontManager];
1380   if (NILP (frame))
1381     f = SELECTED_FRAME ();
1382   else
1383     {
1384       CHECK_FRAME (frame);
1385       f = XFRAME (frame);
1386     }
1388   [fm setSelectedFont: ((struct nsfont_info *)f->output_data.ns->font)->nsfont
1389            isMultiple: NO];
1390   [fm orderFrontFontPanel: NSApp];
1391   return Qnil;
1395 DEFUN ("ns-popup-color-panel", Fns_popup_color_panel, Sns_popup_color_panel,
1396        0, 1, "",
1397        doc: /* Pop up the color panel.  */)
1398      (Lisp_Object frame)
1400   struct frame *f;
1402   check_ns ();
1403   if (NILP (frame))
1404     f = SELECTED_FRAME ();
1405   else
1406     {
1407       CHECK_FRAME (frame);
1408       f = XFRAME (frame);
1409     }
1411   [NSApp orderFrontColorPanel: NSApp];
1412   return Qnil;
1416 DEFUN ("ns-read-file-name", Fns_read_file_name, Sns_read_file_name, 1, 4, 0,
1417        doc: /* Use a graphical panel to read a file name, using prompt PROMPT.
1418 Optional arg DIR, if non-nil, supplies a default directory.
1419 Optional arg MUSTMATCH, if non-nil, means the returned file or
1420 directory must exist.
1421 Optional arg INIT, if non-nil, provides a default file name to use.  */)
1422      (Lisp_Object prompt, Lisp_Object dir, Lisp_Object mustmatch, Lisp_Object init)
1424   static id fileDelegate = nil;
1425   int ret;
1426   id panel;
1427   Lisp_Object fname;
1429   NSString *promptS = NILP (prompt) || !STRINGP (prompt) ? nil :
1430     [NSString stringWithUTF8String: SDATA (prompt)];
1431   NSString *dirS = NILP (dir) || !STRINGP (dir) ?
1432     [NSString stringWithUTF8String: SDATA (BVAR (current_buffer, directory))] :
1433     [NSString stringWithUTF8String: SDATA (dir)];
1434   NSString *initS = NILP (init) || !STRINGP (init) ? nil :
1435     [NSString stringWithUTF8String: SDATA (init)];
1437   check_ns ();
1439   if (fileDelegate == nil)
1440     fileDelegate = [EmacsFileDelegate new];
1442   [NSCursor setHiddenUntilMouseMoves: NO];
1444   if ([dirS characterAtIndex: 0] == '~')
1445     dirS = [dirS stringByExpandingTildeInPath];
1447   panel = NILP (mustmatch) ?
1448     (id)[EmacsSavePanel savePanel] : (id)[EmacsOpenPanel openPanel];
1450   [panel setTitle: promptS];
1452   /* Puma (10.1) does not have */
1453   if ([panel respondsToSelector: @selector (setAllowsOtherFileTypes:)])
1454     [panel setAllowsOtherFileTypes: YES];
1456   [panel setTreatsFilePackagesAsDirectories: YES];
1457   [panel setDelegate: fileDelegate];
1459   panelOK = 0;
1460   BLOCK_INPUT;
1461   if (NILP (mustmatch))
1462     {
1463       ret = [panel runModalForDirectory: dirS file: initS];
1464     }
1465   else
1466     {
1467       [panel setCanChooseDirectories: YES];
1468       ret = [panel runModalForDirectory: dirS file: initS types: nil];
1469     }
1471   ret = (ret == NSOKButton) || panelOK;
1473   if (ret)
1474     fname = build_string ([[panel filename] UTF8String]);
1476   [[FRAME_NS_VIEW (SELECTED_FRAME ()) window] makeKeyWindow];
1477   UNBLOCK_INPUT;
1479   return ret ? fname : Qnil;
1483 DEFUN ("ns-get-resource", Fns_get_resource, Sns_get_resource, 2, 2, 0,
1484        doc: /* Return the value of the property NAME of OWNER from the defaults database.
1485 If OWNER is nil, Emacs is assumed.  */)
1486      (Lisp_Object owner, Lisp_Object name)
1488   const char *value;
1490   check_ns ();
1491   if (NILP (owner))
1492     owner = build_string([ns_app_name UTF8String]);
1493   CHECK_STRING (name);
1494 /*fprintf (stderr, "ns-get-resource checking resource '%s'\n", SDATA (name)); */
1496   value =[[[NSUserDefaults standardUserDefaults]
1497             objectForKey: [NSString stringWithUTF8String: SDATA (name)]]
1498            UTF8String];
1500   if (value)
1501     return build_string (value);
1502   return Qnil;
1506 DEFUN ("ns-set-resource", Fns_set_resource, Sns_set_resource, 3, 3, 0,
1507        doc: /* Set property NAME of OWNER to VALUE, from the defaults database.
1508 If OWNER is nil, Emacs is assumed.
1509 If VALUE is nil, the default is removed.  */)
1510      (Lisp_Object owner, Lisp_Object name, Lisp_Object value)
1512   check_ns ();
1513   if (NILP (owner))
1514     owner = build_string ([ns_app_name UTF8String]);
1515   CHECK_STRING (name);
1516   if (NILP (value))
1517     {
1518       [[NSUserDefaults standardUserDefaults] removeObjectForKey:
1519                          [NSString stringWithUTF8String: SDATA (name)]];
1520     }
1521   else
1522     {
1523       CHECK_STRING (value);
1524       [[NSUserDefaults standardUserDefaults] setObject:
1525                 [NSString stringWithUTF8String: SDATA (value)]
1526                                         forKey: [NSString stringWithUTF8String:
1527                                                          SDATA (name)]];
1528     }
1530   return Qnil;
1534 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
1535        Sx_server_max_request_size,
1536        0, 1, 0,
1537        doc: /* This function is a no-op.  It is only present for completeness.  */)
1538      (Lisp_Object display)
1540   check_ns ();
1541   /* This function has no real equivalent under NeXTstep.  Return nil to
1542      indicate this. */
1543   return Qnil;
1547 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
1548        doc: /* Return the vendor ID string of Nextstep display server DISPLAY.
1549 DISPLAY should be either a frame or a display name (a string).
1550 If omitted or nil, the selected frame's display is used.  */)
1551      (Lisp_Object display)
1553 #ifdef NS_IMPL_GNUSTEP
1554   return build_string ("GNU");
1555 #else
1556   return build_string ("Apple");
1557 #endif
1561 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
1562        doc: /* Return the version numbers of the server of DISPLAY.
1563 The value is a list of three integers: the major and minor
1564 version numbers of the X Protocol in use, and the distributor-specific
1565 release number.  See also the function `x-server-vendor'.
1567 The optional argument DISPLAY specifies which display to ask about.
1568 DISPLAY should be either a frame or a display name (a string).
1569 If omitted or nil, that stands for the selected frame's display.  */)
1570      (Lisp_Object display)
1572   /*NOTE: it is unclear what would best correspond with "protocol";
1573           we return 10.3, meaning Panther, since this is roughly the
1574           level that GNUstep's APIs correspond to.
1575           The last number is where we distinguish between the Apple
1576           and GNUstep implementations ("distributor-specific release
1577           number") and give int'ized versions of major.minor. */
1578   return Fcons (make_number (10),
1579                 Fcons (make_number (3),
1580                        Fcons (make_number (ns_appkit_version_int()), Qnil)));
1584 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
1585        doc: /* Return the number of screens on Nextstep display server DISPLAY.
1586 DISPLAY should be a frame, the display name as a string, or a terminal ID.
1587 If omitted or nil, the selected frame's display is used.  */)
1588      (Lisp_Object display)
1590   int num;
1592   check_ns ();
1593   num = [[NSScreen screens] count];
1595   return (num != 0) ? make_number (num) : Qnil;
1599 DEFUN ("x-display-mm-height", Fx_display_mm_height, Sx_display_mm_height,
1600        0, 1, 0,
1601        doc: /* Return the height of Nextstep display server DISPLAY, in millimeters.
1602 DISPLAY should be a frame, the display name as a string, or a terminal ID.
1603 If omitted or nil, the selected frame's display is used.  */)
1604      (Lisp_Object display)
1606   check_ns ();
1607   return make_number ((int)
1608                      ([ns_get_screen (display) frame].size.height/(92.0/25.4)));
1612 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width,
1613        0, 1, 0,
1614        doc: /* Return the width of Nextstep display server DISPLAY, in millimeters.
1615 DISPLAY should be a frame, the display name as a string, or a terminal ID.
1616 If omitted or nil, the selected frame's display is used.  */)
1617      (Lisp_Object display)
1619   check_ns ();
1620   return make_number ((int)
1621                      ([ns_get_screen (display) frame].size.width/(92.0/25.4)));
1625 DEFUN ("x-display-backing-store", Fx_display_backing_store,
1626        Sx_display_backing_store, 0, 1, 0,
1627        doc: /* Return whether the Nexstep display DISPLAY supports backing store.
1628 The value may be `buffered', `retained', or `non-retained'.
1629 DISPLAY should be a frame, the display name as a string, or a terminal ID.
1630 If omitted or nil, the selected frame's display is used.  */)
1631      (Lisp_Object display)
1633   check_ns ();
1634   switch ([ns_get_window (display) backingType])
1635     {
1636     case NSBackingStoreBuffered:
1637       return intern ("buffered");
1638     case NSBackingStoreRetained:
1639       return intern ("retained");
1640     case NSBackingStoreNonretained:
1641       return intern ("non-retained");
1642     default:
1643       error ("Strange value for backingType parameter of frame");
1644     }
1645   return Qnil;  /* not reached, shut compiler up */
1649 DEFUN ("x-display-visual-class", Fx_display_visual_class,
1650        Sx_display_visual_class, 0, 1, 0,
1651        doc: /* Return the visual class of the Nextstep display server DISPLAY.
1652 The value is one of the symbols `static-gray', `gray-scale',
1653 `static-color', `pseudo-color', `true-color', or `direct-color'.
1654 DISPLAY should be a frame, the display name as a string, or a terminal ID.
1655 If omitted or nil, the selected frame's display is used.  */)
1656      (Lisp_Object display)
1658   NSWindowDepth depth;
1659   check_ns ();
1660   depth = [ns_get_screen (display) depth];
1662   if ( depth == NSBestDepth (NSCalibratedWhiteColorSpace, 2, 2, YES, NULL))
1663     return intern ("static-gray");
1664   else if (depth == NSBestDepth (NSCalibratedWhiteColorSpace, 8, 8, YES, NULL))
1665     return intern ("gray-scale");
1666   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 8, 8, YES, NULL))
1667     return intern ("pseudo-color");
1668   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 4, 12, NO, NULL))
1669     return intern ("true-color");
1670   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 8, 24, NO, NULL))
1671     return intern ("direct-color");
1672   else
1673     /* color mgmt as far as we do it is really handled by Nextstep itself anyway */
1674     return intern ("direct-color");
1678 DEFUN ("x-display-save-under", Fx_display_save_under,
1679        Sx_display_save_under, 0, 1, 0,
1680        doc: /* Return t if DISPLAY supports the save-under feature.
1681 The optional argument DISPLAY specifies which display to ask about.
1682 DISPLAY should be a frame, the display name as a string, or a terminal ID.
1683 If omitted or nil, the selected frame's display is used.  */)
1684      (Lisp_Object display)
1686   check_ns ();
1687   switch ([ns_get_window (display) backingType])
1688     {
1689     case NSBackingStoreBuffered:
1690       return Qt;
1692     case NSBackingStoreRetained:
1693     case NSBackingStoreNonretained:
1694       return Qnil;
1696     default:
1697       error ("Strange value for backingType parameter of frame");
1698     }
1699   return Qnil;  /* not reached, shut compiler up */
1703 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
1704        1, 3, 0,
1705        doc: /* Open a connection to a display server.
1706 DISPLAY is the name of the display to connect to.
1707 Optional second arg XRM-STRING is a string of resources in xrdb format.
1708 If the optional third arg MUST-SUCCEED is non-nil,
1709 terminate Emacs if we can't open the connection.
1710 \(In the Nextstep version, the last two arguments are currently ignored.)  */)
1711      (Lisp_Object display, Lisp_Object resource_string, Lisp_Object must_succeed)
1713   struct ns_display_info *dpyinfo;
1715   CHECK_STRING (display);
1717   nxatoms_of_nsselect ();
1718   dpyinfo = ns_term_init (display);
1719   if (dpyinfo == 0)
1720     {
1721       if (!NILP (must_succeed))
1722         fatal ("OpenStep on %s not responding.\n",
1723                SDATA (display));
1724       else
1725         error ("OpenStep on %s not responding.\n",
1726                SDATA (display));
1727     }
1729   /* Register our external input/output types, used for determining
1730      applicable services and also drag/drop eligibility. */
1731   ns_send_types = [[NSArray arrayWithObjects: NSStringPboardType, nil] retain];
1732   ns_return_types = [[NSArray arrayWithObjects: NSStringPboardType, nil]
1733                       retain];
1734   ns_drag_types = [[NSArray arrayWithObjects:
1735                             NSStringPboardType,
1736                             NSTabularTextPboardType,
1737                             NSFilenamesPboardType,
1738                             NSURLPboardType,
1739                             NSColorPboardType,
1740                             NSFontPboardType, nil] retain];
1742   return Qnil;
1746 DEFUN ("x-close-connection", Fx_close_connection, Sx_close_connection,
1747        1, 1, 0,
1748        doc: /* Close the connection to the current Nextstep display server.
1749 The argument DISPLAY is currently ignored.  */)
1750      (Lisp_Object display)
1752   check_ns ();
1753   /*ns_delete_terminal (dpyinfo->terminal); */
1754   [NSApp terminate: NSApp];
1755   return Qnil;
1759 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
1760        doc: /* Return the list of display names that Emacs has connections to.  */)
1761      (void)
1763   Lisp_Object tail, result;
1765   result = Qnil;
1766   for (tail = ns_display_name_list; CONSP (tail); tail = XCDR (tail))
1767     result = Fcons (XCAR (XCAR (tail)), result);
1769   return result;
1773 DEFUN ("ns-hide-others", Fns_hide_others, Sns_hide_others,
1774        0, 0, 0,
1775        doc: /* Hides all applications other than Emacs.  */)
1776      (void)
1778   check_ns ();
1779   [NSApp hideOtherApplications: NSApp];
1780   return Qnil;
1783 DEFUN ("ns-hide-emacs", Fns_hide_emacs, Sns_hide_emacs,
1784        1, 1, 0,
1785        doc: /* If ON is non-nil, the entire Emacs application is hidden.
1786 Otherwise if Emacs is hidden, it is unhidden.
1787 If ON is equal to `activate', Emacs is unhidden and becomes
1788 the active application.  */)
1789      (Lisp_Object on)
1791   check_ns ();
1792   if (EQ (on, intern ("activate")))
1793     {
1794       [NSApp unhide: NSApp];
1795       [NSApp activateIgnoringOtherApps: YES];
1796     }
1797   else if (NILP (on))
1798     [NSApp unhide: NSApp];
1799   else
1800     [NSApp hide: NSApp];
1801   return Qnil;
1805 DEFUN ("ns-emacs-info-panel", Fns_emacs_info_panel, Sns_emacs_info_panel,
1806        0, 0, 0,
1807        doc: /* Shows the 'Info' or 'About' panel for Emacs.  */)
1808      (void)
1810   check_ns ();
1811   [NSApp orderFrontStandardAboutPanel: nil];
1812   return Qnil;
1816 DEFUN ("ns-font-name", Fns_font_name, Sns_font_name, 1, 1, 0,
1817        doc: /* Determine font postscript or family name for font NAME.
1818 NAME should be a string containing either the font name or an XLFD
1819 font descriptor.  If string contains `fontset' and not
1820 `fontset-startup', it is left alone. */)
1821      (Lisp_Object name)
1823   char *nm;
1824   CHECK_STRING (name);
1825   nm = SDATA (name);
1827   if (nm[0] != '-')
1828     return name;
1829   if (strstr (nm, "fontset") && !strstr (nm, "fontset-startup"))
1830     return name;
1832   return build_string (ns_xlfd_to_fontname (SDATA (name)));
1836 DEFUN ("ns-list-colors", Fns_list_colors, Sns_list_colors, 0, 1, 0,
1837        doc: /* Return a list of all available colors.
1838 The optional argument FRAME is currently ignored.  */)
1839      (Lisp_Object frame)
1841   Lisp_Object list = Qnil;
1842   NSEnumerator *colorlists;
1843   NSColorList *clist;
1845   if (!NILP (frame))
1846     {
1847       CHECK_FRAME (frame);
1848       if (! FRAME_NS_P (XFRAME (frame)))
1849         error ("non-Nextstep frame used in `ns-list-colors'");
1850     }
1852   BLOCK_INPUT;
1854   colorlists = [[NSColorList availableColorLists] objectEnumerator];
1855   while (clist = [colorlists nextObject])
1856     {
1857       if ([[clist name] length] < 7 ||
1858           [[clist name] rangeOfString: @"PANTONE"].location == 0)
1859         {
1860           NSEnumerator *cnames = [[clist allKeys] reverseObjectEnumerator];
1861           NSString *cname;
1862           while (cname = [cnames nextObject])
1863             list = Fcons (build_string ([cname UTF8String]), list);
1864 /*           for (i = [[clist allKeys] count] - 1; i >= 0; i--)
1865                list = Fcons (build_string ([[[clist allKeys] objectAtIndex: i]
1866                                              UTF8String]), list); */
1867         }
1868     }
1870   UNBLOCK_INPUT;
1872   return list;
1876 DEFUN ("ns-list-services", Fns_list_services, Sns_list_services, 0, 0, 0,
1877        doc: /* List available Nextstep services by querying NSApp.  */)
1878      (void)
1880 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
1881   /* You can't get services like this in 10.6+.  */
1882   return Qnil;
1883 #else
1884   Lisp_Object ret = Qnil;
1885   NSMenu *svcs;
1886   id delegate;
1888   check_ns ();
1889   svcs = [[NSMenu alloc] initWithTitle: @"Services"];
1890   [NSApp setServicesMenu: svcs];  /* this and next rebuild on <10.4 */
1891   [NSApp registerServicesMenuSendTypes: ns_send_types
1892                            returnTypes: ns_return_types];
1894 /* On Tiger, services menu updating was made lazier (waits for user to
1895    actually click on the menu), so we have to force things along: */
1896 #ifdef NS_IMPL_COCOA
1897   if (NSAppKitVersionNumber >= 744.0)
1898     {
1899       delegate = [svcs delegate];
1900       if (delegate != nil)
1901         {
1902           if ([delegate respondsToSelector: @selector (menuNeedsUpdate:)])
1903               [delegate menuNeedsUpdate: svcs];
1904           if ([delegate respondsToSelector:
1905                             @selector (menu:updateItem:atIndex:shouldCancel:)])
1906             {
1907               int i, len = [delegate numberOfItemsInMenu: svcs];
1908               for (i =0; i<len; i++)
1909                   [svcs addItemWithTitle: @"" action: NULL keyEquivalent: @""];
1910               for (i =0; i<len; i++)
1911                   if (![delegate menu: svcs
1912                            updateItem: (NSMenuItem *)[svcs itemAtIndex: i]
1913                               atIndex: i shouldCancel: NO])
1914                     break;
1915             }
1916         }
1917     }
1918 #endif
1920   [svcs setAutoenablesItems: NO];
1921 #ifdef NS_IMPL_COCOA
1922   [svcs update]; /* on OS X, converts from '/' structure */
1923 #endif
1925   ret = interpret_services_menu (svcs, Qnil, ret);
1926   return ret;
1927 #endif
1931 DEFUN ("ns-perform-service", Fns_perform_service, Sns_perform_service,
1932        2, 2, 0,
1933        doc: /* Perform Nextstep SERVICE on SEND.
1934 SEND should be either a string or nil.
1935 The return value is the result of the service, as string, or nil if
1936 there was no result.  */)
1937      (Lisp_Object service, Lisp_Object send)
1939   id pb;
1940   NSString *svcName;
1941   char *utfStr;
1942   int len;
1944   CHECK_STRING (service);
1945   check_ns ();
1947   utfStr = SDATA (service);
1948   svcName = [NSString stringWithUTF8String: utfStr];
1950   pb =[NSPasteboard pasteboardWithUniqueName];
1951   ns_string_to_pasteboard (pb, send);
1953   if (NSPerformService (svcName, pb) == NO)
1954     Fsignal (Qquit, Fcons (build_string ("service not available"), Qnil));
1956   if ([[pb types] count] == 0)
1957     return build_string ("");
1958   return ns_string_from_pasteboard (pb);
1962 DEFUN ("ns-convert-utf8-nfd-to-nfc", Fns_convert_utf8_nfd_to_nfc,
1963        Sns_convert_utf8_nfd_to_nfc, 1, 1, 0,
1964        doc: /* Return an NFC string that matches the UTF-8 NFD string STR.  */)
1965      (Lisp_Object str)
1967 /* TODO: If GNUstep ever implements precomposedStringWithCanonicalMapping,
1968          remove this. */
1969   NSString *utfStr;
1971   CHECK_STRING (str);
1972   utfStr = [NSString stringWithUTF8String: SDATA (str)];
1973   if (![utfStr respondsToSelector:
1974                  @selector (precomposedStringWithCanonicalMapping)])
1975     {
1976       message1
1977         ("Warning: ns-convert-utf8-nfd-to-nfc unsupported under GNUstep.\n");
1978       return Qnil;
1979     }
1980   else
1981     utfStr = [utfStr precomposedStringWithCanonicalMapping];
1982   return build_string ([utfStr UTF8String]);
1986 #ifdef NS_IMPL_COCOA
1988 /* Compile and execute the AppleScript SCRIPT and return the error
1989    status as function value.  A zero is returned if compilation and
1990    execution is successful, in which case *RESULT is set to a Lisp
1991    string or a number containing the resulting script value.  Otherwise,
1992    1 is returned. */
1993 static int
1994 ns_do_applescript (Lisp_Object script, Lisp_Object *result)
1996   NSAppleEventDescriptor *desc;
1997   NSDictionary* errorDict;
1998   NSAppleEventDescriptor* returnDescriptor = NULL;
2000   NSAppleScript* scriptObject =
2001     [[NSAppleScript alloc] initWithSource:
2002                              [NSString stringWithUTF8String: SDATA (script)]];
2004   returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
2005   [scriptObject release];
2007   *result = Qnil;
2009   if (returnDescriptor != NULL)
2010     {
2011       // successful execution
2012       if (kAENullEvent != [returnDescriptor descriptorType])
2013         {
2014           *result = Qt;
2015           // script returned an AppleScript result
2016           if ((typeUnicodeText == [returnDescriptor descriptorType]) ||
2017 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
2018               (typeUTF16ExternalRepresentation
2019                == [returnDescriptor descriptorType]) ||
2020 #endif
2021               (typeUTF8Text == [returnDescriptor descriptorType]) ||
2022               (typeCString == [returnDescriptor descriptorType]))
2023             {
2024               desc = [returnDescriptor coerceToDescriptorType: typeUTF8Text];
2025               if (desc)
2026                 *result = build_string([[desc stringValue] UTF8String]);
2027             }
2028           else
2029             {
2030               /* use typeUTF16ExternalRepresentation? */
2031               // coerce the result to the appropriate ObjC type
2032               desc = [returnDescriptor coerceToDescriptorType: typeUTF8Text];
2033               if (desc)
2034                 *result = make_number([desc int32Value]);
2035             }
2036         }
2037     }
2038   else
2039     {
2040       // no script result, return error
2041       return 1;
2042     }
2043   return 0;
2046 DEFUN ("ns-do-applescript", Fns_do_applescript, Sns_do_applescript, 1, 1, 0,
2047        doc: /* Execute AppleScript SCRIPT and return the result.
2048 If compilation and execution are successful, the resulting script value
2049 is returned as a string, a number or, in the case of other constructs, t.
2050 In case the execution fails, an error is signaled. */)
2051      (Lisp_Object script)
2053   Lisp_Object result;
2054   int status;
2056   CHECK_STRING (script);
2057   check_ns ();
2059   BLOCK_INPUT;
2060   status = ns_do_applescript (script, &result);
2061   UNBLOCK_INPUT;
2062   if (status == 0)
2063     return result;
2064   else if (!STRINGP (result))
2065     error ("AppleScript error %d", status);
2066   else
2067     error ("%s", SDATA (result));
2069 #endif
2073 /* ==========================================================================
2075     Miscellaneous functions not called through hooks
2077    ========================================================================== */
2080 /* called from image.c */
2081 FRAME_PTR
2082 check_x_frame (Lisp_Object frame)
2084   return check_ns_frame (frame);
2088 /* called from frame.c */
2089 struct ns_display_info *
2090 check_x_display_info (Lisp_Object frame)
2092   return check_ns_display_info (frame);
2096 void
2097 x_set_scroll_bar_default_width (struct frame *f)
2099   int wid = FRAME_COLUMN_WIDTH (f);
2100   FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = NS_SCROLL_BAR_WIDTH_DEFAULT;
2101   FRAME_CONFIG_SCROLL_BAR_COLS (f) = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) +
2102                                       wid - 1) / wid;
2106 /* terms impl this instead of x-get-resource directly */
2107 const char *
2108 x_get_string_resource (XrmDatabase rdb, char *name, char *class)
2110   /* remove appname prefix; TODO: allow for !="Emacs" */
2111   char *toCheck = class + (!strncmp (class, "Emacs.", 6) ? 6 : 0);
2112   const char *res;
2113   check_ns ();
2115   if (inhibit_x_resources)
2116     /* --quick was passed, so this is a no-op.  */
2117     return NULL;
2119   res = [[[NSUserDefaults standardUserDefaults] objectForKey:
2120             [NSString stringWithUTF8String: toCheck]] UTF8String];
2121   return !res ? NULL :
2122       (!strncasecmp (res, "YES", 3) ? "true" :
2123           (!strncasecmp (res, "NO", 2) ? "false" : res));
2127 Lisp_Object
2128 x_get_focus_frame (struct frame *frame)
2130   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
2131   Lisp_Object nsfocus;
2133   if (!dpyinfo->x_focus_frame)
2134     return Qnil;
2136   XSETFRAME (nsfocus, dpyinfo->x_focus_frame);
2137   return nsfocus;
2142 x_pixel_width (struct frame *f)
2144   return FRAME_PIXEL_WIDTH (f);
2149 x_pixel_height (struct frame *f)
2151   return FRAME_PIXEL_HEIGHT (f);
2156 x_char_width (struct frame *f)
2158   return FRAME_COLUMN_WIDTH (f);
2163 x_char_height (struct frame *f)
2165   return FRAME_LINE_HEIGHT (f);
2170 x_screen_planes (struct frame *f)
2172   return FRAME_NS_DISPLAY_INFO (f)->n_planes;
2176 void
2177 x_sync (struct frame *f)
2179   /* XXX Not implemented XXX */
2180   return;
2185 /* ==========================================================================
2187     Lisp definitions that, for whatever reason, we can't alias as 'ns-XXX'.
2189    ========================================================================== */
2192 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
2193        doc: /* Internal function called by `color-defined-p', which see.
2194 \(Note that the Nextstep version of this function ignores FRAME.)  */)
2195      (Lisp_Object color, Lisp_Object frame)
2197   NSColor * col;
2198   check_ns ();
2199   return ns_lisp_to_color (color, &col) ? Qnil : Qt;
2203 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
2204        doc: /* Internal function called by `color-values', which see.  */)
2205      (Lisp_Object color, Lisp_Object frame)
2207   NSColor * col;
2208   CGFloat red, green, blue, alpha;
2210   check_ns ();
2211   CHECK_STRING (color);
2213   if (ns_lisp_to_color (color, &col))
2214     return Qnil;
2216   [[col colorUsingColorSpaceName: NSCalibratedRGBColorSpace]
2217         getRed: &red green: &green blue: &blue alpha: &alpha];
2218   return list3 (make_number (lrint (red*65280)),
2219                 make_number (lrint (green*65280)),
2220                 make_number (lrint (blue*65280)));
2224 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
2225        doc: /* Internal function called by `display-color-p', which see.  */)
2226      (Lisp_Object display)
2228   NSWindowDepth depth;
2229   NSString *colorSpace;
2230   check_ns ();
2231   depth = [ns_get_screen (display) depth];
2232   colorSpace = NSColorSpaceFromDepth (depth);
2234   return    [colorSpace isEqualToString: NSDeviceWhiteColorSpace]
2235          || [colorSpace isEqualToString: NSCalibratedWhiteColorSpace]
2236       ? Qnil : Qt;
2240 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
2241        Sx_display_grayscale_p, 0, 1, 0,
2242        doc: /* Return t if the Nextstep display supports shades of gray.
2243 Note that color displays do support shades of gray.
2244 The optional argument DISPLAY specifies which display to ask about.
2245 DISPLAY should be either a frame, a display name (a string), or terminal ID.
2246 If omitted or nil, that stands for the selected frame's display. */)
2247      (Lisp_Object display)
2249   NSWindowDepth depth;
2250   check_ns ();
2251   depth = [ns_get_screen (display) depth];
2253   return NSBitsPerPixelFromDepth (depth) > 1 ? Qt : Qnil;
2257 DEFUN ("x-display-pixel-width", Fx_display_pixel_width, Sx_display_pixel_width,
2258        0, 1, 0,
2259        doc: /* Return the width in pixels of the Nextstep display DISPLAY.
2260 The optional argument DISPLAY specifies which display to ask about.
2261 DISPLAY should be either a frame, a display name (a string), or terminal ID.
2262 If omitted or nil, that stands for the selected frame's display.  */)
2263      (Lisp_Object display)
2265   check_ns ();
2266   return make_number ((int) [ns_get_screen (display) frame].size.width);
2270 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
2271        Sx_display_pixel_height, 0, 1, 0,
2272        doc: /* Return the height in pixels of the Nextstep display DISPLAY.
2273 The optional argument DISPLAY specifies which display to ask about.
2274 DISPLAY should be either a frame, a display name (a string), or terminal ID.
2275 If omitted or nil, that stands for the selected frame's display.  */)
2276      (Lisp_Object display)
2278   check_ns ();
2279   return make_number ((int) [ns_get_screen (display) frame].size.height);
2283 DEFUN ("display-usable-bounds", Fns_display_usable_bounds,
2284        Sns_display_usable_bounds, 0, 1, 0,
2285        doc: /* Return the bounds of the usable part of the screen.
2286 The return value is a list of integers (LEFT TOP WIDTH HEIGHT), which
2287 are the boundaries of the usable part of the screen, excluding areas
2288 reserved for the Mac menu, dock, and so forth.
2290 The screen queried corresponds to DISPLAY, which should be either a
2291 frame, a display name (a string), or terminal ID.  If omitted or nil,
2292 that stands for the selected frame's display. */)
2293      (Lisp_Object display)
2295   int top;
2296   NSScreen *screen;
2297   NSRect vScreen;
2299   check_ns ();
2300   screen = ns_get_screen (display);
2301   if (!screen)
2302     return Qnil;
2304   vScreen = [screen visibleFrame];
2306   /* NS coordinate system is upside-down.
2307      Transform to screen-specific coordinates. */
2308   return list4 (make_number ((int) vScreen.origin.x),
2309                 make_number ((int) [screen frame].size.height
2310                              - vScreen.size.height - vScreen.origin.y),
2311                 make_number ((int) vScreen.size.width),
2312                 make_number ((int) vScreen.size.height));
2316 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
2317        0, 1, 0,
2318        doc: /* Return the number of bitplanes 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
2326     (NSBitsPerPixelFromDepth ([ns_get_screen (display) depth]));
2330 DEFUN ("x-display-color-cells", Fx_display_color_cells,
2331        Sx_display_color_cells, 0, 1, 0,
2332        doc: /* Returns the number of color cells of the Nextstep display DISPLAY.
2333 The optional argument DISPLAY specifies which display to ask about.
2334 DISPLAY should be either a frame, a display name (a string), or terminal ID.
2335 If omitted or nil, that stands for the selected frame's display.  */)
2336      (Lisp_Object display)
2338   struct ns_display_info *dpyinfo;
2339   check_ns ();
2341   dpyinfo = check_ns_display_info (display);
2342   /* We force 24+ bit depths to 24-bit to prevent an overflow.  */
2343   return make_number (1 << min (dpyinfo->n_planes, 24));
2347 /* Unused dummy def needed for compatibility. */
2348 Lisp_Object tip_frame;
2350 /* TODO: move to xdisp or similar */
2351 static void
2352 compute_tip_xy (struct frame *f,
2353                 Lisp_Object parms,
2354                 Lisp_Object dx,
2355                 Lisp_Object dy,
2356                 int width,
2357                 int height,
2358                 int *root_x,
2359                 int *root_y)
2361   Lisp_Object left, top;
2362   EmacsView *view = FRAME_NS_VIEW (f);
2363   NSPoint pt;
2365   /* Start with user-specified or mouse position.  */
2366   left = Fcdr (Fassq (Qleft, parms));
2367   top = Fcdr (Fassq (Qtop, parms));
2369   if (!INTEGERP (left) || !INTEGERP (top))
2370     {
2371       pt = last_mouse_motion_position;
2372       /* Convert to screen coordinates */
2373       pt = [view convertPoint: pt toView: nil];
2374       pt = [[view window] convertBaseToScreen: pt];
2375     }
2376   else
2377     {
2378       /* Absolute coordinates.  */
2379       pt.x = XINT (left);
2380       pt.y = x_display_pixel_height (FRAME_NS_DISPLAY_INFO (f)) - XINT (top)
2381         - height;
2382     }
2384   /* Ensure in bounds.  (Note, screen origin = lower left.) */
2385   if (INTEGERP (left))
2386     *root_x = pt.x;
2387   else if (pt.x + XINT (dx) <= 0)
2388     *root_x = 0; /* Can happen for negative dx */
2389   else if (pt.x + XINT (dx) + width
2390            <= x_display_pixel_width (FRAME_NS_DISPLAY_INFO (f)))
2391     /* It fits to the right of the pointer.  */
2392     *root_x = pt.x + XINT (dx);
2393   else if (width + XINT (dx) <= pt.x)
2394     /* It fits to the left of the pointer.  */
2395     *root_x = pt.x - width - XINT (dx);
2396   else
2397     /* Put it left justified on the screen -- it ought to fit that way.  */
2398     *root_x = 0;
2400   if (INTEGERP (top))
2401     *root_y = pt.y;
2402   else if (pt.y - XINT (dy) - height >= 0)
2403     /* It fits below the pointer.  */
2404     *root_y = pt.y - height - XINT (dy);
2405   else if (pt.y + XINT (dy) + height
2406            <= x_display_pixel_height (FRAME_NS_DISPLAY_INFO (f)))
2407     /* It fits above the pointer */
2408       *root_y = pt.y + XINT (dy);
2409   else
2410     /* Put it on the top.  */
2411     *root_y = x_display_pixel_height (FRAME_NS_DISPLAY_INFO (f)) - height;
2415 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
2416        doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
2417 A tooltip window is a small window displaying a string.
2419 This is an internal function; Lisp code should call `tooltip-show'.
2421 FRAME nil or omitted means use the selected frame.
2423 PARMS is an optional list of frame parameters which can be used to
2424 change the tooltip's appearance.
2426 Automatically hide the tooltip after TIMEOUT seconds.  TIMEOUT nil
2427 means use the default timeout of 5 seconds.
2429 If the list of frame parameters PARMS contains a `left' parameter,
2430 the tooltip is displayed at that x-position.  Otherwise it is
2431 displayed at the mouse position, with offset DX added (default is 5 if
2432 DX isn't specified).  Likewise for the y-position; if a `top' frame
2433 parameter is specified, it determines the y-position of the tooltip
2434 window, otherwise it is displayed at the mouse position, with offset
2435 DY added (default is -10).
2437 A tooltip's maximum size is specified by `x-max-tooltip-size'.
2438 Text larger than the specified size is clipped.  */)
2439      (Lisp_Object string, Lisp_Object frame, Lisp_Object parms, Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
2441   int root_x, root_y;
2442   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2443   int count = SPECPDL_INDEX ();
2444   struct frame *f;
2445   char *str;
2446   NSSize size;
2448   specbind (Qinhibit_redisplay, Qt);
2450   GCPRO4 (string, parms, frame, timeout);
2452   CHECK_STRING (string);
2453   str = SDATA (string);
2454   f = check_x_frame (frame);
2455   if (NILP (timeout))
2456     timeout = make_number (5);
2457   else
2458     CHECK_NATNUM (timeout);
2460   if (NILP (dx))
2461     dx = make_number (5);
2462   else
2463     CHECK_NUMBER (dx);
2465   if (NILP (dy))
2466     dy = make_number (-10);
2467   else
2468     CHECK_NUMBER (dy);
2470   BLOCK_INPUT;
2471   if (ns_tooltip == nil)
2472     ns_tooltip = [[EmacsTooltip alloc] init];
2473   else
2474     Fx_hide_tip ();
2476   [ns_tooltip setText: str];
2477   size = [ns_tooltip frame].size;
2479   /* Move the tooltip window where the mouse pointer is.  Resize and
2480      show it.  */
2481   compute_tip_xy (f, parms, dx, dy, (int)size.width, (int)size.height,
2482                   &root_x, &root_y);
2484   [ns_tooltip showAtX: root_x Y: root_y for: XINT (timeout)];
2485   UNBLOCK_INPUT;
2487   UNGCPRO;
2488   return unbind_to (count, Qnil);
2492 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
2493        doc: /* Hide the current tooltip window, if there is any.
2494 Value is t if tooltip was open, nil otherwise.  */)
2495      (void)
2497   if (ns_tooltip == nil || ![ns_tooltip isActive])
2498     return Qnil;
2499   [ns_tooltip hide];
2500   return Qt;
2504 /* ==========================================================================
2506     Class implementations
2508    ========================================================================== */
2511 @implementation EmacsSavePanel
2512 #ifdef NS_IMPL_COCOA
2513 /* --------------------------------------------------------------------------
2514    These are overridden to intercept on OS X: ending panel restarts NSApp
2515    event loop if it is stopped.  Not sure if this is correct behavior,
2516    perhaps should check if running and if so send an appdefined.
2517    -------------------------------------------------------------------------- */
2518 - (void) ok: (id)sender
2520   [super ok: sender];
2521   panelOK = 1;
2522   [NSApp stop: self];
2524 - (void) cancel: (id)sender
2526   [super cancel: sender];
2527   [NSApp stop: self];
2529 #endif
2530 @end
2533 @implementation EmacsOpenPanel
2534 #ifdef NS_IMPL_COCOA
2535 /* --------------------------------------------------------------------------
2536    These are overridden to intercept on OS X: ending panel restarts NSApp
2537    event loop if it is stopped.  Not sure if this is correct behavior,
2538    perhaps should check if running and if so send an appdefined.
2539    -------------------------------------------------------------------------- */
2540 - (void) ok: (id)sender
2542   [super ok: sender];
2543   panelOK = 1;
2544   [NSApp stop: self];
2546 - (void) cancel: (id)sender
2548   [super cancel: sender];
2549   [NSApp stop: self];
2551 #endif
2552 @end
2555 @implementation EmacsFileDelegate
2556 /* --------------------------------------------------------------------------
2557    Delegate methods for Open/Save panels
2558    -------------------------------------------------------------------------- */
2559 - (BOOL)panel: (id)sender isValidFilename: (NSString *)filename
2561   return YES;
2563 - (BOOL)panel: (id)sender shouldShowFilename: (NSString *)filename
2565   return YES;
2567 - (NSString *)panel: (id)sender userEnteredFilename: (NSString *)filename
2568           confirmed: (BOOL)okFlag
2570   return filename;
2572 @end
2574 #endif
2577 /* ==========================================================================
2579     Lisp interface declaration
2581    ========================================================================== */
2584 void
2585 syms_of_nsfns (void)
2587   int i;
2589   Qfontsize = intern_c_string ("fontsize");
2590   staticpro (&Qfontsize);
2592   DEFVAR_LISP ("ns-icon-type-alist", Vns_icon_type_alist,
2593                doc: /* Alist of elements (REGEXP . IMAGE) for images of icons associated to frames.
2594 If the title of a frame matches REGEXP, then IMAGE.tiff is
2595 selected as the image of the icon representing the frame when it's
2596 miniaturized.  If an element is t, then Emacs tries to select an icon
2597 based on the filetype of the visited file.
2599 The images have to be installed in a folder called English.lproj in the
2600 Emacs folder.  You have to restart Emacs after installing new icons.
2602 Example: Install an icon Gnus.tiff and execute the following code
2604   (setq ns-icon-type-alist
2605         (append ns-icon-type-alist
2606                 '((\"^\\\\*\\\\(Group\\\\*$\\\\|Summary \\\\|Article\\\\*$\\\\)\"
2607                    . \"Gnus\"))))
2609 When you miniaturize a Group, Summary or Article frame, Gnus.tiff will
2610 be used as the image of the icon representing the frame.  */);
2611   Vns_icon_type_alist = Fcons (Qt, Qnil);
2613   DEFVAR_LISP ("ns-version-string", Vns_version_string,
2614                doc: /* Toolkit version for NS Windowing.  */);
2615   Vns_version_string = ns_appkit_version_str ();
2617   defsubr (&Sns_read_file_name);
2618   defsubr (&Sns_get_resource);
2619   defsubr (&Sns_set_resource);
2620   defsubr (&Sxw_display_color_p); /* this and next called directly by C code */
2621   defsubr (&Sx_display_grayscale_p);
2622   defsubr (&Sns_font_name);
2623   defsubr (&Sns_list_colors);
2624 #ifdef NS_IMPL_COCOA
2625   defsubr (&Sns_do_applescript);
2626 #endif
2627   defsubr (&Sxw_color_defined_p);
2628   defsubr (&Sxw_color_values);
2629   defsubr (&Sx_server_max_request_size);
2630   defsubr (&Sx_server_vendor);
2631   defsubr (&Sx_server_version);
2632   defsubr (&Sx_display_pixel_width);
2633   defsubr (&Sx_display_pixel_height);
2634   defsubr (&Sns_display_usable_bounds);
2635   defsubr (&Sx_display_mm_width);
2636   defsubr (&Sx_display_mm_height);
2637   defsubr (&Sx_display_screens);
2638   defsubr (&Sx_display_planes);
2639   defsubr (&Sx_display_color_cells);
2640   defsubr (&Sx_display_visual_class);
2641   defsubr (&Sx_display_backing_store);
2642   defsubr (&Sx_display_save_under);
2643   defsubr (&Sx_create_frame);
2644   defsubr (&Sx_open_connection);
2645   defsubr (&Sx_close_connection);
2646   defsubr (&Sx_display_list);
2648   defsubr (&Sns_hide_others);
2649   defsubr (&Sns_hide_emacs);
2650   defsubr (&Sns_emacs_info_panel);
2651   defsubr (&Sns_list_services);
2652   defsubr (&Sns_perform_service);
2653   defsubr (&Sns_convert_utf8_nfd_to_nfc);
2654   defsubr (&Sx_focus_frame);
2655   defsubr (&Sns_popup_font_panel);
2656   defsubr (&Sns_popup_color_panel);
2658   defsubr (&Sx_show_tip);
2659   defsubr (&Sx_hide_tip);
2661   /* used only in fontset.c */
2662   check_window_system_func = check_ns;