1 /* Functions for the NeXT/Open/GNUstep and MacOSX window system.
3 Copyright (C) 1989, 1992-1994, 2005-2006, 2008-2014 Free Software
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. */
34 #include <c-strcase.h>
37 #include "blockinput.h"
40 #include "character.h"
43 #include "termhooks.h"
48 #include <IOKit/graphics/IOGraphicsLib.h>
53 int fns_trace_num = 1;
54 #define NSTRACE(x) fprintf (stderr, "%s:%d: [%d] " #x "\n", \
55 __FILE__, __LINE__, ++fns_trace_num)
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;
103 static ptrdiff_t image_cache_refcount;
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;
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;
132 error ("Nextstep windows are not in use or not initialized");
134 else if (TERMINALP (object))
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;
143 else if (STRINGP (object))
144 dpyinfo = ns_display_info_for_name (object);
147 struct frame *f = decode_window_system_frame (object);
148 dpyinfo = FRAME_DISPLAY_INFO (f);
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];
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;
180 for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
181 if (!NILP (Fstring_equal (XCAR (dpyinfo->name_list_element), name)))
184 error ("Emacs for Nextstep does not yet support multi-display");
186 Fx_open_connection (name, Qnil, Qnil);
187 dpyinfo = x_display_list;
190 error ("Display on %s not responding.\n", SDATA (name));
196 ns_filename_from_panel (NSSavePanel *panel)
199 NSURL *url = [panel URL];
200 NSString *str = [url path];
203 return [panel filename];
208 ns_directory_from_panel (NSSavePanel *panel)
211 NSURL *url = [panel directoryURL];
212 NSString *str = [url path];
215 return [panel directory];
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 -------------------------------------------------------------------------- */
233 count = [menu numberOfItems];
234 for (i = 0; i<count; i++)
236 item = [menu itemAtIndex: i];
237 name = [[item title] UTF8String];
240 nameStr = build_string (name);
242 if ([item hasSubmenu])
244 old = interpret_services_menu ([item submenu],
245 Fcons (nameStr, prefix), old);
249 keys = [item keyEquivalent];
250 if (keys && [keys length] )
252 key = [keys characterAtIndex: 0];
253 res = make_number (key|super_modifier);
259 old = Fcons (Fcons (res,
260 Freverse (Fcons (nameStr,
270 /* ==========================================================================
272 Frame parameter setters
274 ========================================================================== */
278 x_set_foreground_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
281 EmacsCGFloat r, g, b, alpha;
283 if (ns_lisp_to_color (arg, &col))
285 store_frame_param (f, Qforeground_color, oldval);
286 error ("Unknown color");
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))
299 update_face_from_frame_parameter (f, Qforeground_color, arg);
300 /*recompute_basic_faces (f); */
301 if (FRAME_VISIBLE_P (f))
308 x_set_background_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
312 NSView *view = FRAME_NS_VIEW (f);
313 EmacsCGFloat r, g, b, alpha;
315 if (ns_lisp_to_color (arg, &col))
317 store_frame_param (f, Qbackground_color, oldval);
318 error ("Unknown color");
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))
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));
336 [[view window] setBackgroundColor: col];
338 if (alpha != (EmacsCGFloat) 1.0)
339 [[view window] setOpaque: NO];
341 [[view window] setOpaque: YES];
343 face = FRAME_DEFAULT_FACE (f);
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);
353 if (FRAME_VISIBLE_P (f))
360 x_set_cursor_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
364 if (ns_lisp_to_color (arg, &col))
366 store_frame_param (f, Qcursor_color, oldval);
367 error ("Unknown color");
370 [FRAME_CURSOR_COLOR (f) release];
371 FRAME_CURSOR_COLOR (f) = [col retain];
373 if (FRAME_VISIBLE_P (f))
375 x_update_cursor (f, 0);
376 x_update_cursor (f, 1);
378 update_face_from_frame_parameter (f, Qcursor_color, arg);
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 */
391 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
394 else if (!STRINGP (oldval) && EQ (oldval, Qnil) == EQ (arg, Qnil))
397 fset_icon_name (f, arg);
401 if (!NILP (f->title))
404 /* Explicit name and no icon-name -> explicit_name. */
405 if (f->explicit_name)
409 /* No explicit name and no icon-name ->
410 name has to be rebuild from icon_title_format. */
411 windows_or_buffers_changed = 62;
416 /* Don't change the name if it's already NAME. */
417 if ([[view window] miniwindowTitle]
418 && ([[[view window] miniwindowTitle]
419 isEqualToString: [NSString stringWithUTF8String:
423 [[view window] setMiniwindowTitle:
424 [NSString stringWithUTF8String: SSDATA (arg)]];
428 ns_set_name_internal (struct frame *f, Lisp_Object name)
431 Lisp_Object encoded_name, encoded_icon_name;
433 NSView *view = FRAME_NS_VIEW (f);
436 encoded_name = ENCODE_UTF_8 (name);
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;
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];
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. */
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);
474 else if (f->explicit_name)
478 name = build_string ([ns_app_name UTF8String]);
482 /* Don't change the name if it's already NAME. */
483 if (! NILP (Fstring_equal (name, f->name)))
488 /* Title overrides explicit name. */
489 if (! NILP (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
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
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);
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. */
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))
535 update_mode_lines = 22;
537 fset_title (f, name);
544 ns_set_name_internal (f, name);
549 ns_set_name_as_filename (struct frame *f)
552 Lisp_Object name, filename;
553 Lisp_Object buf = XWINDOW (f->selected_window)->contents;
555 NSAutoreleasePool *pool;
557 Lisp_Object encoded_name, encoded_filename;
559 NSTRACE (ns_set_name_as_filename);
561 if (f->explicit_name || ! NILP (f->title))
565 pool = [[NSAutoreleasePool alloc] init];
566 filename = BVAR (XBUFFER (buf), filename);
567 name = BVAR (XBUFFER (buf), name);
571 if (! NILP (filename))
572 name = Ffile_name_nondirectory (filename);
574 name = build_string ([ns_app_name UTF8String]);
578 encoded_name = ENCODE_UTF_8 (name);
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))))
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];
602 if (! NILP (filename))
605 encoded_filename = ENCODE_UTF_8 (filename);
608 fstr = [NSString stringWithUTF8String: SSDATA (encoded_filename)];
609 if (fstr == nil) fstr = @"";
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: @""];
621 [[view window] setRepresentedFilename: fstr];
622 [[view window] setTitle: str];
632 ns_set_doc_edited (struct frame *f, Lisp_Object arg)
634 NSView *view = FRAME_NS_VIEW (f);
635 NSAutoreleasePool *pool;
636 if (!MINI_WINDOW_P (XWINDOW (f->selected_window)))
639 pool = [[NSAutoreleasePool alloc] init];
640 [[view window] setDocumentEdited: !NILP (arg)];
648 x_set_menu_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
651 if (FRAME_MINIBUF_ONLY_P (f))
654 if (TYPE_RANGED_INTEGERP (int, value))
655 nlines = XINT (value);
659 FRAME_MENU_BAR_LINES (f) = 0;
662 FRAME_EXTERNAL_MENU_BAR (f) = 1;
663 /* does for all frames, whereas we just want for one frame
664 [NSMenu setMenuBarVisible: YES]; */
668 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
669 free_frame_menubar (f);
670 /* [NSMenu setMenuBarVisible: NO]; */
671 FRAME_EXTERNAL_MENU_BAR (f) = 0;
676 /* toolbar support */
678 x_set_tool_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
682 if (FRAME_MINIBUF_ONLY_P (f))
685 if (RANGED_INTEGERP (0, value, INT_MAX))
686 nlines = XFASTINT (value);
692 FRAME_EXTERNAL_TOOL_BAR (f) = 1;
693 update_frame_tool_bar (f);
697 if (FRAME_EXTERNAL_TOOL_BAR (f))
699 free_frame_tool_bar (f);
700 FRAME_EXTERNAL_TOOL_BAR (f) = 0;
704 x_set_window_size (f, 0, f->text_cols, f->text_lines, 0);
709 x_set_internal_border_width (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
711 int old_width = FRAME_INTERNAL_BORDER_WIDTH (f);
713 CHECK_TYPE_RANGED_INTEGER (int, arg);
714 FRAME_INTERNAL_BORDER_WIDTH (f) = XINT (arg);
715 if (FRAME_INTERNAL_BORDER_WIDTH (f) < 0)
716 FRAME_INTERNAL_BORDER_WIDTH (f) = 0;
718 if (FRAME_INTERNAL_BORDER_WIDTH (f) == old_width)
721 if (FRAME_X_WINDOW (f) != 0)
722 adjust_frame_size (f, -1, -1, 3, 0);
724 SET_FRAME_GARBAGED (f);
729 ns_implicitly_set_icon_type (struct frame *f)
732 EmacsView *view = FRAME_NS_VIEW (f);
734 Lisp_Object chain, elt;
735 NSAutoreleasePool *pool;
738 NSTRACE (ns_implicitly_set_icon_type);
741 pool = [[NSAutoreleasePool alloc] init];
742 if (f->output_data.ns->miniimage
743 && [[NSString stringWithUTF8String: SSDATA (f->name)]
744 isEqualToString: [(NSImage *)f->output_data.ns->miniimage name]])
751 tem = assq_no_quit (Qicon_type, f->param_alist);
752 if (CONSP (tem) && ! NILP (XCDR (tem)))
759 for (chain = Vns_icon_type_alist;
760 image == nil && CONSP (chain);
761 chain = XCDR (chain))
764 /* special case: 't' means go by file type */
765 if (SYMBOLP (elt) && EQ (elt, Qt) && SSDATA (f->name)[0] == '/')
768 = [NSString stringWithUTF8String: SSDATA (f->name)];
769 if ([[NSFileManager defaultManager] fileExistsAtPath: str])
770 image = [[[NSWorkspace sharedWorkspace] iconForFile: str] retain];
772 else if (CONSP (elt) &&
773 STRINGP (XCAR (elt)) &&
774 STRINGP (XCDR (elt)) &&
775 fast_string_match (XCAR (elt), f->name) >= 0)
777 image = [EmacsImage allocInitFromFile: XCDR (elt)];
779 image = [[NSImage imageNamed:
780 [NSString stringWithUTF8String:
781 SSDATA (XCDR (elt))]] retain];
787 image = [[[NSWorkspace sharedWorkspace] iconForFileType: @"text"] retain];
791 [f->output_data.ns->miniimage release];
792 f->output_data.ns->miniimage = image;
793 [view setMiniwindowImage: setMini];
800 x_set_icon_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
802 EmacsView *view = FRAME_NS_VIEW (f);
806 NSTRACE (x_set_icon_type);
808 if (!NILP (arg) && SYMBOLP (arg))
810 arg =build_string (SSDATA (SYMBOL_NAME (arg)));
811 store_frame_param (f, Qicon_type, arg);
814 /* do it the implicit way */
817 ns_implicitly_set_icon_type (f);
823 image = [EmacsImage allocInitFromFile: arg];
825 image =[NSImage imageNamed: [NSString stringWithUTF8String:
830 image = [NSImage imageNamed: @"text"];
834 f->output_data.ns->miniimage = image;
835 [view setMiniwindowImage: setMini];
839 /* TODO: move to nsterm? */
841 ns_lisp_to_cursor_type (Lisp_Object arg)
844 if (XTYPE (arg) == Lisp_String)
846 else if (XTYPE (arg) == Lisp_Symbol)
847 str = SSDATA (SYMBOL_NAME (arg));
849 if (!strcmp (str, "box")) return FILLED_BOX_CURSOR;
850 if (!strcmp (str, "hollow")) return HOLLOW_BOX_CURSOR;
851 if (!strcmp (str, "hbar")) return HBAR_CURSOR;
852 if (!strcmp (str, "bar")) return BAR_CURSOR;
853 if (!strcmp (str, "no")) return NO_CURSOR;
859 ns_cursor_type_to_lisp (int arg)
863 case FILLED_BOX_CURSOR: return Qbox;
864 case HOLLOW_BOX_CURSOR: return intern ("hollow");
865 case HBAR_CURSOR: return intern ("hbar");
866 case BAR_CURSOR: return intern ("bar");
868 default: return intern ("no");
872 /* This is the same as the xfns.c definition. */
874 x_set_cursor_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
876 set_frame_cursor_types (f, arg);
879 /* called to set mouse pointer color, but all other terms use it to
880 initialize pointer types (and don't set the color ;) */
882 x_set_mouse_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
884 /* don't think we can do this on Nextstep */
889 #define Xstr(x) Str(x)
892 ns_appkit_version_str (void)
896 #ifdef NS_IMPL_GNUSTEP
897 sprintf(tmp, "gnustep-gui-%s", Xstr(GNUSTEP_GUI_VERSION));
898 #elif defined (NS_IMPL_COCOA)
900 = [[NSProcessInfo processInfo] operatingSystemVersionString];
901 sprintf(tmp, "appkit-%.2f %s",
902 NSAppKitVersionNumber,
903 [osversion UTF8String]);
907 return build_string (tmp);
911 /* This is for use by x-server-version and collapses all version info we
912 have into a single int. For a better picture of the implementation
913 running, use ns_appkit_version_str.*/
915 ns_appkit_version_int (void)
917 #ifdef NS_IMPL_GNUSTEP
918 return GNUSTEP_GUI_MAJOR_VERSION * 100 + GNUSTEP_GUI_MINOR_VERSION;
919 #elif defined (NS_IMPL_COCOA)
920 return (int)NSAppKitVersionNumber;
927 x_icon (struct frame *f, Lisp_Object parms)
928 /* --------------------------------------------------------------------------
929 Strangely-named function to set icon position parameters in frame.
930 This is irrelevant under OS X, but might be needed under GNUstep,
931 depending on the window manager used. Note, this is not a standard
932 frame parameter-setter; it is called directly from x-create-frame.
933 -------------------------------------------------------------------------- */
935 Lisp_Object icon_x, icon_y;
936 struct ns_display_info *dpyinfo = check_ns_display_info (Qnil);
938 f->output_data.ns->icon_top = Qnil;
939 f->output_data.ns->icon_left = Qnil;
941 /* Set the position of the icon. */
942 icon_x = x_get_arg (dpyinfo, parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
943 icon_y = x_get_arg (dpyinfo, parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
944 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
946 CHECK_NUMBER (icon_x);
947 CHECK_NUMBER (icon_y);
948 f->output_data.ns->icon_top = icon_y;
949 f->output_data.ns->icon_left = icon_x;
951 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
952 error ("Both left and top icon corners of icon must be specified");
956 /* Note: see frame.c for template, also where generic functions are impl */
957 frame_parm_handler ns_frame_parm_handlers[] =
959 x_set_autoraise, /* generic OK */
960 x_set_autolower, /* generic OK */
961 x_set_background_color,
962 0, /* x_set_border_color, may be impossible under Nextstep */
963 0, /* x_set_border_width, may be impossible under Nextstep */
966 x_set_font, /* generic OK */
967 x_set_foreground_color,
970 x_set_internal_border_width, /* generic OK */
971 0, /* x_set_right_divider_width */
972 0, /* x_set_bottom_divider_width */
973 x_set_menu_bar_lines,
975 x_explicitly_set_name,
976 x_set_scroll_bar_width, /* generic OK */
977 x_set_scroll_bar_height, /* generic OK */
979 x_set_unsplittable, /* generic OK */
980 x_set_vertical_scroll_bars, /* generic OK */
981 x_set_horizontal_scroll_bars, /* generic OK */
982 x_set_visibility, /* generic OK */
983 x_set_tool_bar_lines,
984 0, /* x_set_scroll_bar_foreground, will ignore (not possible on NS) */
985 0, /* x_set_scroll_bar_background, will ignore (not possible on NS) */
986 x_set_screen_gamma, /* generic OK */
987 x_set_line_spacing, /* generic OK, sets f->extra_line_spacing to int */
988 x_set_left_fringe, /* generic OK */
989 x_set_right_fringe, /* generic OK */
990 0, /* x_set_wait_for_wm, will ignore */
991 x_set_fullscreen, /* generic OK */
992 x_set_font_backend, /* generic OK */
994 0, /* x_set_sticky */
995 0, /* x_set_tool_bar_position */
999 /* Handler for signals raised during x_create_frame.
1000 FRAME is the frame which is partially constructed. */
1003 unwind_create_frame (Lisp_Object frame)
1005 struct frame *f = XFRAME (frame);
1007 /* If frame is already dead, nothing to do. This can happen if the
1008 display is disconnected after the frame has become official, but
1009 before x_create_frame removes the unwind protect. */
1010 if (!FRAME_LIVE_P (f))
1013 /* If frame is ``official'', nothing to do. */
1014 if (NILP (Fmemq (frame, Vframe_list)))
1016 #if defined GLYPH_DEBUG && defined ENABLE_CHECKING
1017 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1020 x_free_frame_resources (f);
1024 /* Check that reference counts are indeed correct. */
1025 eassert (dpyinfo->terminal->image_cache->refcount == image_cache_refcount);
1031 * Read geometry related parameters from preferences if not in PARMS.
1032 * Returns the union of parms and any preferences read.
1036 get_geometry_from_preferences (struct ns_display_info *dpyinfo,
1044 { "width", "Width", Qwidth },
1045 { "height", "Height", Qheight },
1046 { "left", "Left", Qleft },
1047 { "top", "Top", Qtop },
1051 for (i = 0; i < ARRAYELTS (r); ++i)
1053 if (NILP (Fassq (r[i].tem, parms)))
1056 = x_get_arg (dpyinfo, parms, r[i].tem, r[i].val, r[i].cls,
1058 if (! EQ (value, Qunbound))
1059 parms = Fcons (Fcons (r[i].tem, value), parms);
1066 /* ==========================================================================
1070 ========================================================================== */
1072 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
1074 doc: /* Make a new Nextstep window, called a "frame" in Emacs terms.
1075 Return an Emacs frame object.
1076 PARMS is an alist of frame parameters.
1077 If the parameters specify that the frame should not have a minibuffer,
1078 and do not specify a specific minibuffer window to use,
1079 then `default-minibuffer-frame' must be a frame whose minibuffer can
1080 be shared by the new frame.
1082 This function is an internal primitive--use `make-frame' instead. */)
1086 Lisp_Object frame, tem;
1088 int minibuffer_only = 0;
1089 long window_prompting = 0;
1091 ptrdiff_t count = specpdl_ptr - specpdl;
1092 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1093 Lisp_Object display;
1094 struct ns_display_info *dpyinfo = NULL;
1097 static int desc_ctr = 1;
1099 /* x_get_arg modifies parms. */
1100 parms = Fcopy_alist (parms);
1102 /* Use this general default value to start with
1103 until we know if this frame has a specified name. */
1104 Vx_resource_name = Vinvocation_name;
1106 display = x_get_arg (dpyinfo, parms, Qterminal, 0, 0, RES_TYPE_STRING);
1107 if (EQ (display, Qunbound))
1109 dpyinfo = check_ns_display_info (display);
1110 kb = dpyinfo->terminal->kboard;
1112 if (!dpyinfo->terminal->name)
1113 error ("Terminal is not live, can't create new frames on it");
1115 name = x_get_arg (dpyinfo, parms, Qname, 0, 0, RES_TYPE_STRING);
1117 && ! EQ (name, Qunbound)
1119 error ("Invalid frame name--not a string or nil");
1122 Vx_resource_name = name;
1124 parent = x_get_arg (dpyinfo, parms, Qparent_id, 0, 0, RES_TYPE_NUMBER);
1125 if (EQ (parent, Qunbound))
1127 if (! NILP (parent))
1128 CHECK_NUMBER (parent);
1130 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
1131 /* No need to protect DISPLAY because that's not used after passing
1132 it to make_frame_without_minibuffer. */
1134 GCPRO4 (parms, parent, name, frame);
1135 tem = x_get_arg (dpyinfo, parms, Qminibuffer, "minibuffer", "Minibuffer",
1137 if (EQ (tem, Qnone) || NILP (tem))
1138 f = make_frame_without_minibuffer (Qnil, kb, display);
1139 else if (EQ (tem, Qonly))
1141 f = make_minibuffer_frame ();
1142 minibuffer_only = 1;
1144 else if (WINDOWP (tem))
1145 f = make_frame_without_minibuffer (tem, kb, display);
1149 XSETFRAME (frame, f);
1151 f->terminal = dpyinfo->terminal;
1153 f->output_method = output_ns;
1154 f->output_data.ns = xzalloc (sizeof *f->output_data.ns);
1156 FRAME_FONTSET (f) = -1;
1158 fset_icon_name (f, x_get_arg (dpyinfo, parms, Qicon_name,
1159 "iconName", "Title",
1161 if (! STRINGP (f->icon_name))
1162 fset_icon_name (f, Qnil);
1164 FRAME_DISPLAY_INFO (f) = dpyinfo;
1166 /* With FRAME_DISPLAY_INFO set up, this unwind-protect is safe. */
1167 record_unwind_protect (unwind_create_frame, frame);
1169 f->output_data.ns->window_desc = desc_ctr++;
1170 if (TYPE_RANGED_INTEGERP (Window, parent))
1172 f->output_data.ns->parent_desc = XFASTINT (parent);
1173 f->output_data.ns->explicit_parent = 1;
1177 f->output_data.ns->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
1178 f->output_data.ns->explicit_parent = 0;
1181 /* Set the name; the functions to which we pass f expect the name to
1183 if (EQ (name, Qunbound) || NILP (name) || ! STRINGP (name))
1185 fset_name (f, build_string ([ns_app_name UTF8String]));
1186 f->explicit_name = 0;
1190 fset_name (f, name);
1191 f->explicit_name = 1;
1192 specbind (Qx_resource_name, name);
1197 #ifdef NS_IMPL_COCOA
1198 mac_register_font_driver (f);
1200 register_font_driver (&nsfont_driver, f);
1203 x_default_parameter (f, parms, Qfont_backend, Qnil,
1204 "fontBackend", "FontBackend", RES_TYPE_STRING);
1207 /* use for default font name */
1208 id font = [NSFont userFixedPitchFontOfSize: -1.0]; /* default */
1209 x_default_parameter (f, parms, Qfontsize,
1210 make_number (0 /*(int)[font pointSize]*/),
1211 "fontSize", "FontSize", RES_TYPE_NUMBER);
1212 // Remove ' Regular', not handled by backends.
1213 char *fontname = xstrdup ([[font displayName] UTF8String]);
1214 int len = strlen (fontname);
1215 if (len > 8 && strcmp (fontname + len - 8, " Regular") == 0)
1216 fontname[len-8] = '\0';
1217 x_default_parameter (f, parms, Qfont,
1218 build_string (fontname),
1219 "font", "Font", RES_TYPE_STRING);
1224 x_default_parameter (f, parms, Qborder_width, make_number (0),
1225 "borderwidth", "BorderWidth", RES_TYPE_NUMBER);
1226 x_default_parameter (f, parms, Qinternal_border_width, make_number (2),
1227 "internalBorderWidth", "InternalBorderWidth",
1230 /* default vertical scrollbars on right on Mac */
1233 #ifdef NS_IMPL_GNUSTEP
1238 x_default_parameter (f, parms, Qvertical_scroll_bars, spos,
1239 "verticalScrollBars", "VerticalScrollBars",
1242 x_default_parameter (f, parms, Qhorizontal_scroll_bars, Qnil,
1243 "horizontalScrollBars", "HorizontalScrollBars",
1245 x_default_parameter (f, parms, Qforeground_color, build_string ("Black"),
1246 "foreground", "Foreground", RES_TYPE_STRING);
1247 x_default_parameter (f, parms, Qbackground_color, build_string ("White"),
1248 "background", "Background", RES_TYPE_STRING);
1249 /* FIXME: not supported yet in Nextstep */
1250 x_default_parameter (f, parms, Qline_spacing, Qnil,
1251 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
1252 x_default_parameter (f, parms, Qleft_fringe, Qnil,
1253 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
1254 x_default_parameter (f, parms, Qright_fringe, Qnil,
1255 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
1258 image_cache_refcount =
1259 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
1262 init_frame_faces (f);
1264 /* Read comment about this code in corresponding place in xfns.c. */
1265 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
1266 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 5, 1);
1268 /* The resources controlling the menu-bar and tool-bar are
1269 processed specially at startup, and reflected in the mode
1270 variables; ignore them here. */
1271 x_default_parameter (f, parms, Qmenu_bar_lines,
1272 NILP (Vmenu_bar_mode)
1273 ? make_number (0) : make_number (1),
1274 NULL, NULL, RES_TYPE_NUMBER);
1275 x_default_parameter (f, parms, Qtool_bar_lines,
1276 NILP (Vtool_bar_mode)
1277 ? make_number (0) : make_number (1),
1278 NULL, NULL, RES_TYPE_NUMBER);
1280 x_default_parameter (f, parms, Qbuffer_predicate, Qnil, "bufferPredicate",
1281 "BufferPredicate", RES_TYPE_SYMBOL);
1282 x_default_parameter (f, parms, Qtitle, Qnil, "title", "Title",
1285 parms = get_geometry_from_preferences (dpyinfo, parms);
1286 window_prompting = x_figure_window_size (f, parms, 1);
1288 tem = x_get_arg (dpyinfo, parms, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
1289 f->no_split = minibuffer_only || (!EQ (tem, Qunbound) && !EQ (tem, Qnil));
1291 /* NOTE: on other terms, this is done in set_mouse_color, however this
1292 was not getting called under Nextstep */
1293 f->output_data.ns->text_cursor = [NSCursor IBeamCursor];
1294 f->output_data.ns->nontext_cursor = [NSCursor arrowCursor];
1295 f->output_data.ns->modeline_cursor = [NSCursor pointingHandCursor];
1296 f->output_data.ns->hand_cursor = [NSCursor pointingHandCursor];
1297 f->output_data.ns->hourglass_cursor = [NSCursor disappearingItemCursor];
1298 f->output_data.ns->horizontal_drag_cursor = [NSCursor resizeLeftRightCursor];
1299 f->output_data.ns->vertical_drag_cursor = [NSCursor resizeUpDownCursor];
1300 FRAME_DISPLAY_INFO (f)->vertical_scroll_bar_cursor
1301 = [NSCursor arrowCursor];
1302 FRAME_DISPLAY_INFO (f)->horizontal_scroll_bar_cursor
1303 = [NSCursor arrowCursor];
1304 f->output_data.ns->current_pointer = f->output_data.ns->text_cursor;
1306 [[EmacsView alloc] initFrameFromEmacs: f];
1310 /* ns_display_info does not have a reference_count. */
1311 f->terminal->reference_count++;
1313 /* It is now ok to make the frame official even if we get an error below.
1314 The frame needs to be on Vframe_list or making it visible won't work. */
1315 Vframe_list = Fcons (frame, Vframe_list);
1317 x_default_parameter (f, parms, Qicon_type, Qnil,
1318 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
1320 x_default_parameter (f, parms, Qauto_raise, Qnil,
1321 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
1322 x_default_parameter (f, parms, Qauto_lower, Qnil,
1323 "autoLower", "AutoLower", RES_TYPE_BOOLEAN);
1324 x_default_parameter (f, parms, Qcursor_type, Qbox,
1325 "cursorType", "CursorType", RES_TYPE_SYMBOL);
1326 x_default_parameter (f, parms, Qscroll_bar_width, Qnil,
1327 "scrollBarWidth", "ScrollBarWidth",
1329 x_default_parameter (f, parms, Qscroll_bar_height, Qnil,
1330 "scrollBarHeight", "ScrollBarHeight",
1332 x_default_parameter (f, parms, Qalpha, Qnil,
1333 "alpha", "Alpha", RES_TYPE_NUMBER);
1334 x_default_parameter (f, parms, Qfullscreen, Qnil,
1335 "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
1337 /* Consider frame official, now. */
1340 adjust_frame_size (f, FRAME_TEXT_WIDTH (f), FRAME_TEXT_HEIGHT (f), 0, 1);
1342 if (! f->output_data.ns->explicit_parent)
1344 Lisp_Object visibility;
1346 visibility = x_get_arg (dpyinfo, parms, Qvisibility, 0, 0,
1348 if (EQ (visibility, Qunbound))
1351 if (EQ (visibility, Qicon))
1352 x_iconify_frame (f);
1353 else if (! NILP (visibility))
1355 x_make_frame_visible (f);
1356 [[FRAME_NS_VIEW (f) window] makeKeyWindow];
1360 /* Must have been Qnil. */
1364 if (FRAME_HAS_MINIBUF_P (f)
1365 && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
1366 || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
1367 kset_default_minibuffer_frame (kb, frame);
1369 /* All remaining specified parameters, which have not been "used"
1370 by x_get_arg and friends, now go in the misc. alist of the frame. */
1371 for (tem = parms; CONSP (tem); tem = XCDR (tem))
1372 if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
1373 fset_param_alist (f, Fcons (XCAR (tem), f->param_alist));
1377 if (window_prompting & USPosition)
1378 x_set_offset (f, f->left_pos, f->top_pos, 1);
1380 /* Make sure windows on this frame appear in calls to next-window
1381 and similar functions. */
1382 Vwindow_list = Qnil;
1384 return unbind_to (count, frame);
1388 x_focus_frame (struct frame *f)
1390 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
1392 if (dpyinfo->x_focus_frame != f)
1394 EmacsView *view = FRAME_NS_VIEW (f);
1396 [NSApp activateIgnoringOtherApps: YES];
1397 [[view window] makeKeyAndOrderFront: view];
1403 DEFUN ("ns-popup-font-panel", Fns_popup_font_panel, Sns_popup_font_panel,
1405 doc: /* Pop up the font panel. */)
1408 struct frame *f = decode_window_system_frame (frame);
1409 id fm = [NSFontManager sharedFontManager];
1410 struct font *font = f->output_data.ns->font;
1412 #ifdef NS_IMPL_GNUSTEP
1413 nsfont = ((struct nsfont_info *)font)->nsfont;
1415 #ifdef NS_IMPL_COCOA
1416 nsfont = (NSFont *) macfont_get_nsctfont (font);
1418 [fm setSelectedFont: nsfont isMultiple: NO];
1419 [fm orderFrontFontPanel: NSApp];
1424 DEFUN ("ns-popup-color-panel", Fns_popup_color_panel, Sns_popup_color_panel,
1426 doc: /* Pop up the color panel. */)
1429 check_window_system (NULL);
1430 [NSApp orderFrontColorPanel: NSApp];
1438 #ifdef NS_IMPL_GNUSTEP
1439 NSString *dirS, *initS;
1445 ns_run_file_dialog (void)
1447 if (ns_fd_data.panel == nil) return;
1448 #ifdef NS_IMPL_COCOA
1449 ns_fd_data.ret = [ns_fd_data.panel runModal];
1451 if (ns_fd_data.no_types)
1453 ns_fd_data.ret = [ns_fd_data.panel
1454 runModalForDirectory: ns_fd_data.dirS
1455 file: ns_fd_data.initS];
1459 ns_fd_data.ret = [ns_fd_data.panel
1460 runModalForDirectory: ns_fd_data.dirS
1461 file: ns_fd_data.initS
1465 ns_fd_data.panel = nil;
1468 DEFUN ("ns-read-file-name", Fns_read_file_name, Sns_read_file_name, 1, 5, 0,
1469 doc: /* Use a graphical panel to read a file name, using prompt PROMPT.
1470 Optional arg DIR, if non-nil, supplies a default directory.
1471 Optional arg MUSTMATCH, if non-nil, means the returned file or
1472 directory must exist.
1473 Optional arg INIT, if non-nil, provides a default file name to use.
1474 Optional arg DIR_ONLY_P, if non-nil, means choose only directories. */)
1475 (Lisp_Object prompt, Lisp_Object dir, Lisp_Object mustmatch,
1476 Lisp_Object init, Lisp_Object dir_only_p)
1478 static id fileDelegate = nil;
1480 BOOL isSave = NILP (mustmatch) && NILP (dir_only_p);
1484 NSString *promptS = NILP (prompt) || !STRINGP (prompt) ? nil :
1485 [NSString stringWithUTF8String: SSDATA (prompt)];
1486 NSString *dirS = NILP (dir) || !STRINGP (dir) ?
1487 [NSString stringWithUTF8String: SSDATA (BVAR (current_buffer, directory))] :
1488 [NSString stringWithUTF8String: SSDATA (dir)];
1489 NSString *initS = NILP (init) || !STRINGP (init) ? nil :
1490 [NSString stringWithUTF8String: SSDATA (init)];
1493 check_window_system (NULL);
1495 if (fileDelegate == nil)
1496 fileDelegate = [EmacsFileDelegate new];
1498 [NSCursor setHiddenUntilMouseMoves: NO];
1500 if ([dirS characterAtIndex: 0] == '~')
1501 dirS = [dirS stringByExpandingTildeInPath];
1504 (id)[EmacsSavePanel savePanel] : (id)[EmacsOpenPanel openPanel];
1506 [panel setTitle: promptS];
1508 [panel setAllowsOtherFileTypes: YES];
1509 [panel setTreatsFilePackagesAsDirectories: YES];
1510 [panel setDelegate: fileDelegate];
1512 if (! NILP (dir_only_p))
1514 [panel setCanChooseDirectories: YES];
1515 [panel setCanChooseFiles: NO];
1519 /* This is not quite what the documentation says, but it is compatible
1520 with the Gtk+ code. Also, the menu entry says "Open File...". */
1521 [panel setCanChooseDirectories: NO];
1522 [panel setCanChooseFiles: YES];
1526 ns_fd_data.panel = panel;
1527 ns_fd_data.ret = NO;
1528 #ifdef NS_IMPL_COCOA
1529 if (! NILP (mustmatch) || ! NILP (dir_only_p))
1530 [panel setAllowedFileTypes: nil];
1531 if (dirS) [panel setDirectoryURL: [NSURL fileURLWithPath: dirS]];
1532 if (initS && NILP (Ffile_directory_p (init)))
1533 [panel setNameFieldStringValue: [initS lastPathComponent]];
1535 [panel setNameFieldStringValue: @""];
1538 ns_fd_data.no_types = NILP (mustmatch) && NILP (dir_only_p);
1539 ns_fd_data.dirS = dirS;
1540 ns_fd_data.initS = initS;
1543 /* runModalForDirectory/runModal restarts the main event loop when done,
1544 so we must start an event loop and then pop up the file dialog.
1545 The file dialog may pop up a confirm dialog after Ok has been pressed,
1546 so we can not simply pop down on the Ok/Cancel press.
1548 nxev = [NSEvent otherEventWithType: NSApplicationDefined
1549 location: NSMakePoint (0, 0)
1552 windowNumber: [[NSApp mainWindow] windowNumber]
1553 context: [NSApp context]
1556 data2: NSAPP_DATA2_RUNFILEDIALOG];
1558 [NSApp postEvent: nxev atStart: NO];
1559 while (ns_fd_data.panel != nil)
1562 ret = (ns_fd_data.ret == NSOKButton);
1566 NSString *str = ns_filename_from_panel (panel);
1567 if (! str) str = ns_directory_from_panel (panel);
1568 if (! str) ret = NO;
1569 else fname = build_string ([str UTF8String]);
1572 [[FRAME_NS_VIEW (SELECTED_FRAME ()) window] makeKeyWindow];
1575 return ret ? fname : Qnil;
1579 ns_get_defaults_value (const char *key)
1581 NSObject *obj = [[NSUserDefaults standardUserDefaults]
1582 objectForKey: [NSString stringWithUTF8String: key]];
1584 if (!obj) return NULL;
1586 return [[NSString stringWithFormat: @"%@", obj] UTF8String];
1590 DEFUN ("ns-get-resource", Fns_get_resource, Sns_get_resource, 2, 2, 0,
1591 doc: /* Return the value of the property NAME of OWNER from the defaults database.
1592 If OWNER is nil, Emacs is assumed. */)
1593 (Lisp_Object owner, Lisp_Object name)
1597 check_window_system (NULL);
1599 owner = build_string([ns_app_name UTF8String]);
1600 CHECK_STRING (name);
1602 value = ns_get_defaults_value (SSDATA (name));
1605 return build_string (value);
1610 DEFUN ("ns-set-resource", Fns_set_resource, Sns_set_resource, 3, 3, 0,
1611 doc: /* Set property NAME of OWNER to VALUE, from the defaults database.
1612 If OWNER is nil, Emacs is assumed.
1613 If VALUE is nil, the default is removed. */)
1614 (Lisp_Object owner, Lisp_Object name, Lisp_Object value)
1616 check_window_system (NULL);
1618 owner = build_string ([ns_app_name UTF8String]);
1619 CHECK_STRING (name);
1622 [[NSUserDefaults standardUserDefaults] removeObjectForKey:
1623 [NSString stringWithUTF8String: SSDATA (name)]];
1627 CHECK_STRING (value);
1628 [[NSUserDefaults standardUserDefaults] setObject:
1629 [NSString stringWithUTF8String: SSDATA (value)]
1630 forKey: [NSString stringWithUTF8String:
1638 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
1639 Sx_server_max_request_size,
1641 doc: /* This function is a no-op. It is only present for completeness. */)
1642 (Lisp_Object terminal)
1644 check_ns_display_info (terminal);
1645 /* This function has no real equivalent under NeXTstep. Return nil to
1651 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
1652 doc: /* Return the "vendor ID" string of Nextstep display server TERMINAL.
1653 \(Labeling every distributor as a "vendor" embodies the false assumption
1654 that operating systems cannot be developed and distributed noncommercially.)
1655 The optional argument TERMINAL specifies which display to ask about.
1656 TERMINAL should be a terminal object, a frame or a display name (a string).
1657 If omitted or nil, that stands for the selected frame's display. */)
1658 (Lisp_Object terminal)
1660 check_ns_display_info (terminal);
1661 #ifdef NS_IMPL_GNUSTEP
1662 return build_string ("GNU");
1664 return build_string ("Apple");
1669 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
1670 doc: /* Return the version numbers of the server of display TERMINAL.
1671 The value is a list of three integers: the major and minor
1672 version numbers of the X Protocol in use, and the distributor-specific release
1673 number. See also the function `x-server-vendor'.
1675 The optional argument TERMINAL specifies which display to ask about.
1676 TERMINAL should be a terminal object, a frame or a display name (a string).
1677 If omitted or nil, that stands for the selected frame's display. */)
1678 (Lisp_Object terminal)
1680 check_ns_display_info (terminal);
1681 /*NOTE: it is unclear what would best correspond with "protocol";
1682 we return 10.3, meaning Panther, since this is roughly the
1683 level that GNUstep's APIs correspond to.
1684 The last number is where we distinguish between the Apple
1685 and GNUstep implementations ("distributor-specific release
1686 number") and give int'ized versions of major.minor. */
1687 return list3i (10, 3, ns_appkit_version_int ());
1691 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
1692 doc: /* Return the number of screens on Nextstep display server TERMINAL.
1693 The optional argument TERMINAL specifies which display to ask about.
1694 TERMINAL should be a terminal object, a frame or a display name (a string).
1695 If omitted or nil, that stands for the selected frame's display.
1697 Note: "screen" here is not in Nextstep terminology but in X11's. For
1698 the number of physical monitors, use `(length
1699 (display-monitor-attributes-list TERMINAL))' instead. */)
1700 (Lisp_Object terminal)
1702 check_ns_display_info (terminal);
1703 return make_number (1);
1707 DEFUN ("x-display-mm-height", Fx_display_mm_height, Sx_display_mm_height, 0, 1, 0,
1708 doc: /* Return the height in millimeters of the Nextstep display TERMINAL.
1709 The optional argument TERMINAL specifies which display to ask about.
1710 TERMINAL should be a terminal object, a frame or a display name (a string).
1711 If omitted or nil, that stands for the selected frame's display.
1713 On \"multi-monitor\" setups this refers to the height in millimeters for
1714 all physical monitors associated with TERMINAL. To get information
1715 for each physical monitor, use `display-monitor-attributes-list'. */)
1716 (Lisp_Object terminal)
1718 struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
1720 return make_number (x_display_pixel_height (dpyinfo) / (92.0/25.4));
1724 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
1725 doc: /* Return the width in millimeters of the Nextstep display TERMINAL.
1726 The optional argument TERMINAL specifies which display to ask about.
1727 TERMINAL should be a terminal object, a frame or a display name (a string).
1728 If omitted or nil, that stands for the selected frame's display.
1730 On \"multi-monitor\" setups this refers to the width in millimeters for
1731 all physical monitors associated with TERMINAL. To get information
1732 for each physical monitor, use `display-monitor-attributes-list'. */)
1733 (Lisp_Object terminal)
1735 struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
1737 return make_number (x_display_pixel_width (dpyinfo) / (92.0/25.4));
1741 DEFUN ("x-display-backing-store", Fx_display_backing_store,
1742 Sx_display_backing_store, 0, 1, 0,
1743 doc: /* Return an indication of whether the Nextstep display TERMINAL does backing store.
1744 The value may be `buffered', `retained', or `non-retained'.
1745 The optional argument TERMINAL specifies which display to ask about.
1746 TERMINAL should be a terminal object, a frame or a display name (a string).
1747 If omitted or nil, that stands for the selected frame's display. */)
1748 (Lisp_Object terminal)
1750 check_ns_display_info (terminal);
1751 switch ([ns_get_window (terminal) backingType])
1753 case NSBackingStoreBuffered:
1754 return intern ("buffered");
1755 case NSBackingStoreRetained:
1756 return intern ("retained");
1757 case NSBackingStoreNonretained:
1758 return intern ("non-retained");
1760 error ("Strange value for backingType parameter of frame");
1762 return Qnil; /* not reached, shut compiler up */
1766 DEFUN ("x-display-visual-class", Fx_display_visual_class,
1767 Sx_display_visual_class, 0, 1, 0,
1768 doc: /* Return the visual class of the Nextstep display TERMINAL.
1769 The value is one of the symbols `static-gray', `gray-scale',
1770 `static-color', `pseudo-color', `true-color', or `direct-color'.
1772 The optional argument TERMINAL specifies which display to ask about.
1773 TERMINAL should a terminal object, a frame or a display name (a string).
1774 If omitted or nil, that stands for the selected frame's display. */)
1775 (Lisp_Object terminal)
1777 NSWindowDepth depth;
1779 check_ns_display_info (terminal);
1780 depth = [[[NSScreen screens] objectAtIndex:0] depth];
1782 if ( depth == NSBestDepth (NSCalibratedWhiteColorSpace, 2, 2, YES, NULL))
1783 return intern ("static-gray");
1784 else if (depth == NSBestDepth (NSCalibratedWhiteColorSpace, 8, 8, YES, NULL))
1785 return intern ("gray-scale");
1786 else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 8, 8, YES, NULL))
1787 return intern ("pseudo-color");
1788 else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 4, 12, NO, NULL))
1789 return intern ("true-color");
1790 else if ( depth == NSBestDepth (NSCalibratedRGBColorSpace, 8, 24, NO, NULL))
1791 return intern ("direct-color");
1793 /* color mgmt as far as we do it is really handled by Nextstep itself anyway */
1794 return intern ("direct-color");
1798 DEFUN ("x-display-save-under", Fx_display_save_under,
1799 Sx_display_save_under, 0, 1, 0,
1800 doc: /* Return t if TERMINAL supports the save-under feature.
1801 The optional argument TERMINAL specifies which display to ask about.
1802 TERMINAL should be a terminal object, a frame or a display name (a string).
1803 If omitted or nil, that stands for the selected frame's display. */)
1804 (Lisp_Object terminal)
1806 check_ns_display_info (terminal);
1807 switch ([ns_get_window (terminal) backingType])
1809 case NSBackingStoreBuffered:
1812 case NSBackingStoreRetained:
1813 case NSBackingStoreNonretained:
1817 error ("Strange value for backingType parameter of frame");
1819 return Qnil; /* not reached, shut compiler up */
1823 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
1825 doc: /* Open a connection to a display server.
1826 DISPLAY is the name of the display to connect to.
1827 Optional second arg XRM-STRING is a string of resources in xrdb format.
1828 If the optional third arg MUST-SUCCEED is non-nil,
1829 terminate Emacs if we can't open the connection.
1830 \(In the Nextstep version, the last two arguments are currently ignored.) */)
1831 (Lisp_Object display, Lisp_Object resource_string, Lisp_Object must_succeed)
1833 struct ns_display_info *dpyinfo;
1835 CHECK_STRING (display);
1837 nxatoms_of_nsselect ();
1838 dpyinfo = ns_term_init (display);
1841 if (!NILP (must_succeed))
1842 fatal ("Display on %s not responding.\n",
1845 error ("Display on %s not responding.\n",
1853 DEFUN ("x-close-connection", Fx_close_connection, Sx_close_connection,
1855 doc: /* Close the connection to TERMINAL's Nextstep display server.
1856 For TERMINAL, specify a terminal object, a frame or a display name (a
1857 string). If TERMINAL is nil, that stands for the selected frame's
1859 (Lisp_Object terminal)
1861 check_ns_display_info (terminal);
1862 [NSApp terminate: NSApp];
1867 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
1868 doc: /* Return the list of display names that Emacs has connections to. */)
1871 Lisp_Object result = Qnil;
1872 struct ns_display_info *ndi;
1874 for (ndi = x_display_list; ndi; ndi = ndi->next)
1875 result = Fcons (XCAR (ndi->name_list_element), result);
1881 DEFUN ("ns-hide-others", Fns_hide_others, Sns_hide_others,
1883 doc: /* Hides all applications other than Emacs. */)
1886 check_window_system (NULL);
1887 [NSApp hideOtherApplications: NSApp];
1891 DEFUN ("ns-hide-emacs", Fns_hide_emacs, Sns_hide_emacs,
1893 doc: /* If ON is non-nil, the entire Emacs application is hidden.
1894 Otherwise if Emacs is hidden, it is unhidden.
1895 If ON is equal to `activate', Emacs is unhidden and becomes
1896 the active application. */)
1899 check_window_system (NULL);
1900 if (EQ (on, intern ("activate")))
1902 [NSApp unhide: NSApp];
1903 [NSApp activateIgnoringOtherApps: YES];
1906 [NSApp unhide: NSApp];
1908 [NSApp hide: NSApp];
1913 DEFUN ("ns-emacs-info-panel", Fns_emacs_info_panel, Sns_emacs_info_panel,
1915 doc: /* Shows the 'Info' or 'About' panel for Emacs. */)
1918 check_window_system (NULL);
1919 [NSApp orderFrontStandardAboutPanel: nil];
1924 DEFUN ("ns-font-name", Fns_font_name, Sns_font_name, 1, 1, 0,
1925 doc: /* Determine font PostScript or family name for font NAME.
1926 NAME should be a string containing either the font name or an XLFD
1927 font descriptor. If string contains `fontset' and not
1928 `fontset-startup', it is left alone. */)
1932 CHECK_STRING (name);
1937 if (strstr (nm, "fontset") && !strstr (nm, "fontset-startup"))
1940 return build_string (ns_xlfd_to_fontname (SSDATA (name)));
1944 DEFUN ("ns-list-colors", Fns_list_colors, Sns_list_colors, 0, 1, 0,
1945 doc: /* Return a list of all available colors.
1946 The optional argument FRAME is currently ignored. */)
1949 Lisp_Object list = Qnil;
1950 NSEnumerator *colorlists;
1955 CHECK_FRAME (frame);
1956 if (! FRAME_NS_P (XFRAME (frame)))
1957 error ("non-Nextstep frame used in `ns-list-colors'");
1962 colorlists = [[NSColorList availableColorLists] objectEnumerator];
1963 while ((clist = [colorlists nextObject]))
1965 if ([[clist name] length] < 7 ||
1966 [[clist name] rangeOfString: @"PANTONE"].location == 0)
1968 NSEnumerator *cnames = [[clist allKeys] reverseObjectEnumerator];
1970 while ((cname = [cnames nextObject]))
1971 list = Fcons (build_string ([cname UTF8String]), list);
1972 /* for (i = [[clist allKeys] count] - 1; i >= 0; i--)
1973 list = Fcons (build_string ([[[clist allKeys] objectAtIndex: i]
1974 UTF8String]), list); */
1984 DEFUN ("ns-list-services", Fns_list_services, Sns_list_services, 0, 0, 0,
1985 doc: /* List available Nextstep services by querying NSApp. */)
1988 #ifdef NS_IMPL_COCOA
1989 /* You can't get services like this in 10.6+. */
1992 Lisp_Object ret = Qnil;
1994 #ifdef NS_IMPL_COCOA
1998 check_window_system (NULL);
1999 svcs = [[NSMenu alloc] initWithTitle: @"Services"];
2000 [NSApp setServicesMenu: svcs];
2001 [NSApp registerServicesMenuSendTypes: ns_send_types
2002 returnTypes: ns_return_types];
2004 /* On Tiger, services menu updating was made lazier (waits for user to
2005 actually click on the menu), so we have to force things along: */
2006 #ifdef NS_IMPL_COCOA
2007 delegate = [svcs delegate];
2008 if (delegate != nil)
2010 if ([delegate respondsToSelector: @selector (menuNeedsUpdate:)])
2011 [delegate menuNeedsUpdate: svcs];
2012 if ([delegate respondsToSelector:
2013 @selector (menu:updateItem:atIndex:shouldCancel:)])
2015 int i, len = [delegate numberOfItemsInMenu: svcs];
2016 for (i =0; i<len; i++)
2017 [svcs addItemWithTitle: @"" action: NULL keyEquivalent: @""];
2018 for (i =0; i<len; i++)
2019 if (![delegate menu: svcs
2020 updateItem: (NSMenuItem *)[svcs itemAtIndex: i]
2021 atIndex: i shouldCancel: NO])
2027 [svcs setAutoenablesItems: NO];
2028 #ifdef NS_IMPL_COCOA
2029 [svcs update]; /* on OS X, converts from '/' structure */
2032 ret = interpret_services_menu (svcs, Qnil, ret);
2038 DEFUN ("ns-perform-service", Fns_perform_service, Sns_perform_service,
2040 doc: /* Perform Nextstep SERVICE on SEND.
2041 SEND should be either a string or nil.
2042 The return value is the result of the service, as string, or nil if
2043 there was no result. */)
2044 (Lisp_Object service, Lisp_Object send)
2050 CHECK_STRING (service);
2051 check_window_system (NULL);
2053 utfStr = SSDATA (service);
2054 svcName = [NSString stringWithUTF8String: utfStr];
2056 pb =[NSPasteboard pasteboardWithUniqueName];
2057 ns_string_to_pasteboard (pb, send);
2059 if (NSPerformService (svcName, pb) == NO)
2060 Fsignal (Qquit, list1 (build_string ("service not available")));
2062 if ([[pb types] count] == 0)
2063 return build_string ("");
2064 return ns_string_from_pasteboard (pb);
2068 DEFUN ("ns-convert-utf8-nfd-to-nfc", Fns_convert_utf8_nfd_to_nfc,
2069 Sns_convert_utf8_nfd_to_nfc, 1, 1, 0,
2070 doc: /* Return an NFC string that matches the UTF-8 NFD string STR. */)
2073 /* TODO: If GNUstep ever implements precomposedStringWithCanonicalMapping,
2076 Lisp_Object ret = Qnil;
2077 NSAutoreleasePool *pool;
2080 pool = [[NSAutoreleasePool alloc] init];
2081 utfStr = [NSString stringWithUTF8String: SSDATA (str)];
2082 #ifdef NS_IMPL_COCOA
2084 utfStr = [utfStr precomposedStringWithCanonicalMapping];
2088 const char *cstr = [utfStr UTF8String];
2090 ret = build_string (cstr);
2095 error ("Invalid UTF-8");
2101 #ifdef NS_IMPL_COCOA
2103 /* Compile and execute the AppleScript SCRIPT and return the error
2104 status as function value. A zero is returned if compilation and
2105 execution is successful, in which case *RESULT is set to a Lisp
2106 string or a number containing the resulting script value. Otherwise,
2109 ns_do_applescript (Lisp_Object script, Lisp_Object *result)
2111 NSAppleEventDescriptor *desc;
2112 NSDictionary* errorDict;
2113 NSAppleEventDescriptor* returnDescriptor = NULL;
2115 NSAppleScript* scriptObject =
2116 [[NSAppleScript alloc] initWithSource:
2117 [NSString stringWithUTF8String: SSDATA (script)]];
2119 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
2120 [scriptObject release];
2123 if (returnDescriptor != NULL)
2125 // successful execution
2126 if (kAENullEvent != [returnDescriptor descriptorType])
2129 // script returned an AppleScript result
2130 if ((typeUnicodeText == [returnDescriptor descriptorType]) ||
2131 #if defined (NS_IMPL_COCOA)
2132 (typeUTF16ExternalRepresentation
2133 == [returnDescriptor descriptorType]) ||
2135 (typeUTF8Text == [returnDescriptor descriptorType]) ||
2136 (typeCString == [returnDescriptor descriptorType]))
2138 desc = [returnDescriptor coerceToDescriptorType: typeUTF8Text];
2140 *result = build_string([[desc stringValue] UTF8String]);
2144 /* use typeUTF16ExternalRepresentation? */
2145 // coerce the result to the appropriate ObjC type
2146 desc = [returnDescriptor coerceToDescriptorType: typeUTF8Text];
2148 *result = make_number([desc int32Value]);
2154 // no script result, return error
2160 /* Helper function called from sendEvent to run applescript
2161 from within the main event loop. */
2164 ns_run_ascript (void)
2166 if (! NILP (as_script))
2167 as_status = ns_do_applescript (as_script, as_result);
2171 DEFUN ("ns-do-applescript", Fns_do_applescript, Sns_do_applescript, 1, 1, 0,
2172 doc: /* Execute AppleScript SCRIPT and return the result.
2173 If compilation and execution are successful, the resulting script value
2174 is returned as a string, a number or, in the case of other constructs, t.
2175 In case the execution fails, an error is signaled. */)
2176 (Lisp_Object script)
2181 struct input_event ev;
2183 CHECK_STRING (script);
2184 check_window_system (NULL);
2189 as_result = &result;
2191 /* executing apple script requires the event loop to run, otherwise
2192 errors aren't returned and executeAndReturnError hangs forever.
2193 Post an event that runs applescript and then start the event loop.
2194 The event loop is exited when the script is done. */
2195 nxev = [NSEvent otherEventWithType: NSApplicationDefined
2196 location: NSMakePoint (0, 0)
2199 windowNumber: [[NSApp mainWindow] windowNumber]
2200 context: [NSApp context]
2203 data2: NSAPP_DATA2_RUNASSCRIPT];
2205 [NSApp postEvent: nxev atStart: NO];
2207 // If there are other events, the event loop may exit. Keep running
2208 // until the script has been handled. */
2209 ns_init_events (&ev);
2210 while (! NILP (as_script))
2212 ns_finish_events ();
2220 else if (!STRINGP (result))
2221 error ("AppleScript error %d", status);
2223 error ("%s", SSDATA (result));
2229 /* ==========================================================================
2231 Miscellaneous functions not called through hooks
2233 ========================================================================== */
2235 /* called from frame.c */
2236 struct ns_display_info *
2237 check_x_display_info (Lisp_Object frame)
2239 return check_ns_display_info (frame);
2244 x_set_scroll_bar_default_width (struct frame *f)
2246 int wid = FRAME_COLUMN_WIDTH (f);
2247 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = NS_SCROLL_BAR_WIDTH_DEFAULT;
2248 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) +
2253 x_set_scroll_bar_default_height (struct frame *f)
2255 int height = FRAME_LINE_HEIGHT (f);
2256 FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) = NS_SCROLL_BAR_WIDTH_DEFAULT;
2257 FRAME_CONFIG_SCROLL_BAR_LINES (f) = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) +
2258 height - 1) / height;
2261 /* terms impl this instead of x-get-resource directly */
2263 x_get_string_resource (XrmDatabase rdb, const char *name, const char *class)
2265 /* remove appname prefix; TODO: allow for !="Emacs" */
2266 const char *res, *toCheck = class + (!strncmp (class, "Emacs.", 6) ? 6 : 0);
2268 check_window_system (NULL);
2270 if (inhibit_x_resources)
2271 /* --quick was passed, so this is a no-op. */
2274 res = ns_get_defaults_value (toCheck);
2275 return (!res ? NULL :
2276 (!c_strncasecmp (res, "YES", 3) ? "true" :
2277 (!c_strncasecmp (res, "NO", 2) ? "false" : (char *) res)));
2282 x_get_focus_frame (struct frame *frame)
2284 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
2285 Lisp_Object nsfocus;
2287 if (!dpyinfo->x_focus_frame)
2290 XSETFRAME (nsfocus, dpyinfo->x_focus_frame);
2294 /* ==========================================================================
2296 Lisp definitions that, for whatever reason, we can't alias as 'ns-XXX'.
2298 ========================================================================== */
2301 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
2302 doc: /* Internal function called by `color-defined-p', which see.
2303 \(Note that the Nextstep version of this function ignores FRAME.) */)
2304 (Lisp_Object color, Lisp_Object frame)
2307 check_window_system (NULL);
2308 return ns_lisp_to_color (color, &col) ? Qnil : Qt;
2312 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
2313 doc: /* Internal function called by `color-values', which see. */)
2314 (Lisp_Object color, Lisp_Object frame)
2317 EmacsCGFloat red, green, blue, alpha;
2319 check_window_system (NULL);
2320 CHECK_STRING (color);
2322 if (ns_lisp_to_color (color, &col))
2325 [[col colorUsingDefaultColorSpace]
2326 getRed: &red green: &green blue: &blue alpha: &alpha];
2327 return list3i (lrint (red * 65280), lrint (green * 65280),
2328 lrint (blue * 65280));
2332 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
2333 doc: /* Internal function called by `display-color-p', which see. */)
2334 (Lisp_Object terminal)
2336 NSWindowDepth depth;
2337 NSString *colorSpace;
2339 check_ns_display_info (terminal);
2340 depth = [[[NSScreen screens] objectAtIndex:0] depth];
2341 colorSpace = NSColorSpaceFromDepth (depth);
2343 return [colorSpace isEqualToString: NSDeviceWhiteColorSpace]
2344 || [colorSpace isEqualToString: NSCalibratedWhiteColorSpace]
2349 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p, Sx_display_grayscale_p,
2351 doc: /* Return t if the Nextstep display supports shades of gray.
2352 Note that color displays do support shades of gray.
2353 The optional argument TERMINAL specifies which display to ask about.
2354 TERMINAL should be a terminal object, a frame or a display name (a string).
2355 If omitted or nil, that stands for the selected frame's display. */)
2356 (Lisp_Object terminal)
2358 NSWindowDepth depth;
2360 check_ns_display_info (terminal);
2361 depth = [[[NSScreen screens] objectAtIndex:0] depth];
2363 return NSBitsPerPixelFromDepth (depth) > 1 ? Qt : Qnil;
2367 DEFUN ("x-display-pixel-width", Fx_display_pixel_width, Sx_display_pixel_width,
2369 doc: /* Return the width in pixels of the Nextstep display TERMINAL.
2370 The optional argument TERMINAL specifies which display to ask about.
2371 TERMINAL should be a terminal object, a frame or a display name (a string).
2372 If omitted or nil, that stands for the selected frame's display.
2374 On \"multi-monitor\" setups this refers to the pixel width for all
2375 physical monitors associated with TERMINAL. To get information for
2376 each physical monitor, use `display-monitor-attributes-list'. */)
2377 (Lisp_Object terminal)
2379 struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
2381 return make_number (x_display_pixel_width (dpyinfo));
2385 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
2386 Sx_display_pixel_height, 0, 1, 0,
2387 doc: /* Return the height in pixels of the Nextstep display TERMINAL.
2388 The optional argument TERMINAL specifies which display to ask about.
2389 TERMINAL should be a terminal object, a frame or a display name (a string).
2390 If omitted or nil, that stands for the selected frame's display.
2392 On \"multi-monitor\" setups this refers to the pixel height for all
2393 physical monitors associated with TERMINAL. To get information for
2394 each physical monitor, use `display-monitor-attributes-list'. */)
2395 (Lisp_Object terminal)
2397 struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
2399 return make_number (x_display_pixel_height (dpyinfo));
2402 #ifdef NS_IMPL_COCOA
2404 /* Returns the name for the screen that OBJ represents, or NULL.
2405 Caller must free return value.
2409 ns_get_name_from_ioreg (io_object_t obj)
2413 NSDictionary *info = (NSDictionary *)
2414 IODisplayCreateInfoDictionary (obj, kIODisplayOnlyPreferredName);
2415 NSDictionary *names = [info objectForKey:
2416 [NSString stringWithUTF8String:
2417 kDisplayProductName]];
2419 if ([names count] > 0)
2421 NSString *n = [names objectForKey: [[names allKeys]
2423 if (n != nil) name = xstrdup ([n UTF8String]);
2431 /* Returns the name for the screen that DID came from, or NULL.
2432 Caller must free return value.
2436 ns_screen_name (CGDirectDisplayID did)
2440 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
2441 mach_port_t masterPort;
2445 // CGDisplayIOServicePort is deprecated. Do it another (harder) way.
2447 if (IOMasterPort (MACH_PORT_NULL, &masterPort) != kIOReturnSuccess
2448 || IOServiceGetMatchingServices (masterPort,
2449 IOServiceMatching ("IONDRVDevice"),
2450 &it) != kIOReturnSuccess)
2453 /* Must loop until we find a name. Many devices can have the same unit
2454 number (represents different GPU parts), but only one has a name. */
2455 while (! name && (obj = IOIteratorNext (it)))
2457 CFMutableDictionaryRef props;
2460 if (IORegistryEntryCreateCFProperties (obj,
2462 kCFAllocatorDefault,
2463 kNilOptions) == kIOReturnSuccess
2465 && (val = CFDictionaryGetValue(props, @"IOFBDependentIndex")))
2467 unsigned nr = [(NSNumber *)val unsignedIntegerValue];
2468 if (nr == CGDisplayUnitNumber (did))
2469 name = ns_get_name_from_ioreg (obj);
2473 IOObjectRelease (obj);
2476 IOObjectRelease (it);
2480 name = ns_get_name_from_ioreg (CGDisplayIOServicePort (did));
2488 ns_make_monitor_attribute_list (struct MonitorInfo *monitors,
2490 int primary_monitor,
2493 Lisp_Object monitor_frames = Fmake_vector (make_number (n_monitors), Qnil);
2494 Lisp_Object frame, rest;
2495 NSArray *screens = [NSScreen screens];
2498 FOR_EACH_FRAME (rest, frame)
2500 struct frame *f = XFRAME (frame);
2504 NSView *view = FRAME_NS_VIEW (f);
2505 NSScreen *screen = [[view window] screen];
2509 for (k = 0; i == -1 && k < [screens count]; ++k)
2511 if ([screens objectAtIndex: k] == screen)
2516 ASET (monitor_frames, i, Fcons (frame, AREF (monitor_frames, i)));
2520 return make_monitor_attribute_list (monitors, n_monitors, primary_monitor,
2521 monitor_frames, source);
2524 DEFUN ("ns-display-monitor-attributes-list",
2525 Fns_display_monitor_attributes_list,
2526 Sns_display_monitor_attributes_list,
2528 doc: /* Return a list of physical monitor attributes on the X display TERMINAL.
2530 The optional argument TERMINAL specifies which display to ask about.
2531 TERMINAL should be a terminal object, a frame or a display name (a string).
2532 If omitted or nil, that stands for the selected frame's display.
2534 In addition to the standard attribute keys listed in
2535 `display-monitor-attributes-list', the following keys are contained in
2538 source -- String describing the source from which multi-monitor
2539 information is obtained, \"NS\" is always the source."
2541 Internal use only, use `display-monitor-attributes-list' instead. */)
2542 (Lisp_Object terminal)
2544 struct terminal *term = decode_live_terminal (terminal);
2546 NSUInteger i, n_monitors;
2547 struct MonitorInfo *monitors;
2548 Lisp_Object attributes_list = Qnil;
2549 CGFloat primary_display_height = 0;
2551 if (term->type != output_ns)
2554 screens = [NSScreen screens];
2555 n_monitors = [screens count];
2556 if (n_monitors == 0)
2559 monitors = xzalloc (n_monitors * sizeof *monitors);
2561 for (i = 0; i < [screens count]; ++i)
2563 NSScreen *s = [screens objectAtIndex:i];
2564 struct MonitorInfo *m = &monitors[i];
2565 NSRect fr = [s frame];
2566 NSRect vfr = [s visibleFrame];
2569 #ifdef NS_IMPL_COCOA
2570 NSDictionary *dict = [s deviceDescription];
2571 NSNumber *nid = [dict objectForKey:@"NSScreenNumber"];
2572 CGDirectDisplayID did = [nid unsignedIntValue];
2576 primary_display_height = fr.size.height;
2577 y = (short) fr.origin.y;
2578 vy = (short) vfr.origin.y;
2582 // Flip y coordinate as NS has y starting from the bottom.
2583 y = (short) (primary_display_height - fr.size.height - fr.origin.y);
2584 vy = (short) (primary_display_height -
2585 vfr.size.height - vfr.origin.y);
2588 m->geom.x = (short) fr.origin.x;
2590 m->geom.width = (unsigned short) fr.size.width;
2591 m->geom.height = (unsigned short) fr.size.height;
2593 m->work.x = (short) vfr.origin.x;
2594 // y is flipped on NS, so vy - y are pixels missing at the bottom,
2595 // and fr.size.height - vfr.size.height are pixels missing in total.
2596 // Pixels missing at top are
2597 // fr.size.height - vfr.size.height - vy + y.
2598 // work.y is then pixels missing at top + y.
2599 m->work.y = (short) (fr.size.height - vfr.size.height) - vy + y + y;
2600 m->work.width = (unsigned short) vfr.size.width;
2601 m->work.height = (unsigned short) vfr.size.height;
2603 #ifdef NS_IMPL_COCOA
2604 m->name = ns_screen_name (did);
2607 CGSize mms = CGDisplayScreenSize (did);
2608 m->mm_width = (int) mms.width;
2609 m->mm_height = (int) mms.height;
2613 // Assume 92 dpi as x-display-mm-height/x-display-mm-width does.
2614 m->mm_width = (int) (25.4 * fr.size.width / 92.0);
2615 m->mm_height = (int) (25.4 * fr.size.height / 92.0);
2619 // Primary monitor is always first for NS.
2620 attributes_list = ns_make_monitor_attribute_list (monitors, n_monitors,
2623 free_monitors (monitors, n_monitors);
2624 return attributes_list;
2628 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
2630 doc: /* Return the number of bitplanes of the Nextstep display TERMINAL.
2631 The optional argument TERMINAL specifies which display to ask about.
2632 TERMINAL should be a terminal object, a frame or a display name (a string).
2633 If omitted or nil, that stands for the selected frame's display. */)
2634 (Lisp_Object terminal)
2636 check_ns_display_info (terminal);
2638 (NSBitsPerPixelFromDepth ([[[NSScreen screens] objectAtIndex:0] depth]));
2642 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
2644 doc: /* Returns the number of color cells of the Nextstep display TERMINAL.
2645 The optional argument TERMINAL specifies which display to ask about.
2646 TERMINAL should be a terminal object, a frame or a display name (a string).
2647 If omitted or nil, that stands for the selected frame's display. */)
2648 (Lisp_Object terminal)
2650 struct ns_display_info *dpyinfo = check_ns_display_info (terminal);
2651 /* We force 24+ bit depths to 24-bit to prevent an overflow. */
2652 return make_number (1 << min (dpyinfo->n_planes, 24));
2656 /* Unused dummy def needed for compatibility. */
2657 Lisp_Object tip_frame;
2659 /* TODO: move to xdisp or similar */
2661 compute_tip_xy (struct frame *f,
2670 Lisp_Object left, top;
2671 EmacsView *view = FRAME_NS_VIEW (f);
2672 struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
2675 /* Start with user-specified or mouse position. */
2676 left = Fcdr (Fassq (Qleft, parms));
2677 top = Fcdr (Fassq (Qtop, parms));
2679 if (!INTEGERP (left) || !INTEGERP (top))
2681 pt.x = dpyinfo->last_mouse_motion_x;
2682 pt.y = dpyinfo->last_mouse_motion_y;
2683 /* Convert to screen coordinates */
2684 pt = [view convertPoint: pt toView: nil];
2685 pt = [[view window] convertBaseToScreen: pt];
2689 /* Absolute coordinates. */
2691 pt.y = x_display_pixel_height (FRAME_DISPLAY_INFO (f)) - XINT (top)
2695 /* Ensure in bounds. (Note, screen origin = lower left.) */
2696 if (INTEGERP (left))
2698 else if (pt.x + XINT (dx) <= 0)
2699 *root_x = 0; /* Can happen for negative dx */
2700 else if (pt.x + XINT (dx) + width
2701 <= x_display_pixel_width (FRAME_DISPLAY_INFO (f)))
2702 /* It fits to the right of the pointer. */
2703 *root_x = pt.x + XINT (dx);
2704 else if (width + XINT (dx) <= pt.x)
2705 /* It fits to the left of the pointer. */
2706 *root_x = pt.x - width - XINT (dx);
2708 /* Put it left justified on the screen -- it ought to fit that way. */
2713 else if (pt.y - XINT (dy) - height >= 0)
2714 /* It fits below the pointer. */
2715 *root_y = pt.y - height - XINT (dy);
2716 else if (pt.y + XINT (dy) + height
2717 <= x_display_pixel_height (FRAME_DISPLAY_INFO (f)))
2718 /* It fits above the pointer */
2719 *root_y = pt.y + XINT (dy);
2721 /* Put it on the top. */
2722 *root_y = x_display_pixel_height (FRAME_DISPLAY_INFO (f)) - height;
2726 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
2727 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
2728 A tooltip window is a small window displaying a string.
2730 This is an internal function; Lisp code should call `tooltip-show'.
2732 FRAME nil or omitted means use the selected frame.
2734 PARMS is an optional list of frame parameters which can be used to
2735 change the tooltip's appearance.
2737 Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
2738 means use the default timeout of 5 seconds.
2740 If the list of frame parameters PARMS contains a `left' parameter,
2741 the tooltip is displayed at that x-position. Otherwise it is
2742 displayed at the mouse position, with offset DX added (default is 5 if
2743 DX isn't specified). Likewise for the y-position; if a `top' frame
2744 parameter is specified, it determines the y-position of the tooltip
2745 window, otherwise it is displayed at the mouse position, with offset
2746 DY added (default is -10).
2748 A tooltip's maximum size is specified by `x-max-tooltip-size'.
2749 Text larger than the specified size is clipped. */)
2750 (Lisp_Object string, Lisp_Object frame, Lisp_Object parms, Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
2753 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2754 ptrdiff_t count = SPECPDL_INDEX ();
2759 specbind (Qinhibit_redisplay, Qt);
2761 GCPRO4 (string, parms, frame, timeout);
2763 CHECK_STRING (string);
2764 str = SSDATA (string);
2765 f = decode_window_system_frame (frame);
2767 timeout = make_number (5);
2769 CHECK_NATNUM (timeout);
2772 dx = make_number (5);
2777 dy = make_number (-10);
2782 if (ns_tooltip == nil)
2783 ns_tooltip = [[EmacsTooltip alloc] init];
2787 [ns_tooltip setText: str];
2788 size = [ns_tooltip frame].size;
2790 /* Move the tooltip window where the mouse pointer is. Resize and
2792 compute_tip_xy (f, parms, dx, dy, (int)size.width, (int)size.height,
2795 [ns_tooltip showAtX: root_x Y: root_y for: XINT (timeout)];
2799 return unbind_to (count, Qnil);
2803 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
2804 doc: /* Hide the current tooltip window, if there is any.
2805 Value is t if tooltip was open, nil otherwise. */)
2808 if (ns_tooltip == nil || ![ns_tooltip isActive])
2815 /* ==========================================================================
2817 Class implementations
2819 ========================================================================== */
2822 Handle arrow/function/control keys and copy/paste/cut in file dialogs.
2823 Return YES if handled, NO if not.
2826 handlePanelKeys (NSSavePanel *panel, NSEvent *theEvent)
2832 if ([theEvent type] != NSKeyDown) return NO;
2833 s = [theEvent characters];
2835 for (i = 0; i < [s length]; ++i)
2837 int ch = (int) [s characterAtIndex: i];
2840 case NSHomeFunctionKey:
2841 case NSDownArrowFunctionKey:
2842 case NSUpArrowFunctionKey:
2843 case NSLeftArrowFunctionKey:
2844 case NSRightArrowFunctionKey:
2845 case NSPageUpFunctionKey:
2846 case NSPageDownFunctionKey:
2847 case NSEndFunctionKey:
2848 /* Don't send command modified keys, as those are handled in the
2849 performKeyEquivalent method of the super class.
2851 if (! ([theEvent modifierFlags] & NSCommandKeyMask))
2853 [panel sendEvent: theEvent];
2857 /* As we don't have the standard key commands for
2858 copy/paste/cut/select-all in our edit menu, we must handle
2859 them here. TODO: handle Emacs key bindings for copy/cut/select-all
2860 here, paste works, because we have that in our Edit menu.
2861 I.e. refactor out code in nsterm.m, keyDown: to figure out the
2867 case 'a': // Select all
2868 if ([theEvent modifierFlags] & NSCommandKeyMask)
2877 : @selector(selectAll:))))
2882 // Send all control keys, as the text field supports C-a, C-f, C-e
2884 if ([theEvent modifierFlags] & NSControlKeyMask)
2886 [panel sendEvent: theEvent];
2897 @implementation EmacsSavePanel
2898 - (BOOL)performKeyEquivalent:(NSEvent *)theEvent
2900 BOOL ret = handlePanelKeys (self, theEvent);
2902 ret = [super performKeyEquivalent:theEvent];
2908 @implementation EmacsOpenPanel
2909 - (BOOL)performKeyEquivalent:(NSEvent *)theEvent
2911 // NSOpenPanel inherits NSSavePanel, so passing self is OK.
2912 BOOL ret = handlePanelKeys (self, theEvent);
2914 ret = [super performKeyEquivalent:theEvent];
2920 @implementation EmacsFileDelegate
2921 /* --------------------------------------------------------------------------
2922 Delegate methods for Open/Save panels
2923 -------------------------------------------------------------------------- */
2924 - (BOOL)panel: (id)sender isValidFilename: (NSString *)filename
2928 - (BOOL)panel: (id)sender shouldShowFilename: (NSString *)filename
2932 - (NSString *)panel: (id)sender userEnteredFilename: (NSString *)filename
2933 confirmed: (BOOL)okFlag
2942 /* ==========================================================================
2944 Lisp interface declaration
2946 ========================================================================== */
2950 syms_of_nsfns (void)
2952 Qfontsize = intern_c_string ("fontsize");
2953 staticpro (&Qfontsize);
2955 DEFVAR_LISP ("ns-icon-type-alist", Vns_icon_type_alist,
2956 doc: /* Alist of elements (REGEXP . IMAGE) for images of icons associated to frames.
2957 If the title of a frame matches REGEXP, then IMAGE.tiff is
2958 selected as the image of the icon representing the frame when it's
2959 miniaturized. If an element is t, then Emacs tries to select an icon
2960 based on the filetype of the visited file.
2962 The images have to be installed in a folder called English.lproj in the
2963 Emacs folder. You have to restart Emacs after installing new icons.
2965 Example: Install an icon Gnus.tiff and execute the following code
2967 (setq ns-icon-type-alist
2968 (append ns-icon-type-alist
2969 '((\"^\\\\*\\\\(Group\\\\*$\\\\|Summary \\\\|Article\\\\*$\\\\)\"
2972 When you miniaturize a Group, Summary or Article frame, Gnus.tiff will
2973 be used as the image of the icon representing the frame. */);
2974 Vns_icon_type_alist = list1 (Qt);
2976 DEFVAR_LISP ("ns-version-string", Vns_version_string,
2977 doc: /* Toolkit version for NS Windowing. */);
2978 Vns_version_string = ns_appkit_version_str ();
2980 defsubr (&Sns_read_file_name);
2981 defsubr (&Sns_get_resource);
2982 defsubr (&Sns_set_resource);
2983 defsubr (&Sxw_display_color_p); /* this and next called directly by C code */
2984 defsubr (&Sx_display_grayscale_p);
2985 defsubr (&Sns_font_name);
2986 defsubr (&Sns_list_colors);
2987 #ifdef NS_IMPL_COCOA
2988 defsubr (&Sns_do_applescript);
2990 defsubr (&Sxw_color_defined_p);
2991 defsubr (&Sxw_color_values);
2992 defsubr (&Sx_server_max_request_size);
2993 defsubr (&Sx_server_vendor);
2994 defsubr (&Sx_server_version);
2995 defsubr (&Sx_display_pixel_width);
2996 defsubr (&Sx_display_pixel_height);
2997 defsubr (&Sns_display_monitor_attributes_list);
2998 defsubr (&Sx_display_mm_width);
2999 defsubr (&Sx_display_mm_height);
3000 defsubr (&Sx_display_screens);
3001 defsubr (&Sx_display_planes);
3002 defsubr (&Sx_display_color_cells);
3003 defsubr (&Sx_display_visual_class);
3004 defsubr (&Sx_display_backing_store);
3005 defsubr (&Sx_display_save_under);
3006 defsubr (&Sx_create_frame);
3007 defsubr (&Sx_open_connection);
3008 defsubr (&Sx_close_connection);
3009 defsubr (&Sx_display_list);
3011 defsubr (&Sns_hide_others);
3012 defsubr (&Sns_hide_emacs);
3013 defsubr (&Sns_emacs_info_panel);
3014 defsubr (&Sns_list_services);
3015 defsubr (&Sns_perform_service);
3016 defsubr (&Sns_convert_utf8_nfd_to_nfc);
3017 defsubr (&Sns_popup_font_panel);
3018 defsubr (&Sns_popup_color_panel);
3020 defsubr (&Sx_show_tip);
3021 defsubr (&Sx_hide_tip);