aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorLibravatar Keshav <keshavnrj@gmail.com>2022-05-10 10:09:53 +0530
committerLibravatar Keshav <keshavnrj@gmail.com>2022-05-10 10:17:26 +0530
commit81faa022735b155ac0773e1cc849474a0719c523 (patch)
tree81dd2ce375ab7696511b44555861fae8392bab60 /src
parent8c0df6d34bba406e4d8e2711e4f5134a24107b2e (diff)
downloadwhatsie-81faa022735b155ac0773e1cc849474a0719c523.tar.gz
whatsie-81faa022735b155ac0773e1cc849474a0719c523.zip
feat: implement IPC & other improvements
- lets run only one instance of application - lets pass arguments from secondary instances to main instance - open new chat without reloading page - restore application with commandline argument to secondary instance: example: whatsie whatsapp://whatsie will restore the primary instance of whatsie process
Diffstat (limited to 'src')
-rw-r--r--src/WhatsApp.pro5
-rw-r--r--src/main.cpp47
-rw-r--r--src/mainwindow.cpp98
-rw-r--r--src/mainwindow.h2
-rw-r--r--src/singleapplication/LICENSE24
-rw-r--r--src/singleapplication/SingleApplication1
-rw-r--r--src/singleapplication/singleapplication.cpp272
-rw-r--r--src/singleapplication/singleapplication.h164
-rw-r--r--src/singleapplication/singleapplication.pri10
-rw-r--r--src/singleapplication/singleapplication_p.cpp550
-rw-r--r--src/singleapplication/singleapplication_p.h109
11 files changed, 1235 insertions, 47 deletions
diff --git a/src/WhatsApp.pro b/src/WhatsApp.pro
index a6aca88..2fce6ea 100644
--- a/src/WhatsApp.pro
+++ b/src/WhatsApp.pro
@@ -26,6 +26,9 @@ win32{
LIBS += User32.Lib
}
+include(singleapplication/singleapplication.pri)
+DEFINES += QAPPLICATION_CLASS=QApplication
+
# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Refer to the documentation for the
@@ -63,7 +66,6 @@ SOURCES += \
mainwindow.cpp \
permissiondialog.cpp \
rateapp.cpp \
- rungaurd.cpp \
settingswidget.cpp \
utils.cpp \
webenginepage.cpp \
@@ -89,7 +91,6 @@ HEADERS += \
permissiondialog.h \
rateapp.h \
requestinterceptor.h \
- rungaurd.h \
settingswidget.h \
utils.h \
webenginepage.h \
diff --git a/src/main.cpp b/src/main.cpp
index b162833..0303f3a 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -6,10 +6,9 @@
#include <QtWebEngine>
#include <QtWidgets>
-#include "mainwindow.h"
-
#include "common.h"
-#include "rungaurd.h"
+#include "mainwindow.h"
+#include <singleapplication.h>
int main(int argc, char *argv[]) {
@@ -19,7 +18,7 @@ int main(int argc, char *argv[]) {
if (args.contains("-v") || args.contains("--version")) {
qInfo() << QString("version: %1, branch: %2, commit: %3, built_at: %4")
- .arg(VERSIONSTR, GIT_BRANCH, GIT_HASH, BUILD_TIMESTAMP);
+ .arg(VERSIONSTR, GIT_BRANCH, GIT_HASH, BUILD_TIMESTAMP);
return 0;
}
@@ -38,18 +37,20 @@ int main(int argc, char *argv[]) {
qputenv("QTWEBENGINE_CHROMIUM_FLAGS", "--disable-logging --single-process");
#endif
- QApplication app(argc, argv);
+ SingleApplication app(argc, argv, true);
app.setQuitOnLastWindowClosed(false);
app.setWindowIcon(QIcon(":/icons/app/icon-128.png"));
QApplication::setApplicationName("WhatSie");
QApplication::setOrganizationName("org.keshavnrj.ubuntu");
QApplication::setApplicationVersion(VERSIONSTR);
- QString appname = QApplication::applicationName();
- RunGuard guard("org.keshavnrj.ubuntu." + appname);
- if (!guard.tryToRun()) {
- QMessageBox::critical(0, appname,
- "An instance of " + appname + " is already running.");
+ // if secondary instance is invoked
+ if (app.isSecondary()) {
+ app.sendMessage(app.arguments().join(' ').toUtf8());
+ qInfo() << QApplication::applicationName() +
+ " is already running with PID:" +
+ QString::number(app.primaryPid()) + "; by USER: "
+ << app.primaryUser();
return 0;
}
@@ -64,18 +65,38 @@ int main(int argc, char *argv[]) {
MainWindow window;
+ // else
+ QObject::connect(
+ &app, &SingleApplication::receivedMessage,
+ [&window](int instanceId, QByteArray message) {
+ qInfo() << "Another instance with PID: " + QString::number(instanceId) +
+ ", sent argument: " + message;
+ QString messageStr = QTextCodec::codecForMib(106)->toUnicode(message);
+ if (messageStr.contains("whatsapp://whatsie", Qt::CaseInsensitive)) {
+ window.show();
+ return;
+ } else if (messageStr.contains("whatsapp://", Qt::CaseInsensitive)) {
+ QString urlStr =
+ "whatsapp://" + messageStr.split("whatsapp://").last();
+ window.loadAppWithArgument(urlStr);
+ } else {
+ window.alreadyRunning();
+ }
+ });
+
QStringList argsList = app.arguments();
foreach (QString argStr, argsList) {
if (argStr.contains("whatsapp://")) {
window.loadAppWithArgument(argStr);
}
}
+
QSettings settings;
if (QSystemTrayIcon::isSystemTrayAvailable() &&
settings.value("startMinimized", false).toBool()) {
- window.runMinimized();
- }else{
- window.show();
+ window.runMinimized();
+ } else {
+ window.show();
}
return app.exec();
diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp
index b828593..f32d24b 100644
--- a/src/mainwindow.cpp
+++ b/src/mainwindow.cpp
@@ -128,8 +128,8 @@ void MainWindow::initRateWidget() {
}
void MainWindow::runMinimized() {
- this->minimizeAction->trigger();
- notify("Whatsie", "Whatsie started minimized in tray");
+ this->minimizeAction->trigger();
+ notify("Whatsie", "Whatsie started minimized in tray. Click to Open.");
}
MainWindow::~MainWindow() { webEngine->deleteLater(); }
@@ -137,12 +137,6 @@ MainWindow::~MainWindow() { webEngine->deleteLater(); }
void MainWindow::loadAppWithArgument(const QString &arg) {
// https://faq.whatsapp.com/iphone/how-to-link-to-whatsapp-from-a-different-app/?lang=en
- // The WhatsApp Messenger application
- if (arg.contains("://app")) {
- this->show(); // restore app
- return;
- }
-
// PASSED SCHEME whatsapp://send?text=Hello%2C%20World!&phone=919568388397"
// CONVERTED URI
// https://web.whatsapp.com/send?phone=919568388397&text=Hello%2C%20World New
@@ -151,15 +145,28 @@ void MainWindow::loadAppWithArgument(const QString &arg) {
QString newArg = arg;
newArg = newArg.replace("?", "&");
QUrlQuery query(newArg);
- QString phone, phoneStr, text, textStr, urlStr;
- // create send url equivalent
+
+ static QString phone, phoneStr, text, textStr, urlStr;
phone = query.queryItemValue("phone");
text = query.queryItemValue("text");
- phoneStr = phone.isEmpty() ? "" : "phone=" + phone;
- textStr = text.isEmpty() ? "" : "text=" + text;
- urlStr = "https://web.whatsapp.com/send?" + phoneStr + "&" + textStr;
- this->webEngine->page()->load(QUrl(urlStr));
- return;
+
+ webEngine->page()->runJavaScript(
+ "openNewChatWhatsieDefined()", [this](const QVariant &result) {
+ if (result.toString().contains("true")) {
+ this->webEngine->page()->runJavaScript(
+ QString("openNewChatWhatsie(\"%1\",\"%2\")").arg(phone, text));
+ this->notify(QApplication::applicationName(),
+ "New chat with " + phoneStr +
+ " is ready. Click to Open.");
+ } else {
+ // create send url equivalent
+ phoneStr = phone.isEmpty() ? "" : "phone=" + phone;
+ textStr = text.isEmpty() ? "" : "text=" + text;
+ urlStr =
+ "https://web.whatsapp.com/send?" + phoneStr + "&" + textStr;
+ this->webEngine->page()->load(QUrl(urlStr));
+ }
+ });
}
}
@@ -198,7 +205,9 @@ void MainWindow::updateWindowTheme() {
}
QList<QWidget *> widgets = this->findChildren<QWidget *>();
- foreach (QWidget *w, widgets) { w->setPalette(qApp->palette()); }
+ foreach (QWidget *w, widgets) {
+ w->setPalette(qApp->palette());
+ }
setNotificationPresenter(webEngine->page()->profile());
if (lockWidget != nullptr) {
@@ -485,19 +494,19 @@ void MainWindow::notify(QString title, QString message) {
if (windowState().testFlag(Qt::WindowMinimized) ||
!windowState().testFlag(Qt::WindowActive)) {
activateWindow();
- //raise();
+ // raise();
this->show();
}
});
} else {
auto popup = new NotificationPopup(webEngine);
connect(popup, &NotificationPopup::notification_clicked, popup, [=]() {
- if (windowState().testFlag(Qt::WindowMinimized) ||
- !windowState().testFlag(Qt::WindowActive) ||
- this->isHidden()) {
- this->show();
- setWindowState((windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
- }
+ if (windowState().testFlag(Qt::WindowMinimized) ||
+ !windowState().testFlag(Qt::WindowActive) || this->isHidden()) {
+ this->show();
+ setWindowState((windowState() & ~Qt::WindowMinimized) |
+ Qt::WindowActive);
+ }
});
popup->style()->polish(qApp);
popup->setMinimumWidth(300);
@@ -794,8 +803,7 @@ void MainWindow::createWebPage(bool offTheRecord) {
connect(profile, &QWebEngineProfile::downloadRequested,
&m_downloadManagerWidget, &DownloadManagerWidget::downloadRequested);
- connect(page,
- SIGNAL(fullScreenRequested(QWebEngineFullScreenRequest)), this,
+ connect(page, SIGNAL(fullScreenRequested(QWebEngineFullScreenRequest)), this,
SLOT(fullScreenRequested(QWebEngineFullScreenRequest)));
double currentFactor = settings.value("zoomFactor", 1.0).toDouble();
@@ -814,8 +822,8 @@ void MainWindow::setNotificationPresenter(QWebEngineProfile *profile) {
connect(popup, &NotificationPopup::notification_clicked, popup, [=]() {
if (windowState().testFlag(Qt::WindowMinimized) ||
!windowState().testFlag(Qt::WindowActive) || this->isHidden()) {
- this->show();
- setWindowState((windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
+ this->show();
+ setWindowState((windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
}
});
@@ -833,11 +841,12 @@ void MainWindow::setNotificationPresenter(QWebEngineProfile *profile) {
settings.value("notificationTimeOut", 9000).toInt());
trayIcon->disconnect(trayIcon, SIGNAL(messageClicked()));
connect(trayIcon, &QSystemTrayIcon::messageClicked, trayIcon, [=]() {
- if (windowState().testFlag(Qt::WindowMinimized) ||
- !windowState().testFlag(Qt::WindowActive) || this->isHidden()) {
- this->show();
- setWindowState((windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
- }
+ if (windowState().testFlag(Qt::WindowMinimized) ||
+ !windowState().testFlag(Qt::WindowActive) || this->isHidden()) {
+ this->show();
+ setWindowState((windowState() & ~Qt::WindowMinimized) |
+ Qt::WindowActive);
+ }
});
} else {
@@ -890,10 +899,27 @@ void MainWindow::handleLoadFinished(bool loaded) {
checkLoadedCorrectly();
updatePageTheme();
handleZoom();
+ injectNewChatJavaScript();
settingsWidget->refresh();
}
}
+void MainWindow::injectNewChatJavaScript() {
+ QString js = "const openNewChatWhatsie = (phone,text) => { "
+ "const link = document.createElement('a');"
+ "link.setAttribute('href', "
+ "`whatsapp://send/?phone=${phone}&text=${text}`);"
+ "document.body.append(link);"
+ "link.click();"
+ "document.body.removeChild(link);"
+ "};"
+ "function openNewChatWhatsieDefined()"
+ "{"
+ " return (openNewChatWhatsie != 'undefined');"
+ "}";
+ webEngine->page()->runJavaScript(js);
+}
+
void MainWindow::checkLoadedCorrectly() {
if (webEngine && webEngine->page()) {
// test 1 based on the class name of body of the page
@@ -1055,3 +1081,11 @@ void MainWindow::tryLock() {
init_lock();
}
}
+
+void MainWindow::alreadyRunning() {
+ QString appname = QApplication::applicationName();
+ this->notify(
+ appname,
+ QString("An instance of %1 is already Running, click to restore.")
+ .arg(appname));
+}
diff --git a/src/mainwindow.h b/src/mainwindow.h
index c3c82a2..8573226 100644
--- a/src/mainwindow.h
+++ b/src/mainwindow.h
@@ -50,6 +50,7 @@ public slots:
void handleDownloadRequested(QWebEngineDownloadItem *download);
void loadAppWithArgument(const QString &arg);
void runMinimized();
+ void alreadyRunning();
protected slots:
void closeEvent(QCloseEvent *event) override;
void resizeEvent(QResizeEvent *event) override;
@@ -125,6 +126,7 @@ private slots:
bool isLoggedIn();
void initAutoLock();
void appAutoLockChanged();
+ void injectNewChatJavaScript();
};
#endif // MAINWINDOW_H
diff --git a/src/singleapplication/LICENSE b/src/singleapplication/LICENSE
new file mode 100644
index 0000000..a82e5a6
--- /dev/null
+++ b/src/singleapplication/LICENSE
@@ -0,0 +1,24 @@
+The MIT License (MIT)
+
+Copyright (c) Itay Grudev 2015 - 2020
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+Note: Some of the examples include code not distributed under the terms of the
+MIT License.
diff --git a/src/singleapplication/SingleApplication b/src/singleapplication/SingleApplication
new file mode 100644
index 0000000..8ead1a4
--- /dev/null
+++ b/src/singleapplication/SingleApplication
@@ -0,0 +1 @@
+#include "singleapplication.h"
diff --git a/src/singleapplication/singleapplication.cpp b/src/singleapplication/singleapplication.cpp
new file mode 100644
index 0000000..1234ff9
--- /dev/null
+++ b/src/singleapplication/singleapplication.cpp
@@ -0,0 +1,272 @@
+// The MIT License (MIT)
+//
+// Copyright (c) Itay Grudev 2015 - 2020
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#include <QtCore/QElapsedTimer>
+#include <QtCore/QByteArray>
+#include <QtCore/QSharedMemory>
+
+#include "singleapplication.h"
+#include "singleapplication_p.h"
+
+/**
+ * @brief Constructor. Checks and fires up LocalServer or closes the program
+ * if another instance already exists
+ * @param argc
+ * @param argv
+ * @param allowSecondary Whether to enable secondary instance support
+ * @param options Optional flags to toggle specific behaviour
+ * @param timeout Maximum time blocking functions are allowed during app load
+ */
+SingleApplication::SingleApplication( int &argc, char *argv[], bool allowSecondary, Options options, int timeout, const QString &userData )
+ : app_t( argc, argv ), d_ptr( new SingleApplicationPrivate( this ) )
+{
+ Q_D( SingleApplication );
+
+#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
+ // On Android and iOS since the library is not supported fallback to
+ // standard QApplication behaviour by simply returning at this point.
+ qWarning() << "SingleApplication is not supported on Android and iOS systems.";
+ return;
+#endif
+
+ // Store the current mode of the program
+ d->options = options;
+
+ // Add any unique user data
+ if ( ! userData.isEmpty() )
+ d->addAppData( userData );
+
+ // Generating an application ID used for identifying the shared memory
+ // block and QLocalServer
+ d->genBlockServerName();
+
+ // To mitigate QSharedMemory issues with large amount of processes
+ // attempting to attach at the same time
+ SingleApplicationPrivate::randomSleep();
+
+#ifdef Q_OS_UNIX
+ // By explicitly attaching it and then deleting it we make sure that the
+ // memory is deleted even after the process has crashed on Unix.
+ d->memory = new QSharedMemory( d->blockServerName );
+ d->memory->attach();
+ delete d->memory;
+#endif
+ // Guarantee thread safe behaviour with a shared memory block.
+ d->memory = new QSharedMemory( d->blockServerName );
+
+ // Create a shared memory block
+ if( d->memory->create( sizeof( InstancesInfo ) )){
+ // Initialize the shared memory block
+ if( ! d->memory->lock() ){
+ qCritical() << "SingleApplication: Unable to lock memory block after create.";
+ abortSafely();
+ }
+ d->initializeMemoryBlock();
+ } else {
+ if( d->memory->error() == QSharedMemory::AlreadyExists ){
+ // Attempt to attach to the memory segment
+ if( ! d->memory->attach() ){
+ qCritical() << "SingleApplication: Unable to attach to shared memory block.";
+ abortSafely();
+ }
+ if( ! d->memory->lock() ){
+ qCritical() << "SingleApplication: Unable to lock memory block after attach.";
+ abortSafely();
+ }
+ } else {
+ qCritical() << "SingleApplication: Unable to create block.";
+ abortSafely();
+ }
+ }
+
+ auto *inst = static_cast<InstancesInfo*>( d->memory->data() );
+ QElapsedTimer time;
+ time.start();
+
+ // Make sure the shared memory block is initialised and in consistent state
+ while( true ){
+ // If the shared memory block's checksum is valid continue
+ if( d->blockChecksum() == inst->checksum ) break;
+
+ // If more than 5s have elapsed, assume the primary instance crashed and
+ // assume it's position
+ if( time.elapsed() > 5000 ){
+ qWarning() << "SingleApplication: Shared memory block has been in an inconsistent state from more than 5s. Assuming primary instance failure.";
+ d->initializeMemoryBlock();
+ }
+
+ // Otherwise wait for a random period and try again. The random sleep here
+ // limits the probability of a collision between two racing apps and
+ // allows the app to initialise faster
+ if( ! d->memory->unlock() ){
+ qDebug() << "SingleApplication: Unable to unlock memory for random wait.";
+ qDebug() << d->memory->errorString();
+ }
+ SingleApplicationPrivate::randomSleep();
+ if( ! d->memory->lock() ){
+ qCritical() << "SingleApplication: Unable to lock memory after random wait.";
+ abortSafely();
+ }
+ }
+
+ if( inst->primary == false ){
+ d->startPrimary();
+ if( ! d->memory->unlock() ){
+ qDebug() << "SingleApplication: Unable to unlock memory after primary start.";
+ qDebug() << d->memory->errorString();
+ }
+ return;
+ }
+
+ // Check if another instance can be started
+ if( allowSecondary ){
+ d->startSecondary();
+ if( d->options & Mode::SecondaryNotification ){
+ d->connectToPrimary( timeout, SingleApplicationPrivate::SecondaryInstance );
+ }
+ if( ! d->memory->unlock() ){
+ qDebug() << "SingleApplication: Unable to unlock memory after secondary start.";
+ qDebug() << d->memory->errorString();
+ }
+ return;
+ }
+
+ if( ! d->memory->unlock() ){
+ qDebug() << "SingleApplication: Unable to unlock memory at end of execution.";
+ qDebug() << d->memory->errorString();
+ }
+
+ d->connectToPrimary( timeout, SingleApplicationPrivate::NewInstance );
+
+ delete d;
+
+ ::exit( EXIT_SUCCESS );
+}
+
+SingleApplication::~SingleApplication()
+{
+ Q_D( SingleApplication );
+ delete d;
+}
+
+/**
+ * Checks if the current application instance is primary.
+ * @return Returns true if the instance is primary, false otherwise.
+ */
+bool SingleApplication::isPrimary() const
+{
+ Q_D( const SingleApplication );
+ return d->server != nullptr;
+}
+
+/**
+ * Checks if the current application instance is secondary.
+ * @return Returns true if the instance is secondary, false otherwise.
+ */
+bool SingleApplication::isSecondary() const
+{
+ Q_D( const SingleApplication );
+ return d->server == nullptr;
+}
+
+/**
+ * Allows you to identify an instance by returning unique consecutive instance
+ * ids. It is reset when the first (primary) instance of your app starts and
+ * only incremented afterwards.
+ * @return Returns a unique instance id.
+ */
+quint32 SingleApplication::instanceId() const
+{
+ Q_D( const SingleApplication );
+ return d->instanceNumber;
+}
+
+/**
+ * Returns the OS PID (Process Identifier) of the process running the primary
+ * instance. Especially useful when SingleApplication is coupled with OS.
+ * specific APIs.
+ * @return Returns the primary instance PID.
+ */
+qint64 SingleApplication::primaryPid() const
+{
+ Q_D( const SingleApplication );
+ return d->primaryPid();
+}
+
+/**
+ * Returns the username the primary instance is running as.
+ * @return Returns the username the primary instance is running as.
+ */
+QString SingleApplication::primaryUser() const
+{
+ Q_D( const SingleApplication );
+ return d->primaryUser();
+}
+
+/**
+ * Returns the username the current instance is running as.
+ * @return Returns the username the current instance is running as.
+ */
+QString SingleApplication::currentUser() const
+{
+ return SingleApplicationPrivate::getUsername();
+}
+
+/**
+ * Sends message to the Primary Instance.
+ * @param message The message to send.
+ * @param timeout the maximum timeout in milliseconds for blocking functions.
+ * @param sendMode mode of operation
+ * @return true if the message was sent successfuly, false otherwise.
+ */
+bool SingleApplication::sendMessage( const QByteArray &message, int timeout, SendMode sendMode )
+{
+ Q_D( SingleApplication );
+
+ // Nobody to connect to
+ if( isPrimary() ) return false;
+
+ // Make sure the socket is connected
+ if( ! d->connectToPrimary( timeout, SingleApplicationPrivate::Reconnect ) )
+ return false;
+
+ return d->writeConfirmedMessage( timeout, message, sendMode );
+}
+
+/**
+ * Cleans up the shared memory block and exits with a failure.
+ * This function halts program execution.
+ */
+void SingleApplication::abortSafely()
+{
+ Q_D( SingleApplication );
+
+ qCritical() << "SingleApplication: " << d->memory->error() << d->memory->errorString();
+ delete d;
+ ::exit( EXIT_FAILURE );
+}
+
+QStringList SingleApplication::userData() const
+{
+ Q_D( const SingleApplication );
+ return d->appData();
+}
diff --git a/src/singleapplication/singleapplication.h b/src/singleapplication/singleapplication.h
new file mode 100644
index 0000000..5565bb8
--- /dev/null
+++ b/src/singleapplication/singleapplication.h
@@ -0,0 +1,164 @@
+// The MIT License (MIT)
+//
+// Copyright (c) Itay Grudev 2015 - 2018
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#ifndef SINGLE_APPLICATION_H
+#define SINGLE_APPLICATION_H
+
+#include <QtCore/QtGlobal>
+#include <QtNetwork/QLocalSocket>
+
+#ifndef QAPPLICATION_CLASS
+ #define QAPPLICATION_CLASS QCoreApplication
+#endif
+
+#include QT_STRINGIFY(QAPPLICATION_CLASS)
+
+class SingleApplicationPrivate;
+
+/**
+ * @brief The SingleApplication class handles multiple instances of the same
+ * Application
+ * @see QCoreApplication
+ */
+class SingleApplication : public QAPPLICATION_CLASS
+{
+ Q_OBJECT
+
+ using app_t = QAPPLICATION_CLASS;
+
+public:
+ /**
+ * @brief Mode of operation of SingleApplication.
+ * Whether the block should be user-wide or system-wide and whether the
+ * primary instance should be notified when a secondary instance had been
+ * started.
+ * @note Operating system can restrict the shared memory blocks to the same
+ * user, in which case the User/System modes will have no effect and the
+ * block will be user wide.
+ * @enum
+ */
+ enum Mode {
+ User = 1 << 0,
+ System = 1 << 1,
+ SecondaryNotification = 1 << 2,
+ ExcludeAppVersion = 1 << 3,
+ ExcludeAppPath = 1 << 4
+ };
+ Q_DECLARE_FLAGS(Options, Mode)
+
+ /**
+ * @brief Intitializes a SingleApplication instance with argc command line
+ * arguments in argv
+ * @arg {int &} argc - Number of arguments in argv
+ * @arg {const char *[]} argv - Supplied command line arguments
+ * @arg {bool} allowSecondary - Whether to start the instance as secondary
+ * if there is already a primary instance.
+ * @arg {Mode} mode - Whether for the SingleApplication block to be applied
+ * User wide or System wide.
+ * @arg {int} timeout - Timeout to wait in milliseconds.
+ * @note argc and argv may be changed as Qt removes arguments that it
+ * recognizes
+ * @note Mode::SecondaryNotification only works if set on both the primary
+ * instance and the secondary instance.
+ * @note The timeout is just a hint for the maximum time of blocking
+ * operations. It does not guarantee that the SingleApplication
+ * initialisation will be completed in given time, though is a good hint.
+ * Usually 4*timeout would be the worst case (fail) scenario.
+ * @see See the corresponding QAPPLICATION_CLASS constructor for reference
+ */
+ explicit SingleApplication( int &argc, char *argv[], bool allowSecondary = false, Options options = Mode::User, int timeout = 1000, const QString &userData = {} );
+ ~SingleApplication() override;
+
+ /**
+ * @brief Returns if the instance is the primary instance
+ * @returns {bool}
+ */
+ bool isPrimary() const;
+
+ /**
+ * @brief Returns if the instance is a secondary instance
+ * @returns {bool}
+ */
+ bool isSecondary() const;
+
+ /**
+ * @brief Returns a unique identifier for the current instance
+ * @returns {qint32}
+ */
+ quint32 instanceId() const;
+
+ /**
+ * @brief Returns the process ID (PID) of the primary instance
+ * @returns {qint64}
+ */
+ qint64 primaryPid() const;
+
+ /**
+ * @brief Returns the username of the user running the primary instance
+ * @returns {QString}
+ */
+ QString primaryUser() const;
+
+ /**
+ * @brief Returns the username of the current user
+ * @returns {QString}
+ */
+ QString currentUser() const;
+
+ /**
+ * @brief Mode of operation of sendMessage.
+ * @enum
+ */
+ enum SendMode {
+ NonBlocking, /** Do not wait for the primary instance termination and return immediately */
+ BlockUntilPrimaryExit, /** Wait until the primary instance is terminated */
+ };
+
+ /**
+ * @brief Sends a message to the primary instance. Returns true on success.
+ * @param {int} timeout - Timeout for connecting
+ * @param {SendMode} sendMode - Mode of operation.
+ * @returns {bool}
+ * @note sendMessage() will return false if invoked from the primary
+ * instance.
+ */
+ bool sendMessage( const QByteArray &message, int timeout = 100, SendMode sendMode = NonBlocking );
+
+ /**
+ * @brief Get the set user data.
+ * @returns {QStringList}
+ */
+ QStringList userData() const;
+
+Q_SIGNALS:
+ void instanceStarted();
+ void receivedMessage( quint32 instanceId, QByteArray message );
+
+private:
+ SingleApplicationPrivate *d_ptr;
+ Q_DECLARE_PRIVATE(SingleApplication)
+ void abortSafely();
+};
+
+Q_DECLARE_OPERATORS_FOR_FLAGS(SingleApplication::Options)
+
+#endif // SINGLE_APPLICATION_H
diff --git a/src/singleapplication/singleapplication.pri b/src/singleapplication/singleapplication.pri
new file mode 100644
index 0000000..3597909
--- /dev/null
+++ b/src/singleapplication/singleapplication.pri
@@ -0,0 +1,10 @@
+QT += core network
+CONFIG += c++11
+
+HEADERS += $$PWD/SingleApplication \
+ $$PWD/singleapplication.h \
+ $$PWD/singleapplication_p.h
+SOURCES += $$PWD/singleapplication.cpp \
+ $$PWD/singleapplication_p.cpp
+
+INCLUDEPATH += $$PWD
diff --git a/src/singleapplication/singleapplication_p.cpp b/src/singleapplication/singleapplication_p.cpp
new file mode 100644
index 0000000..2a369bc
--- /dev/null
+++ b/src/singleapplication/singleapplication_p.cpp
@@ -0,0 +1,550 @@
+// The MIT License (MIT)
+//
+// Copyright (c) Itay Grudev 2015 - 2020
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+//
+// W A R N I N G !!!
+// -----------------
+//
+// This file is not part of the SingleApplication API. It is used purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or may even be removed.
+//
+
+#include <cstdlib>
+#include <cstddef>
+
+#include <QtCore/QDir>
+#include <QtCore/QThread>
+#include <QtCore/QByteArray>
+#include <QtCore/QDataStream>
+#include <QtCore/QElapsedTimer>
+#include <QtCore/QCryptographicHash>
+#include <QtNetwork/QLocalServer>
+#include <QtNetwork/QLocalSocket>
+
+#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
+#include <QtCore/QRandomGenerator>
+#else
+#include <QtCore/QDateTime>
+#endif
+
+#include "singleapplication.h"
+#include "singleapplication_p.h"
+
+#ifdef Q_OS_UNIX
+ #include <unistd.h>
+ #include <sys/types.h>
+ #include <pwd.h>
+#endif
+
+#ifdef Q_OS_WIN
+ #ifndef NOMINMAX
+ #define NOMINMAX 1
+ #endif
+ #include <windows.h>
+ #include <lmcons.h>
+#endif
+
+SingleApplicationPrivate::SingleApplicationPrivate( SingleApplication *q_ptr )
+ : q_ptr( q_ptr )
+{
+ server = nullptr;
+ socket = nullptr;
+ memory = nullptr;
+ instanceNumber = 0;
+}
+
+SingleApplicationPrivate::~SingleApplicationPrivate()
+{
+ if( socket != nullptr ){
+ socket->close();
+ delete socket;
+ }
+
+ if( memory != nullptr ){
+ memory->lock();
+ auto *inst = static_cast<InstancesInfo*>(memory->data());
+ if( server != nullptr ){
+ server->close();
+ delete server;
+ inst->primary = false;
+ inst->primaryPid = -1;
+ inst->primaryUser[0] = '\0';
+ inst->checksum = blockChecksum();
+ }
+ memory->unlock();
+
+ delete memory;
+ }
+}
+
+QString SingleApplicationPrivate::getUsername()
+{
+#ifdef Q_OS_WIN
+ wchar_t username[UNLEN + 1];
+ // Specifies size of the buffer on input
+ DWORD usernameLength = UNLEN + 1;
+ if( GetUserNameW( username, &usernameLength ) )
+ return QString::fromWCharArray( username );
+#if QT_VERSION < QT_VERSION_CHECK(5, 10, 0)
+ return QString::fromLocal8Bit( qgetenv( "USERNAME" ) );
+#else
+ return qEnvironmentVariable( "USERNAME" );
+#endif
+#endif
+#ifdef Q_OS_UNIX
+ QString username;
+ uid_t uid = geteuid();
+ struct passwd *pw = getpwuid( uid );
+ if( pw )
+ username = QString::fromLocal8Bit( pw->pw_name );
+ if ( username.isEmpty() ){
+#if QT_VERSION < QT_VERSION_CHECK(5, 10, 0)
+ username = QString::fromLocal8Bit( qgetenv( "USER" ) );
+#else
+ username = qEnvironmentVariable( "USER" );
+#endif
+ }
+ return username;
+#endif
+}
+
+void SingleApplicationPrivate::genBlockServerName()
+{
+ QCryptographicHash appData( QCryptographicHash::Sha256 );
+#if QT_VERSION < QT_VERSION_CHECK(6, 3, 0)
+ appData.addData( "SingleApplication", 17 );
+#else
+ appData.addData( QByteArrayView{"SingleApplication"} );
+#endif
+ appData.addData( SingleApplication::app_t::applicationName().toUtf8() );
+ appData.addData( SingleApplication::app_t::organizationName().toUtf8() );
+ appData.addData( SingleApplication::app_t::organizationDomain().toUtf8() );
+
+ if ( ! appDataList.isEmpty() )
+ appData.addData( appDataList.join(QString()).toUtf8() );
+
+ if( ! (options & SingleApplication::Mode::ExcludeAppVersion) ){
+ appData.addData( SingleApplication::app_t::applicationVersion().toUtf8() );
+ }
+
+ if( ! (options & SingleApplication::Mode::ExcludeAppPath) ){
+#if defined(Q_OS_WIN)
+ appData.addData( SingleApplication::app_t::applicationFilePath().toLower().toUtf8() );
+#elif defined(Q_OS_LINUX)
+ // If the application is running as an AppImage then the APPIMAGE env var should be used
+ // instead of applicationPath() as each instance is launched with its own executable path
+ const QByteArray appImagePath = qgetenv( "APPIMAGE" );
+ if( appImagePath.isEmpty() ){ // Not running as AppImage: use path to executable file
+ appData.addData( SingleApplication::app_t::applicationFilePath().toUtf8() );
+ } else { // Running as AppImage: Use absolute path to AppImage file
+ appData.addData( appImagePath );
+ };
+#else
+ appData.addData( SingleApplication::app_t::applicationFilePath().toUtf8() );
+#endif
+ }
+
+ // User level block requires a user specific data in the hash
+ if( options & SingleApplication::Mode::User ){
+ appData.addData( getUsername().toUtf8() );
+ }
+
+ // Replace the backslash in RFC 2045 Base64 [a-zA-Z0-9+/=] to comply with
+ // server naming requirements.
+ blockServerName = QString::fromUtf8(appData.result().toBase64().replace("/", "_"));
+}
+
+void SingleApplicationPrivate::initializeMemoryBlock() const
+{
+ auto *inst = static_cast<InstancesInfo*>( memory->data() );
+ inst->primary = false;
+ inst->secondary = 0;
+ inst->primaryPid = -1;
+ inst->primaryUser[0] = '\0';
+ inst->checksum = blockChecksum();
+}
+
+void SingleApplicationPrivate::startPrimary()
+{
+ // Reset the number of connections
+ auto *inst = static_cast <InstancesInfo*>( memory->data() );
+
+ inst->primary = true;
+ inst->primaryPid = QCoreApplication::applicationPid();
+ qstrncpy( inst->primaryUser, getUsername().toUtf8().data(), sizeof(inst->primaryUser) );
+ inst->checksum = blockChecksum();
+ instanceNumber = 0;
+ // Successful creation means that no main process exists
+ // So we start a QLocalServer to listen for connections
+ QLocalServer::removeServer( blockServerName );
+ server = new QLocalServer();
+
+ // Restrict access to the socket according to the
+ // SingleApplication::Mode::User flag on User level or no restrictions
+ if( options & SingleApplication::Mode::User ){
+ server->setSocketOptions( QLocalServer::UserAccessOption );
+ } else {
+ server->setSocketOptions( QLocalServer::WorldAccessOption );
+ }
+
+ server->listen( blockServerName );
+ QObject::connect(
+ server,
+ &QLocalServer::newConnection,
+ this,
+ &SingleApplicationPrivate::slotConnectionEstablished
+ );
+}
+
+void SingleApplicationPrivate::startSecondary()
+{
+ auto *inst = static_cast <InstancesInfo*>( memory->data() );
+
+ inst->secondary += 1;
+ inst->checksum = blockChecksum();
+ instanceNumber = inst->secondary;
+}
+
+bool SingleApplicationPrivate::connectToPrimary( int msecs, ConnectionType connectionType )
+{
+ QElapsedTimer time;
+ time.start();
+
+ // Connect to the Local Server of the Primary Instance if not already
+ // connected.
+ if( socket == nullptr ){
+ socket = new QLocalSocket();
+ }
+
+ if( socket->state() == QLocalSocket::ConnectedState ) return true;
+
+ if( socket->state() != QLocalSocket::ConnectedState ){
+
+ while( true ){
+ randomSleep();
+
+ if( socket->state() != QLocalSocket::ConnectingState )
+ socket->connectToServer( blockServerName );
+
+ if( socket->state() == QLocalSocket::ConnectingState ){
+ socket->waitForConnected( static_cast<int>(msecs - time.elapsed()) );
+ }
+
+ // If connected break out of the loop
+ if( socket->state() == QLocalSocket::ConnectedState ) break;
+
+ // If elapsed time since start is longer than the method timeout return
+ if( time.elapsed() >= msecs ) return false;
+ }
+ }
+
+ // Initialisation message according to the SingleApplication protocol
+ QByteArray initMsg;
+ QDataStream writeStream(&initMsg, QIODevice::WriteOnly);
+
+#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
+ writeStream.setVersion(QDataStream::Qt_5_6);
+#endif
+
+ writeStream << blockServerName.toLatin1();
+ writeStream << static_cast<quint8>(connectionType);
+ writeStream << instanceNumber;
+#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
+ quint16 checksum = qChecksum(QByteArray(initMsg.constData(), static_cast<quint32>(initMsg.length())));
+#else
+ quint16 checksum = qChecksum(initMsg.constData(), static_cast<quint32>(initMsg.length()));
+#endif
+ writeStream << checksum;
+
+ return writeConfirmedMessage( static_cast<int>(msecs - time.elapsed()), initMsg );
+}
+
+void SingleApplicationPrivate::writeAck( QLocalSocket *sock ) {
+ sock->putChar('\n');
+}
+
+bool SingleApplicationPrivate::writeConfirmedMessage (int msecs, const QByteArray &msg, SingleApplication::SendMode sendMode)
+{
+ QElapsedTimer time;
+ time.start();
+
+ // Frame 1: The header indicates the message length that follows
+ QByteArray header;
+ QDataStream headerStream(&header, QIODevice::WriteOnly);
+
+#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
+ headerStream.setVersion(QDataStream::Qt_5_6);
+#endif
+ headerStream << static_cast <quint64>( msg.length() );
+
+ if( ! writeConfirmedFrame( static_cast<int>(msecs - time.elapsed()), header ))
+ return false;
+
+ // Frame 2: The message
+ const bool result = writeConfirmedFrame( static_cast<int>(msecs - time.elapsed()), msg );
+
+ // Block if needed
+ if (socket && sendMode == SingleApplication::BlockUntilPrimaryExit)
+ socket->waitForDisconnected(-1);
+
+ return result;
+}
+
+bool SingleApplicationPrivate::writeConfirmedFrame( int msecs, const QByteArray &msg )
+{
+ socket->write( msg );
+ socket->flush();
+
+ bool result = socket->waitForReadyRead( msecs ); // await ack byte
+ if (result) {
+ socket->read( 1 );
+ return true;
+ }
+
+ return false;
+}
+
+quint16 SingleApplicationPrivate::blockChecksum() const
+{
+#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
+ quint16 checksum = qChecksum(QByteArray(static_cast<const char*>(memory->constData()), offsetof(InstancesInfo, checksum)));
+#else
+ quint16 checksum = qChecksum(static_cast<const char*>(memory->constData()), offsetof(InstancesInfo, checksum));
+#endif
+ return checksum;
+}
+
+qint64 SingleApplicationPrivate::primaryPid() const
+{
+ qint64 pid;
+
+ memory->lock();
+ auto *inst = static_cast<InstancesInfo*>( memory->data() );
+ pid = inst->primaryPid;
+ memory->unlock();
+
+ return pid;
+}
+
+QString SingleApplicationPrivate::primaryUser() const
+{
+ QByteArray username;
+
+ memory->lock();
+ auto *inst = static_cast<InstancesInfo*>( memory->data() );
+ username = inst->primaryUser;
+ memory->unlock();
+
+ return QString::fromUtf8( username );
+}
+
+/**
+ * @brief Executed when a connection has been made to the LocalServer
+ */
+void SingleApplicationPrivate::slotConnectionEstablished()
+{
+ QLocalSocket *nextConnSocket = server->nextPendingConnection();
+ connectionMap.insert(nextConnSocket, ConnectionInfo());
+
+ QObject::connect(nextConnSocket, &QLocalSocket::aboutToClose, this,
+ [nextConnSocket, this](){
+ auto &info = connectionMap[nextConnSocket];
+ this->slotClientConnectionClosed( nextConnSocket, info.instanceId );
+ }
+ );
+
+ QObject::connect(nextConnSocket, &QLocalSocket::disconnected, nextConnSocket, &QLocalSocket::deleteLater);
+
+ QObject::connect(nextConnSocket, &QLocalSocket::destroyed, this,
+ [nextConnSocket, this](){
+ connectionMap.remove(nextConnSocket);
+ }
+ );
+
+ QObject::connect(nextConnSocket, &QLocalSocket::readyRead, this,
+ [nextConnSocket, this](){
+ auto &info = connectionMap[nextConnSocket];
+ switch(info.stage){
+ case StageInitHeader:
+ readMessageHeader( nextConnSocket, StageInitBody );
+ break;
+ case StageInitBody:
+ readInitMessageBody(nextConnSocket);
+ break;
+ case StageConnectedHeader:
+ readMessageHeader( nextConnSocket, StageConnectedBody );
+ break;
+ case StageConnectedBody:
+ this->slotDataAvailable( nextConnSocket, info.instanceId );
+ break;
+ default:
+ break;
+ };
+ }
+ );
+}
+
+void SingleApplicationPrivate::readMessageHeader( QLocalSocket *sock, SingleApplicationPrivate::ConnectionStage nextStage )
+{
+ if (!connectionMap.contains( sock )){
+ return;
+ }
+
+ if( sock->bytesAvailable() < ( qint64 )sizeof( quint64 ) ){
+ return;
+ }
+
+ QDataStream headerStream( sock );
+
+#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
+ headerStream.setVersion( QDataStream::Qt_5_6 );
+#endif
+
+ // Read the header to know the message length
+ quint64 msgLen = 0;
+ headerStream >> msgLen;
+ ConnectionInfo &info = connectionMap[sock];
+ info.stage = nextStage;
+ info.msgLen = msgLen;
+
+ writeAck( sock );
+}
+
+bool SingleApplicationPrivate::isFrameComplete( QLocalSocket *sock )
+{
+ if (!connectionMap.contains( sock )){
+ return false;
+ }
+
+ ConnectionInfo &info = connectionMap[sock];
+ if( sock->bytesAvailable() < ( qint64 )info.msgLen ){
+ return false;
+ }
+
+ return true;
+}
+
+void SingleApplicationPrivate::readInitMessageBody( QLocalSocket *sock )
+{
+ Q_Q(SingleApplication);
+
+ if( !isFrameComplete( sock ) )
+ return;
+
+ // Read the message body
+ QByteArray msgBytes = sock->readAll();
+ QDataStream readStream(msgBytes);
+
+#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
+ readStream.setVersion( QDataStream::Qt_5_6 );
+#endif
+
+ // server name
+ QByteArray latin1Name;
+ readStream >> latin1Name;
+
+ // connection type
+ ConnectionType connectionType = InvalidConnection;
+ quint8 connTypeVal = InvalidConnection;
+ readStream >> connTypeVal;
+ connectionType = static_cast <ConnectionType>( connTypeVal );
+
+ // instance id
+ quint32 instanceId = 0;
+ readStream >> instanceId;
+
+ // checksum
+ quint16 msgChecksum = 0;
+ readStream >> msgChecksum;
+
+#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
+ const quint16 actualChecksum = qChecksum(QByteArray(msgBytes.constData(), static_cast<quint32>(msgBytes.length() - sizeof(quint16))));
+#else
+ const quint16 actualChecksum = qChecksum(msgBytes.constData(), static_cast<quint32>(msgBytes.length() - sizeof(quint16)));
+#endif
+
+ bool isValid = readStream.status() == QDataStream::Ok &&
+ QLatin1String(latin1Name) == blockServerName &&
+ msgChecksum == actualChecksum;
+
+ if( !isValid ){
+ sock->close();
+ return;
+ }
+
+ ConnectionInfo &info = connectionMap[sock];
+ info.instanceId = instanceId;
+ info.stage = StageConnectedHeader;
+
+ if( connectionType == NewInstance ||
+ ( connectionType == SecondaryInstance &&
+ options & SingleApplication::Mode::SecondaryNotification ) )
+ {
+ Q_EMIT q->instanceStarted();
+ }
+
+ writeAck( sock );
+}
+
+void SingleApplicationPrivate::slotDataAvailable( QLocalSocket *dataSocket, quint32 instanceId )
+{
+ Q_Q(SingleApplication);
+
+ if ( !isFrameComplete( dataSocket ) )
+ return;
+
+ const QByteArray message = dataSocket->readAll();
+
+ writeAck( dataSocket );
+
+ ConnectionInfo &info = connectionMap[dataSocket];
+ info.stage = StageConnectedHeader;
+
+ Q_EMIT q->receivedMessage( instanceId, message);
+}
+
+void SingleApplicationPrivate::slotClientConnectionClosed( QLocalSocket *closedSocket, quint32 instanceId )
+{
+ if( closedSocket->bytesAvailable() > 0 )
+ slotDataAvailable( closedSocket, instanceId );
+}
+
+void SingleApplicationPrivate::randomSleep()
+{
+#if QT_VERSION >= QT_VERSION_CHECK( 5, 10, 0 )
+ QThread::msleep( QRandomGenerator::global()->bounded( 8u, 18u ));
+#else
+ qsrand( QDateTime::currentMSecsSinceEpoch() % std::numeric_limits<uint>::max() );
+ QThread::msleep( qrand() % 11 + 8);
+#endif
+}
+
+void SingleApplicationPrivate::addAppData(const QString &data)
+{
+ appDataList.push_back(data);
+}
+
+QStringList SingleApplicationPrivate::appData() const
+{
+ return appDataList;
+}
diff --git a/src/singleapplication/singleapplication_p.h b/src/singleapplication/singleapplication_p.h
new file mode 100644
index 0000000..30a2b51
--- /dev/null
+++ b/src/singleapplication/singleapplication_p.h
@@ -0,0 +1,109 @@
+// The MIT License (MIT)
+//
+// Copyright (c) Itay Grudev 2015 - 2020
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+//
+// W A R N I N G !!!
+// -----------------
+//
+// This file is not part of the SingleApplication API. It is used purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or may even be removed.
+//
+
+#ifndef SINGLEAPPLICATION_P_H
+#define SINGLEAPPLICATION_P_H
+
+#include <QtCore/QSharedMemory>
+#include <QtNetwork/QLocalServer>
+#include <QtNetwork/QLocalSocket>
+#include "singleapplication.h"
+
+struct InstancesInfo {
+ bool primary;
+ quint32 secondary;
+ qint64 primaryPid;
+ char primaryUser[128];
+ quint16 checksum; // Must be the last field
+};
+
+struct ConnectionInfo {
+ qint64 msgLen = 0;
+ quint32 instanceId = 0;
+ quint8 stage = 0;
+};
+
+class SingleApplicationPrivate : public QObject {
+Q_OBJECT
+public:
+ enum ConnectionType : quint8 {
+ InvalidConnection = 0,
+ NewInstance = 1,
+ SecondaryInstance = 2,
+ Reconnect = 3
+ };
+ enum ConnectionStage : quint8 {
+ StageInitHeader = 0,
+ StageInitBody = 1,
+ StageConnectedHeader = 2,
+ StageConnectedBody = 3,
+ };
+ Q_DECLARE_PUBLIC(SingleApplication)
+
+ SingleApplicationPrivate( SingleApplication *q_ptr );
+ ~SingleApplicationPrivate() override;
+
+ static QString getUsername();
+ void genBlockServerName();
+ void initializeMemoryBlock() const;
+ void startPrimary();
+ void startSecondary();
+ bool connectToPrimary( int msecs, ConnectionType connectionType );
+ quint16 blockChecksum() const;
+ qint64 primaryPid() const;
+ QString primaryUser() const;
+ bool isFrameComplete(QLocalSocket *sock);
+ void readMessageHeader(QLocalSocket *socket, ConnectionStage nextStage);
+ void readInitMessageBody(QLocalSocket *socket);
+ void writeAck(QLocalSocket *sock);
+ bool writeConfirmedFrame(int msecs, const QByteArray &msg);
+ bool writeConfirmedMessage(int msecs, const QByteArray &msg, SingleApplication::SendMode sendMode = SingleApplication::NonBlocking);
+ static void randomSleep();
+ void addAppData(const QString &data);
+ QStringList appData() const;
+
+ SingleApplication *q_ptr;
+ QSharedMemory *memory;
+ QLocalSocket *socket;
+ QLocalServer *server;
+ quint32 instanceNumber;
+ QString blockServerName;
+ SingleApplication::Options options;
+ QMap<QLocalSocket*, ConnectionInfo> connectionMap;
+ QStringList appDataList;
+
+public Q_SLOTS:
+ void slotConnectionEstablished();
+ void slotDataAvailable( QLocalSocket*, quint32 );
+ void slotClientConnectionClosed( QLocalSocket*, quint32 );
+};
+
+#endif // SINGLEAPPLICATION_P_H