aboutsummaryrefslogtreecommitdiff
path: root/singleapplication.cpp
blob: 7ae333de048f9981832379f3556795ddaf29f70d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include "singleapplication.h"
#include <cstdlib>

/**
 * @brief Constructor. Checks and fires up LocalServer or closes the program
 * if another instance already exists
 * @param argc
 * @param argv
 */
SingleApplication::SingleApplication(int argc, char *argv[])
    : QApplication(argc, argv)
{
    QString serverName = QApplication::organizationName() + QApplication::applicationName();
    serverName.replace(QRegExp("[^\\w\\-. ]"), "");

    // Attempt to connect to the LocalServer
    socket = new QLocalSocket();
    socket->connectToServer(serverName);
    if(socket->waitForConnected(1000)){
        socket->close();
        ::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);
        QObject::connect(server, SIGNAL(newConnection()), this, SLOT(slotConnectionEstablished()));
    }
}

/**
 * @brief Destructor
 */
SingleApplication::~SingleApplication()
{
    server->close();
}

/**
 * @brief Executed when the showUp command is sent to LocalServer
 */
void SingleApplication::slotConnectionEstablished()
{
    server->nextPendingConnection();
    emit showUp();
}