(Fx_create_frame): Pass kb to make_frame_without_minibuffer.
[bpt/emacs.git] / src / xfns.c
index 11a9c47..63a58d1 100644 (file)
@@ -1,5 +1,5 @@
 /* Functions for the X window system.
-   Copyright (C) 1989, 1992, 1993, 1994 Free Software Foundation.
+   Copyright (C) 1989, 1992, 1993, 1994, 1995 Free Software Foundation.
 
 This file is part of GNU Emacs.
 
@@ -24,10 +24,6 @@ the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
 #include <signal.h>
 #include <config.h>
 
-#if 0
-#include <stdio.h>
-#endif
-
 /* This makes the fields of a Display accessible, in Xlib header files.  */
 #define XLIB_ILLEGAL_ACCESS
 
@@ -39,6 +35,7 @@ the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
 #include "dispextern.h"
 #include "keyboard.h"
 #include "blockinput.h"
+#include "paths.h"
 
 #ifdef HAVE_X_WINDOWS
 extern void abort ();
@@ -74,34 +71,22 @@ extern void abort ();
 /* Do the EDITRES protocol if running X11R5 */
 #if (XtSpecificationRelease >= 5)
 #define HACK_EDITRES
-extern void _XEditResCheckMessages();
+extern void _XEditResCheckMessages ();
 #endif /* R5 + Athena */
 
 /* Unique id counter for widgets created by the Lucid Widget
-   Library. */
+   Library.  */
 extern LWLIB_ID widget_id_tick;
 
-/* The one and only application context associated with the connection
-   to the one and only X display that Emacs uses.  */
-XtAppContext Xt_app_con;
+/* This is part of a kludge--see lwlib/xlwmenu.c.  */
+XFontStruct *xlwmenu_default_font;
 
-/* The one and only application shell.  Emacs screens are popup shells of this
-   application.  */
-Widget Xt_app_shell;
-
-extern void free_frame_menubar ();
 extern void free_frame_menubar ();
 #endif /* USE_X_TOOLKIT */
 
 #define min(a,b) ((a) < (b) ? (a) : (b))
 #define max(a,b) ((a) > (b) ? (a) : (b))
 
-/* X Resource data base */
-static XrmDatabase xrdb;
-
-/* The class of this X application.  */
-#define EMACS_CLASS "Emacs"
-
 #ifdef HAVE_X11R4
 #define MAXREQUEST(dpy) (XMaxRequestSize (dpy))
 #else
@@ -111,66 +96,23 @@ static XrmDatabase xrdb;
 /* The name we're using in resource queries.  */
 Lisp_Object Vx_resource_name;
 
-/* Title name and application name for X stuff. */
-extern char *x_id_name;
-
 /* The background and shape of the mouse pointer, and shape when not
-   over text or in the modeline. */
+   over text or in the modeline.  */
 Lisp_Object Vx_pointer_shape, Vx_nontext_pointer_shape, Vx_mode_pointer_shape;
 /* The shape when over mouse-sensitive text.  */
 Lisp_Object Vx_sensitive_text_pointer_shape;
 
-/* Color of chars displayed in cursor box. */
+/* Color of chars displayed in cursor box.  */
 Lisp_Object Vx_cursor_fore_pixel;
 
-/* The screen being used.  */
-static Screen *x_screen;
-
-/* The X Visual we are using for X windows (the default) */
-Visual *screen_visual;
-
-/* Height of this X screen in pixels. */
-int x_screen_height;
-
-/* Width of this X screen in pixels. */
-int x_screen_width;
-
-/* Number of planes for this screen. */
-int x_screen_planes;
+/* Nonzero if using X.  */
+static int x_in_use;
 
-/* Non nil if no window manager is in use. */
+/* Non nil if no window manager is in use.  */
 Lisp_Object Vx_no_window_manager;
 
-/* `t' if a mouse button is depressed. */
-
-Lisp_Object Vmouse_depressed;
-
-/* For now, we have just one x_display structure since we only support
-   one X display.  */
-static struct x_screen the_x_screen;
-
-extern unsigned int x_mouse_x, x_mouse_y, x_mouse_grabbed;
-
-/* Atom for indicating window state to the window manager. */
-extern Atom Xatom_wm_change_state;
-
-/* Communication with window managers. */
-extern Atom Xatom_wm_protocols;
-
-/* Kinds of protocol things we may receive. */
-extern Atom Xatom_wm_take_focus;
-extern Atom Xatom_wm_save_yourself;
-extern Atom Xatom_wm_delete_window;
-
-/* Other WM communication */
-extern Atom Xatom_wm_configure_denied; /* When our config request is denied */
-extern Atom Xatom_wm_window_moved;     /* When the WM moves us. */
-
-/* EditRes protocol */
-extern Atom Xatom_editres_name;
-
-/* The last 23 bits of the timestamp of the last mouse button event. */
-Time mouse_timestamp;
+/* Search path for bitmap files.  */
+Lisp_Object Vx_bitmap_file_path;
 
 /* Evaluate this expression to rebuild the section of syms_of_xfns
    that initializes and staticpros the symbols declared below.  Note
@@ -238,8 +180,9 @@ Lisp_Object Qx_frame_parameter;
 Lisp_Object Qx_resource_name;
 Lisp_Object Quser_position;
 Lisp_Object Quser_size;
+Lisp_Object Qdisplay;
 
-/* The below are defined in frame.c. */
+/* The below are defined in frame.c.  */
 extern Lisp_Object Qheight, Qminibuffer, Qname, Qonly, Qwidth;
 extern Lisp_Object Qunsplittable, Qmenu_bar_lines;
 
@@ -250,7 +193,7 @@ extern Lisp_Object Vwindow_system_version;
 void
 check_x ()
 {
-  if (x_current_display == 0)
+  if (! x_in_use)
     error ("X windows are not in use or not initialized");
 }
 
@@ -259,31 +202,83 @@ check_x ()
 int
 using_x_p ()
 {
-  return x_current_display != 0;
+  return x_in_use;
+}
+
+/* Extract a frame as a FRAME_PTR, defaulting to the selected frame
+   and checking validity for X.  */
+
+FRAME_PTR
+check_x_frame (frame)
+     Lisp_Object frame;
+{
+  FRAME_PTR f;
+
+  if (NILP (frame))
+    f = selected_frame;
+  else
+    {
+      CHECK_LIVE_FRAME (frame, 0);
+      f = XFRAME (frame);
+    }
+  if (! FRAME_X_P (f))
+    error ("non-X frame used");
+  return f;
 }
 
+/* Let the user specify an X display with a frame.
+   nil stands for the selected frame--or, if that is not an X frame,
+   the first X display on the list.  */
+
+static struct x_display_info *
+check_x_display_info (frame)
+     Lisp_Object frame;
+{
+  if (NILP (frame))
+    {
+      if (FRAME_X_P (selected_frame))
+       return FRAME_X_DISPLAY_INFO (selected_frame);
+      else if (x_display_list != 0)
+       return x_display_list;
+      else
+       error ("X windows are not in use or not initialized");
+    }
+  else if (STRINGP (frame))
+    return x_display_info_for_name (frame);
+  else
+    {
+      FRAME_PTR f;
+
+      CHECK_LIVE_FRAME (frame, 0);
+      f = XFRAME (frame);
+      if (! FRAME_X_P (f))
+       error ("non-X frame used");
+      return FRAME_X_DISPLAY_INFO (f);
+    }
+}
+\f
 /* Return the Emacs frame-object corresponding to an X window.
    It could be the frame's main window or an icon window.  */
 
-/* This function can be called during GC, so use XGCTYPE.  */
+/* This function can be called during GC, so use GC_xxx type test macros.  */
 
 struct frame *
