SingleApplication/singleapplication.cpp

50 lines
1.4 KiB
C++
Raw Normal View History

2012-12-23 06:12:38 +08:00
#include "singleapplication.h"
#include <cstdlib>
2012-12-23 06:12:38 +08:00
/**
2015-02-27 03:19:38 +08:00
* @brief Constructor. Checks and fires up LocalServer or closes the program
* if another instance already exists
2012-12-23 06:12:38 +08:00
* @param argc
* @param argv
*/
SingleApplication::SingleApplication(int &argc, char *argv[])
: QApplication(argc, argv)
2012-12-23 06:12:38 +08:00
{
2015-02-27 03:19:38 +08:00
QString serverName = QApplication::organizationName() + QApplication::applicationName();
serverName.replace(QRegExp("[^\\w\\-. ]"), "");
2012-12-23 06:12:38 +08:00
// Attempt to connect to the LocalServer
socket = new QLocalSocket();
socket->connectToServer(serverName);
if(socket->waitForConnected(1000)){
socket->close();
2015-02-27 03:19:38 +08:00
::exit(EXIT_SUCCESS); // Terminate the program using STDLib's exit function
} else {
// If the connection is insuccessful, this is the main process
// So we create a Local Server
server = new QLocalServer();
server->removeServer(serverName);
server->listen(serverName);
2015-02-27 03:19:38 +08:00
QObject::connect(server, SIGNAL(newConnection()), this, SLOT(slotConnectionEstablished()));
}
2012-12-23 06:12:38 +08:00
}
/**
* @brief Destructor
2012-12-23 06:12:38 +08:00
*/
SingleApplication::~SingleApplication()
2012-12-23 06:12:38 +08:00
{
server->close();
2012-12-23 06:12:38 +08:00
}
/**
* @brief Executed when the showUp command is sent to LocalServer
2012-12-23 06:12:38 +08:00
*/
void SingleApplication::slotConnectionEstablished()
2012-12-23 06:12:38 +08:00
{
QLocalSocket *socket = server->nextPendingConnection();
socket->close();
delete socket;
emit showUp();
2012-12-23 06:12:38 +08:00
}