summaryrefslogblamecommitdiffstats
path: root/src/graphwidget.cpp
blob: ec150266b09716c1c111e7b6cede44ddd1a55da8 (plain) (tree)






























































































                                                                                                                                
#include "graphwidget.h"
#include "datasource/idatasource.h"
#include <QDebug>
#include <QResizeEvent>
#include <QPaintEvent>
#include <QPainter>

const QColor GraphWidget::LINE_COLOR = QColor::fromRgb(20, 255, 80);
const QColor GraphWidget::BACK_COLOR = QColor::fromRgb(10, 0, 20);
const QColor GraphWidget::BAR_COLOR = QColor::fromRgb(200, 200, 200);

GraphWidget::GraphWidget(QWidget* parent)
	: QWidget(parent),
	  _source(NULL),
	  _histPos(0),
	  _vScale(0),
	  _doubleSpace(false)
{
	memset(_history, 0, sizeof(*_history) * HISTSIZE);
}

GraphWidget::~GraphWidget()
{
	delete _source;
}

void GraphWidget::setDataSource(IDataSource* source)
{
	delete _source;
	_source = source;
	memset(_history, 0, sizeof(*_history) * HISTSIZE);
	_vScale = (float)height() / (float)_source->getMaximum();
	qDebug() << "sDS " << _vScale;
	update();
}

void GraphWidget::readNextValue()
{
	if (_source == NULL)
		return;
	//
	_history[_histPos] = _source->read();
	_histPos = (_histPos + 1) % HISTSIZE;
	if (_doubleSpace && _histPos % 2 == 1) {
		_history[_histPos] = _history[(_histPos + HISTSIZE - 1) % HISTSIZE];
		update(_updateRectSmall);
	} else {
		update();
	}
}

void GraphWidget::resizeEvent(QResizeEvent * event)
{
	const QSize &size = event->size();
	_updateRectSmall = QRect(size.width() - 1, 0, 1, size.height());
	if (_source != NULL) {
		_vScale = (float)size.height() / (float)_source->getMaximum();
	}
	_doubleSpace = (width() < 400);
	update();
}

void GraphWidget::paintEvent(QPaintEvent * event)
{
	qint64 value;
	int x, y;
	const QRect &rect = event->rect();
	QPainter painter;
	painter.begin(this);
	painter.fillRect(rect, BACK_COLOR);
	if (_source == NULL)
		return;
	painter.setPen(LINE_COLOR);
	const int offset = HISTSIZE + HISTSIZE + _histPos - (this->width() - rect.x()) * (_doubleSpace ? 2 : 1);
	// TODO: double space
	for (int index = 0; index < rect.width(); ++index) {
		x = rect.x() + index;
		if (_doubleSpace) {
			value = (_history[(offset + index * 2) % HISTSIZE] + _history[(offset + index * 2 + 1) % HISTSIZE]) / 2;
		} else {
			value = _history[(offset + index) % HISTSIZE];
		}
		y = height() - int(value * _vScale);
		painter.drawLine(x, y, x, height());
	}
	const QList<qint64> &bars = _source->getBars();
	if (!bars.empty()) {
		painter.setPen(BAR_COLOR);
		for (QList<qint64>::const_iterator it = bars.begin(); it != bars.end(); ++it) {
			y = height() - int(*it * _vScale);
			painter.drawLine(rect.left(), y, rect.right() + 1, y);
		}
	}
	painter.end();
}