Try to fix crashes introduced by 2012-09-10T21:01:45Z!jan.h.d@swipnet.se.
[emacs.git] / src / nsfns.m
blob072005d2d3dba675890c43fdbcd1196cddf4392a
1 /* Functions for the NeXT/Open/GNUstep and MacOSX window system.
3 Copyright (C) 1989, 1992-1994, 2005-2006, 2008-2012
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 <math.h>
34 #include <c-strcase.h>
36 #include "lisp.h"
37 #include "blockinput.h"
38 #include "nsterm.h"
39 #include "window.h"
40 #include "character.h"
41 #include "buffer.h"
42 #include "keyboard.h"
43 #include "termhooks.h"
44 #include "fontset.h"
45 #include "font.h"
47 #if 0
48 int fns_trace_num = 1;
49 #define NSTRACE(x)        fprintf (stderr, "%s:%d: [%d] " #x "\n",        \
50                                   __FILE__, __LINE__, ++fns_trace_num)
51 #else
52 #define NSTRACE(x)
53 #endif
55 #ifdef HAVE_NS
57 extern NSArray *ns_send_types, *ns_return_types, *ns_drag_types;
59 extern Lisp_Object Qforeground_color;
60 extern Lisp_Object Qbackground_color;
61 extern Lisp_Object Qcursor_color;
62 extern Lisp_Object Qinternal_border_width;
63 extern Lisp_Object Qvisibility;
64 extern Lisp_Object Qcursor_type;
65 extern Lisp_Object Qicon_type;
66 extern Lisp_Object Qicon_name;
67 extern Lisp_Object Qicon_left;
68 extern Lisp_Object Qicon_top;
69 extern Lisp_Object Qleft;
70 extern Lisp_Object Qright;
71 extern Lisp_Object Qtop;
72 extern Lisp_Object Qdisplay;
73 extern Lisp_Object Qvertical_scroll_bars;
74 extern Lisp_Object Qauto_raise;
75 extern Lisp_Object Qauto_lower;
76 extern Lisp_Object Qbox;
77 extern Lisp_Object Qscroll_bar_width;
78 extern Lisp_Object Qx_resource_name;
79 extern Lisp_Object Qface_set_after_frame_default;
80 extern Lisp_Object Qunderline, Qundefined;
81 extern Lisp_Object Qheight, Qminibuffer, Qname, Qonly, Qwidth;
82 extern Lisp_Object Qunsplittable, Qmenu_bar_lines, Qbuffer_predicate, Qtitle;
85 Lisp_Object Qbuffered;
86 Lisp_Object Qfontsize;
88 /* hack for OS X file panels */
89 char panelOK = 0;
91 EmacsTooltip *ns_tooltip;
93 /* Need forward declaration here to preserve organizational integrity of file */
94 Lisp_Object Fx_open_connection (Lisp_Object, Lisp_Object, Lisp_Object);
96 extern BOOL ns_in_resize;
98 /* Static variables to handle applescript execution.  */
99 static Lisp_Object as_script, *as_result;
100 static int as_status;
102 #ifdef GLYPH_DEBUG
103 static ptrdiff_t image_cache_refcount;
104 #endif
106 /* ==========================================================================
108     Internal utility functions
110    ========================================================================== */
113 void
114 check_ns (void)
116  if (NSApp == nil)
117    error ("OpenStep is not in use or not initialized");
121 /* Nonzero if we can use mouse menus. */
123 have_menus_p (void)
125   return NSApp != nil;
129 /* Extract a frame as a FRAME_PTR, defaulting to the selected frame
130    and checking validity for NS.  */
131 static FRAME_PTR
132 check_ns_frame (Lisp_Object frame)
134   FRAME_PTR f;
136   if (NILP (frame))
137       f = SELECTED_FRAME ();
138   else
139     {
140       CHECK_LIVE_FRAME (frame);
141       f = XFRAME (frame);
142     }
143   if (! FRAME_NS_P (f))
144     error ("non-Nextstep frame used");
145   return f;
149 /* Let the user specify an Nextstep display with a frame.
150    nil stands for the selected frame--or, if that is not an Nextstep frame,
151    the first Nextstep display on the list.  */
152 static struct ns_display_info *
153 check_ns_display_info (Lisp_Object frame)
155   if (NILP (frame))
156     {
157       struct frame *f = SELECTED_FRAME ();
158       if (FRAME_NS_P (f) && FRAME_LIVE_P (f) )
159         return FRAME_NS_DISPLAY_INFO (f);
160       else if (x_display_list != 0)
161         return x_display_list;
162       else
163         error ("Nextstep windows are not in use or not initialized");
164     }
165   else if (INTEGERP (frame))
166     {
167       struct terminal *t = get_terminal (frame, 1);
169       if (t->type != output_ns)
170         error ("Terminal %"pI"d is not a Nextstep display", XINT (frame));
172       return t->display_info.ns;
173     }
174   else if (STRINGP (frame))
175     return ns_display_info_for_name (frame);
176   else
177     {
178       FRAME_PTR f;
180       CHECK_LIVE_FRAME (frame);
181       f = XFRAME (frame);
182       if (! FRAME_NS_P (f))
183         error ("non-Nextstep frame used");
184       return FRAME_NS_DISPLAY_INFO (f);
185     }
186   return NULL;  /* shut compiler up */
190 static id
191 ns_get_window (Lisp_Object maybeFrame)
193   id view =nil, window =nil;
195   if (!FRAMEP (maybeFrame) || !FRAME_NS_P (XFRAME (maybeFrame)))
196     maybeFrame = selected_frame;/*wrong_type_argument (Qframep, maybeFrame); */
198   if (!NILP (maybeFrame))
199     view = FRAME_NS_VIEW (XFRAME (maybeFrame));
200   if (view) window =[view window];
202   return window;
206 static NSScreen *
207 ns_get_screen (Lisp_Object screen)
209   struct frame *f;
210   struct terminal *terminal;
212   if (EQ (Qt, screen)) /* not documented */
213     return [NSScreen mainScreen];
215   terminal = get_terminal (screen, 1);
216   if (terminal->type != output_ns)
217     return NULL;
219   if (NILP (screen))
220     f = SELECTED_FRAME ();
221   else if (FRAMEP (screen))
222     f = XFRAME (screen);
223   else
224     {
225       struct ns_display_info *dpyinfo = terminal->display_info.ns;
226       f = dpyinfo->x_focus_frame
227         ? dpyinfo->x_focus_frame : dpyinfo->x_highlight_frame;
228     }
230   return ((f && FRAME_NS_P (f)) ? [[FRAME_NS_VIEW (f) window] screen]
231           : NULL);
235 /* Return the X display structure for the display named NAME.
236    Open a new connection if necessary.  */
237 struct ns_display_info *
238 ns_display_info_for_name (Lisp_Object name)
240   Lisp_Object names;
241   struct ns_display_info *dpyinfo;
243   CHECK_STRING (name);
245   for (dpyinfo = x_display_list, names = ns_display_name_list;
246        dpyinfo;
247        dpyinfo = dpyinfo->next, names = XCDR (names))
248     {
249       Lisp_Object tem;
250       tem = Fstring_equal (XCAR (XCAR (names)), name);
251       if (!NILP (tem))
252         return dpyinfo;
253     }
255   error ("Emacs for OpenStep does not yet support multi-display.");
257   Fx_open_connection (name, Qnil, Qnil);
258   dpyinfo = x_display_list;
260   if (dpyinfo == 0)
261     error ("OpenStep on %s not responding.\n", SDATA (name));
263   return dpyinfo;
267 static Lisp_Object
268 interpret_services_menu (NSMenu *menu, Lisp_Object prefix, Lisp_Object old)
269 /* --------------------------------------------------------------------------
270    Turn the input menu (an NSMenu) into a lisp list for tracking on lisp side
271    -------------------------------------------------------------------------- */
273   int i, count;
274   NSMenuItem *item;
275   const char *name;
276   Lisp_Object nameStr;
277   unsigned short key;
278   NSString *keys;
279   Lisp_Object res;
281   count = [menu numberOfItems];
282   for (i = 0; i<count; i++)
283     {
284       item = [menu itemAtIndex: i];
285       name = [[item title] UTF8String];
286       if (!name) continue;
288       nameStr = build_string (name);
290       if ([item hasSubmenu])
291         {
292           old = interpret_services_menu ([item submenu],
293                                         Fcons (nameStr, prefix), old);
294         }
295       else
296         {
297           keys = [item keyEquivalent];
298           if (keys && [keys length] )
299             {
300               key = [keys characterAtIndex: 0];
301               res = make_number (key|super_modifier);
302             }
303           else
304             {
305               res = Qundefined;
306             }
307           old = Fcons (Fcons (res,
308                             Freverse (Fcons (nameStr,
309                                            prefix))),
310                     old);
311         }
312     }
313   return old;
318 /* ==========================================================================
320     Frame parameter setters
322    ========================================================================== */
325 static void
326 x_set_foreground_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
328   NSColor *col;
329   CGFloat r, g, b, alpha;
331   if (ns_lisp_to_color (arg, &col))
332     {
333       store_frame_param (f, Qforeground_color, oldval);
334       error ("Unknown color");
335     }
337   [col retain];
338   [f->output_data.ns->foreground_color release];
339   f->output_data.ns->foreground_color = col;
341   [col getRed: &r green: &g blue: &b alpha: &alpha];
342   FRAME_FOREGROUND_PIXEL (f) =
343     ARGB_TO_ULONG ((int)(alpha*0xff), (int)(r*0xff), (int)(g*0xff), (int)(b*0xff));
345   if (FRAME_NS_VIEW (f))
346     {
347       update_face_from_frame_parameter (f, Qforeground_color, arg);
348       /*recompute_basic_faces (f); */
349       if (FRAME_VISIBLE_P (f))
350         redraw_frame (f);
351     }
355 static void
356 x_set_background_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
358   struct face *face;
359   NSColor *col;
360   NSView *view = FRAME_NS_VIEW (f);
361   CGFloat r, g, b, alpha;
363   if (ns_lisp_to_color (arg, &col))
364     {
365       store_frame_param (f, Qbackground_color, oldval);
366       error ("Unknown color");
367     }
369   /* clear the frame; in some instances the NS-internal GC appears not to
370      update, or it does update and cannot clear old text properly */
371   if (FRAME_VISIBLE_P (f))
372     ns_clear_frame (f);
374   [col retain];
375   [f->output_data.ns->background_color release];
376   f->output_data.ns->background_color = col;
378   [col getRed: &r green: &g blue: &b alpha: &alpha];
379   FRAME_BACKGROUND_PIXEL (f) =
380     ARGB_TO_ULONG ((int)(alpha*0xff), (int)(r*0xff), (int)(g*0xff), (int)(b*0xff));
382   if (view != nil)
383     {
384       [[view window] setBackgroundColor: col];
386       if (alpha != 1.0)
387           [[view window] setOpaque: NO];
388       else
389           [[view window] setOpaque: YES];
391       face = FRAME_DEFAULT_FACE (f);
392       if (face)
393         {
394           col = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f);
395           face->background = ns_index_color
396             ([col colorWithAlphaComponent: alpha], f);
398           update_face_from_frame_parameter (f, Qbackground_color, arg);
399         }
401       if (FRAME_VISIBLE_P (f))
402         redraw_frame (f);
403     }
407 static void
408 x_set_cursor_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
410   NSColor *col;
412   if (ns_lisp_to_color (arg, &col))
413     {
414       store_frame_param (f, Qcursor_color, oldval);
415       error ("Unknown color");
416     }
418   [FRAME_CURSOR_COLOR (f) release];
419   FRAME_CURSOR_COLOR (f) = [col retain];
421   if (FRAME_VISIBLE_P (f))
422     {
423       x_update_cursor (f, 0);
424       x_update_cursor (f, 1);
425     }
426   update_face_from_frame_parameter (f, Qcursor_color, arg);
430 static void
431 x_set_icon_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
433   NSView *view = FRAME_NS_VIEW (f);
434   NSTRACE (x_set_icon_name);
436   if (ns_in_resize)
437     return;
439   /* see if it's changed */
440   if (STRINGP (arg))
441     {
442       if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
443         return;
444     }
445   else if (!STRINGP (oldval) && EQ (oldval, Qnil) == EQ (arg, Qnil))
446     return;
448   fset_icon_name (f, arg);
450   if (NILP (arg))
451     {
452       if (!NILP (f->title))
453         arg = f->title;
454       else
455         /* explicit name and no icon-name -> explicit_name */
456         if (f->explicit_name)
457           arg = f->name;
458         else
459           {
460             /* no explicit name and no icon-name ->
461                name has to be rebuild from icon_title_format */
462             windows_or_buffers_changed++;
463             return;
464           }
465     }
467   /* Don't change the name if it's already NAME.  */
468   if ([[view window] miniwindowTitle] &&
469       ([[[view window] miniwindowTitle]
470              isEqualToString: [NSString stringWithUTF8String:
471                                            SSDATA (arg)]]))
472     return;
474   [[view window] setMiniwindowTitle:
475         [NSString stringWithUTF8String: SSDATA (arg)]];
478 static void
479 ns_set_name_internal (FRAME_PTR f, Lisp_Object name)
481   struct gcpro gcpro1;
482   Lisp_Object encoded_name, encoded_icon_name;
483   NSString *str;
484   NSView *view = FRAME_NS_VIEW (f);
486   GCPRO1 (name);
487   encoded_name = ENCODE_UTF_8 (name);
488   UNGCPRO;
490   str = [NSString stringWithUTF8String: SSDATA (encoded_name)];
492   /* Don't change the name if it's already NAME.  */
493   if (! [[[view window] title] isEqualToString: str])
494     [[view window] setTitle: str];
496   if (!STRINGP (f->icon_name))
497     encoded_icon_name = encoded_name;
498   else
499     encoded_icon_name = ENCODE_UTF_8 (f->icon_name);
501   str = [NSString stringWithUTF8String: SSDATA (encoded_icon_name)];
503   if ([[view window] miniwindowTitle] &&
504       ! [[[view window] miniwindowTitle] isEqualToString: str])
505     [[view window] setMiniwindowTitle: str];
509 static void
510 ns_set_name (struct frame *f, Lisp_Object name, int explicit)
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   fset_name (f, 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   fset_title (f, 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, SSDATA (encoded_name))))
641     {
642       [pool release];
643       UNBLOCK_INPUT;
644       return;
645     }
647   str = [NSString stringWithUTF8String: SSDATA (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: SSDATA (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       fset_name (f, 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   if (FRAME_MINIBUF_ONLY_P (f))
706     return;
708   if (TYPE_RANGED_INTEGERP (int, value))
709     nlines = XINT (value);
710   else
711     nlines = 0;
713   FRAME_MENU_BAR_LINES (f) = 0;
714   if (nlines)
715     {
716       FRAME_EXTERNAL_MENU_BAR (f) = 1;
717       /* does for all frames, whereas we just want for one frame
718          [NSMenu setMenuBarVisible: YES]; */
719     }
720   else
721     {
722       if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
723         free_frame_menubar (f);
724       /*      [NSMenu setMenuBarVisible: NO]; */
725       FRAME_EXTERNAL_MENU_BAR (f) = 0;
726     }
730 /* toolbar support */
731 void
732 x_set_tool_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
734   int nlines;
736   if (FRAME_MINIBUF_ONLY_P (f))
737     return;
739   if (RANGED_INTEGERP (0, value, INT_MAX))
740     nlines = XFASTINT (value);
741   else
742     nlines = 0;
744   if (nlines)
745     {
746       FRAME_EXTERNAL_TOOL_BAR (f) = 1;
747       update_frame_tool_bar (f);
748     }
749   else
750     {
751       if (FRAME_EXTERNAL_TOOL_BAR (f))
752         {
753           free_frame_tool_bar (f);
754           FRAME_EXTERNAL_TOOL_BAR (f) = 0;
755         }
756     }
758   x_set_window_size (f, 0, f->text_cols, f->text_lines);
762 void
763 ns_implicitly_set_icon_type (struct frame *f)
765   Lisp_Object tem;
766   EmacsView *view = FRAME_NS_VIEW (f);
767   id image = nil;
768   Lisp_Object chain, elt;
769   NSAutoreleasePool *pool;
770   BOOL setMini = YES;
772   NSTRACE (ns_implicitly_set_icon_type);
774   BLOCK_INPUT;
775   pool = [[NSAutoreleasePool alloc] init];
776   if (f->output_data.ns->miniimage
777       && [[NSString stringWithUTF8String: SSDATA (f->name)]
778                isEqualToString: [(NSImage *)f->output_data.ns->miniimage name]])
779     {
780       [pool release];
781       UNBLOCK_INPUT;
782       return;
783     }
785   tem = assq_no_quit (Qicon_type, f->param_alist);
786   if (CONSP (tem) && ! NILP (XCDR (tem)))
787     {
788       [pool release];
789       UNBLOCK_INPUT;
790       return;
791     }
793   for (chain = Vns_icon_type_alist;
794        image == nil && CONSP (chain);
795        chain = XCDR (chain))
796     {
797       elt = XCAR (chain);
798       /* special case: 't' means go by file type */
799       if (SYMBOLP (elt) && EQ (elt, Qt) && SSDATA (f->name)[0] == '/')
800         {
801           NSString *str
802              = [NSString stringWithUTF8String: SSDATA (f->name)];
803           if ([[NSFileManager defaultManager] fileExistsAtPath: str])
804             image = [[[NSWorkspace sharedWorkspace] iconForFile: str] retain];
805         }
806       else if (CONSP (elt) &&
807                STRINGP (XCAR (elt)) &&
808                STRINGP (XCDR (elt)) &&
809                fast_string_match (XCAR (elt), f->name) >= 0)
810         {
811           image = [EmacsImage allocInitFromFile: XCDR (elt)];
812           if (image == nil)
813             image = [[NSImage imageNamed:
814                                [NSString stringWithUTF8String:
815                                             SSDATA (XCDR (elt))]] retain];
816         }
817     }
819   if (image == nil)
820     {
821       image = [[[NSWorkspace sharedWorkspace] iconForFileType: @"text"] retain];
822       setMini = NO;
823     }
825   [f->output_data.ns->miniimage release];
826   f->output_data.ns->miniimage = image;
827   [view setMiniwindowImage: setMini];
828   [pool release];
829   UNBLOCK_INPUT;
833 static void
834 x_set_icon_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
836   EmacsView *view = FRAME_NS_VIEW (f);
837   id image = nil;
838   BOOL setMini = YES;
840   NSTRACE (x_set_icon_type);
842   if (!NILP (arg) && SYMBOLP (arg))
843     {
844       arg =build_string (SSDATA (SYMBOL_NAME (arg)));
845       store_frame_param (f, Qicon_type, arg);
846     }
848   /* do it the implicit way */
849   if (NILP (arg))
850     {
851       ns_implicitly_set_icon_type (f);
852       return;
853     }
855   CHECK_STRING (arg);
857   image = [EmacsImage allocInitFromFile: arg];
858   if (image == nil)
859     image =[NSImage imageNamed: [NSString stringWithUTF8String:
860                                             SSDATA (arg)]];
862   if (image == nil)
863     {
864       image = [NSImage imageNamed: @"text"];
865       setMini = NO;
866     }
868   f->output_data.ns->miniimage = image;
869   [view setMiniwindowImage: setMini];
873 /* Xism; we stub out (we do implement this in ns-win.el) */
875 XParseGeometry (char *string, int *x, int *y,
876                 unsigned int *width, unsigned int *height)
878   message1 ("Warning: XParseGeometry not supported under NS.\n");
879   return 0;
883 /* TODO: move to nsterm? */
885 ns_lisp_to_cursor_type (Lisp_Object arg)
887   char *str;
888   if (XTYPE (arg) == Lisp_String)
889     str = SSDATA (arg);
890   else if (XTYPE (arg) == Lisp_Symbol)
891     str = SSDATA (SYMBOL_NAME (arg));
892   else return -1;
893   if (!strcmp (str, "box"))     return FILLED_BOX_CURSOR;
894   if (!strcmp (str, "hollow"))  return HOLLOW_BOX_CURSOR;
895   if (!strcmp (str, "hbar"))    return HBAR_CURSOR;
896   if (!strcmp (str, "bar"))     return BAR_CURSOR;
897   if (!strcmp (str, "no"))      return NO_CURSOR;
898   return -1;
902 Lisp_Object
903 ns_cursor_type_to_lisp (int arg)
905   switch (arg)
906     {
907     case FILLED_BOX_CURSOR: return Qbox;
908     case HOLLOW_BOX_CURSOR: return intern ("hollow");
909     case HBAR_CURSOR:       return intern ("hbar");
910     case BAR_CURSOR:        return intern ("bar");
911     case NO_CURSOR:
912     default:                return intern ("no");
913     }
916 /* This is the same as the xfns.c definition.  */
917 void
918 x_set_cursor_type (FRAME_PTR f, Lisp_Object arg, Lisp_Object oldval)
920   set_frame_cursor_types (f, arg);
922   /* Make sure the cursor gets redrawn.  */
923   cursor_type_changed = 1;
927 /* called to set mouse pointer color, but all other terms use it to
928    initialize pointer types (and don't set the color ;) */
929 static void
930 x_set_mouse_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
932   /* don't think we can do this on Nextstep */
936 #define Str(x) #x
937 #define Xstr(x) Str(x)
939 static Lisp_Object
940 ns_appkit_version_str (void)
942   char tmp[80];
944 #ifdef NS_IMPL_GNUSTEP
945   sprintf(tmp, "gnustep-gui-%s", Xstr(GNUSTEP_GUI_VERSION));
946 #elif defined(NS_IMPL_COCOA)
947   sprintf(tmp, "apple-appkit-%.2f", NSAppKitVersionNumber);
948 #else
949   tmp = "ns-unknown";
950 #endif
951   return build_string (tmp);
955 /* This is for use by x-server-version and collapses all version info we
956    have into a single int.  For a better picture of the implementation
957    running, use ns_appkit_version_str.*/
958 static int
959 ns_appkit_version_int (void)
961 #ifdef NS_IMPL_GNUSTEP
962   return GNUSTEP_GUI_MAJOR_VERSION * 100 + GNUSTEP_GUI_MINOR_VERSION;
963 #elif defined(NS_IMPL_COCOA)
964   return (int)NSAppKitVersionNumber;
965 #endif
966   return 0;
970 static void
971 x_icon (struct frame *f, Lisp_Object parms)
972 /* --------------------------------------------------------------------------
973    Strangely-named function to set icon position parameters in frame.
974    This is irrelevant under OS X, but might be needed under GNUstep,
975    depending on the window manager used.  Note, this is not a standard
976    frame parameter-setter; it is called directly from x-create-frame.
977    -------------------------------------------------------------------------- */
979   Lisp_Object icon_x, icon_y;
980   struct ns_display_info *dpyinfo = check_ns_display_info (Qnil);
982   f->output_data.ns->icon_top = Qnil;
983   f->output_data.ns->icon_left = Qnil;
985   /* Set the position of the icon.  */
986   icon_x = x_get_arg (dpyinfo, parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
987   icon_y = x_get_arg (dpyinfo, parms, Qicon_top, 0, 0,  RES_TYPE_NUMBER);
988   if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
989     {
990       CHECK_NUMBER (icon_x);
991       CHECK_NUMBER (icon_y);
992       f->output_data.ns->icon_top = icon_y;
993       f->output_data.ns->icon_left = icon_x;
994     }
995   else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
996     error ("Both left and top icon corners of icon must be specified");
1000 /* Note: see frame.c for template, also where generic functions are impl */
1001 frame_parm_handler ns_frame_parm_handlers[] =
1003   x_set_autoraise, /* generic OK */
1004   x_set_autolower, /* generic OK */
1005   x_set_background_color,
1006   0, /* x_set_border_color,  may be impossible under Nextstep */
1007   0, /* x_set_border_width,  may be impossible under Nextstep */
1008   x_set_cursor_color,
1009   x_set_cursor_type,
1010   x_set_font, /* generic OK */
1011   x_set_foreground_color,
1012   x_set_icon_name,
1013   x_set_icon_type,
1014   x_set_internal_border_width, /* generic OK */
1015   x_set_menu_bar_lines,
1016   x_set_mouse_color,
1017   x_explicitly_set_name,
1018   x_set_scroll_bar_width, /* generic OK */
1019   x_set_title,
1020   x_set_unsplittable, /* generic OK */
1021   x_set_vertical_scroll_bars, /* generic OK */
1022   x_set_visibility, /* generic OK */
1023   x_set_tool_bar_lines,
1024   0, /* x_set_scroll_bar_foreground, will ignore (not possible on NS) */
1025   0, /* x_set_scroll_bar_background,  will ignore (not possible on NS) */
1026   x_set_screen_gamma, /* generic OK */
1027   x_set_line_spacing, /* generic OK, sets f->extra_line_spacing to int */
1028   x_set_fringe_width, /* generic OK */
1029   x_set_fringe_width, /* generic OK */
1030   0, /* x_set_wait_for_wm, will ignore */
1031   0,  /* x_set_fullscreen will ignore */
1032   x_set_font_backend, /* generic OK */
1033   x_set_alpha,
1034   0, /* x_set_sticky */
1035   0, /* x_set_tool_bar_position */
1039 /* Handler for signals raised during x_create_frame.
1040    FRAME is the frame which is partially constructed.  */
1042 static Lisp_Object
1043 unwind_create_frame (Lisp_Object frame)
1045   struct frame *f = XFRAME (frame);
1047   /* If frame is already dead, nothing to do.  This can happen if the
1048      display is disconnected after the frame has become official, but
1049      before x_create_frame removes the unwind protect.  */
1050   if (!FRAME_LIVE_P (f))
1051     return Qnil;
1053   /* If frame is ``official'', nothing to do.  */
1054   if (NILP (Fmemq (frame, Vframe_list)))
1055     {
1056 #if defined GLYPH_DEBUG && defined ENABLE_CHECKING
1057       struct ns_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
1058 #endif
1060       x_free_frame_resources (f);
1061       free_glyphs (f);
1063 #ifdef GLYPH_DEBUG
1064       /* Check that reference counts are indeed correct.  */
1065       eassert (dpyinfo->terminal->image_cache->refcount == image_cache_refcount);
1066 #endif
1067       return Qt;
1068     }
1070   return Qnil;
1074  * Read geometry related parameters from preferences if not in PARMS.
1075  * Returns the union of parms and any preferences read.
1076  */
1078 static Lisp_Object
1079 get_geometry_from_preferences (struct ns_display_info *dpyinfo,
1080                                Lisp_Object parms)
1082   struct {
1083     const char *val;
1084     const char *cls;
1085     Lisp_Object tem;
1086   } r[] = {
1087     { "width",  "Width", Qwidth },
1088     { "height", "Height", Qheight },
1089     { "left", "Left", Qleft },
1090     { "top", "Top", Qtop },
1091   };
1093   int i;
1094   for (i = 0; i < sizeof (r)/sizeof (r[0]); ++i)
1095     {
1096       if (NILP (Fassq (r[i].tem, parms)))
1097         {
1098           Lisp_Object value
1099             = x_get_arg (dpyinfo, parms, r[i].tem, r[i].val, r[i].cls,
1100                          RES_TYPE_NUMBER);
1101           if (! EQ (value, Qunbound))
1102             parms = Fcons (Fcons (r[i].tem, value), parms);
1103         }
1104     }
1106   return parms;
1109 /* ==========================================================================
1111     Lisp definitions
1113    ========================================================================== */
1115 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
1116        1, 1, 0,
1117        doc: /* Make a new Nextstep window, called a "frame" in Emacs terms.
1118 Return an Emacs frame object.
1119 PARMS is an alist of frame parameters.
1120 If the parameters specify that the frame should not have a minibuffer,
1121 and do not specify a specific minibuffer window to use,
1122 then `default-minibuffer-frame' must be a frame whose minibuffer can
1123 be shared by the new frame.
1125 This function is an internal primitive--use `make-frame' instead.  */)
1126      (Lisp_Object parms)
1128   struct frame *f;
1129   Lisp_Object frame, tem;
1130   Lisp_Object name;
1131   int minibuffer_only = 0;
1132   int window_prompting = 0;
1133   int width, height;
1134   ptrdiff_t count = specpdl_ptr - specpdl;
1135   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1136   Lisp_Object display;
1137   struct ns_display_info *dpyinfo = NULL;
1138   Lisp_Object parent;
1139   struct kboard *kb;
1140   Lisp_Object tfont, tfontsize;
1141   static int desc_ctr = 1;
1143   check_ns ();
1145   /* x_get_arg modifies parms.  */
1146   parms = Fcopy_alist (parms);
1148   /* Use this general default value to start with
1149      until we know if this frame has a specified name.  */
1150   Vx_resource_name = Vinvocation_name;
1152   display = x_get_arg (dpyinfo, parms, Qterminal, 0, 0, RES_TYPE_STRING);
1153   if (EQ (display, Qunbound))
1154     display = Qnil;
1155   dpyinfo = check_ns_display_info (display);
1156   kb = dpyinfo->terminal->kboard;
1158   if (!dpyinfo->terminal->name)
1159     error ("Terminal is not live, can't create new frames on it");
1161   name = x_get_arg (dpyinfo, parms, Qname, 0, 0, RES_TYPE_STRING);
1162   if (!STRINGP (name)
1163       && ! EQ (name, Qunbound)
1164       && ! NILP (name))
1165     error ("Invalid frame name--not a string or nil");
1167   if (STRINGP (name))
1168     Vx_resource_name = name;
1170   parent = x_get_arg (dpyinfo, parms, Qparent_id, 0, 0, RES_TYPE_NUMBER);
1171   if (EQ (parent, Qunbound))
1172     parent = Qnil;
1173   if (! NILP (parent))
1174     CHECK_NUMBER (parent);
1176   /* make_frame_without_minibuffer can run Lisp code and garbage collect.  */
1177   /* No need to protect DISPLAY because that's not used after passing
1178      it to make_frame_without_minibuffer.  */
1179   frame = Qnil;
1180   GCPRO4 (parms, parent, name, frame);
1181   tem = x_get_arg (dpyinfo, parms, Qminibuffer, "minibuffer", "Minibuffer",
1182                   RES_TYPE_SYMBOL);
1183   if (EQ (tem, Qnone) || NILP (tem))
1184       f = make_frame_without_minibuffer (Qnil, kb, display);
1185   else if (EQ (tem, Qonly))
1186     {
1187       f = make_minibuffer_frame ();
1188       minibuffer_only = 1;
1189     }
1190   else if (WINDOWP (tem))
1191       f = make_frame_without_minibuffer (tem, kb, display);
1192   else
1193       f = make_frame (1);
1195   XSETFRAME (frame, f);
1196   FRAME_CAN_HAVE_SCROLL_BARS (f) = 1;
1198   f->terminal = dpyinfo->terminal;
1200   f->output_method = output_ns;
1201   f->output_data.ns = xzalloc (sizeof *f->output_data.ns);
1203   FRAME_FONTSET (f) = -1;
1205   fset_icon_name (f, x_get_arg (dpyinfo, parms, Qicon_name,
1206                                 "iconName", "Title",
1207                                 RES_TYPE_STRING));
1208   if (! STRINGP (f->icon_name))
1209     fset_icon_name (f, Qnil);
1211   FRAME_NS_DISPLAY_INFO (f) = dpyinfo;
1213   /* With FRAME_NS_DISPLAY_INFO set up, this unwind-protect is safe.  */
1214   record_unwind_protect (unwind_create_frame, frame);
1216   f->output_data.ns->window_desc = desc_ctr++;
1217   if (TYPE_RANGED_INTEGERP (Window, parent))
1218     {
1219       f->output_data.ns->parent_desc = XFASTINT (parent);
1220       f->output_data.ns->explicit_parent = 1;
1221     }
1222   else
1223     {
1224       f->output_data.ns->parent_desc = FRAME_NS_DISPLAY_INFO (f)->root_window;
1225       f->output_data.ns->explicit_parent = 0;
1226     }
1228   /* Set the name; the functions to which we pass f expect the name to
1229      be set.  */
1230   if (EQ (name, Qunbound) || NILP (name) || ! STRINGP (name))
1231     {
1232       fset_name (f, build_string ([ns_app_name UTF8String]));
1233       f->explicit_name = 0;
1234     }
1235   else
1236     {
1237       fset_name (f, name);
1238       f->explicit_name = 1;
1239       specbind (Qx_resource_name, name);
1240     }
1242   f->resx = dpyinfo->resx;
1243   f->resy = dpyinfo->resy;
1245   BLOCK_INPUT;
1246   register_font_driver (&nsfont_driver, f);
1247   x_default_parameter (f, parms, Qfont_backend, Qnil,
1248                         "fontBackend", "FontBackend", RES_TYPE_STRING);
1250   {
1251     /* use for default font name */
1252     id font = [NSFont userFixedPitchFontOfSize: -1.0]; /* default */
1253     tfontsize = x_default_parameter (f, parms, Qfontsize,
1254                                     make_number (0 /*(int)[font pointSize]*/),
1255                                     "fontSize", "FontSize", RES_TYPE_NUMBER);
1256     tfont = x_default_parameter (f, parms, Qfont,
1257                                  build_string ([[font fontName] UTF8String]),
1258                                  "font", "Font", RES_TYPE_STRING);
1259   }
1260   UNBLOCK_INPUT;
1262   x_default_parameter (f, parms, Qborder_width, make_number (0),
1263                        "borderwidth", "BorderWidth", RES_TYPE_NUMBER);
1264   x_default_parameter (f, parms, Qinternal_border_width, make_number (2),
1265                       "internalBorderWidth", "InternalBorderWidth",
1266                       RES_TYPE_NUMBER);
1268   /* default scrollbars on right on Mac */
1269   {
1270       Lisp_Object spos
1271 #ifdef NS_IMPL_GNUSTEP
1272           = Qt;
1273 #else
1274           = Qright;
1275 #endif
1276       x_default_parameter (f, parms, Qvertical_scroll_bars, spos,
1277                            "verticalScrollBars", "VerticalScrollBars",
1278                            RES_TYPE_SYMBOL);
1279   }
1280   x_default_parameter (f, parms, Qforeground_color, build_string ("Black"),
1281                       "foreground", "Foreground", RES_TYPE_STRING);
1282   x_default_parameter (f, parms, Qbackground_color, build_string ("White"),
1283                       "background", "Background", RES_TYPE_STRING);
1284   /* FIXME: not supported yet in Nextstep */
1285   x_default_parameter (f, parms, Qline_spacing, Qnil,
1286                        "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
1287   x_default_parameter (f, parms, Qleft_fringe, Qnil,
1288                        "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
1289   x_default_parameter (f, parms, Qright_fringe, Qnil,
1290                        "rightFringe", "RightFringe", RES_TYPE_NUMBER);
1292 #ifdef GLYPH_DEBUG
1293   image_cache_refcount =
1294     FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
1295 #endif
1297   init_frame_faces (f);
1299   /* The resources controlling the menu-bar and tool-bar are
1300      processed specially at startup, and reflected in the mode
1301      variables; ignore them here.  */
1302   x_default_parameter (f, parms, Qmenu_bar_lines,
1303                        NILP (Vmenu_bar_mode)
1304                        ? make_number (0) : make_number (1),
1305                        NULL, NULL, RES_TYPE_NUMBER);
1306   x_default_parameter (f, parms, Qtool_bar_lines,
1307                        NILP (Vtool_bar_mode)
1308                        ? make_number (0) : make_number (1),
1309                        NULL, NULL, RES_TYPE_NUMBER);
1311   x_default_parameter (f, parms, Qbuffer_predicate, Qnil, "bufferPredicate",
1312                        "BufferPredicate", RES_TYPE_SYMBOL);
1313   x_default_parameter (f, parms, Qtitle, Qnil, "title", "Title",
1314                        RES_TYPE_STRING);
1316   parms = get_geometry_from_preferences (dpyinfo, parms);
1317   window_prompting = x_figure_window_size (f, parms, 1);
1319   tem = x_get_arg (dpyinfo, parms, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
1320   f->no_split = minibuffer_only || (!EQ (tem, Qunbound) && !EQ (tem, Qnil));
1322   /* NOTE: on other terms, this is done in set_mouse_color, however this
1323      was not getting called under Nextstep */
1324   f->output_data.ns->text_cursor = [NSCursor IBeamCursor];
1325   f->output_data.ns->nontext_cursor = [NSCursor arrowCursor];
1326   f->output_data.ns->modeline_cursor = [NSCursor pointingHandCursor];
1327   f->output_data.ns->hand_cursor = [NSCursor pointingHandCursor];
1328   f->output_data.ns->hourglass_cursor = [NSCursor disappearingItemCursor];
1329   f->output_data.ns->horizontal_drag_cursor = [NSCursor resizeLeftRightCursor];
1330   FRAME_NS_DISPLAY_INFO (f)->vertical_scroll_bar_cursor
1331      = [NSCursor arrowCursor];
1332   f->output_data.ns->current_pointer = f->output_data.ns->text_cursor;
1334   [[EmacsView alloc] initFrameFromEmacs: f];
1336   x_icon (f, parms);
1338   /* ns_display_info does not have a reference_count.  */
1339   f->terminal->reference_count++;
1341   /* It is now ok to make the frame official even if we get an error below.
1342      The frame needs to be on Vframe_list or making it visible won't work. */
1343   Vframe_list = Fcons (frame, Vframe_list);
1345   x_default_parameter (f, parms, Qicon_type, Qnil,
1346                        "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
1348   x_default_parameter (f, parms, Qauto_raise, Qnil,
1349                        "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
1350   x_default_parameter (f, parms, Qauto_lower, Qnil,
1351                        "autoLower", "AutoLower", RES_TYPE_BOOLEAN);
1352   x_default_parameter (f, parms, Qcursor_type, Qbox,
1353                        "cursorType", "CursorType", RES_TYPE_SYMBOL);
1354   x_default_parameter (f, parms, Qscroll_bar_width, Qnil,
1355                        "scrollBarWidth", "ScrollBarWidth",
1356                        RES_TYPE_NUMBER);
1357   x_default_parameter (f, parms, Qalpha, Qnil,
1358                        "alpha", "Alpha", RES_TYPE_NUMBER);
1360   width = FRAME_COLS (f);
1361   height = FRAME_LINES (f);
1363   SET_FRAME_COLS (f, 0);
1364   FRAME_LINES (f) = 0;
1365   change_frame_size (f, height, width, 1, 0, 0);
1367   if (! f->output_data.ns->explicit_parent)
1368     {
1369       Lisp_Object visibility;
1371       visibility = x_get_arg (dpyinfo, parms, Qvisibility, 0, 0,
1372                               RES_TYPE_SYMBOL);
1373       if (EQ (visibility, Qunbound))
1374         visibility = Qt;
1376       if (EQ (visibility, Qicon))
1377         x_iconify_frame (f);
1378       else if (! NILP (visibility))
1379         {
1380           x_make_frame_visible (f);
1381           [[FRAME_NS_VIEW (f) window] makeKeyWindow];
1382         }
1383       else
1384         {
1385           /* Must have been Qnil.  */
1386         }
1387     }
1389   if (FRAME_HAS_MINIBUF_P (f)
1390       && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
1391           || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
1392     kset_default_minibuffer_frame (kb, frame);
1394   /* All remaining specified parameters, which have not been "used"
1395      by x_get_arg and friends, now go in the misc. alist of the frame.  */
1396   for (tem = parms; CONSP (tem); tem = XCDR (tem))
1397     if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
1398       fset_param_alist (f, Fcons (XCAR (tem), f->param_alist));
1400   UNGCPRO;
1402   /* Make sure windows on this frame appear in calls to next-window
1403      and similar functions.  */
1404   Vwindow_list = Qnil;
1406   return unbind_to (count, frame);
1410 DEFUN ("x-focus-frame", Fx_focus_frame, Sx_focus_frame, 1, 1, 0,
1411        doc: /* Set the input focus to FRAME.
1412 FRAME nil means use the selected frame.  */)
1413      (Lisp_Object frame)
1415   struct frame *f = check_ns_frame (frame);
1416   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (f);
1418   if (dpyinfo->x_focus_frame != f)
1419     {
1420       EmacsView *view = FRAME_NS_VIEW (f);
1421       BLOCK_INPUT;
1422       [NSApp activateIgnoringOtherApps: YES];
1423       [[view window] makeKeyAndOrderFront: view];
1424       UNBLOCK_INPUT;
1425     }
1427   return Qnil;
1431 DEFUN ("ns-popup-font-panel", Fns_popup_font_panel, Sns_popup_font_panel,
1432        0, 1, "",
1433        doc: /* Pop up the font panel. */)
1434      (Lisp_Object frame)
1436   id fm;
1437   struct frame *f;
1439   check_ns ();
1440   fm = [NSFontManager sharedFontManager];
1441   if (NILP (frame))
1442     f = SELECTED_FRAME ();
1443   else
1444     {
1445       CHECK_FRAME (frame);
1446       f = XFRAME (frame);
1447     }
1449   [fm setSelectedFont: ((struct nsfont_info *)f->output_data.ns->font)->nsfont
1450            isMultiple: NO];
1451   [fm orderFrontFontPanel: NSApp];
1452   return Qnil;
1456 DEFUN ("ns-popup-color-panel", Fns_popup_color_panel, Sns_popup_color_panel,
1457        0, 1, "",
1458        doc: /* Pop up the color panel.  */)
1459      (Lisp_Object frame)
1461   struct frame *f;
1463   check_ns ();
1464   if (NILP (frame))
1465     f = SELECTED_FRAME ();
1466   else
1467     {
1468       CHECK_FRAME (frame);
1469       f = XFRAME (frame);
1470     }
1472   [NSApp orderFrontColorPanel: NSApp];
1473   return Qnil;
1477 DEFUN ("ns-read-file-name", Fns_read_file_name, Sns_read_file_name, 1, 4, 0,
1478        doc: /* Use a graphical panel to read a file name, using prompt PROMPT.
1479 Optional arg DIR, if non-nil, supplies a default directory.
1480 Optional arg MUSTMATCH, if non-nil, means the returned file or
1481 directory must exist.
1482 Optional arg INIT, if non-nil, provides a default file name to use.  */)
1483      (Lisp_Object prompt, Lisp_Object dir, Lisp_Object mustmatch, Lisp_Object init)
1485   static id fileDelegate = nil;
1486   int ret;
1487   id panel;
1488   Lisp_Object fname;
1490   NSString *promptS = NILP (prompt) || !STRINGP (prompt) ? nil :
1491     [NSString stringWithUTF8String: SSDATA (prompt)];
1492   NSString *dirS = NILP (dir) || !STRINGP (dir) ?
1493     [NSString stringWithUTF8String: SSDATA (BVAR (current_buffer, directory))] :
1494     [NSString stringWithUTF8String: SSDATA (dir)];
1495   NSString *initS = NILP (init) || !STRINGP (init) ? nil :
1496     [NSString stringWithUTF8String: SSDATA (init)];
1498   check_ns ();
1500   if (fileDelegate == nil)
1501     fileDelegate = [EmacsFileDelegate new];
1503   [NSCursor setHiddenUntilMouseMoves: NO];
1505   if ([dirS characterAtIndex: 0] == '~')
1506     dirS = [dirS stringByExpandingTildeInPath];
1508   panel = NILP (mustmatch) ?
1509     (id)[EmacsSavePanel savePanel] : (id)[EmacsOpenPanel openPanel];
1511   [panel setTitle: promptS];
1513   /* Puma (10.1) does not have */
1514   if ([panel respondsToSelector: @selector (setAllowsOtherFileTypes:)])
1515     [panel setAllowsOtherFileTypes: YES];
1517   [panel setTreatsFilePackagesAsDirectories: YES];
1518   [panel setDelegate: fileDelegate];
1520   panelOK = 0;
1521   BLOCK_INPUT;
1522   if (NILP (mustmatch))
1523     {
1524       ret = [panel runModalForDirectory: dirS file: initS];
1525     }
1526   else
1527     {
1528       [panel setCanChooseDirectories: YES];
1529       ret = [panel runModalForDirectory: dirS file: initS types: nil];
1530     }
1532   ret = (ret == NSOKButton) || panelOK;
1534   if (ret)
1535     fname = build_string ([[panel filename] UTF8String]);
1537   [[FRAME_NS_VIEW (SELECTED_FRAME ()) window] makeKeyWindow];
1538   UNBLOCK_INPUT;
1540   return ret ? fname : Qnil;
1543 const char *
1544 ns_get_defaults_value (const char *key)
1546   NSObject *obj = [[NSUserDefaults standardUserDefaults]
1547                     objectForKey: [NSString stringWithUTF8String: key]];
1549   if (!obj) return NULL;
1551   return [[NSString stringWithFormat: @"%@", obj] UTF8String];
1555 DEFUN ("ns-get-resource", Fns_get_resource, Sns_get_resource, 2, 2, 0,
1556        doc: /* Return the value of the property NAME of OWNER from the defaults database.
1557 If OWNER is nil, Emacs is assumed.  */)
1558      (Lisp_Object owner, Lisp_Object name)
1560   const char *value;
1562   check_ns ();
1563   if (NILP (owner))
1564     owner = build_string([ns_app_name UTF8String]);
1565   CHECK_STRING (name);
1566 /*fprintf (stderr, "ns-get-resource checking resource '%s'\n", SSDATA (name)); */
1568   value = ns_get_defaults_value (SSDATA (name));
1570   if (value)
1571     return build_string (value);
1572   return Qnil;
1576 DEFUN ("ns-set-resource", Fns_set_resource, Sns_set_resource, 3, 3, 0,
1577        doc: /* Set property NAME of OWNER to VALUE, from the defaults database.
1578 If OWNER is nil, Emacs is assumed.
1579 If VALUE is nil, the default is removed.  */)
1580      (Lisp_Object owner, Lisp_Object name, Lisp_Object value)
1582   check_ns ();
1583   if (NILP (owner))
1584     owner = build_string ([ns_app_name UTF8String]);
1585   CHECK_STRING (name);
1586   if (NILP (value))
1587     {
1588       [[NSUserDefaults standardUserDefaults] removeObjectForKey:
1589                          [NSString stringWithUTF8String: SSDATA (name)]];
1590     }
1591   else
1592     {
1593       CHECK_STRING (value);
1594       [[NSUserDefaults standardUserDefaults] setObject:
1595                 [NSString stringWithUTF8String: SSDATA (value)]
1596                                         forKey: [NSString stringWithUTF8String:
1597                                                          SSDATA (name)]];
1598     }
1600   return Qnil;
1604 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
1605        Sx_server_max_request_size,
1606        0, 1, 0,
1607        doc: /* This function is a no-op.  It is only present for completeness.  */)
1608      (Lisp_Object display)
1610   check_ns ();
1611   /* This function has no real equivalent under NeXTstep.  Return nil to
1612      indicate this. */
1613   return Qnil;
1617 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
1618        doc: /* Return the vendor ID string of Nextstep display server DISPLAY.
1619 DISPLAY should be either a frame or a display name (a string).
1620 If omitted or nil, the selected frame's display is used.  */)
1621      (Lisp_Object display)
1623 #ifdef NS_IMPL_GNUSTEP
1624   return build_string ("GNU");
1625 #else
1626   return build_string ("Apple");
1627 #endif
1631 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
1632        doc: /* Return the version numbers of the server of DISPLAY.
1633 The value is a list of three integers: the major and minor
1634 version numbers of the X Protocol in use, and the distributor-specific
1635 release number.  See also the function `x-server-vendor'.
1637 The optional argument DISPLAY specifies which display to ask about.
1638 DISPLAY should be either a frame or a display name (a string).
1639 If omitted or nil, that stands for the selected frame's display.  */)
1640      (Lisp_Object display)
1642   /*NOTE: it is unclear what would best correspond with "protocol";
1643           we return 10.3, meaning Panther, since this is roughly the
1644           level that GNUstep's APIs correspond to.
1645           The last number is where we distinguish between the Apple
1646           and GNUstep implementations ("distributor-specific release
1647           number") and give int'ized versions of major.minor. */
1648   return Fcons (make_number (10),
1649                 Fcons (make_number (3),
1650                        Fcons (make_number (ns_appkit_version_int()), Qnil)));
1654 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
1655        doc: /* Return the number of screens on Nextstep display server DISPLAY.
1656 DISPLAY should be a frame, the display name as a string, or a terminal ID.
1657 If omitted or nil, the selected frame's display is used.  */)
1658      (Lisp_Object display)
1660   int num;
1662   check_ns ();
1663   num = [[NSScreen screens] count];
1665   return (num != 0) ? make_number (num) : Qnil;
1669 DEFUN ("x-display-mm-height", Fx_display_mm_height, Sx_display_mm_height,
1670        0, 1, 0,
1671        doc: /* Return the height of Nextstep display server DISPLAY, in millimeters.
1672 DISPLAY should be a frame, the display name as a string, or a terminal ID.
1673 If omitted or nil, the selected frame's display is used.  */)
1674      (Lisp_Object display)
1676   check_ns ();
1677   return make_number ((int)
1678                      ([ns_get_screen (display) frame].size.height/(92.0/25.4)));
1682 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width,
1683        0, 1, 0,
1684        doc: /* Return the width of Nextstep display server DISPLAY, in millimeters.
1685 DISPLAY should be a frame, the display name as a string, or a terminal ID.
1686 If omitted or nil, the selected frame's display is used.  */)
1687      (Lisp_Object display)
1689   check_ns ();
1690   return make_number ((int)
1691                      ([ns_get_screen (display) frame].size.width/(92.0/25.4)));
1695 DEFUN ("x-display-backing-store", Fx_display_backing_store,
1696        Sx_display_backing_store, 0, 1, 0,
1697        doc: /* Return whether the Nextstep display DISPLAY supports backing store.
1698 The value may be `buffered', `retained', or `non-retained'.
1699 DISPLAY should be a frame, the display name as a string, or a terminal ID.
1700 If omitted or nil, the selected frame's display is used.  */)
1701      (Lisp_Object display)
1703   check_ns ();
1704   switch ([ns_get_window (display) backingType])
1705     {
1706     case NSBackingStoreBuffered:
1707       return intern ("buffered");
1708     case NSBackingStoreRetained:
1709       return intern ("retained");
1710     case NSBackingStoreNonretained:
1711       return intern ("non-retained");
1712     default:
1713       error ("Strange value for backingType parameter of frame");
1714     }
1715   return Qnil;  /* not reached, shut compiler up */
1719 DEFUN ("x-display-visual-class", Fx_display_visual_class,
1720        Sx_display_visual_class, 0, 1, 0,
1721        doc: /* Return the visual class of the Nextstep display server DISPLAY.
1722 The value is one of the symbols `static-gray', `gray-scale',
1723 `static-color', `pseudo-color', `true-color', or `direct-color'.
1724 DISPLAY should be a frame, the display name as a string, or a terminal ID.
1725 If omitted or nil, the selected frame's display is used.  */)
1726      (Lisp_Object display)
1728   NSWindowDepth depth;
1729   check_ns ();
1730   depth = [ns_get_screen (display) depth];
1732   if ( depth == NSBestDepth (NSCalibratedWhiteColorSpace, 2, 2, YES, NULL))
1733     return intern ("static-gray");
1734   else if (depth == NSBestDepth (NSCalibratedWhiteColorSpace, 8, 8, YES, NULL))
1735     return intern ("gray-scale");
1736   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 8, 8, YES, NULL))
1737     return intern ("pseudo-color");
1738   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 4, 12, NO, NULL))
1739     return intern ("true-color");
1740   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 8, 24, NO, NULL))
1741     return intern ("direct-color");
1742   else
1743     /* color mgmt as far as we do it is really handled by Nextstep itself anyway */
1744     return intern ("direct-color");
1748 DEFUN ("x-display-save-under", Fx_display_save_under,
1749        Sx_display_save_under, 0, 1, 0,
1750        doc: /* Return t if DISPLAY supports the save-under feature.
1751 The optional argument DISPLAY specifies which display to ask about.
1752 DISPLAY should be a frame, the display name as a string, or a terminal ID.
1753 If omitted or nil, the selected frame's display is used.  */)
1754      (Lisp_Object display)
1756   check_ns ();
1757   switch ([ns_get_window (display) backingType])
1758     {
1759     case NSBackingStoreBuffered:
1760       return Qt;
1762     case NSBackingStoreRetained:
1763     case NSBackingStoreNonretained:
1764       return Qnil;
1766     default:
1767       error ("Strange value for backingType parameter of frame");
1768     }
1769   return Qnil;  /* not reached, shut compiler up */
1773 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
1774        1, 3, 0,
1775        doc: /* Open a connection to a display server.
1776 DISPLAY is the name of the display to connect to.
1777 Optional second arg XRM-STRING is a string of resources in xrdb format.
1778 If the optional third arg MUST-SUCCEED is non-nil,
1779 terminate Emacs if we can't open the connection.
1780 \(In the Nextstep version, the last two arguments are currently ignored.)  */)
1781      (Lisp_Object display, Lisp_Object resource_string, Lisp_Object must_succeed)
1783   struct ns_display_info *dpyinfo;
1785   CHECK_STRING (display);
1787   nxatoms_of_nsselect ();
1788   dpyinfo = ns_term_init (display);
1789   if (dpyinfo == 0)
1790     {
1791       if (!NILP (must_succeed))
1792         fatal ("OpenStep on %s not responding.\n",
1793                SSDATA (display));
1794       else
1795         error ("OpenStep on %s not responding.\n",
1796                SSDATA (display));
1797     }
1799   return Qnil;
1803 DEFUN ("x-close-connection", Fx_close_connection, Sx_close_connection,
1804        1, 1, 0,
1805        doc: /* Close the connection to the current Nextstep display server.
1806 The argument DISPLAY is currently ignored.  */)
1807      (Lisp_Object display)
1809   check_ns ();
1810   /*ns_delete_terminal (dpyinfo->terminal); */
1811   [NSApp terminate: NSApp];
1812   return Qnil;
1816 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
1817        doc: /* Return the list of display names that Emacs has connections to.  */)
1818      (void)
1820   Lisp_Object tail, result;
1822   result = Qnil;
1823   for (tail = ns_display_name_list; CONSP (tail); tail = XCDR (tail))
1824     result = Fcons (XCAR (XCAR (tail)), result);
1826   return result;
1830 DEFUN ("ns-hide-others", Fns_hide_others, Sns_hide_others,
1831        0, 0, 0,
1832        doc: /* Hides all applications other than Emacs.  */)
1833      (void)
1835   check_ns ();
1836   [NSApp hideOtherApplications: NSApp];
1837   return Qnil;
1840 DEFUN ("ns-hide-emacs", Fns_hide_emacs, Sns_hide_emacs,
1841        1, 1, 0,
1842        doc: /* If ON is non-nil, the entire Emacs application is hidden.
1843 Otherwise if Emacs is hidden, it is unhidden.
1844 If ON is equal to `activate', Emacs is unhidden and becomes
1845 the active application.  */)
1846      (Lisp_Object on)
1848   check_ns ();
1849   if (EQ (on, intern ("activate")))
1850     {
1851       [NSApp unhide: NSApp];
1852       [NSApp activateIgnoringOtherApps: YES];
1853     }
1854   else if (NILP (on))
1855     [NSApp unhide: NSApp];
1856   else
1857     [NSApp hide: NSApp];
1858   return Qnil;
1862 DEFUN ("ns-emacs-info-panel", Fns_emacs_info_panel, Sns_emacs_info_panel,
1863        0, 0, 0,
1864        doc: /* Shows the 'Info' or 'About' panel for Emacs.  */)
1865      (void)
1867   check_ns ();
1868   [NSApp orderFrontStandardAboutPanel: nil];
1869   return Qnil;
1873 DEFUN ("ns-font-name", Fns_font_name, Sns_font_name, 1, 1, 0,
1874        doc: /* Determine font PostScript or family name for font NAME.
1875 NAME should be a string containing either the font name or an XLFD
1876 font descriptor.  If string contains `fontset' and not
1877 `fontset-startup', it is left alone. */)
1878      (Lisp_Object name)
1880   char *nm;
1881   CHECK_STRING (name);
1882   nm = SSDATA (name);
1884   if (nm[0] != '-')
1885     return name;
1886   if (strstr (nm, "fontset") && !strstr (nm, "fontset-startup"))
1887     return name;
1889   return build_string (ns_xlfd_to_fontname (SSDATA (name)));
1893 DEFUN ("ns-list-colors", Fns_list_colors, Sns_list_colors, 0, 1, 0,
1894        doc: /* Return a list of all available colors.
1895 The optional argument FRAME is currently ignored.  */)
1896      (Lisp_Object frame)
1898   Lisp_Object list = Qnil;
1899   NSEnumerator *colorlists;
1900   NSColorList *clist;
1902   if (!NILP (frame))
1903     {
1904       CHECK_FRAME (frame);
1905       if (! FRAME_NS_P (XFRAME (frame)))
1906         error ("non-Nextstep frame used in `ns-list-colors'");
1907     }
1909   BLOCK_INPUT;
1911   colorlists = [[NSColorList availableColorLists] objectEnumerator];
1912   while ((clist = [colorlists nextObject]))
1913     {
1914       if ([[clist name] length] < 7 ||
1915           [[clist name] rangeOfString: @"PANTONE"].location == 0)
1916         {
1917           NSEnumerator *cnames = [[clist allKeys] reverseObjectEnumerator];
1918           NSString *cname;
1919           while ((cname = [cnames nextObject]))
1920             list = Fcons (build_string ([cname UTF8String]), list);
1921 /*           for (i = [[clist allKeys] count] - 1; i >= 0; i--)
1922                list = Fcons (build_string ([[[clist allKeys] objectAtIndex: i]
1923                                              UTF8String]), list); */
1924         }
1925     }
1927   UNBLOCK_INPUT;
1929   return list;
1933 DEFUN ("ns-list-services", Fns_list_services, Sns_list_services, 0, 0, 0,
1934        doc: /* List available Nextstep services by querying NSApp.  */)
1935      (void)
1937 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
1938   /* You can't get services like this in 10.6+.  */
1939   return Qnil;
1940 #else
1941   Lisp_Object ret = Qnil;
1942   NSMenu *svcs;
1943   id delegate;
1945   check_ns ();
1946   svcs = [[NSMenu alloc] initWithTitle: @"Services"];
1947   [NSApp setServicesMenu: svcs];  /* this and next rebuild on <10.4 */
1948   [NSApp registerServicesMenuSendTypes: ns_send_types
1949                            returnTypes: ns_return_types];
1951 /* On Tiger, services menu updating was made lazier (waits for user to
1952    actually click on the menu), so we have to force things along: */
1953 #ifdef NS_IMPL_COCOA
1954   if (NSAppKitVersionNumber >= 744.0)
1955     {
1956       delegate = [svcs delegate];
1957       if (delegate != nil)
1958         {
1959           if ([delegate respondsToSelector: @selector (menuNeedsUpdate:)])
1960               [delegate menuNeedsUpdate: svcs];
1961           if ([delegate respondsToSelector:
1962                             @selector (menu:updateItem:atIndex:shouldCancel:)])
1963             {
1964               int i, len = [delegate numberOfItemsInMenu: svcs];
1965               for (i =0; i<len; i++)
1966                   [svcs addItemWithTitle: @"" action: NULL keyEquivalent: @""];
1967               for (i =0; i<len; i++)
1968                   if (![delegate menu: svcs
1969                            updateItem: (NSMenuItem *)[svcs itemAtIndex: i]
1970                               atIndex: i shouldCancel: NO])
1971                     break;
1972             }
1973         }
1974     }
1975 #endif
1977   [svcs setAutoenablesItems: NO];
1978 #ifdef NS_IMPL_COCOA
1979   [svcs update]; /* on OS X, converts from '/' structure */
1980 #endif
1982   ret = interpret_services_menu (svcs, Qnil, ret);
1983   return ret;
1984 #endif
1988 DEFUN ("ns-perform-service", Fns_perform_service, Sns_perform_service,
1989        2, 2, 0,
1990        doc: /* Perform Nextstep SERVICE on SEND.
1991 SEND should be either a string or nil.
1992 The return value is the result of the service, as string, or nil if
1993 there was no result.  */)
1994      (Lisp_Object service, Lisp_Object send)
1996   id pb;
1997   NSString *svcName;
1998   char *utfStr;
2000   CHECK_STRING (service);
2001   check_ns ();
2003   utfStr = SSDATA (service);
2004   svcName = [NSString stringWithUTF8String: utfStr];
2006   pb =[NSPasteboard pasteboardWithUniqueName];
2007   ns_string_to_pasteboard (pb, send);
2009   if (NSPerformService (svcName, pb) == NO)
2010     Fsignal (Qquit, Fcons (build_string ("service not available"), Qnil));
2012   if ([[pb types] count] == 0)
2013     return build_string ("");
2014   return ns_string_from_pasteboard (pb);
2018 DEFUN ("ns-convert-utf8-nfd-to-nfc", Fns_convert_utf8_nfd_to_nfc,
2019        Sns_convert_utf8_nfd_to_nfc, 1, 1, 0,
2020        doc: /* Return an NFC string that matches the UTF-8 NFD string STR.  */)
2021      (Lisp_Object str)
2023 /* TODO: If GNUstep ever implements precomposedStringWithCanonicalMapping,
2024          remove this. */
2025   NSString *utfStr;
2027   CHECK_STRING (str);
2028   utfStr = [NSString stringWithUTF8String: SSDATA (str)];
2029   if (![utfStr respondsToSelector:
2030                  @selector (precomposedStringWithCanonicalMapping)])
2031     {
2032       message1
2033         ("Warning: ns-convert-utf8-nfd-to-nfc unsupported under GNUstep.\n");
2034       return Qnil;
2035     }
2036   else
2037     utfStr = [utfStr precomposedStringWithCanonicalMapping];
2038   return build_string ([utfStr UTF8String]);
2042 #ifdef NS_IMPL_COCOA
2044 /* Compile and execute the AppleScript SCRIPT and return the error
2045    status as function value.  A zero is returned if compilation and
2046    execution is successful, in which case *RESULT is set to a Lisp
2047    string or a number containing the resulting script value.  Otherwise,
2048    1 is returned. */
2049 static int
2050 ns_do_applescript (Lisp_Object script, Lisp_Object *result)
2052   NSAppleEventDescriptor *desc;
2053   NSDictionary* errorDict;
2054   NSAppleEventDescriptor* returnDescriptor = NULL;
2056   NSAppleScript* scriptObject =
2057     [[NSAppleScript alloc] initWithSource:
2058                              [NSString stringWithUTF8String: SSDATA (script)]];
2060   returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
2061   [scriptObject release];
2063   *result = Qnil;
2065   if (returnDescriptor != NULL)
2066     {
2067       // successful execution
2068       if (kAENullEvent != [returnDescriptor descriptorType])
2069         {
2070           *result = Qt;
2071           // script returned an AppleScript result
2072           if ((typeUnicodeText == [returnDescriptor descriptorType]) ||
2073 #if defined (NS_IMPL_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
2074               (typeUTF16ExternalRepresentation
2075                == [returnDescriptor descriptorType]) ||
2076 #endif
2077               (typeUTF8Text == [returnDescriptor descriptorType]) ||
2078               (typeCString == [returnDescriptor descriptorType]))
2079             {
2080               desc = [returnDescriptor coerceToDescriptorType: typeUTF8Text];
2081               if (desc)
2082                 *result = build_string([[desc stringValue] UTF8String]);
2083             }
2084           else
2085             {
2086               /* use typeUTF16ExternalRepresentation? */
2087               // coerce the result to the appropriate ObjC type
2088               desc = [returnDescriptor coerceToDescriptorType: typeUTF8Text];
2089               if (desc)
2090                 *result = make_number([desc int32Value]);
2091             }
2092         }
2093     }
2094   else
2095     {
2096       // no script result, return error
2097       return 1;
2098     }
2099   return 0;
2102 /* Helper function called from sendEvent to run applescript
2103    from within the main event loop.  */
2105 void
2106 ns_run_ascript (void)
2108   as_status = ns_do_applescript (as_script, as_result);
2111 DEFUN ("ns-do-applescript", Fns_do_applescript, Sns_do_applescript, 1, 1, 0,
2112        doc: /* Execute AppleScript SCRIPT and return the result.
2113 If compilation and execution are successful, the resulting script value
2114 is returned as a string, a number or, in the case of other constructs, t.
2115 In case the execution fails, an error is signaled. */)
2116      (Lisp_Object script)
2118   Lisp_Object result;
2119   int status;
2120   NSEvent *nxev;
2122   CHECK_STRING (script);
2123   check_ns ();
2125   BLOCK_INPUT;
2127   as_script = script;
2128   as_result = &result;
2130   /* executing apple script requires the event loop to run, otherwise
2131      errors aren't returned and executeAndReturnError hangs forever.
2132      Post an event that runs applescript and then start the event loop.
2133      The event loop is exited when the script is done.  */
2134   nxev = [NSEvent otherEventWithType: NSApplicationDefined
2135                             location: NSMakePoint (0, 0)
2136                        modifierFlags: 0
2137                            timestamp: 0
2138                         windowNumber: [[NSApp mainWindow] windowNumber]
2139                              context: [NSApp context]
2140                              subtype: 0
2141                                data1: 0
2142                                data2: NSAPP_DATA2_RUNASSCRIPT];
2144   [NSApp postEvent: nxev atStart: NO];
2145   [NSApp run];
2147   status = as_status;
2148   as_status = 0;
2149   as_script = Qnil;
2150   as_result = 0;
2151   UNBLOCK_INPUT;
2152   if (status == 0)
2153     return result;
2154   else if (!STRINGP (result))
2155     error ("AppleScript error %d", status);
2156   else
2157     error ("%s", SSDATA (result));
2159 #endif
2163 /* ==========================================================================
2165     Miscellaneous functions not called through hooks
2167    ========================================================================== */
2170 /* called from image.c */
2171 FRAME_PTR
2172 check_x_frame (Lisp_Object frame)
2174   return check_ns_frame (frame);
2178 /* called from frame.c */
2179 struct ns_display_info *
2180 check_x_display_info (Lisp_Object frame)
2182   return check_ns_display_info (frame);
2186 void
2187 x_set_scroll_bar_default_width (struct frame *f)
2189   int wid = FRAME_COLUMN_WIDTH (f);
2190   FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = NS_SCROLL_BAR_WIDTH_DEFAULT;
2191   FRAME_CONFIG_SCROLL_BAR_COLS (f) = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) +
2192                                       wid - 1) / wid;
2196 /* terms impl this instead of x-get-resource directly */
2197 const char *
2198 x_get_string_resource (XrmDatabase rdb, char *name, char *class)
2200   /* remove appname prefix; TODO: allow for !="Emacs" */
2201   char *toCheck = class + (!strncmp (class, "Emacs.", 6) ? 6 : 0);
2202   const char *res;
2203   check_ns ();
2205   if (inhibit_x_resources)
2206     /* --quick was passed, so this is a no-op.  */
2207     return NULL;
2209   res = ns_get_defaults_value (toCheck);
2210   return !res ? NULL :
2211       (!c_strncasecmp (res, "YES", 3) ? "true" :
2212           (!c_strncasecmp (res, "NO", 2) ? "false" : res));
2216 Lisp_Object
2217 x_get_focus_frame (struct frame *frame)
2219   struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
2220   Lisp_Object nsfocus;
2222   if (!dpyinfo->x_focus_frame)
2223     return Qnil;
2225   XSETFRAME (nsfocus, dpyinfo->x_focus_frame);
2226   return nsfocus;
2231 x_pixel_width (struct frame *f)
2233   return FRAME_PIXEL_WIDTH (f);
2238 x_pixel_height (struct frame *f)
2240   return FRAME_PIXEL_HEIGHT (f);
2245 x_char_width (struct frame *f)
2247   return FRAME_COLUMN_WIDTH (f);
2252 x_char_height (struct frame *f)
2254   return FRAME_LINE_HEIGHT (f);
2259 x_screen_planes (struct frame *f)
2261   return FRAME_NS_DISPLAY_INFO (f)->n_planes;
2265 void
2266 x_sync (struct frame *f)
2268   /* XXX Not implemented XXX */
2269   return;
2274 /* ==========================================================================
2276     Lisp definitions that, for whatever reason, we can't alias as 'ns-XXX'.
2278    ========================================================================== */
2281 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
2282        doc: /* Internal function called by `color-defined-p', which see.
2283 \(Note that the Nextstep version of this function ignores FRAME.)  */)
2284      (Lisp_Object color, Lisp_Object frame)
2286   NSColor * col;
2287   check_ns ();
2288   return ns_lisp_to_color (color, &col) ? Qnil : Qt;
2292 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
2293        doc: /* Internal function called by `color-values', which see.  */)
2294      (Lisp_Object color, Lisp_Object frame)
2296   NSColor * col;
2297   CGFloat red, green, blue, alpha;
2299   check_ns ();
2300   CHECK_STRING (color);
2302   if (ns_lisp_to_color (color, &col))
2303     return Qnil;
2305   [[col colorUsingColorSpaceName: NSCalibratedRGBColorSpace]
2306         getRed: &red green: &green blue: &blue alpha: &alpha];
2307   return list3 (make_number (lrint (red*65280)),
2308                 make_number (lrint (green*65280)),
2309                 make_number (lrint (blue*65280)));
2313 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
2314        doc: /* Internal function called by `display-color-p', which see.  */)
2315      (Lisp_Object display)
2317   NSWindowDepth depth;
2318   NSString *colorSpace;
2319   check_ns ();
2320   depth = [ns_get_screen (display) depth];
2321   colorSpace = NSColorSpaceFromDepth (depth);
2323   return    [colorSpace isEqualToString: NSDeviceWhiteColorSpace]
2324          || [colorSpace isEqualToString: NSCalibratedWhiteColorSpace]
2325       ? Qnil : Qt;
2329 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
2330        Sx_display_grayscale_p, 0, 1, 0,
2331        doc: /* Return t if the Nextstep display supports shades of gray.
2332 Note that color displays do support shades of gray.
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   NSWindowDepth depth;
2339   check_ns ();
2340   depth = [ns_get_screen (display) depth];
2342   return NSBitsPerPixelFromDepth (depth) > 1 ? Qt : Qnil;
2346 DEFUN ("x-display-pixel-width", Fx_display_pixel_width, Sx_display_pixel_width,
2347        0, 1, 0,
2348        doc: /* Return the width in pixels of the Nextstep display DISPLAY.
2349 The optional argument DISPLAY specifies which display to ask about.
2350 DISPLAY should be either a frame, a display name (a string), or terminal ID.
2351 If omitted or nil, that stands for the selected frame's display.  */)
2352      (Lisp_Object display)
2354   check_ns ();
2355   return make_number ((int) [ns_get_screen (display) frame].size.width);
2359 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
2360        Sx_display_pixel_height, 0, 1, 0,
2361        doc: /* Return the height in pixels of the Nextstep display DISPLAY.
2362 The optional argument DISPLAY specifies which display to ask about.
2363 DISPLAY should be either a frame, a display name (a string), or terminal ID.
2364 If omitted or nil, that stands for the selected frame's display.  */)
2365      (Lisp_Object display)
2367   check_ns ();
2368   return make_number ((int) [ns_get_screen (display) frame].size.height);
2372 DEFUN ("display-usable-bounds", Fns_display_usable_bounds,
2373        Sns_display_usable_bounds, 0, 1, 0,
2374        doc: /* Return the bounds of the usable part of the screen.
2375 The return value is a list of integers (LEFT TOP WIDTH HEIGHT), which
2376 are the boundaries of the usable part of the screen, excluding areas
2377 reserved for the Mac menu, dock, and so forth.
2379 The screen queried corresponds to DISPLAY, which should be either a
2380 frame, a display name (a string), or terminal ID.  If omitted or nil,
2381 that stands for the selected frame's display. */)
2382      (Lisp_Object display)
2384   NSScreen *screen;
2385   NSRect vScreen;
2387   check_ns ();
2388   screen = ns_get_screen (display);
2389   if (!screen)
2390     return Qnil;
2392   vScreen = [screen visibleFrame];
2394   /* NS coordinate system is upside-down.
2395      Transform to screen-specific coordinates. */
2396   return list4 (make_number ((int) vScreen.origin.x),
2397                 make_number ((int) [screen frame].size.height
2398                              - vScreen.size.height - vScreen.origin.y),
2399                 make_number ((int) vScreen.size.width),
2400                 make_number ((int) vScreen.size.height));
2404 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
2405        0, 1, 0,
2406        doc: /* Return the number of bitplanes of the Nextstep display DISPLAY.
2407 The optional argument DISPLAY specifies which display to ask about.
2408 DISPLAY should be either a frame, a display name (a string), or terminal ID.
2409 If omitted or nil, that stands for the selected frame's display.  */)
2410      (Lisp_Object display)
2412   check_ns ();
2413   return make_number
2414     (NSBitsPerPixelFromDepth ([ns_get_screen (display) depth]));
2418 DEFUN ("x-display-color-cells", Fx_display_color_cells,
2419        Sx_display_color_cells, 0, 1, 0,
2420        doc: /* Returns the number of color cells of the Nextstep display DISPLAY.
2421 The optional argument DISPLAY specifies which display to ask about.
2422 DISPLAY should be either a frame, a display name (a string), or terminal ID.
2423 If omitted or nil, that stands for the selected frame's display.  */)
2424      (Lisp_Object display)
2426   struct ns_display_info *dpyinfo;
2427   check_ns ();
2429   dpyinfo = check_ns_display_info (display);
2430   /* We force 24+ bit depths to 24-bit to prevent an overflow.  */
2431   return make_number (1 << min (dpyinfo->n_planes, 24));
2435 /* Unused dummy def needed for compatibility. */
2436 Lisp_Object tip_frame;
2438 /* TODO: move to xdisp or similar */
2439 static void
2440 compute_tip_xy (struct frame *f,
2441                 Lisp_Object parms,
2442                 Lisp_Object dx,
2443                 Lisp_Object dy,
2444                 int width,
2445                 int height,
2446                 int *root_x,
2447                 int *root_y)
2449   Lisp_Object left, top;
2450   EmacsView *view = FRAME_NS_VIEW (f);
2451   NSPoint pt;
2453   /* Start with user-specified or mouse position.  */
2454   left = Fcdr (Fassq (Qleft, parms));
2455   top = Fcdr (Fassq (Qtop, parms));
2457   if (!INTEGERP (left) || !INTEGERP (top))
2458     {
2459       pt = last_mouse_motion_position;
2460       /* Convert to screen coordinates */
2461       pt = [view convertPoint: pt toView: nil];
2462       pt = [[view window] convertBaseToScreen: pt];
2463     }
2464   else
2465     {
2466       /* Absolute coordinates.  */
2467       pt.x = XINT (left);
2468       pt.y = x_display_pixel_height (FRAME_NS_DISPLAY_INFO (f)) - XINT (top)
2469         - height;
2470     }
2472   /* Ensure in bounds.  (Note, screen origin = lower left.) */
2473   if (INTEGERP (left))
2474     *root_x = pt.x;
2475   else if (pt.x + XINT (dx) <= 0)
2476     *root_x = 0; /* Can happen for negative dx */
2477   else if (pt.x + XINT (dx) + width
2478            <= x_display_pixel_width (FRAME_NS_DISPLAY_INFO (f)))
2479     /* It fits to the right of the pointer.  */
2480     *root_x = pt.x + XINT (dx);
2481   else if (width + XINT (dx) <= pt.x)
2482     /* It fits to the left of the pointer.  */
2483     *root_x = pt.x - width - XINT (dx);
2484   else
2485     /* Put it left justified on the screen -- it ought to fit that way.  */
2486     *root_x = 0;
2488   if (INTEGERP (top))
2489     *root_y = pt.y;
2490   else if (pt.y - XINT (dy) - height >= 0)
2491     /* It fits below the pointer.  */
2492     *root_y = pt.y - height - XINT (dy);
2493   else if (pt.y + XINT (dy) + height
2494            <= x_display_pixel_height (FRAME_NS_DISPLAY_INFO (f)))
2495     /* It fits above the pointer */
2496       *root_y = pt.y + XINT (dy);
2497   else
2498     /* Put it on the top.  */
2499     *root_y = x_display_pixel_height (FRAME_NS_DISPLAY_INFO (f)) - height;
2503 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
2504        doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
2505 A tooltip window is a small window displaying a string.
2507 This is an internal function; Lisp code should call `tooltip-show'.
2509 FRAME nil or omitted means use the selected frame.
2511 PARMS is an optional list of frame parameters which can be used to
2512 change the tooltip's appearance.
2514 Automatically hide the tooltip after TIMEOUT seconds.  TIMEOUT nil
2515 means use the default timeout of 5 seconds.
2517 If the list of frame parameters PARMS contains a `left' parameter,
2518 the tooltip is displayed at that x-position.  Otherwise it is
2519 displayed at the mouse position, with offset DX added (default is 5 if
2520 DX isn't specified).  Likewise for the y-position; if a `top' frame
2521 parameter is specified, it determines the y-position of the tooltip
2522 window, otherwise it is displayed at the mouse position, with offset
2523 DY added (default is -10).
2525 A tooltip's maximum size is specified by `x-max-tooltip-size'.
2526 Text larger than the specified size is clipped.  */)
2527      (Lisp_Object string, Lisp_Object frame, Lisp_Object parms, Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
2529   int root_x, root_y;
2530   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2531   ptrdiff_t count = SPECPDL_INDEX ();
2532   struct frame *f;
2533   char *str;
2534   NSSize size;
2536   specbind (Qinhibit_redisplay, Qt);
2538   GCPRO4 (string, parms, frame, timeout);
2540   CHECK_STRING (string);
2541   str = SSDATA (string);
2542   f = check_x_frame (frame);
2543   if (NILP (timeout))
2544     timeout = make_number (5);
2545   else
2546     CHECK_NATNUM (timeout);
2548   if (NILP (dx))
2549     dx = make_number (5);
2550   else
2551     CHECK_NUMBER (dx);
2553   if (NILP (dy))
2554     dy = make_number (-10);
2555   else
2556     CHECK_NUMBER (dy);
2558   BLOCK_INPUT;
2559   if (ns_tooltip == nil)
2560     ns_tooltip = [[EmacsTooltip alloc] init];
2561   else
2562     Fx_hide_tip ();
2564   [ns_tooltip setText: str];
2565   size = [ns_tooltip frame].size;
2567   /* Move the tooltip window where the mouse pointer is.  Resize and
2568      show it.  */
2569   compute_tip_xy (f, parms, dx, dy, (int)size.width, (int)size.height,
2570                   &root_x, &root_y);
2572   [ns_tooltip showAtX: root_x Y: root_y for: XINT (timeout)];
2573   UNBLOCK_INPUT;
2575   UNGCPRO;
2576   return unbind_to (count, Qnil);
2580 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
2581        doc: /* Hide the current tooltip window, if there is any.
2582 Value is t if tooltip was open, nil otherwise.  */)
2583      (void)
2585   if (ns_tooltip == nil || ![ns_tooltip isActive])
2586     return Qnil;
2587   [ns_tooltip hide];
2588   return Qt;
2592 /* ==========================================================================
2594     Class implementations
2596    ========================================================================== */
2599 @implementation EmacsSavePanel
2600 #ifdef NS_IMPL_COCOA
2601 /* --------------------------------------------------------------------------
2602    These are overridden to intercept on OS X: ending panel restarts NSApp
2603    event loop if it is stopped.  Not sure if this is correct behavior,
2604    perhaps should check if running and if so send an appdefined.
2605    -------------------------------------------------------------------------- */
2606 - (void) ok: (id)sender
2608   [super ok: sender];
2609   panelOK = 1;
2610   [NSApp stop: self];
2612 - (void) cancel: (id)sender
2614   [super cancel: sender];
2615   [NSApp stop: self];
2617 #endif
2618 @end
2621 @implementation EmacsOpenPanel
2622 #ifdef NS_IMPL_COCOA
2623 /* --------------------------------------------------------------------------
2624    These are overridden to intercept on OS X: ending panel restarts NSApp
2625    event loop if it is stopped.  Not sure if this is correct behavior,
2626    perhaps should check if running and if so send an appdefined.
2627    -------------------------------------------------------------------------- */
2628 - (void) ok: (id)sender
2630   [super ok: sender];
2631   panelOK = 1;
2632   [NSApp stop: self];
2634 - (void) cancel: (id)sender
2636   [super cancel: sender];
2637   [NSApp stop: self];
2639 #endif
2640 @end
2643 @implementation EmacsFileDelegate
2644 /* --------------------------------------------------------------------------
2645    Delegate methods for Open/Save panels
2646    -------------------------------------------------------------------------- */
2647 - (BOOL)panel: (id)sender isValidFilename: (NSString *)filename
2649   return YES;
2651 - (BOOL)panel: (id)sender shouldShowFilename: (NSString *)filename
2653   return YES;
2655 - (NSString *)panel: (id)sender userEnteredFilename: (NSString *)filename
2656           confirmed: (BOOL)okFlag
2658   return filename;
2660 @end
2662 #endif
2665 /* ==========================================================================
2667     Lisp interface declaration
2669    ========================================================================== */
2672 void
2673 syms_of_nsfns (void)
2675   Qfontsize = intern_c_string ("fontsize");
2676   staticpro (&Qfontsize);
2678   DEFVAR_LISP ("ns-icon-type-alist", Vns_icon_type_alist,
2679                doc: /* Alist of elements (REGEXP . IMAGE) for images of icons associated to frames.
2680 If the title of a frame matches REGEXP, then IMAGE.tiff is
2681 selected as the image of the icon representing the frame when it's
2682 miniaturized.  If an element is t, then Emacs tries to select an icon
2683 based on the filetype of the visited file.
2685 The images have to be installed in a folder called English.lproj in the
2686 Emacs folder.  You have to restart Emacs after installing new icons.
2688 Example: Install an icon Gnus.tiff and execute the following code
2690   (setq ns-icon-type-alist
2691         (append ns-icon-type-alist
2692                 '((\"^\\\\*\\\\(Group\\\\*$\\\\|Summary \\\\|Article\\\\*$\\\\)\"
2693                    . \"Gnus\"))))
2695 When you miniaturize a Group, Summary or Article frame, Gnus.tiff will
2696 be used as the image of the icon representing the frame.  */);
2697   Vns_icon_type_alist = Fcons (Qt, Qnil);
2699   DEFVAR_LISP ("ns-version-string", Vns_version_string,
2700                doc: /* Toolkit version for NS Windowing.  */);
2701   Vns_version_string = ns_appkit_version_str ();
2703   defsubr (&Sns_read_file_name);
2704   defsubr (&Sns_get_resource);
2705   defsubr (&Sns_set_resource);
2706   defsubr (&Sxw_display_color_p); /* this and next called directly by C code */
2707   defsubr (&Sx_display_grayscale_p);
2708   defsubr (&Sns_font_name);
2709   defsubr (&Sns_list_colors);
2710 #ifdef NS_IMPL_COCOA
2711   defsubr (&Sns_do_applescript);
2712 #endif
2713   defsubr (&Sxw_color_defined_p);
2714   defsubr (&Sxw_color_values);
2715   defsubr (&Sx_server_max_request_size);
2716   defsubr (&Sx_server_vendor);
2717   defsubr (&Sx_server_version);
2718   defsubr (&Sx_display_pixel_width);
2719   defsubr (&Sx_display_pixel_height);
2720   defsubr (&Sns_display_usable_bounds);
2721   defsubr (&Sx_display_mm_width);
2722   defsubr (&Sx_display_mm_height);
2723   defsubr (&Sx_display_screens);
2724   defsubr (&Sx_display_planes);
2725   defsubr (&Sx_display_color_cells);
2726   defsubr (&Sx_display_visual_class);
2727   defsubr (&Sx_display_backing_store);
2728   defsubr (&Sx_display_save_under);
2729   defsubr (&Sx_create_frame);
2730   defsubr (&Sx_open_connection);
2731   defsubr (&Sx_close_connection);
2732   defsubr (&Sx_display_list);
2734   defsubr (&Sns_hide_others);
2735   defsubr (&Sns_hide_emacs);
2736   defsubr (&Sns_emacs_info_panel);
2737   defsubr (&Sns_list_services);
2738   defsubr (&Sns_perform_service);
2739   defsubr (&Sns_convert_utf8_nfd_to_nfc);
2740   defsubr (&Sx_focus_frame);
2741   defsubr (&Sns_popup_font_panel);
2742   defsubr (&Sns_popup_color_panel);
2744   defsubr (&Sx_show_tip);
2745   defsubr (&Sx_hide_tip);
2747   /* used only in fontset.c */
2748   check_window_system_func = check_ns;
2750   as_status = 0;
2751   as_script = Qnil;
2752   as_result = 0;