/*	Copyright  (c)	Günter Woigk 2012 - 2017
					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 "MemoryInspector.h"
#include <QComboBox>
#include "MyLineEdit.h"
#include "util.h"
#include <QApplication>
#include "unix/os_utilities.h"
#include <QSettings>
#include "Cpu.h"


const uint data_size = 0x10000;

extern QSettings settings;



/*	MemoryInspector ist die Basis-Klasse für Memory Display Widgets.
	Es bereitet 2 ComboBoxen vor, die von der Subclass angezeigt werden müssen:
	- combobox_displaymode: Hier kann der Benutzer einen anderen MemoryInspector auswählen.
		Das Signal der ComboBox wird an das eigene Signal setDataSource(int) weitergeleitet,
		das das Parent Widget (class ToolWindow) empfängt um diesen MemoryInspector durch den gewünschten zu ersetzen.
	- combobox_datasource: Hier kann der Benutzer eine andere Datenquelle auswählen: Ram, Rom, AsSeenByCpu.
		Dieses Signal wird an den virtuellen Slot setDataSource(int) verbunden, den die SubClass implementieren muss.
	Es bereitet den Timer vor, der von der SubClass gestartet werden muss
*/


// highlight colors:
//
const QColor paper_color_reg(244,244,155);		//gelb
const QColor paper_color_sp(177,255,188);		//grün
const QColor paper_color_hl(177,255,255);		//cyan
const QColor paper_color_pc(255,199,199);		//rot
const QColor color_white(255,255,255);
const QColor color_black(0,0,0);
const QColor color_light_grey(Qt::lightGray);



// ==================================================================================
// ===============================   Head Widget   ==================================
// ==================================================================================


MIHeadWidget::MIHeadWidget(QWidget* parent)
:	QWidget(parent)
{}


/*	resize Head Widget:
	dabei kann sich die Höhe ändern (1-zeilig vs. 2-zeilig)
	Die enthaltenen Widgets werden neu positioniert.
	Return: Neue Höhe des Widgets.
*/
int MIHeadWidget::setWidth(int w)
{
	resize(w,heightForWidth(w));
	return updateLayout();
}


/*	Wie hoch muss das Head Widgets bei einer bestimmten Breite sein?
	Die Höhe kann zwischen 1-zeilig und 2-zeilig variieren.

	virtual: das ist zufällig auch genau das, was QWidget::heightForWidth() macht. :-)
*/
int MIHeadWidget::heightForWidth(int width) const
{
	int min_w = PADDING_L+PADDING_R;

	for(int i=0; i<children().count(); i++)
	{
		QWidget* o = (QWidget*)children().at(i);
		if(o->isWidgetType() && !o->isHidden()) min_w += o->minimumWidth();
	}

	int h = PADDING_T+PADDING_B+MemoryInspector::COMBOBOX_HEIGHT;
	(void)width; //	if(min_w>width)	h = h+h -PADDING_T -PADDING_B +SPACING_V;	// 2-zeiliges Layout			TODO
	return h;
}


