#import "Background.h"
#import <dpsclient/wraps.h>
#import <appkit/Application.h>
#import <objc/hashtable.h>
#import <appkit/defaults.h>
#import "PSsplat.h"
#import <appkit/OpenPanel.h>
#import <appkit/nextstd.h>

#define PSsplat( r, p)	_PSsplat( (r)->origin.x, (r)->origin.y, \
		(r)->size.width, (r)->size.height, (p)->x, (p)->y)

@implementation Background

- free
{
  if( imageName)	NXZoneFree( [self zone], imageName);
  if( image)		[image free];
  return [super free];
}
- setImageNamed:(const char *)aName
{
  if( imageName && aName && !strcmp( aName, imageName))	return nil;
  if( imageName)	NXZoneFree( [self zone], imageName);
  if( image)		[image free];
  imageName=NXCopyStringBufferFromZone( aName, [self zone]);
  image=[[NXImage allocFromZone:[self zone]] initFromFile:imageName];
  return self;
}
- drawSelf:(NXRect *)r :(int)count
{
  PSsetgray( NX_DKGRAY);
  NXRectFill( &bounds);
  if( image)
    {
      int i;
      NXSize s;
      NXSize screenSize;
      NXPoint p={ 0, 0};
      NXRect r={ p};
      [NXApp getScreenSize:&screenSize];
      [image getSize:&s];
      r.size=s;
      [image composite:NX_COPY toPoint:&p];
      for( i=s.width; i<screenSize.width; i+=s.width)
        {
	  p.x=i;
	  PSsplat( &r, &p);
	}
      p.x=0;
      r.size.width=screenSize.width;
      for( i=s.height; i<screenSize.height; i+=s.height)
        {
	  p.y=i;
	  PSsplat( &r, &p);
	}
    }
  return self;
}
- open:sender
{
  OpenPanel *op=[OpenPanel new];
  char *types[]={ "tiff", "eps", NULL};
  char *directory, *filename;
  if( !imageName)
    {
      directory=getenv( "HOME");
      if( !directory)	directory="/";
      filename="";
    }
  else if( filename=rindex( imageName, '/'))
    *filename++=0, directory=imageName;
  else
    {
      filename=imageName;
      directory=getenv( "HOME");
      if( !directory)	directory="/";
    }
  [op allowMultipleFiles:NO];
  if( [op runModalForDirectory:directory file:filename types:types])
    {
      [[self setImageNamed:[op filename]] display];
      NXWriteDefault( "Background", "Image", [op filename]);
    }
  return self;
}

@end
