/*
** xipimg.c for  in 
** 
** Made by 
** Login   <vianney@epita.fr>
** 
** Started on  Wed Sep  1 08:27:06 1999 
** Last update Thu Oct 28 20:24:05 1999 
*/
#ifdef NOTDEF
#define HAVE_XPM
#define XPM_INCLUDE "../libXpm/include/xpm.h"
#endif

#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#include "Xmg.h"
#include "XmgFancy.h"
#include "XmgDict.h"
#include "xipimg.h"
#ifdef HAVE_XPM
# include XPM_INCLUDE
#endif

/* generic callback for img support in fancy widget.
   Currently, it manages X bitmaps and possibly X pixmaps if you uncomment
   things... you might find useful to use Xpm.
   Here is the algorithm used for image loading:
   First, it tries to find a pixmap which match the name in cache 
   possibly forcing depth (see XmgPixmapDictForceGet(3)). If not found,
   it loads a filename in using X or Xpm functions. If a specific depth
   is required it goes back to the first phase. 
   Note: XmgFancy widget also support XImages excepted for some features
   (e.g background pixmap) */
VOID_FUNC			XipFancyImg(w,closure,cbs)
Widget				w;
VOID_PTR			closure;
XmgFancyImgCallbackStruct	*cbs;
{
  t_hash_elt			*he;
  t_status			status;
  Pixmap			pixmap;
  int				retries;

  retries = 0;
retry:
  if (retries > 1)
    goto bad;
  if ((status = XmgPixmapDictForceGet(XtDisplay(w),
				      cbs->src,
				      cbs->depth,
				      &pixmap)) == 0)
    {
      cbs->type = FancyImgTypePixmap;
      cbs->ptr = (VOID_PTR)pixmap;
      return ;
    }
  else
    {
      Pixmap			pixmap;
      unsigned int		width;
      unsigned int		height;
      int			x;
      int			y;
      int			depth;

      if (strstr(cbs->src,"xbm"))
	{
	  if (XReadBitmapFile(XtDisplay(w),
			      DefaultRootWindow(XtDisplay(w)),
			      cbs->src,
			      &width,
			      &height,
			      &pixmap,
			      &x,
			      &y) != BitmapSuccess)
	    {
	      XmgWarning("XipFancyImg: bad xbm %s",cbs->src);
	      goto bad;
	    }
	  depth = 1;
	}
      else
	{
#ifdef HAVE_XPM
	  if (strstr(cbs->src,"xpm"))
	    {
	      XpmAttributes	xa;
              Pixmap		pixmask;    
	      
	      xa.valuemask = XpmReturnPixels;
	      pixmask = XtUnspecifiedPixmap;
	      if (XpmReadFileToPixmap(XtDisplay(w),
				      DefaultRootWindow(XtDisplay(w)),
				      cbs->src,
				      &pixmap,
				      &pixmask,
				      &xa) != 0)
		{
		  XmgWarning("XipFancyImg: bad xpm %s",cbs->src);
		  goto bad;
		}
	      depth = DefaultDepth(XtDisplay(w),
				   DefaultScreen(XtDisplay(w)));
	    }
	  else
#endif
	    {
	      XmgWarning("XipFancyImg: unrecognized %s",cbs->src);
	      goto bad;
	    }
	}
      if ((status = XmgPixmapDictAdd(cbs->src,
				     depth,
				     pixmap)) != 0)
	{
	  XmgWarning("XipFancyImg: %s",err_msg(status));
	  goto bad;
	}
      if (cbs->depth != AnyDepth)
	{
	  retries++;
	  goto retry;
	}
      cbs->depth = depth;
      cbs->type = FancyImgTypePixmap;
      cbs->ptr = (VOID_PTR)pixmap;
      return ;
    }
bad:
  cbs->type = FancyImgTypeAny;
  return ;
}
