/*	Copyright  (c)	Günter Woigk 2013 - 2015
					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.
*/


#include "MicrocodeInspector.h"
#include "unix/FD.h"
#include "util.h"
#include "Cpu.h"
#include <QColor>
#include <QHBoxLayout>
#include <QSettings>


#define key_microcodeview_size		"microcodeview_size"
#define key_microcodeview_position	"microcodeview_position"


/*	colors used for highlighting executed microcode addresses:
 */
static int32 highlight_colors[trace_len] =
{
#define RGB(R,G,B)	(int32)(0xff000000 + (((R)&255)<<16) + (((G)&255)<<8) + (B&255))
#define R 0
#define G 125
#define B 235
#define COLOR(I)	RGB((R*(N-I)+255*I)/N, (G*(N-I)+255*I)/N, (B*(N-I)+255*I)/N)
#define N			(trace_len-1)

	RGB(255,127,127),	// MCA2: rot
	COLOR(0),			// shades of blue
	COLOR(1),
	COLOR(2),
	COLOR(3),
	COLOR(4),
	COLOR(5),
	COLOR(6),
	COLOR(7),
	COLOR(8)
};



MicrocodeInspector::MicrocodeInspector(QWidget* parent, Cpu* cpu, cstr sourcefile)
:	Inspector(parent,"rom"),
	cpu(cpu)
{
	assert(NELEM(highlighted_mcas)==NELEM(highlight_colors));
	for(uint i=0;i<NELEM(highlighted_mcas);i++) highlighted_mcas[i]=0;

// read combined.log -> disass[]:

	logline("reading source file");

	FD fd(sourcefile,'r');
	uint32 filesize = fd.file_size();
	str s = spacestr(filesize,'\n');
	fd.read_bytes(s,filesize);
	fd.close_file(0);
	s = fromutf8str(s);
	source = split(s);

// crop trailing spaces
// and replace tabs:
	for(uint i=0;i<source.count();i++)
	{
		ptr&s = source[i];
		ptr e = strchr(s,0);
		while(e>s && (uchar)*(e-1)<=' ') e--;
		*e=0;

		ptr p;
		for(p=s;(uchar)*p>=' ';p++){}		// search for control code
		if(*p)								// any found?
		{
			ptr temp = new char[(e-s)*4+1];	// max size if all are tabs
			ptr z=temp;
			for(p=s;*p;p++)
			{
				char c = *p;
				if((uchar)c>=' ') *z++ = c;
				else if(c=='\t') do { *z++=' '; } while((z-temp)%4);
			}
			*z=0;
			delete[] s;
			s = newcopy(temp);
		}
	}

// limit consecutive empty lines to 3:
	for(uint i=3;i<source.count();i++)
	{
		if(*source[i] || *source[i-1] || *source[i-2] || *source[i-3]) continue;
		source.remove(i--);
	}

// find all source lines for microcode addresses:
	memset(source_ptr,0,sizeof(source_ptr));
	uint32 lastline=0;
	for(uint line=0;line<source.count();line++)
	{
		s = source[line];
		if((uint8)s[0]<=' ') continue;		// kein Code

		// Beispiel:
		// "0:$3C83 d15:______:A_=A_:D0=D0           ld  cmd,ival    :bit15"

		cptr z = s+33; while(z[2]==' ') z++;
		uint addr = evalhex(substr(s+3,s+7));
		assert(addr<0x8000);

		if(s[0]=='0') source_ptr[0x0000 + addr] = lastline = line;
		if(s[0]=='1') source_ptr[0x4000 + addr] = lastline = line;
	}


// init source position:
	mca2 = 0;
	row0 = source_ptr[mca2];

// init widgets:
	setWindowTitle("Microcode");

	QWidget* w = new QWidget(this);
	setCentralWidget(w);
	textview  = new SimpleTerminal(w);
	connect(textview,SIGNAL(resized()),this,SLOT(update_all()));
	scrollbar = new MyScrollBar(Qt::Vertical,w);
	scrollbar_width	 = scrollbar->sizeHint().width();
	connect(scrollbar,SIGNAL(valueChanged(int)),this,SLOT(scroll_to(int)));

//update_all();
	QSize sz(textview->char_width*80+scrollbar_width,textview->line_height*25);
	move(settings.value(key_microcodeview_position,pos()).toPoint());
	resize(settings.value(key_microcodeview_size,sz).toSize());
}


MicrocodeInspector::~MicrocodeInspector()
{
	settings.setValue(key_microcodeview_size, size());
	settings.setValue(key_microcodeview_position, pos());
}



// ========================================================================

void MicrocodeInspector::print_line(uint row)
{
	if(row>=row0 && row-row0<(uint)textview->rows)
	{
		textview->printAt(row-row0,0,leftstr(source[row],textview->cols));
	}
}

