Source

KVNS / Textbox.cpp

Full commit
#include "Textbox.h"

#include <QPainter>
#include <QPalette>
#include <QKeyEvent>

#include "Options.h"

Textbox::Textbox()
{
	m_timer = 0;
	setAlignment(Qt::AlignLeft | Qt::AlignTop);
	setFocusPolicy(Qt::StrongFocus);
	
	setObjectName("textbox");
	setWordWrap(true);
	
	m_music = 0;
}

Textbox::~Textbox()
{
	if(m_music)
	{
		m_music->stop();
		delete m_music;
		m_music = 0;
	}
}

void Textbox::setSpeech(const QString& name, const QString& text, const QString& sound, bool autoConf)
{
	m_name = name;
	m_text = text;
	m_text = m_text.replace("\\n", "\n");
	
	m_tmpText = name + " :\n";
	m_pos = 0;
	m_autoConf = autoConf;
	setText(m_tmpText);
	
	if(m_nextIsStopped)
	{
		setText(m_tmpText + text);
		//QTimer::singleShot(0, this, SIGNAL(textFinished()));
		m_nextIsStopped = false;
		return;
	}
	
	if(sound.isEmpty() || CTRL_IS_DOWN)
	{
		m_music = 0;
	}
	else
	{
		m_music = SoundSystem::get()->getMusic(sound);
		m_music->play();
	}
	
	if(CTRL_IS_DOWN)
	{
		setText(m_tmpText + text);
		m_pos = 99999;
		QTimer::singleShot(100, this, SIGNAL(textFinished()));
	}
	else
	{
		m_timer = new QTimer(this);
		connect(m_timer, SIGNAL(timeout()), this, SLOT(nextLetter()));
		m_timer->start(Options::get()->value(Options::TEXT_SPEED).toUInt());
	}
}

void Textbox::nextLetter()
{
	if(m_pos < m_text.length())
	{
		m_tmpText.append(m_text[m_pos]);
		m_pos++;
		setText(m_tmpText);
	}
	else
	{
		if(m_timer)
		{
			delete m_timer;
			m_timer = 0;
			if(m_autoConf)
				emit textFinished();
		}
	}
}

void Textbox::keyPressEvent(QKeyEvent* ev)
{
	if(ev->key() == Qt::Key_Return)
	{
		stopText();
	}
	else if(ev->key() == Qt::Key_Control)
	{
		stopText();
	}
}

void Textbox::loadedText()
{
	m_nextIsStopped = true;
}

void Textbox::stopText()
{
	if(m_music)
	{
		m_music->stop();
		
		delete m_music;
		m_music = 0;
	}
	
	if(m_timer)
	{
		delete m_timer;
		m_timer = 0;
		m_tmpText.append(m_text.mid(m_pos));
		setText(m_tmpText);
		if(m_autoConf || CTRL_IS_DOWN)
		{
			emit textFinished();
		}
	}
	else
	{
		emit textFinished();
	}
}

void Textbox::mousePressEvent(QMouseEvent* ev)
{
	if(ev->button() == Qt::LeftButton)
	{
		stopText();
	}
}