-x_window_to_frame (wdesc)
+x_window_to_frame (dpyinfo, wdesc)
+     struct x_display_info *dpyinfo;
      int wdesc;
 {
   Lisp_Object tail, frame;
   struct frame *f;
 
-  for (tail = Vframe_list; XGCTYPE (tail) == Lisp_Cons;
-       tail = XCONS (tail)->cdr)
+  for (tail = Vframe_list; GC_CONSP (tail); tail = XCONS (tail)->cdr)
     {
       frame = XCONS (tail)->car;
-      if (XGCTYPE (frame) != Lisp_Frame)
+      if (!GC_FRAMEP (frame))
         continue;
       f = XFRAME (frame);
+      if (f->display.nothing == 1 || FRAME_X_DISPLAY_INFO (f) != dpyinfo)
+       continue;
 #ifdef USE_X_TOOLKIT
-      if (f->display.nothing == 1) 
-       return 0;
       if ((f->display.x->edit_widget 
           && XtWindow (f->display.x->edit_widget) == wdesc)
           || f->display.x->icon_desc == wdesc)
@@ -302,22 +297,22 @@ x_window_to_frame (wdesc)
    windows.  */
 
 struct frame *
-x_any_window_to_frame (wdesc)
+x_any_window_to_frame (dpyinfo, wdesc)
+     struct x_display_info *dpyinfo;
      int wdesc;
 {
   Lisp_Object tail, frame;
   struct frame *f;
   struct x_display *x;
 
-  for (tail = Vframe_list; XGCTYPE (tail) == Lisp_Cons;
-       tail = XCONS (tail)->cdr)
+  for (tail = Vframe_list; GC_CONSP (tail); tail = XCONS (tail)->cdr)
     {
       frame = XCONS (tail)->car;
-      if (XGCTYPE (frame) != Lisp_Frame)
+      if (!GC_FRAMEP (frame))
         continue;
       f = XFRAME (frame);
-      if (f->display.nothing == 1
-       return 0;
+      if (f->display.nothing == 1 || FRAME_X_DISPLAY_INFO (f) != dpyinfo)
+       continue;
       x = f->display.x;
       /* This frame matches if the window is any of its widgets.  */
       if (wdesc == XtWindow (x->widget) 
@@ -331,26 +326,55 @@ x_any_window_to_frame (wdesc)
   return 0;
 }
 
+/* Likewise, but exclude the menu bar widget.  */
+
+struct frame *
+x_non_menubar_window_to_frame (dpyinfo, wdesc)
+     struct x_display_info *dpyinfo;
+     int wdesc;
+{
+  Lisp_Object tail, frame;
+  struct frame *f;
+  struct x_display *x;
+
+  for (tail = Vframe_list; GC_CONSP (tail); tail = XCONS (tail)->cdr)
+    {
+      frame = XCONS (tail)->car;
+      if (!GC_FRAMEP (frame))
+        continue;
+      f = XFRAME (frame);
+      if (f->display.nothing == 1 || FRAME_X_DISPLAY_INFO (f) != dpyinfo)
+       continue;
+      x = f->display.x;
+      /* This frame matches if the window is any of its widgets.  */
+      if (wdesc == XtWindow (x->widget) 
+         || wdesc == XtWindow (x->column_widget) 
+         || wdesc == XtWindow (x->edit_widget))
+       return f;
+    }
+  return 0;
+}
+
 /* Return the frame whose principal (outermost) window is WDESC.
    If WDESC is some other (smaller) window, we return 0.  */
 
 struct frame *
-x_top_window_to_frame (wdesc)
+x_top_window_to_frame (dpyinfo, wdesc)
+     struct x_display_info *dpyinfo;
      int wdesc;
 {
   Lisp_Object tail, frame;
   struct frame *f;
   struct x_display *x;
 
-  for (tail = Vframe_list; XGCTYPE (tail) == Lisp_Cons;
-       tail = XCONS (tail)->cdr)
+  for (tail = Vframe_list; GC_CONSP (tail); tail = XCONS (tail)->cdr)
     {
       frame = XCONS (tail)->car;
-      if (XGCTYPE (frame) != Lisp_Frame)
+      if (!GC_FRAMEP (frame))
         continue;
       f = XFRAME (frame);
-      if (f->display.nothing == 1
-       return 0;
+      if (f->display.nothing == 1 || FRAME_X_DISPLAY_INFO (f) != dpyinfo)
+       continue;
       x = f->display.x;
       /* This frame matches if the window is its topmost widget.  */
       if (wdesc == XtWindow (x->widget))
@@ -375,73 +399,76 @@ x_top_window_to_frame (wdesc)
 
    If you use x_create_bitmap_from_data, then you must keep track of
    the bitmaps yourself.  That is, creating a bitmap from the same
-   data more than once will not be caught. */
+   data more than once will not be caught.  */
 
 
-/* Structure recording X pixmap and reference count.
-   If REFCOUNT is 0 then this record is free to be reused.  */
+/* Functions to access the contents of a bitmap, given an id.  */
 
-struct x_bitmap_record
+int
+x_bitmap_height (f, id)
+     FRAME_PTR f;
+     int id;
 {
-  Pixmap pixmap;
-  char *file;
-  int refcount;
-};
-
-/* Pointer to bitmap records.  */
-static struct x_bitmap_record *x_bitmaps;
+  return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].height;
+}
 
-/* Allocated size of x_bitmaps.  */
-static int x_bitmaps_size;
+int
+x_bitmap_width (f, id)
+     FRAME_PTR f;
+     int id;
+{
+  return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].width;
+}
 
-/* Last used bitmap index.  */
-static int x_bitmaps_last;
+int
+x_bitmap_pixmap (f, id)
+     FRAME_PTR f;
+     int id;
+{
+  return FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
+}
 
-/* Count of free bitmaps before X_BITMAPS_LAST.  */
-static int x_bitmaps_free;
 
 /* Allocate a new bitmap record.  Returns index of new record.  */
 
 static int
-x_allocate_bitmap_record ()
+x_allocate_bitmap_record (f)
+     FRAME_PTR f;
 {
-  if (x_bitmaps == NULL)
+  struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
+  int i;
+
+  if (dpyinfo->bitmaps == NULL)
     {
-      x_bitmaps_size = 10;
-      x_bitmaps
-       = (struct x_bitmap_record *) xmalloc (x_bitmaps_size * sizeof (struct x_bitmap_record));
-      x_bitmaps_last = 1;
+      dpyinfo->bitmaps_size = 10;
+      dpyinfo->bitmaps
+       = (struct x_bitmap_record *) xmalloc (dpyinfo->bitmaps_size * sizeof (struct x_bitmap_record));
+      dpyinfo->bitmaps_last = 1;
       return 1;
     }
 
-  if (x_bitmaps_last < x_bitmaps_size)
-    return ++x_bitmaps_last;
+  if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
+    return ++dpyinfo->bitmaps_last;
 
-  if (x_bitmaps_free > 0)
-    {
-      int i;
-      for (i = 0; i < x_bitmaps_size; ++i)
-       {
-         if (x_bitmaps[i].refcount == 0)
-           {
-             --x_bitmaps_free;
-             return i + 1;
-           }
-       }
-    }
+  for (i = 0; i < dpyinfo->bitmaps_size; ++i)
+    if (dpyinfo->bitmaps[i].refcount == 0)
+      return i + 1;
 
-  x_bitmaps_size *= 2;
-  x_bitmaps = (struct x_bitmap_record *) xrealloc (x_bitmaps, x_bitmaps_size * sizeof (struct x_bitmap_record));
-  return ++x_bitmaps_last;
+  dpyinfo->bitmaps_size *= 2;
+  dpyinfo->bitmaps
+    = (struct x_bitmap_record *) xrealloc (dpyinfo->bitmaps,
+                                          dpyinfo->bitmaps_size * sizeof (struct x_bitmap_record));
+  return ++dpyinfo->bitmaps_last;
 }
 
 /* Add one reference to the reference count of the bitmap with id ID.  */
 
 void
-x_reference_bitmap (id)
+x_reference_bitmap (f, id)
+     FRAME_PTR f;
      int id;
 {
-  ++x_bitmaps[id - 1].refcount;
+  ++FRAME_X_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
 }
 
 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS.  */
@@ -452,19 +479,23 @@ x_create_bitmap_from_data (f, bits, width, height)
      char *bits;
      unsigned int width, height;
 {
+  struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
   Pixmap bitmap;
   int id;
 
-  bitmap = XCreateBitmapFromData (x_current_display, FRAME_X_WINDOW (f),
+  bitmap = XCreateBitmapFromData (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
                                  bits, width, height);
 
   if (! bitmap)
     return -1;
 
-  id = x_allocate_bitmap_record ();
-  x_bitmaps[id - 1].pixmap = bitmap;
-  x_bitmaps[id - 1].file = NULL;
-  x_bitmaps[id - 1].refcount = 1;
+  id = x_allocate_bitmap_record (f);
+  dpyinfo->bitmaps[id - 1].pixmap = bitmap;
+  dpyinfo->bitmaps[id - 1].file = NULL;
+  dpyinfo->bitmaps[id - 1].refcount = 1;
+  dpyinfo->bitmaps[id - 1].depth = 1;
+  dpyinfo->bitmaps[id - 1].height = height;
+  dpyinfo->bitmaps[id - 1].width = width;
 
   return id;
 }
@@ -474,34 +505,49 @@ x_create_bitmap_from_data (f, bits, width, height)
 int
 x_create_bitmap_from_file (f, file)
      struct frame *f;
-     char *file;
+     Lisp_Object file;
 {
+  struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
   unsigned int width, height;
   Pixmap bitmap;
   int xhot, yhot, result, id;
+  Lisp_Object found;
+  int fd;
+  char *filename;
 
   /* Look for an existing bitmap with the same name.  */
-  for (id = 0; id < x_bitmaps_last; ++id)
+  for (id = 0; id < dpyinfo->bitmaps_last; ++id)
     {
-      if (x_bitmaps[id].refcount
-         && x_bitmaps[id].file
-         && !strcmp (x_bitmaps[id].file, file))
+      if (dpyinfo->bitmaps[id].refcount
+         && dpyinfo->bitmaps[id].file
+         && !strcmp (dpyinfo->bitmaps[id].file, (char *) XSTRING (file)->data))
        {
-         ++x_bitmaps[id].refcount;
+         ++dpyinfo->bitmaps[id].refcount;
          return id + 1;
        }
     }
 
-  result = XReadBitmapFile (x_current_display, FRAME_X_WINDOW (f),
-                           file, &width, &height, &bitmap, &xhot, &yhot);
+  /* Search bitmap-file-path for the file, if appropriate.  */
+  fd = openp (Vx_bitmap_file_path, file, "", &found, 0);
+  if (fd < 0)
+    return -1;
+  close (fd);
+
+  filename = (char *) XSTRING (found)->data;
+
+  result = XReadBitmapFile (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
+                           filename, &width, &height, &bitmap, &xhot, &yhot);
   if (result != BitmapSuccess)
     return -1;
 
-  id = x_allocate_bitmap_record ();
-  x_bitmaps[id - 1].pixmap = bitmap;
-  x_bitmaps[id - 1].refcount = 1;
-  x_bitmaps[id - 1].file = (char *) xmalloc ((strlen (file) + 1));
-  strcpy (x_bitmaps[id - 1].file, file);
+  id = x_allocate_bitmap_record (f);
+  dpyinfo->bitmaps[id - 1].pixmap = bitmap;
+  dpyinfo->bitmaps[id - 1].refcount = 1;
+  dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (XSTRING (file)->size + 1);
+  dpyinfo->bitmaps[id - 1].depth = 1;
+  dpyinfo->bitmaps[id - 1].height = height;
+  dpyinfo->bitmaps[id - 1].width = width;
+  strcpy (dpyinfo->bitmaps[id - 1].file, XSTRING (file)->data);
 
   return id;
 }
@@ -509,31 +555,42 @@ x_create_bitmap_from_file (f, file)
 /* Remove reference to bitmap with id number ID.  */
 
 int
-x_destroy_bitmap (id)
+x_destroy_bitmap (f, id)
+     FRAME_PTR f;
      int id;
 {
+  struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
+
   if (id > 0)
     {
-      --x_bitmaps[id - 1].refcount;
-      if (! x_bitmaps[id - 1].refcount)
+      --dpyinfo->bitmaps[id - 1].refcount;
+      if (dpyinfo->bitmaps[id - 1].refcount == 0)
        {
-         XFreePixmap (x_current_display, x_bitmaps[id - 1].pixmap);
-         if (x_bitmaps[id - 1].file)
+         XFreePixmap (FRAME_X_DISPLAY (f), dpyinfo->bitmaps[id - 1].pixmap);
+         if (dpyinfo->bitmaps[id - 1].file)
            {
-             free (x_bitmaps[id - 1].file);
-             x_bitmaps[id - 1].file = NULL;
+             free (dpyinfo->bitmaps[id - 1].file);
+             dpyinfo->bitmaps[id - 1].file = NULL;
            }
        }
     }
 }
 
-/* Return pixmap given bitmap id.  */
+/* Free all the bitmaps for the display specified by DPYINFO.  */
 
-Pixmap
-x_lookup_pixmap (id)
-     int id;
+static void
+x_destroy_all_bitmaps (dpyinfo)
+     struct x_display_info *dpyinfo;
 {
-  return x_bitmaps[id - 1].pixmap;
+  int i;
+  for (i = 0; i < dpyinfo->bitmaps_last; i++)
+    if (dpyinfo->bitmaps[i].refcount > 0)
+      {
+       XFreePixmap (dpyinfo->display, dpyinfo->bitmaps[i].pixmap);
+       if (dpyinfo->bitmaps[i].file)
+         free (dpyinfo->bitmaps[i].file);
+      }
+  dpyinfo->bitmaps_last = 0;
 }
 \f
 /* Connect the frame-parameter names for X frames
@@ -586,6 +643,7 @@ void x_set_vertical_scroll_bars ();
 void x_set_visibility ();
 void x_set_menu_bar_lines ();
 void x_set_scroll_bar_width ();
+void x_set_unsplittable ();
 
 static struct x_frame_parm_table x_frame_parms[] =
 {
@@ -606,6 +664,7 @@ static struct x_frame_parm_table x_frame_parms[] =
   "visibility", x_set_visibility,
   "menu-bar-lines", x_set_menu_bar_lines,
   "scroll-bar-width", x_set_scroll_bar_width,
+  "unsplittable", x_set_unsplittable,
 };
 
 /* Attach the `x-frame-parameter' properties to
@@ -639,11 +698,15 @@ x_set_frame_parameters (f, alist)
   /* Same here.  */
   Lisp_Object left, top;
 
+  /* Same with these.  */
+  Lisp_Object icon_left, icon_top;
+
   /* Record in these vectors all the parms specified.  */
   Lisp_Object *parms;
   Lisp_Object *values;
   int i;
   int left_no_change = 0, top_no_change = 0;
+  int icon_left_no_change = 0, icon_top_no_change = 0;
 
   i = 0;
   for (tail = alist; CONSP (tail); tail = Fcdr (tail))
@@ -666,6 +729,7 @@ x_set_frame_parameters (f, alist)
     }
 
   width = height = top = left = Qunbound;
+  icon_left = icon_top = Qunbound;
 
   /* Now process them in reverse of specified order.  */
   for (i--; i >= 0; i--)
@@ -683,6 +747,10 @@ x_set_frame_parameters (f, alist)
        top = val;
       else if (EQ (prop, Qleft))
        left = val;
+      else if (EQ (prop, Qicon_top))
+       icon_top = val;
+      else if (EQ (prop, Qicon_left))
+       icon_left = val;
       else
        {
          register Lisp_Object param_index, old_value;
@@ -690,9 +758,8 @@ x_set_frame_parameters (f, alist)
          param_index = Fget (prop, Qx_frame_parameter);
          old_value = get_frame_param (f, prop);
          store_frame_param (f, prop, val);
-         if (INTEGERP (param_index)
-             && XINT (param_index) >= 0
-             && (XINT (param_index)
+         if (NATNUMP (param_index)
+             && (XFASTINT (param_index)
                  < sizeof (x_frame_parms)/sizeof (x_frame_parms[0])))
            (*x_frame_parms[XINT (param_index)].setter)(f, val, old_value);
        }
@@ -716,6 +783,22 @@ x_set_frame_parameters (f, alist)
        XSETINT (top, f->display.x->top_pos);
     }
 
+  /* If one of the icon positions was not set, preserve or default it.  */
+  if (EQ (icon_left, Qunbound) || ! INTEGERP (icon_left))
+    {
+      icon_left_no_change = 1;
+      icon_left = Fcdr (Fassq (Qicon_left, f->param_alist));
+      if (NILP (icon_left))
+       XSETINT (icon_left, 0);
+    }
+  if (EQ (icon_top, Qunbound) || ! INTEGERP (icon_top))
+    {
+      icon_top_no_change = 1;
+      icon_top = Fcdr (Fassq (Qicon_top, f->param_alist));
+      if (NILP (icon_top))
+       XSETINT (icon_top, 0);
+    }
+
   /* Don't die if just one of these was set.  */
   if (EQ (width, Qunbound))
     XSETINT (width, FRAME_WIDTH (f));
@@ -805,10 +888,14 @@ x_set_frame_parameters (f, alist)
        /* Actually set that position, and convert to absolute.  */
        x_set_offset (f, leftpos, toppos, 0);
       }
+
+    if ((!NILP (icon_left) || !NILP (icon_top))
+       && ! (icon_left_no_change && icon_top_no_change))
+      x_wm_set_icon_position (f, XINT (icon_left), XINT (icon_top));
   }
 }
 
-/* Store the positions of frame F into XPTR and YPTR.
+/* Store the screen positions of frame F into XPTR and YPTR.
    These are the positions of the containing window manager window,
    not Emacs's own window.  */
 
@@ -817,7 +904,7 @@ x_real_positions (f, xptr, yptr)
      FRAME_PTR f;
      int *xptr, *yptr;
 {
-  int win_x = 0, win_y = 0;
+  int win_x, win_y;
   Window child;
 
   /* This is pretty gross, but seems to be the easiest way out of
@@ -832,36 +919,51 @@ x_real_positions (f, xptr, yptr)
   Window *tmp_children;
   int tmp_nchildren;
 
-  XQueryTree (x_current_display, outer, &tmp_root_window,
-             &f->display.x->parent_desc,
-             &tmp_children, &tmp_nchildren);
-  xfree (tmp_children);
-
-  /* Find the position of the outside upper-left corner of
-     the inner window, with respect to the outer window.  */
-  if (f->display.x->parent_desc != ROOT_WINDOW)
+  x_catch_errors (FRAME_X_DISPLAY (f));
+  while (1)
     {
-      BLOCK_INPUT;
-      XTranslateCoordinates (x_current_display,
-                              
-                            /* From-window, to-window.  */
+      XQueryTree (FRAME_X_DISPLAY (f), outer, &tmp_root_window,
+                 &f->display.x->parent_desc,
+                 &tmp_children, &tmp_nchildren);
+      xfree (tmp_children);
+
+      win_x = win_y = 0;
+
+      /* Find the position of the outside upper-left corner of
+        the inner window, with respect to the outer window.  */
+      if (f->display.x->parent_desc != FRAME_X_DISPLAY_INFO (f)->root_window)
+       {
+         XTranslateCoordinates (FRAME_X_DISPLAY (f),
+
+                                /* From-window, to-window.  */
 #ifdef USE_X_TOOLKIT
-                            XtWindow (f->display.x->widget),
+                                XtWindow (f->display.x->widget),
 #else
-                            f->display.x->window_desc,
+                                f->display.x->window_desc,
 #endif
-                            f->display.x->parent_desc,
+                                f->display.x->parent_desc,
 
-                            /* From-position, to-position.  */
-                            0, 0, &win_x, &win_y,
+                                /* From-position, to-position.  */
+                                0, 0, &win_x, &win_y,
 
-                            /* Child of win.  */
-                            &child);
-      UNBLOCK_INPUT;
+                                /* Child of win.  */
+                                &child);
+
+         win_x += f->display.x->border_width;
+         win_y += f->display.x->border_width;
+       }
 
-      win_x += f->display.x->border_width;
-      win_y += f->display.x->border_width;
+      /* It is possible for the window returned by the XQueryNotify
+        to become invalid by the time we call XTranslateCoordinates.
+        That can happen when you restart some window managers.
+        If so, we get an error in XTranslateCoordinates.
+        Detect that and try the whole thing over.  */
+      if (! x_had_errors_p (FRAME_X_DISPLAY (f)))
+       break;
     }
+
+  x_uncatch_errors (FRAME_X_DISPLAY (f));
+
   *xptr = f->display.x->left_pos - win_x;
   *yptr = f->display.x->top_pos - win_y;
 }
@@ -891,31 +993,88 @@ x_report_frame_params (f, alistptr)
   store_in_alist (alistptr, Qvisibility,
                  (FRAME_VISIBLE_P (f) ? Qt
                   : FRAME_ICONIFIED_P (f) ? Qicon : Qnil));
+  store_in_alist (alistptr, Qdisplay,
+                 XCONS (FRAME_X_DISPLAY_INFO (f)->name_list_element)->car);
 }
 \f
+
 /* Decide if color named COLOR is valid for the display associated with
    the selected frame; if so, return the rgb values in COLOR_DEF.
    If ALLOC is nonzero, allocate a new colormap cell.  */
 
 int
-defined_color (color, color_def, alloc)
+defined_color (f, color, color_def, alloc)
+     FRAME_PTR f;
      char *color;
-     Color *color_def;
+     XColor *color_def;
      int alloc;
 {
-  register int foo;
+  register int status;
   Colormap screen_colormap;
+  Display *display = FRAME_X_DISPLAY (f);
 
   BLOCK_INPUT;
-  screen_colormap
-    = DefaultColormap (x_current_display, XDefaultScreen (x_current_display));
+  screen_colormap = DefaultColormap (display, XDefaultScreen (display));
 
-  foo = XParseColor (x_current_display, screen_colormap, color, color_def);
-  if (foo && alloc)
-    foo = XAllocColor (x_current_display, screen_colormap, color_def);
+  status = XParseColor (display, screen_colormap, color, color_def);
+  if (status && alloc) 
+    {
+      status = XAllocColor (display, screen_colormap, color_def);
+      if (!status)
+       {
+         /* If we got to this point, the colormap is full, so we're 
+            going to try and get the next closest color.
+            The algorithm used is a least-squares matching, which is
+            what X uses for closest color matching with StaticColor visuals.  */
+
+         XColor *cells;
+         int no_cells;
+         int nearest;
+         long nearest_delta, trial_delta;
+         int x;
+
+         no_cells = XDisplayCells (display, XDefaultScreen (display));
+         cells = (XColor *) alloca (sizeof (XColor) * no_cells);
+
+         for (x = 0; x < no_cells; x++) 
+           cells[x].pixel = x;
+
+         XQueryColors (display, screen_colormap, cells, no_cells);
+         nearest = 0;
+         /* I'm assuming CSE so I'm not going to condense this. */
+         nearest_delta = ((((color_def->red >> 8) - (cells[0].red >> 8))
+                           * ((color_def->red >> 8) - (cells[0].red >> 8)))
+                          +
+                          (((color_def->green >> 8) - (cells[0].green >> 8))
+                           * ((color_def->green >> 8) - (cells[0].green >> 8)))
+                          +
+                          (((color_def->blue >> 8) - (cells[0].blue >> 8))
+                           * ((color_def->blue >> 8) - (cells[0].blue >> 8))));
+         for (x = 1; x < no_cells; x++) 
+           {
+             trial_delta = ((((color_def->red >> 8) - (cells[x].red >> 8))
+                             * ((color_def->red >> 8) - (cells[x].red >> 8)))
+                            +
+                            (((color_def->green >> 8) - (cells[x].green >> 8))
+                             * ((color_def->green >> 8) - (cells[x].green >> 8)))
+                            +
+                            (((color_def->blue >> 8) - (cells[x].blue >> 8))
+                             * ((color_def->blue >> 8) - (cells[x].blue >> 8))));
+             if (trial_delta < nearest_delta) 
+               {
+                 nearest = x;
+                 nearest_delta = trial_delta;
+               }
+           }
+         color_def->red = cells[nearest].red;
+         color_def->green = cells[nearest].green;
+         color_def->blue = cells[nearest].blue;
+         status = XAllocColor (display, screen_colormap, color_def);
+       }
+    }
   UNBLOCK_INPUT;
 
-  if (foo)
+  if (status)
     return 1;
   else
     return 0;
@@ -927,26 +1086,30 @@ defined_color (color, color_def, alloc)
    ARG says.  */
 
 int
-x_decode_color (arg, def)
+x_decode_color (f, arg, def)
+     FRAME_PTR f;
      Lisp_Object arg;
      int def;
 {
-  Color cdef;
+  XColor cdef;
 
   CHECK_STRING (arg, 0);
 
   if (strcmp (XSTRING (arg)->data, "black") == 0)
-    return BLACK_PIX_DEFAULT;
+    return BLACK_PIX_DEFAULT (f);
   else if (strcmp (XSTRING (arg)->data, "white") == 0)
-    return WHITE_PIX_DEFAULT;
+    return WHITE_PIX_DEFAULT (f);
 
-  if (x_screen_planes == 1)
+  if (FRAME_X_DISPLAY_INFO (f)->n_planes == 1)
     return def;
 
-  if (defined_color (XSTRING (arg)->data, &cdef, 1))
+  /* defined_color is responsible for coping with failures
+     by looking for a near-miss.  */
+  if (defined_color (f, XSTRING (arg)->data, &cdef, 1))
     return cdef.pixel;
-  else
-    Fsignal (Qundefined_color, Fcons (arg, Qnil));
+
+  /* defined_color failed; return an ultimate default.  */
+  return def;
 }
 \f
 /* Functions called only from `x_set_frame_param'
@@ -962,13 +1125,14 @@ x_set_foreground_color (f, arg, oldval)
      struct frame *f;
      Lisp_Object arg, oldval;
 {
-  f->display.x->foreground_pixel = x_decode_color (arg, BLACK_PIX_DEFAULT);
+  f->display.x->foreground_pixel
+    = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
   if (FRAME_X_WINDOW (f) != 0)
     {
       BLOCK_INPUT;
-      XSetForeground (x_current_display, f->display.x->normal_gc,
+      XSetForeground (FRAME_X_DISPLAY (f), f->display.x->normal_gc,
                      f->display.x->foreground_pixel);
-      XSetBackground (x_current_display, f->display.x->reverse_gc,
+      XSetBackground (FRAME_X_DISPLAY (f), f->display.x->reverse_gc,
                      f->display.x->foreground_pixel);
       UNBLOCK_INPUT;
       recompute_basic_faces (f);
@@ -985,25 +1149,26 @@ x_set_background_color (f, arg, oldval)
   Pixmap temp;
   int mask;
 
-  f->display.x->background_pixel = x_decode_color (arg, WHITE_PIX_DEFAULT);
+  f->display.x->background_pixel
+    = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
 
   if (FRAME_X_WINDOW (f) != 0)
     {
       BLOCK_INPUT;
-      /* The main frame area. */
-      XSetBackground (x_current_display, f->display.x->normal_gc,
+      /* The main frame area.  */
+      XSetBackground (FRAME_X_DISPLAY (f), f->display.x->normal_gc,
                      f->display.x->background_pixel);
-      XSetForeground (x_current_display, f->display.x->reverse_gc,
+      XSetForeground (FRAME_X_DISPLAY (f), f->display.x->reverse_gc,
                      f->display.x->background_pixel);
-      XSetForeground (x_current_display, f->display.x->cursor_gc,
+      XSetForeground (FRAME_X_DISPLAY (f), f->display.x->cursor_gc,
                      f->display.x->background_pixel);
-      XSetWindowBackground (x_current_display, FRAME_X_WINDOW (f),
+      XSetWindowBackground (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
                            f->display.x->background_pixel);
       {
        Lisp_Object bar;
        for (bar = FRAME_SCROLL_BARS (f); !NILP (bar);
             bar = XSCROLL_BAR (bar)->next)
-         XSetWindowBackground (x_current_display,
+         XSetWindowBackground (FRAME_X_DISPLAY (f),
                                SCROLL_BAR_X_WINDOW (XSCROLL_BAR (bar)),
                                f->display.x->background_pixel);
       }
@@ -1025,9 +1190,10 @@ x_set_mouse_color (f, arg, oldval)
   int mask_color;
 
   if (!EQ (Qnil, arg))
-    f->display.x->mouse_pixel = x_decode_color (arg, BLACK_PIX_DEFAULT);
+    f->display.x->mouse_pixel
+      = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
   mask_color = f->display.x->background_pixel;
-                               /* No invisible pointers. */
+                               /* No invisible pointers.  */
   if (mask_color == f->display.x->mouse_pixel
        && mask_color == f->display.x->background_pixel)
     f->display.x->mouse_pixel = f->display.x->foreground_pixel;
@@ -1035,98 +1201,98 @@ x_set_mouse_color (f, arg, oldval)
   BLOCK_INPUT;
 
   /* It's not okay to crash if the user selects a screwy cursor.  */
-  x_catch_errors ();
+  x_catch_errors (FRAME_X_DISPLAY (f));
 
   if (!EQ (Qnil, Vx_pointer_shape))
     {
       CHECK_NUMBER (Vx_pointer_shape, 0);
-      cursor = XCreateFontCursor (x_current_display, XINT (Vx_pointer_shape));
+      cursor = XCreateFontCursor (FRAME_X_DISPLAY (f), XINT (Vx_pointer_shape));
     }
   else
-    cursor = XCreateFontCursor (x_current_display, XC_xterm);
-  x_check_errors ("bad text pointer cursor: %s");
+    cursor = XCreateFontCursor (FRAME_X_DISPLAY (f), XC_xterm);
+  x_check_errors (FRAME_X_DISPLAY (f), "bad text pointer cursor: %s");
 
   if (!EQ (Qnil, Vx_nontext_pointer_shape))
     {
       CHECK_NUMBER (Vx_nontext_pointer_shape, 0);
-      nontext_cursor = XCreateFontCursor (x_current_display,
+      nontext_cursor = XCreateFontCursor (FRAME_X_DISPLAY (f),
                                          XINT (Vx_nontext_pointer_shape));
     }
   else
-    nontext_cursor = XCreateFontCursor (x_current_display, XC_left_ptr);
-  x_check_errors ("bad nontext pointer cursor: %s");
+    nontext_cursor = XCreateFontCursor (FRAME_X_DISPLAY (f), XC_left_ptr);
+  x_check_errors (FRAME_X_DISPLAY (f), "bad nontext pointer cursor: %s");
 
   if (!EQ (Qnil, Vx_mode_pointer_shape))
     {
       CHECK_NUMBER (Vx_mode_pointer_shape, 0);
-      mode_cursor = XCreateFontCursor (x_current_display,
-                                         XINT (Vx_mode_pointer_shape));
+      mode_cursor = XCreateFontCursor (FRAME_X_DISPLAY (f),
+                                      XINT (Vx_mode_pointer_shape));
     }
   else
-    mode_cursor = XCreateFontCursor (x_current_display, XC_xterm);
-  x_check_errors ("bad modeline pointer cursor: %s");
+    mode_cursor = XCreateFontCursor (FRAME_X_DISPLAY (f), XC_xterm);
+  x_check_errors (FRAME_X_DISPLAY (f), "bad modeline pointer cursor: %s");
 
   if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
     {
       CHECK_NUMBER (Vx_sensitive_text_pointer_shape, 0);
       cross_cursor
-       = XCreateFontCursor (x_current_display,
+       = XCreateFontCursor (FRAME_X_DISPLAY (f),
                             XINT (Vx_sensitive_text_pointer_shape));
     }
   else
-    cross_cursor = XCreateFontCursor (x_current_display, XC_crosshair);
+    cross_cursor = XCreateFontCursor (FRAME_X_DISPLAY (f), XC_crosshair);
 
   /* Check and report errors with the above calls.  */
-  x_check_errors ("can't set cursor shape: %s");
-  x_uncatch_errors ();
+  x_check_errors (FRAME_X_DISPLAY (f), "can't set cursor shape: %s");
+  x_uncatch_errors (FRAME_X_DISPLAY (f));
 
   {
     XColor fore_color, back_color;
 
     fore_color.pixel = f->display.x->mouse_pixel;
     back_color.pixel = mask_color;
-    XQueryColor (x_current_display,
-                DefaultColormap (x_current_display,
-                                 DefaultScreen (x_current_display)),
+    XQueryColor (FRAME_X_DISPLAY (f),
+                DefaultColormap (FRAME_X_DISPLAY (f),
+                                 DefaultScreen (FRAME_X_DISPLAY (f))),
                 &fore_color);
-    XQueryColor (x_current_display,
-                DefaultColormap (x_current_display,
-                                 DefaultScreen (x_current_display)),
+    XQueryColor (FRAME_X_DISPLAY (f),
+                DefaultColormap (FRAME_X_DISPLAY (f),
+                                 DefaultScreen (FRAME_X_DISPLAY (f))),
                 &back_color);
-    XRecolorCursor (x_current_display, cursor,
+    XRecolorCursor (FRAME_X_DISPLAY (f), cursor,
                    &fore_color, &back_color);
-    XRecolorCursor (x_current_display, nontext_cursor,
+    XRecolorCursor (FRAME_X_DISPLAY (f), nontext_cursor,
                    &fore_color, &back_color);
-    XRecolorCursor (x_current_display, mode_cursor,
+    XRecolorCursor (FRAME_X_DISPLAY (f), mode_cursor,
                    &fore_color, &back_color);
-    XRecolorCursor (x_current_display, cross_cursor,
+    XRecolorCursor (FRAME_X_DISPLAY (f), cross_cursor,
                     &fore_color, &back_color);
   }
 
   if (FRAME_X_WINDOW (f) != 0)
     {
-      XDefineCursor (XDISPLAY FRAME_X_WINDOW (f), cursor);
+      XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), cursor);
     }
 
   if (cursor != f->display.x->text_cursor && f->display.x->text_cursor != 0)
-      XFreeCursor (XDISPLAY f->display.x->text_cursor);
+    XFreeCursor (FRAME_X_DISPLAY (f), f->display.x->text_cursor);
   f->display.x->text_cursor = cursor;
 
   if (nontext_cursor != f->display.x->nontext_cursor
       && f->display.x->nontext_cursor != 0)
-      XFreeCursor (XDISPLAY f->display.x->nontext_cursor);
+    XFreeCursor (FRAME_X_DISPLAY (f), f->display.x->nontext_cursor);
   f->display.x->nontext_cursor = nontext_cursor;
 
   if (mode_cursor != f->display.x->modeline_cursor
       && f->display.x->modeline_cursor != 0)
-      XFreeCursor (XDISPLAY f->display.x->modeline_cursor);
+    XFreeCursor (FRAME_X_DISPLAY (f), f->display.x->modeline_cursor);
   f->display.x->modeline_cursor = mode_cursor;
   if (cross_cursor != f->display.x->cross_cursor
       && f->display.x->cross_cursor != 0)
-      XFreeCursor (XDISPLAY f->display.x->cross_cursor);
+    XFreeCursor (FRAME_X_DISPLAY (f), f->display.x->cross_cursor);
   f->display.x->cross_cursor = cross_cursor;
 
-  XFlushQueue ();
+  XFlush (FRAME_X_DISPLAY (f));
   UNBLOCK_INPUT;
 }
 
@@ -1138,10 +1304,11 @@ x_set_cursor_color (f, arg, oldval)
   unsigned long fore_pixel;
 
   if (!EQ (Vx_cursor_fore_pixel, Qnil))
-    fore_pixel = x_decode_color (Vx_cursor_fore_pixel, WHITE_PIX_DEFAULT);
+    fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
+                                WHITE_PIX_DEFAULT (f));
   else
     fore_pixel = f->display.x->background_pixel;
-  f->display.x->cursor_pixel = x_decode_color (arg, BLACK_PIX_DEFAULT);
+  f->display.x->cursor_pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
   
   /* Make sure that the cursor color differs from the background color.  */
   if (f->display.x->cursor_pixel == f->display.x->background_pixel)
@@ -1155,9 +1322,9 @@ x_set_cursor_color (f, arg, oldval)
   if (FRAME_X_WINDOW (f) != 0)
     {
       BLOCK_INPUT;
-      XSetBackground (x_current_display, f->display.x->cursor_gc,
+      XSetBackground (FRAME_X_DISPLAY (f), f->display.x->cursor_gc,
                      f->display.x->cursor_pixel);
-      XSetForeground (x_current_display, f->display.x->cursor_gc,
+      XSetForeground (FRAME_X_DISPLAY (f), f->display.x->cursor_gc,
                      fore_pixel);
       UNBLOCK_INPUT;
 
@@ -1178,7 +1345,7 @@ x_set_cursor_color (f, arg, oldval)
    Note: this is done in two routines because of the way X10 works.
 
    Note: under X11, this is normally the province of the window manager,
-   and so emacs' border colors may be overridden. */
+   and so emacs' border colors may be overridden.  */
 
 void
 x_set_border_color (f, arg, oldval)
@@ -1191,7 +1358,7 @@ x_set_border_color (f, arg, oldval)
   CHECK_STRING (arg, 0);
   str = XSTRING (arg)->data;
 
-    pix = x_decode_color (arg, BLACK_PIX_DEFAULT);
+  pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
 
   x_set_border_pixel (f, pix);
 }
@@ -1212,7 +1379,7 @@ x_set_border_pixel (f, pix)
       int mask;
 
       BLOCK_INPUT;
-      XSetWindowBorder (x_current_display, FRAME_X_WINDOW (f),
+      XSetWindowBorder (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
                         pix);
       UNBLOCK_INPUT;
 
@@ -1227,19 +1394,21 @@ x_set_cursor_type (f, arg, oldval)
      Lisp_Object arg, oldval;
 {
   if (EQ (arg, Qbar))
-    FRAME_DESIRED_CURSOR (f) = bar_cursor;
-  else
-#if 0
-    if (EQ (arg, Qbox))
-#endif
-      FRAME_DESIRED_CURSOR (f) = filled_box_cursor;
-  /* Error messages commented out because people have trouble fixing
-     .Xdefaults with Emacs, when it has something bad in it.  */
-#if 0
+    {
+      FRAME_DESIRED_CURSOR (f) = bar_cursor;
+      f->display.x->cursor_width = 2;
+    }
+  else if (CONSP (arg) && EQ (XCONS (arg)->car, Qbar)
+          && INTEGERP (XCONS (arg)->cdr))
+    {
+      FRAME_DESIRED_CURSOR (f) = bar_cursor;
+      f->display.x->cursor_width = XINT (XCONS (arg)->cdr);
+    }
   else
-    error
-      ("the `cursor-type' frame parameter should be either `bar' or `box'");
-#endif
+    /* Treat anything unknown as "box cursor".
+       It was bad to signal an error; people have trouble fixing
+       .Xdefaults with Emacs, when it has something bad in it.  */
+    FRAME_DESIRED_CURSOR (f) = filled_box_cursor;
 
   /* Make sure the cursor gets redrawn.  This is overkill, but how
      often do people change cursor types?  */
@@ -1265,10 +1434,8 @@ x_set_icon_type (f, arg, oldval)
   BLOCK_INPUT;
   if (NILP (arg))
     result = x_text_icon (f, 0);
-  else if (STRINGP (arg))
-    result = x_bitmap_icon (f, XSTRING (arg)->data);
-  else 
-    result = x_bitmap_icon (f, 0);
+  else
+    result = x_bitmap_icon (f, arg);
 
   if (result)
     {
@@ -1279,25 +1446,30 @@ x_set_icon_type (f, arg, oldval)
   /* If the window was unmapped (and its icon was mapped),
      the new icon is not mapped, so map the window in its stead.  */
   if (FRAME_VISIBLE_P (f))
+    {
 #ifdef USE_X_TOOLKIT
-    XtPopup (f->display.x->widget, XtGrabNone);
+      XtPopup (f->display.x->widget, XtGrabNone);
 #endif
-    XMapWindow (XDISPLAY FRAME_X_WINDOW (f));
+      XMapWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
+    }
 
-  XFlushQueue ();
+  XFlush (FRAME_X_DISPLAY (f));
   UNBLOCK_INPUT;
 }
 
-/* Return 1 if frame F wants a bitmap icon.  */
+/* Return non-nil if frame F wants a bitmap icon.  */
 
-int
+Lisp_Object
 x_icon_type (f)
      FRAME_PTR f;
 {
   Lisp_Object tem;
 
   tem = assq_no_quit (Qicon_type, f->param_alist);
-  return (CONSP (tem) && ! NILP (XCONS (tem)->cdr));
+  if (CONSP (tem))
+    return XCONS (tem)->cdr;
+  else
+    return Qnil;
 }
 
 extern Lisp_Object x_new_font ();
@@ -1367,7 +1539,7 @@ x_set_internal_border_width (f, arg, oldval)
 #if 0
       x_set_resize_hint (f);
 #endif
-      XFlushQueue ();
+      XFlush (FRAME_X_DISPLAY (f));
       UNBLOCK_INPUT;
       SET_FRAME_GARBAGED (f);
     }
@@ -1484,9 +1656,10 @@ x_set_name (f, name, explicit)
     {
       /* Check for no change needed in this very common case
         before we do any consing.  */
-      if (!strcmp (x_id_name, XSTRING (f->name)->data))
+      if (!strcmp (FRAME_X_DISPLAY_INFO (f)->x_id_name,
+                  XSTRING (f->name)->data))
        return;
-      name = build_string (x_id_name);
+      name = build_string (FRAME_X_DISPLAY_INFO (f)->x_id_name);
     }
   else
     CHECK_STRING (name, 0);
@@ -1506,18 +1679,19 @@ x_set_name (f, name, explicit)
        text.format = 8;
        text.nitems = XSTRING (name)->size;
 #ifdef USE_X_TOOLKIT
-       XSetWMName (x_current_display, XtWindow (f->display.x->widget), &text);
-       XSetWMIconName (x_current_display, XtWindow (f->display.x->widget),
+       XSetWMName (FRAME_X_DISPLAY (f),
+                   XtWindow (f->display.x->widget), &text);
+       XSetWMIconName (FRAME_X_DISPLAY (f), XtWindow (f->display.x->widget),
                        &text);
 #else /* not USE_X_TOOLKIT */
-       XSetWMName (x_current_display, FRAME_X_WINDOW (f), &text);
-       XSetWMIconName (x_current_display, FRAME_X_WINDOW (f), &text);
+       XSetWMName (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), &text);
+       XSetWMIconName (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), &text);
 #endif /* not USE_X_TOOLKIT */
       }
 #else /* not HAVE_X11R4 */
-      XSetIconName (XDISPLAY FRAME_X_WINDOW (f),
+      XSetIconName (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
                    XSTRING (name)->data);
-      XStoreName (XDISPLAY FRAME_X_WINDOW (f),
+      XStoreName (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
                  XSTRING (name)->data);
 #endif /* not HAVE_X11R4 */
       UNBLOCK_INPUT;
@@ -1564,6 +1738,14 @@ x_set_autolower (f, arg, oldval)
   f->auto_lower = !EQ (Qnil, arg);
 }
 
+void
+x_set_unsplittable (f, arg, oldval)
+     struct frame *f;
+     Lisp_Object arg, oldval;
+{
+  f->no_split = !NILP (arg);
+}
+
 void
 x_set_vertical_scroll_bars (f, arg, oldval)
      struct frame *f;
@@ -1609,14 +1791,23 @@ x_set_scroll_bar_width (f, arg, oldval)
 static void
 validate_x_resource_name ()
 {
+  int len;
+  /* Number of valid characters in the resource name.  */
+  int good_count = 0;
+  /* Number of invalid characters in the resource name.  */
+  int bad_count = 0;
+  Lisp_Object new;
+  int i;
+
   if (STRINGP (Vx_resource_name))
     {
-      int len = XSTRING (Vx_resource_name)->size;
       unsigned char *p = XSTRING (Vx_resource_name)->data;
       int i;
 
-      /* Allow only letters, digits, - and _,
-        because those are all that X allows.  */
+      len = XSTRING (Vx_resource_name)->size;
+
+      /* Only letters, digits, - and _ are valid in resource names.
+        Count the valid characters and count the invalid ones.  */
       for (i = 0; i < len; i++)
        {
          int c = p[i];
@@ -1624,17 +1815,45 @@ validate_x_resource_name ()
                 || (c >= 'A' && c <= 'Z')
                 || (c >= '0' && c <= '9')
                 || c == '-' || c == '_'))
-           goto fail;
+           bad_count++;
+         else
+           good_count++;
        }
     }
   else
-  fail:
-    Vx_resource_name = make_string ("emacs", 5);
+    /* Not a string => completely invalid.  */
+    bad_count = 5, good_count = 0;
+
+  /* If name is valid already, return.  */
+  if (bad_count == 0)
+    return;
+
+  /* If name is entirely invalid, or nearly so, use `emacs'.  */
+  if (good_count == 0
+      || (good_count == 1 && bad_count > 0))
+    {
+      Vx_resource_name = make_string ("emacs", 5);
+      return;
+    }
+
+  /* Name is partly valid.  Copy it and replace the invalid characters
+     with underscores.  */
+
+  Vx_resource_name = new = Fcopy_sequence (Vx_resource_name);
+
+  for (i = 0; i < len; i++)
+    {
+      int c = XSTRING (new)->data[i];
+      if (! ((c >= 'a' && c <= 'z')
+            || (c >= 'A' && c <= 'Z')
+            || (c >= '0' && c <= '9')
+            || c == '-' || c == '_'))
+       XSTRING (new)->data[i] = '_';
+    }
 }
 
 
 extern char *x_get_string_resource ();
-extern XrmDatabase x_load_resources ();
 
 DEFUN ("x-get-resource", Fx_get_resource, Sx_get_resource, 2, 4, 0,
   "Return the value of ATTRIBUTE, of class CLASS, from the X defaults database.\n\
@@ -1709,7 +1928,8 @@ and the class is `Emacs.CLASS.SUBCLASS'.")
               XSTRING (subclass)->data);
     }
 
-  value = x_get_string_resource (xrdb, name_key, class_key);
+  value = x_get_string_resource (check_x_display_info (Qnil)->xrdb,
+                                name_key, class_key);
 
   if (value != (char *) 0)
     return build_string (value);
@@ -1739,7 +1959,8 @@ x_get_resource_string (attribute, class)
           attribute);
   sprintf (class_key, "%s.%s", EMACS_CLASS, class);
 
-  return x_get_string_resource (xrdb, name_key, class_key);
+  return x_get_string_resource (FRAME_X_DISPLAY_INFO (selected_frame)->xrdb,
+                               name_key, class_key);
 }
 
 /* Types we might convert a resource string into.  */
@@ -1757,7 +1978,7 @@ enum resource_types
 
    If no default is specified, return Qunbound.  If you call
    x_get_arg, make sure you deal with Qunbound in a reasonable way,
-   and don't let it get stored in any lisp-visible variables!  */
+   and don't let it get stored in any Lisp-visible variables!  */
 
 static Lisp_Object
 x_get_arg (alist, param, attribute, class, type)
@@ -1929,7 +2150,7 @@ x_figure_window_size (f, parms)
 
   /* Default values if we fall through.
      Actually, if that happens we should get
-     window manager prompting. */
+     window manager prompting.  */
   f->width = DEFAULT_COLS;
   f->height = DEFAULT_ROWS;
   /* Window managers expect that if program-specified
@@ -2028,7 +2249,7 @@ x_figure_window_size (f, parms)
            window_prompting |= XNegative;
        }
 
-      if (!NILP (tem2))
+      if (!NILP (tem2) && ! EQ (tem2, Qunbound))
        window_prompting |= USPosition;
       else
        window_prompting |= PPosition;
@@ -2063,7 +2284,8 @@ XSetWMProtocols (dpy, w, protocols, count)
    for example, but Xt doesn't).  */
 
 static void
-hack_wm_protocols (widget)
+hack_wm_protocols (f, widget)
+     FRAME_PTR f;
      Widget widget;
 {
   Display *dpy = XtDisplay (widget);
@@ -2079,7 +2301,8 @@ hack_wm_protocols (widget)
     unsigned long nitems = 0;
     unsigned long bytes_after;
 
-    if (Success == XGetWindowProperty (dpy, w, Xatom_wm_protocols,
+    if (Success == XGetWindowProperty (dpy, w,
+                                      FRAME_X_DISPLAY_INFO (f)->Xatom_wm_protocols,
                                       0, 100, False, XA_ATOM,
                                       &type, &format, &nitems, &bytes_after,
                                       (unsigned char **) &atoms)
@@ -2087,20 +2310,27 @@ hack_wm_protocols (widget)
       while (nitems > 0)
        {
          nitems--;
-         if (atoms[nitems] == Xatom_wm_delete_window)      need_delete = 0;
-         else if (atoms[nitems] == Xatom_wm_take_focus)    need_focus = 0;
-         else if (atoms[nitems] == Xatom_wm_save_yourself) need_save = 0;
+         if (atoms[nitems] == FRAME_X_DISPLAY_INFO (f)->Xatom_wm_delete_window)
+           need_delete = 0;
+         else if (atoms[nitems] == FRAME_X_DISPLAY_INFO (f)->Xatom_wm_take_focus)
+           need_focus = 0;
+         else if (atoms[nitems] == FRAME_X_DISPLAY_INFO (f)->Xatom_wm_save_yourself)
+           need_save = 0;
        }
     if (atoms) XFree ((char *) atoms);
   }
   {
     Atom props [10];
     int count = 0;
-    if (need_delete) props[count++] = Xatom_wm_delete_window;
-    if (need_focus)  props[count++] = Xatom_wm_take_focus;
-    if (need_save)   props[count++] = Xatom_wm_save_yourself;
+    if (need_delete)
+      props[count++] = FRAME_X_DISPLAY_INFO (f)->Xatom_wm_delete_window;
+    if (need_focus)
+      props[count++] = FRAME_X_DISPLAY_INFO (f)->Xatom_wm_take_focus;
+    if (need_save)
+      props[count++] = FRAME_X_DISPLAY_INFO (f)->Xatom_wm_save_yourself;
     if (count)
-      XChangeProperty (dpy, w, Xatom_wm_protocols, XA_ATOM, 32, PropModeAppend,
+      XChangeProperty (dpy, w, FRAME_X_DISPLAY_INFO (f)->Xatom_wm_protocols,
+                      XA_ATOM, 32, PropModeAppend,
                       (unsigned char *) props, count);
   }
   UNBLOCK_INPUT;
@@ -2124,23 +2354,25 @@ x_window (f, window_prompting, minibuffer_only)
   Widget shell_widget;
   Widget pane_widget;
   Widget frame_widget;
-  char* name;
   Arg al [25];
   int ac;
 
   BLOCK_INPUT;
 
-  if (STRINGP (f->name))
-    name = (char*) XSTRING (f->name)->data;
-  else
-    name = "emacs";
+  {
+    char *str
+      = (STRINGP (f->name) ? (char *)XSTRING (f->name)->data : "emacs");
+    f->namebuf = (char *) xrealloc (f->namebuf, strlen (str) + 1);
+    strcpy (f->namebuf, str);
+  }
 
   ac = 0;
   XtSetArg (al[ac], XtNallowShellResize, 1); ac++;
   XtSetArg (al[ac], XtNinput, 1); ac++;
-  shell_widget = XtCreatePopupShell ("shell",
-                                    topLevelShellWidgetClass,
-                                    Xt_app_shell, al, ac);
+  XtSetArg (al[ac], XtNmappedWhenManaged, 0); ac++;
+  shell_widget = XtAppCreateShell (f->namebuf, EMACS_CLASS,
+                                  topLevelShellWidgetClass,
+                                  FRAME_X_DISPLAY (f), al, ac);
 
   f->display.x->widget = shell_widget;
   /* maybe_set_screen_title_format (shell_widget); */
@@ -2166,7 +2398,7 @@ x_window (f, window_prompting, minibuffer_only)
   XtSetArg (al[ac], XtNallowResize, 1); ac++;
   XtSetArg (al[ac], XtNresizeToPreferred, 1); ac++;
   XtSetArg (al[ac], XtNemacsFrame, f); ac++;
-  frame_widget = XtCreateWidget (name,
+  frame_widget = XtCreateWidget (f->namebuf,
                                  emacsFrameClass,
                                  pane_widget, al, ac);
   lw_set_main_areas (pane_widget, f->display.x->menubar_widget, frame_widget);
@@ -2191,29 +2423,31 @@ x_window (f, window_prompting, minibuffer_only)
 
     if (FRAME_EXTERNAL_MENU_BAR (f))
       {
-        Dimension ibw;
+        Dimension ibw = 0;
         XtVaGetValues (pane_widget, XtNinternalBorderWidth, &ibw, NULL);
         menubar_size += ibw;
       }
 
-    if (window_prompting & USPosition)
-      {
-       int left = f->display.x->left_pos;
-       int xneg = window_prompting & XNegative;
-       int top = f->display.x->top_pos;
-       int yneg = window_prompting & YNegative;
-       if (xneg)
-         left = -left;
-       if (yneg)
-         top = -top;
-       sprintf (shell_position, "=%dx%d%c%d%c%d", PIXEL_WIDTH (f), 
-                PIXEL_HEIGHT (f) + menubar_size,
-                (xneg ? '-' : '+'), left,
-                (yneg ? '-' : '+'), top);
-      }
-    else
-      sprintf (shell_position, "=%dx%d", PIXEL_WIDTH (f), 
-              PIXEL_HEIGHT (f) + menubar_size);
+    /* Convert our geometry parameters into a geometry string
+       and specify it.
+       Note that we do not specify here whether the position
+       is a user-specified or program-specified one.
+       We pass that information later, in x_wm_set_size_hints.  */
+    {
+      int left = f->display.x->left_pos;
+      int xneg = window_prompting & XNegative;
+      int top = f->display.x->top_pos;
+      int yneg = window_prompting & YNegative;
+      if (xneg)
+       left = -left;
+      if (yneg)
+       top = -top;
+      sprintf (shell_position, "=%dx%d%c%d%c%d", PIXEL_WIDTH (f), 
+              PIXEL_HEIGHT (f) + menubar_size,
+              (xneg ? '-' : '+'), left,
+              (yneg ? '-' : '+'), top);
+    }
+
     len = strlen (shell_position) + 1;
     tem = (char *) xmalloc (len);
     strncpy (tem, shell_position, len);
@@ -2231,13 +2465,14 @@ x_window (f, window_prompting, minibuffer_only)
   validate_x_resource_name ();
   class_hints.res_name = (char *) XSTRING (Vx_resource_name)->data;
   class_hints.res_class = EMACS_CLASS;
-  XSetClassHint (x_current_display, XtWindow (shell_widget), &class_hints);
+  XSetClassHint (FRAME_X_DISPLAY (f), XtWindow (shell_widget), &class_hints);
 
   f->display.x->wm_hints.input = True;
   f->display.x->wm_hints.flags |= InputHint;
-  XSetWMHints (x_current_display, FRAME_X_WINDOW (f), &f->display.x->wm_hints);
+  XSetWMHints (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
+              &f->display.x->wm_hints);
 
-  hack_wm_protocols (shell_widget);
+  hack_wm_protocols (f, shell_widget);
 
 #ifdef HACK_EDITRES
   XtAddEventHandler (shell_widget, 0, True, _XEditResCheckMessages, 0);
@@ -2248,7 +2483,8 @@ x_window (f, window_prompting, minibuffer_only)
      be initialized to something relevant to the time we created the window.
      */
   XChangeProperty (XtDisplay (frame_widget), XtWindow (frame_widget),
-                  Xatom_wm_protocols, XA_ATOM, 32, PropModeAppend,
+                  FRAME_X_DISPLAY_INFO (f)->Xatom_wm_protocols,
+                  XA_ATOM, 32, PropModeAppend,
                   (unsigned char*) NULL, 0);
 
  /* Make all the standard events reach the Emacs frame.  */
@@ -2273,7 +2509,7 @@ x_window (f, window_prompting, minibuffer_only)
     x_set_name (f, name, explicit);
   }
 
-  XDefineCursor (XDISPLAY FRAME_X_WINDOW (f),
+  XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
                 f->display.x->text_cursor);
 
   UNBLOCK_INPUT;
@@ -2308,36 +2544,38 @@ x_window (f)
 
   BLOCK_INPUT;
   FRAME_X_WINDOW (f)
-    = XCreateWindow (x_current_display, ROOT_WINDOW,
+    = XCreateWindow (FRAME_X_DISPLAY (f),
+                    f->display.x->parent_desc,
                     f->display.x->left_pos,
                     f->display.x->top_pos,
                     PIXEL_WIDTH (f), PIXEL_HEIGHT (f),
                     f->display.x->border_width,
                     CopyFromParent, /* depth */
                     InputOutput, /* class */
-                    screen_visual, /* set in Fx_open_connection */
+                    FRAME_X_DISPLAY_INFO (f)->visual,
                     attribute_mask, &attributes);
 
   validate_x_resource_name ();
   class_hints.res_name = (char *) XSTRING (Vx_resource_name)->data;
   class_hints.res_class = EMACS_CLASS;
-  XSetClassHint (x_current_display, FRAME_X_WINDOW (f), &class_hints);
+  XSetClassHint (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), &class_hints);
 
   /* This indicates that we use the "Passive Input" input model.
      Unless we do this, we don't get the Focus{In,Out} events that we
      need to draw the cursor correctly.  Accursed bureaucrats.
-   XWhipsAndChains (x_current_display, IronMaiden, &TheRack);  */
+   XWhipsAndChains (FRAME_X_DISPLAY (f), IronMaiden, &TheRack);  */
 
   f->display.x->wm_hints.input = True;
   f->display.x->wm_hints.flags |= InputHint;
-  XSetWMHints (x_current_display, FRAME_X_WINDOW (f), &f->display.x->wm_hints);
+  XSetWMHints (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
+              &f->display.x->wm_hints);
 
   /* Request "save yourself" and "delete window" commands from wm.  */
   {
     Atom protocols[2];
-    protocols[0] = Xatom_wm_delete_window;
-    protocols[1] = Xatom_wm_save_yourself;
-    XSetWMProtocols (x_current_display, FRAME_X_WINDOW (f), protocols, 2);
+    protocols[0] = FRAME_X_DISPLAY_INFO (f)->Xatom_wm_delete_window;
+    protocols[1] = FRAME_X_DISPLAY_INFO (f)->Xatom_wm_save_yourself;
+    XSetWMProtocols (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), protocols, 2);
   }
 
   /* x_set_name normally ignores requests to set the name if the
@@ -2354,7 +2592,7 @@ x_window (f)
     x_set_name (f, name, explicit);
   }
 
-  XDefineCursor (XDISPLAY FRAME_X_WINDOW (f),
+  XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
                 f->display.x->text_cursor);
 
   UNBLOCK_INPUT;
@@ -2367,7 +2605,7 @@ x_window (f)
 
 /* Handle the icon stuff for this window.  Perhaps later we might
    want an x_set_icon_position which can be called interactively as
-   well. */
+   well.  */
 
 static void
 x_icon (f, parms)
@@ -2377,7 +2615,7 @@ x_icon (f, parms)
   Lisp_Object icon_x, icon_y;
 
   /* Set the position of the icon.  Note that twm groups all
-     icons in an icon window. */
+     icons in an icon window.  */
   icon_x = x_get_arg (parms, Qicon_left, 0, 0, number);
   icon_y = x_get_arg (parms, Qicon_top, 0, 0, number);
   if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
@@ -2432,16 +2670,16 @@ x_make_gc (f)
   gc_values.foreground = f->display.x->foreground_pixel;
   gc_values.background = f->display.x->background_pixel;
   gc_values.line_width = 0;    /* Means 1 using fast algorithm.  */
-  f->display.x->normal_gc = XCreateGC (x_current_display,
+  f->display.x->normal_gc = XCreateGC (FRAME_X_DISPLAY (f),
                                       FRAME_X_WINDOW (f),
                                       GCLineWidth | GCFont
                                       | GCForeground | GCBackground,
                                       &gc_values);
 
-  /* Reverse video style. */
+  /* Reverse video style.  */
   gc_values.foreground = f->display.x->background_pixel;
   gc_values.background = f->display.x->foreground_pixel;
-  f->display.x->reverse_gc = XCreateGC (x_current_display,
+  f->display.x->reverse_gc = XCreateGC (FRAME_X_DISPLAY (f),
                                        FRAME_X_WINDOW (f),
                                        GCFont | GCForeground | GCBackground
                                        | GCLineWidth,
@@ -2452,10 +2690,11 @@ x_make_gc (f)
   gc_values.background = f->display.x->cursor_pixel;
   gc_values.fill_style = FillOpaqueStippled;
   gc_values.stipple
-    = XCreateBitmapFromData (x_current_display, ROOT_WINDOW,
+    = XCreateBitmapFromData (FRAME_X_DISPLAY (f),
+                            FRAME_X_DISPLAY_INFO (f)->root_window,
                             cursor_bits, 16, 16);
   f->display.x->cursor_gc
-    = XCreateGC (x_current_display, FRAME_X_WINDOW (f),
+    = XCreateGC (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
                 (GCFont | GCForeground | GCBackground
                  | GCFillStyle | GCStipple | GCLineWidth),
                 &gc_values);
@@ -2465,11 +2704,12 @@ x_make_gc (f)
      this must be done on a per-frame basis.  */
   f->display.x->border_tile
     = (XCreatePixmapFromBitmapData
-       (x_current_display, ROOT_WINDOW
+       (FRAME_X_DISPLAY (f), FRAME_X_DISPLAY_INFO (f)->root_window
        gray_bits, gray_width, gray_height,
        f->display.x->foreground_pixel,
        f->display.x->background_pixel,
-       DefaultDepth (x_current_display, XDefaultScreen (x_current_display))));
+       DefaultDepth (FRAME_X_DISPLAY (f),
+                     XScreenNumberOfScreen (FRAME_X_SCREEN (f)))));
 
   UNBLOCK_INPUT;
 }
@@ -2477,12 +2717,14 @@ x_make_gc (f)
 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
        1, 1, 0,
   "Make a new X window, which is called a \"frame\" in Emacs terms.\n\
-Return an Emacs frame object representing the X window.\n\
+Returns an Emacs frame object.\n\
 ALIST is an alist of frame parameters.\n\
 If the parameters specify that the frame should not have a minibuffer,\n\
 and do not specify a specific minibuffer window to use,\n\
 then `default-minibuffer-frame' must be a frame whose minibuffer can\n\
-be shared by the new frame.")
+be shared by the new frame.\n\
+\n\
+This function is an internal primitive--use `make-frame' instead.")
   (parms)
      Lisp_Object parms;
 {
@@ -2494,36 +2736,86 @@ be shared by the new frame.")
   int width, height;
   int count = specpdl_ptr - specpdl;
   struct gcpro gcpro1;
+  Lisp_Object display;
+  struct x_display_info *dpyinfo;
+  Lisp_Object parent;
+  struct kboard *kb;
 
   check_x ();
 
+  display = x_get_arg (parms, Qdisplay, 0, 0, 0);
+  if (EQ (display, Qunbound))
+    display = Qnil;
+  dpyinfo = check_x_display_info (display);
+#ifdef MULTI_KBOARD
+  kb = dpyinfo->kboard;
+#else
+  kb = &the_only_kboard;
+#endif
+
   name = x_get_arg (parms, Qname, "title", "Title", string);
   if (!STRINGP (name)
       && ! EQ (name, Qunbound)
       && ! NILP (name))
-    error ("x-create-frame: name parameter must be a string");
+    error ("Invalid frame name--not a string or nil");
+
+  /* See if parent window is specified.  */
+  parent = x_get_arg (parms, Qparent_id, NULL, NULL, number);
+  if (EQ (parent, Qunbound))
+    parent = Qnil;
+  if (! NILP (parent))
+    CHECK_NUMBER (parent, 0);
 
   tem = x_get_arg (parms, Qminibuffer, 0, 0, symbol);
   if (EQ (tem, Qnone) || NILP (tem))
-    f = make_frame_without_minibuffer (Qnil);
+    f = make_frame_without_minibuffer (Qnil, kb);
   else if (EQ (tem, Qonly))
     {
       f = make_minibuffer_frame ();
       minibuffer_only = 1;
     }
   else if (WINDOWP (tem))
-    f = make_frame_without_minibuffer (tem);
+    f = make_frame_without_minibuffer (tem, kb);
   else
     f = make_frame (1);
 
   /* Note that X Windows does support scroll bars.  */
   FRAME_CAN_HAVE_SCROLL_BARS (f) = 1;
 
+  XSETFRAME (frame, f);
+  GCPRO1 (frame);
+
+  f->output_method = output_x_window;
+  f->display.x = (struct x_display *) xmalloc (sizeof (struct x_display));
+  bzero (f->display.x, sizeof (struct x_display));
+  f->display.x->icon_bitmap = -1;
+
+  FRAME_X_DISPLAY_INFO (f) = dpyinfo;
+#ifdef MULTI_KBOARD
+  FRAME_KBOARD (f) = kb;
+#endif
+
+  /* Specify the parent under which to make this X window.  */
+
+  if (!NILP (parent))
+    {
+      f->display.x->parent_desc = parent;
+      f->display.x->explicit_parent = 1;
+    }
+  else
+    {
+      f->display.x->parent_desc = FRAME_X_DISPLAY_INFO (f)->root_window;
+      f->display.x->explicit_parent = 0;
+    }
+
+  /* Note that the frame has no physical cursor right now.  */
+  f->phys_cursor_x = -1;
+
   /* Set the name; the functions to which we pass f expect the name to
      be set.  */
   if (EQ (name, Qunbound) || NILP (name))
     {
-      f->name = build_string (x_id_name);
+      f->name = build_string (dpyinfo->x_id_name);
       f->explicit_name = 0;
     }
   else
@@ -2534,21 +2826,6 @@ be shared by the new frame.")
       specbind (Qx_resource_name, name);
     }
 
-  XSETFRAME (frame, f);
-  GCPRO1 (frame);
-
-  f->output_method = output_x_window;
-  f->display.x = (struct x_display *) xmalloc (sizeof (struct x_display));
-  bzero (f->display.x, sizeof (struct x_display));
-  f->display.x->icon_bitmap = -1;
-
-  FRAME_X_SCREEN (f) = &the_x_screen;
-  FRAME_X_SCREEN (f)->reference_count++;
-  the_x_screen.x_display_value = x_current_display;
-
-  /* Note that the frame has no physical cursor right now.  */
-  f->phys_cursor_x = -1;
-
   /* Extract the window parameters from the supplied values
      that are needed to determine window geometry.  */
   {
@@ -2579,6 +2856,12 @@ be shared by the new frame.")
                         "font", "Font", string);
   }
 
+#ifdef USE_X_TOOLKIT
+  /* Prevent lwlib/xlwmenu.c from crashing because of a bug
+     whereby it fails to get any font.  */
+  xlwmenu_default_font = f->display.x->font;
+#endif
+
   x_default_parameter (f, parms, Qborder_width, make_number (2),
                       "borderwidth", "BorderWidth", number);
   /* This defaults to 2 in order to match xterm.  We recognize either
@@ -2599,7 +2882,7 @@ be shared by the new frame.")
   x_default_parameter (f, parms, Qvertical_scroll_bars, Qt,
                       "verticalScrollBars", "ScrollBars", boolean);
 
-  /* Also do the stuff which must be set before the window exists. */
+  /* Also do the stuff which must be set before the window exists.  */
   x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
                       "foreground", "Foreground", string);
   x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
@@ -2616,7 +2899,7 @@ be shared by the new frame.")
   x_default_parameter (f, parms, Qscroll_bar_width, Qnil,
                       "scrollBarWidth", "ScrollBarWidth", number);
 
-  f->display.x->parent_desc = ROOT_WINDOW;
+  f->display.x->parent_desc = FRAME_X_DISPLAY_INFO (f)->root_window;
   window_prompting = x_figure_window_size (f, parms);
 
   if (window_prompting & XNegative)
@@ -2659,18 +2942,17 @@ be shared by the new frame.")
 
   /* Dimensions, especially f->height, must be done via change_frame_size.
      Change will not be effected unless different from the current
-     f->height. */
+     f->height.  */
   width = f->width;
   height = f->height;
   f->height = f->width = 0;
   change_frame_size (f, height, width, 1, 0);
 
-/* With the toolkit, the geometry management is done in x_window.  */
-#ifndef USE_X_TOOLKIT
+  /* Tell the server what size and position, etc, we want,
+     and how badly we want them.  */
   BLOCK_INPUT;
   x_wm_set_size_hint (f, window_prompting, 0);
   UNBLOCK_INPUT;
-#endif /* USE_X_TOOLKIT */
 
   tem = x_get_arg (parms, Qunsplittable, 0, 0, boolean);
   f->no_split = minibuffer_only || EQ (tem, Qt);
@@ -2683,35 +2965,46 @@ be shared by the new frame.")
      or making it visible won't work.  */
   Vframe_list = Fcons (frame, Vframe_list);
 
+  /* Now that the frame is official, it counts as a reference to
+     its display.  */
+  FRAME_X_DISPLAY_INFO (f)->reference_count++;
+
   /* Make the window appear on the frame and enable display,
-     unless the caller says not to.  */
-  {
-    Lisp_Object visibility;
-
-    visibility = x_get_arg (parms, Qvisibility, 0, 0, symbol);
-    if (EQ (visibility, Qunbound))
-      visibility = Qt;
-
-    if (EQ (visibility, Qicon))
-      x_iconify_frame (f);
-    else if (! NILP (visibility))
-      x_make_frame_visible (f);
-    else
-      /* Must have been Qnil.  */
-      ;
-  }
+     unless the caller says not to.  However, with explicit parent,
+     Emacs cannot control visibility, so don't try.  */
+  if (! f->display.x->explicit_parent)
+    {
+      Lisp_Object visibility;
+
+      visibility = x_get_arg (parms, Qvisibility, 0, 0, symbol);
+      if (EQ (visibility, Qunbound))
+       visibility = Qt;
+
+      if (EQ (visibility, Qicon))
+       x_iconify_frame (f);
+      else if (! NILP (visibility))
+       x_make_frame_visible (f);
+      else
+       /* Must have been Qnil.  */
+       ;
+    }
 
   return unbind_to (count, frame);
 }
 
+/* FRAME is used only to get a handle on the X display.  We don't pass the
+   display info directly because we're called from frame.c, which doesn't
+   know about that structure.  */
 Lisp_Object
-x_get_focus_frame ()
+x_get_focus_frame (frame)
+     struct frame *frame;
 {
+  struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (frame);
   Lisp_Object xfocus;
-  if (! x_focus_frame)
+  if (! dpyinfo->x_focus_frame)
     return Qnil;
 
-  XSETFRAME (xfocus, x_focus_frame);
+  XSETFRAME (xfocus, dpyinfo->x_focus_frame);
   return xfocus;
 }
 
@@ -2737,11 +3030,16 @@ DEFUN ("unfocus-frame", Funfocus_frame, Sunfocus_frame, 0, 0, 0,
   "If a frame has been focused, release it.")
   ()
 {
-  if (x_focus_frame)
+  if (FRAME_X_P (selected_frame))
     {
-      BLOCK_INPUT;
-      x_unfocus_frame (x_focus_frame);
-      UNBLOCK_INPUT;
+      struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (selected_frame);
+
+      if (dpyinfo->x_focus_frame)
+       {
+         BLOCK_INPUT;
+         x_unfocus_frame (dpyinfo->x_focus_frame);
+         UNBLOCK_INPUT;
+       }
     }
 
   return Qnil;
@@ -2756,7 +3054,7 @@ PATTERN is a string, perhaps with wildcard characters;\n\
   the * character matches any substring, and\n\
   the ? character matches any single character.\n\
   PATTERN is case-insensitive.\n\
-FACE is a face name - a symbol.\n\
+FACE is a face name--a symbol.\n\
 \n\
 The return value is a list of strings, suitable as arguments to\n\
 set-face-font.\n\
@@ -2768,7 +3066,9 @@ even if they match PATTERN and FACE.")
 {
   int num_fonts;
   char **names;
+#ifndef BROKEN_XLISTFONTSWITHINFO
   XFontStruct *info;
+#endif
   XFontStruct *size_ref;
   Lisp_Object list;
   FRAME_PTR f;
@@ -2777,10 +3077,8 @@ even if they match PATTERN and FACE.")
   CHECK_STRING (pattern, 0);
   if (!NILP (face))
     CHECK_SYMBOL (face, 1);
-  if (!NILP (frame))
-    CHECK_LIVE_FRAME (frame, 2);
 
-  f = NILP (frame) ? selected_frame : XFRAME (frame);
+  f = check_x_frame (frame);
 
   /* Determine the width standard for comparison with the fonts we find.  */
 
@@ -2808,7 +3106,8 @@ even if they match PATTERN and FACE.")
     }
 
   /* See if we cached the result for this particular query.  */
-  list = Fassoc (pattern, FRAME_X_SCREEN (f)->font_list_cache);
+  list = Fassoc (pattern,
+                XCONS (FRAME_X_DISPLAY_INFO (f)->name_list_element)->cdr);
 
   /* We have info in the cache for this PATTERN.  */
   if (!NILP (list))
@@ -2829,13 +3128,13 @@ even if they match PATTERN and FACE.")
        {
          XFontStruct *thisinfo;
 
-          thisinfo = XLoadQueryFont (x_current_display,
+          thisinfo = XLoadQueryFont (FRAME_X_DISPLAY (f),
                                     XSTRING (XCONS (tem)->car)->data);
 
           if (thisinfo && same_size_fonts (thisinfo, size_ref))
            newlist = Fcons (XCONS (tem)->car, newlist);
 
-         XFreeFont (x_current_display, thisinfo);
+         XFreeFont (FRAME_X_DISPLAY (f), thisinfo);
         }
 
       UNBLOCK_INPUT;
@@ -2846,18 +3145,20 @@ even if they match PATTERN and FACE.")
   BLOCK_INPUT;
 
   /* Solaris 2.3 has a bug in XListFontsWithInfo.  */
-#ifdef BROKEN_XLISTFONTSWITHINFO
-  names = XListFonts (x_current_display,
-                      XSTRING (pattern)->data,
-                      2000, /* maxnames */
-                      &num_fonts); /* count_return */
-#else
-  names = XListFontsWithInfo (x_current_display,
-                             XSTRING (pattern)->data,
-                             2000, /* maxnames */
-                             &num_fonts, /* count_return */
-                             &info); /* info_return */
+#ifndef BROKEN_XLISTFONTSWITHINFO
+  if (size_ref)
+    names = XListFontsWithInfo (FRAME_X_DISPLAY (f),
+                               XSTRING (pattern)->data,
+                               2000, /* maxnames */
+                               &num_fonts, /* count_return */
+                               &info); /* info_return */
+  else
 #endif
+    names = XListFonts (FRAME_X_DISPLAY (f),
+                       XSTRING (pattern)->data,
+                       2000, /* maxnames */
+                       &num_fonts); /* count_return */
+
   UNBLOCK_INPUT;
 
   list = Qnil;
@@ -2872,35 +3173,44 @@ even if they match PATTERN and FACE.")
       full_list = Qnil;
       for (i = 0; i < num_fonts; i++)
        full_list = Fcons (build_string (names[i]), full_list);
-      FRAME_X_SCREEN (f)->font_list_cache
+      XCONS (FRAME_X_DISPLAY_INFO (f)->name_list_element)->cdr
        = Fcons (Fcons (pattern, full_list),
-                FRAME_X_SCREEN (f)->font_list_cache);
+                XCONS (FRAME_X_DISPLAY_INFO (f)->name_list_element)->cdr);
 
       /* Make a list of the fonts that have the right width.  */
       list = Qnil;
       for (i = 0; i < num_fonts; i++)
         {
-         XFontStruct *thisinfo;
+         int keeper;
 
+         if (!size_ref)
+           keeper = 1;
+         else
+           {
 #ifdef BROKEN_XLISTFONTSWITHINFO
-          BLOCK_INPUT;
-          thisinfo = XLoadQueryFont (x_current_display, names[i]);
-          UNBLOCK_INPUT;
+             XFontStruct *thisinfo;
+
+             BLOCK_INPUT;
+             thisinfo = XLoadQueryFont (FRAME_X_DISPLAY (f), names[i]);
+             UNBLOCK_INPUT;
+
+             keeper = thisinfo && same_size_fonts (thisinfo, size_ref);
 #else
-         thisinfo = &info[i];
+             keeper = same_size_fonts (&info[i], size_ref);
 #endif
-          if (thisinfo && (! size_ref
-                          || same_size_fonts (thisinfo, size_ref)))
+           }
+          if (keeper)
            list = Fcons (build_string (names[i]), list);
         }
       list = Fnreverse (list);
 
       BLOCK_INPUT;
-#ifdef BROKEN_XLISTFONTSWITHINFO
-      XFreeFontNames (names);
-#else
-      XFreeFontInfo (names, info, num_fonts);
+#ifndef BROKEN_XLISTFONTSWITHINFO
+      if (size_ref)
+       XFreeFontInfo (names, info, num_fonts);
+      else
 #endif
+       XFreeFontNames (names);
       UNBLOCK_INPUT;
     }
 
@@ -2908,35 +3218,38 @@ even if they match PATTERN and FACE.")
 }
 
 \f
-DEFUN ("x-color-defined-p", Fx_color_defined_p, Sx_color_defined_p, 1, 1, 0,
-  "Return non-nil if the X display supports the color named COLOR.")
-  (color)
-     Lisp_Object color;
+DEFUN ("x-color-defined-p", Fx_color_defined_p, Sx_color_defined_p, 1, 2, 0,
+       "Return non-nil if color COLOR is supported on frame FRAME.\n\
+If FRAME is omitted or nil, use the selected frame.")
+  (color, frame)
+     Lisp_Object color, frame;
 {
-  Color foo;
-  
-  check_x ();
-  CHECK_STRING (color, 0);
+  XColor foo;
+  FRAME_PTR f = check_x_frame (frame);
 
-  if (defined_color (XSTRING (color)->data, &foo, 0))
+  CHECK_STRING (color, 1);
+
+  if (defined_color (f, XSTRING (color)->data, &foo, 0))
     return Qt;
   else
     return Qnil;
 }
 
-DEFUN ("x-color-values", Fx_color_values, Sx_color_values, 1, 1, 0,
-  "Return a description of the color named COLOR.\n\
+DEFUN ("x-color-values", Fx_color_values, Sx_color_values, 1, 2, 0,
+  "Return a description of the color named COLOR on frame FRAME.\n\
 The value is a list of integer RGB values--(RED GREEN BLUE).\n\
-These values appear to range from 0 to 65280; white is (65280 65280 65280).")
-  (color)
-     Lisp_Object color;
+These values appear to range from 0 to 65280 or 65535, depending\n\
+on the system; white is (65280 65280 65280) or (65535 65535 65535).\n\
+If FRAME is omitted or nil, use the selected frame.")
+  (color, frame)
+     Lisp_Object color, frame;
 {
-  Color foo;
-  
-  check_x ();
-  CHECK_STRING (color, 0);
+  XColor foo;
+  FRAME_PTR f = check_x_frame (frame);
 
-  if (defined_color (XSTRING (color)->data, &foo, 0))
+  CHECK_STRING (color, 1);
+
+  if (defined_color (f, XSTRING (color)->data, &foo, 0))
     {
       Lisp_Object rgb[3];
 
@@ -2949,16 +3262,20 @@ These values appear to range from 0 to 65280; white is (65280 65280 65280).")
     return Qnil;
 }
 
-DEFUN ("x-display-color-p", Fx_display_color_p, Sx_display_color_p, 0, 0, 0,
-  "Return t if the X screen currently in use supports color.")
-  ()
+DEFUN ("x-display-color-p", Fx_display_color_p, Sx_display_color_p, 0, 1, 0,
+  "Return t if the X display supports color.\n\
+The optional argument DISPLAY specifies which display to ask about.\n\
+DISPLAY should be either a frame or a display name (a string).\n\
+If omitted or nil, that stands for the selected frame's display.")
+  (display)
+     Lisp_Object display;
 {
-  check_x ();
+  struct x_display_info *dpyinfo = check_x_display_info (display);
 
-  if (x_screen_planes <= 2)
+  if (dpyinfo->n_planes <= 2)
     return Qnil;
 
-  switch (screen_visual->class)
+  switch (dpyinfo->visual->class)
     {
     case StaticColor:
     case PseudoColor:
@@ -2972,139 +3289,182 @@ DEFUN ("x-display-color-p", Fx_display_color_p, Sx_display_color_p, 0, 0, 0,
 }
 
 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p, Sx_display_grayscale_p,
-  0, 0, 0,
-  "Return t if the X screen currently in use supports grayscale.")
-  ()
+  0, 1, 0,
+  "Return t if the X display supports shades of gray.\n\
+The optional argument DISPLAY specifies which display to ask about.\n\
+DISPLAY should be either a frame or a display name (a string).\n\
+If omitted or nil, that stands for the selected frame's display.")
+  (display)
+     Lisp_Object display;
 {
-  check_x ();
+  struct x_display_info *dpyinfo = check_x_display_info (display);
 
-  return (x_screen_planes > 1
-         && (screen_visual->class == StaticGray
-             || screen_visual->class == GrayScale));
+  if (dpyinfo->n_planes <= 2)
+    return Qnil;
+
+  return (dpyinfo->n_planes > 1
+         && (dpyinfo->visual->class == StaticGray
+             || dpyinfo->visual->class == GrayScale));
 }
 
 DEFUN ("x-display-pixel-width", Fx_display_pixel_width, Sx_display_pixel_width,
   0, 1, 0,
-  "Returns the width in pixels of the display FRAME is on.")
-  (frame)
-     Lisp_Object frame;
+  "Returns the width in pixels of the X display DISPLAY.\n\
+The optional argument DISPLAY specifies which display to ask about.\n\
+DISPLAY should be either a frame or a display name (a string).\n\
+If omitted or nil, that stands for the selected frame's display.")
+  (display)
+     Lisp_Object display;
 {
-  Display *dpy = x_current_display;
-  check_x ();
-  return make_number (DisplayWidth (dpy, DefaultScreen (dpy)));
+  struct x_display_info *dpyinfo = check_x_display_info (display);
+
+  return make_number (dpyinfo->width);
 }
 
 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
   Sx_display_pixel_height, 0, 1, 0,
-  "Returns the height in pixels of the display FRAME is on.")
-  (frame)
-     Lisp_Object frame;
+  "Returns the height in pixels of the X display DISPLAY.\n\
+The optional argument DISPLAY specifies which display to ask about.\n\
+DISPLAY should be either a frame or a display name (a string).\n\
+If omitted or nil, that stands for the selected frame's display.")
+  (display)
+     Lisp_Object display;
 {
-  Display *dpy = x_current_display;
-  check_x ();
-  return make_number (DisplayHeight (dpy, DefaultScreen (dpy)));
+  struct x_display_info *dpyinfo = check_x_display_info (display);
+
+  return make_number (dpyinfo->height);
 }
 
 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
   0, 1, 0,
-  "Returns the number of bitplanes of the display FRAME is on.")
-  (frame)
-     Lisp_Object frame;
+  "Returns the number of bitplanes of the X display DISPLAY.\n\
+The optional argument DISPLAY specifies which display to ask about.\n\
+DISPLAY should be either a frame or a display name (a string).\n\
+If omitted or nil, that stands for the selected frame's display.")
+  (display)
+     Lisp_Object display;
 {
-  Display *dpy = x_current_display;
-  check_x ();
-  return make_number (DisplayPlanes (dpy, DefaultScreen (dpy)));
+  struct x_display_info *dpyinfo = check_x_display_info (display);
+
+  return make_number (dpyinfo->n_planes);
 }
 
 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
   0, 1, 0,
-  "Returns the number of color cells of the display FRAME is on.")
-  (frame)
-     Lisp_Object frame;
+  "Returns the number of color cells of the X display DISPLAY.\n\
+The optional argument DISPLAY specifies which display to ask about.\n\
+DISPLAY should be either a frame or a display name (a string).\n\
+If omitted or nil, that stands for the selected frame's display.")
+  (display)
+     Lisp_Object display;
 {
-  Display *dpy = x_current_display;
-  check_x ();
-  return make_number (DisplayCells (dpy, DefaultScreen (dpy)));
+  struct x_display_info *dpyinfo = check_x_display_info (display);
+
+  return make_number (DisplayCells (dpyinfo->display,
+                                   XScreenNumberOfScreen (dpyinfo->screen)));
 }
 
 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
        Sx_server_max_request_size,
   0, 1, 0,
-  "Returns the maximum request size of the X server FRAME is using.")
-  (frame)
-     Lisp_Object frame;
+  "Returns the maximum request size of the X server of display DISPLAY.\n\
+The optional argument DISPLAY specifies which display to ask about.\n\
+DISPLAY should be either a frame or a display name (a string).\n\
+If omitted or nil, that stands for the selected frame's display.")
+  (display)
+     Lisp_Object display;
 {
-  Display *dpy = x_current_display;
-  check_x ();
-  return make_number (MAXREQUEST (dpy));
+  struct x_display_info *dpyinfo = check_x_display_info (display);
+
+  return make_number (MAXREQUEST (dpyinfo->display));
 }
 
 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
-  "Returns the vendor ID string of the X server FRAME is on.")
-  (frame)
-     Lisp_Object frame;
+  "Returns the vendor ID string of the X server of display DISPLAY.\n\
+The optional argument DISPLAY specifies which display to ask about.\n\
+DISPLAY should be either a frame or a display name (a string).\n\
+If omitted or nil, that stands for the selected frame's display.")
+  (display)
+     Lisp_Object display;
 {
-  Display *dpy = x_current_display;
-  char *vendor;
-  check_x ();
-  vendor = ServerVendor (dpy);
+  struct x_display_info *dpyinfo = check_x_display_info (display);
+  char *vendor = ServerVendor (dpyinfo->display);
+
   if (! vendor) vendor = "";
   return build_string (vendor);
 }
 
 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
-  "Returns the version numbers of the X server in use.\n\
+  "Returns the version numbers of the X server of display DISPLAY.\n\
 The value is a list of three integers: the major and minor\n\
 version numbers of the X Protocol in use, and the vendor-specific release\n\
-number.  See also the variable `x-server-vendor'.")
-  (frame)
-     Lisp_Object frame;
+number.  See also the function `x-server-vendor'.\n\n\
+The optional argument DISPLAY specifies which display to ask about.\n\
+DISPLAY should be either a frame or a display name (a string).\n\
+If omitted or nil, that stands for the selected frame's display.")
+  (display)
+     Lisp_Object display;
 {
-  Display *dpy = x_current_display;
+  struct x_display_info *dpyinfo = check_x_display_info (display);
+  Display *dpy = dpyinfo->display;
 
-  check_x ();
   return Fcons (make_number (ProtocolVersion (dpy)),
                Fcons (make_number (ProtocolRevision (dpy)),
                       Fcons (make_number (VendorRelease (dpy)), Qnil)));
 }
 
 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
-  "Returns the number of screens on the X server FRAME is on.")
-  (frame)
-     Lisp_Object frame;
+  "Returns the number of screens on the X server of display DISPLAY.\n\
+The optional argument DISPLAY specifies which display to ask about.\n\
+DISPLAY should be either a frame or a display name (a string).\n\
+If omitted or nil, that stands for the selected frame's display.")
+  (display)
+     Lisp_Object display;
 {
-  check_x ();
-  return make_number (ScreenCount (x_current_display));
+  struct x_display_info *dpyinfo = check_x_display_info (display);
+
+  return make_number (ScreenCount (dpyinfo->display));
 }
 
 DEFUN ("x-display-mm-height", Fx_display_mm_height, Sx_display_mm_height, 0, 1, 0,
-  "Returns the height in millimeters of the X screen FRAME is on.")
-  (frame)
-     Lisp_Object frame;
+  "Returns the height in millimeters of the X display DISPLAY.\n\
+The optional argument DISPLAY specifies which display to ask about.\n\
+DISPLAY should be either a frame or a display name (a string).\n\
+If omitted or nil, that stands for the selected frame's display.")
+  (display)
+     Lisp_Object display;
 {
-  check_x ();
-  return make_number (HeightMMOfScreen (x_screen));
+  struct x_display_info *dpyinfo = check_x_display_info (display);
+
+  return make_number (HeightMMOfScreen (dpyinfo->screen));
 }
 
 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
-  "Returns the width in millimeters of the X screen FRAME is on.")
-  (frame)
-     Lisp_Object frame;
+  "Returns the width in millimeters of the X display DISPLAY.\n\
+The optional argument DISPLAY specifies which display to ask about.\n\
+DISPLAY should be either a frame or a display name (a string).\n\
+If omitted or nil, that stands for the selected frame's display.")
+  (display)
+     Lisp_Object display;
 {
-  check_x ();
-  return make_number (WidthMMOfScreen (x_screen));
+  struct x_display_info *dpyinfo = check_x_display_info (display);
+
+  return make_number (WidthMMOfScreen (dpyinfo->screen));
 }
 
 DEFUN ("x-display-backing-store", Fx_display_backing_store,
   Sx_display_backing_store, 0, 1, 0,
-  "Returns an indication of whether the X screen FRAME is on does backing store.\n\
-The value may be `always', `when-mapped', or `not-useful'.")
-  (frame)
-     Lisp_Object frame;
+  "Returns an indication of whether X display DISPLAY does backing store.\n\
+The value may be `always', `when-mapped', or `not-useful'.\n\
+The optional argument DISPLAY specifies which display to ask about.\n\
+DISPLAY should be either a frame or a display name (a string).\n\
+If omitted or nil, that stands for the selected frame's display.")
+  (display)
+     Lisp_Object display;
 {
-  check_x ();
+  struct x_display_info *dpyinfo = check_x_display_info (display);
 
-  switch (DoesBackingStore (x_screen))
+  switch (DoesBackingStore (dpyinfo->screen))
     {
     case Always:
       return intern ("always");
@@ -3122,15 +3482,18 @@ The value may be `always', `when-mapped', or `not-useful'.")
 
 DEFUN ("x-display-visual-class", Fx_display_visual_class,
   Sx_display_visual_class, 0, 1, 0,
-  "Returns the visual class of the display `screen' is on.\n\
+  "Returns the visual class of the X display DISPLAY.\n\
 The value is one of the symbols `static-gray', `gray-scale',\n\
-`static-color', `pseudo-color', `true-color', or `direct-color'.")
-       (screen)
-     Lisp_Object screen;
+`static-color', `pseudo-color', `true-color', or `direct-color'.\n\n\
+The optional argument DISPLAY specifies which display to ask about.\n\
+DISPLAY should be either a frame or a display name (a string).\n\
+If omitted or nil, that stands for the selected frame's display.")
+       (display)
+     Lisp_Object display;
 {
-  check_x ();
+  struct x_display_info *dpyinfo = check_x_display_info (display);
 
-  switch (screen_visual->class)
+  switch (dpyinfo->visual->class)
     {
     case StaticGray:  return (intern ("static-gray"));
     case GrayScale:   return (intern ("gray-scale"));
@@ -3145,47 +3508,61 @@ The value is one of the symbols `static-gray', `gray-scale',\n\
 
 DEFUN ("x-display-save-under", Fx_display_save_under,
   Sx_display_save_under, 0, 1, 0,
-  "Returns t if the X screen FRAME is on supports the save-under feature.")
-  (frame)
-     Lisp_Object frame;
+  "Returns t if the X display DISPLAY supports the save-under feature.\n\
+The optional argument DISPLAY specifies which display to ask about.\n\
+DISPLAY should be either a frame or a display name (a string).\n\
+If omitted or nil, that stands for the selected frame's display.")
+  (display)
+     Lisp_Object display;
 {
-  check_x ();
+  struct x_display_info *dpyinfo = check_x_display_info (display);
 
-  if (DoesSaveUnders (x_screen) == True)
+  if (DoesSaveUnders (dpyinfo->screen) == True)
     return Qt;
   else
     return Qnil;
 }
 \f
+int
 x_pixel_width (f)
      register struct frame *f;
 {
   return PIXEL_WIDTH (f);
 }
 
+int
 x_pixel_height (f)
      register struct frame *f;
 {
   return PIXEL_HEIGHT (f);
 }
 
+int
 x_char_width (f)
      register struct frame *f;
 {
   return FONT_WIDTH (f->display.x->font);
 }
 
+int
 x_char_height (f)
      register struct frame *f;
 {
   return f->display.x->line_height;
 }
+
+int
+x_screen_planes (frame)
+     Lisp_Object frame;
+{
+  return FRAME_X_DISPLAY_INFO (XFRAME (frame))->n_planes;
+}
 \f
 #if 0  /* These no longer seem like the right way to do things.  */
 
 /* Draw a rectangle on the frame with left top corner including
    the character specified by LEFT_CHAR and TOP_CHAR.  The rectangle is
-   CHARS by LINES wide and long and is the color of the cursor. */
+   CHARS by LINES wide and long and is the color of the cursor.  */
 
 void
 x_rectangle (f, gc, left_char, top_char, chars, lines)
@@ -3209,7 +3586,7 @@ x_rectangle (f, gc, left_char, top_char, chars, lines)
   else
     height = f->display.x->line_height * lines;
 
-  XDrawRectangle (x_current_display, FRAME_X_WINDOW (f),
+  XDrawRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
                  gc, left, top, width, height);
 }
 
@@ -3270,7 +3647,7 @@ X0, Y0, X1, Y1 in the regular background-pixel.")
 {
   register int x0, y0, x1, y1, top, left, n_chars, n_lines;
 
-  CHECK_FRAME (frame, 0);
+  CHECK_LIVE_FRAME (frame, 0);
   CHECK_NUMBER (X0, 0);
   CHECK_NUMBER (Y0, 1);
   CHECK_NUMBER (X1, 2);
@@ -3313,7 +3690,7 @@ X0, Y0, X1, Y1 in the regular background-pixel.")
 
 /* Draw lines around the text region beginning at the character position
    TOP_X, TOP_Y and ending at BOTTOM_X and BOTTOM_Y.  GC specifies the
-   pixel and line characteristics. */
+   pixel and line characteristics.  */
 
 #define line_len(line) (FRAME_CURRENT_GLYPHS (f)->used[(line)])
 
@@ -3339,7 +3716,7 @@ outline_region (f, gc, top_x, top_y, bottom_x, bottom_y)
       this_point->y = ibw + (font_h * top_y);
       this_point++;
       if (x == 0)
-       this_point->x = ibw + (font_w / 2); /* Half-size for newline chars. */
+       this_point->x = ibw + (font_w / 2); /* Half-size for newline chars.  */
       else
        this_point->x = ibw + (font_w * x);
       this_point->y = (this_point - 1)->y;
@@ -3359,7 +3736,7 @@ outline_region (f, gc, top_x, top_y, bottom_x, bottom_y)
       this_point->y = (this_point - 1)->y;
     }
 
-  /* Now do the right side. */
+  /* Now do the right side.  */
   while (y < bottom_y)
     {                          /* Right vertical edge */
       this_point++;
@@ -3377,7 +3754,7 @@ outline_region (f, gc, top_x, top_y, bottom_x, bottom_y)
       this_point->y = (this_point - 1)->y;
     }
 
-  /* Now do the bottom and connect to the top left point. */
+  /* Now do the bottom and connect to the top left point.  */
   this_point->x = ibw + (font_w * (bottom_x + 1));
 
   this_point++;
@@ -3390,7 +3767,7 @@ outline_region (f, gc, top_x, top_y, bottom_x, bottom_y)
   this_point->x = pixel_points->x;
   this_point->y = pixel_points->y;
 
-  XDrawLines (x_current_display, FRAME_X_WINDOW (f),
+  XDrawLines (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
              gc, pixel_points,
              (this_point - pixel_points + 1), CoordModeOrigin);
 }
@@ -3411,8 +3788,8 @@ selected frame.")
   x0 = XINT (Fcar (Fcar (event)));
   y0 = XINT (Fcar (Fcdr (Fcar (event))));
 
-  /* If the mouse is past the end of the line, don't that area. */
-  /* ReWrite this... */
+  /* If the mouse is past the end of the line, don't that area.  */
+  /* ReWrite this...  */
 
   x1 = f->cursor_x;
   y1 = f->cursor_y;
@@ -3433,7 +3810,7 @@ selected frame.")
                       x1, y1, (x0 - x1 + 1), 1);
     }
 
-  XFlush (x_current_display);
+  XFlush (FRAME_X_DISPLAY (f));
   UNBLOCK_INPUT;
 
   return Qnil;
@@ -3481,7 +3858,7 @@ int contour_npoints;
 
 /* Clip the top part of the contour lines down (and including) line Y_POS.
    If X_POS is in the middle (rather than at the end) of the line, drop
-   down a line at that character. */
+   down a line at that character.  */
 
 static void
 clip_contour_top (y_pos, x_pos)
@@ -3491,7 +3868,7 @@ clip_contour_top (y_pos, x_pos)
   register int npoints;
   register struct display_line *line = selected_frame->phys_lines[y_pos + 1];
 
-  if (x_pos >= line->len - 1)  /* Draw one, straight horizontal line. */
+  if (x_pos >= line->len - 1)  /* Draw one, straight horizontal line.  */
     {
       end = contour_lines[y_pos].top_right;
       npoints = (end - begin + 1);
@@ -3504,7 +3881,7 @@ clip_contour_top (y_pos, x_pos)
                  contour_erase_gc, begin, 2, CoordModeOrigin);
       XFlush (x_current_display);
 
-      /* Now, update contour_lines structure. */
+      /* Now, update contour_lines structure.  */
     }
                                /* ______.         */
   else                         /*       |________*/
@@ -3526,12 +3903,12 @@ clip_contour_top (y_pos, x_pos)
                  contour_erase_gc, begin, 4, CoordModeOrigin);
       XFlush (x_current_display);
 
-      /* Now, update contour_lines structure. */
+      /* Now, update contour_lines structure.  */
     }
 }
 
 /* Erase the top horizontal lines of the contour, and then extend
-   the contour upwards. */
+   the contour upwards.  */
 
 static void
 extend_contour_top (line)
@@ -3585,7 +3962,7 @@ DEFUN ("x-select-region", Fx_select_region, Sx_select_region, 1, 1, "e",
 
      if (mouse_below_point)
        {
-        if (x_mouse_y <= point_y)                /* Flipped. */
+        if (x_mouse_y <= point_y)                /* Flipped.  */
           {
             mouse_below_point = 0;
 
@@ -3594,11 +3971,11 @@ DEFUN ("x-select-region", Fx_select_region, Sx_select_region, 1, 1, "e",
             outline_region (f, f->display.x->cursor_gc, x_mouse_x, x_mouse_y,
                             point_x, point_y);
           }
-        else if (x_mouse_y < x_contour_y)        /* Bottom clipped. */
+        else if (x_mouse_y < x_contour_y)        /* Bottom clipped.  */
           {
             clip_contour_bottom (x_mouse_y);
           }
-        else if (x_mouse_y > x_contour_y)        /* Bottom extended. */
+        else if (x_mouse_y > x_contour_y)        /* Bottom extended.  */
           {
             extend_bottom_contour (x_mouse_y);
           }
@@ -3608,7 +3985,7 @@ DEFUN ("x-select-region", Fx_select_region, Sx_select_region, 1, 1, "e",
        }
      else  /* mouse above or same line as point */
        {
-        if (x_mouse_y >= point_y)                /* Flipped. */
+        if (x_mouse_y >= point_y)                /* Flipped.  */
           {
             mouse_below_point = 1;
 
@@ -3617,11 +3994,11 @@ DEFUN ("x-select-region", Fx_select_region, Sx_select_region, 1, 1, "e",
             outline_region (f, f->display.x->cursor_gc, point_x, point_y,
                             x_mouse_x, x_mouse_y);
           }
-        else if (x_mouse_y > x_contour_y)        /* Top clipped. */
+        else if (x_mouse_y > x_contour_y)        /* Top clipped.  */
           {
             clip_contour_top (x_mouse_y);
           }
-        else if (x_mouse_y < x_contour_y)        /* Top extended. */
+        else if (x_mouse_y < x_contour_y)        /* Top extended.  */
           {
             extend_contour_top (x_mouse_y);
           }
@@ -3680,18 +4057,18 @@ DEFUN ("x-horizontal-line", Fx_horizontal_line, Sx_horizontal_line, 1, 1, "e",
   gc_values.cap_style = CapRound;
   gc_values.join_style = JoinRound;
 
-  line_gc = XCreateGC (x_current_display, FRAME_X_WINDOW (f),
+  line_gc = XCreateGC (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
                       GCLineStyle | GCJoinStyle | GCCapStyle
                       | GCLineWidth | GCForeground | GCBackground,
                       &gc_values);
-  XSetDashes (x_current_display, line_gc, 0, dash_list, dashes);
+  XSetDashes (FRAME_X_DISPLAY (f), line_gc, 0, dash_list, dashes);
   gc_values.foreground = f->display.x->background_pixel;
   gc_values.background = f->display.x->foreground_pixel;
-  erase_gc = XCreateGC (x_current_display, FRAME_X_WINDOW (f),
+  erase_gc = XCreateGC (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
                       GCLineStyle | GCJoinStyle | GCCapStyle
                       | GCLineWidth | GCForeground | GCBackground,
                       &gc_values);
-  XSetDashes (x_current_display, erase_gc, 0, dash_list, dashes);
+  XSetDashes (FRAME_X_DISPLAY (f), erase_gc, 0, dash_list, dashes);
 #endif
 
   while (1)
@@ -3703,10 +4080,10 @@ DEFUN ("x-horizontal-line", Fx_horizontal_line, Sx_horizontal_line, 1, 1, "e",
          previous_y = x_mouse_y;
          line = (x_mouse_y + 1) * f->display.x->line_height
            + f->display.x->internal_border_width;
-         XDrawLine (x_current_display, FRAME_X_WINDOW (f),
+         XDrawLine (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
                     line_gc, left, line, right, line);
        }
-      XFlushQueue ();
+      XFlush (FRAME_X_DISPLAY (f));
       UNBLOCK_INPUT;
 
       do
@@ -3718,13 +4095,13 @@ DEFUN ("x-horizontal-line", Fx_horizontal_line, Sx_horizontal_line, 1, 1, "e",
              || x_mouse_grabbed)
            {
              BLOCK_INPUT;
-             XDrawLine (x_current_display, FRAME_X_WINDOW (f),
+             XDrawLine (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
                         erase_gc, left, line, right, line);
              UNBLOCK_INPUT;
              unread_command_event = obj;
 #if 0
-             XFreeGC (x_current_display, line_gc);
-             XFreeGC (x_current_display, erase_gc);
+             XFreeGC (FRAME_X_DISPLAY (f), line_gc);
+             XFreeGC (FRAME_X_DISPLAY (f), erase_gc);
 #endif 
              return Qnil;
            }
@@ -3732,20 +4109,20 @@ DEFUN ("x-horizontal-line", Fx_horizontal_line, Sx_horizontal_line, 1, 1, "e",
       while (x_mouse_y == previous_y);
 
       BLOCK_INPUT;
-      XDrawLine (x_current_display, FRAME_X_WINDOW (f),
+      XDrawLine (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
                 erase_gc, left, line, right, line);
       UNBLOCK_INPUT;
     }
 }
 #endif
 \f
-/* Offset in buffer of character under the pointer, or 0. */
-int mouse_buffer_offset;
-
 #if 0
-/* These keep track of the rectangle following the pointer. */
+/* These keep track of the rectangle following the pointer.  */
 int mouse_track_top, mouse_track_left, mouse_track_width;
 
+/* Offset in buffer of character under the pointer, or 0.  */
+int mouse_buffer_offset;
+
 DEFUN ("x-track-pointer", Fx_track_pointer, Sx_track_pointer, 0, 0, 0,
   "Track the pointer.")
   ()
@@ -3761,7 +4138,7 @@ DEFUN ("x-track-pointer", Fx_track_pointer, Sx_track_pointer, 0, 0, 0,
       struct buffer *buf;
 
       current_pointer_shape = f->display.x->nontext_cursor;
-      XDefineCursor (x_current_display,
+      XDefineCursor (FRAME_X_DISPLAY (f),
                     FRAME_X_WINDOW (f),
                     current_pointer_shape);
 
@@ -3772,12 +4149,12 @@ DEFUN ("x-track-pointer", Fx_track_pointer, Sx_track_pointer, 0, 0, 0,
           && (current_pointer_shape != f->display.x->modeline_cursor))
     {
       current_pointer_shape = f->display.x->modeline_cursor;
-      XDefineCursor (x_current_display,
+      XDefineCursor (FRAME_X_DISPLAY (f),
                     FRAME_X_WINDOW (f),
                     current_pointer_shape);
     }
 
-  XFlushQueue ();
+  XFlush (FRAME_X_DISPLAY (f));
   UNBLOCK_INPUT;
 }
 #endif
@@ -3826,7 +4203,7 @@ DEFUN ("x-track-pointer", Fx_track_pointer, Sx_track_pointer, 1, 1, "e",
          if (! FRAME_CURRENT_GLYPHS (f)->enable[x_mouse_y])
            break;
 
-         /* Erase previous rectangle. */
+         /* Erase previous rectangle.  */
          if (mouse_track_width)
            {
              x_rectangle (f, f->display.x->reverse_gc,
@@ -3845,7 +4222,7 @@ DEFUN ("x-track-pointer", Fx_track_pointer, Sx_track_pointer, 1, 1, "e",
          mouse_track_top = x_mouse_y;
          mouse_track_width = 0;
 
-         if (mouse_track_left > len) /* Past the end of line. */
+         if (mouse_track_left > len) /* Past the end of line.  */
            goto draw_or_not;
 
          if (mouse_track_top == mode_line_vpos)
@@ -3905,9 +4282,9 @@ DEFUN ("x-track-pointer", Fx_track_pointer, Sx_track_pointer, 1, 1, "e",
          while (hp <= x_mouse_x);
 
        draw_or_not:
-         if (mouse_track_width) /* Over text; use text pointer shape. */
+         if (mouse_track_width) /* Over text; use text pointer shape.  */
            {
-             XDefineCursor (x_current_display,
+             XDefineCursor (FRAME_X_DISPLAY (f),
                             FRAME_X_WINDOW (f),
                             f->display.x->text_cursor);
              x_rectangle (f, f->display.x->cursor_gc,
@@ -3915,16 +4292,16 @@ DEFUN ("x-track-pointer", Fx_track_pointer, Sx_track_pointer, 1, 1, "e",
                           mouse_track_width, 1);
            }
          else if (in_mode_line)
-           XDefineCursor (x_current_display,
+           XDefineCursor (FRAME_X_DISPLAY (f),
                           FRAME_X_WINDOW (f),
                           f->display.x->modeline_cursor);
          else
-           XDefineCursor (x_current_display,
+           XDefineCursor (FRAME_X_DISPLAY (f),
                           FRAME_X_WINDOW (f),
                           f->display.x->nontext_cursor);
        }
 
-      XFlush (x_current_display);
+      XFlush (FRAME_X_DISPLAY (f));
       UNBLOCK_INPUT;
 
       obj = read_char (-1, 0, 0, Qnil, 0);
@@ -3951,10 +4328,10 @@ DEFUN ("x-track-pointer", Fx_track_pointer, Sx_track_pointer, 1, 1, "e",
          x_display_cursor (f, 1);
        }
     }
-  XDefineCursor (x_current_display,
+  XDefineCursor (FRAME_X_DISPLAY (f),
                 FRAME_X_WINDOW (f),
                 f->display.x->nontext_cursor);
-  XFlush (x_current_display);
+  XFlush (FRAME_X_DISPLAY (f));
   UNBLOCK_INPUT;
 
   return Qnil;
@@ -3965,7 +4342,7 @@ DEFUN ("x-track-pointer", Fx_track_pointer, Sx_track_pointer, 1, 1, "e",
 #include "glyphs.h"
 
 /* Draw a pixmap specified by IMAGE_DATA of dimensions WIDTH and HEIGHT
-   on the frame F at position X, Y. */
+   on the frame F at position X, Y.  */
 
 x_draw_pixmap (f, x, y, image_data, width, height)
      struct frame *f;
@@ -3974,10 +4351,10 @@ x_draw_pixmap (f, x, y, image_data, width, height)
 {
   Pixmap image;
 
-  image = XCreateBitmapFromData (x_current_display,
+  image = XCreateBitmapFromData (FRAME_X_DISPLAY (f),
                                 FRAME_X_WINDOW (f), image_data,
                                 width, height);
-  XCopyPlane (x_current_display, image, FRAME_X_WINDOW (f),
+  XCopyPlane (FRAME_X_DISPLAY (f), image, FRAME_X_WINDOW (f),
              f->display.x->normal_gc, 0, 0, width, height, x, y);
 }
 #endif
@@ -4104,7 +4481,8 @@ XScreenNumberOfScreen (scr)
 #endif /* not HAVE_XSCREENNUMBEROFSCREEN */
 
 Visual *
-select_visual (screen, depth)
+select_visual (dpy, screen, depth)
+     Display *dpy;
      Screen *screen;
      unsigned int *depth;
 {
@@ -4122,7 +4500,7 @@ select_visual (screen, depth)
 
   vinfo_template.screen = XScreenNumberOfScreen (screen);
 
-  vinfo = XGetVisualInfo (x_current_display,
+  vinfo = XGetVisualInfo (dpy,
                          VisualIDMask | VisualScreenMask, &vinfo_template,
                          &n_visuals);
   if (n_visuals != 1)
@@ -4146,19 +4524,56 @@ select_visual (screen, depth)
   return v;
 }
 
+/* Return the X display structure for the display named NAME.
+   Open a new connection if necessary.  */
+
+struct x_display_info *
+x_display_info_for_name (name)
+     Lisp_Object name;
+{
+  Lisp_Object names;
+  struct x_display_info *dpyinfo;
+
+  CHECK_STRING (name, 0);
+
+  for (dpyinfo = x_display_list, names = x_display_name_list;
+       dpyinfo;
+       dpyinfo = dpyinfo->next, names = XCONS (names)->cdr)
+    {
+      Lisp_Object tem;
+      tem = Fstring_equal (XCONS (XCONS (names)->car)->car, name);
+      if (!NILP (tem))
+       return dpyinfo;
+    }
+
+  validate_x_resource_name ();
+
+  dpyinfo = x_term_init (name, (unsigned char *)0,
+                        XSTRING (Vx_resource_name)->data);
+
+  if (dpyinfo == 0)
+    error ("X server %s not responding", XSTRING (name)->data);
+
+  x_in_use = 1;
+  XSETFASTINT (Vwindow_system_version, 11);
+
+  return dpyinfo;
+}
+
 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
-       1, 2, 0, "Open a connection to an X server.\n\
+       1, 3, 0, "Open a connection to an X server.\n\
 DISPLAY is the name of the display to connect to.\n\
-Optional second arg XRM_STRING is a string of resources in xrdb format.")
-  (display, xrm_string)
-     Lisp_Object display, xrm_string;
+Optional second arg XRM-STRING is a string of resources in xrdb format.\n\
+If the optional third arg MUST-SUCCEED is non-nil,\n\
+terminate Emacs if we can't open the connection.")
+  (display, xrm_string, must_succeed)
+     Lisp_Object display, xrm_string, must_succeed;
 {
   unsigned int n_planes;
   unsigned char *xrm_option;
+  struct x_display_info *dpyinfo;
 
   CHECK_STRING (display, 0);
-  if (x_current_display != 0)
-    error ("X server connection is already initialized");
   if (! NILP (xrm_string))
     CHECK_STRING (xrm_string, 1);
 
@@ -4170,118 +4585,113 @@ Optional second arg XRM_STRING is a string of resources in xrdb format.")
   validate_x_resource_name ();
 
   /* This is what opens the connection and sets x_current_display.
-     This also initializes many symbols, such as those used for input. */
-  x_term_init (XSTRING (display)->data, xrm_option,
-              XSTRING (Vx_resource_name)->data);
+     This also initializes many symbols, such as those used for input.  */
+  dpyinfo = x_term_init (display, xrm_option,
+                        XSTRING (Vx_resource_name)->data);
 
-  XSETFASTINT (Vwindow_system_version, 11);
+  if (dpyinfo == 0)
+    {
+      if (!NILP (must_succeed))
+       fatal ("X server %s not responding.\n\
+Check the DISPLAY environment variable or use \"-d\"\n",
+              XSTRING (display)->data);
+      else
+       error ("X server %s not responding", XSTRING (display)->data);
+    }
 
-  BLOCK_INPUT;
-  xrdb = x_load_resources (x_current_display, xrm_option,
-                          (char *) XSTRING (Vx_resource_name)->data,
-                          EMACS_CLASS);
-  UNBLOCK_INPUT;
-#ifdef HAVE_XRMSETDATABASE
-  XrmSetDatabase (x_current_display, xrdb);
-#else
-  x_current_display->db = xrdb;
-#endif
+  x_in_use = 1;
 
-  the_x_screen.name = display;
+  XSETFASTINT (Vwindow_system_version, 11);
+  return Qnil;
+}
 
-  x_screen = DefaultScreenOfDisplay (x_current_display);
+DEFUN ("x-close-connection", Fx_close_connection,
+       Sx_close_connection, 1, 1, 0,
+   "Close the connection to DISPLAY's X server.\n\
+For DISPLAY, specify either a frame or a display name (a string).\n\
+If DISPLAY is nil, that stands for the selected frame's display.")
+  (display)
+  Lisp_Object display;
+{
+  struct x_display_info *dpyinfo = check_x_display_info (display);
+  struct x_display_info *tail;
+  int i;
 
-  screen_visual = select_visual (x_screen, &n_planes);
-  x_screen_planes = n_planes;
-  x_screen_height = HeightOfScreen (x_screen);
-  x_screen_width = WidthOfScreen (x_screen);
+  if (dpyinfo->reference_count > 0)
+    error ("Display still has frames on it");
 
-  /* X Atoms used by emacs. */
-  Xatoms_of_xselect ();
   BLOCK_INPUT;
-  Xatom_wm_protocols =     XInternAtom (x_current_display, "WM_PROTOCOLS",
-                                       False);
-  Xatom_wm_take_focus =    XInternAtom (x_current_display, "WM_TAKE_FOCUS",
-                                       False);
-  Xatom_wm_save_yourself = XInternAtom (x_current_display, "WM_SAVE_YOURSELF",
-                                       False);
-  Xatom_wm_delete_window = XInternAtom (x_current_display, "WM_DELETE_WINDOW",
-                                       False);
-  Xatom_wm_change_state =  XInternAtom (x_current_display, "WM_CHANGE_STATE",
-                                       False);
-  Xatom_wm_configure_denied =  XInternAtom (x_current_display,
-                                           "WM_CONFIGURE_DENIED", False);
-  Xatom_wm_window_moved =  XInternAtom (x_current_display, "WM_MOVED",
-                                       False);
-  Xatom_editres_name =  XInternAtom (x_current_display, "Editres", False);
+  /* Free the fonts in the font table.  */
+  for (i = 0; i < dpyinfo->n_fonts; i++)
+    {
+      if (dpyinfo->font_table[i].name)
+       free (dpyinfo->font_table[i].name);
+      /* Don't free the full_name string;
+        it is always shared with something else.  */
+      XFreeFont (dpyinfo->display, dpyinfo->font_table[i].font);
+    }
+  x_destroy_all_bitmaps (dpyinfo);
+  XSetCloseDownMode (dpyinfo->display, DestroyAll);
+
+#ifdef USE_X_TOOLKIT
+  XtCloseDisplay (dpyinfo->display);
+#else
+  XCloseDisplay (dpyinfo->display);
+#endif
+
+  x_delete_display (dpyinfo);
   UNBLOCK_INPUT;
+
   return Qnil;
 }
 
-DEFUN ("x-close-current-connection", Fx_close_current_connection,
-       Sx_close_current_connection,
-       0, 0, 0, "Close the connection to the current X server.")
+DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
+  "Return the list of display names that Emacs has connections to.")
   ()
 {
-  /* Note: If we're going to call check_x here, then the fatal error
-     can't happen.  For the moment, this check is just for safety,
-     so a user won't try out the function and get a crash.  If it's
-     really intended only to be called when killing emacs, then there's
-     no reason for it to have a lisp interface at all.  */
-  check_x();
-
-  /* This is ONLY used when killing emacs;  For switching displays
-     we'll have to take care of setting CloseDownMode elsewhere. */
+  Lisp_Object tail, result;
 
-  if (x_current_display)
-    {
-      BLOCK_INPUT;
-      XSetCloseDownMode (x_current_display, DestroyAll);
-      XCloseDisplay (x_current_display);
-      x_current_display = 0;
-    }
-  else
-    fatal ("No current X display connection to close\n");
+  result = Qnil;
+  for (tail = x_display_name_list; ! NILP (tail); tail = XCONS (tail)->cdr)
+    result = Fcons (XCONS (XCONS (tail)->car)->car, result);
 
-  return Qnil;
+  return result;
 }
 
-DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize,
-       1, 1, 0, "If ON is non-nil, report X errors as soon as the erring request is made.\n\
+DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
+   "If ON is non-nil, report X errors as soon as the erring request is made.\n\
 If ON is nil, allow buffering of requests.\n\
 Turning on synchronization prohibits the Xlib routines from buffering\n\
 requests and seriously degrades performance, but makes debugging much\n\
-easier.")
-  (on)
-    Lisp_Object on;
+easier.\n\
+The optional second argument DISPLAY specifies which display to act on.\n\
+DISPLAY should be either a frame or a display name (a string).\n\
+If DISPLAY is omitted or nil, that stands for the selected frame's display.")
+  (on, display)
+    Lisp_Object display, on;
 {
-  check_x ();
+  struct x_display_info *dpyinfo = check_x_display_info (display);
 
-  XSynchronize (x_current_display, !EQ (on, Qnil));
+  XSynchronize (dpyinfo->display, !EQ (on, Qnil));
 
   return Qnil;
 }
 
-/* Wait for responses to all X commands issued so far for FRAME.  */
+/* Wait for responses to all X commands issued so far for frame F.  */
 
 void
-x_sync (frame)
-     Lisp_Object frame;
+x_sync (f)
+     FRAME_PTR f;
 {
   BLOCK_INPUT;
-  XSync (x_current_display, False);
+  XSync (FRAME_X_DISPLAY (f), False);
   UNBLOCK_INPUT;
 }
 \f
 syms_of_xfns ()
 {
   /* This is zero if not using X windows.  */
-  x_current_display = 0;
-
-  the_x_screen.font_list_cache = Qnil;
-  the_x_screen.name = Qnil;
-  staticpro (&the_x_screen.font_list_cache);
-  staticpro (&the_x_screen.name);
+  x_in_use = 0;
 
   /* The section below is built by the lisp expression at the top of the file,
      just above where these variables are declared.  */
@@ -4348,6 +4758,8 @@ syms_of_xfns ()
   staticpro (&Quser_position);
   Quser_size = intern ("user-size");
   staticpro (&Quser_size);
+  Qdisplay = intern ("display");
+  staticpro (&Qdisplay);
   /* This is the end of symbol initialization.  */
 
   Fput (Qundefined_color, Qerror_conditions,
@@ -4357,9 +4769,9 @@ syms_of_xfns ()
 
   init_x_parm_symbols ();
 
-  DEFVAR_INT ("mouse-buffer-offset", &mouse_buffer_offset,
-    "The buffer offset of the character under the pointer.");
-  mouse_buffer_offset = 0;
+  DEFVAR_LISP ("x-bitmap-file-path", &Vx_bitmap_file_path,
+    "List of directories to search for bitmap files for X.");
+  Vx_bitmap_file_path = Fcons (build_string (PATH_BITMAPS), Qnil);
 
   DEFVAR_LISP ("x-pointer-shape", &Vx_pointer_shape,
     "The shape of the pointer when over text.\n\
@@ -4403,10 +4815,6 @@ or when you set the mouse color.");
               "A string indicating the foreground color of the cursor box.");
   Vx_cursor_fore_pixel = Qnil;
 
-  DEFVAR_LISP ("mouse-grabbed", &Vmouse_depressed,
-              "Non-nil if a mouse button is currently depressed.");
-  Vmouse_depressed = Qnil;
-
   DEFVAR_LISP ("x-no-window-manager", &Vx_no_window_manager,
               "Non-nil if no X window manager is in use.");
 
@@ -4454,7 +4862,8 @@ or when you set the mouse color.");
   defsubr (&Sx_horizontal_line);
 #endif
   defsubr (&Sx_open_connection);
-  defsubr (&Sx_close_current_connection);
+  defsubr (&Sx_close_connection);
+  defsubr (&Sx_display_list);
   defsubr (&Sx_synchronize);
 }