pineapple-music/singleapplicationmanager.cpp

67 lines
1.7 KiB
C++
Raw Normal View History

2024-09-08 00:34:45 +08:00
// SPDX-FileCopyrightText: 2024 Gary Wang <git@blumia.net>
//
// SPDX-License-Identifier: MIT
2020-04-11 19:54:51 +08:00
#include "singleapplicationmanager.h"
2022-10-05 14:02:46 +08:00
#include <QVariant>
2020-04-11 19:54:51 +08:00
#include <QDataStream>
#include <QLocalServer>
#include <QLocalSocket>
SingleApplicationManager::SingleApplicationManager(QString applicationKey, QObject *parent)
: QObject(parent)
, m_applicationKey(applicationKey)
{
}
void SingleApplicationManager::on_localSocket_newConnection()
{
QScopedPointer<QLocalSocket> socket(m_localServer->nextPendingConnection());
if (socket) {
socket->waitForReadyRead(500);
2020-04-11 19:54:51 +08:00
QDataStream dataStream(socket.data());
QVariant data;
dataStream.startTransaction();
dataStream >> data;
dataStream.commitTransaction();
emit dataReached(data);
}
}
void SingleApplicationManager::createSingleInstance()
{
m_localServer = new QLocalServer(this);
connect(m_localServer, &QLocalServer::newConnection, this, &SingleApplicationManager::on_localSocket_newConnection);
if (!m_localServer->listen(m_applicationKey)) {
if (m_localServer->serverError() == QAbstractSocket::AddressInUseError) {
QLocalServer::removeServer(m_applicationKey);
m_localServer->listen(m_applicationKey);
}
}
}
bool SingleApplicationManager::checkSingleInstance(QVariant data)
{
QLocalSocket socket;
socket.connectToServer(m_applicationKey);
if (socket.waitForConnected(500)) {
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out << data;
2020-04-11 19:54:51 +08:00
socket.write(block);
2020-04-11 19:54:51 +08:00
socket.waitForBytesWritten();
socket.flush();
socket.disconnectFromServer();
2020-04-11 19:54:51 +08:00
return true;
}
return false;
}