QtPass  1.2.0-pre
Multi-platform GUI for pass, the standard unix password manager.
singleapplication.cpp
Go to the documentation of this file.
1 #include "singleapplication.h"
2 #include "debughelper.h"
3 #include <QLocalSocket>
4 
12 SingleApplication::SingleApplication(int &argc, char *argv[],
13  const QString uniqueKey)
14  : QApplication(argc, argv), _uniqueKey(uniqueKey) {
15  sharedMemory.setKey(_uniqueKey);
16  if (sharedMemory.attach()) {
17  _isRunning = true;
18  } else {
19  _isRunning = false;
20  // create shared memory.
21  if (!sharedMemory.create(1)) {
22  dbg() << "Unable to create single instance.";
23  return;
24  }
25  // create local server and listen to incomming messages from other
26  // instances.
27  localServer.reset(new QLocalServer(this));
28  connect(localServer.data(), SIGNAL(newConnection()), this,
29  SLOT(receiveMessage()));
30  localServer->listen(_uniqueKey);
31  }
32 }
33 
34 // public slots.
35 
41  QLocalSocket *localSocket = localServer->nextPendingConnection();
42  if (!localSocket->waitForReadyRead(timeout)) {
43  dbg() << localSocket->errorString().toLatin1();
44  return;
45  }
46  QByteArray byteArray = localSocket->readAll();
47  QString message = QString::fromUtf8(byteArray.constData());
48  emit messageAvailable(message);
49  localSocket->disconnectFromServer();
50 }
51 
52 // public functions.
58 bool SingleApplication::isRunning() { return _isRunning; }
59 
66 bool SingleApplication::sendMessage(const QString &message) {
67  if (!_isRunning)
68  return false;
69  QLocalSocket localSocket(this);
70  localSocket.connectToServer(_uniqueKey, QIODevice::WriteOnly);
71  if (!localSocket.waitForConnected(timeout)) {
72  dbg() << localSocket.errorString().toLatin1();
73  return false;
74  }
75  localSocket.write(message.toUtf8());
76  if (!localSocket.waitForBytesWritten(timeout)) {
77  dbg() << localSocket.errorString().toLatin1();
78  return false;
79  }
80  localSocket.disconnectFromServer();
81  return true;
82 }
#define dbg()
Definition: debughelper.h:7
bool isRunning()
SingleApplication::isRunning is there already a QtPass instance running, to check wether to be server...
bool sendMessage(const QString &message)
SingleApplication::sendMessage send a message (from commandline) to an already running QtPass instanc...
void messageAvailable(QString message)
messageAvailable notification from commandline
SingleApplication(int &argc, char *argv[], const QString uniqueKey)
SingleApplication::SingleApplication this replaces the QApplication allowing for local socket based c...
void receiveMessage()
SingleApplication::receiveMessage we have received (a command line) message.