//  Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
//
//  This file is part of the VNC system.
//
//  The VNC system is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation; either version 2 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
//  USA.
//
// If the source code for the VNC system is not available from the place 
// whence you received this file, check http://www.uk.research.att.com/vnc or contact
// the authors on vnc@uk.research.att.com for information on obtaining it.


// CoRRE (Compact Rising Rectangle Encoding)
//
// The bits of the ClientConnection object to do with CoRRE.

#include <pspkernel.h>
#include <string.h>
#include "libnet/pspnet.h"
#include "vnc.h"

extern int rfbsock;

extern CARD8 *m_netbuf;
extern CARD16 *m_zlibbuf;

#define GET_PIXEL16(pix,ptr) ((pix)=*(ptr)++)
#define CheckBufferSize(x) if(x>sizeof(m_netbuf)) return false;

int ReadCoRRERect(rfbFramebufferUpdateRectHeader *pfburh)
{
  // An RRE rect is always followed by a background color
  // For speed's sake we read them together into a buffer.
  CARD32 i;
  CARD8 tmpbuf[sz_rfbRREHeader+2];			// biggest pixel is 2 bytes long
  rfbRREHeader *prreh = (rfbRREHeader *) tmpbuf;
  CARD16 *pcolor = (CARD16 *) tmpbuf + sz_rfbRREHeader;
  ReadExact(rfbsock, tmpbuf, sz_rfbRREHeader + 2);

  prreh->nSubrects = Swap32IfLE(prreh->nSubrects);

  CARD16 color;
  GET_PIXEL16(color,pcolor);

  // Draw the background of the rectangle
  DrawVirtualFilledRectangle(color, pfburh->r.x, pfburh->r.y, pfburh->r.w, pfburh->r.h, true);

  if (prreh->nSubrects == 0) return true;

  // Draw the sub-rectangles
  rfbCoRRERectangle *pRect;
  rfbRectangle rect;

  // The size of an CoRRE subrect including color info
  int subRectSize = 2 + sz_rfbCoRRERectangle;

  // Read subrects into the buffer 
  CheckBufferSize(subRectSize * prreh->nSubrects);
  ReadExact(rfbsock, m_netbuf, subRectSize * prreh->nSubrects);
  CARD16 *p = (CARD16 *) m_netbuf;

  for (i = 0; i < prreh->nSubrects; i++) {
    pRect = (rfbCoRRERectangle *) (p + 1);
            
    GET_PIXEL16(color,p);
            
    rect.x = pRect->x + pfburh->r.x;
    rect.y = pRect->y + pfburh->r.y;
    rect.w = pRect->w;
    rect.h = pRect->h;
    DrawVirtualFilledRectangle(color, rect.x, rect.y, rect.w, rect.h, true);
    p+=subRectSize/2;
  }

  return true;
}
