* net/eww.el (eww-mode-map): Remove mentions of `eww-quit'.
[emacs.git] / src / nsfns.m
blobce859e8333d8b3609845815f38f7df12be0ffa37
1 /* Functions for the NeXT/Open/GNUstep and MacOSX window system.
3 Copyright (C) 1989, 1992-1994, 2005-2006, 2008-2014 Free Software
4 Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.  */
22 Originally by Carl Edman
23 Updated by Christian Limpach (chris@nice.ch)
24 OpenStep/Rhapsody port by Scott Bender (sbender@harmony-ds.com)
25 MacOSX/Aqua port by Christophe de Dinechin (descubes@earthlink.net)
26 GNUstep port and post-20 update by Adrian Robert (arobert@cogsci.ucsd.edu)
29 /* This should be the first include, as it may set up #defines affecting
30    interpretation of even the system includes. */
31 #include <config.h>
33 #include <math.h>
34 #include <c-strcase.h>
36 #include "lisp.h"
37 #include "blockinput.h"
38 #include "nsterm.h"
39 #include "window.h"
40 #include "character.h"
41 #include "buffer.h"
42 #include "keyboard.h"
43 #include "termhooks.h"
44 #include "fontset.h"
45 #include "font.h"
47 #ifdef NS_IMPL_COCOA
48 #include <IOKit/graphics/IOGraphicsLib.h>
49 #include "macfont.h"
50 #endif
52 #if 0
53 int fns_trace_num = 1;
54 #define NSTRACE(x)        fprintf (stderr, "%s:%d: [%d] " #x "\n",        \
55                                   __FILE__, __LINE__, ++fns_trace_num)
56 #else
57 #define NSTRACE(x)
58 #endif
60 #ifdef HAVE_NS
62 extern NSArray *ns_send_types, *ns_return_types, *ns_drag_types;
64 extern Lisp_Object Qforeground_color;
65 extern Lisp_Object Qbackground_color;
66 extern Lisp_Object Qcursor_color;
67 extern Lisp_Object Qinternal_border_width;
68 extern Lisp_Object Qvisibility;
69 extern Lisp_Object Qcursor_type;
70 extern Lisp_Object Qicon_type;
71 extern Lisp_Object Qicon_name;
72 extern Lisp_Object Qicon_left;
73 extern Lisp_Object Qicon_top;
74 extern Lisp_Object Qtop;
75 extern Lisp_Object Qdisplay;
76 extern Lisp_Object Qvertical_scroll_bars;
77 extern Lisp_Object Qhorizontal_scroll_bars;
78 extern Lisp_Object Qauto_raise;
79 extern Lisp_Object Qauto_lower;
80 extern Lisp_Object Qbox;
81 extern Lisp_Object Qscroll_bar_width;
82 extern Lisp_Object Qscroll_bar_height;
83 extern Lisp_Object Qx_resource_name;
84 extern Lisp_Object Qface_set_after_frame_default;
85 extern Lisp_Object Qunderline, Qundefined;
86 extern Lisp_Object Qheight, Qminibuffer, Qname, Qonly, Qwidth;
87 extern Lisp_Object Qunsplittable, Qmenu_bar_lines, Qbuffer_predicate, Qtitle;
90 Lisp_Object Qbuffered;
91 Lisp_Object Qfontsize;
93 EmacsTooltip *ns_tooltip = nil;
95 /* Need forward declaration here to preserve organizational integrity of file */
96 Lisp_Object Fx_open_connection (Lisp_Object, Lisp_Object, Lisp_Object);
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
107 /* ==========================================================================
109     Internal utility functions
111    ========================================================================== */
113 /* Let the user specify a Nextstep display with a Lisp object.
114    OBJECT may be nil, a frame or a terminal object.
115    nil stands for the selected frame--or, if that is not a Nextstep frame,
116    the first Nextstep display on the list.  */
118 static struct ns_display_info *
119 check_ns_display_info (Lisp_Object object)
121   struct ns_display_info *dpyinfo = NULL;
123   if (NILP (object))
124     {
125       struct frame *sf = XFRAME (selected_frame);
127       if (FRAME_NS_P (sf) && FRAME_LIVE_P (sf))
128         dpyinfo = FRAME_DISPLAY_INFO (sf);
129       else if (x_display_list != 0)
130         dpyinfo = x_display_list;
131       else
132         error ("Nextstep windows are not in use or not initialized");
133     }
134   else if (TERMINALP (object))
135     {
136       struct terminal *t = decode_live_terminal (object);
138       if (t->type != output_ns)
139         error ("Terminal %d is not a Nextstep display", t->id);
141       dpyinfo = t->display_info.ns;
142     }
143   else if (STRINGP (object))
144     dpyinfo = ns_display_info_for_name (object);
145   else
146     {
147       struct frame *f = decode_window_system_frame (object);
148       dpyinfo = FRAME_DISPLAY_INFO (f);
149     }
151   return dpyinfo;
155 static id
156 ns_get_window (Lisp_Object maybeFrame)
158   id view =nil, window =nil;
160   if (!FRAMEP (maybeFrame) || !FRAME_NS_P (XFRAME (maybeFrame)))
161     maybeFrame = selected_frame;/*wrong_type_argument (Qframep, maybeFrame); */
163   if (!NILP (maybeFrame))
164     view = FRAME_NS_VIEW (XFRAME (maybeFrame));
165   if (view) window =[view window];
167   return window;
171 /* Return the X display structure for the display named NAME.
172    Open a new connection if necessary.  */
173 struct ns_display_info *
174 ns_display_info_for_name (Lisp_Object name)
176   struct ns_display_info *dpyinfo;
178   CHECK_STRING (name);
180   for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
181     if (!NILP (Fstring_equal (XCAR (dpyinfo->name_list_element), name)))
182       return dpyinfo;
184   error ("Emacs for Nextstep does not yet support multi-display");
186   Fx_open_connection (name, Qnil, Qnil);
187   dpyinfo = x_display_list;
189   if (dpyinfo == 0)
190     error ("Display on %s not responding.\n", SDATA (name));
192   return dpyinfo;
195 static NSString *
196 ns_filename_from_panel (NSSavePanel *panel)
198 #ifdef NS_IMPL_COCOA
199   NSURL *url = [panel URL];
200   NSString *str = [url path];
201   return str;
202 #else
203   return [panel filename];
204 #endif
207 static NSString *
208 ns_directory_from_panel (NSSavePanel *panel)
210 #ifdef NS_IMPL_COCOA
211   NSURL *url = [panel directoryURL];
212   NSString *str = [url path];
213   return str;
214 #else
215   return [panel directory];
216 #endif
219 static Lisp_Object
220 interpret_services_menu (NSMenu *menu, Lisp_Object prefix, Lisp_Object old)
221 /* --------------------------------------------------------------------------
222    Turn the input menu (an NSMenu) into a lisp list for tracking on lisp side
223    -------------------------------------------------------------------------- */
225   int i, count;
226   NSMenuItem *item;
227   const char *name;
228   Lisp_Object nameStr;
229   unsigned short key;
230   NSString *keys;
231   Lisp_Object res;
233   count = [menu numberOfItems];
234   for (i = 0; i<count; i++)
235     {
236       item = [menu itemAtIndex: i];
237       name = [[item title] UTF8String];
238       if (!name) continue;
240       nameStr = build_string (name);
242       if ([item hasSubmenu])
243         {
244           old = interpret_services_menu ([item submenu],
245                                         Fcons (nameStr, prefix), old);
246         }
247       else
248         {
249           keys = [item keyEquivalent];
250           if (keys && [keys length] )
251             {
252               key = [keys characterAtIndex: 0];
253               res = make_number (key|super_modifier);
254             }
255           else
256             {
257               res = Qundefined;
258             }
259           old = Fcons (Fcons (res,
260                             Freverse (Fcons (nameStr,
261                                            prefix))),
262                     old);
263         }
264     }
265   return old;
270 /* ==========================================================================
272     Frame parameter setters
274    ========================================================================== */
277 static void
278 x_set_foreground_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
280   NSColor *col;
281   EmacsCGFloat r, g, b, alpha;
283   if (ns_lisp_to_color (arg, &col))
284     {
285       store_frame_param (f, Qforeground_color, oldval);
286       error ("Unknown color");
287     }
289   [col retain];
290   [f->output_data.ns->foreground_color release];
291   f->output_data.ns->foreground_color = col;
293   [col getRed: &r green: &g blue: &b alpha: &alpha];
294   FRAME_FOREGROUND_PIXEL (f) =
295     ARGB_TO_ULONG ((int)(alpha*0xff), (int)(r*0xff), (int)(g*0xff), (int)(b*0xff));
297   if (FRAME_NS_VIEW (f))
298     {
299       update_face_from_frame_parameter (f, Qforeground_color, arg);
300       /*recompute_basic_faces (f); */
301       if (FRAME_VISIBLE_P (f))
302         redraw_frame (f);
303     }
307 static void
308 x_set_background_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
310   struct face *face;
311   NSColor *col;
312   NSView *view = FRAME_NS_VIEW (f);
313   EmacsCGFloat r, g, b, alpha;
315   if (ns_lisp_to_color (arg, &col))
316     {
317       store_frame_param (f, Qbackground_color, oldval);
318       error ("Unknown color");
319     }
321   /* clear the frame; in some instances the NS-internal GC appears not to
322      update, or it does update and cannot clear old text properly */
323   if (FRAME_VISIBLE_P (f))
324     ns_clear_frame (f);
326   [col retain];
327   [f->output_data.ns->background_color release];
328   f->output_data.ns->background_color = col;
330   [col getRed: &r green: &g blue: &b alpha: &alpha];
331   FRAME_BACKGROUND_PIXEL (f) =
332     ARGB_TO_ULONG ((int)(alpha*0xff), (int)(r*0xff), (int)(g*0xff), (int)(b*0xff));
334   if (view != nil)
335     {
336       [[view window] setBackgroundColor: col];
338       if (alpha != (EmacsCGFloat) 1.0)
339           [[view window] setOpaque: NO];
340       else
341           [[view window] setOpaque: YES];
343       face = FRAME_DEFAULT_FACE (f);
344       if (face)
345         {
346           col = ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), f);
347           face->background = ns_index_color
348             ([col colorWithAlphaComponent: alpha], f);
350           update_face_from_frame_parameter (f, Qbackground_color, arg);
351         }
353       if (FRAME_VISIBLE_P (f))
354         redraw_frame (f);
355     }
359 static void
360 x_set_cursor_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
362   NSColor *col;
364   if (ns_lisp_to_color (arg, &col))
365     {
366       store_frame_param (f, Qcursor_color, oldval);
367       error ("Unknown color");
368     }
370   [FRAME_CURSOR_COLOR (f) release];
371   FRAME_CURSOR_COLOR (f) = [col retain];
373   if (FRAME_VISIBLE_P (f))
374     {
375       x_update_cursor (f, 0);
376       x_update_cursor (f, 1);
377     }
378   update_face_from_frame_parameter (f, Qcursor_color, arg);
382 static void
383 x_set_icon_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
385   NSView *view = FRAME_NS_VIEW (f);
386   NSTRACE (x_set_icon_name);
388   /* see if it's changed */
389   if (STRINGP (arg))
390     {
391       if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
392         return;
393     }
394   else if (!STRINGP (oldval) && EQ (oldval, Qnil) == EQ (arg, Qnil))
395     return;
397   fset_icon_name (f, arg);
399   if (NILP (arg))
400     {
401       if (!NILP (f->title))
402         arg = f->title;
403       else
404         /* Explicit name and no icon-name -> explicit_name.  */
405         if (f->explicit_name)
406           arg = f->name;
407         else
408           {
409             /* No explicit name and no icon-name ->
410                name has to be rebuild from icon_title_format.  */
411             windows_or_buffers_changed = 62;
412             return;
413           }
414     }
416   /* Don't change the name if it's already NAME.  */
417   if ([[view window] miniwindowTitle]
418       && ([[[view window] miniwindowTitle]
419              isEqualToString: [NSString stringWithUTF8String:
420                                           SSDATA (arg)]]))
421     return;
423   [[view window] setMiniwindowTitle:
424         [NSString stringWithUTF8String: SSDATA (arg)]];
427 static void
428 ns_set_name_internal (struct frame *f, Lisp_Object name)
430   struct gcpro gcpro1;
431   Lisp_Object encoded_name, encoded_icon_name;
432   NSString *str;
433   NSView *view = FRAME_NS_VIEW (f);
435   GCPRO1 (name);
436   encoded_name = ENCODE_UTF_8 (name);
437   UNGCPRO;
439   str = [NSString stringWithUTF8String: SSDATA (encoded_name)];
441   /* Don't change the name if it's already NAME.  */
442   if (! [[[view window] title] isEqualToString: str])
443     [[view window] setTitle: str];
445   if (!STRINGP (f->icon_name))
446     encoded_icon_name = encoded_name;
447   else
448     encoded_icon_name = ENCODE_UTF_8 (f->icon_name);
450   str = [NSString stringWithUTF8String: SSDATA (encoded_icon_name)];
452   if ([[view window] miniwindowTitle]
453       && ! [[[view window] miniwindowTitle] isEqualToString: str])
454     [[view window] setMiniwindowTitle: str];
458 static void
459 ns_set_name (struct frame *f, Lisp_Object name, int explicit)
461   NSTRACE (ns_set_name);
463   /* Make sure that requests from lisp code override requests from
464      Emacs redisplay code.  */
465   if (explicit)
466     {
467       /* If we're switching from explicit to implicit, we had better
468          update the mode lines and thereby update the title.  */
469       if (f->explicit_name && NILP (name))
470         update_mode_lines = 21;
472       f->explicit_name = ! NILP (name);
473     }
474   else if (f->explicit_name)
475     return;
477   if (NILP (name))
478     name = build_string ([ns_app_name UTF8String]);
479   else
480     CHECK_STRING (name);
482   /* Don't change the name if it's already NAME.  */
483   if (! NILP (Fstring_equal (name, f->name)))
484     return;
486   fset_name (f, name);
488   /* Title overrides explicit name.  */
489   if (! NILP (f->title))
490     name = f->title;
492   ns_set_name_internal (f, name);
496 /* This function should be called when the user's lisp code has
497    specified a name for the frame; the name will override any set by the
498    redisplay code.  */
499 static void
500 x_explicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
502   NSTRACE (x_explicitly_set_name);
503   ns_set_name (f, arg, 1);
507 /* This function should be called by Emacs redisplay code to set the
508    name; names set this way will never override names set by the user's
509    lisp code.  */
510 void
511 x_implicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
513   NSTRACE (x_implicitly_set_name);
515   /* Deal with NS specific format t.  */
516   if (FRAME_NS_P (f) && ((FRAME_ICONIFIED_P (f) && EQ (Vicon_title_format, Qt))
517                          || EQ (Vframe_title_format, Qt)))
518     ns_set_name_as_filename (f);
519   else
520     ns_set_name (f, arg, 0);
524 /* Change the title of frame F to NAME.
525    If NAME is nil, use the frame name as the title.  */
527 static void
528 x_set_title (struct frame *f, Lisp_Object name, Lisp_Object old_name)
530   NSTRACE (x_set_title);
531   /* Don't change the title if it's already NAME.  */
532   if (EQ (name, f->title))
533     return;
535   update_mode_lines = 22;
537   fset_title (f, name);
539   if (NILP (name))
540     name = f->name;
541   else
542     CHECK_STRING (name);
544   ns_set_name_internal (f, name);
548 void
549 ns_set_name_as_filename (struct frame *f)
551   NSView *view;
552   Lisp_Object name, filename;
553   Lisp_Object buf = XWINDOW (f->selected_window)->contents;
554   const char *title;
555   NSAutoreleasePool *pool;
556   struct gcpro gcpro1;
557   Lisp_Object encoded_name, encoded_filename;
558   NSString *str;
559   NSTRACE (ns_set_name_as_filename);
561   if (f->explicit_name || ! NILP (f->title))
562     return;
564   block_input ();
565   pool = [[NSAutoreleasePool alloc] init];
566   filename = BVAR (XBUFFER (buf), filename);
567   name = BVAR (XBUFFER (buf), name);
569   if (NILP (name))
570     {
571       if (! NILP (filename))
572         name = Ffile_name_nondirectory (filename);
573       else
574         name = build_string ([ns_app_name UTF8String]);
575     }
577   GCPRO1 (name);
578   encoded_name = ENCODE_UTF_8 (name);
579   UNGCPRO;
581   view = FRAME_NS_VIEW (f);
583   title = FRAME_ICONIFIED_P (f) ? [[[view window] miniwindowTitle] UTF8String]
584                                 : [[[view window] title] UTF8String];
586   if (title && (! strcmp (title, SSDATA (encoded_name))))
587     {
588       [pool release];
589       unblock_input ();
590       return;
591     }
593   str = [NSString stringWithUTF8String: SSDATA (encoded_name)];
594   if (str == nil) str = @"Bad coding";
596   if (FRAME_ICONIFIED_P (f))
597     [[view window] setMiniwindowTitle: str];
598   else
599     {
600       NSString *fstr;
602       if (! NILP (filename))
603         {
604           GCPRO1 (filename);
605           encoded_filename = ENCODE_UTF_8 (filename);
606           UNGCPRO;
608           fstr = [NSString stringWithUTF8String: SSDATA (encoded_filename)];
609           if (fstr == nil) fstr = @"";
610 #ifdef NS_IMPL_COCOA
611           /* work around a bug observed on 10.3 and later where
612              setTitleWithRepresentedFilename does not clear out previous state
613              if given filename does not exist */
614           if (! [[NSFileManager defaultManager] fileExistsAtPath: fstr])
615             [[view window] setRepresentedFilename: @""];
616 #endif
617         }
618       else
619         fstr = @"";
621       [[view window] setRepresentedFilename: fstr];
622       [[view window] setTitle: str];
623       fset_name (f, name);
624     }
626   [pool release];
627   unblock_input ();
631 void
632 ns_set_doc_edited (void)
634   NSAutoreleasePool *pool;
635   Lisp_Object tail, frame;
636   block_input ();
637   pool = [[NSAutoreleasePool alloc] init];
638   FOR_EACH_FRAME (tail, frame)
639     {
640       BOOL edited = NO;
641       struct frame *f = XFRAME (frame);
642       struct window *w = XWINDOW (FRAME_SELECTED_WINDOW (f));
643       NSView *view = FRAME_NS_VIEW (f);
644       if (!MINI_WINDOW_P (w))
645         edited = ! NILP (Fbuffer_modified_p (w->contents)) &&
646           ! NILP (Fbuffer_file_name (w->contents));
647       [[view window] setDocumentEdited: edited];
648     }
650   [pool release];
651   unblock_input ();
655 void
656 x_set_menu_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
658   int nlines;
659   if (FRAME_MINIBUF_ONLY_P (f))
660     return;
662   if (TYPE_RANGED_INTEGERP (int, value))
663     nlines = XINT (value);
664   else
665     nlines = 0;
667   FRAME_MENU_BAR_LINES (f) = 0;
668   if (nlines)
669     {
670       FRAME_EXTERNAL_MENU_BAR (f) = 1;
671       /* does for all frames, whereas we just want for one frame
672          [NSMenu setMenuBarVisible: YES]; */
673     }
674   else
675     {
676       if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
677         free_frame_menubar (f);
678       /*      [NSMenu setMenuBarVisible: NO]; */
679       FRAME_EXTERNAL_MENU_BAR (f) = 0;
680     }
684 /* toolbar support */
685 void
686 x_set_tool_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
688   int nlines;
690   if (FRAME_MINIBUF_ONLY_P (f))
691     return;
693   if (RANGED_INTEGERP (0, value, INT_MAX))
694     nlines = XFASTINT (value);
695   else
696     nlines = 0;
698   if (nlines)
699     {
700       FRAME_EXTERNAL_TOOL_BAR (f) = 1;
701       update_frame_tool_bar (f);
702     }
703   else
704     {
705       if (FRAME_EXTERNAL_TOOL_BAR (f))
706         {
707           free_frame_tool_bar (f);
708           FRAME_EXTERNAL_TOOL_BAR (f) = 0;
709         }
710     }
712   x_set_window_size (f, 0, f->text_cols, f->text_lines, 0);
716 void
717 x_set_internal_border_width (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
719   int old_width = FRAME_INTERNAL_BORDER_WIDTH (f);
721   CHECK_TYPE_RANGED_INTEGER (int, arg);
722   FRAME_INTERNAL_BORDER_WIDTH (f) = XINT (arg);
723   if (FRAME_INTERNAL_BORDER_WIDTH (f) < 0)
724     FRAME_INTERNAL_BORDER_WIDTH (f) = 0;
726   if (FRAME_INTERNAL_BORDER_WIDTH (f) == old_width)
727     return;
729   if (FRAME_X_WINDOW (f) != 0)
730     adjust_frame_size (f, -1, -1, 3, 0);
732   SET_FRAME_GARBAGED (f);
736 static void
737 ns_implicitly_set_icon_type (struct frame *f)
739   Lisp_Object tem;
740   EmacsView *view = FRAME_NS_VIEW (f);
741   id image = nil;
742   Lisp_Object chain, elt;
743   NSAutoreleasePool *pool;
744   BOOL setMini = YES;
746   NSTRACE (ns_implicitly_set_icon_type);
748   block_input ();
749   pool = [[NSAutoreleasePool alloc] init];
750   if (f->output_data.ns->miniimage
751       && [[NSString stringWithUTF8String: SSDATA (f->name)]
752                isEqualToString: [(NSImage *)f->output_data.ns->miniimage name]])
753     {
754       [pool release];
755       unblock_input ();
756       return;
757     }
759   tem = assq_no_quit (Qicon_type, f->param_alist);
760   if (CONSP (tem) && ! NILP (XCDR (tem)))
761     {
762       [pool release];
763       unblock_input ();
764       return;
765     }
767   for (chain = Vns_icon_type_alist;
768        image == nil && CONSP (chain);
769        chain = XCDR (chain))
770     {
771       elt = XCAR (chain);
772       /* special case: 't' means go by file type */
773       if (SYMBOLP (elt) && EQ (elt, Qt) && SSDATA (f->name)[0] == '/')
774         {
775           NSString *str
776              = [NSString stringWithUTF8String: SSDATA (f->name)];
777           if ([[NSFileManager defaultManager] fileExistsAtPath: str])
778             image = [[[NSWorkspace sharedWorkspace] iconForFile: str] retain];
779         }
780       else if (CONSP (elt) &&
781                STRINGP (XCAR (elt)) &&
782                STRINGP (XCDR (elt)) &&
783                fast_string_match (XCAR (elt), f->name) >= 0)
784         {
785           image = [EmacsImage allocInitFromFile: XCDR (elt)];
786           if (image == nil)
787             image = [[NSImage imageNamed:
788                                [NSString stringWithUTF8String:
789                                             SSDATA (XCDR (elt))]] retain];
790         }
791     }
793   if (image == nil)
794     {
795       image = [[[NSWorkspace sharedWorkspace] iconForFileType: @"text"] retain];
796       setMini = NO;
797     }
799   [f->output_data.ns->miniimage release];
800   f->output_data.ns->miniimage = image;
801   [view setMiniwindowImage: setMini];
802   [pool release];
803   unblock_input ();
807 static void
808 x_set_icon_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
810   EmacsView *view = FRAME_NS_VIEW (f);
811   id image = nil;
812   BOOL setMini = YES;
814   NSTRACE (x_set_icon_type);
816   if (!NILP (arg) && SYMBOLP (arg))
817     {
818       arg =build_string (SSDATA (SYMBOL_NAME (arg)));
819       store_frame_param (f, Qicon_type, arg);
820     }
822   /* do it the implicit way */
823   if (NILP (arg))
824     {
825       ns_implicitly_set_icon_type (f);
826       return;
827     }
829   CHECK_STRING (arg);
831   image = [EmacsImage allocInitFromFile: arg];
832   if (image == nil)
833     image =[NSImage imageNamed: [NSString stringWithUTF8String:
834                                             SSDATA (arg)]];
836   if (image == nil)
837     {
838       image = [NSImage imageNamed: @"text"];
839       setMini = NO;
840     }
842   f->output_data.ns->miniimage = image;
843   [view setMiniwindowImage: setMini];
847 /* TODO: move to nsterm? */
849 ns_lisp_to_cursor_type (Lisp_Object arg)
851   char *str;
852   if (XTYPE (arg) == Lisp_String)
853     str = SSDATA (arg);
854   else if (XTYPE (arg) == Lisp_Symbol)
855     str = SSDATA (SYMBOL_NAME (arg));
856   else return -1;
857   if (!strcmp (str, "box"))     return FILLED_BOX_CURSOR;
858   if (!strcmp (str, "hollow"))  return HOLLOW_BOX_CURSOR;
859   if (!strcmp (str, "hbar"))    return HBAR_CURSOR;
860   if (!strcmp (str, "bar"))     return BAR_CURSOR;
861   if (!strcmp (str, "no"))      return NO_CURSOR;
862   return -1;
866 Lisp_Object
867 ns_cursor_type_to_lisp (int arg)
869   switch (arg)
870     {
871     case FILLED_BOX_CURSOR: return Qbox;
872     case HOLLOW_BOX_CURSOR: return intern ("hollow");
873     case HBAR_CURSOR:       return intern ("hbar");
874     case BAR_CURSOR:        return intern ("bar");
875     case NO_CURSOR:
876     default:                return intern ("no");
877     }
880 /* This is the same as the xfns.c definition.  */
881 static void
882 x_set_cursor_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
884   set_frame_cursor_types (f, arg);
887 /* called to set mouse pointer color, but all other terms use it to
888    initialize pointer types (and don't set the color ;) */
889 static void
890 x_set_mouse_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
892   /* don't think we can do this on Nextstep */
896 #define Str(x) #x
897 #define Xstr(x) Str(x)
899 static Lisp_Object
900 ns_appkit_version_str (void)
902   char tmp[256];
904 #ifdef NS_IMPL_GNUSTEP
905   sprintf(tmp, "gnustep-gui-%s", Xstr(GNUSTEP_GUI_VERSION));
906 #elif defined (NS_IMPL_COCOA)
907   NSString *osversion
908     = [[NSProcessInfo processInfo] operatingSystemVersionString];
909   sprintf(tmp, "appkit-%.2f %s",
910           NSAppKitVersionNumber,
911           [osversion UTF8String]);
912 #else
913   tmp = "ns-unknown";
914 #endif
915   return build_string (tmp);
919 /* This is for use by x-server-version and collapses all version info we
920    have into a single int.  For a better picture of the implementation
921    running, use ns_appkit_version_str.*/
922 static int
923 ns_appkit_version_int (void)
925 #ifdef NS_IMPL_GNUSTEP
926   return GNUSTEP_GUI_MAJOR_VERSION * 100 + GNUSTEP_GUI_MINOR_VERSION;
927 #elif defined (NS_IMPL_COCOA)
928   return (int)NSAppKitVersionNumber;
929 #endif
930   return 0;
934 static void
935 x_icon (struct frame *f, Lisp_Object parms)
936 /* --------------------------------------------------------------------------
937    Strangely-named function to set icon position parameters in frame.
938    This is irrelevant under OS X, but might be needed under GNUstep,
939    depending on the window manager used.  Note, this is not a standard
940    frame parameter-setter; it is called directly from x-create-frame.
941    -------------------------------------------------------------------------- */
943   Lisp_Object icon_x, icon_y;
944   struct ns_display_info *dpyinfo = check_ns_display_info (Qnil);
946   f->output_data.ns->icon_top = -1;
947   f->output_data.ns->icon_left = -1;
949   /* Set the position of the icon.  */
950   icon_x = x_get_arg (dpyinfo, parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
951   icon_y = x_get_arg (dpyinfo, parms, Qicon_top, 0, 0,  RES_TYPE_NUMBER);
952   if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
953     {
954       CHECK_NUMBER (icon_x);
955       CHECK_NUMBER (icon_y);
956       f->output_data.ns->icon_top = XINT (icon_y);
957       f->output_data.ns->icon_left = XINT (icon_x);
958     }
959   else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
960     error ("Both left and top icon corners of icon must be specified");
964 /* Note: see frame.c for template, also where generic functions are impl */
965 frame_parm_handler ns_frame_parm_handlers[] =
967   x_set_autoraise, /* generic OK */
968   x_set_autolower, /* generic OK */
969   x_set_background_color,
970   0, /* x_set_border_color,  may be impossible under Nextstep */
971   0, /* x_set_border_width,  may be impossible under Nextstep */
972   x_set_cursor_color,
973   x_set_cursor_type,
974   x_set_font, /* generic OK */
975   x_set_foreground_color,
976   x_set_icon_name,
977   x_set_icon_type,
978   x_set_internal_border_width, /* generic OK */
979   0, /* x_set_right_divider_width */
980   0, /* x_set_bottom_divider_width */
981   x_set_menu_bar_lines,
982   x_set_mouse_color,
983   x_explicitly_set_name,
984   x_set_scroll_bar_width, /* generic OK */
985   x_set_scroll_bar_height, /* generic OK */
986   x_set_title,
987   x_set_unsplittable, /* generic OK */
988   x_set_vertical_scroll_bars, /* generic OK */
989   x_set_horizontal_scroll_bars, /* generic OK */
990   x_set_visibility, /* generic OK */
991   x_set_tool_bar_lines,
992   0, /* x_set_scroll_bar_foreground, will ignore (not possible on NS) */
993   0, /* x_set_scroll_bar_background,  will ignore (not possible on NS) */
994   x_set_screen_gamma, /* generic OK */
995   x_set_line_spacing, /* generic OK, sets f->extra_line_spacing to int */
996   x_set_left_fringe, /* generic OK */
997   x_set_right_fringe, /* generic OK */
998   0, /* x_set_wait_for_wm, will ignore */
999   x_set_fullscreen, /* generic OK */
1000   x_set_font_backend, /* generic OK */
1001   x_set_alpha,
1002   0, /* x_set_sticky */
1003   0, /* x_set_tool_bar_position */
1007 /* Handler for signals raised during x_create_frame.
1008    FRAME is the frame which is partially constructed.  */
1010 static void
1011 unwind_create_frame (Lisp_Object frame)
1013   struct frame *f = XFRAME (frame);
1015   /* If frame is already dead, nothing to do.  This can happen if the
1016      display is disconnected after the frame has become official, but
1017      before x_create_frame removes the unwind protect.  */
1018   if (!FRAME_LIVE_P (f))
1019     return;
1021   /* If frame is ``official'', nothing to do.  */
1022   if (NILP (Fmemq (frame, Vframe_list)))
1023     {
1024 #if defined GLYPH_DEBUG && defined ENABLE_CHECKING
1025       struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1026 #endif
1028       x_free_frame_resources (f);
1029       free_glyphs (f);
1031 #ifdef GLYPH_DEBUG
1032       /* Check that reference counts are indeed correct.  */
1033       eassert (dpyinfo->terminal->image_cache->refcount == image_cache_refcount);
1034 #endif
1035     }
1039  * Read geometry related parameters from preferences if not in PARMS.
1040  * Returns the union of parms and any preferences read.
1041  */
1043 static Lisp_Object
1044 get_geometry_from_preferences (struct ns_display_info *dpyinfo,
1045                                Lisp_Object parms)
1047   struct {
1048     const char *val;
1049     const char *cls;
1050     Lisp_Object tem;
1051   } r[] = {
1052     { "width",  "Width", Qwidth },
1053     { "height", "Height", Qheight },
1054     { "left", "Left", Qleft },
1055     { "top", "Top", Qtop },
1056   };
1058   int i;
1059   for (i = 0; i < ARRAYELTS (r); ++i)
1060     {
1061       if (NILP (Fassq (r[i].tem, parms)))
1062         {
1063           Lisp_Object value
1064             = x_get_arg (dpyinfo, parms, r[i].tem, r[i].val, r[i].cls,
1065                          RES_TYPE_NUMBER);
1066           if (! EQ (value, Qunbound))
1067             parms = Fcons (Fcons (r[i].tem, value), parms);
1068         }
1069     }
1071   return parms;
1074 /* ==========================================================================
1076     Lisp definitions
1078    ========================================================================== */
1080 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
1081        1, 1, 0,
1082        doc: /* Make a new Nextstep window, called a "frame" in Emacs terms.
1083 Return an Emacs frame object.
1084 PARMS is an alist of frame parameters.
1085 If the parameters specify that the frame should not have a minibuffer,
1086 and do not specify a specific minibuffer window to use,
1087 then `default-minibuffer-frame' must be a frame whose minibuffer can
1088 be shared by the new frame.
1090 This function is an internal primitive--use `make-frame' instead.  */)
1091      (Lisp_Object parms)
1093   struct frame *f;
1094   Lisp_Object frame, tem;
1095   Lisp_Object name;
1096   int minibuffer_only = 0;
1097   long window_prompting = 0;
1098   int width, height;
1099   ptrdiff_t count = specpdl_ptr - specpdl;
1100   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1101   Lisp_Object display;
1102   struct ns_display_info *dpyinfo = NULL;
1103   Lisp_Object parent;
1104   struct kboard *kb;
1105   static int desc_ctr = 1;
1107   /* x_get_arg modifies parms.  */
1108   parms = Fcopy_alist (parms);
1110   /* Use this general default value to start with
1111      until we know if this frame has a specified name.  */
1112   Vx_resource_name = Vinvocation_name;
1114   display = x_get_arg (dpyinfo, parms, Qterminal, 0, 0, RES_TYPE_STRING);
1115   if (EQ (display, Qunbound))
1116     display = Qnil;
1117   dpyinfo = check_ns_display_info (display);
1118   kb = dpyinfo->terminal->kboard;
1120   if (!dpyinfo->terminal->name)
1121     error ("Terminal is not live, can't create new frames on it");
1123   name = x_get_arg (dpyinfo, parms, Qname, 0, 0, RES_TYPE_STRING);
1124   if (!STRINGP (name)
1125       && ! EQ (name, Qunbound)
1126       && ! NILP (name))
1127     error ("Invalid frame name--not a string or nil");
1129   if (STRINGP (name))
1130     Vx_resource_name = name;
1132   parent = x_get_arg (dpyinfo, parms, Qparent_id, 0, 0, RES_TYPE_NUMBER);
1133   if (EQ (parent, Qunbound))
1134     parent = Qnil;
1135   if (! NILP (parent))
1136     CHECK_NUMBER (parent);
1138   /* make_frame_without_minibuffer can run Lisp code and garbage collect.  */
1139   /* No need to protect DISPLAY because that's not used after passing
1140      it to make_frame_without_minibuffer.  */
1141   frame = Qnil;
1142   GCPRO4 (parms, parent, name, frame);
1143   tem = x_get_arg (dpyinfo, parms, Qminibuffer, "minibuffer", "Minibuffer",
1144                   RES_TYPE_SYMBOL);
1145   if (EQ (tem, Qnone) || NILP (tem))
1146       f = make_frame_without_minibuffer (Qnil, kb, display);
1147   else if (EQ (tem, Qonly))
1148     {
1149       f = make_minibuffer_frame ();
1150       minibuffer_only = 1;
1151     }
1152   else if (WINDOWP (tem))
1153       f = make_frame_without_minibuffer (tem, kb, display);
1154   else
1155       f = make_frame (1);
1157   XSETFRAME (frame, f);
1159   f->terminal = dpyinfo->terminal;
1161   f->output_method = output_ns;
1162   f->output_data.ns = xzalloc (sizeof *f->output_data.ns);
1164   FRAME_FONTSET (f) = -1;
1166   fset_icon_name (f, x_get_arg (dpyinfo, parms, Qicon_name,
1167                                 "iconName", "Title",
1168                                 RES_TYPE_STRING));
1169   if (! STRINGP (f->icon_name))
1170     fset_icon_name (f, Qnil);
1172   FRAME_DISPLAY_INFO (f) = dpyinfo;
1174   /* With FRAME_DISPLAY_INFO set up, this unwind-protect is safe.  */
1175   record_unwind_protect (unwind_create_frame, frame);
1177   f->output_data.ns->window_desc = desc_ctr++;
1178   if (TYPE_RANGED_INTEGERP (Window, parent))
1179     {
1180       f->output_data.ns->parent_desc = XFASTINT (parent);
1181       f->output_data.ns->explicit_parent = 1;
1182     }
1183   else
1184     {
1185       f->output_data.ns->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
1186       f->output_data.ns->explicit_parent = 0;
1187     }
1189   /* Set the name; the functions to which we pass f expect the name to
1190      be set.  */
1191   if (EQ (name, Qunbound) || NILP (name) || ! STRINGP (name))
1192     {
1193       fset_name (f, build_string ([ns_app_name UTF8String]));
1194       f->explicit_name = 0;
1195     }
1196   else
1197     {
1198       fset_name (f, name);
1199       f->explicit_name = 1;
1200       specbind (Qx_resource_name, name);
1201     }
1203   block_input ();
1205 #ifdef NS_IMPL_COCOA
1206     mac_register_font_driver (f);
1207 #else
1208     register_font_driver (&nsfont_driver, f);
1209 #endif
1211   x_default_parameter (f, parms, Qfont_backend, Qnil,
1212                         "fontBackend", "FontBackend", RES_TYPE_STRING);
1214   {
1215     /* use for default font name */
1216     id font = [NSFont userFixedPitchFontOfSize: -1.0]; /* default */
1217     x_default_parameter (f, parms, Qfontsize,
1218                                     make_number (0 /*(int)[font pointSize]*/),
1219                                     "fontSize", "FontSize", RES_TYPE_NUMBER);
1220     // Remove ' Regular', not handled by backends.
1221     char *fontname = xstrdup ([[font displayName] UTF8String]);
1222     int len = strlen (fontname);
1223     if (len > 8 && strcmp (fontname + len - 8, " Regular") == 0)
1224       fontname[len-8] = '\0';
1225     x_default_parameter (f, parms, Qfont,
1226                                  build_string (fontname),
1227                                  "font", "Font", RES_TYPE_STRING);
1228     xfree (fontname);
1229   }
1230   unblock_input ();
1232   x_default_parameter (f, parms, Qborder_width, make_number (0),
1233                        "borderwidth", "BorderWidth", RES_TYPE_NUMBER);
1234   x_default_parameter (f, parms, Qinternal_border_width, make_number (2),
1235                       "internalBorderWidth", "InternalBorderWidth",
1236                       RES_TYPE_NUMBER);
1238   /* default vertical scrollbars on right on Mac */
1239   {
1240       Lisp_Object spos
1241 #ifdef NS_IMPL_GNUSTEP
1242           = Qt;
1243 #else
1244           = Qright;
1245 #endif
1246       x_default_parameter (f, parms, Qvertical_scroll_bars, spos,
1247                            "verticalScrollBars", "VerticalScrollBars",
1248                            RES_TYPE_SYMBOL);
1249   }
1250   x_default_parameter (f, parms, Qhorizontal_scroll_bars, Qnil,
1251                        "horizontalScrollBars", "HorizontalScrollBars",
1252                        RES_TYPE_SYMBOL);
1253   x_default_parameter (f, parms, Qforeground_color, build_string ("Black"),
1254                       "foreground", "Foreground", RES_TYPE_STRING);
1255   x_default_parameter (f, parms, Qbackground_color, build_string ("White"),
1256                       "background", "Background", RES_TYPE_STRING);
1257   /* FIXME: not supported yet in Nextstep */
1258   x_default_parameter (f, parms, Qline_spacing, Qnil,
1259                        "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
1260   x_default_parameter (f, parms, Qleft_fringe, Qnil,
1261                        "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
1262   x_default_parameter (f, parms, Qright_fringe, Qnil,
1263                        "rightFringe", "RightFringe", RES_TYPE_NUMBER);
1265 #ifdef GLYPH_DEBUG
1266   image_cache_refcount =
1267     FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
1268 #endif
1270   init_frame_faces (f);
1272   /* Read comment about this code in corresponding place in xfns.c.  */
1273   adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
1274                      FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 5, 1);
1276   /* The resources controlling the menu-bar and tool-bar are
1277      processed specially at startup, and reflected in the mode
1278      variables; ignore them here.  */
1279   x_default_parameter (f, parms, Qmenu_bar_lines,
1280                        NILP (Vmenu_bar_mode)
1281                        ? make_number (0) : make_number (1),
1282                        NULL, NULL, RES_TYPE_NUMBER);
1283   x_default_parameter (f, parms, Qtool_bar_lines,
1284                        NILP (Vtool_bar_mode)
1285                        ? make_number (0) : make_number (1),
1286                        NULL, NULL, RES_TYPE_NUMBER);
1288   x_default_parameter (f, parms, Qbuffer_predicate, Qnil, "bufferPredicate",
1289                        "BufferPredicate", RES_TYPE_SYMBOL);
1290   x_default_parameter (f, parms, Qtitle, Qnil, "title", "Title",
1291                        RES_TYPE_STRING);
1293   parms = get_geometry_from_preferences (dpyinfo, parms);
1294   window_prompting = x_figure_window_size (f, parms, 1);
1296   tem = x_get_arg (dpyinfo, parms, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
1297   f->no_split = minibuffer_only || (!EQ (tem, Qunbound) && !EQ (tem, Qnil));
1299   /* NOTE: on other terms, this is done in set_mouse_color, however this
1300      was not getting called under Nextstep */
1301   f->output_data.ns->text_cursor = [NSCursor IBeamCursor];
1302   f->output_data.ns->nontext_cursor = [NSCursor arrowCursor];
1303   f->output_data.ns->modeline_cursor = [NSCursor pointingHandCursor];
1304   f->output_data.ns->hand_cursor = [NSCursor pointingHandCursor];
1305   f->output_data.ns->hourglass_cursor = [NSCursor disappearingItemCursor];
1306   f->output_data.ns->horizontal_drag_cursor = [NSCursor resizeLeftRightCursor];
1307   f->output_data.ns->vertical_drag_cursor = [NSCursor resizeUpDownCursor];
1308   FRAME_DISPLAY_INFO (f)->vertical_scroll_bar_cursor
1309      = [NSCursor arrowCursor];
1310   FRAME_DISPLAY_INFO (f)->horizontal_scroll_bar_cursor
1311      = [NSCursor arrowCursor];
1312   f->output_data.ns->current_pointer = f->output_data.ns->text_cursor;
1314   [[EmacsView alloc] initFrameFromEmacs: f];
1316   x_icon (f, parms);
1318   /* ns_display_info does not have a reference_count.  */
1319   f->terminal->reference_count++;
1321   /* It is now ok to make the frame official even if we get an error below.
1322      The frame needs to be on Vframe_list or making it visible won't work. */
1323   Vframe_list = Fcons (frame, Vframe_list);
1325   x_default_parameter (f, parms, Qicon_type, Qnil,
1326                        "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
1328   x_default_parameter (f, parms, Qauto_raise, Qnil,
1329                        "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
1330   x_default_parameter (f, parms, Qauto_lower, Qnil,
1331                        "autoLower", "AutoLower", RES_TYPE_BOOLEAN);
1332   x_default_parameter (f, parms, Qcursor_type, Qbox,
1333                        "cursorType", "CursorType", RES_TYPE_SYMBOL);
1334   x_default_parameter (f, parms, Qscroll_bar_width, Qnil,
1335                        "scrollBarWidth", "ScrollBarWidth",
1336                        RES_TYPE_NUMBER);
1337   x_default_parameter (f, parms, Qscroll_bar_height, Qnil,
1338                        "scrollBarHeight", "ScrollBarHeight",
1339                        RES_TYPE_NUMBER);
1340   x_default_parameter (f, parms, Qalpha, Qnil,
1341                        "alpha", "Alpha", RES_TYPE_NUMBER);
1342   x_default_parameter (f, parms, Qfullscreen, Qnil,
1343                        "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
1345   /* Consider frame official, now.  */
1346   f->official = true;
1348   adjust_frame_size (f, FRAME_TEXT_WIDTH (f), FRAME_TEXT_HEIGHT (f), 0, 1);
1350   if (! f->output_data.ns->explicit_parent)
1351     {
1352       Lisp_Object visibility;
1354       visibility = x_get_arg (dpyinfo, parms, Qvisibility, 0, 0,
1355                               RES_TYPE_SYMBOL);
1356       if (EQ (visibility, Qunbound))
1357         visibility = Qt;
1359       if (EQ (visibility, Qicon))
1360         x_iconify_frame (f);
1361       else if (! NILP (visibility))
1362         {
1363           x_make_frame_visible (f);
1364           [[FRAME_NS_VIEW (f) window] makeKeyWindow];
1365         }
1366       else
1367         {
1368           /* Must have been Qnil.  */
1369         }
1370     }
1372   if (FRAME_HAS_MINIBUF_P (f)
1373       && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
1374           || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
1375     kset_default_minibuffer_frame (kb, frame);
1377   /* All remaining specified parameters, which have not been "used"
1378      by x_get_arg and friends, now go in the misc. alist of the frame.  */
1379   for (tem = parms; CONSP (tem); tem = XCDR (tem))
1380     if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
1381       fset_param_alist (f, Fcons (XCAR (tem), f->param_alist));
1383   UNGCPRO;
1385   if (window_prompting & USPosition)
1386     x_set_offset (f, f->left_pos, f->top_pos, 1);
1388   /* Make sure windows on this frame appear in calls to next-window
1389      and similar functions.  */
1390   Vwindow_list = Qnil;
1392   return unbind_to (count, frame);
1395 void
1396 x_focus_frame (struct frame *f)
1398   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1400   if (dpyinfo->x_focus_frame != f)
1401     {
1402       EmacsView *view = FRAME_NS_VIEW (f);
1403       block_input ();
1404       [NSApp activateIgnoringOtherApps: YES];
1405       [[view window] makeKeyAndOrderFront: view];
1406       unblock_input ();
1407     }
1411 DEFUN ("ns-popup-font-panel", Fns_popup_font_panel, Sns_popup_font_panel,
1412        0, 1, "",
1413        doc: /* Pop up the font panel. */)
1414      (Lisp_Object frame)
1416   struct frame *f = decode_window_system_frame (frame);
1417   id fm = [NSFontManager sharedFontManager];
1418   struct font *font = f->output_data.ns->font;
1419   NSFont *nsfont;
1420 #ifdef NS_IMPL_GNUSTEP
1421   nsfont = ((struct nsfont_info *)font)->nsfont;
1422 #endif
1423 #ifdef NS_IMPL_COCOA
1424   nsfont = (NSFont *) macfont_get_nsctfont (font);
1425 #endif
1426   [fm setSelectedFont: nsfont isMultiple: NO];
1427   [fm orderFrontFontPanel: NSApp];
1428   return Qnil;
1432 DEFUN ("ns-popup-color-panel", Fns_popup_color_panel, Sns_popup_color_panel,
1433        0, 1, "",
1434        doc: /* Pop up the color panel.  */)
1435      (Lisp_Object frame)
1437   check_window_system (NULL);
1438   [NSApp orderFrontColorPanel: NSApp];
1439   return Qnil;
1442 static struct
1444   id panel;
1445   BOOL ret;
1446 #ifdef NS_IMPL_GNUSTEP
1447   NSString *dirS, *initS;
1448   BOOL no_types;
1449 #endif
1450 } ns_fd_data;
1452 void
1453 ns_run_file_dialog (void)
1455   if (ns_fd_data.panel == nil) return;
1456 #ifdef NS_IMPL_COCOA
1457   ns_fd_data.ret = [ns_fd_data.panel runModal];
1458 #else
1459   if (ns_fd_data.no_types)
1460     {
1461       ns_fd_data.ret = [ns_fd_data.panel
1462                            runModalForDirectory: ns_fd_data.dirS
1463                            file: ns_fd_data.initS];
1464     }
1465   else
1466     {
1467       ns_fd_data.ret = [ns_fd_data.panel
1468                            runModalForDirectory: ns_fd_data.dirS
1469                            file: ns_fd_data.initS
1470                            types: nil];
1471     }
1472 #endif
1473   ns_fd_data.panel = nil;
1476 DEFUN ("ns-read-file-name", Fns_read_file_name, Sns_read_file_name, 1, 5, 0,
1477        doc: /* Use a graphical panel to read a file name, using prompt PROMPT.
1478 Optional arg DIR, if non-nil, supplies a default directory.
1479 Optional arg MUSTMATCH, if non-nil, means the returned file or
1480 directory must exist.
1481 Optional arg INIT, if non-nil, provides a default file name to use.
1482 Optional arg DIR_ONLY_P, if non-nil, means choose only directories.  */)
1483   (Lisp_Object prompt, Lisp_Object dir, Lisp_Object mustmatch,
1484    Lisp_Object init, Lisp_Object dir_only_p)
1486   static id fileDelegate = nil;
1487   BOOL ret;
1488   BOOL isSave = NILP (mustmatch) && NILP (dir_only_p);
1489   id panel;
1490   Lisp_Object fname;
1492   NSString *promptS = NILP (prompt) || !STRINGP (prompt) ? nil :
1493     [NSString stringWithUTF8String: SSDATA (prompt)];
1494   NSString *dirS = NILP (dir) || !STRINGP (dir) ?
1495     [NSString stringWithUTF8String: SSDATA (BVAR (current_buffer, directory))] :
1496     [NSString stringWithUTF8String: SSDATA (dir)];
1497   NSString *initS = NILP (init) || !STRINGP (init) ? nil :
1498     [NSString stringWithUTF8String: SSDATA (init)];
1499   NSEvent *nxev;
1501   check_window_system (NULL);
1503   if (fileDelegate == nil)
1504     fileDelegate = [EmacsFileDelegate new];
1506   [NSCursor setHiddenUntilMouseMoves: NO];
1508   if ([dirS characterAtIndex: 0] == '~')
1509     dirS = [dirS stringByExpandingTildeInPath];
1511   panel = isSave ?
1512     (id)[EmacsSavePanel savePanel] : (id)[EmacsOpenPanel openPanel];
1514   [panel setTitle: promptS];
1516   [panel setAllowsOtherFileTypes: YES];
1517   [panel setTreatsFilePackagesAsDirectories: YES];
1518   [panel setDelegate: fileDelegate];
1520   if (! NILP (dir_only_p))
1521     {
1522       [panel setCanChooseDirectories: YES];
1523       [panel setCanChooseFiles: NO];
1524     }
1525   else if (! isSave)
1526     {
1527       /* This is not quite what the documentation says, but it is compatible
1528          with the Gtk+ code.  Also, the menu entry says "Open File...".  */
1529       [panel setCanChooseDirectories: NO];
1530       [panel setCanChooseFiles: YES];
1531     }
1533   block_input ();
1534   ns_fd_data.panel = panel;
1535   ns_fd_data.ret = NO;
1536 #ifdef NS_IMPL_COCOA
1537   if (! NILP (mustmatch) || ! NILP (dir_only_p))
1538     [panel setAllowedFileTypes: nil];
1539   if (dirS) [panel setDirectoryURL: [NSURL fileURLWithPath: dirS]];
1540   if (initS && NILP (Ffile_directory_p (init)))
1541     [panel setNameFieldStringValue: [initS lastPathComponent]];
1542   else
1543     [panel setNameFieldStringValue: @""];
1545 #else
1546   ns_fd_data.no_types = NILP (mustmatch) && NILP (dir_only_p);
1547   ns_fd_data.dirS = dirS;
1548   ns_fd_data.initS = initS;
1549 #endif
1551   /* runModalForDirectory/runModal restarts the main event loop when done,
1552      so we must start an event loop and then pop up the file dialog.
1553      The file dialog may pop up a confirm dialog after Ok has been pressed,
1554      so we can not simply pop down on the Ok/Cancel press.
1555    */
1556   nxev = [NSEvent otherEventWithType: NSApplicationDefined
1557                             location: NSMakePoint (0, 0)
1558                        modifierFlags: 0
1559                            timestamp: 0
1560                         windowNumber: [[NSApp mainWindow] windowNumber]
1561                              context: [NSApp context]
1562                              subtype: 0
1563                                data1: 0
1564                                data2: NSAPP_DATA2_RUNFILEDIALOG];
1566   [NSApp postEvent: nxev atStart: NO];
1567   while (ns_fd_data.panel != nil)
1568     [NSApp run];
1570   ret = (ns_fd_data.ret == NSOKButton);
1572   if (ret)
1573     {
1574       NSString *str = ns_filename_from_panel (panel);
1575       if (! str) str = ns_directory_from_panel (panel);
1576       if (! str) ret = NO;
1577       else fname = build_string ([str UTF8String]);
1578     }
1580   [[FRAME_NS_VIEW (SELECTED_FRAME ()) window] makeKeyWindow];
1581   unblock_input ();
1583   return ret ? fname : Qnil;
1586 const char *
1587 ns_get_defaults_value (const char *key)
1589   NSObject *obj = [[NSUserDefaults standardUserDefaults]
1590                     objectForKey: [NSString stringWithUTF8String: key]];
1592   if (!obj) return NULL;
1594   return [[NSString stringWithFormat: @"%@", obj] UTF8String];
1598 DEFUN ("ns-get-resource", Fns_get_resource, Sns_get_resource, 2, 2, 0,
1599        doc: /* Return the value of the property NAME of OWNER from the defaults database.
1600 If OWNER is nil, Emacs is assumed.  */)
1601      (Lisp_Object owner, Lisp_Object name)
1603   const char *value;
1605   check_window_system (NULL);
1606   if (NILP (owner))
1607     owner = build_string([ns_app_name UTF8String]);
1608   CHECK_STRING (name);
1610   value = ns_get_defaults_value (SSDATA (name));
1612   if (value)
1613     return build_string (value);
1614   return Qnil;
1618 DEFUN ("ns-set-resource", Fns_set_resource, Sns_set_resource, 3, 3, 0,
1619        doc: /* Set property NAME of OWNER to VALUE, from the defaults database.
1620 If OWNER is nil, Emacs is assumed.
1621 If VALUE is nil, the default is removed.  */)
1622      (Lisp_Object owner, Lisp_Object name, Lisp_Object value)
1624   check_window_system (NULL);
1625   if (NILP (owner))
1626     owner = build_string ([ns_app_name UTF8String]);
1627   CHECK_STRING (name);
1628   if (NILP (value))
1629     {
1630       [[NSUserDefaults standardUserDefaults] removeObjectForKey:
1631                          [NSString stringWithUTF8String: SSDATA (name)]];
1632     }
1633   else
1634     {
1635       CHECK_STRING (value);
1636       [[NSUserDefaults standardUserDefaults] setObject:
1637                 [NSString stringWithUTF8String: SSDATA (value)]
1638                                         forKey: [NSString stringWithUTF8String:
1639                                                          SSDATA (name)]];
1640     }
1642   return Qnil;
1646 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
1647        Sx_server_max_request_size,
1648        0, 1, 0,
1649        doc: /* This function is a no-op.  It is only present for completeness.  */)
1650      (Lisp_Object terminal)
1652   check_ns_display_info (terminal);
1653   /* This function has no real equivalent under NeXTstep.  Return nil to
1654      indicate this. */
1655   return Qnil;
1659 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
1660        doc: /* Return the "vendor ID" string of Nextstep display server TERMINAL.
1661 \(Labeling every distributor as a "vendor" embodies the false assumption
1662 that operating systems cannot be developed and distributed noncommercially.)
1663 The optional argument TERMINAL specifies which display to ask about.
1664 TERMINAL should be a terminal object, a frame or a display name (a string).
1665 If omitted or nil, that stands for the selected frame's display.  */)
1666   (Lisp_Object terminal)
1668   check_ns_display_info (terminal);
1669 #ifdef NS_IMPL_GNUSTEP
1670   return build_string ("GNU");
1671 #else
1672   return build_string ("Apple");
1673 #endif
1677 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
1678        doc: /* Return the version numbers of the server of display TERMINAL.
1679 The value is a list of three integers: the major and minor
1680 version numbers of the X Protocol in use, and the distributor-specific release
1681 number.  See also the function `x-server-vendor'.
1683 The optional argument TERMINAL specifies which display to ask about.
1684 TERMINAL should be a terminal object, a frame or a display name (a string).
1685 If omitted or nil, that stands for the selected frame's display.  */)
1686   (Lisp_Object terminal)
1688   check_ns_display_info (terminal);
1689   /*NOTE: it is unclear what would best correspond with "protocol";
1690           we return 10.3, meaning Panther, since this is roughly the
1691           level that GNUstep's APIs correspond to.
1692           The last number is where we distinguish between the Apple
1693           and GNUstep implementations ("distributor-specific release
1694           number") and give int'ized versions of major.minor. */
1695   return list3i (10, 3, ns_appkit_version_int ());
1699 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
1700        doc: /* Return the number of screens on Nextstep display server TERMINAL.
1701 The optional argument TERMINAL specifies which display to ask about.
1702 TERMINAL should be a terminal object, a frame or a display name (a string).
1703 If omitted or nil, that stands for the selected frame's display.
1705 Note: "screen" here is not in Nextstep terminology but in X11's.  For
1706 the number of physical monitors, use `(length
1707 (display-monitor-attributes-list TERMINAL))' instead.  */)
1708   (Lisp_Object terminal)
1710   check_ns_display_info (terminal);
1711   return make_number (1);
1715 DEFUN ("x-display-mm-height", Fx_display_mm_height, Sx_display_mm_height, 0, 1, 0,
1716        doc: /* Return the height in millimeters of the Nextstep display TERMINAL.
1717 The optional argument TERMINAL specifies which display to ask about.
1718 TERMINAL should be a terminal object, a frame or a display name (a string).
1719 If omitted or nil, that stands for the selected frame's display.
1721 On \"multi-monitor\" setups this refers to the height in millimeters for
1722 all physical monitors associated with TERMINAL.  To get information
1723 for each physical monitor, use `display-monitor-attributes-list'.  */)
1724   (Lisp_Object terminal)
1726   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
1728   return make_number (x_display_pixel_height (dpyinfo) / (92.0/25.4));
1732 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
1733        doc: /* Return the width in millimeters of the Nextstep display TERMINAL.
1734 The optional argument TERMINAL specifies which display to ask about.
1735 TERMINAL should be a terminal object, a frame or a display name (a string).
1736 If omitted or nil, that stands for the selected frame's display.
1738 On \"multi-monitor\" setups this refers to the width in millimeters for
1739 all physical monitors associated with TERMINAL.  To get information
1740 for each physical monitor, use `display-monitor-attributes-list'.  */)
1741   (Lisp_Object terminal)
1743   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
1745   return make_number (x_display_pixel_width (dpyinfo) / (92.0/25.4));
1749 DEFUN ("x-display-backing-store", Fx_display_backing_store,
1750        Sx_display_backing_store, 0, 1, 0,
1751        doc: /* Return an indication of whether the Nextstep display TERMINAL does backing store.
1752 The value may be `buffered', `retained', or `non-retained'.
1753 The optional argument TERMINAL specifies which display to ask about.
1754 TERMINAL should be a terminal object, a frame or a display name (a string).
1755 If omitted or nil, that stands for the selected frame's display.  */)
1756   (Lisp_Object terminal)
1758   check_ns_display_info (terminal);
1759   switch ([ns_get_window (terminal) backingType])
1760     {
1761     case NSBackingStoreBuffered:
1762       return intern ("buffered");
1763     case NSBackingStoreRetained:
1764       return intern ("retained");
1765     case NSBackingStoreNonretained:
1766       return intern ("non-retained");
1767     default:
1768       error ("Strange value for backingType parameter of frame");
1769     }
1770   return Qnil;  /* not reached, shut compiler up */
1774 DEFUN ("x-display-visual-class", Fx_display_visual_class,
1775        Sx_display_visual_class, 0, 1, 0,
1776        doc: /* Return the visual class of the Nextstep display TERMINAL.
1777 The value is one of the symbols `static-gray', `gray-scale',
1778 `static-color', `pseudo-color', `true-color', or `direct-color'.
1780 The optional argument TERMINAL specifies which display to ask about.
1781 TERMINAL should a terminal object, a frame or a display name (a string).
1782 If omitted or nil, that stands for the selected frame's display.  */)
1783   (Lisp_Object terminal)
1785   NSWindowDepth depth;
1787   check_ns_display_info (terminal);
1788   depth = [[[NSScreen screens] objectAtIndex:0] depth];
1790   if ( depth == NSBestDepth (NSCalibratedWhiteColorSpace, 2, 2, YES, NULL))
1791     return intern ("static-gray");
1792   else if (depth == NSBestDepth (NSCalibratedWhiteColorSpace, 8, 8, YES, NULL))
1793     return intern ("gray-scale");
1794   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 8, 8, YES, NULL))
1795     return intern ("pseudo-color");
1796   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 4, 12, NO, NULL))
1797     return intern ("true-color");
1798   else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 8, 24, NO, NULL))
1799     return intern ("direct-color");
1800   else
1801     /* color mgmt as far as we do it is really handled by Nextstep itself anyway */
1802     return intern ("direct-color");
1806 DEFUN ("x-display-save-under", Fx_display_save_under,
1807        Sx_display_save_under, 0, 1, 0,
1808        doc: /* Return t if TERMINAL supports the save-under feature.
1809 The optional argument TERMINAL specifies which display to ask about.
1810 TERMINAL should be a terminal object, a frame or a display name (a string).
1811 If omitted or nil, that stands for the selected frame's display.  */)
1812   (Lisp_Object terminal)
1814   check_ns_display_info (terminal);
1815   switch ([ns_get_window (terminal) backingType])
1816     {
1817     case NSBackingStoreBuffered:
1818       return Qt;
1820     case NSBackingStoreRetained:
1821     case NSBackingStoreNonretained:
1822       return Qnil;
1824     default:
1825       error ("Strange value for backingType parameter of frame");
1826     }
1827   return Qnil;  /* not reached, shut compiler up */
1831 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
1832        1, 3, 0,
1833        doc: /* Open a connection to a display server.
1834 DISPLAY is the name of the display to connect to.
1835 Optional second arg XRM-STRING is a string of resources in xrdb format.
1836 If the optional third arg MUST-SUCCEED is non-nil,
1837 terminate Emacs if we can't open the connection.
1838 \(In the Nextstep version, the last two arguments are currently ignored.)  */)
1839      (Lisp_Object display, Lisp_Object resource_string, Lisp_Object must_succeed)
1841   struct ns_display_info *dpyinfo;
1843   CHECK_STRING (display);
1845   nxatoms_of_nsselect ();
1846   dpyinfo = ns_term_init (display);
1847   if (dpyinfo == 0)
1848     {
1849       if (!NILP (must_succeed))
1850         fatal ("Display on %s not responding.\n",
1851                SSDATA (display));
1852       else
1853         error ("Display on %s not responding.\n",
1854                SSDATA (display));
1855     }
1857   return Qnil;
1861 DEFUN ("x-close-connection", Fx_close_connection, Sx_close_connection,
1862        1, 1, 0,
1863        doc: /* Close the connection to TERMINAL's Nextstep display server.
1864 For TERMINAL, specify a terminal object, a frame or a display name (a
1865 string).  If TERMINAL is nil, that stands for the selected frame's
1866 terminal.  */)
1867      (Lisp_Object terminal)
1869   check_ns_display_info (terminal);
1870   [NSApp terminate: NSApp];
1871   return Qnil;
1875 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
1876        doc: /* Return the list of display names that Emacs has connections to.  */)
1877      (void)
1879   Lisp_Object result = Qnil;
1880   struct ns_display_info *ndi;
1882   for (ndi = x_display_list; ndi; ndi = ndi->next)
1883     result = Fcons (XCAR (ndi->name_list_element), result);
1885   return result;
1889 DEFUN ("ns-hide-others", Fns_hide_others, Sns_hide_others,
1890        0, 0, 0,
1891        doc: /* Hides all applications other than Emacs.  */)
1892      (void)
1894   check_window_system (NULL);
1895   [NSApp hideOtherApplications: NSApp];
1896   return Qnil;
1899 DEFUN ("ns-hide-emacs", Fns_hide_emacs, Sns_hide_emacs,
1900        1, 1, 0,
1901        doc: /* If ON is non-nil, the entire Emacs application is hidden.
1902 Otherwise if Emacs is hidden, it is unhidden.
1903 If ON is equal to `activate', Emacs is unhidden and becomes
1904 the active application.  */)
1905      (Lisp_Object on)
1907   check_window_system (NULL);
1908   if (EQ (on, intern ("activate")))
1909     {
1910       [NSApp unhide: NSApp];
1911       [NSApp activateIgnoringOtherApps: YES];
1912     }
1913   else if (NILP (on))
1914     [NSApp unhide: NSApp];
1915   else
1916     [NSApp hide: NSApp];
1917   return Qnil;
1921 DEFUN ("ns-emacs-info-panel", Fns_emacs_info_panel, Sns_emacs_info_panel,
1922        0, 0, 0,
1923        doc: /* Shows the 'Info' or 'About' panel for Emacs.  */)
1924      (void)
1926   check_window_system (NULL);
1927   [NSApp orderFrontStandardAboutPanel: nil];
1928   return Qnil;
1932 DEFUN ("ns-font-name", Fns_font_name, Sns_font_name, 1, 1, 0,
1933        doc: /* Determine font PostScript or family name for font NAME.
1934 NAME should be a string containing either the font name or an XLFD
1935 font descriptor.  If string contains `fontset' and not
1936 `fontset-startup', it is left alone. */)
1937      (Lisp_Object name)
1939   char *nm;
1940   CHECK_STRING (name);
1941   nm = SSDATA (name);
1943   if (nm[0] != '-')
1944     return name;
1945   if (strstr (nm, "fontset") && !strstr (nm, "fontset-startup"))
1946     return name;
1948   return build_string (ns_xlfd_to_fontname (SSDATA (name)));
1952 DEFUN ("ns-list-colors", Fns_list_colors, Sns_list_colors, 0, 1, 0,
1953        doc: /* Return a list of all available colors.
1954 The optional argument FRAME is currently ignored.  */)
1955      (Lisp_Object frame)
1957   Lisp_Object list = Qnil;
1958   NSEnumerator *colorlists;
1959   NSColorList *clist;
1961   if (!NILP (frame))
1962     {
1963       CHECK_FRAME (frame);
1964       if (! FRAME_NS_P (XFRAME (frame)))
1965         error ("non-Nextstep frame used in `ns-list-colors'");
1966     }
1968   block_input ();
1970   colorlists = [[NSColorList availableColorLists] objectEnumerator];
1971   while ((clist = [colorlists nextObject]))
1972     {
1973       if ([[clist name] length] < 7 ||
1974           [[clist name] rangeOfString: @"PANTONE"].location == 0)
1975         {
1976           NSEnumerator *cnames = [[clist allKeys] reverseObjectEnumerator];
1977           NSString *cname;
1978           while ((cname = [cnames nextObject]))
1979             list = Fcons (build_string ([cname UTF8String]), list);
1980 /*           for (i = [[clist allKeys] count] - 1; i >= 0; i--)
1981                list = Fcons (build_string ([[[clist allKeys] objectAtIndex: i]
1982                                              UTF8String]), list); */
1983         }
1984     }
1986   unblock_input ();
1988   return list;
1992 DEFUN ("ns-list-services", Fns_list_services, Sns_list_services, 0, 0, 0,
1993        doc: /* List available Nextstep services by querying NSApp.  */)
1994      (void)
1996 #ifdef NS_IMPL_COCOA
1997   /* You can't get services like this in 10.6+.  */
1998   return Qnil;
1999 #else
2000   Lisp_Object ret = Qnil;
2001   NSMenu *svcs;
2002 #ifdef NS_IMPL_COCOA
2003   id delegate;
2004 #endif
2006   check_window_system (NULL);
2007   svcs = [[NSMenu alloc] initWithTitle: @"Services"];
2008   [NSApp setServicesMenu: svcs];
2009   [NSApp registerServicesMenuSendTypes: ns_send_types
2010                            returnTypes: ns_return_types];
2012 /* On Tiger, services menu updating was made lazier (waits for user to
2013    actually click on the menu), so we have to force things along: */
2014 #ifdef NS_IMPL_COCOA
2015   delegate = [svcs delegate];
2016   if (delegate != nil)
2017     {
2018       if ([delegate respondsToSelector: @selector (menuNeedsUpdate:)])
2019         [delegate menuNeedsUpdate: svcs];
2020       if ([delegate respondsToSelector:
2021                        @selector (menu:updateItem:atIndex:shouldCancel:)])
2022         {
2023           int i, len = [delegate numberOfItemsInMenu: svcs];
2024           for (i =0; i<len; i++)
2025             [svcs addItemWithTitle: @"" action: NULL keyEquivalent: @""];
2026           for (i =0; i<len; i++)
2027             if (![delegate menu: svcs
2028                      updateItem: (NSMenuItem *)[svcs itemAtIndex: i]
2029                         atIndex: i shouldCancel: NO])
2030               break;
2031         }
2032     }
2033 #endif
2035   [svcs setAutoenablesItems: NO];
2036 #ifdef NS_IMPL_COCOA
2037   [svcs update]; /* on OS X, converts from '/' structure */
2038 #endif
2040   ret = interpret_services_menu (svcs, Qnil, ret);
2041   return ret;
2042 #endif
2046 DEFUN ("ns-perform-service", Fns_perform_service, Sns_perform_service,
2047        2, 2, 0,
2048        doc: /* Perform Nextstep SERVICE on SEND.
2049 SEND should be either a string or nil.
2050 The return value is the result of the service, as string, or nil if
2051 there was no result.  */)
2052      (Lisp_Object service, Lisp_Object send)
2054   id pb;
2055   NSString *svcName;
2056   char *utfStr;
2058   CHECK_STRING (service);
2059   check_window_system (NULL);
2061   utfStr = SSDATA (service);
2062   svcName = [NSString stringWithUTF8String: utfStr];
2064   pb =[NSPasteboard pasteboardWithUniqueName];
2065   ns_string_to_pasteboard (pb, send);
2067   if (NSPerformService (svcName, pb) == NO)
2068     Fsignal (Qquit, list1 (build_string ("service not available")));
2070   if ([[pb types] count] == 0)
2071     return build_string ("");
2072   return ns_string_from_pasteboard (pb);
2076 DEFUN ("ns-convert-utf8-nfd-to-nfc", Fns_convert_utf8_nfd_to_nfc,
2077        Sns_convert_utf8_nfd_to_nfc, 1, 1, 0,
2078        doc: /* Return an NFC string that matches the UTF-8 NFD string STR.  */)
2079      (Lisp_Object str)
2081 /* TODO: If GNUstep ever implements precomposedStringWithCanonicalMapping,
2082          remove this. */
2083   NSString *utfStr;
2084   Lisp_Object ret = Qnil;
2085   NSAutoreleasePool *pool;
2087   CHECK_STRING (str);
2088   pool = [[NSAutoreleasePool alloc] init];
2089   utfStr = [NSString stringWithUTF8String: SSDATA (str)];
2090 #ifdef NS_IMPL_COCOA
2091   if (utfStr)
2092     utfStr = [utfStr precomposedStringWithCanonicalMapping];
2093 #endif
2094   if (utfStr)
2095     {
2096       const char *cstr = [utfStr UTF8String];
2097       if (cstr)
2098         ret = build_string (cstr);
2099     }
2101   [pool release];
2102   if (NILP (ret))
2103     error ("Invalid UTF-8");
2105   return ret;
2109 #ifdef NS_IMPL_COCOA
2111 /* Compile and execute the AppleScript SCRIPT and return the error
2112    status as function value.  A zero is returned if compilation and
2113    execution is successful, in which case *RESULT is set to a Lisp
2114    string or a number containing the resulting script value.  Otherwise,
2115    1 is returned. */
2116 static int
2117 ns_do_applescript (Lisp_Object script, Lisp_Object *result)
2119   NSAppleEventDescriptor *desc;
2120   NSDictionary* errorDict;
2121   NSAppleEventDescriptor* returnDescriptor = NULL;
2123   NSAppleScript* scriptObject =
2124     [[NSAppleScript alloc] initWithSource:
2125                              [NSString stringWithUTF8String: SSDATA (script)]];
2127   returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
2128   [scriptObject release];
2129   *result = Qnil;
2131   if (returnDescriptor != NULL)
2132     {
2133       // successful execution
2134       if (kAENullEvent != [returnDescriptor descriptorType])
2135         {
2136           *result = Qt;
2137           // script returned an AppleScript result
2138           if ((typeUnicodeText == [returnDescriptor descriptorType]) ||
2139 #if defined (NS_IMPL_COCOA)
2140               (typeUTF16ExternalRepresentation
2141                == [returnDescriptor descriptorType]) ||
2142 #endif
2143               (typeUTF8Text == [returnDescriptor descriptorType]) ||
2144               (typeCString == [returnDescriptor descriptorType]))
2145             {
2146               desc = [returnDescriptor coerceToDescriptorType: typeUTF8Text];
2147               if (desc)
2148                 *result = build_string([[desc stringValue] UTF8String]);
2149             }
2150           else
2151             {
2152               /* use typeUTF16ExternalRepresentation? */
2153               // coerce the result to the appropriate ObjC type
2154               desc = [returnDescriptor coerceToDescriptorType: typeUTF8Text];
2155               if (desc)
2156                 *result = make_number([desc int32Value]);
2157             }
2158         }
2159     }
2160   else
2161     {
2162       // no script result, return error
2163       return 1;
2164     }
2165   return 0;
2168 /* Helper function called from sendEvent to run applescript
2169    from within the main event loop.  */
2171 void
2172 ns_run_ascript (void)
2174   if (! NILP (as_script))
2175     as_status = ns_do_applescript (as_script, as_result);
2176   as_script = Qnil;
2179 DEFUN ("ns-do-applescript", Fns_do_applescript, Sns_do_applescript, 1, 1, 0,
2180        doc: /* Execute AppleScript SCRIPT and return the result.
2181 If compilation and execution are successful, the resulting script value
2182 is returned as a string, a number or, in the case of other constructs, t.
2183 In case the execution fails, an error is signaled. */)
2184      (Lisp_Object script)
2186   Lisp_Object result;
2187   int status;
2188   NSEvent *nxev;
2189   struct input_event ev;
2191   CHECK_STRING (script);
2192   check_window_system (NULL);
2194   block_input ();
2196   as_script = script;
2197   as_result = &result;
2199   /* executing apple script requires the event loop to run, otherwise
2200      errors aren't returned and executeAndReturnError hangs forever.
2201      Post an event that runs applescript and then start the event loop.
2202      The event loop is exited when the script is done.  */
2203   nxev = [NSEvent otherEventWithType: NSApplicationDefined
2204                             location: NSMakePoint (0, 0)
2205                        modifierFlags: 0
2206                            timestamp: 0
2207                         windowNumber: [[NSApp mainWindow] windowNumber]
2208                              context: [NSApp context]
2209                              subtype: 0
2210                                data1: 0
2211                                data2: NSAPP_DATA2_RUNASSCRIPT];
2213   [NSApp postEvent: nxev atStart: NO];
2215   // If there are other events, the event loop may exit.  Keep running
2216   // until the script has been handled.  */
2217   ns_init_events (&ev);
2218   while (! NILP (as_script))
2219     [NSApp run];
2220   ns_finish_events ();
2222   status = as_status;
2223   as_status = 0;
2224   as_result = 0;
2225   unblock_input ();
2226   if (status == 0)
2227     return result;
2228   else if (!STRINGP (result))
2229     error ("AppleScript error %d", status);
2230   else
2231     error ("%s", SSDATA (result));
2233 #endif
2237 /* ==========================================================================
2239     Miscellaneous functions not called through hooks
2241    ========================================================================== */
2243 /* called from frame.c */
2244 struct ns_display_info *
2245 check_x_display_info (Lisp_Object frame)
2247   return check_ns_display_info (frame);
2251 void
2252 x_set_scroll_bar_default_width (struct frame *f)
2254   int wid = FRAME_COLUMN_WIDTH (f);
2255   FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = NS_SCROLL_BAR_WIDTH_DEFAULT;
2256   FRAME_CONFIG_SCROLL_BAR_COLS (f) = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) +
2257                                       wid - 1) / wid;
2260 void
2261 x_set_scroll_bar_default_height (struct frame *f)
2263   int height = FRAME_LINE_HEIGHT (f);
2264   FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) = NS_SCROLL_BAR_WIDTH_DEFAULT;
2265   FRAME_CONFIG_SCROLL_BAR_LINES (f) = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) +
2266                                        height - 1) / height;
2269 /* terms impl this instead of x-get-resource directly */
2270 char *
2271 x_get_string_resource (XrmDatabase rdb, const char *name, const char *class)
2273   /* remove appname prefix; TODO: allow for !="Emacs" */
2274   const char *res, *toCheck = class + (!strncmp (class, "Emacs.", 6) ? 6 : 0);
2276   check_window_system (NULL);
2278   if (inhibit_x_resources)
2279     /* --quick was passed, so this is a no-op.  */
2280     return NULL;
2282   res = ns_get_defaults_value (toCheck);
2283   return (!res ? NULL :
2284           (!c_strncasecmp (res, "YES", 3) ? "true" :
2285            (!c_strncasecmp (res, "NO", 2) ? "false" : (char *) res)));
2289 Lisp_Object
2290 x_get_focus_frame (struct frame *frame)
2292   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
2293   Lisp_Object nsfocus;
2295   if (!dpyinfo->x_focus_frame)
2296     return Qnil;
2298   XSETFRAME (nsfocus, dpyinfo->x_focus_frame);
2299   return nsfocus;
2302 /* ==========================================================================
2304     Lisp definitions that, for whatever reason, we can't alias as 'ns-XXX'.
2306    ========================================================================== */
2309 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
2310        doc: /* Internal function called by `color-defined-p', which see.
2311 \(Note that the Nextstep version of this function ignores FRAME.)  */)
2312      (Lisp_Object color, Lisp_Object frame)
2314   NSColor * col;
2315   check_window_system (NULL);
2316   return ns_lisp_to_color (color, &col) ? Qnil : Qt;
2320 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
2321        doc: /* Internal function called by `color-values', which see.  */)
2322      (Lisp_Object color, Lisp_Object frame)
2324   NSColor * col;
2325   EmacsCGFloat red, green, blue, alpha;
2327   check_window_system (NULL);
2328   CHECK_STRING (color);
2330   if (ns_lisp_to_color (color, &col))
2331     return Qnil;
2333   [[col colorUsingDefaultColorSpace]
2334         getRed: &red green: &green blue: &blue alpha: &alpha];
2335   return list3i (lrint (red * 65280), lrint (green * 65280),
2336                  lrint (blue * 65280));
2340 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
2341        doc: /* Internal function called by `display-color-p', which see.  */)
2342      (Lisp_Object terminal)
2344   NSWindowDepth depth;
2345   NSString *colorSpace;
2347   check_ns_display_info (terminal);
2348   depth = [[[NSScreen screens] objectAtIndex:0] depth];
2349   colorSpace = NSColorSpaceFromDepth (depth);
2351   return    [colorSpace isEqualToString: NSDeviceWhiteColorSpace]
2352          || [colorSpace isEqualToString: NSCalibratedWhiteColorSpace]
2353       ? Qnil : Qt;
2357 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p, Sx_display_grayscale_p,
2358        0, 1, 0,
2359        doc: /* Return t if the Nextstep display supports shades of gray.
2360 Note that color displays do support shades of gray.
2361 The optional argument TERMINAL specifies which display to ask about.
2362 TERMINAL should be a terminal object, a frame or a display name (a string).
2363 If omitted or nil, that stands for the selected frame's display.  */)
2364   (Lisp_Object terminal)
2366   NSWindowDepth depth;
2368   check_ns_display_info (terminal);
2369   depth = [[[NSScreen screens] objectAtIndex:0] depth];
2371   return NSBitsPerPixelFromDepth (depth) > 1 ? Qt : Qnil;
2375 DEFUN ("x-display-pixel-width", Fx_display_pixel_width, Sx_display_pixel_width,
2376        0, 1, 0,
2377        doc: /* Return the width in pixels of the Nextstep display TERMINAL.
2378 The optional argument TERMINAL specifies which display to ask about.
2379 TERMINAL should be a terminal object, a frame or a display name (a string).
2380 If omitted or nil, that stands for the selected frame's display.
2382 On \"multi-monitor\" setups this refers to the pixel width for all
2383 physical monitors associated with TERMINAL.  To get information for
2384 each physical monitor, use `display-monitor-attributes-list'.  */)
2385   (Lisp_Object terminal)
2387   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
2389   return make_number (x_display_pixel_width (dpyinfo));
2393 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
2394        Sx_display_pixel_height, 0, 1, 0,
2395        doc: /* Return the height in pixels of the Nextstep display TERMINAL.
2396 The optional argument TERMINAL specifies which display to ask about.
2397 TERMINAL should be a terminal object, a frame or a display name (a string).
2398 If omitted or nil, that stands for the selected frame's display.
2400 On \"multi-monitor\" setups this refers to the pixel height for all
2401 physical monitors associated with TERMINAL.  To get information for
2402 each physical monitor, use `display-monitor-attributes-list'.  */)
2403   (Lisp_Object terminal)
2405   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
2407   return make_number (x_display_pixel_height (dpyinfo));
2410 #ifdef NS_IMPL_COCOA
2412 /* Returns the name for the screen that OBJ represents, or NULL.
2413    Caller must free return value.
2416 static char *
2417 ns_get_name_from_ioreg (io_object_t obj)
2419   char *name = NULL;
2421   NSDictionary *info = (NSDictionary *)
2422     IODisplayCreateInfoDictionary (obj, kIODisplayOnlyPreferredName);
2423   NSDictionary *names = [info objectForKey:
2424                                 [NSString stringWithUTF8String:
2425                                             kDisplayProductName]];
2427   if ([names count] > 0)
2428     {
2429       NSString *n = [names objectForKey: [[names allKeys]
2430                                                  objectAtIndex:0]];
2431       if (n != nil) name = xstrdup ([n UTF8String]);
2432     }
2434   [info release];
2436   return name;
2439 /* Returns the name for the screen that DID came from, or NULL.
2440    Caller must free return value.
2443 static char *
2444 ns_screen_name (CGDirectDisplayID did)
2446   char *name = NULL;
2448 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
2449   mach_port_t masterPort;
2450   io_iterator_t it;
2451   io_object_t obj;
2453   // CGDisplayIOServicePort is deprecated.  Do it another (harder) way.
2455   if (IOMasterPort (MACH_PORT_NULL, &masterPort) != kIOReturnSuccess
2456       || IOServiceGetMatchingServices (masterPort,
2457                                        IOServiceMatching ("IONDRVDevice"),
2458                                        &it) != kIOReturnSuccess)
2459     return name;
2461   /* Must loop until we find a name.  Many devices can have the same unit
2462      number (represents different GPU parts), but only one has a name.  */
2463   while (! name && (obj = IOIteratorNext (it)))
2464     {
2465       CFMutableDictionaryRef props;
2466       const void *val;
2468       if (IORegistryEntryCreateCFProperties (obj,
2469                                              &props,
2470                                              kCFAllocatorDefault,
2471                                              kNilOptions) == kIOReturnSuccess
2472           && props != nil
2473           && (val = CFDictionaryGetValue(props, @"IOFBDependentIndex")))
2474         {
2475           unsigned nr = [(NSNumber *)val unsignedIntegerValue];
2476           if (nr == CGDisplayUnitNumber (did))
2477             name = ns_get_name_from_ioreg (obj);
2478         }
2480       CFRelease (props);
2481       IOObjectRelease (obj);
2482     }
2484   IOObjectRelease (it);
2486 #else
2488   name = ns_get_name_from_ioreg (CGDisplayIOServicePort (did));
2490 #endif
2491   return name;
2493 #endif
2495 static Lisp_Object
2496 ns_make_monitor_attribute_list (struct MonitorInfo *monitors,
2497                                 int n_monitors,
2498                                 int primary_monitor,
2499                                 const char *source)
2501   Lisp_Object monitor_frames = Fmake_vector (make_number (n_monitors), Qnil);
2502   Lisp_Object frame, rest;
2503   NSArray *screens = [NSScreen screens];
2504   int i;
2506   FOR_EACH_FRAME (rest, frame)
2507     {
2508       struct frame *f = XFRAME (frame);
2510       if (FRAME_NS_P (f))
2511         {
2512           NSView *view = FRAME_NS_VIEW (f);
2513           NSScreen *screen = [[view window] screen];
2514           NSUInteger k;
2516           i = -1;
2517           for (k = 0; i == -1 && k < [screens count]; ++k)
2518             {
2519               if ([screens objectAtIndex: k] == screen)
2520                 i = (int)k;
2521             }
2523           if (i > -1)
2524             ASET (monitor_frames, i, Fcons (frame, AREF (monitor_frames, i)));
2525         }
2526     }
2528   return make_monitor_attribute_list (monitors, n_monitors, primary_monitor,
2529                                       monitor_frames, source);
2532 DEFUN ("ns-display-monitor-attributes-list",
2533        Fns_display_monitor_attributes_list,
2534        Sns_display_monitor_attributes_list,
2535        0, 1, 0,
2536        doc: /* Return a list of physical monitor attributes on the X display TERMINAL.
2538 The optional argument TERMINAL specifies which display to ask about.
2539 TERMINAL should be a terminal object, a frame or a display name (a string).
2540 If omitted or nil, that stands for the selected frame's display.
2542 In addition to the standard attribute keys listed in
2543 `display-monitor-attributes-list', the following keys are contained in
2544 the attributes:
2546  source -- String describing the source from which multi-monitor
2547            information is obtained, \"NS\" is always the source."
2549 Internal use only, use `display-monitor-attributes-list' instead.  */)
2550   (Lisp_Object terminal)
2552   struct terminal *term = decode_live_terminal (terminal);
2553   NSArray *screens;
2554   NSUInteger i, n_monitors;
2555   struct MonitorInfo *monitors;
2556   Lisp_Object attributes_list = Qnil;
2557   CGFloat primary_display_height = 0;
2559   if (term->type != output_ns)
2560     return Qnil;
2562   screens = [NSScreen screens];
2563   n_monitors = [screens count];
2564   if (n_monitors == 0)
2565     return Qnil;
2567   monitors = xzalloc (n_monitors * sizeof *monitors);
2569   for (i = 0; i < [screens count]; ++i)
2570     {
2571       NSScreen *s = [screens objectAtIndex:i];
2572       struct MonitorInfo *m = &monitors[i];
2573       NSRect fr = [s frame];
2574       NSRect vfr = [s visibleFrame];
2575       short y, vy;
2577 #ifdef NS_IMPL_COCOA
2578       NSDictionary *dict = [s deviceDescription];
2579       NSNumber *nid = [dict objectForKey:@"NSScreenNumber"];
2580       CGDirectDisplayID did = [nid unsignedIntValue];
2581 #endif
2582       if (i == 0)
2583         {
2584           primary_display_height = fr.size.height;
2585           y = (short) fr.origin.y;
2586           vy = (short) vfr.origin.y;
2587         }
2588       else
2589         {
2590           // Flip y coordinate as NS has y starting from the bottom.
2591           y = (short) (primary_display_height - fr.size.height - fr.origin.y);
2592           vy = (short) (primary_display_height -
2593                         vfr.size.height - vfr.origin.y);
2594         }
2596       m->geom.x = (short) fr.origin.x;
2597       m->geom.y = y;
2598       m->geom.width = (unsigned short) fr.size.width;
2599       m->geom.height = (unsigned short) fr.size.height;
2601       m->work.x = (short) vfr.origin.x;
2602       // y is flipped on NS, so vy - y are pixels missing at the bottom,
2603       // and fr.size.height - vfr.size.height are pixels missing in total.
2604       // Pixels missing at top are
2605       // fr.size.height - vfr.size.height - vy + y.
2606       // work.y is then pixels missing at top + y.
2607       m->work.y = (short) (fr.size.height - vfr.size.height) - vy + y + y;
2608       m->work.width = (unsigned short) vfr.size.width;
2609       m->work.height = (unsigned short) vfr.size.height;
2611 #ifdef NS_IMPL_COCOA
2612       m->name = ns_screen_name (did);
2614       {
2615         CGSize mms = CGDisplayScreenSize (did);
2616         m->mm_width = (int) mms.width;
2617         m->mm_height = (int) mms.height;
2618       }
2620 #else
2621       // Assume 92 dpi as x-display-mm-height/x-display-mm-width does.
2622       m->mm_width = (int) (25.4 * fr.size.width / 92.0);
2623       m->mm_height = (int) (25.4 * fr.size.height / 92.0);
2624 #endif
2625     }
2627   // Primary monitor is always first for NS.
2628   attributes_list = ns_make_monitor_attribute_list (monitors, n_monitors,
2629                                                     0, "NS");
2631   free_monitors (monitors, n_monitors);
2632   return attributes_list;
2636 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
2637        0, 1, 0,
2638        doc: /* Return the number of bitplanes of the Nextstep display TERMINAL.
2639 The optional argument TERMINAL specifies which display to ask about.
2640 TERMINAL should be a terminal object, a frame or a display name (a string).
2641 If omitted or nil, that stands for the selected frame's display.  */)
2642   (Lisp_Object terminal)
2644   check_ns_display_info (terminal);
2645   return make_number
2646     (NSBitsPerPixelFromDepth ([[[NSScreen screens] objectAtIndex:0] depth]));
2650 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
2651        0, 1, 0,
2652        doc: /* Returns the number of color cells of the Nextstep display TERMINAL.
2653 The optional argument TERMINAL specifies which display to ask about.
2654 TERMINAL should be a terminal object, a frame or a display name (a string).
2655 If omitted or nil, that stands for the selected frame's display.  */)
2656   (Lisp_Object terminal)
2658   struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
2659   /* We force 24+ bit depths to 24-bit to prevent an overflow.  */
2660   return make_number (1 << min (dpyinfo->n_planes, 24));
2664 /* Unused dummy def needed for compatibility. */
2665 Lisp_Object tip_frame;
2667 /* TODO: move to xdisp or similar */
2668 static void
2669 compute_tip_xy (struct frame *f,
2670                 Lisp_Object parms,
2671                 Lisp_Object dx,
2672                 Lisp_Object dy,
2673                 int width,
2674                 int height,
2675                 int *root_x,
2676                 int *root_y)
2678   Lisp_Object left, top;
2679   EmacsView *view = FRAME_NS_VIEW (f);
2680   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2681   NSPoint pt;
2683   /* Start with user-specified or mouse position.  */
2684   left = Fcdr (Fassq (Qleft, parms));
2685   top = Fcdr (Fassq (Qtop, parms));
2687   if (!INTEGERP (left) || !INTEGERP (top))
2688     {
2689       pt.x = dpyinfo->last_mouse_motion_x;
2690       pt.y = dpyinfo->last_mouse_motion_y;
2691       /* Convert to screen coordinates */
2692       pt = [view convertPoint: pt toView: nil];
2693       pt = [[view window] convertBaseToScreen: pt];
2694     }
2695   else
2696     {
2697       /* Absolute coordinates.  */
2698       pt.x = XINT (left);
2699       pt.y = x_display_pixel_height (FRAME_DISPLAY_INFO (f)) - XINT (top)
2700         - height;
2701     }
2703   /* Ensure in bounds.  (Note, screen origin = lower left.) */
2704   if (INTEGERP (left))
2705     *root_x = pt.x;
2706   else if (pt.x + XINT (dx) <= 0)
2707     *root_x = 0; /* Can happen for negative dx */
2708   else if (pt.x + XINT (dx) + width
2709            <= x_display_pixel_width (FRAME_DISPLAY_INFO (f)))
2710     /* It fits to the right of the pointer.  */
2711     *root_x = pt.x + XINT (dx);
2712   else if (width + XINT (dx) <= pt.x)
2713     /* It fits to the left of the pointer.  */
2714     *root_x = pt.x - width - XINT (dx);
2715   else
2716     /* Put it left justified on the screen -- it ought to fit that way.  */
2717     *root_x = 0;
2719   if (INTEGERP (top))
2720     *root_y = pt.y;
2721   else if (pt.y - XINT (dy) - height >= 0)
2722     /* It fits below the pointer.  */
2723     *root_y = pt.y - height - XINT (dy);
2724   else if (pt.y + XINT (dy) + height
2725            <= x_display_pixel_height (FRAME_DISPLAY_INFO (f)))
2726     /* It fits above the pointer */
2727       *root_y = pt.y + XINT (dy);
2728   else
2729     /* Put it on the top.  */
2730     *root_y = x_display_pixel_height (FRAME_DISPLAY_INFO (f)) - height;
2734 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
2735        doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
2736 A tooltip window is a small window displaying a string.
2738 This is an internal function; Lisp code should call `tooltip-show'.
2740 FRAME nil or omitted means use the selected frame.
2742 PARMS is an optional list of frame parameters which can be used to
2743 change the tooltip's appearance.
2745 Automatically hide the tooltip after TIMEOUT seconds.  TIMEOUT nil
2746 means use the default timeout of 5 seconds.
2748 If the list of frame parameters PARMS contains a `left' parameter,
2749 the tooltip is displayed at that x-position.  Otherwise it is
2750 displayed at the mouse position, with offset DX added (default is 5 if
2751 DX isn't specified).  Likewise for the y-position; if a `top' frame
2752 parameter is specified, it determines the y-position of the tooltip
2753 window, otherwise it is displayed at the mouse position, with offset
2754 DY added (default is -10).
2756 A tooltip's maximum size is specified by `x-max-tooltip-size'.
2757 Text larger than the specified size is clipped.  */)
2758      (Lisp_Object string, Lisp_Object frame, Lisp_Object parms, Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
2760   int root_x, root_y;
2761   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2762   ptrdiff_t count = SPECPDL_INDEX ();
2763   struct frame *f;
2764   char *str;
2765   NSSize size;
2767   specbind (Qinhibit_redisplay, Qt);
2769   GCPRO4 (string, parms, frame, timeout);
2771   CHECK_STRING (string);
2772   str = SSDATA (string);
2773   f = decode_window_system_frame (frame);
2774   if (NILP (timeout))
2775     timeout = make_number (5);
2776   else
2777     CHECK_NATNUM (timeout);
2779   if (NILP (dx))
2780     dx = make_number (5);
2781   else
2782     CHECK_NUMBER (dx);
2784   if (NILP (dy))
2785     dy = make_number (-10);
2786   else
2787     CHECK_NUMBER (dy);
2789   block_input ();
2790   if (ns_tooltip == nil)
2791     ns_tooltip = [[EmacsTooltip alloc] init];
2792   else
2793     Fx_hide_tip ();
2795   [ns_tooltip setText: str];
2796   size = [ns_tooltip frame].size;
2798   /* Move the tooltip window where the mouse pointer is.  Resize and
2799      show it.  */
2800   compute_tip_xy (f, parms, dx, dy, (int)size.width, (int)size.height,
2801                   &root_x, &root_y);
2803   [ns_tooltip showAtX: root_x Y: root_y for: XINT (timeout)];
2804   unblock_input ();
2806   UNGCPRO;
2807   return unbind_to (count, Qnil);
2811 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
2812        doc: /* Hide the current tooltip window, if there is any.
2813 Value is t if tooltip was open, nil otherwise.  */)
2814      (void)
2816   if (ns_tooltip == nil || ![ns_tooltip isActive])
2817     return Qnil;
2818   [ns_tooltip hide];
2819   return Qt;
2823 /* ==========================================================================
2825     Class implementations
2827    ========================================================================== */
2830   Handle arrow/function/control keys and copy/paste/cut in file dialogs.
2831   Return YES if handled, NO if not.
2832  */
2833 static BOOL
2834 handlePanelKeys (NSSavePanel *panel, NSEvent *theEvent)
2836   NSString *s;
2837   int i;
2838   BOOL ret = NO;
2840   if ([theEvent type] != NSKeyDown) return NO;
2841   s = [theEvent characters];
2843   for (i = 0; i < [s length]; ++i)
2844     {
2845       int ch = (int) [s characterAtIndex: i];
2846       switch (ch)
2847         {
2848         case NSHomeFunctionKey:
2849         case NSDownArrowFunctionKey:
2850         case NSUpArrowFunctionKey:
2851         case NSLeftArrowFunctionKey:
2852         case NSRightArrowFunctionKey:
2853         case NSPageUpFunctionKey:
2854         case NSPageDownFunctionKey:
2855         case NSEndFunctionKey:
2856           /* Don't send command modified keys, as those are handled in the
2857              performKeyEquivalent method of the super class.
2858           */
2859           if (! ([theEvent modifierFlags] & NSCommandKeyMask))
2860             {
2861               [panel sendEvent: theEvent];
2862               ret = YES;
2863             }
2864           break;
2865           /* As we don't have the standard key commands for
2866              copy/paste/cut/select-all in our edit menu, we must handle
2867              them here.  TODO: handle Emacs key bindings for copy/cut/select-all
2868              here, paste works, because we have that in our Edit menu.
2869              I.e. refactor out code in nsterm.m, keyDown: to figure out the
2870              correct modifier.
2871           */
2872         case 'x': // Cut
2873         case 'c': // Copy
2874         case 'v': // Paste
2875         case 'a': // Select all
2876           if ([theEvent modifierFlags] & NSCommandKeyMask)
2877             {
2878               [NSApp sendAction:
2879                        (ch == 'x'
2880                         ? @selector(cut:)
2881                         : (ch == 'c'
2882                            ? @selector(copy:)
2883                            : (ch == 'v'
2884                               ? @selector(paste:)
2885                               : @selector(selectAll:))))
2886                              to:nil from:panel];
2887               ret = YES;
2888             }
2889         default:
2890           // Send all control keys, as the text field supports C-a, C-f, C-e
2891           // C-b and more.
2892           if ([theEvent modifierFlags] & NSControlKeyMask)
2893             {
2894               [panel sendEvent: theEvent];
2895               ret = YES;
2896             }
2897           break;
2898         }
2899     }
2902   return ret;
2905 @implementation EmacsSavePanel
2906 - (BOOL)performKeyEquivalent:(NSEvent *)theEvent
2908   BOOL ret = handlePanelKeys (self, theEvent);
2909   if (! ret)
2910     ret = [super performKeyEquivalent:theEvent];
2911   return ret;
2913 @end
2916 @implementation EmacsOpenPanel
2917 - (BOOL)performKeyEquivalent:(NSEvent *)theEvent
2919   // NSOpenPanel inherits NSSavePanel, so passing self is OK.
2920   BOOL ret = handlePanelKeys (self, theEvent);
2921   if (! ret)
2922     ret = [super performKeyEquivalent:theEvent];
2923   return ret;
2925 @end
2928 @implementation EmacsFileDelegate
2929 /* --------------------------------------------------------------------------
2930    Delegate methods for Open/Save panels
2931    -------------------------------------------------------------------------- */
2932 - (BOOL)panel: (id)sender isValidFilename: (NSString *)filename
2934   return YES;
2936 - (BOOL)panel: (id)sender shouldShowFilename: (NSString *)filename
2938   return YES;
2940 - (NSString *)panel: (id)sender userEnteredFilename: (NSString *)filename
2941           confirmed: (BOOL)okFlag
2943   return filename;
2945 @end
2947 #endif
2950 /* ==========================================================================
2952     Lisp interface declaration
2954    ========================================================================== */
2957 void
2958 syms_of_nsfns (void)
2960   Qfontsize = intern_c_string ("fontsize");
2961   staticpro (&Qfontsize);
2963   DEFVAR_LISP ("ns-icon-type-alist", Vns_icon_type_alist,
2964                doc: /* Alist of elements (REGEXP . IMAGE) for images of icons associated to frames.
2965 If the title of a frame matches REGEXP, then IMAGE.tiff is
2966 selected as the image of the icon representing the frame when it's
2967 miniaturized.  If an element is t, then Emacs tries to select an icon
2968 based on the filetype of the visited file.
2970 The images have to be installed in a folder called English.lproj in the
2971 Emacs folder.  You have to restart Emacs after installing new icons.
2973 Example: Install an icon Gnus.tiff and execute the following code
2975   (setq ns-icon-type-alist
2976         (append ns-icon-type-alist
2977                 '((\"^\\\\*\\\\(Group\\\\*$\\\\|Summary \\\\|Article\\\\*$\\\\)\"
2978                    . \"Gnus\"))))
2980 When you miniaturize a Group, Summary or Article frame, Gnus.tiff will
2981 be used as the image of the icon representing the frame.  */);
2982   Vns_icon_type_alist = list1 (Qt);
2984   DEFVAR_LISP ("ns-version-string", Vns_version_string,
2985                doc: /* Toolkit version for NS Windowing.  */);
2986   Vns_version_string = ns_appkit_version_str ();
2988   defsubr (&Sns_read_file_name);
2989   defsubr (&Sns_get_resource);
2990   defsubr (&Sns_set_resource);
2991   defsubr (&Sxw_display_color_p); /* this and next called directly by C code */
2992   defsubr (&Sx_display_grayscale_p);
2993   defsubr (&Sns_font_name);
2994   defsubr (&Sns_list_colors);
2995 #ifdef NS_IMPL_COCOA
2996   defsubr (&Sns_do_applescript);
2997 #endif
2998   defsubr (&Sxw_color_defined_p);
2999   defsubr (&Sxw_color_values);
3000   defsubr (&Sx_server_max_request_size);
3001   defsubr (&Sx_server_vendor);
3002   defsubr (&Sx_server_version);
3003   defsubr (&Sx_display_pixel_width);
3004   defsubr (&Sx_display_pixel_height);
3005   defsubr (&Sns_display_monitor_attributes_list);
3006   defsubr (&Sx_display_mm_width);
3007   defsubr (&Sx_display_mm_height);
3008   defsubr (&Sx_display_screens);
3009   defsubr (&Sx_display_planes);
3010   defsubr (&Sx_display_color_cells);
3011   defsubr (&Sx_display_visual_class);
3012   defsubr (&Sx_display_backing_store);
3013   defsubr (&Sx_display_save_under);
3014   defsubr (&Sx_create_frame);
3015   defsubr (&Sx_open_connection);
3016   defsubr (&Sx_close_connection);
3017   defsubr (&Sx_display_list);
3019   defsubr (&Sns_hide_others);
3020   defsubr (&Sns_hide_emacs);
3021   defsubr (&Sns_emacs_info_panel);
3022   defsubr (&Sns_list_services);
3023   defsubr (&Sns_perform_service);
3024   defsubr (&Sns_convert_utf8_nfd_to_nfc);
3025   defsubr (&Sns_popup_font_panel);
3026   defsubr (&Sns_popup_color_panel);
3028   defsubr (&Sx_show_tip);
3029   defsubr (&Sx_hide_tip);
3031   as_status = 0;
3032   as_script = Qnil;
3033   as_result = 0;