/*	Copyright  (c)	Günter Woigk 2012 - 2012
					mailto:kio@little-bat.de

	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.

	Permission to use, copy, modify, distribute, and sell this software and
	its documentation for any purpose is hereby granted without fee, provided
	that the above copyright notice appear in all copies and that both that
	copyright notice and this permission notice appear in supporting
	documentation, and that the name of the copyright holder not be used
	in advertising or publicity pertaining to distribution of the software
	without specific, written prior permission.  The copyright holder makes no
	representations about the suitability of this software for any purpose.
	It is provided "as is" without express or implied warranty.

	THE COPYRIGHT HOLDER DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
	INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
	EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY SPECIAL, INDIRECT OR
	CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
	DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
	TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
	PERFORMANCE OF THIS SOFTWARE.
*/

#define SAFE 3
#define LOG 1
#include "MemoryGraphInspector.h"
#include <QPushButton>
#include <QBoxLayout>
#include <QWidget>
#include <QComboBox>
#include "MyLineEdit.h"
#include <QTimer>
#include "Machine.h"
#include <QImage>
#include <QToolTip>
#include "Application.h"


// offset mouse pointer hotspot -> 'feeled' hotspot
#define mouse_x_offset	-1
#define mouse_y_offset	-3


// ==================================================================================
// =========================   B&W Graphics Widget =================================
// ==================================================================================


class GWidget : public QWidget
{
public:
	QImage*			canvas;
	int				x,y;		// highlight position

protected:
	virtual void	resizeEvent(QResizeEvent*);
    virtual void	paintEvent(QPaintEvent*);

public:
	GWidget(QWidget*parent)		:QWidget(parent),canvas(NULL){}
	~GWidget()					{ delete canvas; }
};

void GWidget::resizeEvent(QResizeEvent*)
{
	delete canvas;
	canvas = new QImage(size(),QImage::Format_Mono);
	update();
}

void GWidget::paintEvent(QPaintEvent*)
{
	QPainter p(this);
	p.drawImage(0,0,*canvas);

	if(x>=0&&y>=0&&x<width()&&y<height())
	{
		uint8 byte = canvas->scanLine(y)[x>>3];
		int x0 = x&~7;

		p.setPen(QColor(180,0,0));	//red
		p.drawLine(x0,y,x0+7,y);

		p.setPen(QColor(0,240,240));	// cyan
		for(int i=0;i<8;i++)
			if((byte<<i)&0x80)
				p.drawPoint(x0+i,y);
	}
}



// ==================================================================================
// ========================   MemoryGraph Inspector   ===============================
// ==================================================================================



MemoryGraphInspector::MemoryGraphInspector( QWidget* parent, IsaObject* item )
:	MemoryInspector(parent,item,MemGraph)
{
	LogIn("new MemoryGraphInspector");

// create & add Widgets:
// note: sie erscheinen in der Kopfzeile in der Reihenfolge, in der sie zum head_widget hinzugefügt werden.

	combobox_register->setParent(head_widget);

	button_set32	= new QPushButton(head_widget);
	button_set32->setFixedSize(50,BUTTON_HEIGHT);
	button_set32->setText("32");
	connect(button_set32,SIGNAL(clicked()),this,SLOT(set32BytesPerRow()));

	address_view	= new SimpleTerminal(data_widget);
	address_view->line_height = rh = 16;
	cw = address_view->char_width;


	graphics_view	= new GWidget(data_widget);

	int min_w = L_MARGIN+R_MARGIN+5*address_view->char_width + 4*8 + H_SPACE + scrollbar_width;	// note: das sind 60 und das wird von OSX oder Qt auf 64 hochgesetzt
	int max_w = L_MARGIN+R_MARGIN+5*address_view->char_width + 128*8 + H_SPACE + scrollbar_width;
	int min_h = 16+head_widget->height();
	int max_h = 2000+head_widget->height();

	setMinimumSize(min_w,min_h);
	setMaximumSize(max_w,max_h);
	setBaseSize(min_w,min_h);
	setSizeIncrement(8,1);
}


void MemoryGraphInspector::resizeEvent(QResizeEvent* e)
{
	MemoryInspector::resizeEvent(e);

	int d  = data_widget->width() - 5*cw - H_SPACE;	// verteilbarer X-Raum
		d  = max(d/8,1);				// Bytes pro Zeile [Bytes]
	int w1 = 5*cw;						// Width of address field --> "$1234"
	int w2 = d * 8;						// Width of Graphics field

	if(bytes_per_row!=d) updateAll();
	bytes_per_row = d;

	rows  = data_widget->height();		// number of pixel rows

//	while(display_base_address <= -bytes_per_row) display_base_address += bytes_per_row;
//	XXXASSERT(display_base_address > -bytes_per_row);

	// set widget sizes:
	address_view->setGeometry(0,0,w1,(rows+rh-1)/rh*rh);
	graphics_view->setGeometry(w1+H_SPACE,0,w2,rows);

	updateScrollbar();

	updateDisplayedData();
}