/*	Positioniere im Head Widget die Child Widgets passend für width().
	Die Höhe des Head Widgets wird im Bedarfsfall resized.
	Return: Neue Höhe des Widgets.
*/
int MIHeadWidget::updateLayout()
{
	int stretch = 0;
	int stretchers = 0;
	Array<QWidget*> items;
	for(int i=0;i<children().count();i++)
	{
		QWidget* o = (QWidget*)children().at(i);
		if(o->isWidgetType() && o->isVisibleTo(this)) { items.append(o); }
	}

	int h = PADDING_T+PADDING_B+MemoryInspector::COMBOBOX_HEIGHT;
	int n = items.count();
	int max_w = PADDING_L+PADDING_R+(n-1)*SPACING_H;
	int min_w = PADDING_L+PADDING_R;

	for(int i=0;i<n;i++)
	{
		QWidget* w = items[i];
		max_w += w->maximumWidth();
		min_w += w->minimumWidth();
		if(w->minimumWidth()==0) { stretch += w->maximumWidth(); stretchers++; }
	}

//	if(min_w>width)	// 2-zeiliges Layout			TODO
//	{
//		h = h+h -PADDING_T -PADDING_B +SPACING_V;
//	}
//	else // 1-zeiliges Layout
	{
		if(height()!=h) resize(width(),h);

		// total spare room:
		int room = width()-min_w;

		// 1.: give room to spacings:
		int spacing_width = n<=1 ? 1 : min((int)SPACING_H, room / (n-1));

		// total spare room without spacings:
		room -= spacing_width*(n-1);

		// 2. give room to non-stretchers:
		float f = min(1.0f, (float)room / (max_w-min_w-stretch-(n-1)*spacing_width));

		// total spare room for stretchers:
		room -= (max_w-min_w-stretch-(n-stretchers-1)*spacing_width) * f;

		int x = PADDING_L;
		int y = PADDING_T;
		for(int i=0;i<n;i++)
		{
			QWidget* widget = items[i];
			bool isb = widget->inherits("QPushButton");
			int _y = y-isb;
			_y = min( _y, PADDING_T+PADDING_B+MemoryInspector::COMBOBOX_HEIGHT -widget->height());
			widget->move(x,_y);
			int w = widget->minimumWidth()==0
				? room/stretchers
				: widget->minimumWidth() + f*(widget->maximumWidth()-widget->minimumWidth());
			widget->resize(w,widget->height());
			x += w+spacing_width;
		}
	}

	return h;
}



// ==================================================================================
// ===========================   MemoryInspector   ==================================
// ==================================================================================



MemoryInspector::MemoryInspector(QWidget*p, Cpu *cpu, MIDisplayMode displaymode, cstr idf)
:	Inspector(p,idf),
	head_widget(new MIHeadWidget(this)),
	data_widget(new QWidget(this)),
	old_display_base_address(0),
	needs_aligned_addresses(displaymode==MemAccess),
	resized(now()),
	display_mode(displaymode),
	update_all(yes)
{
	this->cpu = cpu;

	xlogIn("new MemoryInspector");

	data_widget->move(0,head_widget->height());

	display_base_address= settings.value(prefs_id("baseaddress"),0).toInt();
	bytes_per_row		= settings.value(prefs_id("bytes_per_row"),32).toInt();	// must be validated by subclass
	rows				= settings.value(prefs_id("rows"),8).toInt();			// must be validated by subclass

// security:
	limit(1u,bytes_per_row,128u);
	limit(1u,rows,(data_size-1)/bytes_per_row);

	min_w =	64;
	min_h = 64;
	dw = 1;
	dh = 1;
	setMinimumSize(min_w,min_h);

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

	stretch1 = new QWidget(head_widget); stretch1->setMinimumSize(0,10); stretch1->setMaximumSize(100,10);

	lineedit_baseaddress = new MyLineEdit(catstr("$",hexstr(old_display_base_address,4)),head_widget);
	lineedit_baseaddress->setMinimumSize(50,TEXTEDIT_HEIGHT);
	lineedit_baseaddress->setMaximumSize(70,TEXTEDIT_HEIGHT);
	lineedit_baseaddress->setFocusPolicy(Qt::ClickFocus);
	connect(lineedit_baseaddress,SIGNAL(returnPressed()),this,SLOT(setAddressFromTextEdit()));

	stretch2 = new QWidget(head_widget); stretch2->setMinimumSize(0,10); stretch2->setMaximumSize(100,10);

	combobox_register = new QComboBox(NULL);	// must be added by subclass c'tor or delete TODO
	combobox_register->addItems(QStringList()<<"IP"<<"SP"<<"HP"<<"A0"<<"A1"<<"Atmp"<<"D2AR");
	combobox_register->setFixedSize(50,COMBOBOX_HEIGHT);
	combobox_register->setFocusPolicy(Qt::NoFocus);

	scrollbar		 = new MyScrollBar(Qt::Vertical,this);
	scrollbar_width	 = scrollbar->sizeHint().width();
	//updateScrollbar();

// init:

	connect(combobox_register,SIGNAL(activated(int)),this,SLOT(setAddressFromRegister(int)));
	connect(scrollbar,SIGNAL(valueChanged(int)),this,SLOT(setScrollPosition(int)));
	connect(this,SIGNAL(scrollPositionChanged(int)),scrollbar,SLOT(setValue(int)));

}


