#include "pipixmapmac.h"

PIPixmapMac::PIPixmapMac(PIContainerGen *par, char *nom,
                         int sx, int sy, int px, int py)
: PIPixmapGen(par,nom,sx,sy,px,py), mGWorld(NULL)
{}


PIPixmapMac::~PIPixmapMac()
{}


/* --Methode-- */
void PIPixmapMac::SetPixmap(unsigned char *pix, int sx, int sy, bool refr)
{
  if (nx != sx || ny != sy)
    if (mGWorld) {
      DisposeGWorld(mGWorld);
      mGWorld = NULL;
    }
  PIPixmapGen::SetPixmap(pix, sx, sy, refr);
}

void
PIPixmapMac::Resize()
{
  Refresh();
}

void
PIPixmapMac::Refresh()
{
	PIPixmapGen::Refresh();
}

void
PIPixmapMac::DrawOff()
{
  if (mGWorld) {
    DisposeGWorld(mGWorld);
    mGWorld = NULL;
  }
  
  if (!cmap) return;
  if (!pixmap) return;
  if (nx == 0 || ny == 0) return;
  
  Rect	frame;
  SetRect(&frame, 0, 0, XSize(), YSize());

  
  ThrowIfOSErr_(NewGWorld(&mGWorld, 8, &frame, cmap->mCTab, nil, 0));

    // Lock down Pixels that we are drawing to so that memory will not
	// move
	::LockPixels (mGWorld->portPixMap);

 	// Draw
	PixMapHandle	pMap;
	unsigned char	*pixP;
	
	pMap = GetGWorldPixMap(mGWorld);
	for (int y=frame.top; y<frame.bottom; y++) {
		pixP = (unsigned char *) GetPixBaseAddr(pMap) + y * ((**pMap).rowBytes & 0x7FFF);
		for(int x = frame.left ; x < frame.right ; x++)
			pixP[x] = (x<nx && y<ny) ? pixmap[x + y*nx]+2 : 0;
	}
			
	// Now unlock Pixels.
	::UnlockPixels (mGWorld->portPixMap);
	
	mPane->FocusDraw();
//	SetPalette(mPane->GetMacPort(),cmap->mPalette, true);
//	PIPixmapGen::Refresh();
}

void
PIPixmapMac::Draw(PIGraphic* g,int,int,int,int)
{
  Draw(g);
}

void
PIPixmapMac::Draw(PIGraphic* g)
{
  DrawOff();
  if (!mGWorld) return;
  mPane->FocusDraw();
  Rect	paneFrame;
  mPane-> CalcLocalFrameRect(paneFrame);
  Rect	offsFrame;
  SetRect(&offsFrame, 0, 0, paneFrame.right-paneFrame.left, paneFrame.bottom-paneFrame.top);
  ::LockPixels (mGWorld->portPixMap);
  ::ForeColor (blackColor);
  ::BackColor (whiteColor);
  ::CopyBits((BitMap *) (*(GetGWorldPixMap(mGWorld))),
				&mPane->GetMacPort()->portBits,
				&offsFrame, &paneFrame, srcCopy, nil);
  ::UnlockPixels (mGWorld->portPixMap);
  DisposeGWorld(mGWorld);
  mGWorld = 0;
}