//
// part of X11 interface common to Xview & Xt based ones
//

#include "X11Screen.h"
#include <X11/xpm.h>

X11Screen::X11Screen(int argc, char **argv)
{;}

X11Screen::~X11Screen()
{
  // delete [] readHandlers;
}

int X11Screen::AllocColor(char *name)
{
  XColor rgbColor, realColor;
  XLookupColor(dpy, colormap, name, &rgbColor, &realColor);
  XAllocColor(dpy, colormap, &realColor);
  return realColor.pixel;
}

char **BigPixmap(char **pic) {
  int xsize, ysize, col, depth;
  int i;

  char **dest;
  sscanf(pic[0], "%d %d %d %d", &xsize, &ysize, &col, &depth);
  dest = new charp[2*ysize+col+2];

  dest[0] = new char[15];
  sprintf(dest[0],"%d %d %d %d", 2*xsize, 2*ysize, col, depth);
  for (i = 1; i < col+1; i++)
    dest[i] = pic[i];
  for (i=0; i < ysize; i++)
    {
      dest[col+1+2*i] = dest[col+2+2*i] = new char[2*xsize+1];
      for (int j = 0; j < xsize; j++)
	{
	  dest[col+1+2*i][2*j] = dest[col+1+2*i][2*j+1] = pic[col+1+i][j]; 
	}
      dest[col+1+2*i][2*xsize] = 0;
    }
  dest[2*ysize+col+1] = NULL;

  return dest;
}

PixmapInfo *X11Screen::CompilePixmap(char **data)
{
  Pixmap shape, image;
  XpmAttributes xpmatts;
  xpmatts.valuemask = 0;
  // FIXME: DefaultRootWindow is an approximation !
#ifdef BIGPIXMAPS
  XpmCreatePixmapFromData(dpy, DefaultRootWindow(dpy) , BigPixmap(data), &image, &shape, &xpmatts);
#else
  XpmCreatePixmapFromData(dpy, DefaultRootWindow(dpy) , data, &image, &shape, &xpmatts);
#endif
  if (!image) return NULL;
  PixmapInfo *info = new PixmapInfo;
  if (info) {
    info->pixmap = image;
    info->mask = shape;
    info->w = xpmatts.width;
    info->h = xpmatts.height;
  }
  return info;
}

void X11Screen::FreePixmap(PixmapInfo *info)
{
  XFreePixmap(dpy, info->pixmap);
  XFreePixmap(dpy, info->mask);
  delete info;
}

// get pixmap size
void X11Screen::GetPixmapInfo(PixmapInfo *handle, int &w, int &h)
{
  w = handle->w;
  h = handle->h;
}
