soundboard/src/soundbutton.cpp

117 lines
2.7 KiB
C++

#include "soundbutton.h"
#include <QTextItem>
#include "sound.h"
#include <Log.h>
uint64_t SoundButton::nextid = 0;
SoundButton::SoundButton(const std::string& filename, const std::string& name_, const std::string& keycombo, QWidget* parent) : QPushButton(parent), id(nextid++), file(filename), keycombo(keycombo) {
name = (name_.empty() ? filename : name_);
QString info = getInfo();
setText(info);
setObjectName(QString::fromStdString("soundButton" + std::to_string(id)));
setMinimumSize(QSize(80, 20));
setToolTip(info);
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::getFile() const {
return file;
}
const std::string& SoundButton::getKeyCombo() const {
return keycombo;
}
uint64_t SoundButton::getStartMS() const {
return startms;
}
uint64_t SoundButton::getLengthMS() const {
return lengthms;
}
float SoundButton::getVolume() const {
return volume;
}
void SoundButton::setStartMS(uint64_t startms_) {
startms = startms_;
}
void SoundButton::setLengthMS(uint64_t lengthms_) {
lengthms = lengthms_;
}
void SoundButton::setVolume(float v) {
volume = v;
}
void SoundButton::setHighlighted(bool highlighted_) {
highlighted = highlighted_;
repaint();
}
void SoundButton::paintEvent(QPaintEvent* event) {
QPushButton::paintEvent(event);
QPainter painter(this);
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);
}
QString text = "";
// cancel if nothing to print
if(text.isEmpty())
return;
painter.setPen(QPen(Qt::white));
QPoint textPos(0, painter.fontMetrics().height());
textPos.rx() = width() - painter.fontMetrics().horizontalAdvance(text) - 6;
painter.drawText(textPos, text);
}
void SoundButton::play() {
if(disabled) return;
uint64_t endms = (lengthms == 0 ? 0 : startms + lengthms);
try {
Sound::instance().addPlayback(file, volume, startms, endms);
} catch(const std::exception& e) {
Log::error << "Catched Exception when plaing Audio File: " << file;
setDisabled();
}
}
void SoundButton::setDisabled() {
disabled = true;
setEnabled(false);
}
QString SoundButton::getInfo() const {
return QString::fromStdString(name + (keycombo.empty() ? "" : "\n" + keycombo));
}