+
+Visual *
+find_similar_visual(Screen *screen, Visual *old_visual)
+{
+ Display *dpy = DisplayOfScreen (screen);
+ XVisualInfo vi_in, *vi_out;
+ Visual *result = 0;
+ int out_count;
+
+ vi_in.screen = screen_number (screen);
+ vi_in.class = visual_class (screen, old_visual);
+ vi_in.depth = visual_depth (screen, old_visual);
+
+ /* Look for a visual of the same class and depth.
+ */
+ vi_out = XGetVisualInfo (dpy, (VisualScreenMask | VisualClassMask |
+ VisualDepthMask),
+ &vi_in, &out_count);
+ if (vi_out && out_count > 0)
+ result = vi_out[0].visual;
+ if (vi_out) XFree (vi_out);
+ vi_out = 0;
+
+ /* Failing that, look for a visual of the same class.
+ */
+ if (!result)
+ {
+ vi_out = XGetVisualInfo (dpy, (VisualScreenMask | VisualClassMask),
+ &vi_in, &out_count);
+ if (vi_out && out_count > 0)
+ result = vi_out[0].visual;
+ if (vi_out) XFree (vi_out);
+ vi_out = 0;
+ }
+
+ /* Failing that, return the default visual. */
+ if (!result)
+ result = DefaultVisualOfScreen (screen);
+
+ return result;
+}
+
+
+int
+get_bits_per_pixel(Display *dpy, int depth)
+{
+ unsigned i = 0;
+ int count, result;
+ XPixmapFormatValues *formats = XListPixmapFormats(dpy, &count);
+
+ /* XCreateImage calls _XGetBitsPerPixel to figure this out, but that function
+ is private to Xlib.
+
+ For some reason, _XGetBitsPerPixel tries a hard-coded list of depths if
+ it doesn't find a matching pixmap format, but I (Dave Odell) couldn't
+ find any justification for this in the X11 spec. And the XFree86 CVS
+ repository doesn't quite go back far enough to shed any light on what
+ the deal is with that.
+ http://cvsweb.xfree86.org/cvsweb/xc/lib/X11/ImUtil.c
+
+ The hard-coded list apparently was added between X11R5 and X11R6.
+ See <ftp://ftp.x.org/pub/>.
+ */
+
+ if (!formats) return 0;
+
+ for (;;)
+ {
+ if (i == (unsigned)count)
+ {
+ result = 0;
+ break;
+ }
+
+ if (formats[i].depth == depth)
+ {
+ result = formats[i].bits_per_pixel;
+ break;
+ }
+
+ ++i;
+ }
+
+ XFree (formats);
+ return result;
+}