aboutsummaryrefslogtreecommitdiff
path: root/singleapplication.cpp
blob: 18044da14ef5db1b62bd48f7d6252da1e472e842 (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
48
#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)){
        ::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()
{
    QLocalSocket *socket = server->nextPendingConnection();
    socket->close();
    delete socket;
    emit showUp();
}