Raise existing instance

Closes #193
This commit is contained in:
VukoDrakkeinen 2016-07-25 06:41:13 +02:00 committed by Anton Gulenko
parent 9f819061cd
commit d1310b3337
5 changed files with 87 additions and 1 deletions

View file

@ -22,6 +22,9 @@
#include <QAbstractNativeEventFilter>
#include <QFileOpenEvent>
#include <QSocketNotifier>
#include <QLockFile>
#include <QStandardPaths>
#include <QtNetwork/QLocalSocket>
#include "autotype/AutoType.h"
@ -76,6 +79,8 @@ Application::Application(int& argc, char** argv)
#ifdef Q_OS_UNIX
, m_unixSignalNotifier(nullptr)
#endif
, alreadyRunning(false)
, lock(nullptr)
{
#if defined(Q_OS_UNIX) && !defined(Q_OS_OSX)
installNativeEventFilter(new XcbEventFilter());
@ -85,6 +90,58 @@ Application::Application(int& argc, char** argv)
#if defined(Q_OS_UNIX)
registerUnixSignals();
#endif
QString userName = qgetenv("USER");
if (userName.isEmpty()) {
userName = qgetenv("USERNAME");
}
QString identifier = "keepassx2";
if (!userName.isEmpty()) {
identifier.append("-");
identifier.append(userName);
}
QString socketName = identifier + ".socket";
QString lockName = identifier + ".lock";
// According to documentation we should use RuntimeLocation on *nixes, but even Qt doesn't respect
// this and creates sockets in TempLocation, so let's be consistent.
lock = new QLockFile(QStandardPaths::writableLocation(QStandardPaths::TempLocation) + "/" + lockName);
lock->setStaleLockTime(0);
lock->tryLock();
switch (lock->error()) {
case QLockFile::NoError:
server.setSocketOptions(QLocalServer::UserAccessOption);
server.listen(socketName);
connect(&server, SIGNAL(newConnection()), this, SIGNAL(anotherInstanceStarted()));
break;
case QLockFile::LockFailedError: {
alreadyRunning = true;
// notify the other instance
// try several times, in case the other instance is still starting up
QLocalSocket client;
for (int i = 0; i < 3; i++) {
client.connectToServer(socketName);
if (client.waitForConnected(150)) {
client.abort();
break;
}
}
break;
}
default:
qWarning() << QCoreApplication::translate("Main",
"The lock file could not be created. Single-instance mode disabled.")
.toUtf8().constData();
}
}
Application::~Application()
{
server.close();
if (lock) {
lock->unlock();
delete lock;
}
}
QWidget* Application::mainWindow() const
@ -171,3 +228,9 @@ void Application::quitBySignal()
static_cast<MainWindow*>(m_mainWindow)->appExit();
}
#endif
bool Application::isAlreadyRunning() const
{
return alreadyRunning;
}