//helper:
void MemoryGraphInspector::updateScrollbar()
{
	int current_base_row   = (display_base_address+bytes_per_row-1) / bytes_per_row;
	int total_base_address = display_base_address - current_base_row * bytes_per_row;
	int total_rows		   = (data_size-total_base_address+bytes_per_row-1) / bytes_per_row;

	scrollbar->blockSignals(true);
		scrollbar->setMinimum(0);
		scrollbar->setMaximum(total_rows - rows);		//LogLine("Scrollbar: total rows  = %i",total_rows - rows);
		scrollbar->setPageStep(rows/rh*rh);				//LogLine("Scrollbar: page step   = %i",rows/rh*rh);
		scrollbar->setSingleStep(max(1,rows/rh/16)*rh);	//LogLine("Scrollbar: single step = %i",rows/rh/16*rh);
		scrollbar->setValue(current_base_row);			//LogLine("Scrollbar: curr. value = %i",current_base_row);
	scrollbar->blockSignals(false);
}


void MemoryGraphInspector::set32BytesPerRow()
{
	QRect r = window()->geometry();
	r.setWidth( r.width() -width() +L_MARGIN +address_view->width() +H_SPACE +32*8 +scrollbar_width );
	window()->setGeometry(r);	// -> we'll get a resizeEvent()
	setBaseAddress(display_base_address/32*32);
}


void MemoryGraphInspector::updateDisplayedData()
{
// Feststellen, ob das Toolwindow sichtbar ist:
// das ist gar nicht so einfach...
	if(!appl->isActiveApplication()) return;				 // sonst raus
	if(machine->controller!=front_machine_controller)return; // sonst raus

	MemoryInspector::updateDisplayedData();

	QImage* bmp = graphics_view->canvas;
	if(!bmp) return;
	bmp->fill(Qt::white);

	int address = display_base_address;

	for(int row=0;row<(rows+rh-1)/rh;row++)
	{
		char ad[] = "$0000";
		ad[1] = hexchar(address>>12);
		ad[2] = hexchar(address>>8);
		ad[3] = hexchar(address>>4);
		ad[4] = hexchar(address);
		address_view->printAt(row,0,ad);
		address += bytes_per_row * address_view->line_height;
	}

	Z80* cpu = machine->cpu;
	CoreByte* q = data_source==AllRom || data_source==RomPages ? machine->rom.Data()+data_start : machine->ram.Data()+data_start;

	int a = display_base_address;	XXXASSERT(a > -bytes_per_row);
	int y = 0;
	int x = 0;
	int n = bytes_per_row;
	if(a<0) { x-=a; n+=a; a=0; }

	while(y<rows && a<data_size)
	{
		if(a+n>data_size) n = data_size-a;

		XXXASSERT(n>=0);
		XXXASSERT(x>=0);
		XXXASSERT(x+n<=bytes_per_row);

		if(data_source==AsSeenByCpu) cpu->copyRamToBuffer(a,bmp->scanLine(y)+x,n);
		else Z80::c2b(q+a,bmp->scanLine(y)+x,n);
		a += n;
		x = 0;
		y += 1;
		n = bytes_per_row;
	}

	graphics_view->update();
	update_tooltip();
}


/*	Tooltip aktualisieren:
	aber nur, wenn die Maus über dem MemoryView hovert
	da QToolTip::showText(…) die App zwangsweise in den Vordergrund (zurück-) bringt.
*/
void MemoryGraphInspector::update_tooltip()
{
	XXLogIn("MemoryGraphInspector::updateTooltip");

	QPoint gpos = QCursor::pos();
	if(QApplication::topLevelAt(gpos)!=window()) { graphics_view->x=-99; return; }
	QPoint pos  = graphics_view->mapFromGlobal(gpos);

	uint x = graphics_view->x = pos.x()+mouse_x_offset;	if( x >= (uint)graphics_view->width() ) return;
	uint y = graphics_view->y = pos.y()+mouse_y_offset;	if( y >= (uint)graphics_view->height() ) return;

	uint32 addr = display_base_address + x/8 + y*bytes_per_row;
	if(addr>=(uint32)data_size) { QToolTip::showText(gpos, NULL, graphics_view, QRect()); graphics_view->x=-99; return; }

	uint byte = data_source==AsSeenByCpu ? machine->cpu->peek(addr) :
				data_source==RomPages || data_source==AllRom ? (uint8)machine->rom[data_start+addr] :
				(uint8)machine->ram[data_start+addr];

	QToolTip::showText(gpos, usingstr("$%04X: $%02X",(uint)addr,byte), graphics_view, QRect());
}