MemoryInspector::~MemoryInspector()
{
	xlogIn("~MemoryInspector");

	settings.setValue(prefs_id("baseaddress"), display_base_address);
	settings.setValue(prefs_id("bytes_per_row"), bytes_per_row);
	settings.setValue(prefs_id("rows"), rows);
}


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



// virtual: Qt
// resize head_widget
// reposition and resize data_widget
// data_widget contents must be updated by subclass
void MemoryInspector::resizeEvent(QResizeEvent* e)
{
	xlogIn("MemoryInspector.resizeEvent");

	Inspector::resizeEvent(e);

	int h = head_widget->height();
	int head_height = head_widget->setWidth(width());	// resize head widget
	int data_width  = width()-scrollbar_width-L_MARGIN-R_MARGIN;
	int data_height = height()-head_height-V_MARGINS;

	data_widget->setGeometry(L_MARGIN, head_height, data_width, data_height );
	scrollbar->setGeometry( width()-scrollbar_width, head_height, scrollbar_width, data_height );

	int d = head_widget->height()-h;
	if(d)
	{
		min_h += d;
		setMinimumSize(min_w,min_h);
		emit sizeConstraintsChanged();
	}

	resized = now();
	updateAll();
}



// slot: called from textedit_baseaddress
void MemoryInspector::setAddressFromTextEdit()
{
	xlogIn("MemoryInspector.setAddressFromTextEdit");

	uint16 addr = intValue(lineedit_baseaddress->text());
	if(errno==ok) setBaseAddress(addr);
	else lineedit_baseaddress->setText(lineedit_baseaddress->oldText());
}


//virtual: set display base address
void MemoryInspector::setBaseAddress(uint16 new_base_address)
{
	xlogIn("MemoryInspector.setBaseAddress");

	new_base_address = min( new_base_address, (uint16)(data_size-2*bytes_per_row) );
	if(needs_aligned_addresses) new_base_address -= new_base_address % bytes_per_row;
	display_base_address = new_base_address;
	updateScrollbar();
}


//virtual slot for scrollbar:
void MemoryInspector::setScrollPosition(int row)
{
	xlogIn("MemoryInspector.setScrollPosition");

	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;

	setBaseAddress(total_base_address + row * bytes_per_row);
}


//helper:
void MemoryInspector::updateScrollbar()
{
	xlogIn("MemoryInspector.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);
		scrollbar->setPageStep(rows);
		scrollbar->setSingleStep(max(1u,rows/16));
		scrollbar->setValue(current_base_row);
	scrollbar->blockSignals(false);
}


//slot: called from combobox_register
void MemoryInspector::setAddressFromRegister(int reg)
{
	xlogIn("MemoryInspector.setAddressFromRegister");

	uint address;
	switch(reg)
	{
	default: IERR();
	case regIP:	  address = cpu->areg_ip; break;
	case regSP:	  address = cpu->areg_sp; break;
	case regHP:	  address = cpu->areg_hp; break;
	case regA0:   address = cpu->areg_a0; break;
	case regA1:   address = cpu->areg_a1; break;
	case regATMP: address = cpu->areg_atmp; break;
	case regD2AR: address = cpu->reg_d2ar;  break;
	}

	setBaseAddress(address);
}



void MemoryInspector::update()
{
	xxlogIn("MemoryInspector.update");

	static uint old_mb=0;
	if(old_mb!=QApplication::mouseButtons())
	{
		old_mb = QApplication::mouseButtons();
		xlogline("new mouse buttons = %u",old_mb);
	}

	if(resized && now()>resized+1/*sec*/ /*&& QApplication::mouseButtons()==0*/)
	{
		logline("RESIZED");
		resized=0;

		int w = width();
		int h = height();

		if(dw>1) w = min_w + (w-min_w     ) / dw * dw;
		if(dh>1) h = min_h + (h-min_h+dh/3) / dh * dh;

		if(w!=width() || h!=height()) resize(w,h);
	}

	if(old_display_base_address != display_base_address)
	{
		old_display_base_address = display_base_address;
		lineedit_baseaddress->setText(usingstr("$%04X",old_display_base_address));
	}
}






















































