#pragma once
#include <QObject>
#include <QApplication>
#include <QtNetwork/QLocalServer>
#include <QWidget>
class SingleApp : public QApplication
{
Q_OBJECT
public:
explicit SingleApp(int &argc, char **argv);
bool isRunning();
QWidget *w;
private slots:
void newLocalConnection();
private:
void initLocalConnection();
void newLocalServer();
void activateWindow();
bool m_isRunning;
QLocalServer *m_localServer;
QString m_serverName;
};
#include "SingleApp.h"
#include <QtNetwork/QLocalSocket>
#include <QFileInfo>
#define TIME_OUT (500) // 500ms
SingleApp::SingleApp(int &argc, char **argv)
: QApplication(argc, argv)
, w(nullptr)
, m_isRunning(false)
, m_localServer(nullptr)
{
m_serverName = QFileInfo(QCoreApplication::applicationFilePath()).fileName();
m_serverName += "appName";
initLocalConnection();
}
bool SingleApp::isRunning()
{
return m_isRunning;
}
void SingleApp::newLocalConnection()
{
QLocalSocket *socket = m_localServer->nextPendingConnection();
if (socket) {
socket->waitForReadyRead(2 * TIME_OUT);
delete socket;
activateWindow();
}
}
void SingleApp::initLocalConnection()
{
m_isRunning = false;
QLocalSocket socket;
socket.connectToServer(m_serverName);
if (socket.waitForConnected(TIME_OUT)) {
fprintf(stderr, "%s already running.\n",
m_serverName.toLocal8Bit().constData());
m_isRunning = true;
return;
}
newLocalServer();
}
void SingleApp::newLocalServer()
{
m_localServer = new QLocalServer(this);
connect(m_localServer, SIGNAL(newConnection()), this, SLOT(newLocalConnection()));
if (!m_localServer->listen(m_serverName)) {
if (m_localServer->serverError() == QAbstractSocket::AddressInUseError) {
QLocalServer::removeServer(m_serverName);
m_localServer->listen(m_serverName);
}
}
}
void SingleApp::activateWindow()
{
if (w) {
w->show();
w->raise();
w->activateWindow();
}
}