void MicrocodeInspector::print_line(uint row, int color)
{
	if(row>=row0 && row-row0<(uint)textview->rows)
	{
		textview->setPaperColor(color);
		textview->printAt(row-row0,0,leftstr(source[row],textview->cols));
	}
}


// alle zeilen in der highlight-historie highlighten
//
void MicrocodeInspector::print_highlight_mcas()
{
	const uint n = NELEM(highlighted_mcas);
	for(uint i=n;i--;)
	{
		uint mca = highlighted_mcas[i];
		uint row = source_ptr[mca];
		print_line(row,highlight_colors[i]);
	}
}


void MicrocodeInspector::update_scrollbar()
{
	uint rows = textview->rows;

	scrollbar->blockSignals(true);
		scrollbar->setMinimum(0);
		scrollbar->setMaximum(source.count() - rows);
		scrollbar->setPageStep(rows);
		scrollbar->setSingleStep(max(1u,rows/30));
		scrollbar->setValue(row0);
	scrollbar->blockSignals(false);
}


void MicrocodeInspector::scroll_to(int _row)
{
//	logline("MicrocodeInspector::scroll_to %i",_row);

	uint rows = textview->rows;
	uint cols = textview->cols;
	uint row  = _row;


	row = min(row, source.count()-rows);
	if(row==row0) return;

	textview->setPaperColor(Qt::white);		// white

	if(row<row0 && row0-row<rows)			// neue pos < alte pos && scroll down bringt noch was
	{
		uint d = row0 - row;				// scroll distance
		textview->scrollScreen(-d);			// down
		for(uint r=0;r<d;r++) textview->printAt(r,0,leftstr(source[row+r],cols));
		row0 = row;
	}
	else if(row>=row0 && row<row0+rows)		// neue pos > alte pos && scroll up bringt noch was
	{
		uint d = row - row0;				// scroll distance
		textview->scrollScreen(d);			// up
		row0 += d;
		for(uint r=rows-d;r<rows;r++) textview->printAt(r,0,leftstr(source[row0+r],cols));
	}
	else	// komplett neu zeichnen
	{
		textview->clearScreen();
		for(uint r=0;r<rows;r++) textview->printAt(r,0,leftstr(source[row+r],cols));
		row0 = row;
	}

	print_highlight_mcas();
	update_scrollbar();
}


void MicrocodeInspector::update()
{
	if(cpu->mca2==mca2) return;		// keine Ä. => raus, auch händisches Scrollen nicht rückgängig machen!
	mca2 = cpu->mca2;
	assert(mca2<0x8000);

	//logline("MicrocodeInspector::update");

	uint mca2_row = source_ptr[mca2];
	assert(mca2_row<source.count());

	// prüfe, ob microcode addresse mca2 noch innerhalb des screens liegt:
	// wenn nicht, screen so scrollen o. neu anzeigen, dass sie wieder drin liegt:

	if(mca2_row<row0 || mca2_row>=row0+textview->rows)	// mca2 out of screen -> force inside
	{
		uint row = mca2_row - min(mca2_row,(uint)textview->rows/5);
		scroll_to(row);
	}

	// alle zeilen in der highlight-historie abdimmen
	// zeile mit mca2 rot highlighten

	const uint n = NELEM(highlighted_mcas);

	uint mca = highlighted_mcas[n-1];
	uint row = source_ptr[mca];
	print_line(row,0xffffffff);		// white

	for(uint i=n-1;i>0;i--) highlighted_mcas[i] = highlighted_mcas[i-1];
	highlighted_mcas[0] = mca2;

	print_highlight_mcas();
}


void MicrocodeInspector::update_all()
{
	uint rows = textview->rows;
	uint cols = textview->cols;

	logline("MicrocodeInspector::update_all %i x %i", rows,cols);

	row0 = min(row0, source.count()-rows);		// force legal

	// screen neu zeichnen:
	textview->setPaperColor(Qt::white);			// white
	textview->clearScreen();
	for(uint r=0;r<rows;r++) textview->printAt(r,0,row0+r<source.count() ? leftstr(source[row0+r],cols) : "");

	print_highlight_mcas();
	update_scrollbar();
}


// virtual protected
void MicrocodeInspector::resizeEvent(QResizeEvent*e)
{
	logline("MicrocodeInspector::resizeEvent %i x %i", width(),height());
	Inspector::resizeEvent(e);
	scrollbar->setGeometry(width()-scrollbar_width,0,scrollbar_width,height());
	textview->resize(width()-scrollbar_width,height());
}

//virtual
void MicrocodeInspector::wheelEvent(QWheelEvent* e)
{
	scrollbar->wheelEvent(e);
}


























