id
int64
0
877k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
66
repo_stars
int64
94
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
11 values
repo_extraction_date
stringclasses
197 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
1,541,568
qmlplayer.cpp
missdeer_hannah/desktop/player/qmlplayer.cpp
#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QScreen> #include <QTimer> #include "qmlplayer.h" #include "FlacPic.h" #include "ID3v2Pic.h" #include "bassplayer.h" #include "configurationwindow.h" #include "lrcbar.h" #include "lyrics.h" #include "osd.h" #include "playlistmanagewindow.h" QmlPlayer::QmlPlayer(QObject *parent) : QObject(parent), m_timer(new QTimer()), m_lrcTimer(new QTimer()), m_lyrics(new Lyrics()), m_osd(new OSD()), m_lb(new LrcBar(m_lyrics, gBassPlayer)) { gBassPlayer->devInit(); connect(m_timer, &QTimer::timeout, this, &QmlPlayer::onUpdateTime); connect(m_lrcTimer, &QTimer::timeout, this, &QmlPlayer::onUpdateLrc); m_timer->start(27); m_lrcTimer->start(70); #if defined(Q_OS_WIN) && QT_VERSION < QT_VERSION_CHECK(6, 0, 0) taskbarButton = new QWinTaskbarButton(this); taskbarProgress = taskbarButton->progress(); taskbarProgress->setRange(0, 1000); thumbnailToolBar = new QWinThumbnailToolBar(this); playToolButton = new QWinThumbnailToolButton(thumbnailToolBar); stopToolButton = new QWinThumbnailToolButton(thumbnailToolBar); backwardToolButton = new QWinThumbnailToolButton(thumbnailToolBar); forwardToolButton = new QWinThumbnailToolButton(thumbnailToolBar); playToolButton->setToolTip(tr("Player")); playToolButton->setIcon(QIcon(":/rc/images/player/Play.png")); stopToolButton->setToolTip(tr("Stop")); stopToolButton->setIcon(QIcon(":/rc/images/player/Stop.png")); backwardToolButton->setToolTip(tr("Previous")); backwardToolButton->setIcon(QIcon(":/rc/images/player/Pre.png")); forwardToolButton->setToolTip(tr("Next")); forwardToolButton->setIcon(QIcon(":/rc/images/player/Next.png")); thumbnailToolBar->addButton(playToolButton); thumbnailToolBar->addButton(stopToolButton); thumbnailToolBar->addButton(backwardToolButton); thumbnailToolBar->addButton(forwardToolButton); connect(playToolButton, &QWinThumbnailToolButton::clicked, this, &QmlPlayer::onPlay); connect(stopToolButton, &QWinThumbnailToolButton::clicked, this, &QmlPlayer::onPlayStop); connect(backwardToolButton, &QWinThumbnailToolButton::clicked, this, &QmlPlayer::onPlayPrevious); connect(forwardToolButton, &QWinThumbnailToolButton::clicked, this, &QmlPlayer::onPlayNext); #endif } QmlPlayer::~QmlPlayer() { delete m_lb; delete m_osd; delete m_lyrics; delete m_lrcTimer; delete m_timer; } void QmlPlayer::setTaskbarButtonWindow() { #if defined(Q_OS_WIN) && QT_VERSION < QT_VERSION_CHECK(6, 0, 0) auto *window = qobject_cast<QWindow *>(gQmlApplicationEngine->rootObjects().at(0)); taskbarButton->setWindow(window); thumbnailToolBar->setWindow(window); #endif } void QmlPlayer::onQuit() { QCoreApplication::quit(); } void QmlPlayer::onShowPlaylists() { Q_ASSERT(playlistManageWindow); if (playlistManageWindow->isHidden()) playlistManageWindow->showNormal(); playlistManageWindow->raise(); playlistManageWindow->activateWindow(); } void QmlPlayer::onSettings() { Q_ASSERT(configurationWindow); configurationWindow->onShowConfiguration(); } void QmlPlayer::onFilter() {} void QmlPlayer::onMessage() {} void QmlPlayer::onMusic() {} void QmlPlayer::onCloud() {} void QmlPlayer::onBluetooth() {} void QmlPlayer::onCart() {} void QmlPlayer::presetEQChanged(int index) { QVector<QVector<int>> presets = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {3, 1, 0, -2, -4, -4, -2, 0, 1, 2}, {-2, 0, 2, 4, -2, -2, 0, 0, 4, 4}, {-6, 1, 4, -2, -2, -4, 0, 0, 6, 6}, {0, 8, 8, 4, 0, 0, 0, 0, 2, 2}, {-6, 0, 0, 0, 0, 0, 4, 0, 4, 0}, {-2, 3, 4, 1, -2, -2, 0, 0, 4, 4}, {-2, 0, 0, 2, 2, 0, 0, 0, 4, 4}, {0, 0, 0, 4, 4, 4, 0, 2, 3, 4}, {-2, 0, 2, 1, 0, 0, 0, 0, -2, -4}, {-4, 0, 2, 1, 0, 0, 0, 0, -4, -6}, {0, 0, 0, 4, 5, 3, 6, 3, 0, 0}, {-4, 0, 2, 0, 0, 0, 0, 0, -4, -6}}; if (index >= 0 && index < presets.length()) { auto &preset = presets[index]; setEq0(preset[0]); setEq1(preset[1]); setEq2(preset[2]); setEq3(preset[3]); setEq4(preset[4]); setEq5(preset[5]); setEq6(preset[6]); setEq7(preset[7]); setEq8(preset[8]); setEq9(preset[9]); emit eq0Changed(); emit eq1Changed(); emit eq2Changed(); emit eq3Changed(); emit eq4Changed(); emit eq5Changed(); emit eq6Changed(); emit eq7Changed(); emit eq8Changed(); emit eq9Changed(); } } void QmlPlayer::onOpenPreset() {} void QmlPlayer::onSavePreset() {} void QmlPlayer::onFavorite() {} void QmlPlayer::onStop() {} void QmlPlayer::onPrevious() {} void QmlPlayer::onPause() {} void QmlPlayer::onNext() {} void QmlPlayer::onRepeat() {} void QmlPlayer::onShuffle() {} void QmlPlayer::onSwitchFiles() {} void QmlPlayer::onSwitchPlaylists() {} void QmlPlayer::onSwitchFavourites() {} void QmlPlayer::onOpenFile() {} int QmlPlayer::getPrimaryScreenWidth() { auto *screen = QGuiApplication::primaryScreen(); Q_ASSERT(screen); auto size = screen->availableSize(); return size.width(); } int QmlPlayer::getPrimaryScreenHeight() { auto *screen = QGuiApplication::primaryScreen(); Q_ASSERT(screen); auto size = screen->availableSize(); return size.height(); } void QmlPlayer::showNormal() { emit showPlayer(); } void QmlPlayer::loadAudio(const QString &uri) {} void QmlPlayer::addToListAndPlay(const QList<QUrl> &uris) {} void QmlPlayer::addToListAndPlay(const QStringList &uris) {} void QmlPlayer::addToListAndPlay(const QString &uri) {} qreal QmlPlayer::getEq0() const { return m_eq0; } qreal QmlPlayer::getEq1() const { return m_eq1; } qreal QmlPlayer::getEq2() const { return m_eq2; } qreal QmlPlayer::getEq3() const { return m_eq3; } qreal QmlPlayer::getEq4() const { return m_eq4; } qreal QmlPlayer::getEq5() const { return m_eq5; } qreal QmlPlayer::getEq6() const { return m_eq6; } qreal QmlPlayer::getEq7() const { return m_eq7; } qreal QmlPlayer::getEq8() const { return m_eq8; } qreal QmlPlayer::getEq9() const { return m_eq9; } qreal QmlPlayer::getVolumn() const { return m_volumn; } qreal QmlPlayer::getProgress() const { return m_progress; } const QString &QmlPlayer::getCoverUrl() const { return m_coverUrl; } const QString &QmlPlayer::getSongName() const { return m_songName; } void QmlPlayer::setEq0(qreal value) { if (m_eq0 == value) return; m_eq0 = value; Q_ASSERT(gBassPlayer); gBassPlayer->setEQ(0, (int)m_eq0); } void QmlPlayer::setEq1(qreal value) { if (m_eq1 == value) return; m_eq1 = value; Q_ASSERT(gBassPlayer); gBassPlayer->setEQ(1, (int)m_eq1); } void QmlPlayer::setEq2(qreal value) { if (m_eq2 == value) return; m_eq2 = value; Q_ASSERT(gBassPlayer); gBassPlayer->setEQ(2, (int)m_eq2); } void QmlPlayer::setEq3(qreal value) { if (m_eq3 == value) return; m_eq3 = value; Q_ASSERT(gBassPlayer); gBassPlayer->setEQ(3, (int)m_eq3); } void QmlPlayer::setEq4(qreal value) { if (m_eq4 == value) return; m_eq4 = value; Q_ASSERT(gBassPlayer); gBassPlayer->setEQ(4, (int)m_eq4); } void QmlPlayer::setEq5(qreal value) { if (m_eq5 == value) return; m_eq5 = value; Q_ASSERT(gBassPlayer); gBassPlayer->setEQ(5, (int)m_eq6); } void QmlPlayer::setEq6(qreal value) { if (m_eq6 == value) return; m_eq6 = value; Q_ASSERT(gBassPlayer); gBassPlayer->setEQ(6, (int)m_eq6); } void QmlPlayer::setEq7(qreal value) { if (m_eq7 == value) return; m_eq7 = value; Q_ASSERT(gBassPlayer); gBassPlayer->setEQ(7, (int)m_eq7); } void QmlPlayer::setEq8(qreal value) { if (m_eq8 == value) return; m_eq8 = value; Q_ASSERT(gBassPlayer); gBassPlayer->setEQ(8, (int)m_eq8); } void QmlPlayer::setEq9(qreal value) { if (m_eq9 == value) return; m_eq9 = value; Q_ASSERT(gBassPlayer); gBassPlayer->setEQ(9, (int)m_eq9); } void QmlPlayer::setVolumn(qreal value) { if (m_volumn == value) return; m_volumn = value; Q_ASSERT(gBassPlayer); gBassPlayer->setVol((int)m_volumn); } void QmlPlayer::setProgress(qreal progress) { if (m_progress == progress) return; m_progress = progress; } void QmlPlayer::setCoverUrl(const QString &u) { if (m_coverUrl == u) return; m_coverUrl = u; } void QmlPlayer::setSongName(const QString &n) { if (m_songName == n) return; m_songName = n; } void QmlPlayer::onPlay() {} void QmlPlayer::onPlayStop() {} void QmlPlayer::onPlayPrevious() {} void QmlPlayer::onPlayNext() {} void QmlPlayer::onUpdateTime() {} void QmlPlayer::onUpdateLrc() {}
9,303
C++
.cpp
335
22.826866
101
0.639879
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,569
playlist.cpp
missdeer_hannah/desktop/player/playlist.cpp
#include <QDir> #include <QDragEnterEvent> #include <QDropEvent> #include <QFileDialog> #include <QFileInfo> #include <QFontInfo> #include <QInputDialog> #include <QMessageBox> #include <QMimeData> #include <QStandardPaths> #include "playlist.h" #include "bassplayer.h" #include "ui_playlist.h" PlayList::PlayList(BassPlayer *player, QWidget *parent) : QWidget(parent), ui(new Ui::PlayList), m_player(player) { ui->setupUi(this); ui->playListTable->horizontalHeader()->setStretchLastSection(true); setWindowFlags(Qt::WindowTitleHint | Qt::CustomizeWindowHint); setFixedSize(width(), height()); connect(ui->searchEdit, SIGNAL(returnPressed()), this, SLOT(on_searchButton_clicked())); readFromFile(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + "/default.hpl"); } PlayList::~PlayList() { auto dirPath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); QDir dir(dirPath); if (!dir.exists()) { dir.mkdir(dirPath); } saveToFile(dirPath + "/default.hpl"); delete ui; } bool PlayList::fixSuffix(const QString &uri) { QString ext = QFileInfo(uri).suffix().toLower(); QStringList audioExts = { "mp3", "mp1", "ogg", "ape", "m4a", "aac", "tta", "wma", "mp2", "wav", "aiff", "mp4", "m4v", "alac", "flac", "wv", }; return (audioExts.contains(ext)); } bool PlayList::isEmpty() { return m_trackList.isEmpty(); } void PlayList::add(const QString &fileName) { if (fixSuffix(fileName)) { if ((int)(m_player->getFileSecond(fileName)) >= m_lengthFilter) { m_trackList.append(fileName); m_timeList.append(m_player->getFileTotalTime(fileName)); } } tableUpdate(); } void PlayList::insert(int index, const QString &fileName) { if (fixSuffix(fileName)) { if ((int)(m_player->getFileSecond(fileName)) >= m_lengthFilter) { if (index < m_curIndex) ++m_curIndex; m_trackList.insert(index, fileName); m_timeList.insert(index, m_player->getFileTotalTime(fileName)); } } tableUpdate(); } void PlayList::remove(int index) { if (index <= m_curIndex && index > -1) --m_curIndex; m_trackList.removeAt(index); m_timeList.removeAt(index); tableUpdate(); } void PlayList::clearAll() { m_trackList.clear(); m_timeList.clear(); m_curIndex = 0; tableUpdate(); } int PlayList::getLength() { return m_trackList.length(); } int PlayList::getIndex() { if (!m_trackList.isEmpty()) { return m_curIndex; } return -1; } QString PlayList::next(bool isLoop) { if (!m_trackList.isEmpty()) { if (isLoop) { if (m_curIndex < m_trackList.length() - 1) { ++m_curIndex; } else { m_curIndex = 0; } ui->playListTable->selectRow(m_curIndex); tableUpdate(); return m_trackList[m_curIndex]; } if (m_curIndex < m_trackList.length() - 1) { ++m_curIndex; ui->playListTable->selectRow(m_curIndex); tableUpdate(); return m_trackList[m_curIndex]; } return "stop"; } return ""; } QString PlayList::previous(bool isLoop) { if (!m_trackList.isEmpty()) { if (isLoop) { if (m_curIndex == 0) { m_curIndex = m_trackList.length() - 1; } else { --m_curIndex; } ui->playListTable->selectRow(m_curIndex); tableUpdate(); return m_trackList[m_curIndex]; } if (m_curIndex > 0) { --m_curIndex; ui->playListTable->selectRow(m_curIndex); tableUpdate(); return m_trackList[m_curIndex]; } return "stop"; } return ""; } const QString &PlayList::playIndex(int index) { m_curIndex = index; ui->playListTable->selectRow(m_curIndex); tableUpdate(); return m_trackList[m_curIndex]; } const QString &PlayList::getFileNameForIndex(int index) { return m_trackList[index]; } const QString &PlayList::getCurFile() { return m_trackList[m_curIndex]; } QString PlayList::playLast() { if (!m_trackList.isEmpty()) { m_curIndex = m_trackList.length() - 1; ui->playListTable->selectRow(m_curIndex); tableUpdate(); return m_trackList[m_curIndex]; } return ""; } void PlayList::tableUpdate() { ui->playListTable->clear(); ui->playListTable->setRowCount(getLength()); int count = m_trackList.size(); for (int i = 0; i < count; i++) { QString fileName = m_trackList[i]; QFileInfo fileInfo(fileName); QTableWidgetItem *item = new QTableWidgetItem(fileInfo.fileName()); QTableWidgetItem *timeItem = new QTableWidgetItem(m_timeList[i]); if (i == m_curIndex) { item->setBackground(QColor(128, 255, 0, 128)); timeItem->setBackground(QColor(128, 255, 0, 128)); } ui->playListTable->setItem(i, 0, item); ui->playListTable->setItem(i, 1, timeItem); } } void PlayList::on_deleteButton_clicked() { QItemSelectionModel *selectionModel = ui->playListTable->selectionModel(); QModelIndexList selected = selectionModel->selectedIndexes(); QMap<int, int> rowMap; for (const auto &index : selected) { rowMap.insert(index.row(), 0); } QMapIterator<int, int> rowMapIterator(rowMap); rowMapIterator.toBack(); while (rowMapIterator.hasPrevious()) { rowMapIterator.previous(); remove(rowMapIterator.key()); } } void PlayList::dragEnterEvent(QDragEnterEvent *event) { event->acceptProposedAction(); } void PlayList::dropEvent(QDropEvent *event) { auto urls = event->mimeData()->urls(); if (urls.isEmpty()) return; for (const auto &u : urls) { auto fileName = u.toLocalFile(); if (fixSuffix(fileName)) { add(fileName); } } } void PlayList::on_playListTable_cellDoubleClicked(int row, int) { m_curIndex = row; emit callPlayer(); tableUpdate(); } void PlayList::on_clearButton_clicked() { clearAll(); } void PlayList::on_insertButton_clicked() { int index = ui->playListTable->currentRow(); if (index < 0) index = 0; QStringList fileNames = QFileDialog::getOpenFileNames( this, tr("Insert audio file before selected item"), 0, tr("Audio file (*.mp3 *.mp2 *.mp1 *.wav *.aiff *.ogg *.ape *.mp4 *.m4a *.m4v *.aac *.alac *.tta *.flac *.wma *.wv)")); int count = fileNames.size(); for (int i = 0; i < count; i++) { QString fileName = fileNames[i]; insert(index + i, fileName); } } void PlayList::on_addButton_clicked() { QStringList fileNames = QFileDialog::getOpenFileNames( this, tr("Add audio file"), 0, tr("Audio file (*.mp3 *.mp2 *.mp1 *.wav *.aiff *.ogg *.ape *.mp4 *.m4a *.m4v *.aac *.alac *.tta *.flac *.wma *.wv)")); for (const auto &fileName : fileNames) { add(fileName); } } void PlayList::on_insertUrlButton_clicked() { QString u = QInputDialog::getText(this, tr("Add remote audio"), tr("Remote audio URL")); int index = ui->playListTable->currentRow(); if (index < 0) index = 0; insert(index, u); } void PlayList::on_addUrlButton_clicked() { QString u = QInputDialog::getText(this, tr("Add remote audio"), tr("Remote audio URL")); add(u); } void PlayList::on_searchButton_clicked() { if (!m_trackList.isEmpty() && !ui->searchEdit->text().isEmpty()) { int resultIndex = -1; int count = m_trackList.size(); for (int i = 0; i < count; i++) { QString fileName = m_trackList[i]; QFileInfo fileInfo(fileName); if (ui->isCaseSensitive->isChecked()) { if (fileInfo.fileName().indexOf(ui->searchEdit->text()) > -1) { resultIndex = i; break; } } else { if (fileInfo.fileName().toLower().indexOf(ui->searchEdit->text().toLower()) > -1) { resultIndex = i; break; } } } if (resultIndex != -1) { ui->playListTable->selectRow(resultIndex); } else { QMessageBox::warning(this, tr("Sorry"), tr("Cannot find."), QMessageBox::Ok); } } else if (ui->searchEdit->text().isEmpty()) { QMessageBox::question(this, tr("Hello"), tr("What are you looking for?"), QMessageBox::Ok); } else { QMessageBox::question(this, tr("What's this"), tr("Why I should search in the empty list?"), QMessageBox::Ok); } } void PlayList::on_searchNextButton_clicked() { if (!m_trackList.isEmpty() && !ui->searchEdit->text().isEmpty()) { int resultIndex = -1; int start = ui->playListTable->currentRow() + 1; int count = m_trackList.size(); if (start < count) for (int i = start; i < count; i++) { QString fileName = m_trackList[i]; QFileInfo fileInfo(fileName); if (ui->isCaseSensitive->isChecked()) { if (fileInfo.fileName().indexOf(ui->searchEdit->text()) > -1) { resultIndex = i; break; } } else { if (fileInfo.fileName().toLower().indexOf(ui->searchEdit->text().toLower()) > -1) { resultIndex = i; break; } } } if (resultIndex != -1) { ui->playListTable->selectRow(resultIndex); } else { QMessageBox::information(0, tr("Searching done!"), tr("All things are searched."), QMessageBox::Ok); } } else if (ui->searchEdit->text().isEmpty()) { QMessageBox::question(0, tr("Hello"), tr("What are you looking for?"), QMessageBox::Ok); } else { QMessageBox::question(this, tr("What's this"), tr("Why I should search in the empty list?"), QMessageBox::Ok); } } void PlayList::on_setLenFilButton_clicked() { bool ok; int set = QInputDialog::getInt(0, tr("Minimum Playback Length"), tr("Audio files smaller than this length will not be accepted \n unit: seconds"), m_lengthFilter, 0, 2147483647, 1, &ok); if (ok) m_lengthFilter = set; } void PlayList::saveToFile(const QString &fileName) { QFile file(fileName); if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { QDataStream stream(&file); stream << (quint32)0x61727487 << m_trackList << m_timeList << m_curIndex; file.close(); } } void PlayList::readFromFile(const QString &fileName) { QFile file(fileName); if (file.open(QIODevice::ReadOnly)) { QDataStream stream(&file); quint32 magic; stream >> magic; if (magic == 0x61727487) { stream >> m_trackList; stream >> m_timeList; stream >> m_curIndex; } file.close(); tableUpdate(); } }
12,134
C++
.cpp
438
20.052511
126
0.552008
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,573
fftdisplay.cpp
missdeer_hannah/desktop/player/fftdisplay.cpp
#include <cstring> #include <QBrush> #include <QColor> #include <QPainter> #include <QPen> #include "fftdisplay.h" FFTDisplay::FFTDisplay(QWidget *parent) : QGroupBox(parent) { height = 120; acc = 0.35; maxSpeed = 9; speed = 0.025; forceD = 6; elasticCoefficient = 0.6; minElasticStep = 0.02; setAttribute(Qt::WA_TransparentForMouseEvents, true); std::memset(fftBarValue, 0, sizeof(fftBarValue)); std::memset(fftBarPeakValue, 0, sizeof(fftBarPeakValue)); std::memset(peakSlideSpeed, 0, sizeof(peakSlideSpeed)); } void FFTDisplay::paintEvent(QPaintEvent * /*event*/) { QPainter painter(this); QPen noPen(Qt::NoPen); QPen peakPen(QColor(110, 139, 61)); peakPen.setWidth(2); QBrush stickBrush(QColor(70, 130, 180, 180)); for (int i = 0; i < arraySize; i++) { int drawX = sx + (i * (width + margin)); stickBrush.setColor(QColor(70, 130, 180, (int)(140 * fftBarValue[i]) + 90)); painter.setPen(noPen); painter.setBrush(stickBrush); painter.drawRect(drawX, sy + (height * (1 - fftBarValue[i])), width, (height - 0.000000001) * fftBarValue[i]); painter.setPen(peakPen); int y = sy + ((double)height * (1 - fftBarPeakValue[i])) - 1; painter.drawLine(drawX + 1, y, drawX + width - 1, y); } } void FFTDisplay::peakSlideDown() { for (int i = 0; i < arraySize; i++) { double realityDown = speed * peakSlideSpeed[i]; if (fftBarPeakValue[i] - realityDown <= fftBarValue[i]) { double elasticForce = 0; if (realityDown > minElasticStep) elasticForce = peakSlideSpeed[i] * elasticCoefficient; peakSlideSpeed[i] = (fftBarPeakValue[i] - fftBarValue[i]) * forceD - elasticForce; fftBarPeakValue[i] = fftBarValue[i]; } else { if (fftBarPeakValue[i] > realityDown) { fftBarPeakValue[i] -= realityDown; } else { fftBarPeakValue[i] = 0; } if (peakSlideSpeed[i] + acc <= maxSpeed) peakSlideSpeed[i] += acc; else peakSlideSpeed[i] = maxSpeed; } } } void FFTDisplay::cutValue() { for (double &i : fftBarValue) { if (i > 1) { i = 1; } else if (i < 0) { i = 0; } } }
2,535
C++
.cpp
83
23.156627
118
0.552912
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,574
shadowplayer.cpp
missdeer_hannah/desktop/player/shadowplayer.cpp
#include <QDir> #include <QFile> #include <QFileDialog> #include <QFileInfo> #include <QInputDialog> #include <QMenu> #include <QMessageBox> #include <QMimeData> #include <QMouseEvent> #include <QPainter> #include <QPropertyAnimation> #include <QRandomGenerator> #include <QStandardPaths> #include <QTimer> #include <QToolTip> #include "shadowplayer.h" #include "FlacPic.h" #include "ID3v2Pic.h" #include "bassplayer.h" #include "lrcbar.h" #include "lyrics.h" #include "osd.h" #include "playlist.h" #include "ui_shadowplayer.h" ShadowPlayer::ShadowPlayer(QWidget *parent) : QMainWindow(parent), ui(new Ui::ShadowPlayer), timer(new QTimer()), lrcTimer(new QTimer()), player(new BassPlayer()), lyrics(new Lyrics()), osd(new OSD()), lb(new LrcBar(lyrics, player, 0)) { ui->setupUi(this); // setFixedSize(width(), height()); playList = new PlayList(player, ui->playerListArea); setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint | Qt::WindowMinimizeButtonHint); setAttribute(Qt::WA_TranslucentBackground, true); ui->coverLabel->setScaledContents(true); ui->coverLabel->setPixmap(QPixmap(":/rc/images/player/ShadowPlayer.png")); ui->tagLabel->setShadowMode(1); ui->mediaInfoLabel->setShadowMode(1); ui->tagLabel->setShadowColor(QColor(0, 0, 0, 80)); ui->mediaInfoLabel->setShadowColor(QColor(0, 0, 0, 80)); ui->curTimeLabel->setShadowMode(1); ui->totalTimeLabel->setShadowMode(1); ui->curTimeLabel->setShadowColor(QColor(0, 0, 0, 80)); ui->totalTimeLabel->setShadowColor(QColor(0, 0, 0, 80)); player->devInit(); connect(timer, SIGNAL(timeout()), this, SLOT(UpdateTime())); connect(lrcTimer, SIGNAL(timeout()), this, SLOT(UpdateLrc())); connect(ui->eqSlider_1, SIGNAL(valueChanged(int)), this, SLOT(applyEQ())); connect(ui->eqSlider_2, SIGNAL(valueChanged(int)), this, SLOT(applyEQ())); connect(ui->eqSlider_3, SIGNAL(valueChanged(int)), this, SLOT(applyEQ())); connect(ui->eqSlider_4, SIGNAL(valueChanged(int)), this, SLOT(applyEQ())); connect(ui->eqSlider_5, SIGNAL(valueChanged(int)), this, SLOT(applyEQ())); connect(ui->eqSlider_6, SIGNAL(valueChanged(int)), this, SLOT(applyEQ())); connect(ui->eqSlider_7, SIGNAL(valueChanged(int)), this, SLOT(applyEQ())); connect(ui->eqSlider_8, SIGNAL(valueChanged(int)), this, SLOT(applyEQ())); connect(ui->eqSlider_9, SIGNAL(valueChanged(int)), this, SLOT(applyEQ())); connect(ui->eqSlider_10, SIGNAL(valueChanged(int)), this, SLOT(applyEQ())); connect(playList, SIGNAL(callPlayer()), this, SLOT(callFromPlayList())); timer->start(27); lrcTimer->start(70); setAcceptDrops(true); loadSkin(":/rc/images/Skin1.jpg", false); ui->playerListArea->setGeometry(QRect(370, 200, 331, 0)); loadConfig(); bgLinearGradient.setColorAt(0, QColor(255, 255, 255, 0)); bgLinearGradient.setColorAt(1, QColor(255, 255, 255, 255)); bgLinearGradient.setStart(0, 0); bgLinearGradient.setFinalStop(0, height()); #if defined(Q_OS_WIN) && QT_VERSION < QT_VERSION_CHECK(6, 0, 0) taskbarButton = new QWinTaskbarButton(this); taskbarButton->setWindow(windowHandle()); taskbarProgress = taskbarButton->progress(); taskbarProgress->setRange(0, 1000); connect(ui->playSlider, SIGNAL(valueChanged(int)), taskbarProgress, SLOT(setValue(int))); thumbnailToolBar = new QWinThumbnailToolBar(this); playToolButton = new QWinThumbnailToolButton(thumbnailToolBar); stopToolButton = new QWinThumbnailToolButton(thumbnailToolBar); backwardToolButton = new QWinThumbnailToolButton(thumbnailToolBar); forwardToolButton = new QWinThumbnailToolButton(thumbnailToolBar); playToolButton->setToolTip(tr("Player")); playToolButton->setIcon(QIcon(":/rc/images/player/Play.png")); stopToolButton->setToolTip(tr("Stop")); stopToolButton->setIcon(QIcon(":/rc/images/player/Stop.png")); backwardToolButton->setToolTip(tr("Previous")); backwardToolButton->setIcon(QIcon(":/rc/images/player/Pre.png")); forwardToolButton->setToolTip(tr("Next")); forwardToolButton->setIcon(QIcon(":/rc/images/player/Next.png")); thumbnailToolBar->addButton(playToolButton); thumbnailToolBar->addButton(stopToolButton); thumbnailToolBar->addButton(backwardToolButton); thumbnailToolBar->addButton(forwardToolButton); connect(playToolButton, SIGNAL(clicked()), this, SLOT(on_playButton_clicked())); connect(stopToolButton, SIGNAL(clicked()), this, SLOT(on_stopButton_clicked())); connect(backwardToolButton, SIGNAL(clicked()), this, SLOT(on_playPreButton_clicked())); connect(forwardToolButton, SIGNAL(clicked()), this, SLOT(on_playNextButton_clicked())); #endif sizeSlideAnimation = new QPropertyAnimation(this, "geometry"); sizeSlideAnimation->setDuration(700); sizeSlideAnimation->setEasingCurve(QEasingCurve::OutCirc); tagAnimation = new QPropertyAnimation(ui->tagLabel, "geometry"); tagAnimation->setDuration(700); tagAnimation->setStartValue(QRect(130, 30, 0, 16)); tagAnimation->setEndValue(QRect(130, 30, 221, 16)); mediaInfoAnimation = new QPropertyAnimation(ui->mediaInfoLabel, "geometry"); mediaInfoAnimation->setDuration(800); mediaInfoAnimation->setStartValue(QRect(130, 50, 0, 16)); mediaInfoAnimation->setEndValue(QRect(130, 50, 221, 16)); coverAnimation = new QPropertyAnimation(ui->coverLabel, "geometry"); coverAnimation->setEasingCurve(QEasingCurve::OutCirc); coverAnimation->setDuration(600); coverAnimation->setStartValue(QRect(60, 60, 1, 1)); coverAnimation->setEndValue(QRect(10, 10, 111, 111)); eqHideAnimation = new QPropertyAnimation(ui->eqGroupBox, "geometry"); eqHideAnimation->setDuration(600); eqHideAnimation->setStartValue(QRect(370, 30, 331, 171)); eqHideAnimation->setEndValue(QRect(370, 30, 331, 0)); eqShowAnimation = new QPropertyAnimation(ui->eqGroupBox, "geometry"); eqShowAnimation->setDuration(600); eqShowAnimation->setStartValue(QRect(370, 30, 331, 0)); eqShowAnimation->setEndValue(QRect(370, 30, 331, 171)); lyricsHideAnimation = new QPropertyAnimation(ui->lyricsBox, "geometry"); lyricsHideAnimation->setDuration(600); lyricsHideAnimation->setStartValue(QRect(370, 210, 331, 181)); lyricsHideAnimation->setEndValue(QRect(370, 391, 331, 0)); lyricsShowAnimation = new QPropertyAnimation(ui->lyricsBox, "geometry"); lyricsShowAnimation->setDuration(600); lyricsShowAnimation->setStartValue(QRect(370, 391, 331, 0)); lyricsShowAnimation->setEndValue(QRect(370, 210, 331, 181)); playListHideAnimation = new QPropertyAnimation(ui->playerListArea, "geometry"); playListHideAnimation->setDuration(600); playListHideAnimation->setStartValue(QRect(370, 30, 331, 361)); playListHideAnimation->setEndValue(QRect(370, 205, 331, 0)); playListShowAnimation = new QPropertyAnimation(ui->playerListArea, "geometry"); playListShowAnimation->setDuration(600); playListShowAnimation->setStartValue(QRect(370, 205, 331, 0)); playListShowAnimation->setEndValue(QRect(370, 30, 331, 361)); connect(playListHideAnimation, SIGNAL(finished()), this, SLOT(update())); connect(playListShowAnimation, SIGNAL(finished()), this, SLOT(update())); fadeOutAnimation = new QPropertyAnimation(this, "windowOpacity"); fadeOutAnimation->setDuration(400); fadeOutAnimation->setStartValue(1); fadeOutAnimation->setEndValue(0); connect(fadeOutAnimation, SIGNAL(finished()), this, SLOT(close())); fadeInAnimation = new QPropertyAnimation(this, "windowOpacity"); fadeInAnimation->setDuration(400); fadeInAnimation->setStartValue(0); fadeInAnimation->setEndValue(1); fadeInAnimation->start(); connect(fadeInAnimation, &QPropertyAnimation::finished, [this] { activateWindow(); raise(); #if defined(Q_OS_WIN) && QT_VERSION < QT_VERSION_CHECK(6, 0, 0) setTaskbarButtonWindow(); #endif }); } ShadowPlayer::~ShadowPlayer() { delete ui; delete lb; delete player; delete timer; delete lyrics; delete playList; delete osd; delete sizeSlideAnimation; delete fadeInAnimation; delete tagAnimation; delete mediaInfoAnimation; delete coverAnimation; delete fadeOutAnimation; delete eqHideAnimation; delete eqShowAnimation; delete lyricsHideAnimation; delete lyricsShowAnimation; delete playListHideAnimation; delete playListShowAnimation; } void ShadowPlayer::dragEnterEvent(QDragEnterEvent *event) { event->acceptProposedAction(); } void ShadowPlayer::dropEvent(QDropEvent *event) { QList<QUrl> urls = event->mimeData()->urls(); if (urls.isEmpty()) return; QString fileName = urls.first().toLocalFile(); if (fileName.isEmpty()) return; QFileInfo fi(fileName); QString ext = fi.suffix().toLower(); QStringList imageExts = {"jpg", "jpeg", "png", "gif", "bmp"}; if (imageExts.contains(ext)) { loadSkin(fileName); } else if (ext.compare("lrc", Qt::CaseInsensitive) == 0) { lyrics->resolve(fileName, true); } else { addToListAndPlay(urls); } } void ShadowPlayer::paintEvent(QPaintEvent *) { QPainter painter(this); if (!skin.isNull()) { int topY = 0; switch (skinPos) { case 0: skinDrawPos = 0; break; case 1: skinDrawPos = 0.5; break; case 2: skinDrawPos = 1; break; default: break; } switch (skinMode) { case 0: topY = -(skin.height() - 400) * skinDrawPos; painter.drawPixmap(0, topY, skin); break; case 1: topY = -(skinLeft.height() - 400) * skinDrawPos; painter.drawPixmap(0, topY, skinLeft); break; case 2: topY = -(skinFull.height() - 400) * skinDrawPos; painter.drawPixmap(0, topY, skinFull); break; case 3: if (geometry().width() > 361) { topY = -(skinFull.height() - 400) * skinDrawPos; painter.drawPixmap(0, topY, skinFull); } else { topY = -(skinLeft.height() - 400) * skinDrawPos; painter.drawPixmap(0, topY, skinLeft); } break; case 4: if (geometry().width() <= 360) { topY = -(skinLeft.height() - 400) * skinDrawPos; painter.drawPixmap(0, topY, skinLeft); } else if (geometry().width() >= 710) { topY = -(skinFull.height() - 400) * skinDrawPos; painter.drawPixmap(0, topY, skinFull); } else { topY = -(width() * aspectRatio - 400) * skinDrawPos; painter.drawPixmap(0, topY, width(), width() * aspectRatio, skin); } break; default: break; } } painter.setBrush(QBrush(bgLinearGradient)); painter.setPen(Qt::NoPen); painter.drawRect(0, 0, width(), height()); } void ShadowPlayer::contextMenuEvent(QContextMenuEvent *) { QCursor cur = cursor(); QAction textAction1(tr("Drag left side of the window to adjust position accurately"), this); textAction1.setEnabled(false); QMenu menu; menu.addAction(tr("Load default skin"), this, SLOT(loadDefaultSkin())); menu.addSeparator(); menu.addAction(tr("Fix skin to left side"), this, SLOT(fixSkinSizeLeft())); menu.addAction(tr("Fix skin to full window"), this, SLOT(fixSkinSizeFull())); menu.addAction(tr("Original skin size"), this, SLOT(originalSkinSize())); menu.addAction(tr("Auto resize skin"), this, SLOT(autoSkinSize())); menu.addAction(tr("Resize skin dynamically"), this, SLOT(dynamicSkinSize())); menu.addSeparator(); menu.addAction(tr("Skin on top"), this, SLOT(skinOnTop())); menu.addAction(tr("Skin on center"), this, SLOT(skinOnCenter())); menu.addAction(tr("Skin on bottom"), this, SLOT(skinOnBottom())); menu.addAction(&textAction1); menu.addSeparator(); menu.addAction(tr("Disable skin"), this, SLOT(skinDisable())); menu.addSeparator(); menu.addAction(tr("Physical settings"), this, SLOT(physicsSetting())); menu.addAction(tr("Enable Physical FFT"), this, SLOT(enableFFTPhysics())); menu.addAction(tr("Disable Physical FFT"), this, SLOT(disableFFTPhysics())); menu.addSeparator(); menu.addAction(tr("About"), this, SLOT(showDeveloperInfo())); menu.exec(cur.pos()); } void ShadowPlayer::loadDefaultSkin() { loadSkin(":/rc/images/Skin1.jpg", false); QFile skinFile(QCoreApplication::applicationDirPath() + "/skin.dat"); skinFile.remove(); } void ShadowPlayer::fixSkinSizeLeft() { skinMode = 1; repaint(); } void ShadowPlayer::fixSkinSizeFull() { skinMode = 2; repaint(); } void ShadowPlayer::originalSkinSize() { skinMode = 0; repaint(); } void ShadowPlayer::autoSkinSize() { skinMode = 3; repaint(); } void ShadowPlayer::dynamicSkinSize() { skinMode = 4; repaint(); } void ShadowPlayer::skinOnTop() { skinPos = 0; repaint(); } void ShadowPlayer::skinOnCenter() { skinPos = 1; repaint(); } void ShadowPlayer::skinOnBottom() { skinPos = 2; repaint(); } void ShadowPlayer::skinDisable() { skin = QPixmap(); skinLeft = skin; skinFull = skin; repaint(); } void ShadowPlayer::infoLabelAnimation() { tagAnimation->stop(); mediaInfoAnimation->stop(); coverAnimation->stop(); tagAnimation->start(); mediaInfoAnimation->start(); coverAnimation->start(); update(); } void ShadowPlayer::loadAudio(const QString &uri) { if (player->openAudio(QDir::toNativeSeparators(uri)) != "err") { QFileInfo fileinfo(uri); showCoverPic(uri); ui->mediaInfoLabel->setText(player->getNowPlayInfo()); ui->totalTimeLabel->setText(player->getTotalTime()); oriFreq = player->getFreq(); on_freqSlider_valueChanged(ui->freqSlider->value()); player->setVol(ui->volSlider->value()); applyEQ(); player->setReverse(isReverse); on_eqEnableCheckBox_clicked(ui->eqEnableCheckBox->isChecked()); player->updateReverb(ui->reverbDial->value()); player->play(); if (player->isPlaying()) { playing = true; ui->playButton->setIcon(QIcon(":/rc/images/player/Pause.png")); ui->playButton->setToolTip(tr("Pause")); #if defined(Q_OS_WIN) && QT_VERSION < QT_VERSION_CHECK(6, 0, 0) taskbarProgress->show(); taskbarProgress->resume(); taskbarButton->setOverlayIcon(QIcon(":/rc/images/player/Play.png")); playToolButton->setIcon(QIcon(":/rc/images/player/Pause.png")); playToolButton->setToolTip(tr("Pause")); #endif } if (!lyrics->resolve(uri)) if (!lyrics->loadFromLrcDir(uri)) if (!lyrics->loadFromFileRelativePath(uri, "/Lyrics/")) lyrics->loadFromFileRelativePath(uri, "/../Lyrics/"); if (player->getTags() == tr("Show_File_Name")) ui->tagLabel->setText(fileinfo.fileName()); else ui->tagLabel->setText(player->getTags()); infoLabelAnimation(); osd->showOSD(ui->tagLabel->text(), player->getTotalTime()); } } void ShadowPlayer::loadSkin(const QString &image, bool save) { skin = QPixmap(image); skinLeft = skin.scaledToWidth(360, Qt::SmoothTransformation); skinFull = skin.scaledToWidth(710, Qt::SmoothTransformation); aspectRatio = (double)skin.height() / skin.width(); if (save) saveSkinData(); update(); } void ShadowPlayer::UpdateTime() { ui->leftLevel->setValue(LOWORD(player->getLevel())); ui->rightLevel->setValue(HIWORD(player->getLevel())); ui->leftLevel->update(); ui->rightLevel->update(); double ldB = 20 * log((double)ui->leftLevel->value() / 32768); double rdB = 20 * log((double)ui->rightLevel->value() / 32768); if (ldB < -60) ldB = -60; if (rdB < -60) rdB = -60; ui->leftdB->setValue(ldB); ui->rightdB->setValue(rdB); ui->leftdB->update(); ui->rightdB->update(); if (skinPos == 3) update(); ui->curTimeLabel->setText(player->getCurTime()); if (isPlaySliderPress == false) ui->playSlider->setSliderPosition(player->getPos()); updateFFT(); if (!player->isPlaying()) { switch (playMode) { case 0: playing = false; ui->playButton->setIcon(QIcon(":/rc/images/player/Play.png")); ui->playButton->setToolTip(tr("Play")); #if defined(Q_OS_WIN) && QT_VERSION < QT_VERSION_CHECK(6, 0, 0) taskbarProgress->hide(); taskbarButton->setOverlayIcon(QIcon(":/rc/images/player/Stop.png")); playToolButton->setIcon(QIcon(":/rc/images/player/Play.png")); playToolButton->setToolTip(tr("Play")); #endif break; case 1: if (playing) { player->stop(); player->play(); } break; case 2: if (playing) { QString nextFile = playList->next(false); if (nextFile == "stop") { playing = false; ui->playButton->setIcon(QIcon(":/rc/images/player/Play.png")); ui->playButton->setToolTip(tr("Play")); #if defined(Q_OS_WIN) && QT_VERSION < QT_VERSION_CHECK(6, 0, 0) taskbarProgress->hide(); taskbarButton->setOverlayIcon(QIcon(":/rc/images/player/Stop.png")); playToolButton->setIcon(QIcon(":/rc/images/player/Play.png")); playToolButton->setToolTip(tr("Play")); #endif } else { loadAudio(nextFile); } } break; case 3: if (playing) { loadAudio(playList->next(true)); } break; case 4: if (playing) { int index = QRandomGenerator::global()->bounded(playList->getLength()); loadAudio(playList->playIndex(index)); } default: break; } } } void ShadowPlayer::UpdateLrc() { lyrics->updateTime(player->getCurTimeMS(), player->getTotalTimeMS()); double pos = 0; double curTimePos = lyrics->getTimePos(player->getCurTimeMS()); ui->lrcLabel_1->setText(lyrics->getLrcString(-3)); ui->lrcLabel_2->setText(lyrics->getLrcString(-2)); ui->lrcLabel_3->setText(lyrics->getLrcString(-1)); ui->lrcLabel_4->setText(lyrics->getLrcString(0)); ui->lrcLabel_5->setText(lyrics->getLrcString(1)); ui->lrcLabel_6->setText(lyrics->getLrcString(2)); ui->lrcLabel_7->setText(lyrics->getLrcString(3)); ui->lrcLabel_1->setToolTip(ui->lrcLabel_1->text()); ui->lrcLabel_2->setToolTip(ui->lrcLabel_2->text()); ui->lrcLabel_3->setToolTip(ui->lrcLabel_3->text()); ui->lrcLabel_4->setToolTip(ui->lrcLabel_4->text()); ui->lrcLabel_5->setToolTip(ui->lrcLabel_5->text()); ui->lrcLabel_6->setToolTip(ui->lrcLabel_6->text()); ui->lrcLabel_7->setToolTip(ui->lrcLabel_7->text()); if (curTimePos >= 0.2 && curTimePos <= 0.8) { pos = 0.5; } else if (curTimePos < 0.2) { pos = curTimePos * 2.5; // 0~0.5 } else if (curTimePos > 0.8) { pos = (curTimePos - 0.8) * 2.5 + 0.5; // 0.5~1 } ui->lrcLabel_1->setGeometry(10, 35 - 20 * pos, 311, 16); // ui->lrcLabel_1->setStyleSheet(QString("color: rgba(0, 0, 0, %1)").arg(245 - 235 * curTimePos)); ui->lrcLabel_2->setGeometry(10, 55 - 20 * pos, 311, 16); ui->lrcLabel_3->setGeometry(10, 75 - 20 * pos, 311, 16); ui->lrcLabel_4->setGeometry(10, 95 - 20 * pos, 311, 16); ui->lrcLabel_5->setGeometry(10, 115 - 20 * pos, 311, 16); ui->lrcLabel_6->setGeometry(10, 135 - 20 * pos, 311, 16); ui->lrcLabel_7->setGeometry(10, 155 - 20 * pos, 311, 16); // ui->lrcLabel_7->setStyleSheet(QString("color: rgba(0, 0, 0, %1)").arg(235 * curTimePos + 10)); } void ShadowPlayer::showCoverPic(const QString &filePath) { QFileInfo fileinfo(filePath); QString path = fileinfo.path(); if (spID3::loadPictureData(filePath.toLocal8Bit().data())) { QByteArray picData((const char *)spID3::getPictureDataPtr(), spID3::getPictureLength()); ui->coverLabel->setPixmap(QPixmap::fromImage(QImage::fromData(picData))); spID3::freePictureData(); } else if (spFLAC::loadPictureData(filePath.toLocal8Bit().data())) { QByteArray picData((const char *)spFLAC::getPictureDataPtr(), spFLAC::getPictureLength()); ui->coverLabel->setPixmap(QPixmap::fromImage(QImage::fromData(picData))); spFLAC::freePictureData(); } else if (QFile::exists(path + "/cover.jpg")) ui->coverLabel->setPixmap(QPixmap(path + "/cover.jpg")); else if (QFile::exists(path + "/cover.jpeg")) ui->coverLabel->setPixmap(QPixmap(path + "/cover.jpeg")); else if (QFile::exists(path + "/cover.png")) ui->coverLabel->setPixmap(QPixmap(path + "/cover.png")); else if (QFile::exists(path + "/cover.gif")) ui->coverLabel->setPixmap(QPixmap(path + "/cover.gif")); else ui->coverLabel->setPixmap(QPixmap(":image/image/ShadowPlayer.png")); } void ShadowPlayer::on_openButton_clicked() { QStringList files = QFileDialog::getOpenFileNames( this, tr("Open"), 0, tr("Audio file (*.mp3 *.mp2 *.mp1 *.wav *.aiff *.ogg *.ape *.mp4 *.m4a *.m4v *.aac *.alac *.tta *.flac *.wma *.wv)")); int newIndex = playList->getLength(); for (const auto &f : files) { playList->add(f); } if (playList->getLength() > newIndex) { loadAudio(playList->playIndex(newIndex)); } } void ShadowPlayer::on_playButton_clicked() { if (!playing) { player->play(); if (player->isPlaying()) { playing = true; ui->playButton->setIcon(QIcon(":/rc/images/player/Pause.png")); ui->playButton->setToolTip(tr("Pause")); #if defined(Q_OS_WIN) && QT_VERSION < QT_VERSION_CHECK(6, 0, 0) taskbarProgress->show(); taskbarProgress->resume(); taskbarButton->setOverlayIcon(QIcon(":/rc/images/player/Play.png")); playToolButton->setIcon(QIcon(":/rc/images/player/Pause.png")); playToolButton->setToolTip(tr("Pause")); #endif } else { if (playList->getLength() > 0) loadAudio(playList->playIndex(playList->getIndex())); } } else { player->pause(); playing = false; ui->playButton->setIcon(QIcon(":/rc/images/player/Play.png")); ui->playButton->setToolTip(tr("Play")); #if defined(Q_OS_WIN) && QT_VERSION < QT_VERSION_CHECK(6, 0, 0) taskbarProgress->show(); taskbarProgress->pause(); taskbarButton->setOverlayIcon(QIcon(":/rc/images/player/Pause.png")); playToolButton->setIcon(QIcon(":/rc/images/player/Play.png")); playToolButton->setToolTip(tr("Play")); #endif } } void ShadowPlayer::on_stopButton_clicked() { player->stop(); playing = false; ui->playButton->setIcon(QIcon(":/rc/images/player/Play.png")); ui->playButton->setToolTip(tr("Play")); #if defined(Q_OS_WIN) && QT_VERSION < QT_VERSION_CHECK(6, 0, 0) taskbarProgress->hide(); taskbarButton->setOverlayIcon(QIcon(":/rc/images/player/Stop.png")); playToolButton->setIcon(QIcon(":/rc/images/player/Play.png")); playToolButton->setToolTip(tr("Play")); #endif } void ShadowPlayer::on_volSlider_valueChanged(int value) { player->setVol(value); isMute = false; ui->muteButton->setIcon(QIcon(":/rc/images/player/Vol.png")); } void ShadowPlayer::on_muteButton_clicked() { if (isMute == false) { lastVol = ui->volSlider->value(); ui->volSlider->setValue(0); ui->muteButton->setIcon(QIcon(":/rc/images/player/Mute.png")); isMute = true; } else { ui->volSlider->setValue(lastVol); ui->muteButton->setIcon(QIcon(":/rc/images/player/Vol.png")); isMute = false; } } float ShadowPlayer::arraySUM(int start, int end, float *array) { float sum = 0; for (int i = start; i <= end; i++) { sum += array[i]; } return sum; } void ShadowPlayer::updateFFT() { if (player->isPlaying()) { if (ui->leftLevel->value() > 6 || ui->rightLevel->value() > 6) player->getFFT(fftData); else memset(&fftData, 0, sizeof(fftData)); double start = 5; for (int i = 0; i < 29; i++) { double end = start * 1.23048; ui->FFTGroupBox->fftBarValue[i] = sqrt(arraySUM((int)start, (int)end, fftData)); start = end; } ui->FFTGroupBox->cutValue(); ui->FFTGroupBox->peakSlideDown(); ui->FFTGroupBox->update(); } else { ui->FFTGroupBox->peakSlideDown(); ui->FFTGroupBox->update(); } } void ShadowPlayer::on_playSlider_sliderPressed() { isPlaySliderPress = true; } void ShadowPlayer::on_playSlider_sliderReleased() { isPlaySliderPress = false; player->setPos(ui->playSlider->sliderPosition()); } void ShadowPlayer::on_resetFreqButton_clicked() { ui->freqSlider->setSliderPosition(0); player->setFreq(oriFreq); } void ShadowPlayer::applyEQ() { player->setEQ(0, ui->eqSlider_1->value()); player->setEQ(1, ui->eqSlider_2->value()); player->setEQ(2, ui->eqSlider_3->value()); player->setEQ(3, ui->eqSlider_4->value()); player->setEQ(4, ui->eqSlider_5->value()); player->setEQ(5, ui->eqSlider_6->value()); player->setEQ(6, ui->eqSlider_7->value()); player->setEQ(7, ui->eqSlider_8->value()); player->setEQ(8, ui->eqSlider_9->value()); player->setEQ(9, ui->eqSlider_10->value()); } void ShadowPlayer::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton && event->x() > 10) { pos = event->pos(); clickOnFrame = true; event->accept(); } else if (event->button() == Qt::LeftButton && event->x() <= 10) { clickOnLeft = true; } } void ShadowPlayer::mouseReleaseEvent(QMouseEvent *) { clickOnFrame = false; clickOnLeft = false; } void ShadowPlayer::mouseMoveEvent(QMouseEvent *event) { if (event->buttons() & Qt::LeftButton && clickOnFrame && event->x() > 10) { move(event->globalPos() - pos); event->accept(); } else if (event->buttons() & Qt::LeftButton && clickOnLeft && event->y() >= 0 && event->y() <= 400) { skinDrawPos = (double)event->y() / 400; skinPos = -1; update(); } } void ShadowPlayer::on_extraButton_clicked() { if (geometry().width() < 535) { sizeSlideAnimation->stop(); sizeSlideAnimation->setStartValue(QRect(geometry().x(), geometry().y(), 360, 402)); sizeSlideAnimation->setEndValue(QRect(geometry().x() - 175, geometry().y(), 710, 400)); sizeSlideAnimation->start(); ui->extraButton->setText("<-"); } else { sizeSlideAnimation->stop(); sizeSlideAnimation->setStartValue(QRect(geometry().x(), geometry().y(), 710, 402)); sizeSlideAnimation->setEndValue(QRect(geometry().x() + 175, geometry().y(), 360, 400)); sizeSlideAnimation->start(); ui->extraButton->setText("->"); } } void ShadowPlayer::on_closeButton_clicked() { fadeOutAnimation->start(); } void ShadowPlayer::closeEvent(QCloseEvent *event) { #if defined(Q_OS_MACOS) if (!event->spontaneous() || !isVisible()) { return; } #endif if (isVisible()) { hide(); event->ignore(); } } void ShadowPlayer::on_setSkinButton_clicked() { QString image = QFileDialog::getOpenFileName(this, tr("Choose skin"), 0, tr("Image file (*.bmp *.jpg *.jpeg *.png *.gif)")); if (!image.isEmpty()) { loadSkin(image); } } void ShadowPlayer::on_miniSizeButton_clicked() { showMinimized(); } void ShadowPlayer::on_playModeButton_clicked() { const QStringList icons = {":/rc/images/player/Single.png", ":/rc/images/player/Repeat.png", ":/rc/images/player/Order.png", ":/rc/images/player/AllRepeat.png", ":/rc/images/player/Shuffle.png"}; const QStringList tooltips = {tr("Track Play"), tr("Track Repeat"), tr("Playlist Order"), tr("Playlist Repeat"), tr("Shuffle")}; playMode = ++playMode % 5; Q_ASSERT(playMode >= 0 && playMode <= 4); ui->playModeButton->setIcon(QIcon(icons[playMode])); ui->playModeButton->setToolTip(tooltips[playMode]); QToolTip::showText(QCursor::pos(), ui->playModeButton->toolTip()); } void ShadowPlayer::on_showDskLrcButton_clicked() { if (lb->isVisible()) lb->hide(); else lb->show(); } void ShadowPlayer::on_loadLrcButton_clicked() { QString file = QFileDialog::getOpenFileName(this, tr("Load lyric"), 0, tr("Lyric file (*.lrc)")); if (QFile::exists(file)) lyrics->resolve(file, true); } void ShadowPlayer::on_playSlider_valueChanged(int value) { // avoiding setValue being triggered recursively if (qAbs(player->getPos() - value) > 2) { player->setPos(value); } } void ShadowPlayer::on_freqSlider_valueChanged(int value) { player->setFreq(oriFreq + (oriFreq * value * 0.0001)); ui->textLabel1->setText(tr("Playback speed (x%1)").arg(value * 0.0001 + 1)); } void ShadowPlayer::on_eqComboBox_currentIndexChanged(int index) { QVector<QVector<int>> presets = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {3, 1, 0, -2, -4, -4, -2, 0, 1, 2}, {-2, 0, 2, 4, -2, -2, 0, 0, 4, 4}, {-6, 1, 4, -2, -2, -4, 0, 0, 6, 6}, {0, 8, 8, 4, 0, 0, 0, 0, 2, 2}, {-6, 0, 0, 0, 0, 0, 4, 0, 4, 0}, {-2, 3, 4, 1, -2, -2, 0, 0, 4, 4}, {-2, 0, 0, 2, 2, 0, 0, 0, 4, 4}, {0, 0, 0, 4, 4, 4, 0, 2, 3, 4}, {-2, 0, 2, 1, 0, 0, 0, 0, -2, -4}, {-4, 0, 2, 1, 0, 0, 0, 0, -4, -6}, {0, 0, 0, 4, 5, 3, 6, 3, 0, 0}, {-4, 0, 2, 0, 0, 0, 0, 0, -4, -6}}; if (index >= 0 && index < presets.length()) { auto &preset = presets[index]; ui->eqSlider_1->setSliderPosition(preset[0]); ui->eqSlider_2->setSliderPosition(preset[1]); ui->eqSlider_3->setSliderPosition(preset[2]); ui->eqSlider_4->setSliderPosition(preset[3]); ui->eqSlider_5->setSliderPosition(preset[4]); ui->eqSlider_6->setSliderPosition(preset[5]); ui->eqSlider_7->setSliderPosition(preset[6]); ui->eqSlider_8->setSliderPosition(preset[7]); ui->eqSlider_9->setSliderPosition(preset[8]); ui->eqSlider_10->setSliderPosition(preset[9]); applyEQ(); } } void ShadowPlayer::addToListAndPlay(const QList<QUrl> &files) { int newIndex = playList->getLength(); int length = files.length(); if (!files.isEmpty()) { for (int i = 0; i < length; i++) { playList->add(files[i].toLocalFile()); } if (playList->getLength() > newIndex) loadAudio(playList->playIndex(newIndex)); } } void ShadowPlayer::addToListAndPlay(const QStringList &files) { int newIndex = playList->getLength(); int length = files.length(); if (length > 0) { for (int i = 0; i < length; i++) { playList->add(files[i]); } if (playList->getLength() > newIndex) loadAudio(playList->playIndex(newIndex)); } } void ShadowPlayer::addToListAndPlay(const QString &file) { int newIndex = playList->getLength(); playList->add(file); if (playList->getLength() > newIndex) loadAudio(playList->playIndex(newIndex)); } void ShadowPlayer::showPlayer() { show(); fadeInAnimation->start(); } void ShadowPlayer::on_playPreButton_clicked() { if (playMode == 3) { loadAudio(playList->previous(true)); } else if (playMode == 4) { if (!playList->isEmpty()) { int index = QRandomGenerator::global()->bounded(playList->getLength()); loadAudio(playList->playIndex(index)); } } else { loadAudio(playList->previous(false)); } } void ShadowPlayer::on_playNextButton_clicked() { if (playMode == 3) { loadAudio(playList->next(true)); } else if (playMode == 4) { if (!playList->isEmpty()) { int index = QRandomGenerator::global()->bounded(playList->getLength()); loadAudio(playList->playIndex(index)); } } else { loadAudio(playList->next(false)); } } void ShadowPlayer::on_playListButton_clicked() { if (width() < 370) on_extraButton_clicked(); if (playListHideAnimation->state() != QAbstractAnimation::Running && playListShowAnimation->state() != QAbstractAnimation::Running) { if (ui->playerListArea->height() < 190) { eqHideAnimation->stop(); lyricsHideAnimation->stop(); playListShowAnimation->stop(); eqHideAnimation->start(); lyricsHideAnimation->start(); playListShowAnimation->start(); } else { if (width() > 370) { eqShowAnimation->stop(); lyricsShowAnimation->stop(); playListHideAnimation->stop(); eqShowAnimation->start(); lyricsShowAnimation->start(); playListHideAnimation->start(); } } } } void ShadowPlayer::callFromPlayList() { loadAudio(playList->getCurFile()); } void ShadowPlayer::on_reverseButton_clicked() { if (isReverse) { isReverse = false; ui->reverseButton->setText(tr("Play")); player->setReverse(false); } else { isReverse = true; ui->reverseButton->setText(tr("Reverse Play")); player->setReverse(true); } } void ShadowPlayer::on_reverbDial_valueChanged(int value) { player->updateReverb(value); } void ShadowPlayer::physicsSetting() { double temp = 0; bool ok = false; temp = QInputDialog::getDouble(this, tr("Acceleration"), tr("Gravitational acceleration \n [parameters are ratios, 1 = total length of spectrum bar"), ui->FFTGroupBox->acc, 0, 2147483647, 3, &ok); if (ok) { ui->FFTGroupBox->acc = temp; } temp = QInputDialog::getDouble( this, tr("Maximum drop speed"), tr("The maximum velocity of the object falling"), ui->FFTGroupBox->maxSpeed, 0, 2147483647, 3, &ok); if (ok) { ui->FFTGroupBox->maxSpeed = temp; } temp = QInputDialog::getDouble(this, tr("Base speed"), tr("Overall speed, force multiplier \n This value affects the elasticity, throwing force \n The initial version " "was used for falling speed, when there was no physical effect \n [modified with caution]"), ui->FFTGroupBox->speed, 0, 2147483647, 3, &ok); if (ok) { ui->FFTGroupBox->speed = temp; } temp = QInputDialog::getDouble(this, tr("Throwing force multiplication factor"), tr("The coefficient of multiplication of the intensity of the throwing force of the spectrum bar on the object \n " "the throwing force will be doubled by this multiplier"), ui->FFTGroupBox->forceD, 0, 2147483647, 3, &ok); if (ok) { ui->FFTGroupBox->forceD = temp; } temp = QInputDialog::getDouble( this, tr("Elasticity factor"), tr("The amount of kinetic energy retained after landing \n the object falls to the ground, part of the kinetic energy into sound and heat \n " "this parameter determines the percentage of kinetic energy remaining after the collision \n [Note: due to algorithm bugs, each fall will " "lose the potential energy of the last frame height from the ground, so kinetic energy has been lost] \n because it did not do air " "resistance, so it should make kinetic energy loss more \n1 = complete rebound"), ui->FFTGroupBox->elasticCoefficient, 0, 2147483647, 3, &ok); if (ok) { ui->FFTGroupBox->elasticCoefficient = temp; } temp = QInputDialog::getDouble(this, tr("Elasticity Threshold"), tr("When the percentage of objects falling in one frame (considered to be penetrable) is less than this value \n " "does not calculate the elasticity"), ui->FFTGroupBox->minElasticStep, 0, 2147483647, 3, &ok); if (ok) { ui->FFTGroupBox->minElasticStep = temp; } } void ShadowPlayer::enableFFTPhysics() { ui->FFTGroupBox->acc = 0.35; ui->FFTGroupBox->maxSpeed = 9; ui->FFTGroupBox->speed = 0.025; ui->FFTGroupBox->forceD = 6; ui->FFTGroupBox->elasticCoefficient = 0.6; ui->FFTGroupBox->minElasticStep = 0.02; } void ShadowPlayer::disableFFTPhysics() { ui->FFTGroupBox->acc = 0.15; ui->FFTGroupBox->maxSpeed = 2; ui->FFTGroupBox->speed = 0.025; ui->FFTGroupBox->forceD = 0; ui->FFTGroupBox->elasticCoefficient = 0; ui->FFTGroupBox->minElasticStep = 0.02; } void ShadowPlayer::resizeEvent(QResizeEvent *) { ui->extraButton->setGeometry(width() - 20, 0, 20, 20); ui->closeButton->setGeometry(width() - 65, 0, 40, 20); ui->miniSizeButton->setGeometry(width() - 90, 0, 25, 20); ui->setSkinButton->setGeometry(width() - 115, 0, 25, 20); } void ShadowPlayer::showDeveloperInfo() { QMessageBox::about(this, tr("Hannah"), tr("Simple Music Player")); } void ShadowPlayer::saveConfig() { auto dirPath = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation); QDir dir(dirPath); if (!dir.exists()) { dir.mkdir(dirPath); } QFile file(dirPath + "/config.dat"); if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { QDataStream stream(&file); stream << (quint32)0x61727480 << ui->freqSlider->value() << ui->volSlider->value() << isMute << ui->reverbDial->value() << playMode << skinMode << skinPos << skinDrawPos << ui->eqComboBox->currentIndex() << ui->eqEnableCheckBox->isChecked() << ui->eqSlider_1->value() << ui->eqSlider_2->value() << ui->eqSlider_3->value() << ui->eqSlider_4->value() << ui->eqSlider_5->value() << ui->eqSlider_6->value() << ui->eqSlider_7->value() << ui->eqSlider_8->value() << ui->eqSlider_9->value() << ui->eqSlider_10->value() << lb->isVisible(); file.close(); } } void ShadowPlayer::loadConfig() { auto dirPath = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation); QFile file(dirPath + "/config.dat"); if (file.open(QIODevice::ReadOnly)) { QDataStream stream(&file); quint32 magic; stream >> magic; if (magic == 0x61727480) { int dataInt = 0; stream >> dataInt; ui->freqSlider->setValue(dataInt); stream >> dataInt; ui->volSlider->setValue(dataInt); bool dataBool = false; stream >> dataBool; isMute = dataBool; if (isMute) { ui->muteButton->setIcon(QIcon(":/rc/images/player/Mute.png")); } else { ui->muteButton->setIcon(QIcon(":/rc/images/player/Vol.png")); } stream >> dataInt; ui->reverbDial->setValue(dataInt); stream >> playMode; playMode %= 5; const QStringList icons = {":/rc/images/player/Single.png", ":/rc/images/player/Repeat.png", ":/rc/images/player/Order.png", ":/rc/images/player/AllRepeat.png", ":/rc/images/player/Shuffle.png"}; const QStringList tooltips = {tr("Track Play"), tr("Track Repeat"), tr("Playlist Order"), tr("Playlist Repeat"), tr("Shuffle")}; Q_ASSERT(playMode >= 0 && playMode <= 4); ui->playModeButton->setIcon(QIcon(icons[playMode])); ui->playModeButton->setToolTip(tooltips[playMode]); stream >> skinMode; stream >> skinPos; stream >> skinDrawPos; stream >> dataInt; ui->eqComboBox->setCurrentIndex(dataInt); stream >> dataBool; ui->eqEnableCheckBox->setChecked(dataBool); stream >> dataInt; ui->eqSlider_1->setValue(dataInt); stream >> dataInt; ui->eqSlider_2->setValue(dataInt); stream >> dataInt; ui->eqSlider_3->setValue(dataInt); stream >> dataInt; ui->eqSlider_4->setValue(dataInt); stream >> dataInt; ui->eqSlider_5->setValue(dataInt); stream >> dataInt; ui->eqSlider_6->setValue(dataInt); stream >> dataInt; ui->eqSlider_7->setValue(dataInt); stream >> dataInt; ui->eqSlider_8->setValue(dataInt); stream >> dataInt; ui->eqSlider_9->setValue(dataInt); stream >> dataInt; ui->eqSlider_10->setValue(dataInt); stream >> dataBool; lb->setVisible(dataBool); } file.close(); } } void ShadowPlayer::saveSkinData() { auto dirPath = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation); QDir dir(dirPath); if (!dir.exists()) { dir.mkdir(dirPath); } QFile file(dirPath + "/skin.dat"); if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { QDataStream stream(&file); stream << (quint32)0x61727481 << skin; file.close(); } } void ShadowPlayer::loadSkinData() { auto dirPath = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation); QFile file(dirPath + "/skin.dat"); if (file.open(QIODevice::ReadOnly)) { QDataStream stream(&file); quint32 magic; stream >> magic; if (magic == 0x61727481) { stream >> skin; skinLeft = skin.scaledToWidth(360, Qt::SmoothTransformation); skinFull = skin.scaledToWidth(710, Qt::SmoothTransformation); aspectRatio = (double)skin.height() / skin.width(); } file.close(); } } #if defined(Q_OS_WIN) && QT_VERSION < QT_VERSION_CHECK(6, 0, 0) bool ShadowPlayer::nativeEvent(const QByteArray &eventType, void *message, long * /*result*/) { Q_UNUSED(eventType); MSG *msg = reinterpret_cast<MSG *>(message); if (msg->message == WM_COPYDATA) { COPYDATASTRUCT *p = reinterpret_cast<COPYDATASTRUCT *>(msg->lParam); addToListAndPlay(QString::fromUtf8((LPCSTR)(p->lpData))); return true; } return false; } void ShadowPlayer::setTaskbarButtonWindow() { taskbarButton->setWindow(windowHandle()); thumbnailToolBar->setWindow(windowHandle()); } #endif void ShadowPlayer::on_eqEnableCheckBox_clicked(bool checked) { if (checked) { player->eqReady(); applyEQ(); } else { player->disableEQ(); } }
45,687
C++
.cpp
1,271
28.203777
150
0.598826
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,575
bassplayer.cpp
missdeer_hannah/desktop/player/bassplayer.cpp
#include <QCoreApplication> #include <QDir> #include <QFileInfo> #include <QMap> #include <QMessageBox> #include <QUrl> #include <QtCore> #include "bassplayer.h" #include "bass_fx.h" #include "tags.h" #if defined(Q_OS_WIN) # include "bassasio.h" # include "bassmix.h" # include "basswasapi.h" #endif BassPlayer::BassPlayer() { QString bassPluginsPath = QCoreApplication::applicationDirPath() + #if defined(Q_OS_MAC) "/../Plugins"; #else "/bassplugins"; #endif QDir dir(bassPluginsPath); auto plugins = dir.entryList(QStringList() << #if defined(Q_OS_WIN) "*.dll" #elif defined(Q_OS_MAC) "*.dylib" #else "*.so" #endif ); for (auto &p : plugins) { QString plugin = QDir::toNativeSeparators(bassPluginsPath + "/" + p); BASS_PluginLoad(plugin.toStdString().c_str(), 0); } } BassPlayer::~BassPlayer() { #if defined(Q_OS_WIN) if (m_asioInitialized) BASS_ASIO_Free(); if (m_wasapiInitialized) BASS_WASAPI_Free(); #endif BASS_Free(); } QString BassPlayer::openAudio(const QString &uri) { BASS_ChannelStop(m_hNowPlay); BASS_StreamFree(m_hNowPlay); if (QFile::exists(uri)) { QString ext = QFileInfo(uri).suffix().toLower(); static const QVector<QString> audioExts = { "mp3", "mp2", "mp1", "ogg", "wav", "aiff", "ape", "m4a", "aac", "tta", "wma", "mp4", "m4v", "alac", "flac", "wv", }; if (!audioExts.contains(ext)) { return "err"; } m_hNowPlay = BASS_StreamCreateFile(false, #if defined(Q_OS_WIN) (const wchar_t *)uri.utf16(), #else uri.toStdString().c_str(), #endif 0, 0, BASS_UNICODE | BASS_SAMPLE_FLOAT | BASS_SAMPLE_FX | BASS_STREAM_DECODE | BASS_STREAM_PRESCAN); } else if (uri.startsWith("https://", Qt::CaseInsensitive) || uri.startsWith("http://", Qt::CaseInsensitive)) { m_hNowPlay = BASS_StreamCreateURL( #if defined(Q_OS_WIN) (const wchar_t *)uri.utf16(), #else uri.toStdString().c_str(), #endif BASS_UNICODE | BASS_SAMPLE_FLOAT | BASS_SAMPLE_FX | BASS_STREAM_DECODE | BASS_STREAM_PRESCAN, 0, nullptr, 0); } if (BASS_ErrorGetCode() != 0) { return "err"; } if (m_hNowPlay) { m_hNowPlay = BASS_FX_ReverseCreate(m_hNowPlay, 2, BASS_FX_FREESOURCE | BASS_SAMPLE_FLOAT /*|BASS_SAMPLE_FX*/); BASS_ChannelSetAttribute(m_hNowPlay, BASS_ATTRIB_REVERSE_DIR, BASS_FX_RVS_FORWARD); } m_hReverbFX = BASS_ChannelSetFX(m_hNowPlay, BASS_FX_DX8_REVERB, 1); return "ok"; } void BassPlayer::eqReady() { BASS_BFX_PEAKEQ peakEQ; m_hEqFX = BASS_ChannelSetFX(m_hNowPlay, BASS_FX_BFX_PEAKEQ, 2); peakEQ.fGain = 0; peakEQ.fQ = 0; peakEQ.fBandwidth = 2.5f; peakEQ.lChannel = BASS_BFX_CHANALL; peakEQ.lBand = 0; peakEQ.fCenter = 31; BASS_FXSetParameters(m_hEqFX, &peakEQ); peakEQ.lBand = 1; peakEQ.fCenter = 62; BASS_FXSetParameters(m_hEqFX, &peakEQ); peakEQ.lBand = 2; peakEQ.fCenter = 125; BASS_FXSetParameters(m_hEqFX, &peakEQ); peakEQ.lBand = 3; peakEQ.fCenter = 250; BASS_FXSetParameters(m_hEqFX, &peakEQ); peakEQ.lBand = 4; peakEQ.fCenter = 500; BASS_FXSetParameters(m_hEqFX, &peakEQ); peakEQ.lBand = 5; peakEQ.fCenter = 1000; BASS_FXSetParameters(m_hEqFX, &peakEQ); peakEQ.lBand = 6; peakEQ.fCenter = 2000; BASS_FXSetParameters(m_hEqFX, &peakEQ); peakEQ.lBand = 7; peakEQ.fCenter = 4000; BASS_FXSetParameters(m_hEqFX, &peakEQ); peakEQ.lBand = 8; peakEQ.fCenter = 8000; BASS_FXSetParameters(m_hEqFX, &peakEQ); peakEQ.lBand = 9; peakEQ.fCenter = 16000; BASS_FXSetParameters(m_hEqFX, &peakEQ); } void BassPlayer::disableEQ() { BASS_ChannelRemoveFX(m_hNowPlay, m_hEqFX); } void BassPlayer::setEQ(int id, int gain) { BASS_BFX_PEAKEQ peakEQ; peakEQ.lBand = id; BASS_FXGetParameters(m_hEqFX, &peakEQ); peakEQ.fGain = gain; BASS_FXSetParameters(m_hEqFX, &peakEQ); } void BassPlayer::setVol(int vol) { float v = (float)vol / 100; BASS_ChannelSetAttribute(m_hNowPlay, BASS_ATTRIB_VOL, v); } int BassPlayer::getVol() { float vol; BASS_ChannelGetAttribute(m_hNowPlay, BASS_ATTRIB_VOL, &vol); return (int)(vol * 100); } bool BassPlayer::isPlaying() { return (BASS_ChannelIsActive(m_hNowPlay) == BASS_ACTIVE_PLAYING); } void BassPlayer::getFFT(float *array) { if (BASS_ChannelIsActive(m_hNowPlay) == BASS_ACTIVE_PLAYING) BASS_ChannelGetData(m_hNowPlay, array, BASS_DATA_FFT4096); } void BassPlayer::play() { BASS_ChannelPlay(m_hNowPlay, false); } void BassPlayer::stop() { BASS_ChannelStop(m_hNowPlay); BASS_ChannelSetPosition(m_hNowPlay, 0, BASS_POS_BYTE); } void BassPlayer::pause() { BASS_ChannelPause(m_hNowPlay); } bool BassPlayer::devInit() { return BASS_Init(-1, 48000, 0, 0, NULL); } QString BassPlayer::getTags() { QString tags = TAGS_Read(m_hNowPlay, "%IFV2(%ARTI,%UTF8(%ARTI) - ,)%IFV2(%TITL,%UTF8(%TITL),)"); if (tags.trimmed().isEmpty()) return "Show_File_Name"; return tags; } int BassPlayer::getPos() { return (int)(BASS_ChannelGetPosition(m_hNowPlay, BASS_POS_BYTE) * 1000 / BASS_ChannelGetLength(m_hNowPlay, BASS_POS_BYTE)); } void BassPlayer::setPos(int pos) { BASS_ChannelSetPosition(m_hNowPlay, pos * BASS_ChannelGetLength(m_hNowPlay, BASS_POS_BYTE) / 1000, BASS_POS_BYTE); } int BassPlayer::getBitRate() { float time = BASS_ChannelBytes2Seconds(m_hNowPlay, BASS_ChannelGetLength(m_hNowPlay, BASS_POS_BYTE)); DWORD len = BASS_StreamGetFilePosition(m_hNowPlay, BASS_FILEPOS_END); int bitrate = (int)(len / (125 * time) + 0.5); return bitrate; } int BassPlayer::getFreq() { BASS_CHANNELINFO cInfo; BASS_ChannelGetInfo(m_hNowPlay, &cInfo); return cInfo.freq; } void BassPlayer::setFreq(float freq) { BASS_ChannelSetAttribute(m_hNowPlay, BASS_ATTRIB_FREQ, freq); } QString BassPlayer::getNowPlayInfo() { QString fmt; BASS_CHANNELINFO cInfo; BASS_CHANNELINFO *info = &cInfo; BASS_ChannelGetInfo(m_hNowPlay, info); QMap<DWORD, QString> types = { {BASS_CTYPE_STREAM_AIFF, " AIFF"}, {BASS_CTYPE_STREAM_MP3, " MP3"}, {BASS_CTYPE_STREAM_MP2, " MP2"}, {BASS_CTYPE_STREAM_MP1, " MP1"}, {BASS_CTYPE_STREAM_OGG, " OGG"}, {BASS_CTYPE_STREAM_WAV_PCM, " Wave PCM"}, {BASS_CTYPE_STREAM_WAV_FLOAT, " Wave Float Point"}, // {BASS_CTYPE_STREAM_APE, " APE"}, // {BASS_CTYPE_STREAM_MP4, " MP4"}, // {BASS_CTYPE_STREAM_AAC, " AAC"}, // {BASS_CTYPE_STREAM_ALAC, " ALAC"}, // {BASS_CTYPE_STREAM_TTA, " TTA"}, // {BASS_CTYPE_STREAM_FLAC, " FLAC"}, // {BASS_CTYPE_STREAM_WMA, " WMA"}, // {BASS_CTYPE_STREAM_WMA_MP3, " WMA"}, // {BASS_CTYPE_STREAM_WV, " WV"}, }; fmt = types.value(info->ctype, ""); return QString("%1Hz %2Kbps %3%4").arg(info->freq).arg(getBitRate()).arg((info->chans == 1) ? QObject::tr("mono") : QObject::tr("stereo"), fmt); } QString BassPlayer::getCurTime() { int totalSec = (int)BASS_ChannelBytes2Seconds(m_hNowPlay, BASS_ChannelGetPosition(m_hNowPlay, BASS_POS_BYTE)); int minute = totalSec / 60; int second = totalSec % 60; if (second != -1) { return QString("%1:%2").arg(minute).arg(second, 2, 10, QChar('0')); } return "0:00"; } QString BassPlayer::getTotalTime() { int totalSec = (int)BASS_ChannelBytes2Seconds(m_hNowPlay, BASS_ChannelGetLength(m_hNowPlay, BASS_POS_BYTE)); int minute = totalSec / 60; int second = totalSec % 60; if (second != -1) { return QString("%1:%2").arg(minute).arg(second, 2, 10, QChar('0')); } return "0:00"; } int BassPlayer::getCurTimeMS() const { return (int)(BASS_ChannelBytes2Seconds(m_hNowPlay, BASS_ChannelGetPosition(m_hNowPlay, BASS_POS_BYTE)) * 1000); } int BassPlayer::getTotalTimeMS() const { return (int)(BASS_ChannelBytes2Seconds(m_hNowPlay, BASS_ChannelGetLength(m_hNowPlay, BASS_POS_BYTE)) * 1000); } double BassPlayer::getCurTimeSec() const { return BASS_ChannelBytes2Seconds(m_hNowPlay, BASS_ChannelGetPosition(m_hNowPlay, BASS_POS_BYTE)); } double BassPlayer::getTotalTimeSec() const { return BASS_ChannelBytes2Seconds(m_hNowPlay, BASS_ChannelGetLength(m_hNowPlay, BASS_POS_BYTE)); } DWORD BassPlayer::getLevel() const { DWORD level = BASS_ChannelGetLevel(m_hNowPlay); if (level != (DWORD)-1) { return level; } return 0; } QString BassPlayer::getFileTotalTime(const QString &fileName) { HSTREAM fileStream = BASS_StreamCreateFile(false, (const wchar_t *)fileName.utf16(), 0, 0, BASS_UNICODE); int totalSec = (int)BASS_ChannelBytes2Seconds(fileStream, BASS_ChannelGetLength(fileStream, BASS_POS_BYTE)); BASS_StreamFree(fileStream); const int secondsInAMinute = 60; int minute = totalSec / secondsInAMinute; int second = totalSec % secondsInAMinute; if (second != -1) { return QString("%1:%2").arg(minute).arg(second, 2, 10, QChar('0')); } return "0:00"; } double BassPlayer::getFileSecond(const QString &fileName) { HSTREAM fileStream = BASS_StreamCreateFile(false, (const wchar_t *)fileName.utf16(), 0, 0, BASS_UNICODE); double totalSec = BASS_ChannelBytes2Seconds(fileStream, BASS_ChannelGetLength(fileStream, BASS_POS_BYTE)); BASS_StreamFree(fileStream); return totalSec; } void BassPlayer::setReverse(bool isEnable) const { BASS_ChannelSetAttribute(m_hNowPlay, BASS_ATTRIB_REVERSE_DIR, isEnable ? BASS_FX_RVS_REVERSE : BASS_FX_RVS_FORWARD); } void BassPlayer::updateReverb(int value) const { BASS_DX8_REVERB p; BASS_FXGetParameters(m_hReverbFX, &p); p.fReverbMix = 0.012f * (value * value * value); BASS_FXSetParameters(m_hReverbFX, &p); } BassDriver BassPlayer::getDriver() const { return m_driver; } void BassPlayer::setDriver(BassDriver &driver) { m_driver = driver; } #if defined(Q_OS_WIN) bool BassPlayer::asioInit() { if (!BASS_ASIO_Init(-1, 0)) { return false; } // initialize BASS "no sound" device BASS_Init(0, 48000, 0, 0, NULL); // create a dummy stream for reserving ASIO channels auto dummy = BASS_StreamCreate(2, 48000, BASS_SAMPLE_FLOAT | BASS_STREAM_DECODE, STREAMPROC_DUMMY, NULL); // prepare ASIO output channel pairs (up to 4) int a; BASS_ASIO_INFO i; BASS_ASIO_GetInfo(&i); for (a = 0; a < 4; a++) { BASS_ASIO_CHANNELINFO i, i2; if (BASS_ASIO_ChannelGetInfo(FALSE, a * 2, &i) && BASS_ASIO_ChannelGetInfo(FALSE, a * 2 + 1, &i2)) { char name[200]; sprintf_s(name, "%s + %s", i.name, i2.name); // MESS(30 + a, WM_SETTEXT, 0, name); // display channel names BASS_ASIO_ChannelEnableBASS(FALSE, 0, dummy, TRUE); // enable ASIO channels using the dummy stream BASS_ASIO_ChannelPause(FALSE, a * 2); // not playing anything immediately, so pause the channel } } // start the device using default buffer/latency and 2 threads for parallel processing if (!BASS_ASIO_Start(0, 2)) { return false; } m_asioInitialized = true; return true; } DWORD BassPlayer::WasapiProc(void *buffer, DWORD length, void *user) { BassPlayer *pThis = (BassPlayer *)user; DWORD c = BASS_ChannelGetData(pThis->m_mixer, buffer, length); if (c == -1) c = 0; // an error, no data return c; } bool BassPlayer::wasapiInit() { // not playing anything via BASS, so don't need an update thread BASS_SetConfig(BASS_CONFIG_UPDATEPERIOD, 0); // setup BASS - "no sound" device BASS_Init(0, 48000, 0, 0, NULL); // initialize the default WASAPI device (400ms buffer, 50ms update period, auto-select format) if (!BASS_WASAPI_Init(-1, 0, 0, BASS_WASAPI_AUTOFORMAT | BASS_WASAPI_EXCLUSIVE, 0.4, 0.05, &BassPlayer::WasapiProc, (void *)this)) { // exclusive mode failed, try shared mode if (!BASS_WASAPI_Init(-1, 0, 0, BASS_WASAPI_AUTOFORMAT, 0.4, 0.05, &BassPlayer::WasapiProc, (void *)this)) { return false; } } BASS_WASAPI_INFO wi; BASS_WASAPI_GetInfo(&wi); // create a mixer with same format as the output m_mixer = BASS_Mixer_StreamCreate(wi.freq, wi.chans, BASS_SAMPLE_FLOAT | BASS_STREAM_DECODE); // start the output BASS_WASAPI_Start(); m_wasapiInitialized = true; return true; } #endif
13,335
C++
.cpp
415
26.53494
148
0.62397
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,576
osd.cpp
missdeer_hannah/desktop/player/osd.cpp
#include <QGuiApplication> #include <QMouseEvent> #include <QPaintEvent> #include <QPainter> #include <QPropertyAnimation> #include <QScreen> #include <QTimer> #include "osd.h" #include "ui_osd.h" OSD::OSD(QWidget *parent) : QWidget(parent), ui(new Ui::OSD) { ui->setupUi(this); timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(timeRoll())); backGround = QPixmap(":/rc/images/OSD.png"); setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Tool); setAttribute(Qt::WA_TranslucentBackground); setGeometry(QGuiApplication::primaryScreen()->availableGeometry().width() - width(), 80, width(), height()); setFixedSize(width(), height()); hideAnimation = new QPropertyAnimation(this, "windowOpacity"); hideAnimation->setDuration(600); hideAnimation->setStartValue(1); hideAnimation->setEndValue(0); connect(hideAnimation, SIGNAL(finished()), this, SLOT(hide())); titleAnimation = new QPropertyAnimation(ui->titleLabel, "geometry"); titleAnimation->setEasingCurve(QEasingCurve::OutCirc); titleAnimation->setDuration(1200); titleAnimation->setStartValue(QRect(30, 30, 0, 61)); titleAnimation->setEndValue(QRect(40, 30, 281, 61)); timeAnimation = new QPropertyAnimation(ui->timeLabel, "geometry"); timeAnimation->setEasingCurve(QEasingCurve::OutCirc); timeAnimation->setDuration(1200); timeAnimation->setStartValue(QRect(331, 80, 0, 41)); timeAnimation->setEndValue(QRect(40, 80, 281, 41)); } OSD::~OSD() { delete ui; delete timer; delete hideAnimation; delete titleAnimation; delete timeAnimation; } void OSD::paintEvent(QPaintEvent *) { QPainter painter(this); painter.drawPixmap(0, 0, backGround); } void OSD::timeRoll() { timeleft--; if (timeleft <= 0) { hideAnimation->start(); // setVisible(false); timer->stop(); } } void OSD::showOSD(QString tags, QString totalTime) { timeleft = 4; hideAnimation->stop(); titleAnimation->stop(); titleAnimation->start(); timeAnimation->stop(); timeAnimation->start(); setWindowOpacity(1); QFontMetrics titleFontMetrics(ui->titleLabel->font()); if (titleFontMetrics.boundingRect(tags).width() > 281) { ui->titleLabel->setAlignment(Qt::AlignTop | Qt::AlignLeft); ui->titleLabel->setWordWrap(true); } else { ui->titleLabel->setAlignment(Qt::AlignCenter); ui->titleLabel->setWordWrap(false); } ui->titleLabel->setText(tags); ui->timeLabel->setText(totalTime); timer->start(1000); show(); update(); } void OSD::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { timer->stop(); hide(); } }
2,796
C++
.cpp
92
26.021739
112
0.688848
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,577
kugou.cpp
missdeer_hannah/desktop/ProviderAPI/kugou.cpp
#include "kugou.h" namespace ProviderAPI { namespace kugou { boost::beast::http::response<boost::beast::http::string_body> playlist(std::string &reqBody, UrlQuery &urlQuery, UrlParam &params) { return {}; } boost::beast::http::response<boost::beast::http::string_body> songinfo(std::string &reqBody, UrlQuery &urlQuery, UrlParam &params) { return {}; } } // namespace kugou } // namespace ProviderAPI
482
C++
.cpp
13
29.846154
138
0.626068
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,578
netease.cpp
missdeer_hannah/desktop/ProviderAPI/netease.cpp
#include "netease.h" namespace ProviderAPI { namespace netease { boost::beast::http::response<boost::beast::http::string_body> playlist(std::string &reqBody, UrlQuery &urlQuery, UrlParam &params) { return {}; } boost::beast::http::response<boost::beast::http::string_body> songinfo(std::string &reqBody, UrlQuery &urlQuery, UrlParam &params) { return {}; } } // namespace netease } // namespace ProviderAPI
488
C++
.cpp
13
30.307692
138
0.630802
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,579
migu.cpp
missdeer_hannah/desktop/ProviderAPI/migu.cpp
#include "migu.h" namespace ProviderAPI { namespace migu { boost::beast::http::response<boost::beast::http::string_body> playlist(std::string &reqBody, UrlQuery &urlQuery, UrlParam &params) { return {}; } boost::beast::http::response<boost::beast::http::string_body> songinfo(std::string &reqBody, UrlQuery &urlQuery, UrlParam &params) { return {}; } } // namespace migu } // namespace ProviderAPI
479
C++
.cpp
13
29.615385
138
0.623656
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,580
qq.cpp
missdeer_hannah/desktop/ProviderAPI/qq.cpp
#include "qq.h" namespace ProviderAPI { namespace qq { boost::beast::http::response<boost::beast::http::string_body> playlist(std::string &reqBody, UrlQuery &urlQuery, UrlParam &params) { return {}; } boost::beast::http::response<boost::beast::http::string_body> songinfo(std::string &reqBody, UrlQuery &urlQuery, UrlParam &params) { return {}; } } // namespace qq } // namespace ProviderAPI
473
C++
.cpp
13
29.153846
138
0.618736
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,581
kuwo.cpp
missdeer_hannah/desktop/ProviderAPI/kuwo.cpp
#include "kuwo.h" namespace ProviderAPI { namespace kuwo { boost::beast::http::response<boost::beast::http::string_body> playlist(std::string &reqBody, UrlQuery &urlQuery, UrlParam &params) { return {}; } boost::beast::http::response<boost::beast::http::string_body> songinfo(std::string &reqBody, UrlQuery &urlQuery, UrlParam &params) { return {}; } } // namespace kuwo } // namespace ProviderAPI
479
C++
.cpp
13
29.615385
138
0.623656
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,582
BeastHttpResponseHandler.cpp
missdeer_hannah/desktop/BeastServer/BeastHttpResponseHandler.cpp
#include <boost/beast/version.hpp> #include "BeastHttpResponseHandler.h" namespace BeastHttpServer { http::response<http::string_body> ok(const std::string &resp_body, const std::string &content_type /*= "application/json; charset=UTF-8"*/) { auto const size = resp_body.size(); http::response<http::string_body> res {http::status::ok, 11}; res.set(http::field::server, BOOST_BEAST_VERSION_STRING); res.set(http::field::content_type, content_type); res.keep_alive(false); res.body() = resp_body; res.content_length(size); res.prepare_payload(); return res; } http::response<http::string_body> htmlOk(const std::string &resp_body) { return ok(resp_body, "text/html; charset=UTF-8"); } http::response<http::string_body> jsonOk(const std::string &resp_body) { return ok(resp_body, "application/json; charset=UTF-8"); } } // namespace BeastHttpServer
978
C++
.cpp
25
32.88
143
0.655391
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,583
BeastWebsocketSessionManager.cpp
missdeer_hannah/desktop/BeastServer/BeastWebsocketSessionManager.cpp
#include <functional> #include "BeastWebsocketSessionManager.h" BeastWebsocketSessionManager BeastWebsocketSessionManager::m_instance; BeastWebsocketSessionManager::BeastWebsocketSessionManager() { m_webMsgHandler = std::bind(&BeastWebsocketSessionManager::dummyWebMsgHandler, this, std::placeholders::_1); } void BeastWebsocketSessionManager::dummyWebMsgHandler(const std::string &msg) {} void BeastWebsocketSessionManager::add(BeastWebsocketSessionPtr session) { std::lock_guard<std::mutex> lock(m_beastWebsocketSessionsMutex); m_beastWebsocketSessions.insert(session); } void BeastWebsocketSessionManager::remove(BeastWebsocketSessionPtr session) { std::lock_guard<std::mutex> lock(m_beastWebsocketSessionsMutex); m_beastWebsocketSessions.erase(session); } void BeastWebsocketSessionManager::clear() { std::lock_guard<std::mutex> lock(m_beastWebsocketSessionsMutex); m_beastWebsocketSessions.clear(); } BeastWebsocketSessions::iterator BeastWebsocketSessionManager::begin() { return m_beastWebsocketSessions.begin(); } BeastWebsocketSessions::iterator BeastWebsocketSessionManager::end() { return m_beastWebsocketSessions.end(); } void BeastWebsocketSessionManager::lock() { m_beastWebsocketSessionsMutex.lock(); } void BeastWebsocketSessionManager::unlock() { m_beastWebsocketSessionsMutex.unlock(); } void BeastWebsocketSessionManager::registerWebMsgHandler(std::function<void(const std::string &msg)> handler) { m_webMsgHandler = handler; } void BeastWebsocketSessionManager::onWebMsg(const std::string &msg) { m_webMsgHandler(msg); } void BeastWebsocketSessionManager::send(std::string message) { // Put the message in a shared pointer so we can re-use it for each client const auto ss = std::make_shared<const std::string>(std::move(message)); // Make a local list of all the weak pointers representing // the sessions, so we can do the actual sending without // holding the mutex: std::vector<std::weak_ptr<BeastWebsocketSession>> v; { std::lock_guard<std::mutex> lock(m_beastWebsocketSessionsMutex); v.reserve(m_beastWebsocketSessions.size()); for (auto p : m_beastWebsocketSessions) { v.emplace_back(p->weak_from_this()); } } // For each session in our local list, try to acquire a strong // pointer. If successful, then send the message on that session. for (auto const &wp : v) { if (auto sp = wp.lock()) { sp->send(ss); } } }
2,550
C++
.cpp
73
31.054795
112
0.753965
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,584
UrlQuery.cpp
missdeer_hannah/desktop/BeastServer/UrlQuery.cpp
#include <vector> #include <boost/algorithm/string.hpp> #include "UrlQuery.h" UrlQuery::UrlQuery(const std::string &uri) { parse(uri); } QueryPairType::iterator UrlQuery::begin() { return m_queries.begin(); } QueryPairType::iterator UrlQuery::end() { return m_queries.end(); } bool UrlQuery::contains(const std::string &key) { return m_queries.find(key) != m_queries.end(); } const std::string &UrlQuery::value(const std::string &key) { return m_queries[key]; } int UrlQuery::intValue(const std::string &key) { auto iter = m_queries.find(key); return std::stoi(iter->second); } bool UrlQuery::isInt(const std::string &key) { auto iter = m_queries.find(key); if (m_queries.end() != iter) { try { std::stoi(iter->second); return true; } catch (...) { } } return false; } std::int64_t UrlQuery::int64Value(const std::string &key) { auto iter = m_queries.find(key); return std::stoll(iter->second); } bool UrlQuery::isInt64(const std::string &key) { auto iter = m_queries.find(key); if (m_queries.end() != iter) { try { std::stoll(iter->second); return true; } catch (...) { } } return false; } bool UrlQuery::boolValue(const std::string &key) { auto iter = m_queries.find(key); if (m_queries.end() != iter) { return boost::algorithm::iequals(iter->second, "true"); } return false; } bool UrlQuery::isBool(const std::string &key) { auto iter = m_queries.find(key); if (m_queries.end() != iter) { return boost::algorithm::iequals(iter->second, "true") || boost::algorithm::iequals(iter->second, "false"); } return false; } void UrlQuery::parse(const std::string &uri) { auto pos = uri.find('?'); if (pos == std::string::npos) { return; } auto parameters = uri.substr(pos + 1); // split by & std::vector<std::string> expressions; boost::split(expressions, parameters, boost::is_any_of("&")); for (const auto &expression : expressions) { // split by = std::vector<std::string> kv; boost::split(kv, expression, boost::is_any_of("=")); if (kv.size() == 2) { m_queries.insert(std::make_pair(kv[0], kv[1])); } } } void UrlParam::push_back(const std::string &value) { m_values.push_back(value); } bool UrlParam::isInt(size_t index) { if (index < m_values.size()) { try { auto val = std::stoi(m_values.at(index)); return true; } catch (...) { } } return false; } int UrlParam::intAt(size_t index) { return std::stoi(m_values.at(index)); } bool UrlParam::isInt64(size_t index) { if (index < m_values.size()) { try { auto val = std::stoll(m_values.at(index)); return true; } catch (...) { } } return false; } std::int64_t UrlParam::int64At(size_t index) { return std::stoll(m_values.at(index)); } const std::string &UrlParam::at(size_t index) { return m_values.at(index); } size_t UrlParam::size() const { return m_values.size(); } bool UrlParam::empty() const { return m_values.empty(); }
3,389
C++
.cpp
159
16.45283
115
0.582709
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,585
BeastHttpSession.cpp
missdeer_hannah/desktop/BeastServer/BeastHttpSession.cpp
#include <algorithm> #include <cstdlib> #include <functional> #include <iostream> #include <map> #include <regex> #include <string> #include <vector> #include <boost/asio/bind_executor.hpp> #include <boost/asio/dispatch.hpp> #include <boost/asio/signal_set.hpp> #include <boost/asio/strand.hpp> #include <boost/beast/version.hpp> #include <boost/beast/websocket.hpp> #include <boost/make_unique.hpp> #include <boost/multi_index/identity.hpp> #include <boost/multi_index/member.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index_container.hpp> #include "BeastHttpSession.h" #include "BeastHttpResponseHandler.h" #include "BeastWebsocketSessionManager.h" #include "UrlQuery.h" #include "ProviderAPI/kugou.h" #include "ProviderAPI/qq.h" #include "ProviderAPI/kuwo.h" #include "ProviderAPI/migu.h" #include "ProviderAPI/netease.h" namespace beast = boost::beast; // from <boost/beast.hpp> namespace http = beast::http; // from <boost/beast/http.hpp> namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp> namespace net = boost::asio; // from <boost/asio.hpp> using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp> namespace { using pHttpStaticRouterHandler = http::response<http::string_body> (*)(std::string &, UrlQuery &); struct HandlerDef { beast::string_view path; http::verb method; pHttpStaticRouterHandler handler; HandlerDef(const beast::string_view &p, http::verb m, pHttpStaticRouterHandler h) : path(p), method(m), handler(h) {} bool operator<(const HandlerDef &e) const { return path < e.path; } }; using HandlerDefSet = boost::multi_index_container< HandlerDef, boost::multi_index::indexed_by< boost::multi_index::ordered_non_unique<boost::multi_index::member<HandlerDef, beast::string_view, &HandlerDef::path>>, boost::multi_index::ordered_non_unique<boost::multi_index::member<HandlerDef, http::verb, &HandlerDef::method>>>>; // http://172.16.206.13:8090/pages/viewpage.action?pageId=16867802 static HandlerDefSet handlerMap = { // {"/api/v1/database/create", http::verb::post, RESTfulAPI::database::post_create}, }; using pHttpRegexRouterHandler = http::response<http::string_body> (*)(std::string &, UrlQuery &, UrlParam &); struct RegexHandlerDef { std::regex pattern; http::verb method; pHttpRegexRouterHandler handler; RegexHandlerDef(const std::regex &p, http::verb m, pHttpRegexRouterHandler h) : pattern(p), method(m), handler(h) {} }; using RegexHandlerDefSet = std::list<RegexHandlerDef>; static RegexHandlerDefSet regexHandlerMap = { {std::regex("^/netease/([a-zA-Z0-9_]+)/([a-zA-Z0-9_]+)$"), http::verb::get, ProviderAPI::netease::playlist}, {std::regex("^/netease/([a-zA-Z0-9_]+)$"), http::verb::get, ProviderAPI::netease::playlist}, {std::regex("^/netease/([a-zA-Z0-9_]+)/([a-zA-Z0-9_]+)$"), http::verb::head, ProviderAPI::netease::songinfo}, {std::regex("^/netease/([a-zA-Z0-9_]+)$"), http::verb::head, ProviderAPI::netease::songinfo}, {std::regex("^/kuwo/([a-zA-Z0-9_]+)/([a-zA-Z0-9_]+)$"), http::verb::get, ProviderAPI::kuwo::playlist}, {std::regex("^/kuwo/([a-zA-Z0-9_]+)$"), http::verb::get, ProviderAPI::kuwo::playlist}, {std::regex("^/kuwo/([a-zA-Z0-9_]+)/([a-zA-Z0-9_]+)$"), http::verb::head, ProviderAPI::kuwo::songinfo}, {std::regex("^/kuwo/([a-zA-Z0-9_]+)$"), http::verb::head, ProviderAPI::kuwo::songinfo}, {std::regex("^/kugou/([a-zA-Z0-9_]+)/([a-zA-Z0-9_]+)$"), http::verb::get, ProviderAPI::kugou::playlist}, {std::regex("^/kugou/([a-zA-Z0-9_]+)$"), http::verb::get, ProviderAPI::kugou::playlist}, {std::regex("^/kugou/([a-zA-Z0-9_]+)/([a-zA-Z0-9_]+)$"), http::verb::head, ProviderAPI::kugou::songinfo}, {std::regex("^/kugou/([a-zA-Z0-9_]+)$"), http::verb::head, ProviderAPI::kugou::songinfo}, {std::regex("^/migu/([a-zA-Z0-9_]+)/([a-zA-Z0-9_]+)$"), http::verb::get, ProviderAPI::migu::playlist}, {std::regex("^/migu/([a-zA-Z0-9_]+)$"), http::verb::get, ProviderAPI::migu::playlist}, {std::regex("^/migu/([a-zA-Z0-9_]+)/([a-zA-Z0-9_]+)$"), http::verb::head, ProviderAPI::migu::songinfo}, {std::regex("^/migu/([a-zA-Z0-9_]+)$"), http::verb::head, ProviderAPI::migu::songinfo}, {std::regex("^/qq/([a-zA-Z0-9_]+)/([a-zA-Z0-9_]+)$"), http::verb::get, ProviderAPI::qq::playlist}, {std::regex("^/qq/([a-zA-Z0-9_]+)$"), http::verb::get, ProviderAPI::qq::playlist}, {std::regex("^/qq/([a-zA-Z0-9_]+)/([a-zA-Z0-9_]+)$"), http::verb::head, ProviderAPI::qq::songinfo}, {std::regex("^/qq/([a-zA-Z0-9_]+)$"), http::verb::head, ProviderAPI::qq::songinfo}, }; } // namespace void registerHttpStaticRouter(const beast::string_view &path, http::verb method, pHttpStaticRouterHandler handler) { handlerMap.insert({path, method, handler}); } void registerHttpRegexRouter(const std::string &pattern, http::verb method, pHttpRegexRouterHandler handler) { regexHandlerMap.emplace_back(std::regex(pattern), method, handler); } void registerHttpRegexRouter(const std::regex &regexp, http::verb method, pHttpRegexRouterHandler handler) { regexHandlerMap.emplace_back(regexp, method, handler); } // This function produces an HTTP response for the given // request. The type of the response object depends on the // contents of the request, so the interface requires the // caller to pass a generic lambda for receiving the response. template<class Body, class Allocator, class Send> void handle_request(http::request<Body, http::basic_fields<Allocator>> &&req, Send &&send) { // Make sure we can handle the method if (req.method() != http::verb::get && req.method() != http::verb::head && req.method() != http::verb::delete_ && req.method() != http::verb::post && req.method() != http::verb::put) { return send(BeastHttpServer::bad_request(req, "Unknown HTTP-method")); } auto target = req.target(); // Request path must be absolute and not contain "..". if (target.empty() || target[0] != '/') { return send(BeastHttpServer::bad_request(req, "Illegal request-target")); } std::string path(target); if (auto pos = path.find('?'); pos != std::string::npos) { path = path.substr(0, pos); } boost::beast::string_view trimmedPath(path); auto method = req.method(); auto [begin, end] = handlerMap.get<0>().equal_range(trimmedPath); auto plaintextIter = std::find_if(begin, end, [method](const auto &item) { return item.method == method; }); if (end != plaintextIter) { UrlQuery uriParam {std::string {target}}; auto res = plaintextIter->handler(req.body(), uriParam); return send(std::move(res)); } auto regexIter = std::find_if(regexHandlerMap.begin(), regexHandlerMap.end(), [path](const auto &item) { return std::regex_match(path.begin(), path.end(), item.pattern); }); if (regexHandlerMap.end() != regexIter) { UrlQuery urlQuery {std::string {target}}; std::smatch paramMatch; UrlParam urlParams; const std::string &urlPath(path); if (std::regex_search(urlPath, paramMatch, regexIter->pattern)) { for (size_t i = 1, count = paramMatch.size(); i < count; ++i) { urlParams.push_back(paramMatch[i]); } } auto res = regexIter->handler(req.body(), urlQuery, urlParams); return send(std::move(res)); } return send(BeastHttpServer::not_found(req, target)); } BeastHttpSession::queue::queue(BeastHttpSession &self) : self_(self) { static_assert(limit > 0, "queue limit must be positive"); items_.reserve(limit); } bool BeastHttpSession::queue::is_full() const { return items_.size() >= limit; } bool BeastHttpSession::queue::on_write() { BOOST_ASSERT(!items_.empty()); auto const was_full = is_full(); items_.erase(items_.begin()); if (!items_.empty()) { (*items_.front())(); } return was_full; } BeastHttpSession::BeastHttpSession(tcp::socket &&socket) : stream_(std::move(socket)), queue_(*this) {} void BeastHttpSession::run() { // We need to be executing within a strand to perform async operations // on the I/O objects in this session. Although not strictly necessary // for single-threaded contexts, this example code is written to be // thread-safe by default. net::dispatch(stream_.get_executor(), beast::bind_front_handler(&BeastHttpSession::do_read, this->shared_from_this())); } void BeastHttpSession::do_read() { // Construct a new parser for each message parser_.emplace(); // Apply a reasonable limit to the allowed size // of the body in bytes to prevent abuse. parser_->body_limit(50 * 1024 * 1024); // Set the timeout. stream_.expires_after(std::chrono::seconds(30)); // Read a request using the parser-oriented interface http::async_read(stream_, buffer_, *parser_, beast::bind_front_handler(&BeastHttpSession::on_read, shared_from_this())); } void BeastHttpSession::on_read(beast::error_code ec, std::size_t bytes_transferred) { boost::ignore_unused(bytes_transferred); // This means they closed the connection if (ec == http::error::end_of_stream) { return do_close(); } if (ec) { fail(ec, "read"); return; } // See if it is a WebSocket Upgrade if (websocket::is_upgrade(parser_->get())) { // Create a websocket session, transferring ownership // of both the socket and the HTTP request. std::make_shared<BeastWebsocketSession>(stream_.release_socket())->doAccept(parser_->release()); return; } // Send the response handle_request(parser_->release(), queue_); // If we aren't at the queue limit, try to pipeline another request if (!queue_.is_full()) { do_read(); } } void BeastHttpSession::on_write(bool close, beast::error_code ec, std::size_t bytes_transferred) { boost::ignore_unused(bytes_transferred); if (ec) { fail(ec, "write"); return; } if (close) { // This means we should close the connection, usually because // the response indicated the "Connection: close" semantic. return do_close(); } // Inform the queue that a write completed if (queue_.on_write()) { // Read another request do_read(); } } void BeastHttpSession::do_close() { // Send a TCP shutdown beast::error_code ec; stream_.socket().shutdown(tcp::socket::shutdown_send, ec); // At this point the connection is closed gracefully } void BeastHttpSession::fail(beast::error_code ec, char const *what) { // Don't report on canceled operations if (ec == net::error::operation_aborted) { return; } }
11,207
C++
.cpp
260
37.903846
140
0.640689
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,586
BeastWebsocketSession.cpp
missdeer_hannah/desktop/BeastServer/BeastWebsocketSession.cpp
#include <algorithm> #include <cstdlib> #include <functional> #include <iostream> #include <string> #include <thread> #include <vector> #include <boost/algorithm/string.hpp> #include <boost/asio/bind_executor.hpp> #include <boost/asio/dispatch.hpp> #include <boost/asio/signal_set.hpp> #include <boost/asio/strand.hpp> #include <boost/beast/http.hpp> #include <boost/beast/version.hpp> #include <boost/make_unique.hpp> #include <boost/optional.hpp> #include "BeastWebsocketSession.h" #include "BeastWebsocketSessionManager.h" namespace beast = boost::beast; // from <boost/beast.hpp> namespace http = beast::http; // from <boost/beast/http.hpp> namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp> namespace net = boost::asio; // from <boost/asio.hpp> using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp> BeastWebsocketSession::BeastWebsocketSession(tcp::socket &&socket) : m_websocket(std::move(socket)) {} BeastWebsocketSession::~BeastWebsocketSession() { BeastWebsocketSessionManager::instance().remove(this); } void BeastWebsocketSession::onAccept(beast::error_code ec) { if (ec) { fail(ec, "accept"); return; } BeastWebsocketSessionManager::instance().add(this); // always an empty session id // set preset command by session id // Read a message m_websocket.async_read(m_buffer, beast::bind_front_handler(&BeastWebsocketSession::onRead, shared_from_this())); } void BeastWebsocketSession::onRead(beast::error_code ec, std::size_t bytes_transferred) { boost::ignore_unused(bytes_transferred); if (ec) { fail(ec, "read"); return; } // pass to handlers if (m_websocket.got_text()) { std::string payload(beast::buffers_to_string(m_buffer.data())); std::string str1 = "on_message called with hdl: ?? and message : " + payload; try { bool bHandled = analyseCommand(payload); if (!bHandled) { onWebMsg(payload); //! NOTICE: it's mainly a test purpose work flow // Send to all connections // BeastWebsocketSessionManager::instance().send(payload); } } catch (const std::exception &e) { BeastWebsocketSessionManager::instance().send(e.what()); } catch (...) { BeastWebsocketSessionManager::instance().send("unknown error on analyzing command and handle web message"); } } // Clear the buffer m_buffer.consume(m_buffer.size()); // wait for the next message m_websocket.async_read(m_buffer, beast::bind_front_handler(&BeastWebsocketSession::onRead, shared_from_this())); } void BeastWebsocketSession::onWrite(beast::error_code ec, std::size_t bytes_transferred) { boost::ignore_unused(bytes_transferred); // Handle the error, if any if (ec) { fail(ec, "write"); return; } // Remove the string from the queue m_msgQueue.erase(m_msgQueue.begin()); // Send the next message if any if (!m_msgQueue.empty()) { m_websocket.async_write(net::buffer(*m_msgQueue.front()), beast::bind_front_handler(&BeastWebsocketSession::onWrite, shared_from_this())); } } void BeastWebsocketSession::onSend(const std::shared_ptr<const std::string> &msg) { // Always add to queue m_msgQueue.push_back(msg); // Are we already writing? if (m_msgQueue.size() > 1) { return; } // We are not currently writing, so send this immediately m_websocket.async_write(net::buffer(*m_msgQueue.front()), beast::bind_front_handler(&BeastWebsocketSession::onWrite, shared_from_this())); } void BeastWebsocketSession::onWebMsg(const std::string &msg) { BeastWebsocketSessionManager::instance().onWebMsg(msg); } void BeastWebsocketSession::fail(beast::error_code ec, char const *what) { // Don't report these if (ec == net::error::operation_aborted || ec == websocket::error::closed) { return; } } std::string BeastWebsocketSession::getPresetCommand() { std::string strCommand = getCommand("SESSION_1_DOWN"); return strCommand; } std::string BeastWebsocketSession::getConfirmCommand() { std::string strCommand = getCommand("SESSION_2_DOWN"); return strCommand; } std::string BeastWebsocketSession::getCommand(const std::string &actionType) { return {}; } bool BeastWebsocketSession::analyseCommand(const std::string &strCommand) { return false; } void BeastWebsocketSession::send(const std::shared_ptr<const std::string> &msg) { // Post our work to the strand, this ensures // that the members of `this` will not be // accessed concurrently. net::post(m_websocket.get_executor(), beast::bind_front_handler(&BeastWebsocketSession::onSend, shared_from_this(), msg)); }
4,952
C++
.cpp
144
29.618056
146
0.678459
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,587
BeastServerRunner.cpp
missdeer_hannah/desktop/BeastServer/BeastServerRunner.cpp
#include <QSettings> #include "BeastServerRunner.h" #include "BeastServer.h" void BeastServerRunner::stop() { StopBeastServer(); } void BeastServerRunner::run() { StartBeastServer(); } void BeastServerRunner::applySettings(QSettings &settings) {}
260
C++
.cpp
12
19.583333
61
0.786008
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,588
BeastServer.cpp
missdeer_hannah/desktop/BeastServer/BeastServer.cpp
#include <algorithm> #include <cstdlib> #include <functional> #include <iostream> #include <string> #include <thread> #include <vector> #include <boost/asio/bind_executor.hpp> #include <boost/asio/dispatch.hpp> #include <boost/asio/signal_set.hpp> #include <boost/asio/strand.hpp> #include <boost/beast/version.hpp> #include <boost/format.hpp> #include <boost/json.hpp> #include <boost/make_unique.hpp> #include <boost/optional.hpp> #include "BeastServer.h" #include "BeastHttpSession.h" #include "BeastWebsocketSessionManager.h" namespace beast = boost::beast; // from <boost/beast.hpp> namespace net = boost::asio; // from <boost/asio.hpp> using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp> namespace { net::io_context *g_ioc = nullptr; unsigned short g_listeningPort = 9100; } // namespace std::string ConcatAPIUrl(const std::string &path) { if (!g_ioc) { return {}; } boost::format fmter("http://127.0.0.1:%1%"); fmter % g_listeningPort; return fmter.str() + path; } void StartBeastServer() { const auto address = net::ip::make_address("127.0.0.1"); const auto threadCount = std::max<int>(4, std::thread::hardware_concurrency()); net::io_context ioc {threadCount}; g_ioc = &ioc; std::make_shared<BeastServer>(ioc, tcp::endpoint {address, g_listeningPort})->run(); std::vector<std::thread> threads; threads.reserve(threadCount - 1); for (auto i = threadCount - 1; i > 0; --i) { threads.emplace_back([&ioc] { try { ioc.run(); } catch (std::exception &e) { } }); } boost::format fmter(R"({"pid" : %1%,"action" : "notification","type" : "websocket-ready","detail" : %2%})"); DWORD processId = GetCurrentProcessId(); fmter % processId % g_listeningPort; std::string notification = fmter.str(); try { ioc.run(); } catch (std::exception &e) { } // (If we get here, it means StopBeastServer() is called) // Block until all the threads exit for (auto &thread : threads) { thread.join(); } g_ioc = nullptr; BeastWebsocketSessionManager::instance().clear(); } void StopBeastServer() { if (g_ioc) { g_ioc->stop(); } } BeastServer::BeastServer(boost::asio::io_context &ioc, boost::asio::ip::tcp::endpoint endpoint) : m_ioc(ioc), m_acceptor(boost::asio::make_strand(ioc)) { beast::error_code ec; // Open the acceptor m_acceptor.open(endpoint.protocol(), ec); if (ec) { fail(ec, "open"); return; } // Allow address reuse m_acceptor.set_option(net::socket_base::reuse_address(true), ec); if (ec) { fail(ec, "set_option"); return; } // Bind to the server address m_acceptor.bind(endpoint, ec); if (ec) { fail(ec, "bind"); return; } // Start listening for connections m_acceptor.listen(net::socket_base::max_listen_connections, ec); if (ec) { fail(ec, "listen"); return; } } void BeastServer::run() { // We need to be executing within a strand to perform async operations // on the I/O objects in this session. Although not strictly necessary // for single-threaded contexts, this example code is written to be // thread-safe by default. boost::asio::dispatch(m_acceptor.get_executor(), beast::bind_front_handler(&BeastServer::do_accept, shared_from_this())); } void BeastServer::do_accept() { // The new connection gets its own strand m_acceptor.async_accept(boost::asio::make_strand(m_ioc), beast::bind_front_handler(&BeastServer::on_accept, shared_from_this())); } void BeastServer::on_accept(beast::error_code ec, tcp::socket socket) { if (ec) { fail(ec, "accept"); } else { // Create the http session and run it std::make_shared<BeastHttpSession>(std::move(socket))->run(); } // Accept another connection do_accept(); } void BeastServer::fail(beast::error_code ec, char const *what) { // Don't report on canceled operations if (ec == net::error::operation_aborted) { return; } } void SetListenPort(unsigned short port) { g_listeningPort = port; }
4,389
C++
.cpp
157
23.280255
133
0.628952
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,589
Sqlite3Statement.cpp
missdeer_hannah/desktop/sqlite/Sqlite3Statement.cpp
#include <sqlite3.h> #include <QtCore> #include "Sqlite3Statement.h" Sqlite3Statement::Sqlite3Statement(sqlite3 *&database, sqlite3_stmt *pVM) : m_db(database), m_pVM(pVM) {} void Sqlite3Statement::bind(int nParam, const QString &value) {} void Sqlite3Statement::bind(const char *szParam, const char *szValue, int nLen /*= -1*/) { int nParam = bindParameterIndex(szParam); bind(nParam, szValue, nLen); } void Sqlite3Statement::bind(const char *szParam, int nValue) { int nParam = bindParameterIndex(szParam); bind(nParam, nValue); } void Sqlite3Statement::bind(const char *szParam, int64_t nValue) { int nParam = bindParameterIndex(szParam); bind(nParam, nValue); } void Sqlite3Statement::bind(const char *szParam, double dwValue) { int nParam = bindParameterIndex(szParam); bind(nParam, dwValue); } void Sqlite3Statement::bind(const char *szParam, const unsigned char *blobValue, int nLen) { int nParam = bindParameterIndex(szParam); bind(nParam, blobValue, nLen); } void Sqlite3Statement::bind(const char *szParam, std::string_view szValue) { bind(szParam, szValue.data(), static_cast<int>(szValue.size())); } void Sqlite3Statement::bind(const char *szParam, const std::string &szValue) { bind(szParam, szValue.c_str(), static_cast<int>(szValue.size())); } void Sqlite3Statement::bindNull(const char *szParam) { int nParam = bindParameterIndex(szParam); bindNull(nParam); } void Sqlite3Statement::bind(const std::string &szParam, const std::string &szValue) { bind(szParam.c_str(), szValue.c_str(), static_cast<int>(szValue.size())); } void Sqlite3Statement::bind(const std::string &szParam, int nValue) { bind(szParam.c_str(), nValue); } void Sqlite3Statement::bind(const std::string &szParam, int64_t nValue) { bind(szParam.c_str(), nValue); } void Sqlite3Statement::bind(const std::string &szParam, double dwValue) { bind(szParam.c_str(), dwValue); } void Sqlite3Statement::bind(const std::string &szParam, const unsigned char *blobValue, int nLen) { bind(szParam.c_str(), blobValue, nLen); } void Sqlite3Statement::bind(const std::string &szParam, std::string_view szValue) { bind(szParam.c_str(), szValue.data(), static_cast<int>(szValue.size())); } void Sqlite3Statement::bindNull(const std::string &szParam) { bindNull(szParam.c_str()); } int Sqlite3Statement::bindParameterIndex(const QString &szParam) { return bindParameterIndex(szParam.toStdString().c_str()); } void Sqlite3Statement::bind(const QString &szParam, const QString &value) { bind(szParam.toStdString().c_str(), value.toStdString().c_str()); } void Sqlite3Statement::bind(const QString &szParam, const std::string &szValue) { bind(szParam.toStdString().c_str(), szValue.c_str()); } void Sqlite3Statement::bind(const QString &szParam, std::string_view szValue) { bind(szParam.toStdString().c_str(), szValue); } void Sqlite3Statement::bind(const QString &szParam, int nValue) { bind(szParam.toStdString().c_str(), nValue); } void Sqlite3Statement::bind(const QString &szParam, int64_t nValue) { bind(szParam.toStdString().c_str(), nValue); } void Sqlite3Statement::bind(const QString &szParam, double dwValue) { bind(szParam.toStdString().c_str(), dwValue); } void Sqlite3Statement::bind(const QString &szParam, const unsigned char *blobValue, int nLen) { bind(szParam.toStdString().c_str(), blobValue, nLen); } void Sqlite3Statement::bindNull(const QString &szParam) { bindNull(szParam.toStdString().c_str()); } void Sqlite3Statement::bind(int nParam, const char *szValue, int nLen /*= -1*/) { if (!isDatabaseOpened()) { qWarning() << "database is not opened"; return; } if (!m_pVM) { qCritical() << "VM null pointer"; return; } int nRes = sqlite3_bind_text(m_pVM, nParam, szValue, nLen, SQLITE_TRANSIENT); if (nRes != SQLITE_OK) { qCritical() << "Error binding string param"; } } void Sqlite3Statement::bind(int nParam, const std::string &szValue) { bind(nParam, szValue.c_str(), static_cast<int>(szValue.size())); } void Sqlite3Statement::bind(int nParam, std::string_view szValue) { bind(nParam, szValue.data(), static_cast<int>(szValue.size())); } void Sqlite3Statement::bind(int nParam, int nValue) { if (!isDatabaseOpened()) { qWarning() << "database is not opened"; return; } if (!m_pVM) { qCritical() << "VM null pointer"; return; } int nRes = sqlite3_bind_int(m_pVM, nParam, nValue); if (nRes != SQLITE_OK) { qCritical() << "Error binding int param"; } } void Sqlite3Statement::bind(int nParam, int64_t nValue) { if (!isDatabaseOpened()) { qWarning() << "database is not opened"; return; } if (!m_pVM) { qCritical() << "VM null pointer"; return; } int nRes = sqlite3_bind_int64(m_pVM, nParam, nValue); if (nRes != SQLITE_OK) { qCritical() << "Error binding int param"; } } void Sqlite3Statement::bind(int nParam, double dValue) { if (!isDatabaseOpened()) { qWarning() << "database is not opened"; return; } if (!m_pVM) { qCritical() << "VM null pointer"; return; } int nRes = sqlite3_bind_double(m_pVM, nParam, dValue); if (nRes != SQLITE_OK) { qCritical() << "Error binding double param"; } } void Sqlite3Statement::bind(int nParam, const unsigned char *blobValue, int nLen) { if (!isDatabaseOpened()) { qWarning() << "database is not opened"; return; } if (!m_pVM) { qCritical() << "VM null pointer"; return; } int nRes = sqlite3_bind_blob(m_pVM, nParam, (const void *)blobValue, nLen, SQLITE_TRANSIENT); if (nRes != SQLITE_OK) { qCritical() << "Error binding blob param"; } } void Sqlite3Statement::bindNull(int nParam) { if (!isDatabaseOpened()) { qWarning() << "database is not opened"; return; } if (!m_pVM) { qCritical() << "VM null pointer"; return; } int nRes = sqlite3_bind_null(m_pVM, nParam); if (nRes != SQLITE_OK) { qCritical() << "Error binding NULL param"; } } int Sqlite3Statement::bindParameterIndex(const char *szParam) { if (!isDatabaseOpened()) { qWarning() << "database is not opened"; return -1; } if (!m_pVM) { qCritical() << "VM null pointer"; return -1; } int nParam = sqlite3_bind_parameter_index(m_pVM, szParam); if (!nParam) { qCritical() << "parameter is not valid for this statement"; } return nParam; } void Sqlite3Statement::bind(const char *szParam, const QString &value) { bind(szParam, value.toStdString().c_str()); } int Sqlite3Statement::bindParameterIndex(const std::string &szParam) { return bindParameterIndex(szParam.c_str()); } void Sqlite3Statement::bind(const std::string &szParam, const QString &value) { bind(szParam.c_str(), value.toStdString().c_str()); } int Sqlite3Statement::execDML() { if (!isDatabaseOpened()) { qWarning() << "database is not opened"; return -1; } if (!m_pVM) { qCritical() << "VM null pointer"; return -1; } if (sqlite3_step(m_pVM) == SQLITE_DONE) { int nRowsChanged = sqlite3_changes(m_db); if (sqlite3_finalize(m_pVM) != SQLITE_OK) { qCritical() << sqlite3_errmsg(m_db); return -1; } return nRowsChanged; } sqlite3_finalize(m_pVM); qCritical() << sqlite3_errmsg(m_db); return -1; } int Sqlite3Statement::execQuery(bool &eof) { int nRet = sqlite3_step(m_pVM); if (nRet == SQLITE_DONE) { // no rows sqlite3_finalize(m_pVM); eof = true; return nRet; } if (nRet == SQLITE_ROW) { // at least 1 row eof = false; return nRet; } nRet = sqlite3_finalize(m_pVM); if (nRet == SQLITE_SCHEMA) { return nRet; } qCritical() << sqlite3_errmsg(m_db); return -1; } int Sqlite3Statement::nextRow(bool &eof) { int nRet = sqlite3_step(m_pVM); if (nRet == SQLITE_DONE) { // no rows sqlite3_finalize(m_pVM); eof = true; } else if (nRet == SQLITE_ROW) { // more rows, nothing to do eof = false; } else { nRet = sqlite3_finalize(m_pVM); qCritical() << sqlite3_errmsg(m_db); return nRet; } return nRet; } int Sqlite3Statement::endQuery() { int nRet = sqlite3_finalize(m_pVM); if (nRet != SQLITE_OK && nRet != SQLITE_DONE) { qCritical() << sqlite3_errmsg(m_db); } return nRet; } int Sqlite3Statement::getInt(int column) { if (!isDatabaseOpened()) { qWarning() << "database is not opened"; return -1; } if (!m_pVM) { qCritical() << "VM null pointer"; return -1; } return sqlite3_column_int(m_pVM, column); } double Sqlite3Statement::getDouble(int column) { if (!isDatabaseOpened()) { qWarning() << "database is not opened"; return -1; } if (!m_pVM) { qCritical() << "VM null pointer"; return -1; } return sqlite3_column_double(m_pVM, column); } std::int64_t Sqlite3Statement::getInt64(int column) { if (!isDatabaseOpened()) { qWarning() << "database is not opened"; return -1; } if (!m_pVM) { qCritical() << "VM null pointer"; return -1; } return sqlite3_column_int64(m_pVM, column); } std::string Sqlite3Statement::getString(int column) { if (!isDatabaseOpened()) { qWarning() << "database is not opened"; return {}; } if (!m_pVM) { qCritical() << "VM null pointer"; return {}; } return {(const char *)sqlite3_column_text(m_pVM, column), static_cast<std::string::size_type>(sqlite3_column_bytes(m_pVM, column))}; } QString Sqlite3Statement::getQString(int column) { return QString::fromStdString(getString(column)); } std::string Sqlite3Statement::getLastErrorString() { return sqlite3_errmsg(m_db); } int Sqlite3Statement::countRow() { int count = 0; int nRet = 0; bool eof = false; do { nRet = execQuery(eof); if (nRet == SQLITE_DONE || nRet == SQLITE_ROW) { while (!eof) { count = sqlite3_column_int(m_pVM, 0); nextRow(eof); } break; } } while (nRet == SQLITE_SCHEMA); return count; } bool Sqlite3Statement::isValid() { return m_pVM != nullptr; } bool Sqlite3Statement::isDatabaseOpened() { return m_db != nullptr; } QByteArray Sqlite3Statement::getBlob(int column) { if (!isDatabaseOpened()) { qWarning() << "database is not opened"; return {}; } if (!m_pVM) { qCritical() << "VM null pointer"; return {}; } return {static_cast<const char *>(sqlite3_column_blob(m_pVM, column)), sqlite3_column_bytes(m_pVM, column)}; } void Sqlite3Statement::bind(int nParam, const QByteArray &blobValue) { bind(nParam, (const unsigned char *)blobValue.data(), blobValue.length()); } void Sqlite3Statement::bind(const char *szParam, const QByteArray &blobValue) { bind(szParam, (const unsigned char *)blobValue.data(), blobValue.length()); } void Sqlite3Statement::bind(const std::string &szParam, const QByteArray &blobValue) { bind(szParam, (const unsigned char *)blobValue.data(), blobValue.length()); } void Sqlite3Statement::bind(const QString &szParam, const QByteArray &blobValue) { bind(szParam, (const unsigned char *)blobValue.data(), blobValue.length()); }
11,933
C++
.cpp
457
21.516411
136
0.640158
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,590
Sqlite3DBManager.cpp
missdeer_hannah/desktop/sqlite/Sqlite3DBManager.cpp
#include <filesystem> #include <random> #include <sqlite3.h> #include <QtCore> #include "Sqlite3DBManager.h" #include "Sqlite3Constants.h" void Sqlite3DBManager::regenerateSavePoint() { static const std::string chars("abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "1234567890"); std::random_device rng; std::uniform_int_distribution<> index_dist(0, static_cast<int>(chars.size()) - 1); std::string res; const int length = 16; for (int i = 0; i < length; i++) { res.append(1, chars[index_dist(rng)]); } m_savePoint = res; } void Sqlite3DBManager::clearSavePoint() { m_savePoint.clear(); } bool Sqlite3DBManager::setSavePoint() { std::string sql = "SAVEPOINT '" + m_savePoint + "';"; if (m_sqlite.execDML(sql) != SQLITE_OK) { qCritical() << "Cannot set savepoint."; return false; } qDebug() << "set savepoint" << QString::fromStdString(m_savePoint); return true; } bool Sqlite3DBManager::releaseSavePoint() { std::string sql = "RELEASE '" + m_savePoint + "';"; if (m_sqlite.execDML(sql) != SQLITE_OK) { qCritical() << "Cannot release savepoint."; return false; } qDebug() << "released savepoint" << QString::fromStdString(m_savePoint); return true; } bool Sqlite3DBManager::open(const QString &dbPath, bool readOnly) { return open(dbPath.toUtf8().constData(), readOnly); } bool Sqlite3DBManager::open(const std::string &dbPath, bool readOnly) { return open(dbPath.c_str(), readOnly); } bool Sqlite3DBManager::open(const char *dbPath, bool readOnly) { if (sqlite3_open_v2(dbPath, &m_db, (readOnly ? SQLITE_OPEN_READONLY : SQLITE_OPEN_READWRITE), nullptr) != SQLITE_OK) { qCritical() << "Cannot open the database" << QString::fromUtf8(dbPath); return false; } Q_ASSERT(m_db); if (!readOnly) { regenerateSavePoint(); setSavePoint(); } qDebug() << "The database" << QString::fromStdString(dbPath) << "is opened"; return true; } bool Sqlite3DBManager::close() { if (!m_db) { qWarning() << "database is not opened"; return true; } int result = sqlite3_close_v2(m_db); while (result == SQLITE_BUSY) { qDebug() << "Close db result: " << result << sqlite3_errmsg(m_db); sqlite3_stmt *stmt = sqlite3_next_stmt(m_db, nullptr); if (stmt) { result = sqlite3_finalize(stmt); if (result == SQLITE_OK) { result = sqlite3_close_v2(m_db); qDebug() << "Secondary try closing db result: " << result << sqlite3_errmsg(m_db); } } } if (result != SQLITE_OK) { qCritical() << "Closing db failed:" << result << sqlite3_errmsg(m_db); return false; } m_db = nullptr; qDebug() << "database closed"; return true; } bool Sqlite3DBManager::save() { releaseSavePoint(); // always set a new save point regenerateSavePoint(); return setSavePoint(); } bool Sqlite3DBManager::saveAndClose() { if (!releaseSavePoint()) { return false; } return close(); } bool Sqlite3DBManager::create(const QString &dbPath) { return create(dbPath.toUtf8().constData()); } bool Sqlite3DBManager::create(const std::string &dbPath) { return create(dbPath.c_str()); } bool Sqlite3DBManager::create(const char *dbPath) { if (sqlite3_open_v2(dbPath, &m_db, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, nullptr) != SQLITE_OK) { qCritical() << "Cannot create the database" << QString::fromUtf8(dbPath); return false; } Q_ASSERT(m_db); qInfo() << "The database is created at" << QString::fromStdString(dbPath); qDebug() << "set sqlite options for performance issue"; if (m_sqlite.execDML(SQL_STATEMENT_CACHE_SIZE) != SQLITE_OK) { qCritical() << "Cannot set cache size."; return false; } if (m_sqlite.execDML(SQL_STATEMENT_ENABLE_FOREIGN_KEYS) != SQLITE_OK) { qCritical() << "Cannot enable the foreign keys."; return false; } regenerateSavePoint(); setSavePoint(); return true; } Sqlite3Helper &Sqlite3DBManager::engine() { return m_sqlite; } Sqlite3DBManager::~Sqlite3DBManager() { if (isOpened()) { close(); } } bool Sqlite3DBManager::isOpened() const { return m_db != nullptr; } bool Sqlite3DBManager::loadOrSaveInMemory(const QString &dbPath, bool isSave) { sqlite3 *pFile = nullptr; /* Database connection opened on zFilename */ /* Open the database file identified by zFilename. Exit early if this fails ** for any reason. */ #if defined(Q_OS_WIN) int result = sqlite3_open(dbPath.toUtf8().constData(), &pFile); #else int result = sqlite3_open(dbPath.toStdString().c_str(), &pFile); #endif if (result == SQLITE_OK) { /* If this is a 'load' operation (isSave==0), then data is copied ** from the database file just opened to database pInMemory. ** Otherwise, if this is a 'save' operation (isSave==1), then data ** is copied from pInMemory to pFile. Set the variables pFrom and ** pTo accordingly. */ auto *pFrom = (isSave ? m_db : pFile); auto *pTo = (isSave ? pFile : m_db); /* Set up the backup procedure to copy from the "main" database of ** connection pFile to the main database of connection pInMemory. ** If something goes wrong, pBackup will be set to NULL and an error ** code and message left in connection pTo. ** ** If the backup object is successfully created, call backup_step() ** to copy data from pFile to pInMemory. Then call backup_finish() ** to release resources associated with the pBackup object. If an ** error occurred, then an error code and message will be left in ** connection pTo. If no error occurred, then the error code belonging ** to pTo is set to SQLITE_OK. */ auto *pBackup = sqlite3_backup_init(pTo, "main", pFrom, "main"); if (pBackup) { (void)sqlite3_backup_step(pBackup, -1); (void)sqlite3_backup_finish(pBackup); } result = sqlite3_errcode(pTo); } else { qCritical() << "cannot open file" << dbPath; } /* Close the database connection opened on database file zFilename ** and return the result of this function. */ (void)sqlite3_close(pFile); return result == SQLITE_OK; } bool Sqlite3DBManager::saveAs(const QString &newDbPath) { return saveAs(newDbPath.toUtf8().constData()); } bool Sqlite3DBManager::saveAs(const std::string &newDbPath) { return saveAs(newDbPath.c_str()); } bool Sqlite3DBManager::saveAs(const char *newDbPath) { releaseSavePoint(); sqlite3 *newDb = nullptr; if (sqlite3_open_v2(newDbPath, &newDb, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, nullptr) != SQLITE_OK) { qCritical() << "Cannot open the database" << QString::fromUtf8(newDbPath); return false; } Q_ASSERT(newDbPath); Sqlite3Helper newEngine(newDb); newEngine.beginTransaction(); sqlite3_backup *backup = sqlite3_backup_init(newDb, "main", m_db, "main"); if (backup == nullptr) { qCritical() << "sqlite3_backup_init failed:" << sqlite3_errmsg(newDb); return false; } int resultCode = sqlite3_backup_step(backup, -1); if (resultCode != SQLITE_DONE) { qCritical() << "sqlite3_backup_step failed:" << resultCode << "-" << sqlite3_errmsg(newDb); return false; } resultCode = sqlite3_backup_finish(backup); if (resultCode != SQLITE_OK) { qCritical() << "sqlite3_backup_finish failed:" << resultCode << "-" << sqlite3_errmsg(newDb); return false; } newEngine.endTransaction(); close(); m_db = newDb; regenerateSavePoint(); setSavePoint(); return true; }
8,176
C++
.cpp
257
26.190661
120
0.629846
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,591
Sqlite3Helper.cpp
missdeer_hannah/desktop/sqlite/Sqlite3Helper.cpp
#include <chrono> #include <vector> #include <sqlite3.h> #include <QFile> #include <QtCore/qstringliteral.h> #include <QtCore> #include "Sqlite3Helper.h" #include "Sqlite3Constants.h" Sqlite3Helper::Sqlite3Helper(sqlite3 *&db) : m_db(db) {} Sqlite3StatementPtr Sqlite3Helper::compile(const char *szSQL) { if (!m_db) { qCritical() << szSQL << "null db pointer"; return nullptr; } sqlite3_stmt *pVM = nullptr; int res = sqlite3_prepare(m_db, szSQL, -1, &pVM, nullptr); if (res != SQLITE_OK) { const char *szError = sqlite3_errmsg(m_db); qCritical() << "prepare SQL statement" << szSQL << "failed:" << res << "-" << szError; return nullptr; } return std::make_shared<Sqlite3Statement>(m_db, pVM); } Sqlite3StatementPtr Sqlite3Helper::compile(const std::string &sql) { return compile(sql.c_str()); } Sqlite3StatementPtr Sqlite3Helper::compile(const QString &sql) { return compile(sql.toStdString().c_str()); } int Sqlite3Helper::execDML(const char *szSQL) { int resultCode = SQLITE_OK; do { auto stmt = compile(szSQL); if (!stmt || !stmt->isValid()) { qCritical() << szSQL << "null pVM, quit"; return SQLITE_ERROR; } resultCode = sqlite3_step(stmt->m_pVM); if (resultCode == SQLITE_ERROR) { qCritical() << "step SQL statement " << szSQL << "failed:" << resultCode << "-" << sqlite3_errmsg(m_db); sqlite3_finalize(stmt->m_pVM); break; } resultCode = sqlite3_finalize(stmt->m_pVM); } while (resultCode == SQLITE_SCHEMA); return resultCode; } int Sqlite3Helper::execDML(const std::string &sql) { return execDML(sql.c_str()); } int Sqlite3Helper::execDML(const QString &sql) { return execDML(sql.toStdString().c_str()); } bool Sqlite3Helper::isQueryOk(int result) { return (result == SQLITE_DONE || result == SQLITE_ROW); } bool Sqlite3Helper::isOk(int result) { return result == SQLITE_OK; } bool Sqlite3Helper::canQueryLoop(int result) { return result == SQLITE_SCHEMA; } int Sqlite3Helper::getQueryResult(const char *szSQL) { int count = 0; int nRet = 0; bool eof = false; do { auto stmt = compile(szSQL); nRet = stmt->execQuery(eof); if (nRet == SQLITE_DONE || nRet == SQLITE_ROW) { while (!eof) { count = stmt->getInt(0); stmt->nextRow(eof); } break; } } while (nRet == SQLITE_SCHEMA); return count; } int Sqlite3Helper::getQueryResult(const std::string &sql) { return getQueryResult(sql.c_str()); } int Sqlite3Helper::getQueryResult(const QString &sql) { return getQueryResult(sql.toStdString().c_str()); } bool Sqlite3Helper::isDatabaseOpened() { return m_db != nullptr; } int Sqlite3Helper::checkTableOrIndexExists(const std::string &field, const std::string &name) { bool eof = false; int nRet = 0; do { auto stmt = compile(SQL_STATEMENT_SELECT_SQLITE_MASTER); if (!stmt || !stmt->isValid()) { return -1; } stmt->bind(1, field.c_str()); stmt->bind(2, name.c_str()); nRet = stmt->execQuery(eof); if (nRet == SQLITE_DONE || nRet == SQLITE_ROW) { int size = 0; while (!eof) { size = 1; if (!stmt->nextRow(eof)) { return -2; } } if (size > 0) { qDebug() << "found expected" << QString::fromStdString(field) << ":" << QString::fromStdString(name); return size; } qDebug() << "not found expected" << QString::fromStdString(field) << ":" << QString::fromStdString(name); return 0; } } while (nRet == SQLITE_SCHEMA); return 0; } int Sqlite3Helper::checkTableOrIndexExists(const QString &field, const QString &name) { return checkTableOrIndexExists(field.toStdString(), name.toStdString()); } bool Sqlite3Helper::createTablesAndIndexes(std::map<std::string, const char *> &tablesMap, std::map<std::string, const char *> &indexesMap) { for (auto &[tableName, sql] : tablesMap) { int res = checkTableOrIndexExists("table", tableName); if (res < 0) { // do repair database file return false; } if (!res) { if (execDML(sql) != SQLITE_OK) { qWarning() << sqlite3_errmsg(m_db); return false; } } } for (auto &[indexName, sql] : indexesMap) { int res = checkTableOrIndexExists("index", indexName); if (res < 0) { // do repair database file return false; } if (!res) { if (execDML(sql) != SQLITE_OK) { qWarning() << sqlite3_errmsg(m_db); return false; } } } return true; } bool Sqlite3Helper::beginTransaction() { return execDML(SQL_STATEMENT_BEGIN_TRANSACTION) == SQLITE_OK; } bool Sqlite3Helper::endTransaction() { return execDML(SQL_STATEMENT_COMMIT_TRANSACTION) == SQLITE_OK; } bool Sqlite3Helper::rollbackTransaction() { return execDML(SQL_STATEMENT_ROLLBACK_TRANSACTION) == SQLITE_OK; } bool Sqlite3Helper::vacuum() { return execDML(SQL_STATEMENT_VACUUM) == SQLITE_OK; } std::int64_t Sqlite3Helper::lastInsertRowId() { if (m_db) { return sqlite3_last_insert_rowid(m_db); } return -1; } bool Sqlite3Helper::addTableColumn(const QString &tableName, const QString &fieldName, const QString &fieldType) { QString sql = QStringLiteral("ALTER TABLE %1 ADD COLUMN %2 %3;").arg(tableName, fieldName, fieldType); return execDML(sql) == SQLITE_OK; } bool Sqlite3Helper::checkTableColumnExists(const QString &tableName, const QString &fieldName) { sqlite3_stmt *stmt = nullptr; QString sql = QStringLiteral("SELECT %2 FROM %1 LIMIT 1;").arg(tableName, fieldName); int resultCode = sqlite3_prepare_v2(m_db, sql.toStdString().c_str(), -1, &stmt, nullptr); if (resultCode != SQLITE_OK) { qCritical() << "Error preparing statement: " << sqlite3_errmsg(m_db); return false; } int columnIndex = sqlite3_column_count(stmt); sqlite3_finalize(stmt); return (columnIndex >= 1); } int Sqlite3Helper::getTableColumnCount(const QString &tableName) { sqlite3_stmt *stmt = nullptr; QString sql = QStringLiteral("SELECT * FROM %1;").arg(tableName); int resultCode = sqlite3_prepare_v2(m_db, sql.toStdString().c_str(), -1, &stmt, nullptr); if (resultCode != SQLITE_OK) { qCritical() << "Error preparing statement: " << sqlite3_errmsg(m_db); return false; } int columnCount = sqlite3_column_count(stmt); sqlite3_finalize(stmt); return columnCount; } int Sqlite3Helper::getTableRowCount(const QString &tableName) { return getQueryResult(QStringLiteral("SELECT COUNT(*) FROM %1;").arg(tableName)); }
7,288
C++
.cpp
248
23.173387
139
0.605696
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,592
parsercsv.cpp
missdeer_hannah/desktop/parser/parsercsv.cpp
// // C++ Implementation: parsercsv // // Description: module to parse Comma-Separated Values (CSV) formatted playlists (rfc4180) // // // Author: Ingo Kossyk <kossyki@cs.tu-berlin.de>, (C) 2004 // Author: Tobias Rafreider trafreider@mixxx.org, (C) 2011 // Author: Daniel Schürmann daschuer@gmx.de, (C) 2011 // // Copyright: See COPYING file that comes with this distribution // // #include <QDir> #include <QMessageBox> #include <QTextStream> #include <QtDebug> #include "parsercsv.h" QList<QString> ParserCsv::parse(const QString &sFilename) { QFile file(sFilename); QString basepath = sFilename.section('/', 0, -2); clearLocations(); // qDebug() << "ParserCsv: Starting to parse."; if (file.open(QIODevice::ReadOnly) && !isBinary(sFilename)) { QByteArray ba = file.readAll(); QList<QList<QString>> tokens = tokenize(ba, ','); // detect Location column int loc_coll = 0x7fffffff; if (!tokens.empty()) { for (int i = 0; i < tokens[0].size(); ++i) { if (tokens[0][i] == tr("Location")) { loc_coll = i; break; } } for (int i = 1; i < tokens.size(); ++i) { if (loc_coll < tokens[i].size()) { // Todo: check if path is relative QFileInfo fi(tokens[i][loc_coll]); if (fi.isRelative()) { // add base path qDebug() << "is relative" << basepath << fi.filePath(); fi.setFile(basepath, fi.filePath()); } m_sLocations.append(fi.filePath()); } } } file.close(); if (m_sLocations.count() != 0) { return m_sLocations; } return {}; // NULL pointer returned when no locations were found } file.close(); return {}; // if we get here something went wrong } // Code was posted at http://www.qtcentre.org/threads/35511-Parsing-CSV-data // by "adzajac" and adapted to use QT Classes QList<QList<QString>> ParserCsv::tokenize(const QByteArray &str, char delimiter) { QList<QList<QString>> tokens; unsigned int row = 0; bool quotes = false; QByteArray field = ""; tokens.append(QList<QString>()); for (int pos = 0; pos < str.length(); ++pos) { char c = str[pos]; if (!quotes && c == '"') { quotes = true; } else if (quotes && c == '"') { if (pos + 1 < str.length() && str[pos + 1] == '"') { field.append(c); pos++; } else { quotes = false; } } else if (!quotes && c == delimiter) { if (isUtf8(field.constData())) { tokens[row].append(QString::fromUtf8(field)); } else { tokens[row].append(QString::fromLatin1(field)); } field.clear(); } else if (!quotes && (c == '\r' || c == '\n')) { if (isUtf8(field.constData())) { tokens[row].append(QString::fromUtf8(field)); } else { tokens[row].append(QString::fromLatin1(field)); } field.clear(); tokens.append(QList<QString>()); row++; } else { field.push_back(c); } } return tokens; }
3,745
C++
.cpp
127
19.653543
90
0.47697
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,593
parser.cpp
missdeer_hannah/desktop/parser/parser.cpp
// // C++ Implementation: parser // // Description: superclass for external formats parsers // // // Author: Ingo Kossyk <kossyki@cs.tu-berlin.de>, (C) 2004 // Author: Tobias Rafreider trafreider@mixxx.org, (C) 2011 // // Copyright: See COPYING file that comes with this distribution // // #include <QDir> #include <QFile> #include <QIODevice> #include <QUrl> #include <QtDebug> #include "parser.h" void Parser::clearLocations() { m_sLocations.clear(); } long Parser::countParsed() { return (long)m_sLocations.count(); } bool Parser::isBinary(const QString &filename) { char firstByte; QFile file(filename); if (file.open(QIODevice::ReadOnly) && file.getChar(&firstByte)) { // If starting byte is not an ASCII character then the file // probably contains binary data. if (firstByte >= 32 && firstByte <= 126) { // Valid ASCII character return false; } // Check for UTF-8 BOM if (firstByte == '\xEF') { char nextChar; if (file.getChar(&nextChar) && nextChar == '\xBB' && file.getChar(&nextChar) && nextChar == '\xBF') { // UTF-8 text file return false; } return true; } } qDebug() << "Parser: Error reading from" << filename; return true; // should this raise an exception? } // The following public domain code is taken from // http://stackoverflow.com/questions/1031645/how-to-detect-utf-8-in-plain-c // Thank you Christoph! // static bool Parser::isUtf8(const char *string) { if (!string) { return false; } const unsigned char *bytes = (const unsigned char *)string; while (*bytes) { if (( // ASCII bytes[0] == 0x09 || bytes[0] == 0x0A || bytes[0] == 0x0D || (0x20 <= bytes[0] && bytes[0] <= 0x7E))) { bytes += 1; continue; } if (( // non-overlong 2-byte (0xC2 <= bytes[0] && bytes[0] <= 0xDF) && (0x80 <= bytes[1] && bytes[1] <= 0xBF))) { bytes += 2; continue; } if (( // excluding overlongs bytes[0] == 0xE0 && (0xA0 <= bytes[1] && bytes[1] <= 0xBF) && (0x80 <= bytes[2] && bytes[2] <= 0xBF)) || ( // straight 3-byte ((0xE1 <= bytes[0] && bytes[0] <= 0xEC) || bytes[0] == 0xEE || bytes[0] == 0xEF) && (0x80 <= bytes[1] && bytes[1] <= 0xBF) && (0x80 <= bytes[2] && bytes[2] <= 0xBF)) || ( // excluding surrogates bytes[0] == 0xED && (0x80 <= bytes[1] && bytes[1] <= 0x9F) && (0x80 <= bytes[2] && bytes[2] <= 0xBF))) { bytes += 3; continue; } if (( // planes 1-3 bytes[0] == 0xF0 && (0x90 <= bytes[1] && bytes[1] <= 0xBF) && (0x80 <= bytes[2] && bytes[2] <= 0xBF) && (0x80 <= bytes[3] && bytes[3] <= 0xBF)) || ( // planes 4-15 (0xF1 <= bytes[0] && bytes[0] <= 0xF3) && (0x80 <= bytes[1] && bytes[1] <= 0xBF) && (0x80 <= bytes[2] && bytes[2] <= 0xBF) && (0x80 <= bytes[3] && bytes[3] <= 0xBF)) || ( // plane 16 bytes[0] == 0xF4 && (0x80 <= bytes[1] && bytes[1] <= 0x8F) && (0x80 <= bytes[2] && bytes[2] <= 0xBF) && (0x80 <= bytes[3] && bytes[3] <= 0xBF))) { bytes += 4; continue; } return false; } return true; } TrackFile Parser::playlistEntryToTrackFile(const QString &playlistEntry, const QString &basePath) { if (playlistEntry.startsWith("file:")) { // URLs are always absolute return TrackFile::fromUrl(QUrl(playlistEntry)); } auto filePath = QString(playlistEntry).replace('\\', '/'); auto trackFile = TrackFile(filePath); if (basePath.isEmpty() || trackFile.asFileInfo().isAbsolute()) { return trackFile; } else { // Fallback: Relative to base path return TrackFile(QDir(basePath), filePath); } }
4,108
C++
.cpp
126
25.246032
141
0.524565
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,594
parserm3u.cpp
missdeer_hannah/desktop/parser/parserm3u.cpp
// // C++ Implementation: parserm3u // // Description: module to parse m3u(plaintext) formatted playlists // // // Author: Ingo Kossyk <kossyki@cs.tu-berlin.de>, (C) 2004 // Author: Tobias Rafreider trafreider@mixxx.org, (C) 2011 // // Copyright: See COPYING file that comes with this distribution // // #include <QDir> #include <QMessageBox> #include <QTextCodec> #include <QUrl> #include <QtDebug> #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)) # include <QStringConverter> #endif #include "parserm3u.h" /** ToDo: - parse ALL information from the pls file if available , not only the filepath; Userinformation : The M3U format is just a headerless plaintext format where every line of text either represents a file location or a comment. comments are being preceded by a '#'. This parser will try to parse all file information from the given file and add the filepaths to the locations ptrlist when the file is existing locally or on a mounted harddrive. **/ QList<QString> ParserM3u::parse(const QString &sFilename) { clearLocations(); QFile file(sFilename); if (isBinary(sFilename) || !file.open(QIODevice::ReadOnly)) { qWarning() << "Failed to open playlist file" << sFilename; return m_sLocations; } // Unfortunately QTextStream does not handle <CR> (=\r or asci value 13) line breaks. // This is important on OS X where iTunes, e.g., exports M3U playlists using <CR> // rather that <LF>. // // Using QFile::readAll() we obtain the complete content of the playlist as a ByteArray. // We replace any '\r' with '\n' if applicaple // This ensures that playlists from iTunes on OS X can be parsed QByteArray ba = file.readAll(); // detect encoding bool isCRLF_encoded = ba.contains("\r\n"); bool isCR_encoded = ba.contains("\r"); if (isCR_encoded && !isCRLF_encoded) { ba.replace('\r', '\n'); } QTextStream textstream(ba.constData()); if (isUtf8(ba.constData())) { #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)) textstream.setEncoding(QStringConverter::Utf8); #else textstream.setCodec("UTF-8"); #endif } else { #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)) textstream.setEncoding(QStringConverter::Utf8); #else textstream.setCodec("windows-1252"); #endif } const auto basePath = sFilename.section('/', 0, -2); while (!textstream.atEnd()) { QString sLine = getFilePath(&textstream, basePath); if (sLine.isEmpty()) { continue; } m_sLocations.append(sLine); } return m_sLocations; } QString ParserM3u::getFilePath(QTextStream *stream, const QString &basePath) { QString textline; while (!(textline = stream->readLine().trimmed()).isEmpty()) { if (textline.startsWith("#")) { // Skip comments continue; } auto trackFile = playlistEntryToTrackFile(textline, basePath); if (trackFile.checkFileExists()) { return trackFile.location(); } // We couldn't match this to a real file so ignore it qWarning() << trackFile << "not found"; } // Signal we reached the end return QString(); } bool ParserM3u::writeM3UFile(const QString &file_str, const QList<QString> &items, bool useRelativePath) { return writeM3UFile(file_str, items, useRelativePath, false); } bool ParserM3u::writeM3U8File(const QString &file_str, const QList<QString> &items, bool useRelativePath) { return writeM3UFile(file_str, items, useRelativePath, true); } bool ParserM3u::writeM3UFile(const QString &file_str, const QList<QString> &items, bool useRelativePath, bool useUtf8) { // Important note: // On Windows \n will produce a <CR><CL> (=\r\n) // On Linux and OS X \n is <CR> (which remains \n) QTextCodec *codec = nullptr; if (useUtf8) { codec = QTextCodec::codecForName("UTF-8"); } else { // according to http://en.wikipedia.org/wiki/M3U the default encoding of m3u is Windows-1252 // see also http://tools.ietf.org/html/draft-pantos-http-live-streaming-07 // check if the all items can be properly encoded to Latin1. codec = QTextCodec::codecForName("windows-1252"); for (const auto & item : items) { if (!codec->canEncode(item)) { // filepath contains incompatible character QMessageBox::warning(nullptr, tr("Playlist Export Failed"), tr("File path contains characters, not allowed in m3u " "playlists.\n") + tr("Export a m3u8 playlist instead!\n") + item); return false; } } } QFile file(file_str); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { QMessageBox::warning(nullptr, tr("Playlist Export Failed"), tr("Could not create file") + " " + file_str); return false; } // Base folder of file QString base = file_str.section('/', 0, -2); QDir base_dir(base); qDebug() << "Basepath: " << base; QTextStream out(&file); #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) out.setCodec(codec); #else out.setEncoding(QStringConverter::Utf8); #endif out << "#EXTM3U\n"; for (const auto & item : items) { out << "#EXTINF\n"; // Write relative path if possible if (useRelativePath) { // QDir::relativePath() will return the absolutePath if it cannot compute the // relative Path out << base_dir.relativeFilePath(item) << "\n"; } else { out << item << "\n"; } } return true; }
5,968
C++
.cpp
180
26.472222
118
0.616811
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,595
parserpls.cpp
missdeer_hannah/desktop/parser/parserpls.cpp
// // C++ Implementation: parserpls // // Description: module to parse pls formatted playlists // // // Author: Ingo Kossyk <kossyki@cs.tu-berlin.de>, (C) 2004 // Author: Tobias Rafreider trafreider@mixxx.org, (C) 2011 // // Copyright: See COPYING file that comes with this distribution // // #include <QDir> #include <QFile> #include <QMessageBox> #include <QUrl> #include <QtDebug> #include "parserpls.h" /** ToDo: - parse ALL information from the pls file if available , not only the filepath; **/ QList<QString> ParserPls::parse(const QString &sFilename) { // long numEntries =0; QFile file(sFilename); const auto basePath = sFilename.section('/', 0, -2); clearLocations(); if (file.open(QIODevice::ReadOnly) && !isBinary(sFilename)) { /* Unfortunately, QT 4.7 does not handle <CR> (=\r or asci value 13) line breaks. * This is important on OS X where iTunes, e.g., exports M3U playlists using <CR> * rather that <LF> * * Using QFile::readAll() we obtain the complete content of the playlist as a ByteArray. * We replace any '\r' with '\n' if applicaple * This ensures that playlists from iTunes on OS X can be parsed */ QByteArray ba = file.readAll(); // detect encoding bool isCRLF_encoded = ba.contains("\r\n"); bool isCR_encoded = ba.contains("\r"); if (isCR_encoded && !isCRLF_encoded) { ba.replace('\r', '\n'); } QTextStream textstream(ba.constData()); while (!textstream.atEnd()) { QString psLine = getFilePath(&textstream, basePath); if (psLine.isNull()) { break; } m_sLocations.append(psLine); } file.close(); if (m_sLocations.count() != 0) { return m_sLocations; } return {}; // NULL pointer returned when no locations were found } file.close(); return {}; // if we get here something went wrong :D } long ParserPls::getNumEntries(QTextStream *stream) { QString textline; textline = stream->readLine(); if (textline.contains("[playlist]")) { while (!textline.contains("NumberOfEntries")) { textline = stream->readLine(); } QString temp = textline.section("=", -1, -1); return temp.toLong(); } qDebug() << "ParserPls: pls file is not a playlist! \n"; return 0; } QString ParserPls::getFilePath(QTextStream *stream, const QString &basePath) { QString textline = stream->readLine(); while (!textline.isEmpty()) { if (textline.isNull()) { break; } if (textline.contains("File")) { int iPos = textline.indexOf("=", 0); ++iPos; QString filename = textline.right(textline.length() - iPos); auto trackFile = playlistEntryToTrackFile(filename, basePath); if (trackFile.checkFileExists()) { return trackFile.location(); } // We couldn't match this to a real file so ignore it qWarning() << trackFile << "not found"; } textline = stream->readLine(); } // Signal we reached the end return {}; } bool ParserPls::writePLSFile(const QString &file_str, const QList<QString> &items, bool useRelativePath) { QFile file(file_str); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { QMessageBox::warning(nullptr, tr("Playlist Export Failed"), tr("Could not create file") + " " + file_str); return false; } // Base folder of file QString base = file_str.section('/', 0, -2); QDir base_dir(base); QTextStream out(&file); out << "[playlist]\n"; out << "NumberOfEntries=" << items.size() << "\n"; for (int i = 0; i < items.size(); ++i) { // Write relative path if possible if (useRelativePath) { // QDir::relativePath() will return the absolutePath if it cannot compute the // relative Path out << "File" << i << "=" << base_dir.relativeFilePath(items.at(i)) << "\n"; } else { out << "File" << i << "=" << items.at(i) << "\n"; } } return true; }
4,405
C++
.cpp
140
24.407143
114
0.578029
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,596
songlistmodel.cpp
missdeer_hannah/desktop/model/songlistmodel.cpp
#include "songlistmodel.h" SonglistModel::SonglistModel(QObject *parent) : QAbstractTableModel(parent) { } int SonglistModel::rowCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return m_songs.length(); } int SonglistModel::columnCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return 1; } QVariant SonglistModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (role != Qt::DisplayRole) return QVariant(); if (index.row() < 0 || index.row() >= m_songs.length()) return QVariant(); return QVariant(m_songs[index.row()]); } bool SonglistModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (data(index, role) != value) { // FIXME: Implement me! emit dataChanged(index, index, QVector<int>() << role); return true; } return false; } Qt::ItemFlags SonglistModel::flags(const QModelIndex &index) const { if (!index.isValid()) return Qt::NoItemFlags; return QAbstractItemModel::flags(index); } bool SonglistModel::insertRows(int row, int count, const QModelIndex &parent) { beginInsertRows(parent, row, row + count - 1); for (int i = row; i < row + count; i++) m_songs.insert(i, ""); endInsertRows(); return true; } bool SonglistModel::removeRows(int row, int count, const QModelIndex &parent) { beginRemoveRows(parent, row, row + count - 1); for (int i = row + count; i > row; i--) m_songs.removeAt(i - 1); endRemoveRows(); return true; } QVariant SonglistModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { QMap<int, QString> m = { {0, tr("URI")}, }; auto it = m.find(section); if (it != m.end()) return QVariant(it.value()); } return QVariant(); } void SonglistModel::setSongList(const QStringList &songs) { int rc = m_songs.length(); m_songs = songs; emit dataChanged(index(0, 0), index(rc - 1, 0)); } void SonglistModel::appendToSonglist(const QStringList &s) {} void SonglistModel::clearAndAddToSonglist(const QStringList &s) {} void SonglistModel::appendToSonglistFile(const QStringList &s) {} void SonglistModel::clearAndAddToSonglistFile(const QStringList &s) {} void SonglistModel::deleteSongs(QList<int> rows) {}
2,512
C++
.cpp
82
26.195122
92
0.66985
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,597
playlistmodel.cpp
missdeer_hannah/desktop/model/playlistmodel.cpp
#include "playlistmodel.h" PlaylistModel::PlaylistModel(QObject *parent) : QAbstractListModel(parent) { } int PlaylistModel::rowCount(const QModelIndex &parent) const { // For list models only the root node (an invalid parent) should return the list's size. For all // other (valid) parents, rowCount() should return 0 so that it does not become a tree model. if (parent.isValid()) { return 0; } return m_isFiltered ? m_filteredPlaylists.length() : m_playlists.length(); } QVariant PlaylistModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) { return {}; } if (role != Qt::DisplayRole) { return {}; } if (index.row() < 0 || index.row() >= rowCount()) { return {}; } if (m_isFiltered) { return m_filteredPlaylists[index.row()]; } return m_playlists[index.row()]; } bool PlaylistModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (data(index, role) != value) { // FIXME: Implement me! emit dataChanged(index, index, QVector<int>() << role); return true; } return false; } Qt::ItemFlags PlaylistModel::flags(const QModelIndex &index) const { if (!index.isValid()) { return Qt::NoItemFlags; } return m_isFiltered ? QAbstractListModel::flags(index) : Qt::ItemIsEditable; // FIXME: Implement me! } bool PlaylistModel::insertRows(int row, int count, const QModelIndex &parent) { beginInsertRows(parent, row, row + count - 1); for (int i = row; i < row + count; i++) { m_playlists.insert(i, ""); } endInsertRows(); return true; } bool PlaylistModel::removeRows(int row, int count, const QModelIndex &parent) { beginRemoveRows(parent, row, row + count - 1); for (int i = row + count; i > row; i--) { m_playlists.removeAt(i - 1); } endRemoveRows(); return true; } void PlaylistModel::setPlaylists(const QStringList &playlists) { int rc = m_playlists.length(); m_playlists = playlists; m_isFiltered = false; emit dataChanged(index(0, 0), index(rc - 1, 0)); } void PlaylistModel::addPlaylist() { int rc = rowCount(); insertRows(rc, 1); } void PlaylistModel::deletePlaylist(int row) { QString playlist = m_playlists[row]; m_playlists.removeAt(row); removeRows(row, 1); } void PlaylistModel::filterPlaylist(const QString &keyword) { int rc = rowCount(); m_filteredPlaylists.clear(); if (keyword.isEmpty()) { m_isFiltered = false; } else { m_isFiltered = true; for (const auto &s : m_playlists) { if (s.contains(keyword, Qt::CaseInsensitive)) { m_filteredPlaylists.append(s); } } } emit dataChanged(index(0, 0), index(rc - 1, 0)); } bool PlaylistModel::isFilteredPlaylists() const { return m_isFiltered; }
2,972
C++
.cpp
114
21.385965
104
0.637227
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,598
configurationwindow.cpp
missdeer_hannah/desktop/ui/configurationwindow.cpp
#include <QClipboard> #include <QCloseEvent> #include <QComboBox> #include <QCoreApplication> #include <QDesktopServices> #include <QEventLoop> #include <QFileDialog> #include <QMenu> #include <QMessageBox> #include <QNetworkAccessManager> #include <QNetworkInterface> #include <QProcess> #include <QQmlApplicationEngine> #include <QQuickStyle> #include <QSettings> #include <QStandardItem> #include <QStandardPaths> #if defined(Q_OS_WIN) # include <Windows.h> # include <shellapi.h> # include <tchar.h> # include "bassasio.h" # include "basswasapi.h" #endif #include "BeastServerRunner.h" #include "bass.h" #include "comboboxdelegate.h" #include "configurationwindow.h" #include "externalreverseproxyrunner.h" #include "playlistmanagewindow.h" #include "qmlplayer.h" #include "ui_configurationwindow.h" ConfigurationWindow::ConfigurationWindow(BeastServerRunner &runner, ExternalReverseProxyRunner &externalReverseProxyRunner, QWidget *parent) : QMainWindow(parent), ui(new Ui::ConfigurationWindow), m_builtinReverseProxyRunner(runner), m_externalReverseProxyRunner(externalReverseProxyRunner), m_nam(new QNetworkAccessManager(this)) { m_settings = new QSettings(QSettings::IniFormat, QSettings::UserScope, "minidump.info", "Hannah"); ui->setupUi(this); ui->cbOutputDevices->setItemDelegate(new ComboBoxDelegate); initNetworkInterfaces(); initOutputDevices(); bool ok = true; ui->externalPlayerPath->setText(m_settings->value("externalPlayerPath").toString()); ui->externalPlayerArguments->setText(m_settings->value("externalPlayerArguments").toString()); ui->externalPlayerWorkingDir->setText(m_settings->value("externalPlayerWorkingDir").toString()); ui->reverseProxyBindNetworkInterface->setCurrentText(m_settings->value("reverseProxyBindNetworkInterface", tr("-- Default --")).toString()); ui->reverseProxyProxyType->setCurrentText(m_settings->value("reverseProxyProxyType", tr("None")).toString()); ui->reverseProxyProxyAddress->setText(m_settings->value("reverseProxyProxyAddress").toString()); bool bUseExternalPlayer = m_settings->value("useExternalPlayer", false).toBool(); ui->useExternalPlayer->setChecked(bUseExternalPlayer); onUseExternalPlayerStateChanged(bUseExternalPlayer); ui->useBuiltinPlayer->setChecked(!bUseExternalPlayer); onUseBuiltinPlayerStateChanged(!bUseExternalPlayer); auto state = m_settings->value("reverseProxyAutoRedirect", 2).toInt(&ok); if (ok) { ui->reverseProxyAutoRedirect->setCheckState(static_cast<Qt::CheckState>(state)); } state = m_settings->value("reverseProxyRedirect", 2).toInt(&ok); if (ok) { ui->reverseProxyRedirect->setCheckState(static_cast<Qt::CheckState>(state)); } state = m_settings->value("useExternalReverseProxy", 2).toInt(&ok); if (ok) { ui->cbUseExternalReverseProxy->setCheckState(static_cast<Qt::CheckState>(state)); } ui->edtExternalReverseProxyPath->setText(m_settings->value("externalReverseProxyPath").toString()); auto port = m_settings->value("reverseProxyListenPort", 8090).toInt(&ok); if (ok) { ui->reverseProxyListenPort->setValue(port); } connect(ui->reverseProxyBindNetworkInterface, &QComboBox::currentTextChanged, this, &ConfigurationWindow::onReverseProxyBindNetworkInterfaceCurrentTextChanged); connect(ui->useBuiltinPlayer, &QRadioButton::toggled, this, &ConfigurationWindow::onUseBuiltinPlayerStateChanged); connect(ui->useExternalPlayer, &QRadioButton::toggled, this, &ConfigurationWindow::onUseExternalPlayerStateChanged); connect(ui->browseExternalPlayer, &QPushButton::clicked, this, &ConfigurationWindow::onBrowseExternalPlayerClicked); connect(ui->browseExternalPlayerWorkingDir, &QPushButton::clicked, this, &ConfigurationWindow::onBrowseExternalPlayerWorkingDirClicked); connect(ui->externalPlayerPath, &QLineEdit::textChanged, this, &ConfigurationWindow::onExternalPlayerPathTextChanged); connect(ui->externalPlayerArguments, &QLineEdit::textChanged, this, &ConfigurationWindow::onExternalPlayerArgumentsTextChanged); connect(ui->externalPlayerWorkingDir, &QLineEdit::textChanged, this, &ConfigurationWindow::onExternalPlayerWorkingDirTextChanged); connect( ui->reverseProxyListenPort, QOverload<int>::of(&QSpinBox::valueChanged), this, &ConfigurationWindow::onReverseProxyListenPortValueChanged); connect(ui->reverseProxyAutoRedirect, &QCheckBox::stateChanged, this, &ConfigurationWindow::onReverseProxyAutoRedirectStateChanged); connect(ui->reverseProxyRedirect, &QCheckBox::stateChanged, this, &ConfigurationWindow::onReverseProxyRedirectStateChanged); connect(ui->reverseProxyProxyType, &QComboBox::currentTextChanged, this, &ConfigurationWindow::onReverseProxyProxyTypeCurrentTextChanged); connect(ui->reverseProxyProxyAddress, &QLineEdit::textChanged, this, &ConfigurationWindow::onReverseProxyProxyAddressTextChanged); connect(ui->cbUseExternalReverseProxy, &QCheckBox::stateChanged, this, &ConfigurationWindow::onUseExternalReverseProxyStateChanged); connect(ui->btnBrowseExternalReverseProxy, &QPushButton::clicked, this, &ConfigurationWindow::onBrowseExternalReverseProxy); connect(ui->edtExternalReverseProxyPath, &QLineEdit::textChanged, this, &ConfigurationWindow::onExternalReverseProxyPathChanged); auto *clipboard = QGuiApplication::clipboard(); connect(clipboard, &QClipboard::dataChanged, this, &ConfigurationWindow::onGlobalClipboardChanged); auto *configAction = new QAction(tr("&Configuration"), this); connect(configAction, &QAction::triggered, this, &ConfigurationWindow::onShowConfiguration); auto *showHidePlayerAction = new QAction(tr("Show/Hide &Player"), this); connect(showHidePlayerAction, &QAction::triggered, this, &ConfigurationWindow::onShowHideBuiltinPlayer); auto *playlistManageAction = new QAction(tr("Playlist Manage"), this); connect(playlistManageAction, &QAction::triggered, this, &ConfigurationWindow::onShowPlaylistManage); auto *quitAction = new QAction(tr("&Quit"), this); connect(quitAction, &QAction::triggered, qApp, &QCoreApplication::quit); m_trayIconMenu = new QMenu(this); m_trayIconMenu->addAction(tr("Netease"), []() { QDesktopServices::openUrl(QUrl("https://music.163.com")); }); m_trayIconMenu->addAction(tr("QQ"), []() { QDesktopServices::openUrl(QUrl("https://y.qq.com")); }); m_trayIconMenu->addAction(tr("Migu"), []() { QDesktopServices::openUrl(QUrl("https://music.migu.cn/v3")); }); m_trayIconMenu->addAction(tr("Kugou"), []() { QDesktopServices::openUrl(QUrl("https://www.kugou.com")); }); m_trayIconMenu->addAction(tr("Kuwo"), []() { QDesktopServices::openUrl(QUrl("http://kuwo.cn")); }); m_trayIconMenu->addSeparator(); m_trayIconMenu->addAction(configAction); m_trayIconMenu->addAction(showHidePlayerAction); m_trayIconMenu->addAction(playlistManageAction); m_trayIconMenu->addAction(quitAction); m_trayIcon = new QSystemTrayIcon(this); m_trayIcon->setContextMenu(m_trayIconMenu); m_trayIcon->setIcon(QIcon(":/hannah.png")); m_trayIcon->show(); connect(m_trayIcon, &QSystemTrayIcon::activated, this, &ConfigurationWindow::onSystemTrayIconActivated); } ConfigurationWindow::~ConfigurationWindow() { delete m_nam; m_settings->sync(); delete m_settings; delete ui; } void ConfigurationWindow::onSearch(const QString &s) { Q_UNUSED(s); } void ConfigurationWindow::onOpenUrl(const QString &s) { openLink(s); } void ConfigurationWindow::onOpenLink(const QString &s) { openLink(s); } void ConfigurationWindow::closeEvent(QCloseEvent *event) { #if defined(Q_OS_MACOS) if (!event->spontaneous() || !isVisible()) { return; } #endif if (m_trayIcon->isVisible()) { hide(); event->ignore(); } } void ConfigurationWindow::onOpenUrl(const QUrl &url) { onApplicationMessageReceived(url.toString()); } void ConfigurationWindow::onApplicationMessageReceived(const QString &message) { const QString &u = message; QString pattern = "hannah://play"; if (u.startsWith(pattern)) { auto index = u.indexOf("url="); if (index > pattern.length()) { auto url = u.mid(index + 4); handle(url, false); } } } void ConfigurationWindow::onUseBuiltinPlayerStateChanged(bool checked) { ui->cbOutputDevices->setEnabled(checked); } void ConfigurationWindow::onUseExternalPlayerStateChanged(bool checked) { ui->externalPlayerArguments->setEnabled(checked); ui->externalPlayerPath->setEnabled(checked); ui->externalPlayerWorkingDir->setEnabled(checked); ui->browseExternalPlayer->setEnabled(checked); ui->browseExternalPlayerWorkingDir->setEnabled(checked); Q_ASSERT(m_settings); m_settings->setValue("useExternalPlayer", checked); m_settings->sync(); } void ConfigurationWindow::onExternalPlayerPathTextChanged(const QString &text) { Q_ASSERT(m_settings); m_settings->setValue("externalPlayerPath", text); if (ui->externalPlayerWorkingDir->text().isEmpty()) { QFileInfo fi(text); if (fi.isAbsolute() && fi.isFile() && fi.exists()) { ui->externalPlayerWorkingDir->setText(fi.absolutePath()); } } m_settings->sync(); } void ConfigurationWindow::onBrowseExternalPlayerClicked() { QString fn = QFileDialog::getOpenFileName(this, tr("External Player")); ui->externalPlayerPath->setText(fn); } void ConfigurationWindow::onExternalPlayerArgumentsTextChanged(const QString &text) { Q_ASSERT(m_settings); m_settings->setValue("externalPlayerArguments", text); m_settings->sync(); } void ConfigurationWindow::onExternalPlayerWorkingDirTextChanged(const QString &text) { Q_ASSERT(m_settings); m_settings->setValue("externalPlayerWorkingDir", text); m_settings->sync(); } void ConfigurationWindow::onBrowseExternalPlayerWorkingDirClicked() { QString dir = QFileDialog::getExistingDirectory(this, tr("Working Directory")); ui->externalPlayerWorkingDir->setText(dir); } void ConfigurationWindow::initOutputDevices() { auto *model = new QStandardItemModel; auto *item = new QStandardItem(tr("Default Driver")); item->setFlags(item->flags() & ~(Qt::ItemIsEnabled | Qt::ItemIsSelectable)); item->setData("parent", Qt::AccessibleDescriptionRole); QFont font = item->font(); font.setBold(true); item->setFont(font); model->appendRow(item); BASS_DEVICEINFO info; for (int deviceIndex = 1; BASS_GetDeviceInfo(deviceIndex, &info); deviceIndex++) { if (info.flags & BASS_DEVICE_ENABLED) { auto *item = new QStandardItem(QString::fromUtf8(info.name) + QString(4, QChar(' '))); item->setData("child", Qt::AccessibleDescriptionRole); model->appendRow(item); } } #if defined(Q_OS_WIN) BASS_ASIO_DEVICEINFO asioinfo; for (int deviceIndex = 0; BASS_ASIO_GetDeviceInfo(deviceIndex, &asioinfo); deviceIndex++) { if (deviceIndex == 0) { item = new QStandardItem("ASIO"); item->setFlags(item->flags() & ~(Qt::ItemIsEnabled | Qt::ItemIsSelectable)); item->setData("parent", Qt::AccessibleDescriptionRole); font.setBold(true); item->setFont(font); model->appendRow(item); } auto *item = new QStandardItem(QString::fromUtf8(asioinfo.name) + QString(4, QChar(' '))); item->setData("child", Qt::AccessibleDescriptionRole); model->appendRow(item); } BASS_WASAPI_DEVICEINFO wasapiinfo; for (int deviceIndex = 0; BASS_WASAPI_GetDeviceInfo(deviceIndex, &wasapiinfo); deviceIndex++) { if (deviceIndex == 0) { item = new QStandardItem("WASAPI"); item->setFlags(item->flags() & ~(Qt::ItemIsEnabled | Qt::ItemIsSelectable)); item->setData("parent", Qt::AccessibleDescriptionRole); font.setBold(true); item->setFont(font); model->appendRow(item); } if (!(wasapiinfo.flags & BASS_DEVICE_INPUT) // device is an output device (not input) && (wasapiinfo.flags & BASS_DEVICE_ENABLED)) // and it is enabled { auto *item = new QStandardItem(QString::fromUtf8(wasapiinfo.name) + QString(4, QChar(' '))); item->setData("child", Qt::AccessibleDescriptionRole); model->appendRow(item); } } #endif ui->cbOutputDevices->setModel(model); } void ConfigurationWindow::initNetworkInterfaces() { auto interfaces = QNetworkInterface::allInterfaces(); for (const auto &networkInterface : interfaces) { if (networkInterface.type() == QNetworkInterface::Ethernet || networkInterface.type() == QNetworkInterface::Wifi || networkInterface.type() == QNetworkInterface::Ppp) { ui->reverseProxyBindNetworkInterface->addItem(networkInterface.humanReadableName()); } } } void ConfigurationWindow::restartReverseProxy() { if (m_settings->value("useExternalReverseProxy", 2).toInt() == Qt::Checked) { m_externalReverseProxyRunner.stop(); m_externalReverseProxyRunner.start(); } else { m_builtinReverseProxyRunner.stop(); m_builtinReverseProxyRunner.wait(); m_builtinReverseProxyRunner.start(); } } void ConfigurationWindow::onReverseProxyListenPortValueChanged(int port) { Q_ASSERT(m_settings); m_settings->setValue("reverseProxyListenPort", port); m_settings->sync(); restartReverseProxy(); } void ConfigurationWindow::onReverseProxyBindNetworkInterfaceCurrentTextChanged(const QString &text) { Q_ASSERT(m_settings); m_settings->setValue("reverseProxyBindNetworkInterface", text); m_settings->sync(); restartReverseProxy(); } void ConfigurationWindow::onReverseProxyAutoRedirectStateChanged(int state) { Q_ASSERT(m_settings); m_settings->setValue("reverseProxyAutoRedirect", state); m_settings->sync(); restartReverseProxy(); } void ConfigurationWindow::onReverseProxyRedirectStateChanged(int state) { Q_ASSERT(m_settings); m_settings->setValue("reverseProxyRedirect", state); m_settings->sync(); restartReverseProxy(); } void ConfigurationWindow::onReverseProxyProxyTypeCurrentTextChanged(const QString &text) { Q_ASSERT(m_settings); m_settings->setValue("reverseProxyProxyType", text); m_settings->sync(); restartReverseProxy(); } void ConfigurationWindow::onReverseProxyProxyAddressTextChanged(const QString &text) { Q_ASSERT(m_settings); m_settings->setValue("reverseProxyProxyAddress", text); m_settings->sync(); restartReverseProxy(); } void ConfigurationWindow::openLink(const QString &text) { static const QVector<QRegularExpression> patterns = { QRegularExpression(R"(^https?:\/\/music\.163\.com\/(?:#\/)?discover\/toplist\?id=(\d+))"), QRegularExpression(R"(^https?:\/\/music\.163\.com\/(?:#\/)?playlist\?id=(\d+))"), QRegularExpression(R"(^https?:\/\/music\.163\.com\/(?:#\/)?my\/m\/music\/playlist\?id=(\d+))"), QRegularExpression(R"(^https?:\/\/y\.qq\.com\/n\/yqq\/playlist\/(\d+)\.html)"), QRegularExpression(R"(^https?:\/\/www\.kugou\.com\/yy\/special\/single\/(\d+)\.html)"), QRegularExpression(R"(^https?:\/\/(?:www\.)?kuwo\.cn\/playlist_detail\/(\d+))"), QRegularExpression(R"(^https?:\/\/music\.migu\.cn\/v3\/music\/playlist\/(\d+))"), QRegularExpression(R"(^https?:\/\/music\.163\.com\/(?:#\/)?song\?id=(\d+))"), QRegularExpression(R"(^https?:\/\/y\.qq\.com/n\/yqq\/song\/(\w+)\.html)"), QRegularExpression(R"(^https?:\/\/www\.kugou\.com\/song\/#hash=([0-9A-F]+))"), QRegularExpression(R"(^https?:\/\/(?:www\.)kuwo.cn\/play_detail\/(\d+))"), QRegularExpression(R"(^https?:\/\/music\.migu\.cn\/v3\/music\/song\/(\d+))"), QRegularExpression(R"(^https?:\/\/music\.163\.com\/weapi\/v1\/artist\/(\d+))"), QRegularExpression(R"(^https?:\/\/music\.163\.com\/(?:#\/)?artist\?id=(\d+))"), QRegularExpression(R"(^https?:\/\/y\.qq\.com\/n\/yqq\/singer\/(\w+)\.html)"), QRegularExpression(R"(^https?:\/\/(?:www\.)?kuwo\.cn\/singer_detail\/(\d+))"), QRegularExpression(R"(^https?:\/\/music\.migu\.cn\/v3\/music\/artist\/(\d+))"), QRegularExpression(R"(^https?:\/\/music\.163\.com\/weapi\/v1\/album\/(\d+))"), QRegularExpression(R"(^https?:\/\/music\.163\.com\/(?:#\/)?album\?id=(\d+))"), QRegularExpression(R"(^https?:\/\/y\.qq\.com\/n\/yqq\/album\/(\w+)\.html)"), QRegularExpression(R"(^https?:\/\/(?:www\.)?kuwo\.cn\/album_detail\/(\d+))"), QRegularExpression(R"(^https?:\/\/music\.migu\.cn\/v3\/music\/album\/(\d+))")}; auto iter = std::find_if(patterns.begin(), patterns.end(), [&text](const auto &r) { return r.match(text).hasMatch(); }); if (patterns.end() != iter) { handle(QString(QUrl::toPercentEncoding(text)), true); } } void ConfigurationWindow::onGlobalClipboardChanged() { auto *clipboard = QGuiApplication::clipboard(); auto text = clipboard->text(); openLink(text); } void ConfigurationWindow::onReplyError(QNetworkReply::NetworkError code) { Q_UNUSED(code); #if !defined(QT_NO_DEBUG) auto *reply = qobject_cast<QNetworkReply *>(sender()); Q_ASSERT(reply); qDebug() << reply->errorString(); #endif } void ConfigurationWindow::onReplyFinished() { auto *reply = qobject_cast<QNetworkReply *>(sender()); reply->deleteLater(); #if !defined(QT_NO_DEBUG) qDebug() << " finished: " << QString(m_playlistContent).left(256) << "\n"; #endif auto fn = QStandardPaths::writableLocation(QStandardPaths::TempLocation) + "/hannah.m3u"; if (m_playlistContent.isEmpty()) { QFile::remove(fn); return; } QFile f(fn); if (f.open(QIODevice::WriteOnly | QIODevice::Truncate)) { f.write(m_playlistContent); f.close(); } } void ConfigurationWindow::onReplySslErrors(const QList<QSslError> & #if !defined(QT_NO_DEBUG) errors #endif ) { #if !defined(QT_NO_DEBUG) for (const auto &e : errors) { qDebug() << "ssl error:" << e.errorString(); } #endif } void ConfigurationWindow::onReplyReadyRead() { auto *reply = qobject_cast<QNetworkReply *>(sender()); int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (statusCode >= 200 && statusCode < 300) { m_playlistContent.append(reply->readAll()); } } void ConfigurationWindow::onSystemTrayIconActivated(QSystemTrayIcon::ActivationReason reason) { if (reason == QSystemTrayIcon::DoubleClick) { onShowConfiguration(); } } void ConfigurationWindow::onShowConfiguration() { if (isHidden()) { showNormal(); } activateWindow(); raise(); } void ConfigurationWindow::onShowPlaylistManage() { if (playlistManageWindow->isHidden()) { playlistManageWindow->showNormal(); } playlistManageWindow->activateWindow(); playlistManageWindow->raise(); } void ConfigurationWindow::onShowHideBuiltinPlayer() { gQmlPlayer->showNormal(); } void ConfigurationWindow::handle(const QString &url, bool needConfirm) { auto player = QDir::toNativeSeparators(ui->externalPlayerPath->text()); auto arguments = ui->externalPlayerArguments->text(); auto workingDir = QDir::toNativeSeparators(ui->externalPlayerWorkingDir->text()); QFileInfo fi(player); if (!fi.exists()) { if (!needConfirm) { QMessageBox::critical(this, tr("Error"), tr("External player path not configured properly")); } return; } m_playlistContent.clear(); QNetworkRequest req(QUrl::fromUserInput(QString("http://localhost:%1/m3u/generate?u=").arg(ui->reverseProxyListenPort->value()) + url)); auto *reply = m_nam->get(req); connect(reply, &QNetworkReply::finished, this, &ConfigurationWindow::onReplyFinished); connect(reply, &QNetworkReply::readyRead, this, &ConfigurationWindow::onReplyReadyRead); connect(reply, &QNetworkReply::errorOccurred, this, &ConfigurationWindow::onReplyError); connect(reply, &QNetworkReply::sslErrors, this, &ConfigurationWindow::onReplySslErrors); QEventLoop loop; QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit); loop.exec(); auto localTempPlaylist = QDir::toNativeSeparators(QStandardPaths::writableLocation(QStandardPaths::TempLocation) + "/hannah.m3u"); if (!QFile::exists(localTempPlaylist)) { QMessageBox::critical(this, tr("Error"), tr("Can't get song(s), maybe VIP is requested.")); return; } if (needConfirm && QMessageBox::question(this, tr("Confirm"), tr("Play song(s) by %1?").arg(player), QMessageBox::Ok | QMessageBox::Cancel) != QMessageBox::Ok) { return; } #if defined(Q_OS_MACOS) if (fi.isBundle() && player.endsWith(".app")) { auto script = QString("tell application \"%1\" to open \"%2\"").arg(player, localTempPlaylist); QProcess::startDetached("/usr/bin/osascript", {"-e", script}, workingDir); return; } else { QFile f(":/rc/runInTerminal.app.scpt"); if (f.open(QIODevice::ReadOnly)) { auto data = f.readAll(); f.close(); auto runInTerminalScriptPath = QStandardPaths::writableLocation(QStandardPaths::TempLocation) + "/runInTerminal.app.scpt"; QFile tf(runInTerminalScriptPath); if (tf.open(QIODevice::WriteOnly)) { tf.write(data); tf.close(); QStringList args = {QDir::toNativeSeparators(runInTerminalScriptPath), QString("\"%1\" %2 \"%3\"").arg(player, arguments, localTempPlaylist)}; QProcess::startDetached("/usr/bin/osascript", args, workingDir); return; } } } #elif defined(Q_OS_WIN) auto args = arguments.split(" "); args << localTempPlaylist; args.removeAll(""); ::ShellExecuteW((HWND)winId(), L"open", (const wchar_t *)player.utf16(), (const wchar_t *)args.join(" ").utf16(), (const wchar_t *)workingDir.utf16(), SW_SHOWNORMAL); return; #else #endif auto argv = arguments.split(" "); argv << localTempPlaylist; argv.removeAll(""); QProcess::startDetached(player, argv, workingDir); } void ConfigurationWindow::onBrowseExternalReverseProxy() { QString filePath = QFileDialog::getOpenFileName(this, tr("Find Reverse Proxy")); if (filePath.isEmpty() || !QFile::exists(filePath)) { return; } ui->edtExternalReverseProxyPath->setText(filePath); } void ConfigurationWindow::onUseExternalReverseProxyStateChanged(int state) { Q_ASSERT(m_settings); m_settings->setValue("useExternalReverseProxy", state); m_settings->sync(); } void ConfigurationWindow::onExternalReverseProxyPathChanged(const QString &text) { Q_ASSERT(m_settings); m_settings->setValue("externalReverseProxyPath", text); m_settings->sync(); }
23,570
C++
.cpp
572
35.727273
148
0.691925
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,599
playlistmanagewindow.cpp
missdeer_hannah/desktop/ui/playlistmanagewindow.cpp
#include <QCloseEvent> #include <QDir> #include <QFile> #include <QFileDialog> #include <QInputDialog> #include <QRegularExpression> #include <QStandardPaths> #include <map> #include "playlistmanagewindow.h" #include "playlistmodel.h" #include "songlistmodel.h" #include "Sqlite3Helper.h" #include "ui_playlistmanagewindow.h" PlaylistManageWindow::PlaylistManageWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::PlaylistManageWindow) { ui->setupUi(this); ui->lstPlaylist->setModel(m_playlistModel); ui->tblSongs->setModel(m_songlistModel); QString fn = QDir::toNativeSeparators(QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + "/default.hpls"); if (QFile::exists(fn)) { } else { } } PlaylistManageWindow::~PlaylistManageWindow() { delete ui; } void PlaylistManageWindow::closeEvent(QCloseEvent *event) { #if defined(Q_OS_MACOS) if (!event->spontaneous() || !isVisible()) { return; } #endif hide(); event->ignore(); } void PlaylistManageWindow::onAppendToPlaylist(const QStringList &s) { Q_ASSERT(m_playlistModel); Q_ASSERT(m_songlistModel); m_songlistModel->appendToSonglist(s); } void PlaylistManageWindow::onClearAndAddToPlaylist(const QStringList &s) { Q_ASSERT(m_playlistModel); Q_ASSERT(m_songlistModel); m_songlistModel->clearAndAddToSonglist(s); } void PlaylistManageWindow::onAppendToPlaylistFile(const QStringList &s) { Q_ASSERT(m_playlistModel); Q_ASSERT(m_songlistModel); m_songlistModel->appendToSonglistFile(s); } void PlaylistManageWindow::onClearAndAddToPlaylistFile(const QStringList &s) { Q_ASSERT(m_playlistModel); Q_ASSERT(m_songlistModel); m_songlistModel->clearAndAddToSonglistFile(s); } void PlaylistManageWindow::on_edtPlaylistFilter_textChanged(const QString &s) { Q_ASSERT(m_playlistModel); m_playlistModel->filterPlaylist(s); bool isFiltered = m_playlistModel->isFilteredPlaylists(); ui->btnAddPlaylist->setEnabled(!isFiltered); ui->btnDeletePlaylist->setEnabled(!isFiltered); ui->btnImportPlaylist->setEnabled(!isFiltered); ui->btnExportPlaylist->setEnabled(!isFiltered); } void PlaylistManageWindow::on_tblSongs_activated(const QModelIndex &index) { Q_ASSERT(m_songlistModel); } void PlaylistManageWindow::on_btnAddPlaylist_clicked(bool) { Q_ASSERT(m_playlistModel); m_playlistModel->addPlaylist(); } void PlaylistManageWindow::on_btnDeletePlaylist_clicked(bool) { auto *model = ui->lstPlaylist->selectionModel(); if (model->hasSelection()) { Q_ASSERT(m_playlistModel); auto selections = model->selectedRows(); for (const auto &selection : selections) { m_playlistModel->deletePlaylist(selection.row()); } } } void PlaylistManageWindow::on_btnImportPlaylist_clicked(bool) { QString fn = QFileDialog::getOpenFileName(this, tr("Import playlist"), "", tr("Playlist (*.m3u *.m3u8)")); Q_ASSERT(m_playlistModel); } void PlaylistManageWindow::on_btnExportPlaylist_clicked(bool) { QString fn = QFileDialog::getSaveFileName(this, tr("Export playlist"), "", tr("Playlist (*.m3u)")); Q_ASSERT(m_playlistModel); } void PlaylistManageWindow::on_btnAddSongs_clicked(bool) { QString lines = QInputDialog::getMultiLineText(this, tr("Add song(s)"), tr("Input song url, one url per line:")); if (!lines.isEmpty()) { Q_ASSERT(m_songlistModel); m_songlistModel->appendToSonglist(lines.split(QRegularExpression("\n|\r\n|\r"))); } } void PlaylistManageWindow::on_btnDeleteSongs_clicked(bool) { auto *model = ui->tblSongs->selectionModel(); if (model->hasSelection()) { QList<int> rows; auto selections = model->selectedRows(); for (const auto &selection : selections) { rows.append(selection.row()); } Q_ASSERT(m_songlistModel); m_songlistModel->deleteSongs(rows); } } void PlaylistManageWindow::on_btnImportSongs_clicked(bool) { QStringList songs = QFileDialog::getOpenFileNames( this, tr("Import song(s)"), "", tr("Songs (*.m3u *.m3u8 *.mp1 *.mp2 *.mp3 *.wav *.ogg *.ape *.flac *.m4a *.aac *.caf *.wma *.opus)")); Q_ASSERT(m_songlistModel); } void PlaylistManageWindow::createDataTables() { std::map<QString, QString> tablesCreationMap = { {"playlist", "CREATE TABLE IF NOT EXISTS playlist(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT);"}, {"song", "CREATE TABLE IF NOT EXISTS song(id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT);"}, {"playlist_song_map", "CREATE TABLE IF NOT EXISTS playlist_song_map(id INTEGER PRIMARY KEY AUTOINCREMENT, playlist INTEGER, song INTEGER);"}}; std::map<QString, QString> tablesMap = {{"table", "playlist"}, {"table", "song"}, {"table", "playlist_song_map"}}; }
4,887
C++
.cpp
147
29.238095
150
0.71574
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,600
qmldialog.cpp
missdeer_hannah/desktop/ui/qmldialog.cpp
#include <QQmlEngine> #include <QQmlContext> #include "qmldialog.h" #include "ui_qmldialog.h" QmlDialog::QmlDialog(QWidget *parent) : QDialog(parent), ui(new Ui::QmlDialog) { ui->setupUi(this); ui->quickWidget->setAttribute(Qt::WA_TranslucentBackground, true); ui->quickWidget->setAttribute(Qt::WA_AlwaysStackOnTop, true); ui->quickWidget->setClearColor(Qt::transparent); ui->quickWidget->setResizeMode(QQuickWidget::SizeRootObjectToView); ui->quickWidget->engine()->addImportPath("qrc:/rc/qml"); } QmlDialog::~QmlDialog() { delete ui; } void QmlDialog::doClose() { QDialog::accept(); } void QmlDialog::loadQml(const QUrl &u) { ui->quickWidget->setSource(u); } QQmlEngine *QmlDialog::engine() { return ui->quickWidget->engine(); } QQmlContext *QmlDialog::context() { return ui->quickWidget->engine()->rootContext(); }
876
C++
.cpp
35
22.371429
71
0.729341
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,602
networkreplyhelper.cpp
missdeer_hannah/desktop/network/networkreplyhelper.cpp
#include <zlib.h> #include <QEventLoop> #include <QIODevice> #include <QJsonDocument> #include <QJsonParseError> #include <QTimer> #include "networkreplyhelper.h" static QByteArray gUncompress(const QByteArray &data) { if (data.size() <= 4) { qWarning("gUncompress: Input data is truncated"); return data; } QByteArray result; int ret = 0; z_stream strm; static const int CHUNK_SIZE = 1024; char out[CHUNK_SIZE]; /* allocate inflate state */ strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.avail_in = data.size(); strm.next_in = (Bytef *)(data.data()); ret = inflateInit2(&strm, 15 + 32); // gzip decoding if (ret != Z_OK) { return data; } // run inflate() do { strm.avail_out = CHUNK_SIZE; strm.next_out = (Bytef *)(out); ret = inflate(&strm, Z_NO_FLUSH); Q_ASSERT(ret != Z_STREAM_ERROR); // state not clobbered switch (ret) { case Z_NEED_DICT: ret = Z_DATA_ERROR; // and fall through case Z_DATA_ERROR: case Z_MEM_ERROR: (void)inflateEnd(&strm); return data; } result.append(out, CHUNK_SIZE - strm.avail_out); } while (strm.avail_out == 0); // clean up and return inflateEnd(&strm); return result; } NetworkReplyHelper::NetworkReplyHelper(QNetworkReply *reply, QByteArray *content, QObject *parent) : QObject(parent), m_reply(reply), m_content(content) { Q_ASSERT(reply); connect(reply, &QNetworkReply::downloadProgress, this, &NetworkReplyHelper::downloadProgress); #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) connect(reply, &QNetworkReply::errorOccurred, this, &NetworkReplyHelper::error); #else connect(reply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), this, &NetworkReplyHelper::error); #endif connect(reply, &QNetworkReply::finished, this, &NetworkReplyHelper::finished); connect(reply, &QNetworkReply::sslErrors, this, &NetworkReplyHelper::sslErrors); connect(reply, &QNetworkReply::uploadProgress, this, &NetworkReplyHelper::uploadProgress); connect(reply, &QNetworkReply::readyRead, this, &NetworkReplyHelper::readyRead); if (!m_content) { m_content = new QByteArray; m_ownContentObject = true; } } NetworkReplyHelper::NetworkReplyHelper(QNetworkReply *reply, QIODevice *storage, QObject *parent) : QObject(parent), m_reply(reply), m_storage(storage) { Q_ASSERT(reply); connect(reply, &QNetworkReply::downloadProgress, this, &NetworkReplyHelper::downloadProgress); #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) connect(reply, &QNetworkReply::errorOccurred, this, &NetworkReplyHelper::error); #else connect(reply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), this, &NetworkReplyHelper::error); #endif connect(reply, &QNetworkReply::finished, this, &NetworkReplyHelper::finished); connect(reply, &QNetworkReply::sslErrors, this, &NetworkReplyHelper::sslErrors); connect(reply, &QNetworkReply::uploadProgress, this, &NetworkReplyHelper::uploadProgress); connect(reply, &QNetworkReply::readyRead, this, &NetworkReplyHelper::readyRead); if (!m_storage) { m_content = new QByteArray; m_ownContentObject = true; } } NetworkReplyHelper::~NetworkReplyHelper() { if (m_reply) { m_reply->disconnect(this); m_reply->deleteLater(); m_reply = nullptr; } if (m_timeoutTimer) { if (m_timeoutTimer->isActive()) { m_timeoutTimer->stop(); } delete m_timeoutTimer; m_timeoutTimer = nullptr; } if (m_ownContentObject) { delete m_content; m_content = nullptr; } } QJsonDocument NetworkReplyHelper::json() { QJsonParseError err {}; QJsonDocument jsonDocument = QJsonDocument::fromJson(*m_content, &err); if (err.error == QJsonParseError::NoError) { return jsonDocument; } return {}; } void NetworkReplyHelper::waitForFinished() { QEventLoop loop; QObject::connect(m_reply, &QNetworkReply::finished, &loop, &QEventLoop::quit); loop.exec(); QObject::disconnect(m_reply, &QNetworkReply::finished, &loop, &QEventLoop::quit); } void NetworkReplyHelper::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) { #if defined(NETWORK_LOG) qDebug() << __FUNCTION__ << __LINE__ << bytesReceived << bytesTotal; #else Q_UNUSED(bytesReceived); Q_UNUSED(bytesTotal); #endif if (m_timeoutTimer && m_timeoutTimer->isActive()) { m_timeoutTimer->start(); } } void NetworkReplyHelper::error(QNetworkReply::NetworkError code) { m_error = code; auto *reply = qobject_cast<QNetworkReply *>(sender()); m_errMsg.append(reply->errorString() + "\n"); #if defined(NETWORK_LOG) qCritical() << __FUNCTION__ << __LINE__ << m_errMsg; #endif emit errorMessage(code, m_errMsg); } void NetworkReplyHelper::finished() { if (m_timeoutTimer) { m_timeoutTimer->stop(); } auto *reply = qobject_cast<QNetworkReply *>(sender()); auto contentEncoding = reply->rawHeader("Content-Encoding"); #if defined(NETWORK_LOG) auto headerList = reply->rawHeaderList(); for (const auto &header : headerList) { qDebug() << __FUNCTION__ << __LINE__ << QString(header) << ":" << QString(reply->rawHeader(header)); } qDebug() << __FUNCTION__ << __LINE__ << contentEncoding << m_content->length() << "bytes received"; #endif readData(reply); if (contentEncoding == "gzip" || contentEncoding == "deflate") { auto content = gUncompress(*m_content); if (m_storage) { m_storage->write(content); } if (!content.isEmpty()) { m_content->swap(content); } } #if defined(NETWORK_LOG) qDebug() << __FUNCTION__ << __LINE__ << m_content->length() << "bytes uncompressed: " << QString(*m_content).left(256) << "\n"; #endif postFinished(); } void NetworkReplyHelper::sslErrors(const QList<QSslError> &errors) { for (const auto &err : errors) { #if defined(NETWORK_LOG) qCritical() << __FUNCTION__ << __LINE__ << err.errorString(); #endif m_errMsg.append(err.errorString() + "\n"); } } void NetworkReplyHelper::uploadProgress(qint64 bytesSent, qint64 bytesTotal) { Q_UNUSED(bytesSent); Q_UNUSED(bytesTotal); if (m_timeoutTimer && m_timeoutTimer->isActive()) { m_timeoutTimer->start(); } } void NetworkReplyHelper::readyRead() { auto *reply = qobject_cast<QNetworkReply *>(sender()); #if defined(NETWORK_LOG) int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); qDebug() << __FUNCTION__ << __LINE__ << statusCode << reply; #endif // if (statusCode >= 200 && statusCode < 300) { readData(reply); } } void NetworkReplyHelper::timeout() { #if defined(NETWORK_LOG) qDebug() << __FUNCTION__ << __LINE__; #endif if (m_reply && m_reply->isRunning()) { m_reply->abort(); } } void NetworkReplyHelper::readData(QNetworkReply *reply) { auto resp = receivedData(reply->readAll()); auto contentEncoding = reply->rawHeader("Content-Encoding"); #if defined(NETWORK_LOG) qDebug() << __FUNCTION__ << __LINE__ << contentEncoding << resp.length() << QString(resp); #endif if (contentEncoding != "gzip" && contentEncoding != "deflate") { if (m_storage) { m_storage->write(resp); } } m_content->append(resp); } QVariant NetworkReplyHelper::data() const { return m_data; } void NetworkReplyHelper::setData(const QVariant &data) { m_data = data; } void NetworkReplyHelper::setTimeout(int milliseconds) { if (!m_reply->isRunning()) { return; } if (!m_timeoutTimer) { m_timeoutTimer = new QTimer; m_timeoutTimer->setSingleShot(true); connect(m_timeoutTimer, &QTimer::timeout, this, &NetworkReplyHelper::timeout); } m_timeoutTimer->start(milliseconds); } const QString &NetworkReplyHelper::getErrorMessage() const { return m_errMsg; } QNetworkReply *NetworkReplyHelper::reply() { return m_reply; } QIODevice *NetworkReplyHelper::storage() { return m_storage; } QByteArray &NetworkReplyHelper::content() { return *m_content; } bool NetworkReplyHelper::isOk() const { return m_error == QNetworkReply::NoError; } void NetworkReplyHelper::postFinished() { emit done(); } void NetworkReplyHelper::setErrorMessage(const QString &errMsg) { m_errMsg = errMsg; } QByteArray NetworkReplyHelper::receivedData(QByteArray data) { return data; }
8,939
C++
.cpp
300
25.176667
143
0.656465
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,603
BassWinamp.h
missdeer_hannah/output/bass/include/BassWinamp.h
#ifndef BASSWINAMP_H #define BASSWINAMP_H #include <bass.h> #ifdef __cplusplus extern "C" { #endif #ifndef BASSWINAMPDEF #define BASSWINAMPDEF(f) WINAPI f #endif #define BASS_CTYPE_STREAM_WINAMP 0x10400 #define BASS_WINAMP_SYNC_BITRATE 100 // BASS_SetConfig, BASS_GetConfig flags #define BASS_CONFIG_WINAMP_INPUT_TIMEOUT 0x10800 // Set the time to wait until timing out because // the plugin is not using the output system // BASS_WINAMP_FindPlugin flags #define BASS_WINAMP_FIND_INPUT 1 #define BASS_WINAMP_FIND_RECURSIVE 4 // return value type #define BASS_WINAMP_FIND_COMMALIST 8 // Delphi's comma list style (item1,item2,"item with , commas",item4,"item with space") // the list ends with single NULL character char* BASSWINAMPDEF(BASS_WINAMP_FindPlugins)(char *pluginpath, DWORD flags); DWORD BASSWINAMPDEF(BASS_WINAMP_LoadPlugin)(char *f); void BASSWINAMPDEF(BASS_WINAMP_UnloadPlugin)(DWORD handle); char* BASSWINAMPDEF(BASS_WINAMP_GetName)(DWORD handle); int BASSWINAMPDEF(BASS_WINAMP_GetVersion)(DWORD handle); BOOL BASSWINAMPDEF(BASS_WINAMP_GetIsSeekable)(DWORD handle); BOOL BASSWINAMPDEF(BASS_WINAMP_GetUsesOutput)(DWORD handle); char* BASSWINAMPDEF(BASS_WINAMP_GetExtentions)(DWORD handle); BOOL BASSWINAMPDEF(BASS_WINAMP_GetFileInfo)(char *f, char *title, int *lenms); BOOL BASSWINAMPDEF(BASS_WINAMP_InfoDlg)(char *f, DWORD win); void BASSWINAMPDEF(BASS_WINAMP_ConfigPlugin)(DWORD handle, DWORD win); void BASSWINAMPDEF(BASS_WINAMP_AboutPlugin)(DWORD handle, DWORD win); HSTREAM BASSWINAMPDEF(BASS_WINAMP_StreamCreate)(char *f, DWORD flags); #ifdef __cplusplus } #endif #endif
1,656
C++
.h
38
40.947368
100
0.781581
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,604
bassasio.h
missdeer_hannah/output/bass/include/bassasio.h
/* BASSASIO 1.4 C/C++ header file Copyright (c) 2005-2019 Un4seen Developments Ltd. See the BASSASIO.CHM file for more detailed documentation */ #ifndef BASSASIO_H #define BASSASIO_H #include <wtypes.h> #ifdef __cplusplus extern "C" { #endif #ifndef BASSASIODEF #define BASSASIODEF(f) WINAPI f #endif #define BASSASIOVERSION 0x104 // API version // error codes returned by BASS_ASIO_ErrorGetCode #define BASS_OK 0 // all is OK #define BASS_ERROR_FILEOPEN 2 // can't open the file #define BASS_ERROR_DRIVER 3 // can't find a free/valid driver #define BASS_ERROR_HANDLE 5 // invalid handle #define BASS_ERROR_FORMAT 6 // unsupported sample format #define BASS_ERROR_INIT 8 // BASS_ASIO_Init has not been successfully called #define BASS_ERROR_START 9 // BASS_ASIO_Start has/hasn't been called #define BASS_ERROR_ALREADY 14 // already initialized/started #define BASS_ERROR_NOCHAN 18 // no channels are enabled #define BASS_ERROR_ILLPARAM 20 // an illegal parameter was specified #define BASS_ERROR_DEVICE 23 // illegal device number #define BASS_ERROR_NOTAVAIL 37 // not available #define BASS_ERROR_UNKNOWN -1 // some other mystery error // BASS_ASIO_Init flags #define BASS_ASIO_THREAD 1 // host driver in dedicated thread #define BASS_ASIO_JOINORDER 2 // order joined channels by when they were joined // device info structure typedef struct { const char *name; // description const char *driver; // driver } BASS_ASIO_DEVICEINFO; typedef struct { char name[32]; // driver name DWORD version; // driver version DWORD inputs; // number of inputs DWORD outputs; // number of outputs DWORD bufmin; // minimum buffer length DWORD bufmax; // maximum buffer length DWORD bufpref; // preferred/default buffer length int bufgran; // buffer length granularity DWORD initflags; // BASS_ASIO_Init "flags" parameter } BASS_ASIO_INFO; typedef struct { DWORD group; DWORD format; // sample format (BASS_ASIO_FORMAT_xxx) char name[32]; // channel name } BASS_ASIO_CHANNELINFO; // sample formats #define BASS_ASIO_FORMAT_16BIT 16 // 16-bit integer #define BASS_ASIO_FORMAT_24BIT 17 // 24-bit integer #define BASS_ASIO_FORMAT_32BIT 18 // 32-bit integer #define BASS_ASIO_FORMAT_FLOAT 19 // 32-bit floating-point #define BASS_ASIO_FORMAT_DSD_LSB 32 // DSD (LSB 1st) #define BASS_ASIO_FORMAT_DSD_MSB 33 // DSD (MSB 1st) #define BASS_ASIO_FORMAT_DITHER 0x100 // flag: apply dither when converting from floating-point to integer // BASS_ASIO_ChannelReset flags #define BASS_ASIO_RESET_ENABLE 1 // disable channel #define BASS_ASIO_RESET_JOIN 2 // unjoin channel #define BASS_ASIO_RESET_PAUSE 4 // unpause channel #define BASS_ASIO_RESET_FORMAT 8 // reset sample format to native format #define BASS_ASIO_RESET_RATE 16 // reset sample rate to device rate #define BASS_ASIO_RESET_VOLUME 32 // reset volume to 1.0 #define BASS_ASIO_RESET_JOINED 0x10000 // apply to joined channels too // BASS_ASIO_ChannelIsActive return values #define BASS_ASIO_ACTIVE_DISABLED 0 #define BASS_ASIO_ACTIVE_ENABLED 1 #define BASS_ASIO_ACTIVE_PAUSED 2 typedef DWORD (CALLBACK ASIOPROC)(BOOL input, DWORD channel, void *buffer, DWORD length, void *user); /* ASIO channel callback function. input : Input? else output channel: Channel number buffer : Buffer containing the sample data length : Number of bytes user : The 'user' parameter given when calling BASS_ASIO_ChannelEnable RETURN : The number of bytes written (ignored with input channels) */ typedef void (CALLBACK ASIONOTIFYPROC)(DWORD notify, void *user); /* Driver notification callback function. notify : The notification (BASS_ASIO_NOTIFY_xxx) user : The 'user' parameter given when calling BASS_ASIO_SetNotify */ // driver notifications #define BASS_ASIO_NOTIFY_RATE 1 // sample rate change #define BASS_ASIO_NOTIFY_RESET 2 // reset (reinitialization) request // BASS_ASIO_ChannelGetLevel flags #define BASS_ASIO_LEVEL_RMS 0x1000000 DWORD BASSASIODEF(BASS_ASIO_GetVersion)(); BOOL BASSASIODEF(BASS_ASIO_SetUnicode)(BOOL unicode); DWORD BASSASIODEF(BASS_ASIO_ErrorGetCode)(); BOOL BASSASIODEF(BASS_ASIO_GetDeviceInfo)(DWORD device, BASS_ASIO_DEVICEINFO *info); DWORD BASSASIODEF(BASS_ASIO_AddDevice)(const GUID *clsid, const char *driver, const char *name); BOOL BASSASIODEF(BASS_ASIO_SetDevice)(DWORD device); DWORD BASSASIODEF(BASS_ASIO_GetDevice)(); BOOL BASSASIODEF(BASS_ASIO_Init)(int device, DWORD flags); BOOL BASSASIODEF(BASS_ASIO_Free)(); BOOL BASSASIODEF(BASS_ASIO_Lock)(BOOL lock); BOOL BASSASIODEF(BASS_ASIO_SetNotify)(ASIONOTIFYPROC *proc, void *user); BOOL BASSASIODEF(BASS_ASIO_ControlPanel)(); BOOL BASSASIODEF(BASS_ASIO_GetInfo)(BASS_ASIO_INFO *info); BOOL BASSASIODEF(BASS_ASIO_CheckRate)(double rate); BOOL BASSASIODEF(BASS_ASIO_SetRate)(double rate); double BASSASIODEF(BASS_ASIO_GetRate)(); BOOL BASSASIODEF(BASS_ASIO_Start)(DWORD buflen, DWORD threads); BOOL BASSASIODEF(BASS_ASIO_Stop)(); BOOL BASSASIODEF(BASS_ASIO_IsStarted)(); DWORD BASSASIODEF(BASS_ASIO_GetLatency)(BOOL input); float BASSASIODEF(BASS_ASIO_GetCPU)(); BOOL BASSASIODEF(BASS_ASIO_Monitor)(int input, DWORD output, DWORD gain, DWORD state, DWORD pan); BOOL BASSASIODEF(BASS_ASIO_SetDSD)(BOOL dsd); BOOL BASSASIODEF(BASS_ASIO_Future)(DWORD selector, void *param); BOOL BASSASIODEF(BASS_ASIO_ChannelGetInfo)(BOOL input, DWORD channel, BASS_ASIO_CHANNELINFO *info); BOOL BASSASIODEF(BASS_ASIO_ChannelReset)(BOOL input, int channel, DWORD flags); BOOL BASSASIODEF(BASS_ASIO_ChannelEnable)(BOOL input, DWORD channel, ASIOPROC *proc, void *user); BOOL BASSASIODEF(BASS_ASIO_ChannelEnableMirror)(DWORD channel, BOOL input2, DWORD channel2); BOOL BASSASIODEF(BASS_ASIO_ChannelEnableBASS)(BOOL input, DWORD channel, DWORD handle, BOOL join); BOOL BASSASIODEF(BASS_ASIO_ChannelJoin)(BOOL input, DWORD channel, int channel2); BOOL BASSASIODEF(BASS_ASIO_ChannelPause)(BOOL input, DWORD channel); DWORD BASSASIODEF(BASS_ASIO_ChannelIsActive)(BOOL input, DWORD channel); BOOL BASSASIODEF(BASS_ASIO_ChannelSetFormat)(BOOL input, DWORD channel, DWORD format); DWORD BASSASIODEF(BASS_ASIO_ChannelGetFormat)(BOOL input, DWORD channel); BOOL BASSASIODEF(BASS_ASIO_ChannelSetRate)(BOOL input, DWORD channel, double rate); double BASSASIODEF(BASS_ASIO_ChannelGetRate)(BOOL input, DWORD channel); BOOL BASSASIODEF(BASS_ASIO_ChannelSetVolume)(BOOL input, int channel, float volume); float BASSASIODEF(BASS_ASIO_ChannelGetVolume)(BOOL input, int channel); float BASSASIODEF(BASS_ASIO_ChannelGetLevel)(BOOL input, DWORD channel); #ifdef __cplusplus } #endif #endif
6,506
C++
.h
133
47.62406
107
0.791529
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,605
BASS_WADSP.h
missdeer_hannah/output/bass/include/BASS_WADSP.h
// Written by Bernd Niedergesaess // Version: 2.4.1.0 // Copyright: 2005-2009, radio42, Bernd Niedergesaess // All Rights reserved. // // Note: // You should disable floating-point exceptions in your app. // This is because some Winamp DSPs might change the FloatingPointUnit state and raise a stupid exception. // Simply call before using/loading this library: // "_control87(-1,_MCW_EM);" #ifndef BASS_WADSP_H #define BASS_WADSP_H #include <bass.h> #ifdef __cplusplus extern "C" { #endif #ifndef BASSDSPDEF #define BASSDSPDEF(f) WINAPI f #endif typedef DWORD HWADSP; // Winamp SDK message parameter values (for lParam) #define BASS_WADSP_IPC_GETOUTPUTTIME 105 #define BASS_WADSP_IPC_ISPLAYING 104 #define BASS_WADSP_IPC_GETVERSION 0 #define BASS_WADSP_IPC_STARTPLAY 102 #define BASS_WADSP_IPC_GETINFO 126 #define BASS_WADSP_IPC_GETLISTLENGTH 124 #define BASS_WADSP_IPC_GETLISTPOS 125 #define BASS_WADSP_IPC_GETPLAYLISTFILE 211 #define BASS_WADSP_IPC_GETPLAYLISTTITLE 212 #define BASS_WADSP_IPC WM_USER int BASSDSPDEF(BASS_WADSP_GetVersion)(void); BOOL BASSDSPDEF(BASS_WADSP_Init)(HWND hwndMain); BOOL BASSDSPDEF(BASS_WADSP_Free)(void); BOOL BASSDSPDEF(BASS_WADSP_FreeDSP)(HWADSP plugin); HWND BASSDSPDEF(BASS_WADSP_GetFakeWinampWnd)(HWADSP plugin); BOOL BASSDSPDEF(BASS_WADSP_SetSongTitle)(HWADSP plugin, const char *thetitle); BOOL BASSDSPDEF(BASS_WADSP_SetFileName)(HWADSP plugin, const char *thefile); typedef LRESULT (CALLBACK WINAMPWINPROC)(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); HWADSP BASSDSPDEF(BASS_WADSP_Load)(const char *dspfile, int x, int y, int width, int height, WINAMPWINPROC *proc); BOOL BASSDSPDEF(BASS_WADSP_Config)(HWADSP plugin); BOOL BASSDSPDEF(BASS_WADSP_Start)(HWADSP plugin, DWORD module, DWORD hchan); BOOL BASSDSPDEF(BASS_WADSP_Stop)(HWADSP plugin); BOOL BASSDSPDEF(BASS_WADSP_SetChannel)(HWADSP plugin, DWORD hchan); DWORD BASSDSPDEF(BASS_WADSP_GetModule)(HWADSP plugin); HDSP BASSDSPDEF(BASS_WADSP_ChannelSetDSP)(HWADSP plugin, DWORD hchan, int priority); BOOL BASSDSPDEF(BASS_WADSP_ChannelRemoveDSP)(HWADSP plugin); DWORD BASSDSPDEF(BASS_WADSP_ModifySamplesSTREAM)(HWADSP plugin, void *buffer, DWORD length); DWORD BASSDSPDEF(BASS_WADSP_ModifySamplesDSP)(HWADSP plugin, void *buffer, DWORD length); LPTSTR BASSDSPDEF(BASS_WADSP_GetName)(HWADSP plugin); UINT BASSDSPDEF(BASS_WADSP_GetModuleCount)(HWADSP plugin); LPTSTR BASSDSPDEF(BASS_WADSP_GetModuleName)(HWADSP plugin, DWORD module); BOOL BASSDSPDEF(BASS_WADSP_PluginInfoFree)(void); BOOL BASSDSPDEF(BASS_WADSP_PluginInfoLoad)(const char *dspfile); LPTSTR BASSDSPDEF(BASS_WADSP_PluginInfoGetName)(void); UINT BASSDSPDEF(BASS_WADSP_PluginInfoGetModuleCount)(void); LPTSTR BASSDSPDEF(BASS_WADSP_PluginInfoGetModuleName)(DWORD module); #ifdef __cplusplus } #endif #endif
2,859
C++
.h
61
45.622951
114
0.789946
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,606
bassmix.h
missdeer_hannah/output/bass/include/bassmix.h
/* BASSmix 2.4 C/C++ header file Copyright (c) 2005-2020 Un4seen Developments Ltd. See the BASSMIX.CHM file for more detailed documentation */ #ifndef BASSMIX_H #define BASSMIX_H #include "bass.h" #if BASSVERSION!=0x204 #error conflicting BASS and BASSmix versions #endif #ifdef __cplusplus extern "C" { #endif #ifndef BASSMIXDEF #define BASSMIXDEF(f) WINAPI f #endif // Additional BASS_SetConfig options #define BASS_CONFIG_MIXER_BUFFER 0x10601 #define BASS_CONFIG_MIXER_POSEX 0x10602 #define BASS_CONFIG_SPLIT_BUFFER 0x10610 // BASS_Mixer_StreamCreate flags #define BASS_MIXER_END 0x10000 // end the stream when there are no sources #define BASS_MIXER_NONSTOP 0x20000 // don't stall when there are no sources #define BASS_MIXER_RESUME 0x1000 // resume stalled immediately upon new/unpaused source #define BASS_MIXER_POSEX 0x2000 // enable BASS_Mixer_ChannelGetPositionEx support // BASS_Mixer_StreamAddChannel/Ex flags #define BASS_MIXER_CHAN_ABSOLUTE 0x1000 // start is an absolute position #define BASS_MIXER_CHAN_BUFFER 0x2000 // buffer data for BASS_Mixer_ChannelGetData/Level #define BASS_MIXER_CHAN_LIMIT 0x4000 // limit mixer processing to the amount available from this source #define BASS_MIXER_CHAN_MATRIX 0x10000 // matrix mixing #define BASS_MIXER_CHAN_PAUSE 0x20000 // don't process the source #define BASS_MIXER_CHAN_DOWNMIX 0x400000 // downmix to stereo/mono #define BASS_MIXER_CHAN_NORAMPIN 0x800000 // don't ramp-in the start #define BASS_MIXER_BUFFER BASS_MIXER_CHAN_BUFFER #define BASS_MIXER_LIMIT BASS_MIXER_CHAN_LIMIT #define BASS_MIXER_MATRIX BASS_MIXER_CHAN_MATRIX #define BASS_MIXER_PAUSE BASS_MIXER_CHAN_PAUSE #define BASS_MIXER_DOWNMIX BASS_MIXER_CHAN_DOWNMIX #define BASS_MIXER_NORAMPIN BASS_MIXER_CHAN_NORAMPIN // Mixer attributes #define BASS_ATTRIB_MIXER_LATENCY 0x15000 // BASS_Split_StreamCreate flags #define BASS_SPLIT_SLAVE 0x1000 // only read buffered data #define BASS_SPLIT_POS 0x2000 // Splitter attributes #define BASS_ATTRIB_SPLIT_ASYNCBUFFER 0x15010 #define BASS_ATTRIB_SPLIT_ASYNCPERIOD 0x15011 // Envelope node typedef struct { QWORD pos; float value; } BASS_MIXER_NODE; // Envelope types #define BASS_MIXER_ENV_FREQ 1 #define BASS_MIXER_ENV_VOL 2 #define BASS_MIXER_ENV_PAN 3 #define BASS_MIXER_ENV_LOOP 0x10000 // flag: loop #define BASS_MIXER_ENV_REMOVE 0x20000 // flag: remove at end // Additional sync types #define BASS_SYNC_MIXER_ENVELOPE 0x10200 #define BASS_SYNC_MIXER_ENVELOPE_NODE 0x10201 // Additional BASS_Mixer_ChannelSetPosition flag #define BASS_POS_MIXER_RESET 0x10000 // flag: clear mixer's playback buffer // BASS_CHANNELINFO types #define BASS_CTYPE_STREAM_MIXER 0x10800 #define BASS_CTYPE_STREAM_SPLIT 0x10801 DWORD BASSMIXDEF(BASS_Mixer_GetVersion)(); HSTREAM BASSMIXDEF(BASS_Mixer_StreamCreate)(DWORD freq, DWORD chans, DWORD flags); BOOL BASSMIXDEF(BASS_Mixer_StreamAddChannel)(HSTREAM handle, DWORD channel, DWORD flags); BOOL BASSMIXDEF(BASS_Mixer_StreamAddChannelEx)(HSTREAM handle, DWORD channel, DWORD flags, QWORD start, QWORD length); DWORD BASSMIXDEF(BASS_Mixer_StreamGetChannels)(HSTREAM handle, DWORD *channels, DWORD count); HSTREAM BASSMIXDEF(BASS_Mixer_ChannelGetMixer)(DWORD handle); DWORD BASSMIXDEF(BASS_Mixer_ChannelFlags)(DWORD handle, DWORD flags, DWORD mask); BOOL BASSMIXDEF(BASS_Mixer_ChannelRemove)(DWORD handle); BOOL BASSMIXDEF(BASS_Mixer_ChannelSetPosition)(DWORD handle, QWORD pos, DWORD mode); QWORD BASSMIXDEF(BASS_Mixer_ChannelGetPosition)(DWORD handle, DWORD mode); QWORD BASSMIXDEF(BASS_Mixer_ChannelGetPositionEx)(DWORD channel, DWORD mode, DWORD delay); DWORD BASSMIXDEF(BASS_Mixer_ChannelGetLevel)(DWORD handle); BOOL BASSMIXDEF(BASS_Mixer_ChannelGetLevelEx)(DWORD handle, float *levels, float length, DWORD flags); DWORD BASSMIXDEF(BASS_Mixer_ChannelGetData)(DWORD handle, void *buffer, DWORD length); HSYNC BASSMIXDEF(BASS_Mixer_ChannelSetSync)(DWORD handle, DWORD type, QWORD param, SYNCPROC *proc, void *user); BOOL BASSMIXDEF(BASS_Mixer_ChannelRemoveSync)(DWORD channel, HSYNC sync); BOOL BASSMIXDEF(BASS_Mixer_ChannelSetMatrix)(DWORD handle, const void *matrix); BOOL BASSMIXDEF(BASS_Mixer_ChannelSetMatrixEx)(DWORD handle, const void *matrix, float time); BOOL BASSMIXDEF(BASS_Mixer_ChannelGetMatrix)(DWORD handle, void *matrix); BOOL BASSMIXDEF(BASS_Mixer_ChannelSetEnvelope)(DWORD handle, DWORD type, const BASS_MIXER_NODE *nodes, DWORD count); BOOL BASSMIXDEF(BASS_Mixer_ChannelSetEnvelopePos)(DWORD handle, DWORD type, QWORD pos); QWORD BASSMIXDEF(BASS_Mixer_ChannelGetEnvelopePos)(DWORD handle, DWORD type, float *value); HSTREAM BASSMIXDEF(BASS_Split_StreamCreate)(DWORD channel, DWORD flags, const int *chanmap); DWORD BASSMIXDEF(BASS_Split_StreamGetSource)(HSTREAM handle); DWORD BASSMIXDEF(BASS_Split_StreamGetSplits)(DWORD handle, HSTREAM *splits, DWORD count); BOOL BASSMIXDEF(BASS_Split_StreamReset)(DWORD handle); BOOL BASSMIXDEF(BASS_Split_StreamResetEx)(DWORD handle, DWORD offset); DWORD BASSMIXDEF(BASS_Split_StreamGetAvailable)(DWORD handle); #ifdef __cplusplus } #endif #endif
5,065
C++
.h
99
49.878788
118
0.812462
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
1,541,607
basswasapi.h
missdeer_hannah/output/bass/include/basswasapi.h
/* BASSWASAPI 2.4 C/C++ header file Copyright (c) 2009-2020 Un4seen Developments Ltd. See the BASSWASAPI.CHM file for more detailed documentation */ #ifndef BASSWASAPI_H #define BASSWASAPI_H #include "bass.h" #ifdef __cplusplus extern "C" { #endif #ifndef BASSWASAPIDEF #define BASSWASAPIDEF(f) WINAPI f #endif // Additional error codes returned by BASS_ErrorGetCode #define BASS_ERROR_WASAPI 5000 // no WASAPI #define BASS_ERROR_WASAPI_BUFFER 5001 // buffer size is invalid #define BASS_ERROR_WASAPI_CATEGORY 5002 // can't set category #define BASS_ERROR_WASAPI_DENIED 5003 // access denied // Device info structure typedef struct { const char *name; const char *id; DWORD type; DWORD flags; float minperiod; float defperiod; DWORD mixfreq; DWORD mixchans; } BASS_WASAPI_DEVICEINFO; typedef struct { DWORD initflags; DWORD freq; DWORD chans; DWORD format; DWORD buflen; float volmax; float volmin; float volstep; } BASS_WASAPI_INFO; // BASS_WASAPI_DEVICEINFO "type" #define BASS_WASAPI_TYPE_NETWORKDEVICE 0 #define BASS_WASAPI_TYPE_SPEAKERS 1 #define BASS_WASAPI_TYPE_LINELEVEL 2 #define BASS_WASAPI_TYPE_HEADPHONES 3 #define BASS_WASAPI_TYPE_MICROPHONE 4 #define BASS_WASAPI_TYPE_HEADSET 5 #define BASS_WASAPI_TYPE_HANDSET 6 #define BASS_WASAPI_TYPE_DIGITAL 7 #define BASS_WASAPI_TYPE_SPDIF 8 #define BASS_WASAPI_TYPE_HDMI 9 #define BASS_WASAPI_TYPE_UNKNOWN 10 // BASS_WASAPI_DEVICEINFO flags #define BASS_DEVICE_ENABLED 1 #define BASS_DEVICE_DEFAULT 2 #define BASS_DEVICE_INIT 4 #define BASS_DEVICE_LOOPBACK 8 #define BASS_DEVICE_INPUT 16 #define BASS_DEVICE_UNPLUGGED 32 #define BASS_DEVICE_DISABLED 64 // BASS_WASAPI_Init flags #define BASS_WASAPI_EXCLUSIVE 1 #define BASS_WASAPI_AUTOFORMAT 2 #define BASS_WASAPI_BUFFER 4 #define BASS_WASAPI_EVENT 16 #define BASS_WASAPI_SAMPLES 32 #define BASS_WASAPI_DITHER 64 #define BASS_WASAPI_RAW 128 #define BASS_WASAPI_ASYNC 0x100 #define BASS_WASAPI_CATEGORY_MASK 0xf000 #define BASS_WASAPI_CATEGORY_OTHER 0x0000 #define BASS_WASAPI_CATEGORY_FOREGROUNDONLYMEDIA 0x1000 #define BASS_WASAPI_CATEGORY_BACKGROUNDCAPABLEMEDIA 0x2000 #define BASS_WASAPI_CATEGORY_COMMUNICATIONS 0x3000 #define BASS_WASAPI_CATEGORY_ALERTS 0x4000 #define BASS_WASAPI_CATEGORY_SOUNDEFFECTS 0x5000 #define BASS_WASAPI_CATEGORY_GAMEEFFECTS 0x6000 #define BASS_WASAPI_CATEGORY_GAMEMEDIA 0x7000 #define BASS_WASAPI_CATEGORY_GAMECHAT 0x8000 #define BASS_WASAPI_CATEGORY_SPEECH 0x9000 #define BASS_WASAPI_CATEGORY_MOVIE 0xa000 #define BASS_WASAPI_CATEGORY_MEDIA 0xb000 // BASS_WASAPI_INFO "format" #define BASS_WASAPI_FORMAT_FLOAT 0 #define BASS_WASAPI_FORMAT_8BIT 1 #define BASS_WASAPI_FORMAT_16BIT 2 #define BASS_WASAPI_FORMAT_24BIT 3 #define BASS_WASAPI_FORMAT_32BIT 4 // BASS_WASAPI_Set/GetVolume modes #define BASS_WASAPI_CURVE_DB 0 #define BASS_WASAPI_CURVE_LINEAR 1 #define BASS_WASAPI_CURVE_WINDOWS 2 #define BASS_WASAPI_VOL_SESSION 8 typedef DWORD (CALLBACK WASAPIPROC)(void *buffer, DWORD length, void *user); /* WASAPI callback function. buffer : Buffer containing the sample data length : Number of bytes user : The 'user' parameter given when calling BASS_WASAPI_Init RETURN : The number of bytes written (output devices), 0/1 = stop/continue (input devices) */ // Special WASAPIPROCs #define WASAPIPROC_PUSH (WASAPIPROC*)0 // push output #define WASAPIPROC_BASS (WASAPIPROC*)-1 // BASS channel typedef void (CALLBACK WASAPINOTIFYPROC)(DWORD notify, DWORD device, void *user); /* WASAPI device notification callback function. notify : The notification (BASS_WASAPI_NOTIFY_xxx) device : Device that the notification applies to user : The 'user' parameter given when calling BASS_WASAPI_SetNotify */ // Device notifications #define BASS_WASAPI_NOTIFY_ENABLED 0 #define BASS_WASAPI_NOTIFY_DISABLED 1 #define BASS_WASAPI_NOTIFY_DEFOUTPUT 2 #define BASS_WASAPI_NOTIFY_DEFINPUT 3 #define BASS_WASAPI_NOTIFY_FAIL 0x100 DWORD BASSWASAPIDEF(BASS_WASAPI_GetVersion)(); BOOL BASSWASAPIDEF(BASS_WASAPI_SetNotify)(WASAPINOTIFYPROC *proc, void *user); BOOL BASSWASAPIDEF(BASS_WASAPI_GetDeviceInfo)(DWORD device, BASS_WASAPI_DEVICEINFO *info); float BASSWASAPIDEF(BASS_WASAPI_GetDeviceLevel)(DWORD device, int chan); BOOL BASSWASAPIDEF(BASS_WASAPI_SetDevice)(DWORD device); DWORD BASSWASAPIDEF(BASS_WASAPI_GetDevice)(); DWORD BASSWASAPIDEF(BASS_WASAPI_CheckFormat)(DWORD device, DWORD freq, DWORD chans, DWORD flags); BOOL BASSWASAPIDEF(BASS_WASAPI_Init)(int device, DWORD freq, DWORD chans, DWORD flags, float buffer, float period, WASAPIPROC *proc, void *user); BOOL BASSWASAPIDEF(BASS_WASAPI_Free)(); BOOL BASSWASAPIDEF(BASS_WASAPI_GetInfo)(BASS_WASAPI_INFO *info); float BASSWASAPIDEF(BASS_WASAPI_GetCPU)(); BOOL BASSWASAPIDEF(BASS_WASAPI_Lock)(BOOL lock); BOOL BASSWASAPIDEF(BASS_WASAPI_Start)(); BOOL BASSWASAPIDEF(BASS_WASAPI_Stop)(BOOL reset); BOOL BASSWASAPIDEF(BASS_WASAPI_IsStarted)(); BOOL BASSWASAPIDEF(BASS_WASAPI_SetVolume)(DWORD mode, float volume); float BASSWASAPIDEF(BASS_WASAPI_GetVolume)(DWORD mode); BOOL BASSWASAPIDEF(BASS_WASAPI_SetMute)(DWORD mode, BOOL mute); BOOL BASSWASAPIDEF(BASS_WASAPI_GetMute)(DWORD mode); DWORD BASSWASAPIDEF(BASS_WASAPI_PutData)(void *buffer, DWORD length); DWORD BASSWASAPIDEF(BASS_WASAPI_GetData)(void *buffer, DWORD length); DWORD BASSWASAPIDEF(BASS_WASAPI_GetLevel)(); BOOL BASSWASAPIDEF(BASS_WASAPI_GetLevelEx)(float *levels, float length, DWORD flags); #ifdef __cplusplus } #endif #endif
5,475
C++
.h
140
37.821429
145
0.802973
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
1,541,609
externalreverseproxyrunner.h
missdeer_hannah/desktop/externalreverseproxyrunner.h
#pragma once #include <QObject> QT_FORWARD_DECLARE_CLASS(QProcess); QT_FORWARD_DECLARE_CLASS(QSettings); class ExternalReverseProxyRunner : public QObject { Q_OBJECT public: explicit ExternalReverseProxyRunner(QObject *parent = nullptr); ~ExternalReverseProxyRunner(); void start(); void stop(); void restart(); void applySettings(QSettings& settings); [[nodiscard]] bool isRunning(); private: QProcess *m_process {nullptr}; };
468
C++
.h
18
22.777778
67
0.748879
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,610
trackfile.h
missdeer_hannah/desktop/trackfile.h
#pragma once #include <QDateTime> #include <QFile> #include <QFileInfo> #include <QUrl> #include <QtDebug> // Wrapper class for dealing with track files and their // path/location, URL, and URI representations. // // All file-related track properties are snapshots from the provided // QFileInfo. Obtaining them might involve accessing the file system // and should be used consciously! The QFileInfo class does some // caching behind the scenes. // // Please note that the canonical location of QFileInfo may change at // any time, when the underlying file system structure is modified. // It becomes empty if the file is deleted. // // Copying an instance of this class is thread-safe, because the // underlying QFileInfo is implicitly shared. class TrackFile { public: static TrackFile fromUrl(const QUrl &url) { return TrackFile(url.toLocalFile()); } // For backward-compatibility the QString single argument // constructor has not been declared as "explicit". It is // also not strictly necessary and might be removed at some // point to prevent unintended type conversions. /*non-explicit*/ TrackFile(const QString &filePath) : m_fileInfo(filePath) {} explicit TrackFile(QFileInfo fileInfo = QFileInfo()) : m_fileInfo(std::move(fileInfo)) {} explicit TrackFile(const QDir &dir, const QString &file = QString()) : m_fileInfo(QFileInfo(dir, file)) {} const QFileInfo &asFileInfo() const { return m_fileInfo; } // Local file representation QString location() const { return m_fileInfo.absoluteFilePath(); } QString canonicalLocation() const { return m_fileInfo.canonicalFilePath(); } QString directory() const { return m_fileInfo.absolutePath(); } QString baseName() const { return m_fileInfo.baseName(); } QString fileName() const { return m_fileInfo.fileName(); } qint64 fileSize() const { return m_fileInfo.size(); } QDateTime fileCreated() const { #if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) return m_fileInfo.birthTime(); #else return m_fileInfo.created(); #endif } QDateTime fileLastModified() const { return m_fileInfo.lastModified(); } // Check if the file actually exists on the file system. bool checkFileExists() const { return QFile::exists(location()); } void refresh() { m_fileInfo.refresh(); } // Refresh the canonical location if it is still empty, i.e. if // the file may have re-appeared after mounting the corresponding // drive while Mixxx is already running. // // We ignore the case when the user changes a symbolic link to // point a file to an other location, since this is a user action. // We also don't care if a file disappears while Mixxx is running. // Opening a non-existent file is already handled and doesn't cause // any malfunction. QString freshCanonicalLocation(); // Portable URL representation QUrl toUrl() const { return QUrl::fromLocalFile(location()); } friend bool operator==(const TrackFile &lhs, const TrackFile &rhs) { return lhs.m_fileInfo == rhs.m_fileInfo; } private: QFileInfo m_fileInfo; }; inline bool operator!=(const TrackFile &lhs, const TrackFile &rhs) { return !(lhs == rhs); } inline QDebug operator<<(QDebug debug, const TrackFile &trackFile) { #if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0) return debug << trackFile.asFileInfo(); #else return debug << trackFile.location(); #endif }
3,644
C++
.h
118
26.508475
110
0.693052
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,611
serviceslots.h
missdeer_hannah/desktop/serviceslots.h
#ifndef _SERVICESLOTS_H_ #define _SERVICESLOTS_H_ #include <QStringList> void serviceSearch(const QString &s); void serviceOpenUrl(const QString &s); void serviceOpenLink(const QString &s); void serviceAppendToPlaylist(const QStringList &s); void serviceClearAndAddToPlaylist(const QStringList &s); void serviceAppendToPlaylistFile(const QStringList &s); void serviceClearAndAddToPlaylistFile(const QStringList &s); #endif
426
C++
.h
11
37.454545
60
0.84466
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,613
lrcbar.h
missdeer_hannah/desktop/player/lrcbar.h
#ifndef LRCBAR_H #define LRCBAR_H #include <QWidget> QT_FORWARD_DECLARE_CLASS(QTimer); QT_FORWARD_DECLARE_CLASS(QPaintEvent); QT_FORWARD_DECLARE_CLASS(QMouseEvent); QT_FORWARD_DECLARE_CLASS(QContextMenuEvent); class Lyrics; class BassPlayer; namespace Ui { class LrcBar; } class LrcBar : public QWidget { Q_OBJECT public: Q_DISABLE_COPY_MOVE(LrcBar) LrcBar(Lyrics *lrc, BassPlayer *plr, QWidget *parent = nullptr); ~LrcBar(); private slots: void UpdateTime(); void settingFont(); void enableShadow(); void enableStroke(); private: Ui::LrcBar * ui; QTimer * timer; Lyrics * lyrics; BassPlayer * player; QPoint pos; bool clickOnFrame; bool mouseEnter = {false}; QLinearGradient linearGradient; QLinearGradient maskLinearGradient; QFont font; int shadowMode {0}; protected: void paintEvent(QPaintEvent *) override; void mousePressEvent(QMouseEvent *event) override; void mouseMoveEvent(QMouseEvent *event) override; void mouseReleaseEvent(QMouseEvent *) override; #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) void enterEvent(QEvent *) override; #endif void leaveEvent(QEvent *) override; void contextMenuEvent(QContextMenuEvent *event) override; }; #endif // LRCBAR_H
1,358
C++
.h
49
24.306122
68
0.69746
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,614
qmlplayer.h
missdeer_hannah/desktop/player/qmlplayer.h
#ifndef QMLPLAYER_H #define QMLPLAYER_H #include <QObject> #if defined(Q_OS_WIN) && QT_VERSION < QT_VERSION_CHECK(6, 0, 0) # include <QtWinExtras> #endif QT_FORWARD_DECLARE_CLASS(QTimer); QT_FORWARD_DECLARE_CLASS(QQmlApplicationEngine); class PlayList; class Lyrics; class OSD; class LrcBar; class QmlPlayer : public QObject { Q_OBJECT Q_PROPERTY(int primaryScreenWidth READ getPrimaryScreenWidth NOTIFY primaryScreenWidthChanged) Q_PROPERTY(int primaryScreenHeight READ getPrimaryScreenHeight NOTIFY primaryScreenHeightChanged) Q_PROPERTY(qreal eq0 READ getEq0 WRITE setEq0 NOTIFY eq0Changed) Q_PROPERTY(qreal eq1 READ getEq1 WRITE setEq1 NOTIFY eq1Changed) Q_PROPERTY(qreal eq2 READ getEq2 WRITE setEq2 NOTIFY eq2Changed) Q_PROPERTY(qreal eq3 READ getEq3 WRITE setEq3 NOTIFY eq3Changed) Q_PROPERTY(qreal eq4 READ getEq4 WRITE setEq4 NOTIFY eq4Changed) Q_PROPERTY(qreal eq5 READ getEq5 WRITE setEq5 NOTIFY eq5Changed) Q_PROPERTY(qreal eq6 READ getEq6 WRITE setEq6 NOTIFY eq6Changed) Q_PROPERTY(qreal eq7 READ getEq7 WRITE setEq7 NOTIFY eq7Changed) Q_PROPERTY(qreal eq8 READ getEq8 WRITE setEq8 NOTIFY eq8Changed) Q_PROPERTY(qreal eq9 READ getEq9 WRITE setEq9 NOTIFY eq9Changed) Q_PROPERTY(qreal volumn READ getVolumn WRITE setVolumn NOTIFY volumnChanged) Q_PROPERTY(qreal progress READ getProgress WRITE setProgress NOTIFY progressChanged) Q_PROPERTY(QString coverUrl READ getCoverUrl WRITE setCoverUrl NOTIFY coverUrlChanged) Q_PROPERTY(QString songName READ getSongName WRITE setSongName NOTIFY songNameChanged) public: Q_DISABLE_COPY_MOVE(QmlPlayer) explicit QmlPlayer(QObject *parent = nullptr); ~QmlPlayer(); void showNormal(); void loadAudio(const QString &uri); void addToListAndPlay(const QList<QUrl> &uris); void addToListAndPlay(const QStringList &uris); void addToListAndPlay(const QString &uri); void setTaskbarButtonWindow(); Q_INVOKABLE void onQuit(); Q_INVOKABLE void onShowPlaylists(); Q_INVOKABLE void onSettings(); Q_INVOKABLE void onFilter(); Q_INVOKABLE void onMessage(); Q_INVOKABLE void onMusic(); Q_INVOKABLE void onCloud(); Q_INVOKABLE void onBluetooth(); Q_INVOKABLE void onCart(); Q_INVOKABLE void presetEQChanged(int index); Q_INVOKABLE void onOpenPreset(); Q_INVOKABLE void onSavePreset(); Q_INVOKABLE void onFavorite(); Q_INVOKABLE void onStop(); Q_INVOKABLE void onPrevious(); Q_INVOKABLE void onPause(); Q_INVOKABLE void onNext(); Q_INVOKABLE void onRepeat(); Q_INVOKABLE void onShuffle(); Q_INVOKABLE void onSwitchFiles(); Q_INVOKABLE void onSwitchPlaylists(); Q_INVOKABLE void onSwitchFavourites(); Q_INVOKABLE void onOpenFile(); int getPrimaryScreenWidth(); int getPrimaryScreenHeight(); qreal getEq0() const; qreal getEq1() const; qreal getEq2() const; qreal getEq3() const; qreal getEq4() const; qreal getEq5() const; qreal getEq6() const; qreal getEq7() const; qreal getEq8() const; qreal getEq9() const; qreal getVolumn() const; qreal getProgress() const; const QString &getCoverUrl() const; const QString &getSongName() const; void setEq0(qreal value); void setEq1(qreal value); void setEq2(qreal value); void setEq3(qreal value); void setEq4(qreal value); void setEq5(qreal value); void setEq6(qreal value); void setEq7(qreal value); void setEq8(qreal value); void setEq9(qreal value); void setVolumn(qreal value); void setProgress(qreal progress); void setCoverUrl(const QString &u); void setSongName(const QString &n); private slots: void onUpdateTime(); void onUpdateLrc(); void onPlay(); void onPlayStop(); void onPlayPrevious(); void onPlayNext(); signals: void showPlayer(); void eq0Changed(); void eq1Changed(); void eq2Changed(); void eq3Changed(); void eq4Changed(); void eq5Changed(); void eq6Changed(); void eq7Changed(); void eq8Changed(); void eq9Changed(); void volumnChanged(); void progressChanged(); void coverUrlChanged(); void songNameChanged(); void primaryScreenWidthChanged(); void primaryScreenHeightChanged(); private: QTimer *m_timer {nullptr}; QTimer *m_lrcTimer {nullptr}; Lyrics *m_lyrics {nullptr}; OSD * m_osd {nullptr}; LrcBar *m_lb {nullptr}; float m_fftData[2048]; double m_fftBarValue[29]; double m_fftBarPeakValue[29]; int m_oriFreq {0}; bool m_playing {false}; qreal m_eq0 {0.0}; qreal m_eq1 {0.0}; qreal m_eq2 {0.0}; qreal m_eq3 {0.0}; qreal m_eq4 {0.0}; qreal m_eq5 {0.0}; qreal m_eq6 {0.0}; qreal m_eq7 {0.0}; qreal m_eq8 {0.0}; qreal m_eq9 {0.0}; qreal m_volumn {0.0}; qreal m_progress {0.0}; QString m_coverUrl; QString m_songName; #if defined(Q_OS_WIN) && QT_VERSION < QT_VERSION_CHECK(6, 0, 0) QWinTaskbarButton * taskbarButton; QWinTaskbarProgress *taskbarProgress; QWinThumbnailToolBar * thumbnailToolBar; QWinThumbnailToolButton *playToolButton; QWinThumbnailToolButton *stopToolButton; QWinThumbnailToolButton *backwardToolButton; QWinThumbnailToolButton *forwardToolButton; #endif float arraySUM(int start, int end, float *array); void updateFFT(); void showCoverPic(const QString &filePath); void infoLabelAnimation(); void drawFFTBar(QWidget *parent, int x, int y, int width, int height, double percent); void drawFFTBarPeak(QWidget *parent, int x, int y, int width, int height, double percent); }; inline QmlPlayer * gQmlPlayer = nullptr; inline QQmlApplicationEngine *gQmlApplicationEngine = nullptr; #endif // QMLPLAYER_H
5,967
C++
.h
163
32.092025
101
0.707275
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,615
shadowplayer.h
missdeer_hannah/desktop/player/shadowplayer.h
#ifndef SHADOWPLAYER_H #define SHADOWPLAYER_H #include <math.h> #include <QLinearGradient> #include <QList> #include <QMainWindow> #include <QUrl> #if defined(Q_OS_WIN) && QT_VERSION < QT_VERSION_CHECK(6, 0, 0) # include <QtWinExtras> #endif #include "bass.h" QT_FORWARD_DECLARE_CLASS(QTimer); QT_FORWARD_DECLARE_CLASS(QPropertyAnimation); class BassPlayer; class PlayList; class Lyrics; class OSD; class LrcBar; namespace Ui { class ShadowPlayer; } class ShadowPlayer : public QMainWindow { Q_OBJECT public: explicit ShadowPlayer(QWidget *parent = 0); ~ShadowPlayer(); void loadAudio(const QString &uri); void loadSkin(const QString &image, bool save = true); int cutInt(int i); void addToListAndPlay(const QList<QUrl> &files); void addToListAndPlay(const QStringList &files); void addToListAndPlay(const QString &file); void showPlayer(); private slots: void UpdateTime(); void UpdateLrc(); void callFromPlayList(); void on_openButton_clicked(); void on_playButton_clicked(); void on_stopButton_clicked(); void on_volSlider_valueChanged(int value); void on_muteButton_clicked(); void on_playSlider_sliderPressed(); void on_playSlider_sliderReleased(); void on_resetFreqButton_clicked(); void applyEQ(); void on_extraButton_clicked(); void on_closeButton_clicked(); void on_setSkinButton_clicked(); void loadDefaultSkin(); void fixSkinSizeLeft(); void fixSkinSizeFull(); void originalSkinSize(); void autoSkinSize(); void dynamicSkinSize(); void skinOnTop(); void skinOnCenter(); void skinOnBottom(); void skinDisable(); void physicsSetting(); void enableFFTPhysics(); void disableFFTPhysics(); void on_miniSizeButton_clicked(); void on_playModeButton_clicked(); void on_loadLrcButton_clicked(); void on_playSlider_valueChanged(int value); void on_freqSlider_valueChanged(int value); void on_eqComboBox_currentIndexChanged(int index); void on_playPreButton_clicked(); void on_playNextButton_clicked(); void on_playListButton_clicked(); void on_reverseButton_clicked(); void showDeveloperInfo(); void on_reverbDial_valueChanged(int value); #if defined(Q_OS_WIN) && QT_VERSION < QT_VERSION_CHECK(6, 0, 0) void setTaskbarButtonWindow(); #endif void on_eqEnableCheckBox_clicked(bool checked); public slots: void on_showDskLrcButton_clicked(); private: Ui::ShadowPlayer *ui; float arraySUM(int start, int end, float *array); void updateFFT(); void showCoverPic(const QString &filePath); void infoLabelAnimation(); void drawFFTBar(QWidget *parent, int x, int y, int width, int height, double percent); void drawFFTBarPeak(QWidget *parent, int x, int y, int width, int height, double percent); void saveConfig(); void loadConfig(); void saveSkinData(); void loadSkinData(); QTimer * timer; QTimer * lrcTimer; BassPlayer * player; Lyrics * lyrics; OSD * osd; LrcBar * lb; PlayList *playList; bool isPlaySliderPress {false}; bool isMute {false}; int lastVol; float fftData[2048]; double fftBarValue[29]; double fftBarPeakValue[29]; int oriFreq; bool playing {false}; QPoint pos; bool clickOnFrame {false}; bool clickOnLeft {false}; QPixmap skin; QPixmap skinLeft; QPixmap skinFull; double aspectRatio {0.0}; int skinMode {2}; int playMode {2}; int skinPos {1}; double skinDrawPos {0.0}; bool isReverse {false}; #if defined(Q_OS_WIN) && QT_VERSION < QT_VERSION_CHECK(6, 0, 0) QWinTaskbarButton * taskbarButton; QWinTaskbarProgress *taskbarProgress; QWinThumbnailToolBar * thumbnailToolBar; QWinThumbnailToolButton *playToolButton; QWinThumbnailToolButton *stopToolButton; QWinThumbnailToolButton *backwardToolButton; QWinThumbnailToolButton *forwardToolButton; #endif QPropertyAnimation *sizeSlideAnimation; QPropertyAnimation *fadeInAnimation; QPropertyAnimation *tagAnimation; QPropertyAnimation *mediaInfoAnimation; QPropertyAnimation *coverAnimation; QPropertyAnimation *fadeOutAnimation; QPropertyAnimation *eqHideAnimation; QPropertyAnimation *eqShowAnimation; QPropertyAnimation *lyricsHideAnimation; QPropertyAnimation *lyricsShowAnimation; QPropertyAnimation *playListHideAnimation; QPropertyAnimation *playListShowAnimation; QLinearGradient bgLinearGradient; protected: void dragEnterEvent(QDragEnterEvent *event) override; void dropEvent(QDropEvent *event) override; void paintEvent(QPaintEvent *) override; void mousePressEvent(QMouseEvent *event) override; void mouseMoveEvent(QMouseEvent *event) override; void mouseReleaseEvent(QMouseEvent *event) override; void contextMenuEvent(QContextMenuEvent *) override; void closeEvent(QCloseEvent *) override; void resizeEvent(QResizeEvent *) override; #if defined(Q_OS_WIN) && QT_VERSION < QT_VERSION_CHECK(6, 0, 0) bool nativeEvent(const QByteArray &eventType, void *message, long *result) override; #endif }; inline ShadowPlayer *shadowPlayer = nullptr; #endif // SHADOWPLAYER_H
5,324
C++
.h
159
29.27044
95
0.73065
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,616
bassplayer.h
missdeer_hannah/desktop/player/bassplayer.h
#ifndef PLAYER_H #define PLAYER_H #include <QString> #include "bass.h" enum BassDriver { BD_Default, BD_ASIO, BD_WASAPI, }; class BassPlayer { public: Q_DISABLE_COPY_MOVE(BassPlayer) BassPlayer(); ~BassPlayer(); bool devInit(); [[nodiscard]] QString getTags(); void setVol(int vol); [[nodiscard]] int getVol(); QString openAudio(const QString &uri); void play(); void pause(); void stop(); [[nodiscard]] int getPos(); void setPos(int pos); [[nodiscard]] int getBitRate(); void getFFT(float *array); [[nodiscard]] bool isPlaying(); [[nodiscard]] int getFreq(); void setFreq(float freq); void eqReady(); void disableEQ(); void setEQ(int id, int gain); [[nodiscard]] QString getNowPlayInfo(); [[nodiscard]] QString getTotalTime(); [[nodiscard]] QString getCurTime(); [[nodiscard]] int getCurTimeMS() const; [[nodiscard]] int getTotalTimeMS() const; [[nodiscard]] double getCurTimeSec() const; [[nodiscard]] double getTotalTimeSec() const; [[nodiscard]] DWORD getLevel() const; [[nodiscard]] QString getFileTotalTime(const QString &fileName); [[nodiscard]] double getFileSecond(const QString &fileName); void setReverse(bool isEnable) const; void updateReverb(int value) const; void setJumpPoint(double timeFrom, double timeTo); void removeJumpPoint(); [[nodiscard]] BassDriver getDriver() const; void setDriver(BassDriver &driver); // WASAPI function static DWORD CALLBACK WasapiProc(void *buffer, DWORD length, void *user); private: HSTREAM m_hNowPlay {0}; HFX m_hEqFX {0}; HFX m_hReverbFX {0}; HSYNC m_hJumping {0}; bool m_bPlayNextEnable {true}; #if defined(Q_OS_WIN) HSTREAM m_mixer {0}; bool m_asioInitialized {false}; bool m_wasapiInitialized {false}; bool asioInit(); bool wasapiInit(); #endif BassDriver m_driver {BD_Default}; }; inline BassPlayer *gBassPlayer = nullptr; #endif // PLAYER_H
2,179
C++
.h
69
27.405797
77
0.631003
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,619
osd.h
missdeer_hannah/desktop/player/osd.h
#ifndef OSD_H #define OSD_H #include <QPixmap> #include <QWidget> QT_FORWARD_DECLARE_CLASS(QTimer); QT_FORWARD_DECLARE_CLASS(QPropertyAnimation); QT_FORWARD_DECLARE_CLASS(QPaintEvent); QT_FORWARD_DECLARE_CLASS(QMouseEvent); namespace Ui { class OSD; } class OSD : public QWidget { Q_OBJECT public: Q_DISABLE_COPY_MOVE(OSD) explicit OSD(QWidget *parent = 0); ~OSD(); void showOSD(QString tags, QString totalTime); private: Ui::OSD *ui; QPixmap backGround; QTimer *timer; int timeleft; QPropertyAnimation *hideAnimation; QPropertyAnimation *titleAnimation; QPropertyAnimation *timeAnimation; private slots: void timeRoll(); protected: void paintEvent(QPaintEvent *); void mousePressEvent(QMouseEvent *event); }; #endif // OSD_H
795
C++
.h
34
20.352941
50
0.75133
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,621
playlist.h
missdeer_hannah/desktop/player/playlist.h
#ifndef PLAYLIST_H #define PLAYLIST_H #include <QWidget> namespace Ui { class PlayList; } class BassPlayer; class PlayList : public QWidget { Q_OBJECT public: explicit PlayList(BassPlayer *player, QWidget *parent = 0); ~PlayList(); bool fixSuffix(const QString &uri); bool isEmpty(); void add(const QString &fileName); void insert(int index, const QString &fileName); void remove(int index); void clearAll(); int getLength(); int getIndex(); QString next(bool isLoop = false); QString previous(bool isLoop = false); const QString &playIndex(int index); const QString &getFileNameForIndex(int index); const QString &getCurFile(); QString playLast(); void tableUpdate(); void saveToFile(const QString &fileName); void readFromFile(const QString &fileName); private slots: void on_deleteButton_clicked(); void on_playListTable_cellDoubleClicked(int row, int); void on_clearButton_clicked(); void on_insertButton_clicked(); void on_addButton_clicked(); void on_insertUrlButton_clicked(); void on_addUrlButton_clicked(); void on_searchButton_clicked(); void on_searchNextButton_clicked(); void on_setLenFilButton_clicked(); signals: void callPlayer(); private: Ui::PlayList * ui; QList<QString> m_trackList; QList<QString> m_timeList; BassPlayer * m_player {nullptr}; int m_curIndex {0}; int m_lengthFilter {0}; protected: void dragEnterEvent(QDragEnterEvent *event) override; void dropEvent(QDropEvent *event) override; }; #endif // PLAYLIST_H
1,767
C++
.h
56
27.517857
63
0.651969
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,622
shadowlabel.h
missdeer_hannah/desktop/player/shadowlabel.h
#ifndef SHADOWLABEL_H #define SHADOWLABEL_H #include <QLabel> QT_FORWARD_DECLARE_CLASS(QPaintEvent); QT_FORWARD_DECLARE_CLASS(QColor); class ShadowLabel : public QLabel { Q_OBJECT public: explicit ShadowLabel(QWidget *parent = 0); void setShadowColor(QColor color); void setShadowMode(int mode); signals: public slots: private: QColor shadowColor {QColor(255, 255, 255, 128)}; int shadowMode {0}; protected: void paintEvent(QPaintEvent *event); }; #endif // SHADOWLABEL_H
512
C++
.h
21
21.619048
52
0.757261
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,623
lyrics.h
missdeer_hannah/desktop/player/lyrics.h
#ifndef LYRICS_H #define LYRICS_H #include <QList> #include <QMap> #include <QString> class Lyrics { public: bool resolve(const QString &fileName, bool isLrc = false); bool loadFromLrcDir(const QString &fileName); bool loadFromFileRelativePath(const QString &fileName, const QString &path); void updateTime(int ms, int totalms); double getTimePos(int ms); QString getLrcString(int offset); bool isLrcEmpty(); private: QMap<int, QString> lrcMap; QList<int> timeList; int curLrcTime {0}; int nextLrcTime {0}; }; #endif // LYRICS_H
630
C++
.h
22
25.5
83
0.666116
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,624
fftdisplay.h
missdeer_hannah/desktop/player/fftdisplay.h
#ifndef FFTDISPLAY_H #define FFTDISPLAY_H #include <QGroupBox> QT_FORWARD_DECLARE_CLASS(QPaintEvent); const int arraySize = 29; class FFTDisplay : public QGroupBox { Q_OBJECT public: explicit FFTDisplay(QWidget *parent = 0); void peakSlideDown(); void cutValue(); double acc {0.35}; double maxSpeed {9}; double speed {0.025}; double forceD {6}; double elasticCoefficient {0.6}; double minElasticStep {0.02}; double fftBarValue[arraySize]; signals: public slots: protected: void paintEvent(QPaintEvent *event) override; private: int sx {10}; int sy {190}; int margin {1}; int width {10}; int height {120}; double fftBarPeakValue[arraySize]; double peakSlideSpeed[arraySize]; }; #endif // FFTDISPLAY_H
805
C++
.h
33
20.787879
49
0.694226
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,625
migu.h
missdeer_hannah/desktop/ProviderAPI/migu.h
#pragma once #include <string> #include <boost/beast/http.hpp> class UrlQuery; class UrlParam; namespace ProviderAPI { namespace migu { boost::beast::http::response<boost::beast::http::string_body> playlist(std::string &reqBody, UrlQuery &urlQuery, UrlParam &params); boost::beast::http::response<boost::beast::http::string_body> songinfo(std::string &reqBody, UrlQuery &urlQuery, UrlParam &params); } // namespace migu } // namespace ProviderAPI
477
C++
.h
13
33.384615
139
0.733766
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,626
kugou.h
missdeer_hannah/desktop/ProviderAPI/kugou.h
#pragma once #include <string> #include <boost/beast/http.hpp> class UrlQuery; class UrlParam; namespace ProviderAPI { namespace kugou { boost::beast::http::response<boost::beast::http::string_body> playlist(std::string &reqBody, UrlQuery &urlQuery, UrlParam &params); boost::beast::http::response<boost::beast::http::string_body> songinfo(std::string &reqBody, UrlQuery &urlQuery, UrlParam &params); } // namespace kugou } // namespace ProviderAPI
479
C++
.h
13
33.538462
139
0.734914
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,627
qq.h
missdeer_hannah/desktop/ProviderAPI/qq.h
#pragma once #include <string> #include <boost/beast/http.hpp> class UrlQuery; class UrlParam; namespace ProviderAPI { namespace qq { boost::beast::http::response<boost::beast::http::string_body> playlist(std::string &reqBody, UrlQuery &urlQuery, UrlParam &params); boost::beast::http::response<boost::beast::http::string_body> songinfo(std::string &reqBody, UrlQuery &urlQuery, UrlParam &params); } // namespace qq } // namespace ProviderAPI
473
C++
.h
13
33.076923
139
0.731441
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,628
netease.h
missdeer_hannah/desktop/ProviderAPI/netease.h
#pragma once #include <string> #include <boost/beast/http.hpp> class UrlQuery; class UrlParam; namespace ProviderAPI { namespace netease { boost::beast::http::response<boost::beast::http::string_body> playlist(std::string &reqBody, UrlQuery &urlQuery, UrlParam &params); boost::beast::http::response<boost::beast::http::string_body> songinfo(std::string &reqBody, UrlQuery &urlQuery, UrlParam &params); } // namespace netease } // namespace ProviderAPI
483
C++
.h
13
33.846154
139
0.737179
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,629
kuwo.h
missdeer_hannah/desktop/ProviderAPI/kuwo.h
#pragma once #include <string> #include <boost/beast/http.hpp> class UrlQuery; class UrlParam; namespace ProviderAPI { namespace kuwo { boost::beast::http::response<boost::beast::http::string_body> playlist(std::string &reqBody, UrlQuery &urlQuery, UrlParam &params); boost::beast::http::response<boost::beast::http::string_body> songinfo(std::string &reqBody, UrlQuery &urlQuery, UrlParam &params); } // namespace kuwo } // namespace ProviderAPI
477
C++
.h
13
33.384615
139
0.733766
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,630
BeastServerRunner.h
missdeer_hannah/desktop/BeastServer/BeastServerRunner.h
#pragma once #include <QObject> #include <QThread> QT_FORWARD_DECLARE_CLASS(QSettings); class BeastServerRunner : public QThread { Q_OBJECT public: void stop(); void applySettings(QSettings& settings); protected: void run() override; };
263
C++
.h
13
17.230769
44
0.758333
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,631
BeastHttpResponseHandler.h
missdeer_hannah/desktop/BeastServer/BeastHttpResponseHandler.h
#pragma once #include <boost/beast/core.hpp> #include <boost/beast/http.hpp> namespace beast = boost::beast; // from <boost/beast.hpp> namespace http = beast::http; // from <boost/beast/http.hpp> namespace BeastHttpServer { // Returns a bad request response template<class Body, class Allocator> http::response<http::string_body> bad_request(http::request<Body, http::basic_fields<Allocator>> &req, beast::string_view why) { http::response<http::string_body> res {http::status::bad_request, req.version()}; res.set(http::field::server, BOOST_BEAST_VERSION_STRING); res.set(http::field::content_type, "text/html; charset=UTF-8"); res.keep_alive(req.keep_alive()); res.body() = std::string(why); res.prepare_payload(); return res; }; // Returns a not found response template<class Body, class Allocator> http::response<http::string_body> not_found(http::request<Body, http::basic_fields<Allocator>> &req, beast::string_view target) { http::response<http::string_body> res {http::status::not_found, req.version()}; res.set(http::field::server, BOOST_BEAST_VERSION_STRING); res.set(http::field::content_type, "text/html; charset=UTF-8"); res.keep_alive(req.keep_alive()); res.body() = "The resource '" + std::string(target) + "' was not found."; res.prepare_payload(); return res; }; // Returns a server error response template<class Body, class Allocator> http::response<http::string_body> server_error(http::request<Body, http::basic_fields<Allocator>> &req, beast::string_view what) { http::response<http::string_body> res {http::status::internal_server_error, req.version()}; res.set(http::field::server, BOOST_BEAST_VERSION_STRING); res.set(http::field::content_type, "text/html; charset=UTF-8"); res.keep_alive(req.keep_alive()); res.body() = "An error occurred: '" + std::string(what) + "'"; res.prepare_payload(); return res; }; http::response<http::string_body> ok(const std::string &resp_body, const std::string &content_type = "application/json; charset=UTF-8"); http::response<http::string_body> htmlOk(const std::string &resp_body); http::response<http::string_body> jsonOk(const std::string &resp_body); } // namespace BeastHttpServer
2,392
C++
.h
47
44.680851
140
0.666239
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,632
BeastServer.h
missdeer_hannah/desktop/BeastServer/BeastServer.h
#pragma once #include <memory> #include <boost/asio/ip/tcp.hpp> #include <boost/beast/core.hpp> class BeastServer : public std::enable_shared_from_this<BeastServer> { boost::asio::io_context &m_ioc; boost::asio::ip::tcp::acceptor m_acceptor; public: BeastServer(boost::asio::io_context &ioc, boost::asio::ip::tcp::endpoint endpoint); // Start accepting incoming connections void run(); private: void do_accept(); void on_accept(boost::beast::error_code ec, boost::asio::ip::tcp::socket socket); void fail(boost::beast::error_code ec, char const *what); }; void StartBeastServer(); void StopBeastServer(); void SetListenPort(unsigned short port);
694
C++
.h
20
31.6
87
0.724398
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,633
BeastWebsocketSession.h
missdeer_hannah/desktop/BeastServer/BeastWebsocketSession.h
#pragma once #include <memory> #include <mutex> #include <string> #include <unordered_set> #include <vector> #include <boost/asio/ip/tcp.hpp> #include <boost/beast/core.hpp> #include <boost/beast/http.hpp> #include <boost/beast/websocket.hpp> // Echoes back all received WebSocket messages class BeastWebsocketSession : public std::enable_shared_from_this<BeastWebsocketSession> { boost::beast::websocket::stream<boost::beast::tcp_stream> m_websocket; boost::beast::flat_buffer m_buffer; std::vector<std::shared_ptr<const std::string>> m_msgQueue; std::mutex m_msgQueueMutex; std::string m_strSessionID; std::string m_strSessionToken; public: // Take ownership of the socket explicit BeastWebsocketSession(boost::asio::ip::tcp::socket &&socket); ~BeastWebsocketSession(); // Start the asynchronous accept operation template<class Body, class Allocator> void doAccept(boost::beast::http::request<Body, boost::beast::http::basic_fields<Allocator>> req) { // Set suggested timeout settings for the websocket m_websocket.set_option( boost::beast::websocket::stream_base::timeout::suggested(boost::beast::role_type::server)); // Set a decorator to change the Server of the handshake m_websocket.set_option( boost::beast::websocket::stream_base::decorator([](boost::beast::websocket::response_type &res) { res.set(boost::beast::http::field::server, std::string(BOOST_BEAST_VERSION_STRING) + " hannah-api-fake-server"); })); m_websocket.auto_fragment(true); m_websocket.write_buffer_bytes(20 * 1024 * 1024); // Accept the websocket handshake m_websocket.async_accept( req, boost::beast::bind_front_handler(&BeastWebsocketSession::onAccept, shared_from_this())); } void send(const std::shared_ptr<const std::string> &msg); private: void onAccept(boost::beast::error_code ec); void onRead(boost::beast::error_code ec, std::size_t bytes_transferred); void onWrite(boost::beast::error_code ec, std::size_t bytes_transferred); void onSend(const std::shared_ptr<const std::string> &msg); void onWebMsg(const std::string &msg); void fail(boost::beast::error_code ec, char const *what); std::string getPresetCommand(); std::string getConfirmCommand(); bool analyseCommand(const std::string &strCommand); std::string getCommand(const std::string &actionType); };
2,698
C++
.h
55
43.145455
109
0.650667
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,634
BeastWebsocketSessionManager.h
missdeer_hannah/desktop/BeastServer/BeastWebsocketSessionManager.h
#pragma once #include "BeastWebsocketSession.h" using BeastWebsocketSessionPtr = BeastWebsocketSession *; using BeastWebsocketSessions = std::unordered_set<BeastWebsocketSessionPtr>; class BeastWebsocketSessionManager { public: static BeastWebsocketSessionManager &instance() { return m_instance; } void add(BeastWebsocketSessionPtr session); void remove(BeastWebsocketSessionPtr session); void clear(); BeastWebsocketSessions::iterator begin(); BeastWebsocketSessions::iterator end(); void lock(); void unlock(); void registerWebMsgHandler(std::function<void(const std::string &msg)> handler); void onWebMsg(const std::string &msg); void send(std::string message); private: static BeastWebsocketSessionManager m_instance; BeastWebsocketSessions m_beastWebsocketSessions; std::mutex m_beastWebsocketSessionsMutex; std::function<void(const std::string &msg)> m_webMsgHandler; BeastWebsocketSessionManager(); void dummyWebMsgHandler(const std::string &msg); };
1,173
C++
.h
29
36.206897
84
0.693122
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,635
UrlQuery.h
missdeer_hannah/desktop/BeastServer/UrlQuery.h
#pragma once #include <map> #include <string> #include <vector> using QueryPairType = std::map<std::string, std::string>; //! UrlQuery parse something like https://www.example.com/some/path?id=xxx&name=yyy&age=zzz class UrlQuery { public: explicit UrlQuery(const std::string &uri); QueryPairType::iterator begin(); QueryPairType::iterator end(); bool contains(const std::string &key); const std::string &value(const std::string &key); int intValue(const std::string &key); bool isInt(const std::string &key); std::int64_t int64Value(const std::string &key); bool isInt64(const std::string &key); bool boolValue(const std::string &key); bool isBool(const std::string &key); private: QueryPairType m_queries; void parse(const std::string &uri); }; //! UrlParam represent something like https://www.exmample.com/some/{id}/path class UrlParam { public: void push_back(const std::string &value); bool isInt(size_t index); int intAt(size_t index); bool isInt64(size_t index); std::int64_t int64At(size_t index); const std::string &at(size_t index); size_t size() const; bool empty() const; private: std::vector<std::string> m_values; };
1,446
C++
.h
39
33.641026
91
0.595
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,636
BeastHttpSession.h
missdeer_hannah/desktop/BeastServer/BeastHttpSession.h
#pragma once #include <memory> #include <vector> #include <boost/beast/core.hpp> #include <boost/beast/http.hpp> // Handles an HTTP server connection class BeastHttpSession : public std::enable_shared_from_this<BeastHttpSession> { // This queue is used for HTTP pipelining. class queue { enum { // Maximum number of responses we will queue limit = 8 }; // The type-erased, saved work item struct work { virtual ~work() = default; virtual void operator()() = 0; }; BeastHttpSession &self_; std::vector<std::unique_ptr<work>> items_; public: explicit queue(BeastHttpSession &self); // Returns `true` if we have reached the queue limit bool is_full() const; // Called when a message finishes sending // Returns `true` if the caller should initiate a read bool on_write(); // Called by the HTTP handler to send a response. template<bool isRequest, class Body, class Fields> void operator()(boost::beast::http::message<isRequest, Body, Fields> &&msg) { // This holds a work item struct work_impl : work { BeastHttpSession &self_; boost::beast::http::message<isRequest, Body, Fields> msg_; work_impl(BeastHttpSession &self, boost::beast::http::message<isRequest, Body, Fields> &&msg) : self_(self), msg_(std::move(msg)) { } void operator()() { boost::beast::http::async_write(self_.stream_, msg_, boost::beast::bind_front_handler(&BeastHttpSession::on_write, self_.shared_from_this(), msg_.need_eof())); } }; // Allocate and store the work items_.push_back(boost::make_unique<work_impl>(self_, std::move(msg))); // If there was no previous work, start this one if (items_.size() == 1) (*items_.front())(); } }; boost::beast::tcp_stream stream_; boost::beast::flat_buffer buffer_; queue queue_; // The parser is stored in an optional container so we can // construct it from scratch it at the beginning of each new message. boost::optional<boost::beast::http::request_parser<boost::beast::http::string_body>> parser_; public: // Take ownership of the socket explicit BeastHttpSession(boost::asio::ip::tcp::socket &&socket); // Start the session void run(); private: void do_read(); void on_read(boost::beast::error_code ec, std::size_t bytes_transferred); void on_write(bool close, boost::beast::error_code ec, std::size_t bytes_transferred); void do_close(); void fail(boost::beast::error_code ec, char const *what); };
3,261
C++
.h
78
29.730769
113
0.52863
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,637
tags.h
missdeer_hannah/desktop/3rdparty/bass/include/tags.h
////////////////////////////////////////////////////////////////////////// // // tags.h - TAGS: Yet Another Tag Reading Library for BASS 2.3+ // // Author: Wraith, 2k5-2k6 // Public domain. No warranty. // // (public) // // Abstract: reads tags from given BASS handle, formats them according // to given format string and returns the resulting string. // // read tags-readme.txt for details // #ifndef _YATRL_H_W2348_H4232 #define _YATRL_H_W2348_H4232 #include "bass.h" #ifdef __cplusplus extern "C" { #endif // Current version. Just increments each release. #define TAGS_VERSION 18 // get the loaded version DWORD WINAPI TAGS_GetVersion(); // enable UTF-8 encoding BOOL WINAPI TAGS_SetUTF8( BOOL enable ); // main purpose of this library const char* WINAPI TAGS_Read( DWORD dwHandle, const char* fmt ); const char* WINAPI TAGS_ReadEx( DWORD dwHandle, const char* fmt, DWORD tagtype, int codepage ); // returns description of the last error. const char* WINAPI TAGS_GetLastErrorDesc(); #ifdef __cplusplus } #endif #endif
1,060
C++
.h
35
28.628571
95
0.680473
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,638
Sqlite3Helper.h
missdeer_hannah/desktop/sqlite/Sqlite3Helper.h
#pragma once #include <cstdint> #include <map> #include <string> #include "Sqlite3Statement.h" struct sqlite3; struct sqlite3_stmt; struct sqlite3_context; struct sqlite3_value; class Sqlite3Helper { public: explicit Sqlite3Helper(sqlite3 *&db); Sqlite3StatementPtr compile(const char *szSQL); Sqlite3StatementPtr compile(const std::string &sql); Sqlite3StatementPtr compile(const QString &sql); int execDML(const char *szSQL); int execDML(const std::string &sql); int execDML(const QString &sql); static bool isQueryOk(int result); static bool isOk(int result); static bool canQueryLoop(int result); int getQueryResult(const char *szSQL); int getQueryResult(const std::string &sql); int getQueryResult(const QString &sql); bool isDatabaseOpened(); int checkTableOrIndexExists(const std::string &field, const std::string &name); int checkTableOrIndexExists(const QString &field, const QString &name); bool checkTableColumnExists(const QString &tableName, const QString &field); bool addTableColumn(const QString &tableName, const QString &fieldName, const QString &fieldType); int getTableColumnCount(const QString &tableName); int getTableRowCount(const QString &tableName); bool createTablesAndIndexes(std::map<std::string, const char *> &tablesMap, std::map<std::string, const char *> &indexesMap); bool beginTransaction(); bool endTransaction(); bool rollbackTransaction(); bool vacuum(); std::int64_t lastInsertRowId(); void registerCustomFunctions(); private: sqlite3 *&m_db; };
1,689
C++
.h
42
36.119048
129
0.720688
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,639
Sqlite3DBManager.h
missdeer_hannah/desktop/sqlite/Sqlite3DBManager.h
#pragma once #include <cstdint> #include "Sqlite3Helper.h" struct sqlite3; class Sqlite3DBManager { public: Sqlite3DBManager() : m_sqlite(m_db) {} ~Sqlite3DBManager(); bool open(const QString &dbPath, bool readOnly); bool open(const std::string &dbPath, bool readOnly); bool open(const char *dbPath, bool readOnly); [[nodiscard]] bool isOpened() const; bool close(); bool save(); bool saveAs(const QString &newDbPath); bool saveAs(const std::string &newDbPath); bool saveAs(const char *newDbPath); bool saveAndClose(); bool create(const QString &dbPath); bool create(const std::string &dbPath); bool create(const char *dbPath); bool loadOrSaveInMemory(const QString &dbPath, bool isSave); Sqlite3Helper &engine(); private: sqlite3 *m_db {nullptr}; Sqlite3Helper m_sqlite; std::string m_savePoint; void regenerateSavePoint(); void clearSavePoint(); bool setSavePoint(); bool releaseSavePoint(); };
1,228
C++
.h
33
33
78
0.576371
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,640
Sqlite3Constants.h
missdeer_hannah/desktop/sqlite/Sqlite3Constants.h
#pragma once const char *const SQL_STATEMENT_CIPHER_VERSION = "PRAGMA cipher_version;"; const char *const SQL_STATEMENT_CIPHER_PROVIDER = "PRAGMA cipher_provider;"; const char *const SQL_STATEMENT_CIPHER_PROVIDER_VERSION = "PRAGMA cipher_provider_version;"; const char *const SQL_STATEMENT_ENABLE_FOREIGN_KEYS = "PRAGMA foreign_keys = ON;"; // SQLite options for performance issue const char *const SQL_STATEMENT_MMAP_SIZE = "PRAGMA mmap_size=268435456;"; const char *const SQL_STATEMENT_SYNCHRONOUS = "PRAGMA synchronous = OFF;"; const char *const SQL_STATEMENT_JOURNAL_MODE = "PRAGMA journal_mode = MEMORY;"; const char *const SQL_STATEMENT_CACHE_SIZE = "PRAGMA cache_size=-400;"; // SQLCipher options for performance issue const char *const SQL_STATEMENT_KDF_ITER_V3_MOBILE = "PRAGMA kdf_iter = 10000;"; const char *const SQL_STATEMENT_CIPHER_PAGE_SIZE_V3_MOBILE = "PRAGMA cipher_page_size = 4096;"; const char *const SQL_STATEMENT_KDF_ITER_V3_DESKTOP = "PRAGMA kdf_iter = 64000;"; const char *const SQL_STATEMENT_CIPHER_PAGE_SIZE_V3_DESKTOP = "PRAGMA cipher_page_size = 1024;"; // SQLCipher options for v3.x const char *const SQL_STATEMENT_CIPHER_HMAC_ALGO = "PRAGMA cipher_hmac_algorithm = HMAC_SHA1;"; const char *const SQL_STATEMENT_CIPHER_KDF_ALGO = "PRAGMA cipher_kdf_algorithm = PBKDF2_HMAC_SHA1;"; // SQLCipher options for performance issue upgrade const char *const SQL_STATEMENT_NEWDB_KDF_ITER = "PRAGMA newdb.kdf_iter = '10000';"; const char *const SQL_STATEMENT_NEWDB_CIPHER_PAGE_SIZE = "PRAGMA newdb.cipher_page_size = 4096;"; // export SQLCipher database const char *const SQL_STATEMENT_ATTACH_DATABASE_NEWDB_KEY = "ATTACH DATABASE ? AS newdb KEY ?;"; const char *const SQL_STATEMENT_NEWDB_EXPORT = "SELECT sqlcipher_export('newdb');"; const char *const SQL_STATEMENT_NEWDB_DETACH = "DETACH DATABASE newdb;"; // for error recovery const char *const SQL_STATEMENT_INTEGRITY_CHECK = "PRAGMA integrity_check;"; // transaction const char *const SQL_STATEMENT_BEGIN_TRANSACTION = "BEGIN TRANSACTION;"; const char *const SQL_STATEMENT_COMMIT_TRANSACTION = "COMMIT TRANSACTION;"; const char *const SQL_STATEMENT_ROLLBACK_TRANSACTION = "ROLLBACK TRANSACTION;"; const char *const SQL_STATEMENT_VACUUM = "VACUUM;"; const char *const SQL_STATEMENT_SELECT_SQLITE_MASTER = "SELECT name FROM sqlite_master WHERE type = ? AND name = ?;";
2,436
C++
.h
33
72.515152
117
0.743
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,641
Sqlite3Statement.h
missdeer_hannah/desktop/sqlite/Sqlite3Statement.h
#pragma once #include <cstdint> #include <memory> #include <string> #include <string_view> #include <QByteArray> #include <QString> struct sqlite3; struct sqlite3_stmt; class Sqlite3Helper; class Sqlite3Statement { friend class Sqlite3Helper; public: Sqlite3Statement(sqlite3 *&database, sqlite3_stmt *pVM); void bind(int nParam, const QString &value); void bind(int nParam, const char *szValue, int nLen = -1); void bind(int nParam, const std::string &szValue); void bind(int nParam, std::string_view szValue); void bind(int nParam, int nValue); void bind(int nParam, int64_t nValue); void bind(int nParam, double dValue); void bind(int nParam, const unsigned char *blobValue, int nLen); void bind(int nParam, const QByteArray &blobValue); void bindNull(int nParam); int bindParameterIndex(const char *szParam); void bind(const char *szParam, const QString &value); void bind(const char *szParam, const char *szValue, int nLen = -1); void bind(const char *szParam, const std::string &szValue); void bind(const char *szParam, std::string_view szValue); void bind(const char *szParam, int nValue); void bind(const char *szParam, int64_t nValue); void bind(const char *szParam, double dwValue); void bind(const char *szParam, const unsigned char *blobValue, int nLen); void bind(const char *szParam, const QByteArray &blobValue); void bindNull(const char *szParam); int bindParameterIndex(const std::string &szParam); void bind(const std::string &szParam, const QString &value); void bind(const std::string &szParam, const std::string &szValue); void bind(const std::string &szParam, std::string_view szValue); void bind(const std::string &szParam, int nValue); void bind(const std::string &szParam, int64_t nValue); void bind(const std::string &szParam, double dwValue); void bind(const std::string &szParam, const unsigned char *blobValue, int nLen); void bind(const std::string &szParam, const QByteArray &blobValue); void bindNull(const std::string &szParam); int bindParameterIndex(const QString &szParam); void bind(const QString &szParam, const QString &value); void bind(const QString &szParam, const std::string &szValue); void bind(const QString &szParam, std::string_view szValue); void bind(const QString &szParam, int nValue); void bind(const QString &szParam, int64_t nValue); void bind(const QString &szParam, double dwValue); void bind(const QString &szParam, const unsigned char *blobValue, int nLen); void bind(const QString &szParam, const QByteArray &blobValue); void bindNull(const QString &szParam); int execDML(); int execQuery(bool &eof); int nextRow(bool &eof); int endQuery(); int getInt(int column); double getDouble(int column); std::int64_t getInt64(int column); std::string getString(int column); QString getQString(int column); QByteArray getBlob(int column); std::string getLastErrorString(); int countRow(); bool isValid(); private: sqlite3 *&m_db; sqlite3_stmt *m_pVM; bool isDatabaseOpened(); }; using Sqlite3StatementPtr = std::shared_ptr<Sqlite3Statement>;
3,275
C++
.h
75
39.293333
84
0.719761
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,642
parser.h
missdeer_hannah/desktop/parser/parser.h
// // C++ Interface: parser // // Description: Interface header for the parser Parser // // // Author: Ingo Kossyk <kossyki@cs.tu-berlin.de>, (C) 2004 // Author: Tobias Rafreider trafreider@mixxx.org, (C) 2011 // // Copyright: See COPYING file that comes with this distribution // // #pragma once /**Developer Information: This is the rootclass for all parser classes for the Importer class. It can be used to write a new type-specific parser by deriving a new class from it and overwrite the parse function and add class specific functions to it afterwards for proper functioning **/ #include <QList> #include <QObject> #include <QString> #include "trackfile.h" class Parser : public QObject { Q_OBJECT public: static bool isPlaylistFilenameSupported(const QString &fileName) { return fileName.endsWith(".m3u", Qt::CaseInsensitive) || fileName.endsWith(".m3u8", Qt::CaseInsensitive) || fileName.endsWith(".pls", Qt::CaseInsensitive) || fileName.endsWith(".csv", Qt::CaseInsensitive); } Parser() = default; virtual ~Parser() = default; /**Can be called to parse a pls file Note for developers: This function should return an empty PtrList or 0 in order for the trackimporter to function**/ virtual QList<QString> parse(const QString &) = 0; protected: // Pointer to the parsed Filelocations QList<QString> m_sLocations; // Returns the number of parsed locations long countParsed(); // Clears m_psLocations void clearLocations(); // Checks if the file does contain binary content bool isBinary(const QString &); // check for Utf8 encoding static bool isUtf8(const char *string); // Resolve an absolute or relative file path TrackFile playlistEntryToTrackFile(const QString &playlistEntry, const QString &basePath = QString()); };
1,861
C++
.h
53
31.792453
115
0.727374
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,643
parserpls.h
missdeer_hannah/desktop/parser/parserpls.h
// // C++ Interface: parserpls // // Description: Interface header for the example parser PlsParser // // // Author: Ingo Kossyk <kossyki@cs.tu-berlin.de>, (C) 2004 // // Copyright: See COPYING file that comes with this distribution // // #pragma once #include <QList> #include <QString> #include <QTextStream> #include "parser.h" class ParserPls : public Parser { Q_OBJECT public: ParserPls() = default; ~ParserPls() = default; /**Can be called to parse a pls file**/ QList<QString> parse(const QString &); // Playlist Export static bool writePLSFile(const QString &file, const QList<QString> &items, bool useRelativePath); private: /**Returns the Number of entries in the pls file**/ long getNumEntries(QTextStream *); /**Reads a line from the file and returns filepath**/ QString getFilePath(QTextStream *, const QString &basePath); };
888
C++
.h
32
25.25
101
0.71831
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,644
parserm3u.h
missdeer_hannah/desktop/parser/parserm3u.h
// // C++ Interface: parserm3u // // Description: Interface header for the example parser ParserM3u // // // Author: Ingo Kossyk <kossyki@cs.tu-berlin.de>, (C) 2004 // Author: Tobias Rafreider trafreider@mixxx.org, (C) 2011 // // Copyright: See COPYING file that comes with this distribution // // #pragma once #include <QDir> #include <QList> #include <QString> #include <QTextStream> #include "parser.h" class ParserM3u : public Parser { Q_OBJECT public: ParserM3u() = default; ~ParserM3u() = default; /**Overwriting function parse in class Parser**/ QList<QString> parse(const QString &); // Playlist Export static bool writeM3UFile(const QString &file_str, const QList<QString> &items, bool useRelativePath, bool useUtf8); static bool writeM3UFile(const QString &file, const QList<QString> &items, bool useRelativePath); static bool writeM3U8File(const QString &file_str, const QList<QString> &items, bool useRelativePath); private: /**Reads a line from the file and returns filepath if a valid file**/ QString getFilePath(QTextStream *stream, const QString &basePath); };
1,126
C++
.h
34
30.705882
119
0.741728
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,645
parsercsv.h
missdeer_hannah/desktop/parser/parsercsv.h
// // C++ Interface: parserm3u // // Description: Interface header parse Comma-Separated Values (CSV) formatted playlists (rfc4180) // // // Author: Ingo Kossyk <kossyki@cs.tu-berlin.de>, (C) 2004 // Author: Tobias Rafreider trafreider@mixxx.org, (C) 2011 // Author: Daniel Schürmann daschuer@gmx.de, (C) 2011 // // Copyright: See COPYING file that comes with this distribution // // #pragma once #include <QByteArray> #include <QList> #include <QString> #include "parser.h" class ParserCsv : public Parser { Q_OBJECT public: ParserCsv() = default; ~ParserCsv() = default; /**Overwriting function parse in class Parser**/ QList<QString> parse(const QString &); private: /**Reads a line from the file and returns filepath if a valid file**/ QList<QList<QString>> tokenize(const QByteArray &str, char delimiter); };
848
C++
.h
30
26.2
97
0.726044
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,648
qmldialog.h
missdeer_hannah/desktop/ui/qmldialog.h
#ifndef QMLDIALOG_H #define QMLDIALOG_H #include <QDialog> namespace Ui { class QmlDialog; } class QQmlEngine; class QQmlContext; class QmlDialog : public QDialog { Q_OBJECT public: explicit QmlDialog(QWidget *parent = nullptr); void loadQml(const QUrl& u); QQmlEngine* engine(); QQmlContext* context(); ~QmlDialog(); public slots: void doClose(); private: Ui::QmlDialog *ui; }; #endif // QMLDIALOG_H
440
C++
.h
23
16.434783
50
0.731707
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,649
playlistmanagewindow.h
missdeer_hannah/desktop/ui/playlistmanagewindow.h
#ifndef PLAYLISTMANAGEWINDOW_H #define PLAYLISTMANAGEWINDOW_H #include <QMainWindow> namespace Ui { class PlaylistManageWindow; } class QCloseEvent; class PlaylistModel; class SonglistModel; class Sqlite3Helper; class PlaylistManageWindow : public QMainWindow { Q_OBJECT public: explicit PlaylistManageWindow(QWidget *parent = nullptr); ~PlaylistManageWindow(); void onAppendToPlaylist(const QStringList &s); void onClearAndAddToPlaylist(const QStringList &s); void onAppendToPlaylistFile(const QStringList &s); void onClearAndAddToPlaylistFile(const QStringList &s); protected: void closeEvent(QCloseEvent *event); private slots: void on_edtPlaylistFilter_textChanged(const QString &s); void on_tblSongs_activated(const QModelIndex &index); void on_btnAddPlaylist_clicked(bool checked); void on_btnDeletePlaylist_clicked(bool checked); void on_btnImportPlaylist_clicked(bool checked); void on_btnExportPlaylist_clicked(bool checked); void on_btnAddSongs_clicked(bool checked); void on_btnDeleteSongs_clicked(bool checked); void on_btnImportSongs_clicked(bool checked); private: Ui::PlaylistManageWindow *ui; Sqlite3Helper * m_sqlite3Helper{nullptr}; PlaylistModel * m_playlistModel{nullptr}; SonglistModel * m_songlistModel{nullptr}; void createDataTables(); }; inline PlaylistManageWindow *playlistManageWindow = nullptr; #endif // PLAYLISTMANAGEWINDOW_H
1,502
C++
.h
41
32.829268
61
0.779555
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,652
networkreplyhelper.h
missdeer_hannah/desktop/network/networkreplyhelper.h
#ifndef NETWORKREPLYHELPER_H #define NETWORKREPLYHELPER_H #include <QAbstractItemModel> #include <QNetworkReply> QT_BEGIN_NAMESPACE class QTimer; class QIODevice; QT_END_NAMESPACE class NetworkReplyHelper : public QObject { Q_OBJECT public: explicit NetworkReplyHelper(QNetworkReply *reply, QIODevice *storage = nullptr, QObject *parent = nullptr); explicit NetworkReplyHelper(QNetworkReply *reply, QByteArray *content, QObject *parent = nullptr); NetworkReplyHelper(const NetworkReplyHelper &) = delete; void operator=(const NetworkReplyHelper &) = delete; NetworkReplyHelper(NetworkReplyHelper &&) = delete; void operator=(NetworkReplyHelper &&) = delete; virtual ~NetworkReplyHelper(); virtual void postFinished(); virtual QByteArray receivedData(QByteArray data); [[nodiscard]] QJsonDocument json(); [[nodiscard]] QByteArray &content(); [[nodiscard]] QNetworkReply *reply(); [[nodiscard]] QIODevice *storage(); [[nodiscard]] QVariant data() const; void setData(const QVariant &data); void setTimeout(int milliseconds); [[nodiscard]] const QString &getErrorMessage() const; void waitForFinished(); [[nodiscard]] bool isOk() const; protected: void setErrorMessage(const QString &errMsg); signals: void done(); void cancel(); void errorMessage(QNetworkReply::NetworkError, QString); public slots: void downloadProgress(qint64 bytesReceived, qint64 bytesTotal); void error(QNetworkReply::NetworkError code); void finished(); void sslErrors(const QList<QSslError> &errors); void uploadProgress(qint64 bytesSent, qint64 bytesTotal); void readyRead(); private slots: void timeout(); private: void readData(QNetworkReply *reply); QNetworkReply *m_reply {nullptr}; QIODevice *m_storage {nullptr}; QByteArray *m_content {nullptr}; QTimer *m_timeoutTimer {nullptr}; QNetworkReply::NetworkError m_error {QNetworkReply::NoError}; QVariant m_data; QString m_errMsg; bool m_ownContentObject {false}; }; #endif // NETWORKREPLYHELPER_H
2,326
C++
.h
58
36.086207
111
0.673324
missdeer/hannah
39
1
7
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,653
lex_test.cpp
truongpt_meo/test/lex/lex_test.cpp
/* * Copyright (c) 2018/12 truong <truongptk30a3@gmail.com> * This file is released under the GPLv3 */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <string> #include <iostream> #include <fstream> #include "lex.h" #include "log.h" #include "error_code.h" #include "common.h" #include "catch.hh" using namespace std; TEST_CASE("lex test get single resource") { create_folder("data"); std::ofstream outfile ("data/xyz"); outfile << "1" << std::endl; outfile.close(); void* prm = NULL; REQUIRE(Success == LexCreate()); REQUIRE(InParameterInvalid == LexOpen(&prm, NULL)); REQUIRE(Success == LexOpen(&prm, (char*)"data/xyz")); REQUIRE(InParameterInvalid == LexOpen(&prm, (char*)"data/xyz")); REQUIRE(Success == LexClose(prm)); REQUIRE(Success == LexDestroy()); } TEST_CASE("lex test get multi resource") { int max_rsc = 10; vector<void*> prm = vector<void*>(10,NULL); REQUIRE(Success == LexCreate()); for (int i = 0; i < max_rsc; i++) { std::ofstream outfile ("data/xyz"+ to_string(i)); outfile.close(); REQUIRE(Success == LexOpen(&prm[i], ("data/xyz"+ to_string(i)).c_str() )); REQUIRE(NULL != prm[i]); } { std::ofstream outfile ("data/xyzk"); outfile.close(); REQUIRE(InParameterInvalid == LexOpen(&prm[0], (char*)"data/xyzk")); } { void* a_prm = NULL; std::ofstream outfile ("data/xyzf"); outfile.close(); REQUIRE(LexLimitResource == LexOpen(&a_prm, (char*)"data/xyzf")); REQUIRE(NULL == a_prm); } for (auto& p : prm) { REQUIRE(Success == LexClose(p)); } REQUIRE(Success == LexDestroy()); } TEST_CASE("lex test operator token") { std::ofstream outfile ("data/test1"); outfile << "-+*/()" << std::endl; outfile.close(); vector<Token> expect = vector<Token>{ {TokenMinus ,-1}, {TokenPlus ,-1}, {TokenMul ,-1}, {TokenDiv ,-1}, {TokenLP ,-1}, {TokenRP ,-1}, {TokenEoi ,-1} }; void* prm = NULL; REQUIRE(Success == LexCreate()); REQUIRE(Success == LexOpen(&prm, (char*)"data/test1")); Token T; int i = 0; while(Success == LexProc(prm, &T)) { Token t = expect[i]; REQUIRE(T.tok == t.tok); i++; if (TokenEoi == T.tok) { break; } } REQUIRE(i == expect.size()); REQUIRE(Success == LexClose(prm)); REQUIRE(Success == LexDestroy()); } TEST_CASE("lex test numeric token") { std::ofstream outfile ("data/test2"); outfile << "1 2 3 4" << std::endl; outfile.close(); vector<Token> expect = vector<Token>{ {TokenNumber ,1}, {TokenNumber ,2}, {TokenNumber ,3}, {TokenNumber ,4}, {TokenEoi ,-1} }; void* prm = NULL; REQUIRE(Success == LexCreate()); REQUIRE(Success == LexOpen(&prm, (char*)"data/test2")); Token T; int i = 0; while(Success == LexProc(prm, &T)) { Token t = expect[i]; REQUIRE(T.tok == t.tok); if (TokenNumber == t.tok) { REQUIRE(T.value == t.value); } i++; if (TokenEoi == T.tok) { break; } } REQUIRE(i == expect.size()); REQUIRE(Success == LexClose(prm)); REQUIRE(Success == LexDestroy()); } TEST_CASE("lex test arithmetic expression") { std::ofstream outfile ("data/test4"); outfile << "1 + 2 * 3 * 4" << std::endl; outfile.close(); vector<Token> expect = vector<Token>{ {TokenNumber ,1}, {TokenPlus ,-1}, {TokenNumber ,2}, {TokenMul ,-1}, {TokenNumber ,3}, {TokenMul ,-1}, {TokenNumber ,4}, {TokenEoi ,-1} }; void* prm = NULL; REQUIRE(Success == LexCreate()); REQUIRE(Success == LexOpen(&prm, (char*)"data/test4")); Token T; int i = 0; while(Success == LexProc(prm, &T)) { Token t = expect[i]; REQUIRE(T.tok == t.tok); if (TokenNumber == t.tok) { REQUIRE(T.value == t.value); } i++; if (TokenEoi == T.tok) { break; } } REQUIRE(i == expect.size()); REQUIRE(Success == LexClose(prm)); REQUIRE(Success == LexDestroy()); } TEST_CASE("lex test arithmetic expression with special character") { std::ofstream outfile ("data/test5"); outfile << "1 " << std::endl; outfile << " +" << std::endl; outfile << "2 " << std::endl; outfile << "* " << std::endl; outfile << "3 " << std::endl; outfile << " *" << std::endl; outfile << " 4" << std::endl; outfile << " /" << std::endl; outfile << " 5" << std::endl; outfile.close(); vector<Token> expect = vector<Token>{ {TokenNumber ,1}, {TokenPlus ,-1}, {TokenNumber ,2}, {TokenMul ,-1}, {TokenNumber ,3}, {TokenMul ,-1}, {TokenNumber ,4}, {TokenDiv ,-1}, {TokenNumber ,5}, {TokenEoi ,-1} }; void* prm = NULL; REQUIRE(Success == LexCreate()); REQUIRE(Success == LexOpen(&prm, (char*)"data/test5")); Token T; int i = 0; while(Success == LexProc(prm, &T)) { Token t = expect[i]; REQUIRE(T.tok == t.tok); if (TokenNumber == t.tok) { REQUIRE(T.value == t.value); } i++; if (TokenEoi == T.tok) { break; } } REQUIRE(i == expect.size()); REQUIRE(Success == LexClose(prm)); REQUIRE(Success == LexDestroy()); } TEST_CASE("lex test token: int type, L&R bracket, return") { std::ofstream outfile ("data/test6"); outfile << "int" << std::endl; outfile << "void" << std::endl; outfile << "{}" << std::endl; outfile << "return" << std::endl; outfile.close(); vector<Token> expect = vector<Token>{ {TokenIntType ,-1}, {TokenVoidType ,-1}, {TokenLBracket ,-1}, {TokenRBracket ,-1}, {TokenReturn ,-1}, {TokenEoi ,-1} }; void* prm = NULL; REQUIRE(Success == LexCreate()); REQUIRE(Success == LexOpen(&prm, (char*)"data/test6")); Token T; int i = 0; while(Success == LexProc(prm, &T)) { Token t = expect[i]; REQUIRE(T.tok == t.tok); i++; if (TokenEoi == T.tok) { break; } } REQUIRE(i == expect.size()); REQUIRE(Success == LexClose(prm)); REQUIRE(Success == LexDestroy()); } TEST_CASE("lex test token: int type, assign, identifier") { std::ofstream outfile ("data/test7"); outfile << "int cnt1234 = 10;" << std::endl; outfile.close(); vector<Token> expect = vector<Token>{ {TokenIntType ,-1}, {TokenIdentifier ,-1}, {TokenAssign ,-1}, {TokenNumber ,10}, {TokenSemi ,-1}, {TokenEoi ,-1} }; memcpy(expect[1].id_str,"cnt1234", strlen("cnt1234")); void* prm = NULL; REQUIRE(Success == LexCreate()); REQUIRE(Success == LexOpen(&prm, (char*)"data/test7")); Token T; int i = 0; while(Success == LexProc(prm, &T)) { Token t = expect[i]; REQUIRE(T.tok == t.tok); i++; if (TokenNumber == T.tok) { REQUIRE(T.value == t.value); } else if (TokenIdentifier == T.tok) { REQUIRE(0 == strncmp(T.id_str, t.id_str, strlen(t.id_str))); } else if (TokenEoi == T.tok) { break; } } REQUIRE(i == expect.size()); REQUIRE(Success == LexClose(prm)); REQUIRE(Success == LexDestroy()); } TEST_CASE("lex test bool operator: == <= >= !=") { std::ofstream outfile ("data/test8"); outfile << "1 == 2;" << std::endl; outfile << "1 >= 2;" << std::endl; outfile << "1 <= 2;" << std::endl; outfile << "1 != 2;" << std::endl; outfile << "1 > 2;" << std::endl; outfile << "1 < 2;" << std::endl; outfile.close(); vector<Token> expect = vector<Token>{ {TokenNumber ,1}, {TokenEQ , -1}, {TokenNumber ,2}, {TokenSemi , -1}, {TokenNumber ,1}, {TokenGE ,-1}, {TokenNumber ,2}, {TokenSemi , -1}, {TokenNumber ,1}, {TokenLE ,-1}, {TokenNumber ,2}, {TokenSemi , -1}, {TokenNumber ,1}, {TokenNE ,-1}, {TokenNumber ,2}, {TokenSemi , -1}, {TokenNumber ,1}, {TokenGT ,-1}, {TokenNumber ,2}, {TokenSemi , -1}, {TokenNumber ,1}, {TokenLT ,-1}, {TokenNumber ,2}, {TokenSemi ,-1}, {TokenEoi ,-1} }; void* prm = NULL; REQUIRE(Success == LexCreate()); REQUIRE(Success == LexOpen(&prm, (char*)"data/test8")); Token T; int i = 0; while(Success == LexProc(prm, &T)) { Token t = expect[i]; if (T.tok != t.tok) { mlog(ERROR,"%s == %s\n",tok2str(T.tok), tok2str(t.tok)); mlog(ERROR, "error index %d\n",i); REQUIRE(T.tok == t.tok); } if (TokenNumber == t.tok) { REQUIRE(T.value == t.value); } i++; if (TokenEoi == T.tok) { break; } } REQUIRE(i == expect.size()); REQUIRE(Success == LexClose(prm)); REQUIRE(Success == LexDestroy()); } TEST_CASE("lex test if-then- operator: == <= >= !=") { std::ofstream outfile ("data/test9"); outfile << "if (1 == 2)"<< std::endl; outfile << "{1; }"<< std::endl; outfile << "else "<< std::endl; outfile << "{2; }" << std::endl; outfile.close(); vector<Token> expect = vector<Token>{ {TokenIf, -1}, {TokenLP, -1}, {TokenNumber, 1}, {TokenEQ, -1}, {TokenNumber, 2}, {TokenRP, -1}, {TokenLBracket,-1}, {TokenNumber, 1}, {TokenSemi, -1}, {TokenRBracket,-1}, {TokenElse, -1}, {TokenLBracket,-1}, {TokenNumber, 2}, {TokenSemi, -1}, {TokenRBracket,-1}, {TokenEoi ,-1} }; void* prm = NULL; REQUIRE(Success == LexCreate()); REQUIRE(Success == LexOpen(&prm, (char*)"data/test9")); Token T; int i = 0; while(Success == LexProc(prm, &T)) { Token t = expect[i]; if (T.tok != t.tok) { mlog(ERROR,"%s == %s\n",tok2str(T.tok), tok2str(t.tok)); mlog(ERROR, "error index %d\n",i); REQUIRE(T.tok == t.tok); } if (TokenNumber == t.tok) { REQUIRE(T.value == t.value); } i++; if (TokenEoi == T.tok) { break; } } REQUIRE(i == expect.size()); REQUIRE(Success == LexClose(prm)); REQUIRE(Success == LexDestroy()); } TEST_CASE("lex test operator: == <= >= !=") { std::ofstream outfile ("data/test10"); outfile << "& && | || ^"<< std::endl; outfile.close(); vector<Token> expect = vector<Token>{ {TokenBitAnd,-1}, {TokenAnd, -1}, {TokenBitOr, -1}, {TokenOr, 2}, {TokenBitXor,-1}, {TokenEoi ,-1} }; void* prm = NULL; REQUIRE(Success == LexCreate()); REQUIRE(Success == LexOpen(&prm, (char*)"data/test10")); Token T; int i = 0; while(Success == LexProc(prm, &T)) { Token t = expect[i]; if (T.tok != t.tok) { mlog(ERROR,"%s == %s\n",tok2str(T.tok), tok2str(t.tok)); mlog(ERROR, "error index %d\n",i); REQUIRE(T.tok == t.tok); } if (TokenNumber == t.tok) { REQUIRE(T.value == t.value); } i++; if (TokenEoi == T.tok) { break; } } REQUIRE(i == expect.size()); REQUIRE(Success == LexClose(prm)); REQUIRE(Success == LexDestroy()); } TEST_CASE("lex test string") { std::ofstream outfile ("data/test11"); outfile << " \"conchocon\" " << std::endl; outfile.close(); vector<Token> expect = vector<Token>{ {TokenString ,-1}, {TokenEoi ,-1} }; memcpy(expect[0].str,"conchocon", strlen("conchocon")); void* prm = NULL; REQUIRE(Success == LexCreate()); REQUIRE(Success == LexOpen(&prm, (char*)"data/test11")); Token T; int i = 0; while(Success == LexProc(prm, &T)) { Token t = expect[i]; REQUIRE(T.tok == t.tok); i++; if (TokenNumber == T.tok) { REQUIRE(T.value == t.value); } else if (TokenString == T.tok) { REQUIRE(0 == strncmp(T.str, t.str, strlen(t.str))); } else if (TokenEoi == T.tok) { break; } } REQUIRE(i == expect.size()); REQUIRE(Success == LexClose(prm)); REQUIRE(Success == LexDestroy()); }
12,888
C++
.cpp
448
22.004464
82
0.514099
truongpt/meo
38
2
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,654
mock_arch.cpp
truongpt_meo/test/intergration/mock_arch.cpp
#include <unordered_map> #include <iostream> #include <vector> #include <string.h> #include "error_code.h" #include "gen_internal.h" using namespace std; static char* mock_load(int32_t value, FILE* out_file); static char* mock_out(char* r, FILE* out_file); static char* mock_free(char* r, FILE* out_file); static char* mock_add(char* r1, char* r2, FILE* out_file); static char* mock_sub(char* r1, char* r2, FILE* out_file); static char* mock_mul(char* r1, char* r2, FILE* out_file); static char* mock_div(char* r1, char* r2, FILE* out_file); static char* mock_lt(char* r1, char* r2, FILE* out_file); static char* mock_le(char* r1, char* r2, FILE* out_file); static char* mock_gt(char* r1, char* r2, FILE* out_file); static char* mock_ge(char* r1, char* r2, FILE* out_file); static char* mock_eq(char* r1, char* r2, FILE* out_file); static char* mock_ne(char* r1, char* r2, FILE* out_file); static char* mock_or(char* r1, char* r2, FILE* out_file); static char* mock_and(char* r1, char* r2, FILE* out_file); static char* mock_b_or(char* r1, char* r2, FILE* out_file); static char* mock_b_xor(char* r1, char* r2, FILE* out_file); static char* mock_b_and(char* r1, char* r2, FILE* out_file); static char* mock_lt_j(char* r1, char* r2, char* l, FILE* out_file); static char* mock_le_j(char* r1, char* r2, char* l, FILE* out_file); static char* mock_gt_j(char* r1, char* r2, char* l, FILE* out_file); static char* mock_ge_j(char* r1, char* r2, char* l, FILE* out_file); static char* mock_eq_j(char* r1, char* r2, char* l, FILE* out_file); static char* mock_ne_j(char* r1, char* r2, char* l, FILE* out_file); static char* mock_jump(char* l, FILE* out_file); static char* mock_zero_j(char* r, char* l, FILE* out_file); static char* mock_label(char* l, FILE* out_file); static char* mock_func(char* name, int stack_size, FILE* out_file); static char* mock_func_exit(char* label, int stack_size, FILE* out_file); static char* mock_return(char* r, char* exit_label, FILE* out_file); static char* mock_var(char* var, FILE* out_file); static char* mock_local_var(char* var, int size, FILE* out_file); static char* mock_store(char* r, char* var, FILE* out_file); static char* mock_load_var(char* var, FILE* out_file); // register vector<char*> reg = {"r0","r1","r2","r3","r4"}; unordered_map<string, int32_t> g_variable; unordered_map<char*, int32_t> mem; int cur = 0; vector<int> return_value = {}; int p_index = 0; int32_t GenLoadX86_64(GenFuncTable *func) { func->f_load = &mock_load; func->f_out = &mock_out; func->f_free = &mock_free; func->f_var = &mock_var; func->f_l_var = &mock_local_var; func->f_add = &mock_add; func->f_sub = &mock_sub; func->f_mul = &mock_mul; func->f_div = &mock_div; func->f_lt = &mock_lt; func->f_le = &mock_le; func->f_gt = &mock_gt; func->f_ge = &mock_ge; func->f_eq = &mock_eq; func->f_ne = &mock_ne; func->f_or = &mock_or; func->f_and = &mock_and; func->f_b_or = &mock_b_or; func->f_b_xor = &mock_b_xor; func->f_b_and = &mock_b_and; func->f_lt_j = &mock_lt_j; func->f_le_j = &mock_le_j; func->f_gt_j = &mock_gt_j; func->f_ge_j = &mock_ge_j; func->f_eq_j = &mock_eq_j; func->f_ne_j = &mock_ne_j; func->f_jump = &mock_jump; func->f_zero_j = &mock_zero_j; func->f_label = &mock_label; func->f_func = &mock_func; func->f_func_exit = &mock_func_exit; func->f_return = &mock_return; func->f_store = &mock_store; func->f_load_var = &mock_load_var; for (auto r : reg) { mem[r] = 0; } cur = 0; p_index = 0; g_variable.clear(); return_value.clear(); return Success; } int32_t MockGetReturnValue() { if (p_index > return_value.size()) { cout << "Not having print out data" << endl; return -1; }; return return_value[p_index++]; } char* reg_alloc() { if (cur >= reg.size()) { cout << "Not have available register" << endl; return NULL; } return reg[cur++]; } void reg_free(char* r) { if (mem.find(r) == mem.end()) { // cout << "Free reg is not correct: " << r << endl; return; } reg[--cur] = r; } static char* mock_load(int32_t value, FILE* out_file) { char* r = reg_alloc(); if (NULL == r) { return NULL; } mem[r] = value; fprintf(out_file,"[LOAD]:\t %s = %d\n", r, value); return r; } static char* mock_out(char* r, FILE* out_file) { reg_free(r); return r; } static char* mock_free(char* r, FILE* out_file) { reg_free(r); return NULL; } static char* mock_add(char* r1, char* r2, FILE* out_file) { mem[r1] += mem[r2]; mem[r2] = 0; reg_free(r2); fprintf(out_file,"[ADD ]:\t %s = %s+%s\n",r1,r1,r2); return r1; } static char* mock_sub(char* r1, char* r2, FILE* out_file) { mem[r1] -= mem[r2]; mem[r2] = 0; reg_free(r2); fprintf(out_file,"[SUB ]:\t %s = %s-%s\n",r1,r1,r2); return r1; } static char* mock_mul(char* r1, char* r2, FILE* out_file) { mem[r1] *= mem[r2]; mem[r2] = 0; reg_free(r2); fprintf(out_file,"[MUL ]:\t %s = %s*%s\n",r1,r1,r2); return r1; } static char* mock_div(char* r1, char* r2, FILE* out_file) { mem[r1] /= mem[r2]; mem[r2] = 0; reg_free(r2); fprintf(out_file,"[DIV ]:\t %s = %s/%s\n",r1,r1,r2); return r1; } static char* mock_lt(char* r1, char* r2, FILE* out_file) { mem[r1] = (mem[r1] < mem[r2]); mem[r2] = 0; reg_free(r2); fprintf(out_file,"[LT ]:\t %s = %s < %s\n",r1,r1,r2); return r1; } static char* mock_le(char* r1, char* r2, FILE* out_file) { mem[r1] = (mem[r1] <= mem[r2]); mem[r2] = 0; reg_free(r2); fprintf(out_file,"[LE ]:\t %s = %s <= %s\n",r1,r1,r2); return r1; } static char* mock_gt(char* r1, char* r2, FILE* out_file) { mem[r1] = (mem[r1] > mem[r2]); mem[r2] = 0; reg_free(r2); fprintf(out_file,"[GT ]:\t %s = %s > %s\n",r1,r1,r2); return r1; } static char* mock_ge(char* r1, char* r2, FILE* out_file) { mem[r1] = (mem[r1] <= mem[r2]); mem[r2] = 0; reg_free(r2); fprintf(out_file,"[GE ]:\t %s = %s >= %s\n",r1,r1,r2); return r1; } static char* mock_eq(char* r1, char* r2, FILE* out_file) { mem[r1] = (mem[r1] == mem[r2]); mem[r2] = 0; reg_free(r2); fprintf(out_file,"[EQUA]:\t %s = %s == %s\n",r1,r1,r2); return r1; } static char* mock_ne(char* r1, char* r2, FILE* out_file) { mem[r1] = (mem[r1] != mem[r2]); mem[r2] = 0; reg_free(r2); fprintf(out_file,"[NE ]:\t %s = %s != %s\n",r1,r1,r2); return r1; } static char* mock_or(char* r1, char* r2, FILE* out_file) { mem[r1] = mem[r1] || mem[r2]; mem[r2] = 0; reg_free(r2); fprintf(out_file,"[OR ]:\t %s = %s || %s\n",r1,r1,r2); return r1; } static char* mock_and(char* r1, char* r2, FILE* out_file) { mem[r1] = mem[r1] && mem[r2]; mem[r2] = 0; reg_free(r2); fprintf(out_file,"[AND ]:\t %s = %s && %s\n",r1,r1,r2); return r1; } static char* mock_b_or(char* r1, char* r2, FILE* out_file) { mem[r1] = mem[r1] | mem[r2]; mem[r2] = 0; reg_free(r2); fprintf(out_file,"[BOR ]:\t %s = %s | %s\n",r1,r1,r2); return r1; } static char* mock_b_xor(char* r1, char* r2, FILE* out_file) { mem[r1] = mem[r1] ^ mem[r2]; mem[r2] = 0; reg_free(r2); fprintf(out_file,"[BXOR]:\t %s = %s ^ %s\n",r1,r1,r2); return r1; } static char* mock_b_and(char* r1, char* r2, FILE* out_file) { mem[r1] = mem[r1] & mem[r2]; mem[r2] = 0; reg_free(r2); fprintf(out_file,"[BAND]:\t %s = %s & %s\n",r1,r1,r2); return r1; } static char* mock_lt_j(char* r1, char* r2, char* l, FILE* out_file) { // TODO : add mock processing reg_free(r1); reg_free(r2); fprintf(out_file,"[JUMP]:\t %s if %s < %s\n",l,r1,r2); return l; } static char* mock_le_j(char* r1, char* r2, char* l, FILE* out_file) { // TODO : add mock processing reg_free(r1); reg_free(r2); fprintf(out_file,"[JUMP]:\t %s if %s <= %s\n",l,r1,r2); return l; } static char* mock_gt_j(char* r1, char* r2, char* l, FILE* out_file) { reg_free(r1); reg_free(r2); fprintf(out_file,"[JUMP]:\t %s if %s > %s\n",l,r1,r2); return l; } static char* mock_ge_j(char* r1, char* r2, char* l, FILE* out_file) { reg_free(r1); reg_free(r2); fprintf(out_file,"[JUMP]:\t %s if %s >= %s\n",l,r1,r2); return l; } static char* mock_eq_j(char* r1, char* r2, char* l, FILE* out_file) { reg_free(r1); reg_free(r2); fprintf(out_file,"[JUMP]:\t %s if %s == %s\n",l,r1,r2); return l; } static char* mock_ne_j(char* r1, char* r2, char* l, FILE* out_file) { reg_free(r1); reg_free(r2); fprintf(out_file,"[JUMP]:\t %s if %s != %s\n",l,r1,r2); return l; } static char* mock_jump(char* l, FILE* out_file) { fprintf(out_file,"[JUMP]:\t %s\n",l); return l; } static char* mock_zero_j(char* r, char* l, FILE* out_file) { fprintf(out_file,"[JPZR]:\t %s if %s == 0\n",l,r); } static char* mock_label(char* l, FILE* out_file) { fprintf(out_file,"[LBEL]:\t %s: <- label\n",l); return l; } static char* mock_func(char* name, int stack_size, FILE* out_file) { (void)stack_size; fprintf(out_file,"[FUNC]:\t %s:\n",name); return name; } static char* mock_func_exit(char* label, int stack_size, FILE* out_file) { (void)stack_size; fprintf(out_file,"[EXIT]:\t %s:\n",label); return label; } static char* mock_return(char* r, char* exit_label, FILE* out_file) { return_value.push_back(mem[r]); reg_free(r); fprintf(out_file,"[RET ]:\t %s\n",r); fprintf(out_file,"[GOTO]:\t %s\n",exit_label); return exit_label; } static char* mock_var(char* var, FILE* out_file) { // just allocate buffer for var string s_var(var); g_variable[s_var] = 0; fprintf(out_file,"[DECL]:\t %s\n",var); return var; } static char* mock_local_var(char* var, int size, FILE* out_file) { string s_var(var); g_variable[s_var] = 0; fprintf(out_file,"[DECL]:\t %s\n",var); return var; } static char* mock_store(char* var, char* r, FILE* out_file) { string s_var(var); if (g_variable.find(s_var) == g_variable.end()) { fprintf(out_file,"[FUCK]:\t %s not found\n",var); return NULL; } g_variable[s_var] = mem[r]; reg_free(r); fprintf(out_file,"[STOR]:\t %s = %s(%d)\n",var,r,mem[r]); return var; } static char* mock_load_var(char* var, FILE* out_file) { string s_var(var); char* r = reg_alloc(); mem[r] = g_variable[s_var]; fprintf(out_file,"[LOAD]:\t %s = %s(%d)\n",r,var,g_variable[s_var]); return r; }
10,730
C++
.cpp
368
25.630435
73
0.588024
truongpt/meo
38
2
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,656
parse_lex_test.cpp
truongpt_meo/test/intergration/parse_lex_test.cpp
/* * Copyright (c) 2020/07 gravieb <truongptk30a3@gmail.com> * This file is released under the GPLv3 */ #include <stdio.h> #include <string.h> #include <string> #include <iostream> #include <fstream> #include "lex.h" #include "gen.h" #include "parse.h" #include "error_code.h" #include "common.h" #include "catch.hh" using namespace std; int32_t MockGetReturnValue(); TEST_CASE("basic arithmetic op parttern : return 1+2;") { create_folder("data"); std::ofstream outfile ("data/test1"); outfile << "int main() {" << std::endl; outfile << "return 1+2;" << std::endl; outfile << "}" << std::endl; outfile.close(); void* lex_prm = NULL; REQUIRE(Success == LexCreate()); REQUIRE(Success == LexOpen(&lex_prm, (char*)"data/test1")); void* gen_prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&gen_prm, GenX86_64, (char*)"data/out1")); void* parse_prm = NULL; REQUIRE(Success == ParseCreate()); REQUIRE(Success == ParseOpen(&parse_prm, lex_prm, gen_prm, false)); REQUIRE(Success == ParseProc(parse_prm)); REQUIRE(MockGetReturnValue() == (1+2)); ParseClose(parse_prm); ParseDestroy(); REQUIRE(Success == GenClose(gen_prm)); REQUIRE(Success == GenDestroy()); REQUIRE(Success == LexClose(lex_prm)); REQUIRE(Success == LexDestroy()); } TEST_CASE("basic variable parttern: int a; int b;") { std::ofstream outfile ("data/test2"); outfile << "int main() { " << std::endl; outfile << " int a; " << std::endl; outfile << " int b; " << std::endl; outfile << " a = 2; " << std::endl; outfile << " b = 5; " << std::endl; outfile << " a = a*b; " << std::endl; outfile << " return a*b;" << std::endl; outfile << "} " << std::endl; outfile.close(); void* lex_prm = NULL; REQUIRE(Success == LexCreate()); REQUIRE(Success == LexOpen(&lex_prm, (char*)"data/test2")); void* gen_prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&gen_prm, GenX86_64, (char*)"data/out2")); void* parse_prm = NULL; REQUIRE(Success == ParseCreate()); REQUIRE(Success == ParseOpen(&parse_prm, lex_prm, gen_prm, false)); REQUIRE(Success == ParseProc(parse_prm)); REQUIRE(MockGetReturnValue() == (2*5*5)); ParseClose(parse_prm); ParseDestroy(); REQUIRE(Success == GenClose(gen_prm)); REQUIRE(Success == GenDestroy()); REQUIRE(Success == LexClose(lex_prm)); REQUIRE(Success == LexDestroy()); } TEST_CASE("basic variable parttern: hw reg resource manager test") { std::ofstream outfile ("data/test3"); outfile << "int main() {" << std::endl; outfile << "int a1;" << std::endl; outfile << "int a2;" << std::endl; outfile << "int a3;" << std::endl; outfile << "int a4;" << std::endl; outfile << "int a5;" << std::endl; outfile << "int a6;" << std::endl; outfile << "int a7;" << std::endl; outfile << "a1 = 1;" << std::endl; outfile << "a2 = 2;" << std::endl; outfile << "a3 = 3;" << std::endl; outfile << "a4 = 4;" << std::endl; outfile << "a5 = 5;" << std::endl; outfile << "a6 = 6;" << std::endl; outfile << "return a1+a2+a3+a4+a5+a6;" << std::endl; outfile << "}" << std::endl; outfile.close(); void* lex_prm = NULL; REQUIRE(Success == LexCreate()); REQUIRE(Success == LexOpen(&lex_prm, (char*)"data/test3")); void* gen_prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&gen_prm, GenX86_64, (char*)"data/out3")); void* parse_prm = NULL; REQUIRE(Success == ParseCreate()); REQUIRE(Success == ParseOpen(&parse_prm, lex_prm, gen_prm, false)); REQUIRE(Success == ParseProc(parse_prm)); REQUIRE(MockGetReturnValue() == (1+2+3+4+5+6)); ParseClose(parse_prm); ParseDestroy(); REQUIRE(Success == GenClose(gen_prm)); REQUIRE(Success == GenDestroy()); REQUIRE(Success == LexClose(lex_prm)); REQUIRE(Success == LexDestroy()); } TEST_CASE("relational basic pattern") { std::ofstream outfile ("data/test4"); outfile << "int main() {" << std::endl; outfile << "return 1 < 2;" << std::endl; outfile << "}" << std::endl; outfile.close(); void* lex_prm = NULL; REQUIRE(Success == LexCreate()); REQUIRE(Success == LexOpen(&lex_prm, (char*)"data/test4")); void* gen_prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&gen_prm, GenX86_64, (char*)"data/out4")); void* parse_prm = NULL; REQUIRE(Success == ParseCreate()); REQUIRE(Success == ParseOpen(&parse_prm, lex_prm, gen_prm, false)); REQUIRE(Success == ParseProc(parse_prm)); REQUIRE(MockGetReturnValue() == 1); ParseClose(parse_prm); ParseDestroy(); REQUIRE(Success == GenClose(gen_prm)); REQUIRE(Success == GenDestroy()); REQUIRE(Success == LexClose(lex_prm)); REQUIRE(Success == LexDestroy()); } TEST_CASE("relational basic pattern with variable") { std::ofstream outfile ("data/test5"); outfile << "void main() {" << std::endl; outfile << "int a1;" << std::endl; outfile << "int a2;" << std::endl; outfile << "a1 = 1;" << std::endl; outfile << "a2 = 2;" << std::endl; outfile << "return a1 > a2;" << std::endl; outfile << "}" << std::endl; outfile.close(); void* lex_prm = NULL; REQUIRE(Success == LexCreate()); REQUIRE(Success == LexOpen(&lex_prm, (char*)"data/test5")); void* gen_prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&gen_prm, GenX86_64, (char*)"data/out5")); void* parse_prm = NULL; REQUIRE(Success == ParseCreate()); REQUIRE(Success == ParseOpen(&parse_prm, lex_prm, gen_prm, false)); REQUIRE(Success == ParseProc(parse_prm)); REQUIRE(MockGetReturnValue() == 0); ParseClose(parse_prm); ParseDestroy(); REQUIRE(Success == GenClose(gen_prm)); REQUIRE(Success == GenDestroy()); REQUIRE(Success == LexClose(lex_prm)); REQUIRE(Success == LexDestroy()); } TEST_CASE("equal basic pattern with variable") { std::ofstream outfile ("data/test6"); outfile << "int main() {" << std::endl; outfile << "int a1;" << std::endl; outfile << "int a2;" << std::endl; outfile << "a1 = 2;" << std::endl; outfile << "a2 = 2;" << std::endl; outfile << "return a1 == a2;" << std::endl; outfile << "}" << std::endl; outfile.close(); void* lex_prm = NULL; REQUIRE(Success == LexCreate()); REQUIRE(Success == LexOpen(&lex_prm, (char*)"data/test6")); void* gen_prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&gen_prm, GenX86_64, (char*)"data/out6")); void* parse_prm = NULL; REQUIRE(Success == ParseCreate()); REQUIRE(Success == ParseOpen(&parse_prm, lex_prm, gen_prm, false)); REQUIRE(Success == ParseProc(parse_prm)); REQUIRE(MockGetReturnValue() == 1); ParseClose(parse_prm); ParseDestroy(); REQUIRE(Success == GenClose(gen_prm)); REQUIRE(Success == GenDestroy()); REQUIRE(Success == LexClose(lex_prm)); REQUIRE(Success == LexDestroy()); } TEST_CASE("basic parttern with {}") { std::ofstream outfile ("data/test7"); outfile << "void main() {" << std::endl; outfile << "int a1;" << std::endl; outfile << "int a2;" << std::endl; outfile << "{a1 = 1;}" << std::endl; outfile << "a2 = 2;" << std::endl; outfile << "{{{{return a2;}}}}" << std::endl; outfile << "}" << std::endl; outfile.close(); void* lex_prm = NULL; REQUIRE(Success == LexCreate()); REQUIRE(Success == LexOpen(&lex_prm, (char*)"data/test7")); void* gen_prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&gen_prm, GenX86_64, (char*)"data/out7")); void* parse_prm = NULL; REQUIRE(Success == ParseCreate()); REQUIRE(Success == ParseOpen(&parse_prm, lex_prm, gen_prm, false)); REQUIRE(Success == ParseProc(parse_prm)); REQUIRE(MockGetReturnValue() == 2); ParseClose(parse_prm); ParseDestroy(); REQUIRE(Success == GenClose(gen_prm)); REQUIRE(Success == GenDestroy()); REQUIRE(Success == LexClose(lex_prm)); REQUIRE(Success == LexDestroy()); } TEST_CASE("basic if-else pattern") { std::ofstream outfile ("data/test8"); outfile << "int main() { " << std::endl; outfile << " int a1; " << std::endl; outfile << " int a2; " << std::endl; outfile << " a1 = 1; " << std::endl; outfile << " a2 = 2; " << std::endl; outfile << " if (a1 > a2) " << std::endl; outfile << " {return a1;} " << std::endl; outfile << " else " << std::endl; outfile << " {return a2;} " << std::endl; outfile << "} " << std::endl; outfile.close(); void* lex_prm = NULL; REQUIRE(Success == LexCreate()); REQUIRE(Success == LexOpen(&lex_prm, (char*)"data/test8")); void* gen_prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&gen_prm, GenX86_64, (char*)"data/out8")); void* parse_prm = NULL; REQUIRE(Success == ParseCreate()); REQUIRE(Success == ParseOpen(&parse_prm, lex_prm, gen_prm, false)); REQUIRE(Success == ParseProc(parse_prm)); // todo: consider how to verify result // REQUIRE(MockGetReturnValue() == 2); ParseClose(parse_prm); ParseDestroy(); REQUIRE(Success == GenClose(gen_prm)); REQUIRE(Success == GenDestroy()); REQUIRE(Success == LexClose(lex_prm)); REQUIRE(Success == LexDestroy()); } TEST_CASE("basic & && | || ^ pattern") { std::ofstream outfile ("data/test9"); outfile << "int main() { " << std::endl; outfile << " int a1; " << std::endl; outfile << " int a2; " << std::endl; outfile << " a1 = 1; " << std::endl; outfile << " a2 = 2; " << std::endl; outfile << " return (a1 && a2) + (a1 & a2) + (a1 || a2) + (a1 | a2) + (a1 ^ a2); " << std::endl; outfile << "} " << std::endl; outfile.close(); void* lex_prm = NULL; REQUIRE(Success == LexCreate()); REQUIRE(Success == LexOpen(&lex_prm, (char*)"data/test9")); void* gen_prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&gen_prm, GenX86_64, (char*)"data/out9")); void* parse_prm = NULL; REQUIRE(Success == ParseCreate()); REQUIRE(Success == ParseOpen(&parse_prm, lex_prm, gen_prm, false)); REQUIRE(Success == ParseProc(parse_prm)); int a1 = 1, a2 = 2; REQUIRE(MockGetReturnValue() == (a1 && a2) + (a1 & a2) + (a1 || a2) + (a1 | a2) + (a1 ^ a2)); ParseClose(parse_prm); ParseDestroy(); REQUIRE(Success == GenClose(gen_prm)); REQUIRE(Success == GenDestroy()); REQUIRE(Success == LexClose(lex_prm)); REQUIRE(Success == LexDestroy()); } TEST_CASE("simple test case to confirm bug?") { std::ofstream outfile ("data/test10"); outfile << "int main() { " << std::endl; outfile << " int a; " << std::endl; outfile << " a = 9; " << std::endl; outfile << " return a; " << std::endl; outfile << "} " << std::endl; outfile.close(); void* lex_prm = NULL; REQUIRE(Success == LexCreate()); REQUIRE(Success == LexOpen(&lex_prm, (char*)"data/test10")); void* gen_prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&gen_prm, GenX86_64, (char*)"data/out10")); void* parse_prm = NULL; REQUIRE(Success == ParseCreate()); REQUIRE(Success == ParseOpen(&parse_prm, lex_prm, gen_prm, false)); REQUIRE(Success == ParseProc(parse_prm)); REQUIRE(MockGetReturnValue() == 9); ParseClose(parse_prm); ParseDestroy(); REQUIRE(Success == GenClose(gen_prm)); REQUIRE(Success == GenDestroy()); REQUIRE(Success == LexClose(lex_prm)); REQUIRE(Success == LexDestroy()); } TEST_CASE("pointer 1") { std::ofstream outfile ("data/point1"); outfile << "int main() { " << std::endl; outfile << " int *a; " << std::endl; outfile << " int b = 10; " << std::endl; outfile << " a = &b; " << std::endl; outfile << " int b = 11; " << std::endl; outfile << " return *a; " << std::endl; outfile << "} " << std::endl; outfile.close(); void* lex_prm = NULL; REQUIRE(Success == LexCreate()); REQUIRE(Success == LexOpen(&lex_prm, (char*)"data/point1")); void* gen_prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&gen_prm, GenX86_64, (char*)"data/point1")); void* parse_prm = NULL; REQUIRE(Success == ParseCreate()); REQUIRE(Success == ParseOpen(&parse_prm, lex_prm, gen_prm, false)); REQUIRE(Success == ParseProc(parse_prm)); REQUIRE(MockGetReturnValue() == 11); ParseClose(parse_prm); ParseDestroy(); REQUIRE(Success == GenClose(gen_prm)); REQUIRE(Success == GenDestroy()); REQUIRE(Success == LexClose(lex_prm)); REQUIRE(Success == LexDestroy()); } TEST_CASE("pointer 2") { std::ofstream outfile ("data/point2"); outfile << "int main() { " << std::endl; outfile << " int *a; " << std::endl; outfile << " int b = 10; " << std::endl; outfile << " a = &b; " << std::endl; outfile << " *a = 11; " << std::endl; outfile << " return b; " << std::endl; outfile << "} " << std::endl; outfile.close(); void* lex_prm = NULL; REQUIRE(Success == LexCreate()); REQUIRE(Success == LexOpen(&lex_prm, (char*)"data/point2")); void* gen_prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&gen_prm, GenX86_64, (char*)"data/point2")); void* parse_prm = NULL; REQUIRE(Success == ParseCreate()); REQUIRE(Success == ParseOpen(&parse_prm, lex_prm, gen_prm, false)); REQUIRE(Success == ParseProc(parse_prm)); REQUIRE(MockGetReturnValue() == 11); ParseClose(parse_prm); ParseDestroy(); REQUIRE(Success == GenClose(gen_prm)); REQUIRE(Success == GenDestroy()); REQUIRE(Success == LexClose(lex_prm)); REQUIRE(Success == LexDestroy()); }
14,342
C++
.cpp
371
33.862534
103
0.587004
truongpt/meo
38
2
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,657
symtable_test.cpp
truongpt_meo/test/parse/symtable_test.cpp
/* * Copyright (c) 2020/08 gravieb <truongptk30a3@gmail.com> * This file is released under the GPLv3 */ #include "symtable.h" #include "error_code.h" #include "catch.hh" TEST_CASE("symtable add - find work") { SymbolTable st; char* s1 = "conchocon"; char* s2 = "conmeo"; char* s3 = "conchocanconmeoconmeoduoiconchuot"; REQUIRE(Success == symtable_init(&st)); REQUIRE(Success == symtable_add(&st, s1, 0)); REQUIRE(-1 != symtable_find(&st, s1, 0)); REQUIRE(-1 == symtable_find(&st, s2, 0)); REQUIRE(Success == symtable_add(&st, s2, 0)); REQUIRE(-1 != symtable_find(&st, s2, 0)); REQUIRE(-1 == symtable_find(&st, s3, 0)); REQUIRE(Success == symtable_add(&st, s3, 0)); REQUIRE(-1 != symtable_find(&st, s3, 0)); } TEST_CASE("symtable add - find valid work") { SymbolTable st; char* s1 = "a"; char* s2 = "b"; char* s3 = "c"; REQUIRE(Success == symtable_init(&st)); REQUIRE(Success == symtable_add(&st, s1, 0)); REQUIRE(Success == symtable_add(&st, s2, 1)); REQUIRE(Success == symtable_add(&st, s3, 2)); REQUIRE(-1 != symtable_find_valid(&st, s1, 100)); REQUIRE(-1 != symtable_find_valid(&st, s2, 100)); REQUIRE(-1 != symtable_find_valid(&st, s3, 100)); }
1,253
C++
.cpp
37
30.054054
58
0.620149
truongpt/meo
38
2
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,658
parse_test.cpp
truongpt_meo/test/parse/parse_test.cpp
/* * Copyright (c) 2020/07 gravieb <truongptk30a3@gmail.com> * This file is released under the GPLv3 */ #include <stdio.h> #include <string.h> #include <string> #include <iostream> #include <fstream> #include "lex.h" #include "gen.h" #include "parse.h" #include "error_code.h" #include "common.h" #include "catch.hh" using namespace std; int32_t MockLexCreate(vector<Token> tok_array); int32_t MockLexDestroy(); int32_t MockGetReturnValue(); TEST_CASE("parse test get single resource") { create_folder("data"); std::ofstream outfile ("data/testp0"); outfile << "0" << std::endl; outfile.close(); void* lex_prm = NULL; REQUIRE(Success == LexCreate()); REQUIRE(Success == LexOpen(&lex_prm, (char*)"data/in0")); void* gen_prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&gen_prm, GenX86_64, (char*)"data/out0")); void* prm = NULL; REQUIRE(Success == ParseCreate()); REQUIRE(Success == ParseOpen(&prm, lex_prm, gen_prm, false)); REQUIRE(Success == ParseClose(prm)); REQUIRE(Success == ParseDestroy()); REQUIRE(Success == LexClose(lex_prm)); REQUIRE(Success == LexDestroy()); REQUIRE(Success == GenClose(gen_prm)); REQUIRE(Success == GenDestroy()); } TEST_CASE("parse test get multi resource") { std::ofstream outfile ("data/testp1"); outfile << "0" << std::endl; outfile.close(); void* lex_prm = NULL; REQUIRE(Success == LexCreate()); REQUIRE(Success == LexOpen(&lex_prm, (char*)"data/in1")); void* gen_prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&gen_prm, GenX86_64, (char*)"data/out1")); int max_rsc = 10; vector<void*> prm = vector<void*>(10,NULL); REQUIRE(Success == ParseCreate()); for (auto& p : prm) { REQUIRE(Success == ParseOpen(&p, lex_prm, gen_prm, false)); REQUIRE(NULL != p); } REQUIRE(InParameterInvalid == ParseOpen(&prm[0], lex_prm, gen_prm, false)); void* a_prm = NULL; REQUIRE(ParseLimitResource == ParseOpen(&a_prm, lex_prm, gen_prm, false)); REQUIRE(NULL == a_prm); for (auto& p : prm) { REQUIRE(Success == ParseClose(p)); } REQUIRE(Success == ParseDestroy()); REQUIRE(Success == LexClose(lex_prm)); REQUIRE(Success == LexDestroy()); REQUIRE(Success == GenClose(gen_prm)); REQUIRE(Success == GenDestroy()); } TEST_CASE("parse test plus token: (1+2);") { int32_t mock_lex_prm; vector<Token> token_test = { {TokenIntType, -1}, {TokenIdentifier, -1}, {TokenLP, -1}, {TokenRP, -1}, {TokenLBracket, -1}, {TokenReturn, -1}, {TokenLP, -1}, {TokenNumber, 1}, {TokenPlus, -1}, {TokenNumber, 2}, {TokenRP, -1}, {TokenSemi, -1}, {TokenRBracket, -1}, {TokenEoi, -1} }; memcpy(token_test[1].id_str,"main", strlen("main")); MockLexCreate(token_test); void* gen_prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&gen_prm, GenX86_64, (char*)"data/out2")); void* parse_prm = NULL; REQUIRE(Success == ParseCreate()); REQUIRE(Success == ParseOpen(&parse_prm, (void*)&mock_lex_prm, gen_prm, false)); REQUIRE(Success == ParseProc(parse_prm)); REQUIRE(MockGetReturnValue() == (1+2)); ParseClose(parse_prm); ParseDestroy(); MockLexDestroy(); } TEST_CASE("parse test plus token: (2*3);") { int32_t mock_lex_prm; vector<Token> token_test = { {TokenIntType, -1}, {TokenIdentifier, -1}, {TokenLP, -1}, {TokenRP, -1}, {TokenLBracket, -1}, {TokenReturn, -1}, {TokenLP, -1}, {TokenNumber, 2}, {TokenMul, -1}, {TokenNumber, 3}, {TokenRP, -1}, {TokenSemi, -1}, {TokenRBracket, -1}, {TokenEoi, -1} }; memcpy(token_test[1].id_str,"main", strlen("main")); MockLexCreate(token_test); void* gen_prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&gen_prm, GenX86_64, (char*)"data/out2")); void* parse_prm = NULL; REQUIRE(Success == ParseCreate()); REQUIRE(Success == ParseOpen(&parse_prm, (void*)&mock_lex_prm, gen_prm, false)); REQUIRE(Success == ParseProc(parse_prm)); REQUIRE(MockGetReturnValue() == (2*3)); ParseClose(parse_prm); ParseDestroy(); MockLexDestroy(); } TEST_CASE("parse test plus token: (1+2*3+4);") { int32_t mock_lex_prm; vector<Token> token_test = { {TokenIntType, -1}, {TokenIdentifier, -1}, {TokenLP, -1}, {TokenRP, -1}, {TokenLBracket, -1}, {TokenReturn, -1}, {TokenLP, -1}, {TokenNumber, 1}, {TokenPlus, -1}, {TokenNumber, 2}, {TokenMul, -1}, {TokenNumber, 3}, {TokenPlus, -1}, {TokenNumber, 4}, {TokenRP, -1}, {TokenSemi, -1}, {TokenRBracket, -1}, {TokenEoi, -1} }; memcpy(token_test[1].id_str,"main", strlen("main")); MockLexCreate(token_test); void* gen_prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&gen_prm, GenX86_64, (char*)"data/out3")); void* parse_prm = NULL; REQUIRE(Success == ParseCreate()); REQUIRE(Success == ParseOpen(&parse_prm, (void*)&mock_lex_prm, gen_prm, false)); REQUIRE(Success == ParseProc(parse_prm)); REQUIRE(MockGetReturnValue() == (1+2*3+4)); ParseClose(parse_prm); ParseDestroy(); MockLexDestroy(); } TEST_CASE("parse test plus token: (1+2)*(3+4);") { int32_t mock_lex_prm; vector<Token> token_test = { {TokenIntType, -1}, {TokenIdentifier, -1}, {TokenLP, -1}, {TokenRP, -1}, {TokenLBracket, -1}, {TokenReturn, -1}, {TokenLP, -1}, {TokenNumber, 1}, {TokenPlus, -1}, {TokenNumber, 2}, {TokenRP, -1}, {TokenMul, -1}, {TokenLP, -1}, {TokenNumber, 3}, {TokenPlus, -1}, {TokenNumber, 4}, {TokenRP, -1}, {TokenSemi, -1}, {TokenRBracket, -1}, {TokenEoi, -1} }; memcpy(token_test[1].id_str,"main", strlen("main")); MockLexCreate(token_test); void* gen_prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&gen_prm, GenX86_64, (char*)"data/out4")); void* parse_prm = NULL; REQUIRE(Success == ParseCreate()); REQUIRE(Success == ParseOpen(&parse_prm, (void*)&mock_lex_prm, gen_prm, false)); REQUIRE(Success == ParseProc(parse_prm)); REQUIRE(MockGetReturnValue() == ((1+2)*(3+4))); ParseClose(parse_prm); ParseDestroy(); MockLexDestroy(); } TEST_CASE("parse test pattern: int xyz;") { int32_t mock_lex_prm; vector<Token> token_test = { {TokenIntType, -1}, {TokenIdentifier, -1}, {TokenLP, -1}, {TokenRP, -1}, {TokenLBracket, -1}, {TokenIntType, -1}, {TokenIdentifier, -1}, {TokenSemi, -1}, {TokenRBracket, -1}, {TokenEoi, -1} }; memcpy(token_test[1].id_str,"main", strlen("main")); memcpy(token_test[6].id_str,"xyz", strlen("xyz")); MockLexCreate(token_test); void* gen_prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&gen_prm, GenX86_64, (char*)"data/out5")); void* parse_prm = NULL; REQUIRE(Success == ParseCreate()); REQUIRE(Success == ParseOpen(&parse_prm, (void*)&mock_lex_prm, gen_prm, false)); REQUIRE(Success == ParseProc(parse_prm)); // TODO check result ParseClose(parse_prm); ParseDestroy(); MockLexDestroy(); } TEST_CASE("parse test return token: return (1+2);") { int32_t mock_lex_prm; vector<Token> token_test = { {TokenIntType, -1}, {TokenIdentifier, -1}, {TokenLP, -1}, {TokenRP, -1}, {TokenLBracket, -1}, {TokenReturn, -1}, {TokenLP, -1}, {TokenNumber, 1}, {TokenPlus, -1}, {TokenNumber, 2}, {TokenRP, -1}, {TokenSemi, -1}, {TokenRBracket, -1}, {TokenEoi, -1} }; memcpy(token_test[1].id_str,"main", strlen("main")); MockLexCreate(token_test); void* gen_prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&gen_prm, GenX86_64, (char*)"data/out2")); void* parse_prm = NULL; REQUIRE(Success == ParseCreate()); REQUIRE(Success == ParseOpen(&parse_prm, (void*)&mock_lex_prm, gen_prm, false)); REQUIRE(Success == ParseProc(parse_prm)); // todo: consider method to confirm ParseClose(parse_prm); ParseDestroy(); MockLexDestroy(); } TEST_CASE("parse test pattern: int a; a = 10; return a;") { int32_t mock_lex_prm; vector<Token> token_test = { {TokenIntType, -1}, {TokenIdentifier, -1}, {TokenLP, -1}, {TokenRP, -1}, {TokenLBracket, -1}, {TokenIntType, -1}, {TokenIdentifier, -1}, {TokenSemi, -1}, {TokenIdentifier, -1}, {TokenAssign, -1}, {TokenNumber, 10}, {TokenSemi, -1}, {TokenReturn, -1}, {TokenIdentifier, -1}, {TokenSemi, -1}, {TokenRBracket, -1}, {TokenEoi, -1} }; memcpy(token_test[1].id_str,"main", strlen("main")); memcpy(token_test[6].id_str,"abc", strlen("abc")); memcpy(token_test[8].id_str,"abc", strlen("abc")); memcpy(token_test[13].id_str,"abc", strlen("abc")); MockLexCreate(token_test); void* gen_prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&gen_prm, GenX86_64, (char*)"data/out6")); void* parse_prm = NULL; REQUIRE(Success == ParseCreate()); REQUIRE(Success == ParseOpen(&parse_prm, (void*)&mock_lex_prm, gen_prm, false)); REQUIRE(Success == ParseProc(parse_prm)); REQUIRE(MockGetReturnValue() == 10); ParseClose(parse_prm); ParseDestroy(); MockLexDestroy(); } TEST_CASE("parse test pattern: a+b;") { int32_t mock_lex_prm; vector<Token> token_test = { {TokenIntType, -1}, {TokenIdentifier,-1}, {TokenLP, -1}, {TokenRP, -1}, {TokenLBracket, -1}, {TokenIntType, -1}, {TokenIdentifier,-1}, //1 {TokenSemi, -1}, // int a; {TokenIntType, -1}, {TokenIdentifier,-1}, //4 {TokenSemi, -1}, // int b;/ {TokenIdentifier,-1}, //6: a = 1 {TokenAssign, -1}, {TokenNumber, 1}, {TokenSemi, -1}, {TokenIdentifier,-1}, //10: b = 2 {TokenAssign, -1}, {TokenNumber, 2}, {TokenSemi, -1}, {TokenReturn, -1}, // return a+b; {TokenIdentifier,-1}, //15 a {TokenPlus, -1}, {TokenIdentifier,-1}, // 17 b {TokenSemi, -1}, {TokenRBracket, -1}, {TokenEoi, -1} }; memcpy(token_test[1].id_str,"main", strlen("main")); memcpy(token_test[6].id_str,"a", strlen("a")); memcpy(token_test[9].id_str,"b", strlen("b")); memcpy(token_test[11].id_str,"a", strlen("a")); memcpy(token_test[15].id_str,"b", strlen("b")); memcpy(token_test[20].id_str,"a", strlen("a")); memcpy(token_test[22].id_str,"b", strlen("b")); MockLexCreate(token_test); void* gen_prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&gen_prm, GenX86_64, (char*)"data/out7")); void* parse_prm = NULL; REQUIRE(Success == ParseCreate()); REQUIRE(Success == ParseOpen(&parse_prm, (void*)&mock_lex_prm, gen_prm, false)); REQUIRE(Success == ParseProc(parse_prm)); REQUIRE(MockGetReturnValue() == (1+2)); ParseClose(parse_prm); ParseDestroy(); MockLexDestroy(); }
12,744
C++
.cpp
367
27.506812
84
0.539026
truongpt/meo
38
2
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,659
mock_lex.cpp
truongpt_meo/test/parse/mock_lex.cpp
/* * Copyright (c) 2020/07 gravieb <truongptk30a3@gmail.com> * This file is released under the GPLv3 */ #include "lex.h" #include "error_code.h" #include <vector> #include <stdlib.h> using namespace std; vector<Token> g_tok_array; int32_t tok_idx = 0; int32_t MockLexCreate(vector<Token> tok_array) { g_tok_array = tok_array; //g_tok_array(tok_array.begin(), tok_array.end()); tok_idx = 0; return Success; } int32_t MockLexDestroy() { g_tok_array.clear(); tok_idx = 0; return Success; } int32_t LexCreate(void) { return Success; } int32_t LexDestroy(void) { return Success; } int32_t LexOpen(void** prm, const char* file) { *prm = malloc(1); return Success; } int32_t LexClose(void* prm) { free(prm); return Success; } int32_t LexProc(void* prm, Token *t) { if (tok_idx >= g_tok_array.size()) { return -1; } *t = g_tok_array[tok_idx++]; return Success; } int32_t LexGetLine(void* prm) { return Success; }
1,001
C++
.cpp
54
15.759259
58
0.667024
truongpt/meo
38
2
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,660
ast_test.cpp
truongpt_meo/test/ast/ast_test.cpp
/* * Copyright (c) 2018/12 truong <truongptk30a3@gmail.com> * This file is released under the GPLv3 */ #include <stdio.h> #include <string> #include <iostream> #include <fstream> #include "ast.h" #include "gen.h" #include "parse.h" #include "error_code.h" #include "common.h" #include "catch.hh" using namespace std; TEST_CASE("ast test") { create_folder("data"); Token T = {TokenNumber, 10}; AstNode* node = ast_create_leaf(T); REQUIRE(NULL != node); REQUIRE(10 == node->value); } TEST_CASE("ast test operator +") { Token T = {TokenNumber, 10}; AstNode* node = ast_create_leaf(T); REQUIRE(NULL != node); REQUIRE(10 == node->value); REQUIRE(AstNumber == node->type); Token T1 = {TokenNumber, 5}; AstNode* node1 = ast_create_leaf(T1); REQUIRE(NULL != node1); REQUIRE(5 == node1->value); REQUIRE(AstNumber == node1->type); Token T2 = {TokenPlus, -1}; AstNode* node2 = ast_create_node(T2, node, node1); REQUIRE(NULL != node2); REQUIRE(AstPlus == node2->type); // todo // REQUIRE(15 == ast_interpret(NULL, node2)); } TEST_CASE("ast test operator -") { void* gen_prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&gen_prm, GenX86_64, (char*)"data/out1")); int32_t mock_lex_prm; void* parse_prm = NULL; REQUIRE(Success == ParseCreate()); REQUIRE(Success == ParseOpen(&parse_prm, (void*)&mock_lex_prm, gen_prm, false)); Token T = {TokenNumber, 10}; AstNode* node = ast_create_leaf(T); REQUIRE(NULL != node); REQUIRE(10 == node->value); REQUIRE(AstNumber == node->type); Token T1 = {TokenNumber, 5}; AstNode* node1 = ast_create_leaf(T1); REQUIRE(NULL != node1); REQUIRE(5 == node1->value); REQUIRE(AstNumber == node1->type); Token T2 = {TokenMinus, -1}; AstNode* node2 = ast_create_node(T2, node, node1); REQUIRE(NULL != node2); REQUIRE(AstMinus == node2->type); ast_gen((ParseParameter*)parse_prm, node2); ParseClose(parse_prm); ParseDestroy(); }
2,060
C++
.cpp
69
25.985507
84
0.643725
truongpt/meo
38
2
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,661
mock_arch.cpp
truongpt_meo/test/gen/mock_arch.cpp
#include <unordered_map> #include <iostream> #include <vector> #include <string.h> #include "error_code.h" #include "gen_internal.h" using namespace std; static char* mock_load(int32_t value, FILE* out_file); static char* mock_add(char* r1, char* r2, FILE* out_file); static char* mock_sub(char* r1, char* r2, FILE* out_file); static char* mock_mul(char* r1, char* r2, FILE* out_file); static char* mock_div(char* r1, char* r2, FILE* out_file); // register vector<char*> reg = {"r0","r1","r2","r3","r4"}; int cur = 0; unordered_map<char*, int32_t> mem; int32_t GenLoadX86_64(GenFuncTable *func) { func->f_load = &mock_load; func->f_add = &mock_add; func->f_sub = &mock_sub; func->f_mul = &mock_mul; func->f_div = &mock_div; for (auto r : reg) { mem[r] = 0; } cur = 0; return Success; } int32_t MockGetValue(char* r) { return mem[r]; } char* reg_alloc() { if (cur >= reg.size()) { cout << "Not have available register" << endl; return NULL; } return reg[cur++]; } void reg_free(char* r) { if (mem.find(r) == mem.end()) { cout << "Free reg is not correct" << endl; exit(1); } reg[--cur] = r; } static char* mock_load(int32_t value, FILE* out_file) { char* r = reg_alloc(); if (NULL == r) { return NULL; } mem[r] = value; return r; } static char* mock_add(char* r1, char* r2, FILE* out_file) { mem[r1] += mem[r2]; mem[r2] = 0; reg_free(r2); return r1; } static char* mock_sub(char* r1, char* r2, FILE* out_file) { mem[r1] -= mem[r2]; mem[r2] = 0; reg_free(r2); return r1; } static char* mock_mul(char* r1, char* r2, FILE* out_file) { mem[r1] *= mem[r2]; mem[r2] = 0; reg_free(r2); return r1; } static char* mock_div(char* r1, char* r2, FILE* out_file) { mem[r1] /= mem[r2]; mem[r2] = 0; reg_free(r2); return r1; }
1,923
C++
.cpp
84
19.416667
58
0.592004
truongpt/meo
38
2
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,662
gen_test.cpp
truongpt_meo/test/gen/gen_test.cpp
/* * Copyright (c) 2020/07 gravieb <truongptk30a3@gmail.com> * This file is released under the GPLv3 */ #include <stdio.h> #include <string> #include <iostream> #include <fstream> #include "gen.h" #include "error_code.h" #include "common.h" #include "catch.hh" using namespace std; int32_t MockGetValue(char* r); TEST_CASE("gen test get single resource") { create_folder("data"); void* prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&prm, GenX86_64, (char*)"data/test1")); REQUIRE(Success == GenClose(prm)); REQUIRE(Success == GenDestroy()); } TEST_CASE("gen test get multi resource") { int max_rsc = 10; vector<void*> prm = vector<void*>(10,NULL); REQUIRE(Success == GenCreate()); for (auto& p : prm) { REQUIRE(Success == GenOpen(&p, GenX86_64, (char*)"data/test2")); REQUIRE(NULL != p); } REQUIRE(InParameterInvalid == GenOpen(&prm[0], GenX86_64, (char*)"data/test21")); void* a_prm = NULL; REQUIRE(GenLimitResource == GenOpen(&a_prm, GenX86_64, (char*)"data/test22")); REQUIRE(NULL == a_prm); for (auto& p : prm) { REQUIRE(Success == GenClose(p)); } REQUIRE(Success == GenDestroy()); } TEST_CASE("gen test basic parttern + ") { void* prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&prm, GenX86_64, (char*)"data/test3")); char* r1 = GenLoad(prm, 1); REQUIRE(NULL != r1); char* r2 = GenLoad(prm, 2); REQUIRE(NULL != r2); char* r3 = GenPlus(prm, r1,r2); int32_t total = MockGetValue(r3); REQUIRE(total == (1+2)); REQUIRE(Success == GenClose(prm)); REQUIRE(Success == GenDestroy()); } TEST_CASE("gen test basic parttern -") { void* prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&prm, GenX86_64, (char*)"data/test3")); char* r1 = GenLoad(prm, 1); REQUIRE(NULL != r1); char* r2 = GenLoad(prm, 2); REQUIRE(NULL != r2); char* r3 = GenMinus(prm, r1,r2); int32_t total = MockGetValue(r3); REQUIRE(total == (1-2)); REQUIRE(Success == GenClose(prm)); REQUIRE(Success == GenDestroy()); } TEST_CASE("gen test basic parttern * ") { void* prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&prm, GenX86_64, (char*)"data/test3")); char* r1 = GenLoad(prm, 3); REQUIRE(NULL != r1); char* r2 = GenLoad(prm, 2); REQUIRE(NULL != r2); char* r3 = GenMul(prm, r1,r2); int32_t total = MockGetValue(r3); REQUIRE(total == (3*2)); REQUIRE(Success == GenClose(prm)); REQUIRE(Success == GenDestroy()); } TEST_CASE("gen test basic parttern / ") { void* prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&prm, GenX86_64, (char*)"data/test3")); char* r1 = GenLoad(prm, 10); REQUIRE(NULL != r1); char* r2 = GenLoad(prm, 2); REQUIRE(NULL != r2); char* r3 = GenDiv(prm, r1,r2); int32_t total = MockGetValue(r3); REQUIRE(total == (10/2)); REQUIRE(Success == GenClose(prm)); REQUIRE(Success == GenDestroy()); } TEST_CASE("gen test basic parttern combine arithmetic 10*2+4/2-5") { void* prm = NULL; REQUIRE(Success == GenCreate()); REQUIRE(Success == GenOpen(&prm, GenX86_64, (char*)"data/test3")); Token t1 = {TokenNumber, 10}; Token t2 = {TokenNumber, 2}; Token t3 = {TokenNumber, 4}; Token t4 = {TokenNumber, 2}; Token t5 = {TokenNumber, 5}; char* r1 = GenLoad(prm, 10); REQUIRE(NULL != r1); char* r2 = GenLoad(prm, 2); REQUIRE(NULL != r2); char* r3 = GenMul(prm, r1,r2); REQUIRE(NULL != r3); char* r4 = GenLoad(prm, 4); REQUIRE(NULL != r4); char* r5 = GenLoad(prm, 2); REQUIRE(NULL != r5); char* r6 = GenDiv(prm, r4, r5); char* r7 = GenPlus(prm, r3, r6); // 10*2+4/2 char* r8 = GenLoad(prm, 5); REQUIRE(NULL != r8); char* r9 = GenMinus(prm, r7, r8); // 10*2+4/2-5 int32_t total = MockGetValue(r9); REQUIRE(total == (10*2+4/2-5)); REQUIRE(Success == GenClose(prm)); REQUIRE(Success == GenDestroy()); }
4,130
C++
.cpp
131
27.145038
85
0.615424
truongpt/meo
38
2
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,664
common.h
truongpt_meo/test/inc/common.h
/* * Copyright (c) 2020/07 gravieb <truongptk30a3@gmail.com> * This file is released under the GPLv3 */ #include <stdio.h> #include <sys/stat.h> #include <string> #ifndef _COMMON_TEST_H_ #define _COMMON_TEST_H_ void create_folder(std::string folder) { struct stat sb; if (!(stat(folder.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode))) { system(("mkdir " + folder).c_str()); } } #endif
406
C++
.h
17
21.352941
67
0.65285
truongpt/meo
38
2
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,665
parse.h
truongpt_meo/inc/parse.h
/* * Copyright (c) 2020/07 gravieb <truongptk30a3@gmail.com> * This file is released under the GPLv3 */ #ifndef _PARSE_H_ #define _PARSE_H_ #include <stdio.h> #include "meo.h" #ifdef __cplusplus extern "C" { #endif int32_t ParseCreate(void); int32_t ParseDestroy(void); int32_t ParseOpen(void** prm, void* scan_prm, void* gen_prm, bool is_interpreter); int32_t ParseClose(void* prm); int32_t ParseProc(void* prm); #ifdef __cplusplus } #endif #endif
458
C++
.h
20
21.45
82
0.743056
truongpt/meo
38
2
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,666
lex.h
truongpt_meo/inc/lex.h
/* * Copyright (c) 2020/07 gravieb <truongptk30a3@gmail.com> * This file is released under the GPLv3 */ #ifndef _LEX_H_ #define _LEX_H_ #include <stdio.h> #include <stdint.h> #include "meo.h" #ifdef __cplusplus extern "C" { #endif int32_t LexCreate(void); int32_t LexDestroy(void); int32_t LexOpen(void** lex_prm, const char* file); int32_t LexClose(void* lex_prm); int32_t LexProc(void* lex_prm, Token *t); int32_t LexGetLine(void* lex_prm); #ifdef __cplusplus } #endif #endif
487
C++
.h
22
20.727273
58
0.734205
truongpt/meo
38
2
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,667
meo.h
truongpt_meo/inc/meo.h
/* * Copyright (c) 2020/07 gravieb <truongptk30a3@gmail.com> * This file is released under the GPLv3 */ #include <stdio.h> #include <stdint.h> #include <stdbool.h> #ifndef _MEO_H_ #define _MEO_H_ #define MAX_IDENT_LEN 32 #define MAX_STR_LEN 100 // todo: need dynamic #define MAX_IDENT_CNT 1000 #define MAX_LABEL_LEN 10 typedef struct Token { int32_t tok; union { int32_t value; struct { char id_str[MAX_IDENT_LEN]; bool left_value; }; char str[MAX_STR_LEN]; }; int32_t var_id; } Token; enum TokenType{ TokenEof, // operator TokenPlus, TokenMinus, TokenMul, TokenStar = TokenMul, // for pointer TokenDiv, TokenEQ, TokenNE, TokenLT, TokenLE, TokenGT, TokenGE, // Bitwise TokenBitAnd, TokenDereference = TokenBitAnd, // for dereference of pointer TokenBitOr, TokenBitXor, // Logical TokenAnd, TokenOr, // loop TokenIf, TokenElse, TokenWhile, TokenDo, TokenFor, // data type TokenIntType, TokenVoidType, TokenLongType, TokenString, TokenNumber, TokenLP, TokenRP, TokenLBracket, TokenRBracket, TokenComma, TokenAssign, TokenReturn, TokenEoi, TokenSemi, TokenIdentifier, }; #endif // _MEO_H_
1,352
C++
.h
71
14.352113
65
0.64218
truongpt/meo
38
2
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,668
error_code.h
truongpt_meo/inc/error_code.h
/* * Copyright (c) 2020/07 gravieb <truongptk30a3@gmail.com> * This file is released under the GPLv3 */ #ifndef _ERROR_CODE_H_ #define _ERROR_CODE_H_ enum ErrorCode { Success, InParameterInvalid, OpenFileError, SyntaxError, TokenError, SymbolNotFound, SymbolTableOver, VariableDeclared, LexLimitResource, ParseLimitResource, GenLimitResource }; #endif // _ERROR_CODE_H_
419
C++
.h
20
17.5
58
0.72796
truongpt/meo
38
2
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,669
symtable.h
truongpt_meo/inc/symtable.h
/* * Copyright (c) 2020/08 gravieb <truongptk30a3@gmail.com> * This file is released under the GPLv3 */ #ifndef _SYM_TABLE_H_ #define _SYM_TABLE_H_ #include <stdio.h> #include <stdint.h> #include "meo.h" #include "error_code.h" #define NSYMBOLS 1024 typedef struct SymbolData { char name[MAX_IDENT_LEN]; int32_t type; int32_t pointer_level; int32_t level; int32_t id; char* label; union { int32_t int_value; float float_value; }; } SymbolData; enum SymbolType { SymbolInt, SymbolFloat }; typedef struct SymbolTable { SymbolData data[NSYMBOLS]; int32_t cur_pos; int32_t cur_id; } SymbolTable; #ifdef __cplusplus extern "C" { #endif int32_t symtable_init(SymbolTable* st); int32_t symtable_add(SymbolTable* st, char* symbol, int level); int32_t symtable_remove(SymbolTable* st, char* symbol); int32_t symtable_find(SymbolTable* st, char* symbol, int level); int32_t symtable_find_valid(SymbolTable* st, char* symbol, int level); int32_t symtable_get_value(SymbolTable* st, char* symbol, int level); int32_t symtable_get_id(SymbolTable* st, char* symbol, int level); int32_t symtable_set_type(SymbolTable* st, char* symbol, int level, int32_t type); int32_t symtable_set_label(SymbolTable* st, char* symbol, int level, char* lable); char* symtable_get_label(SymbolTable* st, char* symbol, int level); int32_t symtable_set_value(SymbolTable* st, char* symbol, int level, int32_t value); int32_t symtable_clear_level(SymbolTable* st, int32_t level); int32_t symtable_set_pointer_level(SymbolTable* st, char* symbol, int level, int32_t pointer_level); #ifdef __cplusplus } #endif #endif
1,665
C++
.h
52
29.461538
100
0.734248
truongpt/meo
38
2
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,670
gen.h
truongpt_meo/inc/gen.h
/* * Copyright (c) 2020/07 gravieb <truongptk30a3@gmail.com> * This file is released under the GPLv3 */ #include <stdio.h> #include <stdlib.h> #include "meo.h" #ifndef _GEN_ASM_H_ #define _GEN_ASM_H_ #ifdef __cplusplus extern "C" { #endif enum GenArch { GenX86_64, GenArm }; int32_t GenCreate(void); int32_t GenDestroy(void); int32_t GenOpen(void** gen_prm, int32_t arch, char* out_file); int32_t GenClose(void* gen_prm); int32_t GenGetLabel(void* gen_prm); char* GenLoad(void* gen_prm, int32_t value); char* GenFree(void* gen_prm, char* r); char* GenPlus(void* gen_prm, char* r1, char* r2); char* GenMinus(void* gen_prm, char* r1, char* r2); char* GenMul(void* gen_prm, char* r1, char* r2); char* GenDiv(void* gen_prm, char* r1, char* r2); char* GenLT(void* gen_prm, char* r1, char* r2); char* GenLE(void* gen_prm, char* r1, char* r2); char* GenGE(void* gen_prm, char* r1, char* r2); char* GenGT(void* gen_prm, char* r1, char* r2); char* GenEQ(void* gen_prm, char* r1, char* r2); char* GenNE(void* gen_prm, char* r1, char* r2); char* GenOr(void* gen_prm, char* r1, char* r2); char* GenAnd(void* gen_prm, char* r1, char* r2); char* GenBitOr(void* gen_prm, char* r1, char* r2); char* GenBitXor(void* gen_prm, char* r1, char* r2); char* GenBitAnd(void* gen_prm, char* r1, char* r2); char* GenLtJump(void* gen_prm, char* r1, char* r2, char* label); char* GenLeJump(void* gen_prm, char* r1, char* r2, char* label); char* GenGeJump(void* gen_prm, char* r1, char* r2, char* label); char* GenGtJump(void* gen_prm, char* r1, char* r2, char* label); char* GenEqJump(void* gen_prm, char* r1, char* r2, char* label); char* GenNeJump(void* gen_prm, char* r1, char* r2, char* label); char* GenJump(void* gen_prm, char* label); char* GenZeroJump(void* gen_prm, char* r, char* label); char* GenLabel(void* gen_prm, char* label); char* GenStrLabel(void* gen_prm, char* label, char* str); char* GenFunc(void* gen_prm, char* name, int stack_size); char* GenFuncArg(void* gen_prm, int arg_order); char* GenFuncExit(void* gen_prm, char* exit_label, int stack_size); char* GenFuncCall(void* gen_prm, char* name); char* GenArg(void* gen_prm, char* arg, int idx); void GenOut(void* gen_prm, char* r); char* GenGlobalVar(void* gen_prm, char* var); char* GenLocalVar(void* gen_prm, char* var, int size); char* GenStore(void* gen_prm, char* var, char* r); char* GenLoadVar(void* gen_prm, char* var); char* GenReturn(void* gen_prm, char* r, char* exit_label); char* GenRegBackup(void* gen_prm); char* GenRegRestore(void* gen_prm); #ifdef __cplusplus } #endif #endif
2,563
C++
.h
65
38.061538
67
0.701408
truongpt/meo
38
2
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,671
parse_internal.h
truongpt_meo/src/parse_internal.h
/* * Copyright (c) 2020/07 gravieb <truongptk30a3@gmail.com> * This file is released under the GPLv3 */ #include <stdlib.h> #include <stdbool.h> #include "symtable.h" #ifndef _PARSE_INTERNAL_H_ #define _PARSE_INTERNAL_H_ typedef struct StringMap { char id[MAX_IDENT_LEN]; char* label; } StringMap; typedef struct ParseParameter{ bool avail; bool is_interpret; void *lex_prm; void *gen_prm; SymbolTable symbol_table; Token cur_token; int var_level; StringMap var_map[MAX_IDENT_CNT]; int var_map_pos; } ParseParameter; #endif
577
C++
.h
25
19.96
58
0.716117
truongpt/meo
38
2
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,672
ast.h
truongpt_meo/src/ast.h
/* * Copyright (c) 2020/08 gravieb <truongptk30a3@gmail.com> * This file is released under the GPLv3 */ #include <stdio.h> #include <stdlib.h> #include "meo.h" #include "parse_internal.h" #ifndef _AST_H_ #define _AST_H_ #ifdef __cplusplus extern "C" { #endif typedef struct AstNode { int32_t type; union { int32_t value; char id_str[MAX_IDENT_LEN]; char str[MAX_STR_LEN]; char exit_label[MAX_LABEL_LEN]; }; int32_t var_type; int32_t var_level; // use to manage local var in scope int32_t arg_order; // use to handle function argument. // if statement: if (left) {mid} else {right}; // function: left -> function name, mid -> argument, right -> function body struct AstNode* left; struct AstNode* mid; struct AstNode* right; } AstNode; enum AstVarType{ AstVarGlobal, AstVarLocal }; enum AstType { AstPlus, AstMinus, AstMul, AstDiv, AstLT, AstLE, AstGT, AstGE, AstEQ, AstNE, AstDeclare, AstNumber, AstIntType, AstVoidType, AstString, AstIdentifier, AstLeftVar, AstRightVar, AstAssign, AstBitAnd, AstBitOr, AstBitXor, AstAnd, AstOr, AstIf, AstWhile, AstFunc, AstFuncArg, AstFuncCall, AstArgPass, AstReturn, // Link statements AstLink }; AstNode* ast_create_node(Token token, AstNode* left, AstNode* right); AstNode* ast_create_leaf(Token token); AstNode* ast_create_unary(Token token, AstNode* left); AstNode* ast_create_link(AstNode* left, AstNode* right); AstNode* ast_create_ifnode(AstNode* left, AstNode* mid, AstNode* right); AstNode* ast_create_func(AstNode* left, AstNode* mid, AstNode* right); AstNode* ast_create_arg_init(Token token, int arg_order); AstNode* ast_create_leaf(Token token); AstNode* ast_create_func_call(void); AstNode* ast_create_arg_pass(AstNode* arg, int arg_order); AstNode* ast_create_declare(AstNode* left, AstNode* right, int var_type); AstNode* ast_interpret(ParseParameter* parse_prm, AstNode* node); void* ast_compile(ParseParameter* parse_prm, AstNode* node); void ast_gen(ParseParameter* parse_prm, AstNode* node); void ast_map_init(ParseParameter* parse_prm); #ifdef __cplusplus } #endif #endif /* _AST_H_ */
2,281
C++
.h
88
22.227273
79
0.697931
truongpt/meo
38
2
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,673
gen_internal.h
truongpt_meo/src/gen_internal.h
/* * Copyright (c) 2020/07 gravieb <truongptk30a3@gmail.com> * This file is released under the GPLv3 */ #include <stdio.h> #include <stdlib.h> #ifndef _GEN_ASM_INTERNAL_H_ #define _GEN_ASM_INTERNAL_H_ #ifdef __cplusplus extern "C" { #endif typedef struct GenFuncTable { char* (*f_load)(int32_t value, FILE*); char* (*f_free)(char* r, FILE*); char* (*f_out)(char* r, FILE*); char* (*f_var)(char* var, FILE*); char* (*f_l_var)(char* var, int size, FILE*); char* (*f_add)(char* r1, char* r2, FILE*); char* (*f_sub)(char* r1, char* r2, FILE*); char* (*f_mul)(char* r1, char* r2, FILE*); char* (*f_div)(char* r1, char* r2, FILE*); char* (*f_lt)(char* r1, char* r2, FILE*); char* (*f_le)(char* r1, char* r2, FILE*); char* (*f_gt)(char* r1, char* r2, FILE*); char* (*f_ge)(char* r1, char* r2, FILE*); char* (*f_eq)(char* r1, char* r2, FILE*); char* (*f_ne)(char* r1, char* r2, FILE*); char* (*f_or)(char* r1, char* r2, FILE*); char* (*f_and)(char* r1, char* r2, FILE*); char* (*f_b_or)(char* r1, char* r2, FILE*); char* (*f_b_xor)(char* r1, char* r2, FILE*); char* (*f_b_and)(char* r1, char* r2, FILE*); char* (*f_lt_j)(char* r1, char* r2, char* label, FILE*); char* (*f_le_j)(char* r1, char* r2, char* label, FILE*); char* (*f_gt_j)(char* r1, char* r2, char* label, FILE*); char* (*f_ge_j)(char* r1, char* r2, char* label, FILE*); char* (*f_eq_j)(char* r1, char* r2, char* label, FILE*); char* (*f_ne_j)(char* r1, char* r2, char* label, FILE*); char* (*f_zero_j)(char* r, char* label, FILE*); char* (*f_jump)(char* label, FILE*); char* (*f_label)(char* label, FILE*); char* (*f_str_label)(char* label, char* str, FILE*); char* (*f_func)(char* name, int stack_size, FILE*); char* (*f_func_arg)(int arg_order, FILE*); char* (*f_func_exit)(char* exit_label, int stack_size, FILE*); char* (*f_func_call)(char* name, FILE*); char* (*f_arg)(char* arg, int idx, FILE*); char* (*f_reg_backup)(FILE*); char* (*f_reg_restore)(FILE*); char* (*f_store)(char* var, char* r, FILE*); char* (*f_load_var)(char* var, FILE*); char* (*f_return)(char* r, char* exit_label, FILE*); } GenFuncTable; int32_t GenLoadX86_64(GenFuncTable *func); #ifdef __cplusplus } #endif #endif
2,323
C++
.h
58
36.051724
66
0.576752
truongpt/meo
38
2
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,674
log.h
truongpt_meo/src/log.h
/* * Copyright (c) 2020/08 gravieb <truongptk30a3@gmail.com> * This file is released under the GPLv3 */ #include <stdio.h> #include <stdarg.h> #ifndef _LOG_H_ #define _LOG_H_ #ifdef __cplusplus extern "C" { #endif #define MLOG(...) do { mlog(__VA_ARGS__);} while(0) enum LogLevel { TRACE, DEBUG, INFO, WARN, ERROR, CLGT }; void set_log_level(int level); void mlog(int level, char* format, ...); char* tok2str(int tok); #ifdef __cplusplus } #endif #endif
489
C++
.h
27
15.814815
58
0.671806
truongpt/meo
38
2
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,675
K2ServerDriver.cpp
KinectToVR_k2vr-application/driver_KinectToVR/K2ServerDriver.cpp
#include "K2ServerDriver.h" #include <thread> #include <boost/lexical_cast.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/serialization/vector.hpp> #include <boost/serialization/string.hpp> int K2ServerDriver::init_ServerDriver( const std::string& k2_to_pipe, const std::string& k2_from_pipe, const std::string& k2_to_sem, const std::string& k2_from_sem, const std::string& k2_start_sem) { using namespace std::chrono_literals; _isActive = true; // initialize the semaphores try { // Create the *to* semaphore k2api_to_Semaphore = CreateSemaphoreA( NULL, //Security Attributes 0, //Initial State i.e.Non Signaled 1, //No. of Resources "Global\\k2api_to_sem");//Semaphore Name if (nullptr == k2api_to_Semaphore) { LOG(ERROR) << "Semaphore Creation Failed\n"; LOG(ERROR) << "Error No - " << GetLastError() << '\n'; return -1; } LOG(INFO) << "*TO* Semaphore Creation Success\n"; // Automatically release the sem after creation ReleaseSemaphore(k2api_to_Semaphore, 1, 0); // Create the *from* semaphore k2api_from_Semaphore = CreateSemaphoreA( NULL, //Security Attributes 0, //Initial State i.e.Non Signaled 1, //No. of Resources "Global\\k2api_from_sem");//Semaphore Name if (nullptr == k2api_from_Semaphore) { LOG(ERROR) << "Semaphore Creation Failed\n"; LOG(ERROR) << "Error No - " << GetLastError() << '\n'; return -1; } LOG(INFO) << "*FROM* Semaphore Creation Success\n"; // Create the *start* semaphore k2api_start_Semaphore = CreateSemaphoreA( NULL, //Security Attributes 0, //Initial State i.e.Non Signaled 1, //No. of Resources "Global\\k2api_start_sem");//Semaphore Name if (nullptr == k2api_start_Semaphore) { LOG(ERROR) << "Semaphore Creation Failed\n"; LOG(ERROR) << "Error No - " << GetLastError() << '\n'; return -1; } LOG(INFO) << "*START* Semaphore Creation Success\n"; } catch (std::exception const& e) { LOG(ERROR) << "Setting up server failed: " << e.what(); return -1; } // Log the prepended trackers for (auto& _tracker : trackerVector) LOG(INFO) << "Registered a pre-added tracker: " << _tracker.get_serial(); std::thread([&]() { // create chrono for limiting loop timing using clock = std::chrono::steady_clock; auto next_frame = clock::now(); LOG(INFO) << "Server thread started"; // Errors' case bool server_giveUp = false; int server_tries = 0; while (!server_giveUp) { try { // run until termination while (true) { while (_isActive) { // measure loop time, let's run at 140/s next_frame += std::chrono::milliseconds(1000 / 140); // Wait for the client to request a read while (WaitForSingleObject(k2api_start_Semaphore, 15000L) != WAIT_OBJECT_0) { LOG(INFO) << "Releasing the *TO* semaphore\n"; // Release the semaphore in case something hangs, // no request would take as long as 15 seconds anyway ReleaseSemaphore(k2api_to_Semaphore, 1, 0); } // Here, read from the *TO* pipe // Create the pipe file std::optional<HANDLE> ReaderPipe = CreateFile( TEXT("\\\\.\\pipe\\k2api_to_pipe"), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr); // Create the buffer char read_buffer[4096]; DWORD Read = DWORD(); std::string read_string; // Check if we're good if (ReaderPipe.has_value()) { // Read the pipe ReadFile(ReaderPipe.value(), read_buffer, 4096, &Read, nullptr); // Convert the message to string read_string = read_buffer; } else LOG(ERROR) << "Error: Pipe object was not initialized."; // Close the pipe CloseHandle(ReaderPipe.value()); // parse request, send reply and return try { // I don't know why, when and how, // but somehow K2API inserts this shit at index 62 std::string _s = read_string; if (_s.find("3120300a") == 62)_s.erase(62, 8); // Convert hex to readable ascii and parse std::string s = ktvr::asciiString(_s); #ifdef K2PAI_DEBUG LOG(INFO) << s; #endif // This is also in parsefromstring of K2Message. // Though, this time we want to catch any error ourselves. std::istringstream i(s); boost::archive::text_iarchive ia(i); // Deserialize now ktvr::K2Message response; ia >> response; parse_message(response); } catch (boost::archive::archive_exception const& e) { LOG(ERROR) << "Message may be corrupted. Boost serialization error: " << e.what(); } catch (std::exception const& e) { LOG(ERROR) << "Global parsing error: " << e.what(); } //Sleep until next frame, if time haven't passed yet std::this_thread::sleep_until(next_frame); } // if we're currently not running, just wait std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } } catch (...) // Catch everything { LOG(ERROR) << "Server loop has crashed! Restarting it now..."; server_tries++; // One more? if(server_tries > 3) { // We've crashed the third time now. Somethin's off.. really... LOG(ERROR) << "Server loop has already crashed 3 times. Giving up..."; server_giveUp = true; } } } }).detach(); // if everything went ok, return 0 return 0; } void replace_all(std::string& str, const std::string& from, const std::string& to) { if (from.empty()) return; size_t start_pos = 0; while ((start_pos = str.find(from, start_pos)) != std::string::npos) { str.replace(start_pos, from.length(), to); start_pos += to.length(); } } void K2ServerDriver::parse_message(const ktvr::K2Message& message) { std::string _reply; // Reply that will be sent to client ktvr::K2ResponseMessage _response; // Response message to be sent // Add the timestamp: parsing _response.messageManualTimestamp = K2API_GET_TIMESTAMP_NOW; // Parse the message if it's not invalid if (message.messageType != ktvr::K2MessageType::K2Message_Invalid) { // Switch based on the message type switch (message.messageType) { case ktvr::K2MessageType::K2Message_AddTracker: { // Check if the base exists if (message.tracker_base.has_value()) { // Check if the serial is okay if (!message.tracker_base.value().data.serial.empty()) { // Check for tracker with same serial bool exists_yet = false; for (K2Tracker& t : trackerVector) if (message.tracker_base.value().data.serial == t.get_serial()) exists_yet = true; // Already exists if (!exists_yet) { // Push new tracker to vector and return its id trackerVector.emplace_back(K2Tracker(message.tracker_base.value())); LOG(INFO) << "New tracker added! Serial: " + message.tracker_base.value().data.serial + " Role: " + ktvr::ITrackerType_Role_String.at(static_cast<ktvr::ITrackerType>(message.tracker_base.value().data.role)); if (message.tracker_base.value().data.isActive && // If autospawn is desired !trackerVector.at(message.id).is_added()) { // Spawn and set the state if (trackerVector.at(message.id).spawn()) { trackerVector.at(message.id).set_state( message.tracker_base.value().data.isActive); LOG(INFO) << "Tracker autospawned! Serial: " + message.tracker_base.value().data.serial + " Role: " + ktvr::ITrackerType_Role_String.at(static_cast<ktvr::ITrackerType>(message.tracker_base.value().data.role)); } else { LOG(INFO) << "Tracker autospawn exception! Serial: " + message.tracker_base.value().data.serial + " Role: " + ktvr::ITrackerType_Role_String.at(static_cast<ktvr::ITrackerType>(message.tracker_base.value().data.role)); _response.result = ktvr::K2ResponseMessageCode_SpawnFailed; } } // Compose the response _response.success = true; _response.id = (int)trackerVector.size() - 1; // ID // Copy the tracker base object _response.tracker_base = trackerVector.back().getTrackerBase(); _response.messageType = ktvr::K2ResponseMessageType::K2ResponseMessage_Tracker; } else { LOG(ERROR) << "Couldn't add new tracker. Serial already present."; _response.result = ktvr::K2ResponseMessageCode_AlreadyPresent; } } else { LOG(ERROR) << "Couldn't add new tracker. Serial is empty."; _response.result = ktvr::K2ResponseMessageCode_BadSerial; } } else { LOG(ERROR) << "Couldn't add new tracker. Tracker base is empty."; _response.result = ktvr::K2ResponseMessageCode_BadRequest; } }break; case ktvr::K2MessageType::K2Message_SetTrackerState: { // Check if desired tracker exists if (message.id < trackerVector.size() && message.id >= 0) { // Set tracker's state to one gathered from argument if (!trackerVector.at(message.id).is_added()) if (!trackerVector.at(message.id).spawn()) { // spawn if needed LOG(INFO) << "Tracker autospawn exception! Serial: " + trackerVector.at(message.id).get_serial(); _response.result = ktvr::K2ResponseMessageCode_SpawnFailed; } // Set the state trackerVector.at(message.id).set_state(message.state); LOG(INFO) << "Tracker id: " + std::to_string(message.id) + " state has been set to: " + std::to_string(message.state); // Update the tracker trackerVector.at(message.id).update(); // Compose the response _response.success = true; _response.id = message.id; // ID _response.messageType = ktvr::K2ResponseMessageType::K2ResponseMessage_ID; } else { LOG(ERROR) << "Couldn't set tracker id: " + std::to_string(message.id) + " state. Index out of bounds."; _response.result = ktvr::K2ResponseMessageCode_BadRequest; } }break; case ktvr::K2MessageType::K2Message_SetStateAll: { // Set all trackers' state for (K2Tracker& k2_tracker : trackerVector) { if (!k2_tracker.is_added()) if (!k2_tracker.spawn()) { // spawn if needed LOG(INFO) << "Tracker autospawn exception! Serial: " + k2_tracker.get_serial(); _response.result = ktvr::K2ResponseMessageCode_SpawnFailed; } k2_tracker.set_state(message.state); // set state k2_tracker.update(); // Update the tracker } LOG(INFO) << "All trackers' state has been set to: " + std::to_string(message.state); // Compose the response _response.success = true; _response.messageType = ktvr::K2ResponseMessageType::K2ResponseMessage_Success; }break; case ktvr::K2MessageType::K2Message_UpdateTrackerPose: { // Check if the pose exists if (message.tracker_pose.has_value()) { // Check if desired tracker exists if (message.id < trackerVector.size() && message.id >= 0) { // Update tracker pose (with time offset) trackerVector.at(message.id).set_pose(message.tracker_pose.value()); // Compose the response _response.success = true; _response.id = message.id; // ID _response.messageType = ktvr::K2ResponseMessageType::K2ResponseMessage_ID; } else { LOG(ERROR) << "Couldn't set tracker id: " + std::to_string(message.id) + " pose. Index out of bounds."; _response.result = ktvr::K2ResponseMessageCode_BadRequest; } } else { LOG(ERROR) << "Couldn't set tracker id: " + std::to_string(message.id) + " pose. Pose is empty."; _response.result = ktvr::K2ResponseMessageCode_BadRequest; } }break; case ktvr::K2MessageType::K2Message_UpdateTrackerData: { // Check if desired tracker exists if (message.id < trackerVector.size() && message.id >= 0) { // Update tracker data (with time offset) trackerVector.at(message.id).set_data(message.tracker_data); // Compose the response _response.success = true; _response.id = message.id; // ID _response.messageType = ktvr::K2ResponseMessageType::K2ResponseMessage_ID; } else { LOG(ERROR) << "Couldn't set tracker id: " + std::to_string(message.id) + " data. Index out of bounds."; _response.result = ktvr::K2ResponseMessageCode_BadRequest; } }break; case ktvr::K2MessageType::K2Message_DownloadTracker: { // Check if desired tracker exists if (message.id < trackerVector.size() && message.id >= 0) { // Copy the tracker object _response.tracker_base = trackerVector.at(message.id).getTrackerBase(); // Compose the response _response.success = true; _response.id = message.id; // ID _response.messageType = ktvr::K2ResponseMessageType::K2ResponseMessage_Tracker; } // In case we're searching with serial else if (message.id < 0 && !message.tracker_data.serial.empty()) { bool trackerFound = false; // If we can even search if (!trackerVector.empty()) { // Search in our trackers vector for (int _tracker_id = 0; _tracker_id < trackerVector.size(); _tracker_id++) { // If we've found the one if (message.tracker_data.serial == trackerVector.at(_tracker_id).get_serial()) { // Copy the tracker object _response.tracker_base = trackerVector.at(_tracker_id).getTrackerBase(); // Compose the response _response.success = true; _response.id = _tracker_id; // Return the ID _response.messageType = ktvr::K2ResponseMessageType::K2ResponseMessage_Tracker; LOG(INFO) << "Serial: " + trackerVector.at(_tracker_id).get_serial() + " <-> id: " + std::to_string(_response.id); // Exit loop trackerFound = true; break; } } } else { // If tracker was not found LOG(ERROR) << "Couldn't download tracker via serial: " + message.tracker_data.serial + " because there are no trackers added."; _response.result = ktvr::K2ResponseMessageCode_BadRequest; } // If tracker was not found if (!trackerFound) LOG(ERROR) << "Couldn't download tracker via serial: " + message.tracker_data.serial + ". Not found."; _response.result = ktvr::K2ResponseMessageCode_BadRequest; } else { LOG(ERROR) << "Couldn't download tracker via id: " + std::to_string(message.id) + " or serial. Index out of bounds / null."; _response.result = ktvr::K2ResponseMessageCode_BadRequest; } }break; case ktvr::K2MessageType::K2Message_RefreshTracker: { // Check if desired tracker exists if (message.id < trackerVector.size() && message.id >= 0) { // Update the tracker trackerVector.at(message.id).update(); // Compose the response _response.success = true; _response.id = message.id; // ID _response.messageType = ktvr::K2ResponseMessageType::K2ResponseMessage_ID; } else { LOG(ERROR) << "Couldn't refresh tracker with id: " + std::to_string(message.id) + ". Index out of bounds."; _response.result = ktvr::K2ResponseMessageCode_BadRequest; } }break; case ktvr::K2MessageType::K2Message_RequestRestart: { // Request the reboot if (!message.message_string.empty()) { LOG(INFO) << "Requesting OpenVR restart with reason: " + message.message_string; // Perform the request vr::VRServerDriverHost()->RequestRestart( message.message_string.c_str(), "vrstartup.exe", "", ""); // Compose the response _response.success = true; _response.messageType = ktvr::K2ResponseMessageType::K2ResponseMessage_Success; } else { LOG(ERROR) << "Couldn't request a reboot. Reason string is empty."; _response.result = ktvr::K2ResponseMessageCode_BadRequest; } }break; case ktvr::K2MessageType::K2Message_Ping: { // Compose the response _response.success = true; _response.messageType = ktvr::K2ResponseMessageType::K2ResponseMessage_Tracker; }break; default: LOG(ERROR) << "Couldn't process message. The message type was not set. (Type invalid)"; _response.result = ktvr::K2ResponseMessageCode_BadRequest; break; } } else { LOG(ERROR) << "Couldn't process message. Message had had invalid type."; _response.result = ktvr::K2ResponseMessageCode_ParsingError; // We're done, screw em if the type was bad ReleaseSemaphore(k2api_to_Semaphore, 1, 0); return; } // Check the return code if (_response.success) // If succeed, let's assume it's okay _response.result = ktvr::K2ResponseMessageCode_OK; // Set the manual timestamp _response.messageTimestamp = K2API_GET_TIMESTAMP_NOW; // Serialize the response _reply = // Serialize to hex format ktvr::hexString(_response.serializeToString()); // Check if the client wants a response and eventually send it if (message.want_reply) { // Here, write to the *from* pipe HANDLE WriterPipe = CreateNamedPipe( TEXT("\\\\.\\pipe\\k2api_from_pipe"), PIPE_ACCESS_INBOUND | PIPE_ACCESS_OUTBOUND, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE, 1, 4096, 4096, 1000L, nullptr); DWORD Written; // Let the client know that we'll be writing soon ReleaseSemaphore(k2api_from_Semaphore, 1, 0); // Read from the pipe ConnectNamedPipe(WriterPipe, nullptr); WriteFile(WriterPipe, _reply.c_str(), strlen(_reply.c_str()), &Written, nullptr); FlushFileBuffers(WriterPipe); // Disconnect and close the pipe DisconnectNamedPipe(WriterPipe); CloseHandle(WriterPipe); } } /* * FROM-TO * BEGIN-STRING_END: data.substr(data.rfind(begin) + begin.length()) * STRING_BEGIN-END: data.substr(0, data.rfind(end)) * BEGIN_END: data.substr(data.find(begin) + begin.length(), data.rfind(end) - end.length()) */
17,722
C++
.cpp
465
33.002151
128
0.665134
KinectToVR/k2vr-application
38
4
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,676
K2Tracker.cpp
KinectToVR_k2vr-application/driver_KinectToVR/K2Tracker.cpp
#include "K2Tracker.h" #include <openvr_driver.h> #include <string> #include <thread> #include <KinectToVR_API.h> K2Tracker::K2Tracker(ktvr::K2TrackerBase const& tracker_base) { _serial = tracker_base.data.serial; _role = tracker_base.data.role; _active = tracker_base.data.isActive; _pose = { 0 }; _pose.poseIsValid = true; // Otherwise tracker may disappear _pose.result = vr::TrackingResult_Running_OK; _pose.deviceIsConnected = tracker_base.data.isActive; _pose.qWorldFromDriverRotation.w = 1; _pose.qWorldFromDriverRotation.x = 0; _pose.qWorldFromDriverRotation.y = 0; _pose.qWorldFromDriverRotation.z = 0; _pose.qDriverFromHeadRotation.w = 1; _pose.qDriverFromHeadRotation.x = 0; _pose.qDriverFromHeadRotation.y = 0; _pose.qDriverFromHeadRotation.z = 0; _pose.vecPosition[0] = 0; _pose.vecPosition[1] = 0; _pose.vecPosition[2] = 0; } std::string K2Tracker::get_serial() const { return _serial; } void K2Tracker::update() { if (_index != vr::k_unTrackedDeviceIndexInvalid && _activated) { // If _active is false, then disconnect the tracker _pose.poseIsValid = _active; _pose.deviceIsConnected = _active; vr::VRServerDriverHost()->TrackedDevicePoseUpdated(_index, _pose, sizeof _pose); } } void K2Tracker::set_pose(ktvr::K2PosePacket const& pose) { try { // For handling PosePacket's time offset std::thread([&, pose]() { // Wait the specified time if (pose.millisFromNow > 0) std::this_thread::sleep_for(std::chrono::milliseconds( static_cast<int>(pose.millisFromNow))); // Just copy the values _pose.vecPosition[0] = pose.position.x(); _pose.vecPosition[1] = pose.position.y(); _pose.vecPosition[2] = pose.position.z(); _pose.qRotation.w = pose.orientation.w(); _pose.qRotation.x = pose.orientation.x(); _pose.qRotation.y = pose.orientation.y(); _pose.qRotation.z = pose.orientation.z(); // Automatically update the tracker when finished update(); // called from this }).detach(); } catch (...) { LOG(ERROR) << "Couldn't set tracker pose. An exception occurred."; } } void K2Tracker::set_data(ktvr::K2DataPacket const& data) { try { // For handling PosePacket's time offset std::thread([&, data]() { // Wait the specified time if (data.millisFromNow > 0) std::this_thread::sleep_for(std::chrono::milliseconds( static_cast<int>(data.millisFromNow))); // Not spawning, just pose validity _active = data.isActive; // Data may only change if the tracker isn't spawned if (!_added && !_activated) { LOG(INFO) << "Updating tracker's role: " << ktvr::ITrackerType_Role_String.at(static_cast<ktvr::ITrackerType>(_role)) << " to: " << ktvr::ITrackerType_Role_String.at(static_cast<ktvr::ITrackerType>(data.role)); _role = data.role; if(!data.serial.empty()) { LOG(INFO) << "Updating tracker's serial: " << _serial << " to: " << data.serial; _serial = data.serial; } else LOG(ERROR) << "Couldn't set tracker data. The provided serial was empty."; // Spawn automatically if (_active) { // Spawn and set the state spawn(); LOG(INFO) << "Tracker autospawned! Serial: " + get_serial() + " Role: " + ktvr::ITrackerType_Role_String.at(static_cast<ktvr::ITrackerType>(_role)); } } else LOG(ERROR) << "Couldn't set tracker data. It has been already added."; }).detach(); } catch (...) { LOG(ERROR) << "Couldn't set tracker data. An exception occurred."; } } void K2Tracker::set_state(bool state) { _active = state; } bool K2Tracker::spawn() { try { if (!_added && !_serial.empty()) { // Add device to OpenVR devices list vr::VRServerDriverHost()->TrackedDeviceAdded(_serial.c_str(), vr::TrackedDeviceClass_GenericTracker, this); _added = true; return true; } } catch (...) {} return false; } vr::TrackedDeviceIndex_t K2Tracker::get_index() const { return _index; } void K2Tracker::process_event(const vr::VREvent_t& event) { } vr::EVRInitError K2Tracker::Activate(vr::TrackedDeviceIndex_t index) { // Save the device index _index = index; // Get the properties handle for our controller _props = vr::VRProperties()->TrackedDeviceToPropertyContainer(_index); /* * Of course thanks to @SDraw */ // Set our universe ID vr::VRProperties()->SetUint64Property(_props, vr::Prop_CurrentUniverseId_Uint64, 2); // Create components vr::VRDriverInput()->CreateBooleanComponent(_props, "/input/system/click", &_components._system_click); vr::VRDriverInput()->CreateHapticComponent(_props, "/output/haptic", &_components._haptic); // Register all properties, dumped by sdraw originally vr::VRProperties()->SetStringProperty(_props, vr::Prop_TrackingSystemName_String, "lighthouse"); vr::VRProperties()->SetStringProperty(_props, vr::Prop_ModelNumber_String, "Vive Tracker Pro MV"); vr::VRProperties()->SetStringProperty(_props, vr::Prop_SerialNumber_String, _serial.c_str()); vr::VRProperties()->SetStringProperty(_props, vr::Prop_RenderModelName_String, "{htc}vr_tracker_vive_1_0"); vr::VRProperties()->SetBoolProperty(_props, vr::Prop_WillDriftInYaw_Bool, false); vr::VRProperties()->SetStringProperty(_props, vr::Prop_ManufacturerName_String, "HTC"); vr::VRProperties()->SetStringProperty(_props, vr::Prop_TrackingFirmwareVersion_String, "1541800000 RUNNER-WATCHMAN$runner-watchman@runner-watchman 2018-01-01 FPGA 512(2.56/0/0) BL 0 VRC 1541800000 Radio 1518800000"); vr::VRProperties()->SetStringProperty(_props, vr::Prop_HardwareRevision_String, "product 128 rev 2.5.6 lot 2000/0/0 0"); vr::VRProperties()->SetStringProperty(_props, vr::Prop_ConnectedWirelessDongle_String, "D0000BE000"); vr::VRProperties()->SetBoolProperty(_props, vr::Prop_DeviceIsWireless_Bool, true); vr::VRProperties()->SetBoolProperty(_props, vr::Prop_DeviceIsCharging_Bool, false); vr::VRProperties()->SetFloatProperty(_props, vr::Prop_DeviceBatteryPercentage_Float, 1.f); vr::HmdMatrix34_t l_transform = { -1.f, 0.f, 0.f, 0.f, 0.f, 0.f, -1.f, 0.f, 0.f, -1.f, 0.f, 0.f }; vr::VRProperties()->SetProperty(_props, vr::Prop_StatusDisplayTransform_Matrix34, &l_transform, sizeof(vr::HmdMatrix34_t), vr::k_unHmdMatrix34PropertyTag); vr::VRProperties()->SetBoolProperty(_props, vr::Prop_Firmware_UpdateAvailable_Bool, false); vr::VRProperties()->SetBoolProperty(_props, vr::Prop_Firmware_ManualUpdate_Bool, false); vr::VRProperties()->SetStringProperty(_props, vr::Prop_Firmware_ManualUpdateURL_String, "https://developer.valvesoftware.com/wiki/SteamVR/HowTo_Update_Firmware"); vr::VRProperties()->SetUint64Property(_props, vr::Prop_HardwareRevision_Uint64, 2214720000); vr::VRProperties()->SetUint64Property(_props, vr::Prop_FirmwareVersion_Uint64, 1541800000); vr::VRProperties()->SetUint64Property(_props, vr::Prop_FPGAVersion_Uint64, 512); vr::VRProperties()->SetUint64Property(_props, vr::Prop_VRCVersion_Uint64, 1514800000); vr::VRProperties()->SetUint64Property(_props, vr::Prop_RadioVersion_Uint64, 1518800000); vr::VRProperties()->SetUint64Property(_props, vr::Prop_DongleVersion_Uint64, 8933539758); vr::VRProperties()->SetBoolProperty(_props, vr::Prop_DeviceProvidesBatteryStatus_Bool, true); vr::VRProperties()->SetBoolProperty(_props, vr::Prop_DeviceCanPowerOff_Bool, true); vr::VRProperties()->SetStringProperty(_props, vr::Prop_Firmware_ProgrammingTarget_String, _serial.c_str()); vr::VRProperties()->SetInt32Property(_props, vr::Prop_DeviceClass_Int32, vr::TrackedDeviceClass_GenericTracker); vr::VRProperties()->SetBoolProperty(_props, vr::Prop_Firmware_ForceUpdateRequired_Bool, false); //vr::VRProperties()->SetUint64Property(_props, vr::Prop_ParentDriver_Uint64, 8589934597); vr::VRProperties()->SetStringProperty(_props, vr::Prop_ResourceRoot_String, "htc"); std::string l_registeredType("htc/vive_tracker"); l_registeredType.append(_serial); vr::VRProperties()->SetStringProperty(_props, vr::Prop_RegisteredDeviceType_String, l_registeredType.c_str()); vr::VRProperties()->SetBoolProperty(_props, vr::Prop_Identifiable_Bool, false); vr::VRProperties()->SetBoolProperty(_props, vr::Prop_Firmware_RemindUpdate_Bool, false); vr::VRProperties()->SetInt32Property(_props, vr::Prop_ControllerRoleHint_Int32, vr::TrackedControllerRole_Invalid); vr::VRProperties()->SetInt32Property(_props, vr::Prop_ControllerHandSelectionPriority_Int32, -1); vr::VRProperties()->SetStringProperty(_props, vr::Prop_NamedIconPathDeviceOff_String, "{htc}/icons/tracker_status_off.png"); vr::VRProperties()->SetStringProperty(_props, vr::Prop_NamedIconPathDeviceSearching_String, "{htc}/icons/tracker_status_searching.gif"); vr::VRProperties()->SetStringProperty(_props, vr::Prop_NamedIconPathDeviceSearchingAlert_String, "{htc}/icons/tracker_status_searching_alert.gif"); vr::VRProperties()->SetStringProperty(_props, vr::Prop_NamedIconPathDeviceReady_String, "{htc}/icons/tracker_status_ready.png"); vr::VRProperties()->SetStringProperty(_props, vr::Prop_NamedIconPathDeviceReadyAlert_String, "{htc}/icons/tracker_status_ready_alert.png"); vr::VRProperties()->SetStringProperty(_props, vr::Prop_NamedIconPathDeviceNotReady_String, "{htc}/icons/tracker_status_error.png"); vr::VRProperties()->SetStringProperty(_props, vr::Prop_NamedIconPathDeviceStandby_String, "{htc}/icons/tracker_status_standby.png"); vr::VRProperties()->SetStringProperty(_props, vr::Prop_NamedIconPathDeviceAlertLow_String, "{htc}/icons/tracker_status_ready_low.png"); vr::VRProperties()->SetBoolProperty(_props, vr::Prop_HasDisplayComponent_Bool, false); vr::VRProperties()->SetBoolProperty(_props, vr::Prop_HasCameraComponent_Bool, false); vr::VRProperties()->SetBoolProperty(_props, vr::Prop_HasDriverDirectModeComponent_Bool, false); vr::VRProperties()->SetBoolProperty(_props, vr::Prop_HasVirtualDisplayComponent_Bool, false); /*Get tracker role*/ const std::string role_enum_string = ktvr::ITrackerType_String.at(static_cast<ktvr::ITrackerType>(_role)); /*Update controller type and input path*/ const std::string input_path = "{htc}/input/tracker/" + role_enum_string + "_profile.json"; vr::VRProperties()->SetStringProperty(_props, vr::Prop_InputProfilePath_String, input_path.c_str()); vr::VRProperties()->SetStringProperty(_props, vr::Prop_ControllerType_String, role_enum_string.c_str()); /*Update tracker's role in menu*/ std::string l_registeredDevice("/devices/htc/vive_tracker"); l_registeredDevice.append(_serial); vr::VRSettings()->SetString(vr::k_pch_Trackers_Section, l_registeredDevice.c_str(), ktvr::ITrackerType_Role_String.at(static_cast<ktvr::ITrackerType>(_role))); /*Mark tracker as activated*/ _activated = true; return vr::VRInitError_None; } vr::DriverPose_t K2Tracker::GetPose() { return _pose; } ktvr::K2TrackerBase K2Tracker::getTrackerBase() { // Copy the data _trackerBase.data.serial = _serial; _trackerBase.data.role = _role; _trackerBase.data.isActive = _active; // Copy the position _trackerBase.pose.position.x() = _pose.vecPosition[0]; _trackerBase.pose.position.y() = _pose.vecPosition[1]; _trackerBase.pose.position.z() = _pose.vecPosition[2]; // Copy the orientation _trackerBase.pose.orientation.w() = _pose.qRotation.w; _trackerBase.pose.orientation.x() = _pose.qRotation.x; _trackerBase.pose.orientation.y() = _pose.qRotation.y; _trackerBase.pose.orientation.z() = _pose.qRotation.z; // Return the base object return _trackerBase; }
11,477
C++
.cpp
248
43.342742
131
0.736644
KinectToVR/k2vr-application
38
4
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,677
K2ServerProvider.cpp
KinectToVR_k2vr-application/driver_KinectToVR/K2ServerProvider.cpp
#include <iostream> #include <Windows.h> #include <thread> #include <openvr_driver.h> #include <K2Tracker.h> #include <K2ServerDriver.h> namespace k2_driver { class K2ServerProvider : public vr::IServerTrackedDeviceProvider { K2ServerDriver m_ServerDriver; public: K2ServerProvider() { LOG(INFO) << "Provider component creation has started"; } vr::EVRInitError Init(vr::IVRDriverContext* pDriverContext) override { // NOTE 1: use the driver context. Sets up a big set of globals VR_INIT_SERVER_DRIVER_CONTEXT(pDriverContext); LOG(INFO) << "Driver context init success"; // Initialize communication with K2API const int initCode = m_ServerDriver.init_ServerDriver(); // Default IPC addresses LOG(INFO) << "Driver's IPC server init code: " + std::to_string(initCode); if (initCode == 0) { LOG(INFO) << "OpenVR ServerDriver init success"; return vr::VRInitError_None; } LOG(ERROR) << "OpenVR ServerDriver init failure! Aborting..."; return vr::VRInitError_Driver_Failed; } void Cleanup() override { LOG(INFO) << "Cleaning up..."; m_ServerDriver.setActive(false); } const char* const* GetInterfaceVersions() override { return vr::k_InterfaceVersions; } // It's running every frame void RunFrame() override { } bool ShouldBlockStandbyMode() override { return false; } void EnterStandby() override { } void LeaveStandby() override { } }; } bool g_bExiting = false; class K2WatchdogDriver : public vr::IVRWatchdogProvider { public: K2WatchdogDriver() { m_pWatchdogThread = nullptr; } vr::EVRInitError Init(vr::IVRDriverContext* pDriverContext) override; void Cleanup() override; private: std::thread* m_pWatchdogThread; }; vr::EVRInitError K2WatchdogDriver::Init(vr::IVRDriverContext* pDriverContext) { VR_INIT_WATCHDOG_DRIVER_CONTEXT(pDriverContext); LOG(INFO) << "Watchdog init has started..."; g_bExiting = false; return vr::VRInitError_None; } void K2WatchdogDriver::Cleanup() { g_bExiting = true; } extern "C" __declspec(dllexport) void* HmdDriverFactory(const char* pInterfaceName, int* pReturnCode) { // ktvr::GetK2AppDataFileDir will create all directories by itself /* Initialize logging */ google::InitGoogleLogging(ktvr::GetK2AppDataLogFileDir("driver_KinectToVR.dll").c_str()); /* Log everything >=INFO to same file */ google::SetLogDestination(google::GLOG_INFO, ktvr::GetK2AppDataLogFileDir("driver_KinectToVR.dll").c_str()); google::SetLogFilenameExtension(".log"); FLAGS_logbufsecs = 0; //Set max timeout FLAGS_minloglevel = google::GLOG_INFO; LOG(INFO) << "~~~KinectToVR OpenVR Driver new logging session begins here!~~~"; LOG(INFO) << "Interface name: " << pInterfaceName; static k2_driver::K2ServerProvider k2_server_provider; static K2WatchdogDriver k2_watchdog_driver; LOG(INFO) << "KinectToVR OpenVR Driver will try to run on K2API's default addresses."; if (0 == strcmp(vr::IServerTrackedDeviceProvider_Version, pInterfaceName)) { return &k2_server_provider; } if (0 == strcmp(vr::IVRWatchdogProvider_Version, pInterfaceName)) { return &k2_watchdog_driver; } (*pReturnCode) = vr::VRInitError_None; if (pReturnCode) *pReturnCode = vr::VRInitError_Init_InterfaceNotFound; }
3,284
C++
.cpp
108
27.592593
109
0.746331
KinectToVR/k2vr-application
38
4
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,678
KinectToVR_API.cpp
KinectToVR_k2vr-application/KinectToVR_API/KinectToVR_API.cpp
#include "pch.h" #include "KinectToVR_API.h" void replace_all(std::string& str, const std::string& from, const std::string& to) { if (from.empty()) return; size_t start_pos = 0; while ((start_pos = str.find(from, start_pos)) != std::string::npos) { str.replace(start_pos, from.length(), to); start_pos += to.length(); } } template <class V> std::type_info const& var_type(V const& v) { return std::visit([](auto&& x)-> decltype(auto) { return typeid(x); }, v); } namespace ktvr { int init_k2api( const std::string& k2_to_pipe, const std::string& k2_from_pipe, const std::string& k2_to_sem, const std::string& k2_from_sem, const std::string& k2_start_sem) noexcept { try { // Copy pipe addresses k2api_to_pipe_address = k2_to_pipe; k2api_from_pipe_address = k2_from_pipe; // Open existing *to* semaphore k2api_to_Semaphore = OpenSemaphoreA( SYNCHRONIZE | SEMAPHORE_MODIFY_STATE, FALSE, k2_to_sem.c_str()); //Semaphore Name // Open existing *from* semaphore k2api_from_Semaphore = OpenSemaphoreA( SYNCHRONIZE | SEMAPHORE_MODIFY_STATE, FALSE, k2_from_sem.c_str()); //Semaphore Name // Open existing *start* semaphore k2api_start_Semaphore = OpenSemaphoreA( SYNCHRONIZE | SEMAPHORE_MODIFY_STATE, FALSE, k2_start_sem.c_str()); //Semaphore Name if (k2api_to_Semaphore == nullptr || k2api_from_Semaphore == nullptr || k2api_start_Semaphore == nullptr) return -1; } catch (std::exception const& e) { return -1; } return 0; } // May be blocking int close_k2api() noexcept { try { CloseHandle(k2api_to_Semaphore); CloseHandle(k2api_from_Semaphore); CloseHandle(k2api_start_Semaphore); } catch (std::exception const& e) { return -1; } return 0; } std::string send_message(std::string const& data, const bool want_reply) noexcept(false) { // change the string to hex format std::string msg_data = hexString(data); ///// Send the message via named pipe ///// // Wait for the semaphore if it's locked WaitForSingleObject(k2api_to_Semaphore, INFINITE); // Here, write to the *to* pipe HANDLE API_WriterPipe = CreateNamedPipeA( k2api_to_pipe_address.c_str(), PIPE_ACCESS_INBOUND | PIPE_ACCESS_OUTBOUND, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE, 1, 4096, 4096, 1000L, nullptr); DWORD Written; // Let the server know we'll be writing soon ReleaseSemaphore(k2api_start_Semaphore, 1, 0); // Read from the pipe ConnectNamedPipe(API_WriterPipe, nullptr); WriteFile(API_WriterPipe, msg_data.c_str(), strlen(msg_data.c_str()), &Written, nullptr); FlushFileBuffers(API_WriterPipe); // Close the pipe DisconnectNamedPipe(API_WriterPipe); CloseHandle(API_WriterPipe); ///// Send the message via named pipe ///// ///// Receive the response via named pipe ///// if (want_reply) { // Wait for the server to request a response, max 1s if (WaitForSingleObject(k2api_from_Semaphore, 1000L) != WAIT_OBJECT_0) { k2api_last_error = "Server didn't respond after 1 second.\n"; return ""; //LOG(ERROR) << "Server didn't respond after 1 second.\n"; } // Here, read from the *from* pipe // Create the pipe file std::optional<HANDLE> API_ReaderPipe = CreateFile( TEXT("\\\\.\\pipe\\k2api_from_pipe"), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr); // Create the buffer char API_read_buffer[4096]; DWORD Read = DWORD(); // Check if we're good if (API_ReaderPipe.has_value()) { // Read the pipe ReadFile(API_ReaderPipe.value(), API_read_buffer, 4096, &Read, nullptr); } else { k2api_last_error = "Error: Pipe object was not initialized."; return ""; //LOG(ERROR) << "Error: Pipe object was not initialized."; } CloseHandle(API_ReaderPipe.value()); // Unlock the semaphore after job done ReleaseSemaphore(k2api_to_Semaphore, 1, 0); ///// Receive the response via named pipe ///// // I don't know why, when and how, // but somehow K2API inserts this shit at index 62 std::string _s = API_read_buffer; if (_s.find("3120300a") == 62)_s.erase(62, 8); // decode hex reply return asciiString(_s); // Return only the reply } else { // Unlock the semaphore after job done ReleaseSemaphore(k2api_to_Semaphore, 1, 0); return ""; // No reply } } K2ResponseMessage add_tracker(K2TrackerBase& tracker) noexcept { try { // Send and grab the response // Thanks to our constructors, // message will set all K2ResponseMessage response = send_message(K2Message(tracker)); // Overwrite the current tracker's id tracker.id = response.id; // Send the message and return return response; } catch (std::exception const& e) { return K2ResponseMessage(); // Success is set to false by default } } K2ResponseMessage download_tracker(int const& tracker_id) noexcept { try { // Send and grab the response // Thanks to our constructors, // message will set all // Send the message and return return send_message(K2Message(tracker_id)); } catch (std::exception const& e) { return K2ResponseMessage(); // Success is set to false by default } } K2ResponseMessage download_tracker(std::string const& tracker_serial) noexcept { try { // Send and grab the response // Send the message and return // Normally, we'd set some id to grab tracker from, // although this time it'll be -1, // forcing the driver to check if we've provided a serial K2Message message = K2Message(); message.messageType = K2Message_DownloadTracker; message.tracker_data.serial = tracker_serial; return send_message(message); } catch (std::exception const& e) { return K2ResponseMessage(); // Success is set to false by default } } K2ResponseMessage download_tracker(K2TrackerBase const& tracker) noexcept { try { // Send the message and return return download_tracker(tracker.id); } catch (std::exception const& e) { return K2ResponseMessage(); // Success is set to false by default } } std::tuple<K2ResponseMessage, long long, long long> test_connection() noexcept { try { K2Message message = K2Message(); message.messageType = K2Message_Ping; // Grab the current time and send the message const long long send_time = K2API_GET_TIMESTAMP_NOW; const auto response = send_message(message); // Return tuple with response and elapsed time const auto elapsed_time = // Always >= 0 std::clamp(K2API_GET_TIMESTAMP_NOW - send_time, static_cast<long long>(0), LLONG_MAX); return std::make_tuple(response, send_time, elapsed_time); } catch (std::exception const& e) { return std::make_tuple(K2ResponseMessage(), (long long)0, (long long)0); // Success is set to false by default } } std::string hexString(const std::string& s) { std::ostringstream ret; // Change ascii string to hex string for (char c : s) ret << std::hex << std::setfill('0') << std::setw(2) << std::nouppercase << (int)c; std::string ret_s = ret.str(); // Erase 0a00 if there is so if (ret_s.find("0a00") == 0)ret_s.erase(0, 4); return ret_s;; } std::string asciiString(const std::string& s) { std::ostringstream ret; // Start from the index 2, removing 0A00 occur for (std::string::size_type i = 0; i < s.length(); i += 2) ret << (char)(int)strtol(s.substr(i, 2).c_str(), nullptr, 16); return ret.str(); } }
7,587
C++
.cpp
257
25.797665
89
0.679429
KinectToVR/k2vr-application
38
4
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,679
K2ServerDriver.h
KinectToVR_k2vr-application/driver_KinectToVR/K2ServerDriver.h
#pragma once #include <iostream> #include <Windows.h> #include <optional> #include <chrono> #include "K2Tracker.h" #include <KinectToVR_API.h> class K2ServerDriver { public: // Parse a message from K2API void parse_message(const ktvr::K2Message& message); bool _isActive = false; // Server status // IPC things to work properly //Global Handle for Semaphore HANDLE k2api_to_Semaphore, k2api_from_Semaphore, k2api_start_Semaphore; [[nodiscard]] int init_ServerDriver( const std::string& k2_to_pipe = "\\\\.\\pipe\\k2api_to_pipe", const std::string& k2_from_pipe = "\\\\.\\pipe\\k2api_from_pipe", const std::string& k2_to_sem = "Global\\k2api_to_sem", const std::string& k2_from_sem = "Global\\k2api_from_sem", const std::string& k2_start_sem = "Global\\k2api_start_sem"); void setActive(bool m_isActive) { _isActive = m_isActive; } // Value should not be discarded, it'd be useless [[nodiscard]] bool isActive() const { return _isActive; } // Tracker vector with pre-appended 3 default lower body trackers std::vector<K2Tracker> trackerVector { K2Tracker( // WAIST TRACKER ktvr::K2TrackerBase( ktvr::K2TrackerPose(), // Default pose ktvr::K2TrackerData( "LHR-CB9AD1T0", // Serial ktvr::Tracker_Waist, // Role false // AutoAdd ) )), K2Tracker( // LEFT FOOT TRACKER ktvr::K2TrackerBase( ktvr::K2TrackerPose(), // Default pose ktvr::K2TrackerData( "LHR-CB9AD1T1", // Serial ktvr::Tracker_LeftFoot, // Role false // AutoAdd ) )), K2Tracker( // RIGHT FOOT TRACKER ktvr::K2TrackerBase( ktvr::K2TrackerPose(), // Default pose ktvr::K2TrackerData( "LHR-CB9AD1T2", // Serial ktvr::Tracker_RightFoot, // Role false // AutoAdd ) )) }; };
1,750
C++
.h
59
26.559322
67
0.6956
KinectToVR/k2vr-application
38
4
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,680
K2Tracker.h
KinectToVR_k2vr-application/driver_KinectToVR/K2Tracker.h
#pragma once #include <string> #include <openvr_driver.h> #include <KinectToVR_API.h> #define GLOG_NO_ABBREVIATED_SEVERITIES #include <glog/logging.h> class K2Tracker : public vr::ITrackedDeviceServerDriver { public: explicit K2Tracker(ktvr::K2TrackerBase const& tracker_base); virtual ~K2Tracker() = default; /** * \brief Get tracker serial number * \return Returns tracker's serial in std::string */ [[nodiscard]] std::string get_serial() const; /** * \brief Get device index in OpenVR * \return OpenVR device index in uint32_t */ [[nodiscard]] vr::TrackedDeviceIndex_t get_index() const; /** * \brief Update void for server driver */ void update(); /** * \brief Function processing OpenVR events */ void process_event(const vr::VREvent_t& event); /** * \brief Activate device (called from OpenVR) * \return InitError for OpenVR if we're set up correctly */ virtual vr::EVRInitError Activate(vr::TrackedDeviceIndex_t index); /** * \brief Deactivate tracker (remove) */ virtual void Deactivate() { // Clear device id _index = vr::k_unTrackedDeviceIndexInvalid; } /** * \brief Handle debug request (not needed/implemented) */ virtual void DebugRequest(const char* request, char* response_buffer, uint32_t response_buffer_size) { // No custom debug requests defined if (response_buffer_size >= 1) response_buffer[0] = 0; } virtual void EnterStandby() { } virtual void LeaveStandby() { } virtual bool ShouldBlockStandbyMode() { return false; } /** * \brief Get component handle (for OpenVR) */ void* GetComponent(const char* component) { // No extra components on this device so always return nullptr return NULL; } /** * \brief Return device's actual pose */ vr::DriverPose_t GetPose() override; // Update pose void set_pose(ktvr::K2PosePacket const& pose); // Update data (only if uninitialized) void set_data(ktvr::K2DataPacket const& data); void set_state(bool state); bool spawn(); // TrackedDeviceAdded // Get to know if tracker is activated (added) [[nodiscard]] bool is_added() const { return _added; } // Get to know if tracker is active (connected) [[nodiscard]] bool is_active() const { return _active; } // Get the base object [[nodiscard]] ktvr::K2TrackerBase getTrackerBase(); private: // Tracker base to be returned ktvr::K2TrackerBase _trackerBase; // Is tracker added/active bool _added = false, _active = false; bool _activated = false; // Stores the openvr supplied device index. vr::TrackedDeviceIndex_t _index; // Stores the devices current pose. vr::DriverPose_t _pose; // An identifier for OpenVR for when we want to make property changes to this device. vr::PropertyContainerHandle_t _props; // A struct for concise storage of all of the component handles for this device. struct TrackerComponents { vr::VRInputComponentHandle_t _system_click, _haptic; }; TrackerComponents _components; std::string _serial; int _role; };
2,997
C++
.h
98
28.020408
103
0.733868
KinectToVR/k2vr-application
38
4
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,681
KinectToVR_API.h
KinectToVR_k2vr-application/KinectToVR_API/KinectToVR_API.h
#pragma once #include <iostream> #include <Windows.h> #include <vector> #include <random> #include <sstream> #include <iomanip> #include <string> #include <chrono> #include <span> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/serialization/export.hpp> #include <boost/serialization/vector.hpp> #include <boost/serialization/array.hpp> #include <boost/serialization/utility.hpp> #include <boost/serialization/shared_ptr.hpp> #include <boost/serialization/optional.hpp> #include <boost/assign/list_of.hpp> #include <boost/assign.hpp> #include <boost/lexical_cast.hpp> #include <boost/unordered_map.hpp> #include <boost/math/special_functions/fpclassify.hpp> #include <Eigen/Dense> /* * Default IPC defines are: * * \\\\.\\pipe\\k2api_to_pipe * \\\\.\\pipe\\k2api_from_pipe * * Global\\k2api_to_sem * Global\\k2api_from_sem * Global\\k2api_start_sem */ #define K2API_GET_TIMESTAMP_NOW \ std::chrono::time_point_cast<std::chrono::microseconds> \ (std::chrono::system_clock::now()).time_since_epoch().count() #ifdef KINECTTOVR_API_EXPORTS #define KTVR_API __declspec(dllexport) #else #define KTVR_API __declspec(dllimport) #endif namespace boost::serialization { // Eigen serialization template <class Archive, typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols> void serialize(Archive& ar, Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>& t, const unsigned int file_version ) { for (size_t i = 0; i < t.size(); i++) ar & make_nvp(("m" + std::to_string(i)).c_str(), t.data()[i]); } template <class Archive, typename _Scalar> void serialize(Archive& ar, Eigen::Quaternion<_Scalar>& q, unsigned) { ar & BOOST_SERIALIZATION_NVP(q.w()) & BOOST_SERIALIZATION_NVP(q.x()) & BOOST_SERIALIZATION_NVP(q.y()) & BOOST_SERIALIZATION_NVP(q.z()); } template <class Archive, typename _Scalar> void serialize(Archive& ar, Eigen::Vector3<_Scalar>& v, unsigned) { ar & BOOST_SERIALIZATION_NVP(v.x()) & BOOST_SERIALIZATION_NVP(v.y()) & BOOST_SERIALIZATION_NVP(v.z()); } } namespace ktvr { // Device types for K2app enum ITrackingDeviceType { K2_KinectV1, K2_KinectV2, K2_PSMoveService, K2_Other, K2_Unknown }; // Global joint states enum ITrackedJointState { State_NotTracked, State_Inferred, State_Tracked }; // Global Joint Types, // see enumeration in external/Kinect enum ITrackedJointType { Joint_Head, Joint_Neck, Joint_SpineShoulder, Joint_ShoulderLeft, Joint_ElbowLeft, Joint_WristLeft, Joint_HandLeft, Joint_HandTipLeft, Joint_ThumbLeft, Joint_ShoulderRight, Joint_ElbowRight, Joint_WristRight, Joint_HandRight, Joint_HandTipRight, Joint_ThumbRight, Joint_SpineMiddle, Joint_SpineWaist, Joint_HipLeft, Joint_KneeLeft, Joint_AnkleLeft, Joint_FootLeft, Joint_HipRight, Joint_KneeRight, Joint_AnkleRight, Joint_FootRight, Joint_Total }; // OpenVR Tracker types enum ITrackerType { Tracker_Handed, Tracker_LeftFoot, Tracker_RightFoot, Tracker_LeftShoulder, Tracker_RightShoulder, Tracker_LeftElbow, Tracker_RightElbow, Tracker_LeftKnee, Tracker_RightKnee, Tracker_Waist, Tracker_Chest, Tracker_Camera, Tracker_Keyboard }; // K2API messaging types enum K2MessageType { K2Message_Invalid, // Default K2Message_AddTracker, // Add K2Message_SetTrackerState, K2Message_SetStateAll, // State K2Message_UpdateTrackerPose, K2Message_UpdateTrackerData, // Update K2Message_DownloadTracker, // Get tracker K2Message_RefreshTracker, // Refresh tracker pose K2Message_RequestRestart, // Request a restart K2Message_Ping // Test message }; // Return messaging types enum K2ResponseMessageType { K2ResponseMessage_Invalid, // Default K2ResponseMessage_ID, // Just the ID K2ResponseMessage_Success, // State success, type only for ping K2ResponseMessage_Tracker // Tracker object, includes ID too! }; // Return messenging types enum K2ResponseMessageCode { K2ResponseMessageCode_Exception = -10, // Excaption occured K2ResponseMessageCode_UnknownError = -1, // IDK K2ResponseMessageCode_Invalid = 0, // Default Invalid K2ResponseMessageCode_OK = 1, // Default OK K2ResponseMessageCode_SpawnFailed = 2, // Spawn failed, exception K2ResponseMessageCode_AlreadyPresent = 3, // Serial already present K2ResponseMessageCode_BadRequest = 4, // Unknown message type, wrong ID K2ResponseMessageCode_ParsingError = 5, // Global parsing exception K2ResponseMessageCode_BadSerial = 6 // Serial was empty }; // Alias for code readability typedef int JointTrackingState, TrackingDeviceType, MessageType, MessageCode; // Mapping enum to string for eliminating if-else loop const boost::unordered_map<ITrackerType, const char*> ITrackerType_String = boost::assign::map_list_of (Tracker_Handed, "vive_tracker_handed") (Tracker_LeftFoot, "vive_tracker_left_foot") (Tracker_RightFoot, "vive_tracker_right_foot") (Tracker_LeftShoulder, "vive_tracker_left_Shoulder") (Tracker_RightShoulder, "vive_tracker_right_shoulder") (Tracker_LeftElbow, "vive_tracker_left_elbow") (Tracker_RightElbow, "vive_tracker_right_elbow") (Tracker_LeftKnee, "vive_tracker_left_knee") (Tracker_RightKnee, "vive_tracker_right_knee") (Tracker_Waist, "vive_tracker_waist") (Tracker_Chest, "vive_tracker_chest") (Tracker_Camera, "vive_tracker_camera") (Tracker_Keyboard, "vive_tracker_keyboard"), ITrackerType_Role_String = boost::assign::map_list_of (Tracker_Handed, "TrackerRole_Handed") (Tracker_LeftFoot, "TrackerRole_LeftFoot") (Tracker_RightFoot, "TrackerRole_RightFoot") (Tracker_LeftShoulder, "TrackerRole_LeftShoulder") (Tracker_RightShoulder, "TrackerRole_RightShoulder") (Tracker_LeftElbow, "TrackerRole_LeftElbow") (Tracker_RightElbow, "TrackerRole_RightElbow") (Tracker_LeftKnee, "TrackerRole_LeftKnee") (Tracker_RightKnee, "TrackerRole_RightKnee") (Tracker_Waist, "TrackerRole_Waist") (Tracker_Chest, "TrackerRole_Chest") (Tracker_Camera, "TrackerRole_Camera") (Tracker_Keyboard, "TrackerRole_Keyboard"); // Check Eigen quaternions template <typename _Scalar> Eigen::Quaternion<_Scalar> quaternion_normal(const Eigen::Quaternion<_Scalar>& q) { return Eigen::Quaternion<_Scalar>( boost::math::isnormal(q.w()) ? q.w() : 1.f, boost::math::isnormal(q.x()) ? q.x() : 0.f, boost::math::isnormal(q.y()) ? q.y() : 0.f, boost::math::isnormal(q.z()) ? q.z() : 0.f ); } // Check Eigen Vectors template <typename _Scalar> Eigen::Vector3<_Scalar> vector3_normal(const Eigen::Vector3<_Scalar>& v) { return Eigen::Vector3<_Scalar>( boost::math::isnormal(v.x()) ? v.x() : 0.f, boost::math::isnormal(v.y()) ? v.y() : 0.f, boost::math::isnormal(v.z()) ? v.z() : 0.f ); } // Get file location in AppData inline std::string GetK2AppDataFileDir(const std::string& relativeFilePath) { CreateDirectoryA(std::string(std::string(std::getenv("APPDATA")) + "\\KinectToVR\\").c_str(), nullptr); return std::string(std::getenv("APPDATA")) + "\\KinectToVR\\" + relativeFilePath; } // Get file location in AppData inline std::string GetK2AppDataLogFileDir(const std::string& relativeFilePath) { CreateDirectoryA(std::string(std::string(std::getenv("APPDATA")) + "\\KinectToVR\\logs\\").c_str(), nullptr); return std::string(std::getenv("APPDATA")) + "\\KinectToVR\\logs\\" + relativeFilePath; } class K2Vector3 { public: float x = 0.f, y = 0.f, z = 0.f; // Default constructors K2Vector3() = default; ~K2Vector3() = default; // Copy constructors K2Vector3(const K2Vector3&) = default; K2Vector3& operator=(const K2Vector3&) = default; // Move operators K2Vector3(K2Vector3&&) = default; K2Vector3& operator=(K2Vector3&&) = default; K2Vector3(float _x, float _y, float _z) : x(_x), y(_y), z(_z) { } K2Vector3(Eigen::Vector3f v) : x(v.x()), y(v.y()), z(v.z()) { } // Conversion operator Eigen::Vector3f() const { return Eigen::Vector3f(x, y, z); } template <class Archive> void serialize(Archive& ar, const unsigned int version) { if (!boost::math::isnormal(x))x = 0.f; if (!boost::math::isnormal(y))y = 0.f; if (!boost::math::isnormal(z))z = 0.f; ar & BOOST_SERIALIZATION_NVP(x) & BOOST_SERIALIZATION_NVP(y) & BOOST_SERIALIZATION_NVP(z); } }; class K2Quaternion { public: float w = 0.f, x = 0.f, y = 0.f, z = 0.f; // Default constructors K2Quaternion() = default; ~K2Quaternion() = default; // Copy constructors K2Quaternion(const K2Quaternion&) = default; K2Quaternion& operator=(const K2Quaternion&) = default; // Move operators K2Quaternion(K2Quaternion&&) = default; K2Quaternion& operator=(K2Quaternion&&) = default; K2Quaternion(float _w, float _x, float _y, float _z) : w(_w), x(_x), y(_y), z(_z) { } K2Quaternion(Eigen::Quaternionf q) : w(q.w()), x(q.x()), y(q.y()), z(q.z()) { } // Conversion operator Eigen::Quaternionf() const { return Eigen::Quaternionf(w, x, y, z); } template <class Archive> void serialize(Archive& ar, const unsigned int version) { if (!boost::math::isnormal(w))w = 1.f; if (!boost::math::isnormal(x))x = 0.f; if (!boost::math::isnormal(y))y = 0.f; if (!boost::math::isnormal(z))z = 0.f; ar & BOOST_SERIALIZATION_NVP(w) & BOOST_SERIALIZATION_NVP(x) & BOOST_SERIALIZATION_NVP(y) & BOOST_SERIALIZATION_NVP(z); } }; class K2TrackerPose { public: // Tracker should be centered automatically Eigen::Quaternionf orientation = Eigen::Quaternionf(1.f, 0.f, 0.f, 0.f); Eigen::Vector3f position = Eigen::Vector3f(0.f, 0.f, 0.f); template <class Archive> void serialize(Archive& ar, const unsigned int version) { ar & BOOST_SERIALIZATION_NVP(orientation) & BOOST_SERIALIZATION_NVP(position); } // Default constructors K2TrackerPose() = default; ~K2TrackerPose() = default; // Copy constructors K2TrackerPose(const K2TrackerPose&) = default; K2TrackerPose& operator=(const K2TrackerPose&) = default; // Move operators K2TrackerPose(K2TrackerPose&&) = default; K2TrackerPose& operator=(K2TrackerPose&&) = default; // Quick constructor K2TrackerPose(Eigen::Quaternionf m_orientation, Eigen::Vector3f m_position) : orientation(std::move(m_orientation)), position(std::move(m_position)) { } }; // Assuming not autoadded by default // To autoadd set isActive to true // Data packet, as known in k2api class K2TrackerData { public: std::string serial; // Must be set manually int role = 0; // Handed Tracker bool isActive = false; template <class Archive> void serialize(Archive& ar, const unsigned int version) { ar & BOOST_SERIALIZATION_NVP(serial) & BOOST_SERIALIZATION_NVP(role) & BOOST_SERIALIZATION_NVP(isActive); } // Default constructors K2TrackerData() = default; ~K2TrackerData() = default; // Copy constructors K2TrackerData(const K2TrackerData&) = default; K2TrackerData& operator=(const K2TrackerData&) = default; // Move operators K2TrackerData(K2TrackerData&&) = default; K2TrackerData& operator=(K2TrackerData&&) = default; // Quick constructor K2TrackerData(std::string m_serial, ITrackerType m_role, bool m_isActive = false) : serial(std::move(m_serial)), role(m_role), isActive(m_isActive) { } }; class K2PosePacket : public K2TrackerPose { public: double millisFromNow = 0; // Time offset after sending K2PosePacket() = default; ~K2PosePacket() = default; // Copy constructors K2PosePacket(const K2PosePacket&) = default; K2PosePacket& operator=(const K2PosePacket&) = default; // Move operators K2PosePacket(K2PosePacket&& packet) noexcept : K2TrackerPose(packet) { } K2PosePacket& operator=(K2PosePacket&& packet) noexcept { K2TrackerPose::operator=(packet); return *this; } // Default constructor 2 K2PosePacket(const K2TrackerPose& m_pose, const int& millis) : K2TrackerPose(m_pose), millisFromNow(millis) { } // Default constructor K2PosePacket(const K2TrackerPose& m_pose) : K2TrackerPose(m_pose) { } template <class Archive> void serialize(Archive& ar, const unsigned int version) { ar & BOOST_SERIALIZATION_NVP(orientation) & BOOST_SERIALIZATION_NVP(position) & BOOST_SERIALIZATION_NVP(millisFromNow); // Serialize } }; class K2DataPacket : public K2TrackerData { public: double millisFromNow = 0; // Time offset after sending // Default constructors K2DataPacket() = default; ~K2DataPacket() = default; // Copy constructors K2DataPacket(const K2DataPacket&) = default; K2DataPacket& operator=(const K2DataPacket&) = default; // Move operators K2DataPacket(K2DataPacket&& packet) noexcept : K2TrackerData(packet) { } K2DataPacket& operator=(K2DataPacket&& packet) noexcept { K2TrackerData::operator=(packet); return *this; } // Default constructor 2 K2DataPacket(const K2TrackerData& m_data, const int& millis) : K2TrackerData(m_data), millisFromNow(millis) { } // Default constructor K2DataPacket(const K2TrackerData& m_data) : K2TrackerData(m_data) { } template <class Archive> void serialize(Archive& ar, const unsigned int version) { ar & BOOST_SERIALIZATION_NVP(serial) & BOOST_SERIALIZATION_NVP(role) & BOOST_SERIALIZATION_NVP(isActive) & BOOST_SERIALIZATION_NVP(millisFromNow); // Serialize } }; class K2TrackerBase { public: K2TrackerPose pose = K2TrackerPose(); K2TrackerData data = K2TrackerData(); int id = -1; // For error case template <class Archive> void serialize(Archive& ar, const unsigned int version) { ar & BOOST_SERIALIZATION_NVP(pose) & BOOST_SERIALIZATION_NVP(data) & BOOST_SERIALIZATION_NVP(id); } // Default constructors K2TrackerBase() = default; ~K2TrackerBase() = default; // Copy constructors K2TrackerBase(const K2TrackerBase&) = default; K2TrackerBase& operator=(const K2TrackerBase&) = default; // Move operators K2TrackerBase(K2TrackerBase&&) = default; K2TrackerBase& operator=(K2TrackerBase&&) = default; K2TrackerBase(const K2TrackerPose& m_pose, K2TrackerData m_data) : pose(m_pose), data(std::move(m_data)) { } }; // Tracker: for new tracker creation // ID: while updating a tracker for state // Pose / Data: while updating a tracker // :update possible via base object too class K2Message { public: // Message type, assume fail MessageType messageType = K2Message_Invalid; // Message timestamp when sent long long messageTimestamp = 0, messageManualTimestamp = 0; // This one's for mid-events // Since we're updating the main timestamp on creation, // we'd like to check other ones somehow // Object, parsing depends on type boost::optional<K2TrackerBase> tracker_base; boost::optional<K2PosePacket> tracker_pose; K2DataPacket tracker_data; // Rest object, depends on type too int id = -1; bool state = false, want_reply = true; std::string message_string; // Placeholder for anything template <class Archive> void serialize(Archive& ar, const unsigned int version) { ar & BOOST_SERIALIZATION_NVP(messageType) & BOOST_SERIALIZATION_NVP(tracker_base) & BOOST_SERIALIZATION_NVP(tracker_pose) & BOOST_SERIALIZATION_NVP(tracker_data) & BOOST_SERIALIZATION_NVP(message_string) & BOOST_SERIALIZATION_NVP(id) & BOOST_SERIALIZATION_NVP(state) & BOOST_SERIALIZATION_NVP(want_reply) & BOOST_SERIALIZATION_NVP(messageTimestamp) & BOOST_SERIALIZATION_NVP(messageManualTimestamp); } // Serialize as string std::string serializeToString() { std::ostringstream o; boost::archive::text_oarchive oa(o); oa << *this; return o.str(); } // Serialize from string, do not call as an overwrite [[nodiscard]] static K2Message parseFromString(const std::string& str) noexcept { try { std::istringstream i(str); boost::archive::text_iarchive ia(i); K2Message response; ia >> response; return response; } catch (const boost::archive::archive_exception& e) { return K2Message(); } } // Default constructors K2Message() = default; ~K2Message() = default; // Copy constructors K2Message(const K2Message&) = default; K2Message& operator=(const K2Message&) = default; // Move operators K2Message(K2Message&&) = default; K2Message& operator=(K2Message&&) = default; /* * Lower constructors are made just * to have a faster way to construct a message, * without caring about its type. * I mean, just why not? */ // Update the tracker's pose K2Message(int m_id, K2PosePacket m_pose) : id(m_id) { tracker_pose = std::move(m_pose); messageType = K2Message_UpdateTrackerPose; } // Update the tracker's data K2Message(int m_id, K2DataPacket m_data) : id(m_id) { tracker_data = std::move(m_data); messageType = K2Message_UpdateTrackerData; } // Add a tracker, to automatically spawn, // set it's state to true K2Message(K2TrackerBase m_tracker) { tracker_base = std::move(m_tracker); messageType = K2Message_AddTracker; } // Basically the upper command, // although written a bit different // It uhmmm... will let us autospawn, but at the call K2Message(K2TrackerBase m_tracker, bool m_state) : state(m_state) { tracker_base = std::move(m_tracker); messageType = K2Message_AddTracker; } // Set all trackers' state K2Message(const bool m_state) : state(m_state) { messageType = K2Message_SetStateAll; } // Set one tracker's state K2Message(const int m_id, const bool m_state) : id(m_id), state(m_state) { messageType = K2Message_SetTrackerState; } // Download a tracker K2Message(const int m_id) : id(m_id) { messageType = K2Message_DownloadTracker; } }; // Tracker: for new tracker creation // ID: while updating a tracker for state // Pose / Data: while updating a tracker // :update possible via base object too class K2ResponseMessage { public: // Message type, assume fail MessageType messageType = K2ResponseMessage_Invalid; // Message timestamp when sent long long messageTimestamp = 0, messageManualTimestamp = 0; // This one's for mid-events // Since we're updating the main timestamp on creation, // we'd like to check other ones somehow // For downloading a tracker K2TrackerBase tracker_base = K2TrackerBase(); // Rest object, depends on type too int id = -1; // Tracker's id, assume fail MessageCode result = -1; // For error case bool success = false; template <class Archive> void serialize(Archive& ar, const unsigned int version) { ar & BOOST_SERIALIZATION_NVP(messageType) & BOOST_SERIALIZATION_NVP(tracker_base) & BOOST_SERIALIZATION_NVP(id) & BOOST_SERIALIZATION_NVP(result) & BOOST_SERIALIZATION_NVP(success) & BOOST_SERIALIZATION_NVP(messageTimestamp) & BOOST_SERIALIZATION_NVP(messageManualTimestamp); } // Serialize as string std::string serializeToString() { std::ostringstream o; boost::archive::text_oarchive oa(o); oa << *this; return o.str(); } // Serialize from string, do not call as an overwriter [[nodiscard]] static K2ResponseMessage parseFromString(const std::string& str) noexcept { try { std::istringstream i(str); boost::archive::text_iarchive ia(i); K2ResponseMessage response; ia >> response; return response; } catch (const boost::archive::archive_exception& e) { } return K2ResponseMessage(); } // Default constructors K2ResponseMessage() = default; ~K2ResponseMessage() = default; // Copy constructors K2ResponseMessage(const K2ResponseMessage&) = default; K2ResponseMessage& operator=(const K2ResponseMessage&) = default; // Move operators K2ResponseMessage(K2ResponseMessage&&) = default; K2ResponseMessage& operator=(K2ResponseMessage&&) = default; /* * Lower constructors are made just because * to have a faster way to construct a message, * without caring about its type. * I mean, just why not? */ // ID as the response K2ResponseMessage(const int m_id) : id(m_id) { messageType = K2ResponseMessage_ID; } // Success return, eg for ping or somewhat // Set all trackers' state K2ResponseMessage(const bool m_state) : success(m_state) { messageType = K2ResponseMessage_Success; } // Return whole tracker object: creation / download K2ResponseMessage(K2TrackerBase m_tracker) : tracker_base(std::move(m_tracker)) { messageType = K2ResponseMessage_Tracker; } }; /** * \brief Dump std::string to hex character string * \param s String to be converted * \return Returns hex string */ KTVR_API std::string hexString(const std::string& s); /** * \brief Dump hex std::string to ascii character string * \param s String to be converted * \return Returns ascii string */ KTVR_API std::string asciiString(const std::string& s); /// <summary> /// K2API Semaphore handles for WINAPI calls /// </summary> inline HANDLE k2api_to_Semaphore, k2api_from_Semaphore, k2api_start_Semaphore; /// <summary> /// K2API's last error string, check for empty /// </summary> inline std::string k2api_last_error; /// <summary> /// Get K2API's last error string /// </summary> inline std::string GetLastError() { return k2api_last_error; } /// <summary> /// K2API Pipe handle addresses for WINAPI calls /// </summary> inline std::string k2api_to_pipe_address, k2api_from_pipe_address; /** * \brief Connects socket object to selected port, K2 uses 7135 * \return Returns 0 for success and -1 for failure */ KTVR_API int init_k2api( const std::string& k2_to_pipe = "\\\\.\\pipe\\k2api_to_pipe", const std::string& k2_from_pipe = "\\\\.\\pipe\\k2api_from_pipe", const std::string& k2_to_sem = "Global\\k2api_to_sem", const std::string& k2_from_sem = "Global\\k2api_from_sem", const std::string& k2_start_sem = "Global\\k2api_start_sem") noexcept; /** * \brief Disconnects socket object from port * \return Returns 0 for success and -1 for failure */ KTVR_API int close_k2api() noexcept; /** * \brief Send message and get a server reply, there is no need to decode return * \param data String which is to be sent * \param want_reply Check if the client wants a reply * \return Returns server's reply to the message */ KTVR_API std::string send_message(const std::string& data, bool want_reply = true) noexcept(false); /** * \brief Send message and get a server reply * \param message Message which is to be sent * \argument want_reply Check if the client wants a reply * \return Returns server's reply to the message */ template <bool want_reply = true> typename std::conditional<want_reply, K2ResponseMessage, std::monostate>::type send_message(K2Message message) noexcept(false) { // Add timestamp message.messageTimestamp = K2API_GET_TIMESTAMP_NOW; message.want_reply = want_reply; // Serialize to string std::ostringstream o; boost::archive::text_oarchive oa(o); oa << message; // Send the message // Deserialize then if constexpr (want_reply) { // Compose the response K2ResponseMessage response; auto reply = send_message(o.str(), want_reply); std::istringstream i(reply); boost::archive::text_iarchive ia(i); ia >> response; // Deserialize reply and return return std::move(response); } else { // Probably void send_message(o.str(), want_reply); return std::monostate(); } } /** * \brief Add tracker to driver's trackers list * \param tracker Tracker base that should be used for device creation * \return Returns new tracker object / id / success, overwrites object's id */ KTVR_API [[nodiscard]] K2ResponseMessage add_tracker(K2TrackerBase& tracker) noexcept; /** * \brief Connect (activate/spawn) tracker in SteamVR * \param id Tracker's id which is to connect * \param state Tracker's state to be set * \argument want_reply Check if the client wants a reply * \return Returns tracker id / success? */ template <bool want_reply = true> typename std::conditional<want_reply, K2ResponseMessage, std::monostate>::type set_tracker_state(int id, bool state) noexcept { try { // Send and grab the response // Thanks to our constructors, // message will set all // Send the message and return return send_message<want_reply>( K2Message(id, state)); } catch (const std::exception& e) { if constexpr (want_reply) return K2ResponseMessage(); // Success is set to false by default else return std::monostate(); } } /** * \brief Connect (activate/spawn) all trackers in SteamVR * \param state Tracker's state to be set * \argument want_reply Check if the client wants a reply * \return Returns success? */ template <bool want_reply = true> typename std::conditional<want_reply, K2ResponseMessage, std::monostate>::type set_state_all(bool state) noexcept { try { // Send and grab the response // Thanks to our constructors, // message will set all // Send the message return send_message<want_reply>( K2Message(state)); } catch (const std::exception& e) { if constexpr (want_reply) return K2ResponseMessage(); // Success is set to false by default else return std::monostate(); } } /** * \brief Update tracker's pose in SteamVR driver * \param id Tracker's id which is to update * \param tracker_pose New pose for tracker * \argument want_reply Check if the client wants a reply * \return Returns tracker id / success? */ template <bool want_reply = true> typename std::conditional<want_reply, K2ResponseMessage, std::monostate>::type update_tracker_pose(int id, const K2PosePacket& tracker_pose) noexcept { try { // Send and grab the response // Thanks to our constructors, // message will set all // Send the message and return return send_message<want_reply>( K2Message(id, tracker_pose)); } catch (const std::exception& e) { if constexpr (want_reply) return K2ResponseMessage(); // Success is set to false by default else return std::monostate(); } } /** * \brief Update tracker's pose in SteamVR driver * \param tracker_handle Tracker for updating data * \argument want_reply Check if the client wants a reply * \return Returns tracker id / success? */ template <bool want_reply = true> typename std::conditional<want_reply, K2ResponseMessage, std::monostate>::type update_tracker_pose(const K2TrackerBase& tracker_handle) noexcept { try { // Send the message and return return update_tracker_pose<want_reply>(tracker_handle.id, tracker_handle.pose); } catch (const std::exception& e) { if constexpr (want_reply) return K2ResponseMessage(); // Success is set to false by default else return std::monostate(); } } /** * \brief Update tracker's data in SteamVR driver (ONLY for yet not spawned trackers) * \param id Tracker's id which is to update * \param tracker_data New pose for tracker * \argument want_reply Check if the client wants a reply * \return Returns tracker id / success? */ template <bool want_reply = true> typename std::conditional<want_reply, K2ResponseMessage, std::monostate>::type update_tracker_data(int id, const K2DataPacket& tracker_data) noexcept { try { // Send and grab the response // Thanks to our constructors, // message will set all // Send the message and return return send_message<want_reply>( K2Message(id, tracker_data)); } catch (const std::exception& e) { if constexpr (want_reply) return K2ResponseMessage(); // Success is set to false by default else return std::monostate(); } } /** * \brief Update tracker's data in SteamVR driver * \param tracker_handle Tracker for updating data * \argument want_reply Check if the client wants a reply * \return Returns tracker id / success? */ template <bool want_reply = true> typename std::conditional<want_reply, K2ResponseMessage, std::monostate>::type update_tracker_data(const K2TrackerBase& tracker_handle) noexcept { try { // Send the message and return return update_tracker_data<want_reply>(tracker_handle.id, tracker_handle.data); } catch (const std::exception& e) { if constexpr (want_reply) return K2ResponseMessage(); // Success is set to false by default else return std::monostate(); } } /** * \brief Update tracker in SteamVR driver * \param tracker Tracker base to be updated from * \argument want_reply Check if the client wants a reply * \return Returns tracker id / success? */ template <bool want_reply = true> typename std::conditional<want_reply, K2ResponseMessage, std::monostate>::type update_tracker(const K2TrackerBase& tracker) noexcept { try { // Send the message and return update_tracker_pose<want_reply>(tracker.id, tracker.pose); // Data is more important then return data return update_tracker_data<want_reply>(tracker.id, tracker.data); } catch (const std::exception& e) { if constexpr (want_reply) return K2ResponseMessage(); // Success is set to false by default else return std::monostate(); } } /** * \brief Update tracker's pose in SteamVR driver with already existing values * \param tracker_id Tracker for updating data * \argument want_reply Check if the client wants a reply * \return Returns tracker id / success? */ template <bool want_reply = true> typename std::conditional<want_reply, K2ResponseMessage, std::monostate>::type refresh_tracker_pose(const int& tracker_id) noexcept { try { // Send and grab the response auto message = K2Message(); message.id = tracker_id; message.messageType = K2Message_RefreshTracker; // Send the message and return return send_message<want_reply>(message); } catch (const std::exception& e) { if constexpr (want_reply) return K2ResponseMessage(); // Success is set to false by default else return std::monostate(); } } /** * \brief Request OpenVR to restart with a message * \param reason Reason for the restart * \argument want_reply Check if the client wants a reply * \return Returns tracker id / success? */ template <bool want_reply = true> typename std::conditional<want_reply, K2ResponseMessage, std::monostate>::type request_vr_restart(const std::string& reason) noexcept { try { // Send and grab the response auto message = K2Message(); message.message_string = std::move(reason); message.messageType = K2Message_RequestRestart; // Send the message and return return send_message<want_reply>(message); } catch (const std::exception& e) { if constexpr (want_reply) return K2ResponseMessage(); // Success is set to false by default else return std::monostate(); } } /** * \brief Grab all possible data from existing tracker * \param tracker_id Tracker id for download * \return Returns tracker object / id / success? */ KTVR_API K2ResponseMessage download_tracker(const int& tracker_id) noexcept; /** * \brief Grab all possible data from existing tracker * \param tracker_serial Tracker id for download * \return Returns tracker object / id / success? */ KTVR_API K2ResponseMessage download_tracker(const std::string& tracker_serial) noexcept; /** * \brief Grab all possible data from existing tracker * \param tracker Tracker base id is to be grabbed from * \return Returns tracker object / id / success? */ KTVR_API K2ResponseMessage download_tracker(const K2TrackerBase& tracker) noexcept; /** * \brief Test connection with the server * \return Returns send_time / total_time / success? */ KTVR_API std::tuple<K2ResponseMessage, long long, long long> test_connection() noexcept; }
32,070
C++
.h
1,030
27.95534
108
0.720181
KinectToVR/k2vr-application
38
4
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,682
TrackingDeviceBase.h
KinectToVR_k2vr-application/external/Kinect/TrackingDeviceBase.h
#pragma once #include "ITrackingDevice.h" #include <glm/vec4.hpp> #include <glm/detail/type_quat.hpp> #include <glm/gtc/quaternion.hpp> #include <iostream> #include <KinectToVR_API.h> class TrackingDeviceBase : public ITrackingDevice { public: TrackingDeviceBase() { } ~TrackingDeviceBase() { } // These 3 functions are critical // One should be called before launching k2vr // Update and shutdown is called by the k2vr itself virtual void initialize() {}; virtual void shutdown() {}; virtual void update() {}; virtual HRESULT getStatusResult() { return E_NOTIMPL; } virtual std::string statusResultString(HRESULT stat) { return "statusResultString behaviour not defined"; }; /* * Handler for Tracking Joints, num 25 * You must update these during device's update function call */ glm::vec4 jointPositions[25] = { glm::vec4() }; glm::quat jointOrientations[25] = { glm::quat() }; ktvr::JointTrackingState trackingStates[25] = { 0 }; // Device type, specified in K2API ktvr::TrackingDeviceType deviceType = ktvr::K2_Unknown; // Helper bool for knowing if skeleton't tracked bool isSkeletonTracked = false; };
1,143
C++
.h
33
32.575758
109
0.75386
KinectToVR/k2vr-application
38
4
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false