soundboard/src/soundbutton.cpp

106 lines
2.8 KiB
C++

#include "soundbutton.h"
#include <QTextItem>
#include "sound.h"
#include <Log.h>
SoundButton::SoundButton(uint32_t id, const std::string& name_, const std::string& keycombo, QWidget* parent) : QPushButton(parent), id(id), name(name_), keycombo(keycombo) {
setText(getInfo(false));
setObjectName(QString::fromStdString("soundButton" + std::to_string(id)));
setMinimumSize(QSize(80, 20));
setToolTip(getInfo(true));
setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred));
QKeySequence seq(QString::fromStdString(keycombo));
globalShortcut = new QxtGlobalShortcut(seq);
QObject::connect(globalShortcut, SIGNAL( activated() ), this, SLOT( play() ));
QObject::connect(this, SIGNAL( clicked() ), this, SLOT( play() ));
}
SoundButton::~SoundButton() {
delete globalShortcut;
}
const std::string& SoundButton::getName() const {
return name;
}
const std::string& SoundButton::getKeyCombo() const {
return keycombo;
}
void SoundButton::addSample(Sample& s) {
samples.push_back(s);
}
void SoundButton::setHighlighted(bool highlighted_) {
highlighted = highlighted_;
repaint();
}
void SoundButton::paintEvent(QPaintEvent* event) {
QPushButton::paintEvent(event);
QPainter painter(this);
// highlight
if(highlighted) {
QSize s = size();
QRect rect(HIGHLIGHTBORDEROFFSET, HIGHLIGHTBORDEROFFSET, s.width() - HIGHLIGHTBORDEROFFSET*2, s.height() - HIGHLIGHTBORDEROFFSET*2);
painter.setPen(QPen(Qt::red));
painter.drawRect(rect);
}
// sample count
if(samples.size() > 1) {
const QString text = QString::fromStdString(std::to_string(currentSample+1) + "/" + std::to_string(samples.size()));
painter.setPen(QPen(Qt::white));
QPoint textPos(0, painter.fontMetrics().height());
textPos.rx() = width() - painter.fontMetrics().horizontalAdvance(text) - 6;
painter.drawText(textPos, text);
}
// button id
const QString idtext = QString::fromStdString(std::to_string(id));
painter.setPen(QPen(Qt::gray));
QPoint textPos(6, painter.fontMetrics().height());
painter.drawText(textPos, idtext);
}
void SoundButton::play() {
if(disabled) return;
if(samples.size() == 0) {
Log::error << "Button " << name << " has no sample set";
setDisabled();
return;
}
const Sample& sample = samples.at(currentSample++);
if(currentSample >= samples.size())
currentSample = 0;
try {
Sound::instance().addPlayback(sample.file, sample.volume, sample.startms, sample.lengthms);
} catch(const std::exception& e) {
Log::error << "Catched Exception when plaing Audio File: " << sample.file;
setDisabled();
}
repaint();
}
void SoundButton::setDisabled() {
disabled = true;
setEnabled(false);
}
QString SoundButton::getInfo(bool withid) const {
return QString::fromStdString(name + (keycombo.empty() ? "" : "\n" + keycombo) + (withid ? "\nID: " + std::to_string(id) : ""));
}