Krita is a free and open source cross-platform application that offers an end-to-end solution for creating digital art files from scratch built on the KDE and Qt frameworks.
C++
Update QtSingleApplication for a new version from Qt's repo
Dmitry Kazakovbc9ad7c8e23d
diff --git a/krita/main.cc b/krita/main.ccindex 475b1bc208..40f1736fd2 100644--- a/krita/main.cc+++ b/krita/main.cc@@ -670,7 +670,7 @@ extern "C" MAIN_EXPORT int MAIN_FN(int argc, char **argv)const bool batchRun = args.exportAs() || args.exportSequence();if (!batchRun) {- if (app.sendMessage(args.serialize())) {+ if (app.sendMessage(args.serialize().toBase64())) {return 0;}}@@ -732,11 +732,8 @@ extern "C" MAIN_EXPORT int MAIN_FN(int argc, char **argv)KisApplication::setAttribute(Qt::AA_CompressHighFrequencyEvents, false);// Set up remote arguments.- QObject::connect(&app, SIGNAL(messageReceived(QByteArray,QObject*)),- &app, SLOT(remoteArguments(QByteArray,QObject*)));-- QObject::connect(&app, SIGNAL(fileOpenRequest(QString)),- &app, SLOT(fileOpenRequested(QString)));+ QObject::connect(&app, &KisApplication::messageReceived,+ &app, &KisApplication::remoteArguments);// Hardware informationKisUsageLogger::writeSysInfo("\nHardware Information\n");diff --git a/libs/ui/CMakeLists.txt b/libs/ui/CMakeLists.txtindex eecd482c1f..aafe60fe81 100644--- a/libs/ui/CMakeLists.txt+++ b/libs/ui/CMakeLists.txt@@ -1,6 +1,3 @@-include_directories(- ${CMAKE_CURRENT_SOURCE_DIR}/qtlockedfile-)if (ANDROID)# We explicitly set QT_OPENGL_ES_3 here because Qt for some reason does@@ -442,8 +439,6 @@ set(kritaui_LIB_SRCSKisViewManager.cppkis_mirror_manager.cpp- qtlockedfile/qtlockedfile.cpp-qtsingleapplication/qtlocalpeer.cppqtsingleapplication/qtsingleapplication.cpp@@ -490,10 +485,6 @@ if (Mlt7_FOUND)endif()if(WIN32)- set(kritaui_LIB_SRCS- ${kritaui_LIB_SRCS}- qtlockedfile/qtlockedfile_win.cpp- )set(kritaui_LIB_SRCS${kritaui_LIB_SRCS}dialogs/KisDlgCustomTabletResolution.cpp@@ -522,13 +513,6 @@ endif()input/wintab/drawpile_tablettester/tablettest.cpp)-if (UNIX)- set(kritaui_LIB_SRCS- ${kritaui_LIB_SRCS}- qtlockedfile/qtlockedfile_unix.cpp- )-endif()-if (ENABLE_UPDATERS)if (UNIX)set(kritaui_LIB_SRCSdiff --git a/libs/ui/KisApplication.cpp b/libs/ui/KisApplication.cppindex 6aca8a6e2f..5f53c92c20 100644--- a/libs/ui/KisApplication.cpp+++ b/libs/ui/KisApplication.cpp@@ -979,10 +979,8 @@ void KisApplication::executeRemoteArguments(QByteArray message, KisMainWindow *m}-void KisApplication::remoteArguments(QByteArray message, QObject *socket)+void KisApplication::remoteArguments(const QString &message){- Q_UNUSED(socket);-// check if we have any mainwindowKisMainWindow *mw = qobject_cast<KisMainWindow*>(qApp->activeWindow());@@ -990,11 +988,14 @@ void KisApplication::remoteArguments(QByteArray message, QObject *socket)mw = KisPart::instance()->mainWindows().first();}+ const QByteArray unpackedMessage =+ QByteArray::fromBase64(message.toLatin1());+if (!mw) {- d->earlyRemoteArguments << message;+ d->earlyRemoteArguments << unpackedMessage;return;}- executeRemoteArguments(message, mw);+ executeRemoteArguments(unpackedMessage, mw);}void KisApplication::fileOpenRequested(const QString &url)diff --git a/libs/ui/KisApplication.h b/libs/ui/KisApplication.hindex a55ac1d227..3fa6d0a492 100644--- a/libs/ui/KisApplication.h+++ b/libs/ui/KisApplication.h@@ -96,7 +96,7 @@ public:public Q_SLOTS:void executeRemoteArguments(QByteArray message, KisMainWindow *mainWindow);- void remoteArguments(QByteArray message, QObject*socket);+ void remoteArguments(const QString &message);void fileOpenRequested(const QString & url);void setSplashScreenLoadingText(const QString&);diff --git a/libs/ui/KisApplicationArguments.cpp b/libs/ui/KisApplicationArguments.cppindex 40208ab6c9..7eb21243a9 100644--- a/libs/ui/KisApplicationArguments.cpp+++ b/libs/ui/KisApplicationArguments.cpp@@ -238,7 +238,9 @@ QByteArray KisApplicationArguments::serialize()buf.open(QIODevice::WriteOnly);QDataStream ds(&buf);ds.setVersion(QDataStream::Qt_5_0);- ds << d->filenames.count();+ // explicitly declare the type of the size variable+ const qsizetype fileNamesCount = d->filenames.count();+ ds << fileNamesCount;Q_FOREACH (const QString &filename, d->filenames) {ds << filename;}@@ -274,9 +276,9 @@ KisApplicationArguments KisApplicationArguments::deserialize(QByteArray &serialibuf.open(QIODevice::ReadOnly);QDataStream ds(&buf);ds.setVersion(QDataStream::Qt_5_0);- int count;- ds >> count;- for(int i = 0; i < count; ++i) {+ qsizetype fileNamesCount;+ ds >> fileNamesCount;+ for(int i = 0; i < fileNamesCount; ++i) {QString s;ds >> s;args.d->filenames << s;diff --git a/libs/ui/qtlockedfile/README.txt b/libs/ui/qtlockedfile/README.txtdeleted file mode 100644index 6fcf2fd295..0000000000--- a/libs/ui/qtlockedfile/README.txt+++ /dev/null@@ -1,10 +0,0 @@-This is the src directory of the QtLockedFile-solution integrated over from addons/main/utils/qtlockedfile/src .--namespace.patch was applied to introduce the SharedTools namespace.--It is required by the QtSingleApplication solution.--History:--16.05.2008 Integrateddiff --git a/libs/ui/qtlockedfile/qtlockedfile.cpp b/libs/ui/qtlockedfile/qtlockedfile.cppdeleted file mode 100644index d3b7e85213..0000000000--- a/libs/ui/qtlockedfile/qtlockedfile.cpp+++ /dev/null@@ -1,157 +0,0 @@-/****************************************************************************-**-** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).-** Contact: http://www.qt-project.org/legal-**-** This file is part of Qt Creator.-**-** Commercial License Usage-** Licensees holding valid commercial Qt licenses may use this file in-** accordance with the commercial license agreement provided with the-** Software or, alternatively, in accordance with the terms contained in-** a written agreement between you and Digia. For licensing terms and-** conditions see http://www.qt.io/licensing. For further information-** use the contact form at http://www.qt.io/contact-us.-**-** GNU Lesser General Public License Usage-** Alternatively, this file may be used under the terms of the GNU Lesser-** General Public License version 2.1 or version 3 as published by the Free-** Software Foundation and appearing in the file LICENSE.LGPLv21 and-** LICENSE.LGPLv3 included in the packaging of this file. Please review the-** following information to ensure the GNU Lesser General Public License-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.-**-** In addition, as a special exception, Digia gives you certain additional-** rights. These rights are described in the Digia Qt LGPL Exception-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.-**-****************************************************************************/--#include "qtlockedfile.h"----/*!- \class QtLockedFile-- \brief The QtLockedFile class extends QFile with advisory locking functions.-- A file may be locked in read or write mode. Multiple instances of- \e QtLockedFile, created in multiple processes running on the same- machine, may have a file locked in read mode. Exactly one instance- may have it locked in write mode. A read and a write lock cannot- exist simultaneously on the same file.-- The file locks are advisory. This means that nothing prevents- another process from manipulating a locked file using QFile or- file system functions offered by the OS. Serialization is only- guaranteed if all processes that access the file use- QtLockedFile. Also, while holding a lock on a file, a process- must not open the same file again (through any API), or locks- can be unexpectedly lost.-- The lock provided by an instance of \e QtLockedFile is released- whenever the program terminates. This is true even when the- program crashes and no destructors are called.-*/--/*! \enum QtLockedFile::LockMode-- This enum describes the available lock modes.-- \var ReadLock A read lock.- \var WriteLock A write lock.- \var NoLock Neither a read lock nor a write lock.-*/--/*!- Constructs an unlocked \e QtLockedFile object. This constructor behaves in the same way- as \e QFile::QFile().-- \sa QFile::QFile()-*/-QtLockedFile::QtLockedFile()- : QFile()-{-#ifdef Q_OS_WIN- m_semaphore_hnd = 0;- m_mutex_hnd = 0;-#endif- m_lock_mode = NoLock;-}--/*!- Constructs an unlocked QtLockedFile object with file \a name. This constructor behaves in- the same way as \e QFile::QFile(const QString&).-- \sa QFile::QFile()-*/-QtLockedFile::QtLockedFile(const QString &name)- : QFile(name)-{-#ifdef Q_OS_WIN- m_semaphore_hnd = 0;- m_mutex_hnd = 0;-#endif- m_lock_mode = NoLock;-}--/*!- Returns \e true if this object has a in read or write lock;- otherwise returns \e false.-- \sa lockMode()-*/-bool QtLockedFile::isLocked() const-{- return m_lock_mode != NoLock;-}--/*!- Returns the type of lock currently held by this object, or \e QtLockedFile::NoLock.-- \sa isLocked()-*/-QtLockedFile::LockMode QtLockedFile::lockMode() const-{- return m_lock_mode;-}--/*!- \fn bool QtLockedFile::lock(LockMode mode, bool block = true)-- Obtains a lock of type \a mode.-- If \a block is true, this- function will block until the lock is acquired. If \a block is- false, this function returns \e false immediately if the lock cannot- be acquired.-- If this object already has a lock of type \a mode, this function returns \e true immediately. If this object has a lock of a different type than \a mode, the lock- is first released and then a new lock is obtained.-- This function returns \e true if, after it executes, the file is locked by this object,- and \e false otherwise.-- \sa unlock(), isLocked(), lockMode()-*/--/*!- \fn bool QtLockedFile::unlock()-- Releases a lock.-- If the object has no lock, this function returns immediately.-- This function returns \e true if, after it executes, the file is not locked by- this object, and \e false otherwise.-- \sa lock(), isLocked(), lockMode()-*/--/*!- \fn QtLockedFile::~QtLockedFile()-- Destroys the \e QtLockedFile object. If any locks were held, they are released.-*/diff --git a/libs/ui/qtlockedfile/qtlockedfile.h b/libs/ui/qtlockedfile/qtlockedfile.hdeleted file mode 100644index 7bc9338299..0000000000--- a/libs/ui/qtlockedfile/qtlockedfile.h+++ /dev/null@@ -1,76 +0,0 @@-/****************************************************************************-**-** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).-** Contact: http://www.qt-project.org/legal-**-** This file is part of Qt Creator.-**-** Commercial License Usage-** Licensees holding valid commercial Qt licenses may use this file in-** accordance with the commercial license agreement provided with the-** Software or, alternatively, in accordance with the terms contained in-** a written agreement between you and Digia. For licensing terms and-** conditions see http://www.qt.io/licensing. For further information-** use the contact form at http://www.qt.io/contact-us.-**-** GNU Lesser General Public License Usage-** Alternatively, this file may be used under the terms of the GNU Lesser-** General Public License version 2.1 or version 3 as published by the Free-** Software Foundation and appearing in the file LICENSE.LGPLv21 and-** LICENSE.LGPLv3 included in the packaging of this file. Please review the-** following information to ensure the GNU Lesser General Public License-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.-**-** In addition, as a special exception, Digia gives you certain additional-** rights. These rights are described in the Digia Qt LGPL Exception-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.-**-****************************************************************************/--#ifndef QTLOCKEDFILE_H-#define QTLOCKEDFILE_H--#include <QFile>--#if defined(Q_OS_WIN)-# if !defined(QT_QTLOCKEDFILE_EXPORT) && !defined(QT_QTLOCKEDFILE_IMPORT)-# define QT_QTLOCKEDFILE_EXPORT-# elif defined(QT_QTLOCKEDFILE_IMPORT)-# if defined(QT_QTLOCKEDFILE_EXPORT)-# undef QT_QTLOCKEDFILE_EXPORT-# endif-# define QT_QTLOCKEDFILE_EXPORT __declspec(dllimport)-# elif defined(QT_QTLOCKEDFILE_EXPORT)-# undef QT_QTLOCKEDFILE_EXPORT-# define QT_QTLOCKEDFILE_EXPORT __declspec(dllexport)-# endif-#else-# define QT_QTLOCKEDFILE_EXPORT-#endif----class QT_QTLOCKEDFILE_EXPORT QtLockedFile : public QFile-{-public:- enum LockMode { NoLock = 0, ReadLock, WriteLock };-- QtLockedFile();- QtLockedFile(const QString &name);- ~QtLockedFile() override;-- bool lock(LockMode mode, bool block = true);- bool unlock();- bool isLocked() const;- LockMode lockMode() const;--private:-#ifdef Q_OS_WIN- Qt::HANDLE m_semaphore_hnd;- Qt::HANDLE m_mutex_hnd;-#endif- LockMode m_lock_mode;-};--#endif // QTLOCKEDFILE_Hdiff --git a/libs/ui/qtlockedfile/qtlockedfile.pri b/libs/ui/qtlockedfile/qtlockedfile.prideleted file mode 100644index 46d1f1a12a..0000000000--- a/libs/ui/qtlockedfile/qtlockedfile.pri+++ /dev/null@@ -1,13 +0,0 @@-INCLUDEPATH += $$PWD-DEPENDPATH += $$PWD-HEADERS += $$PWD/qtlockedfile.h-SOURCES += $$PWD/qtlockedfile.cpp--unix:SOURCES += $$PWD/qtlockedfile_unix.cpp-win32:SOURCES += $$PWD/qtlockedfile_win.cpp--win32:contains(TEMPLATE, lib):contains(CONFIG, shared) {- DEFINES += QT_QTLOCKEDFILE_EXPORT=__declspec(dllexport)-}--diff --git a/libs/ui/qtlockedfile/qtlockedfile_unix.cpp b/libs/ui/qtlockedfile/qtlockedfile_unix.cppdeleted file mode 100644index 0d0ba95fab..0000000000--- a/libs/ui/qtlockedfile/qtlockedfile_unix.cpp+++ /dev/null@@ -1,107 +0,0 @@-/****************************************************************************-**-** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).-** Contact: http://www.qt-project.org/legal-**-** This file is part of Qt Creator.-**-** Commercial License Usage-** Licensees holding valid commercial Qt licenses may use this file in-** accordance with the commercial license agreement provided with the-** Software or, alternatively, in accordance with the terms contained in-** a written agreement between you and Digia. For licensing terms and-** conditions see http://www.qt.io/licensing. For further information-** use the contact form at http://www.qt.io/contact-us.-**-** GNU Lesser General Public License Usage-** Alternatively, this file may be used under the terms of the GNU Lesser-** General Public License version 2.1 or version 3 as published by the Free-** Software Foundation and appearing in the file LICENSE.LGPLv21 and-** LICENSE.LGPLv3 included in the packaging of this file. Please review the-** following information to ensure the GNU Lesser General Public License-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.-**-** In addition, as a special exception, Digia gives you certain additional-** rights. These rights are described in the Digia Qt LGPL Exception-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.-**-****************************************************************************/--#include "qtlockedfile.h"--#include <string.h>-#include <errno.h>-#include <unistd.h>-#include <fcntl.h>----bool QtLockedFile::lock(LockMode mode, bool block)-{- if (!isOpen()) {- qWarning("QtLockedFile::lock(): file is not opened");- return false;- }-- if (mode == NoLock)- return unlock();-- if (mode == m_lock_mode)- return true;-- if (m_lock_mode != NoLock)- unlock();-- struct flock fl;- fl.l_whence = SEEK_SET;- fl.l_start = 0;- fl.l_len = 0;- fl.l_type = (mode == ReadLock) ? F_RDLCK : F_WRLCK;- int cmd = block ? F_SETLKW : F_SETLK;- int ret = fcntl(handle(), cmd, &fl);-- if (ret == -1) {- if (errno != EINTR && errno != EAGAIN)- qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno));- return false;- }--- m_lock_mode = mode;- return true;-}---bool QtLockedFile::unlock()-{- if (!isOpen()) {- qWarning("QtLockedFile::unlock(): file is not opened");- return false;- }-- if (!isLocked())- return true;-- struct flock fl;- fl.l_whence = SEEK_SET;- fl.l_start = 0;- fl.l_len = 0;- fl.l_type = F_UNLCK;- int ret = fcntl(handle(), F_SETLKW, &fl);-- if (ret == -1) {- qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno));- return false;- }-- m_lock_mode = NoLock;- remove();- return true;-}--QtLockedFile::~QtLockedFile()-{- if (isOpen())- unlock();-}diff --git a/libs/ui/qtlockedfile/qtlockedfile_win.cpp b/libs/ui/qtlockedfile/qtlockedfile_win.cppdeleted file mode 100644index 4f5d8a1f5c..0000000000--- a/libs/ui/qtlockedfile/qtlockedfile_win.cpp+++ /dev/null@@ -1,196 +0,0 @@-/****************************************************************************-**-** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).-** Contact: http://www.qt-project.org/legal-**-** This file is part of Qt Creator.-**-** Commercial License Usage-** Licensees holding valid commercial Qt licenses may use this file in-** accordance with the commercial license agreement provided with the-** Software or, alternatively, in accordance with the terms contained in-** a written agreement between you and Digia. For licensing terms and-** conditions see http://www.qt.io/licensing. For further information-** use the contact form at http://www.qt.io/contact-us.-**-** GNU Lesser General Public License Usage-** Alternatively, this file may be used under the terms of the GNU Lesser-** General Public License version 2.1 or version 3 as published by the Free-** Software Foundation and appearing in the file LICENSE.LGPLv21 and-** LICENSE.LGPLv3 included in the packaging of this file. Please review the-** following information to ensure the GNU Lesser General Public License-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.-**-** In addition, as a special exception, Digia gives you certain additional-** rights. These rights are described in the Digia Qt LGPL Exception-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.-**-****************************************************************************/--#include "qtlockedfile.h"--#include <qt_windows.h>-#include <QFileInfo>----#define SEMAPHORE_PREFIX "QtLockedFile semaphore "-#define MUTEX_PREFIX "QtLockedFile mutex "-#define SEMAPHORE_MAX 100--static QString errorCodeToString(DWORD errorCode)-{- QString result;- char *data = 0;- FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,- 0, errorCode, 0,- (char*)&data, 0, 0);- result = QString::fromLocal8Bit(data);- if (data != 0)- LocalFree(data);-- if (result.endsWith(QLatin1Char('\n')))- result.truncate(result.length() - 1);-- return result;-}--bool QtLockedFile::lock(LockMode mode, bool block)-{- if (!isOpen()) {- qWarning("QtLockedFile::lock(): file is not opened");- return false;- }-- if (mode == m_lock_mode)- return true;-- if (m_lock_mode != 0)- unlock();-- if (m_semaphore_hnd == 0) {- QFileInfo fi(*this);- QString sem_name = QString::fromLatin1(SEMAPHORE_PREFIX)- + fi.absoluteFilePath().toLower();-- m_semaphore_hnd = CreateSemaphoreW(0, SEMAPHORE_MAX, SEMAPHORE_MAX,- (TCHAR*)sem_name.utf16());-- if (m_semaphore_hnd == 0) {- qWarning("QtLockedFile::lock(): CreateSemaphore: %s",- errorCodeToString(GetLastError()).toLatin1().constData());- return false;- }- }-- bool gotMutex = false;- int decrement;- if (mode == ReadLock) {- decrement = 1;- } else {- decrement = SEMAPHORE_MAX;- if (m_mutex_hnd == 0) {- QFileInfo fi(*this);- QString mut_name = QString::fromLatin1(MUTEX_PREFIX)- + fi.absoluteFilePath().toLower();-- m_mutex_hnd = CreateMutexW(NULL, FALSE, (TCHAR*)mut_name.utf16());-- if (m_mutex_hnd == 0) {- qWarning("QtLockedFile::lock(): CreateMutex: %s",- errorCodeToString(GetLastError()).toLatin1().constData());- return false;- }- }- DWORD res = WaitForSingleObject(m_mutex_hnd, block ? INFINITE : 0);- if (res == WAIT_TIMEOUT)- return false;- if (res == WAIT_FAILED) {- qWarning("QtLockedFile::lock(): WaitForSingleObject (mutex): %s",- errorCodeToString(GetLastError()).toLatin1().constData());- return false;- }- gotMutex = true;- }-- for (int i = 0; i < decrement; ++i) {- DWORD res = WaitForSingleObject(m_semaphore_hnd, block ? INFINITE : 0);- if (res == WAIT_TIMEOUT) {- if (i) {- // A failed nonblocking rw locking. Undo changes to semaphore.- if (ReleaseSemaphore(m_semaphore_hnd, i, NULL) == 0) {- qWarning("QtLockedFile::unlock(): ReleaseSemaphore: %s",- errorCodeToString(GetLastError()).toLatin1().constData());- // Fall through- }- }- if (gotMutex)- ReleaseMutex(m_mutex_hnd);- return false;- }- if (res != WAIT_OBJECT_0) {- if (gotMutex)- ReleaseMutex(m_mutex_hnd);- qWarning("QtLockedFile::lock(): WaitForSingleObject (semaphore): %s",- errorCodeToString(GetLastError()).toLatin1().constData());- return false;- }- }-- m_lock_mode = mode;- if (gotMutex)- ReleaseMutex(m_mutex_hnd);- return true;-}--bool QtLockedFile::unlock()-{- if (!isOpen()) {- qWarning("QtLockedFile::unlock(): file is not opened");- return false;- }-- if (!isLocked())- return true;-- int increment;- if (m_lock_mode == ReadLock)- increment = 1;- else- increment = SEMAPHORE_MAX;-- DWORD ret = ReleaseSemaphore(m_semaphore_hnd, increment, 0);- if (ret == 0) {- qWarning("QtLockedFile::unlock(): ReleaseSemaphore: %s",- errorCodeToString(GetLastError()).toLatin1().constData());- return false;- }-- m_lock_mode = QtLockedFile::NoLock;- remove();- return true;-}--QtLockedFile::~QtLockedFile()-{- if (isOpen())- unlock();- if (m_mutex_hnd != 0) {- DWORD ret = CloseHandle(m_mutex_hnd);- if (ret == 0) {- qWarning("QtLockedFile::~QtLockedFile(): CloseHandle (mutex): %s",- errorCodeToString(GetLastError()).toLatin1().constData());- }- m_mutex_hnd = 0;- }- if (m_semaphore_hnd != 0) {- DWORD ret = CloseHandle(m_semaphore_hnd);- if (ret == 0) {- qWarning("QtLockedFile::~QtLockedFile(): CloseHandle (semaphore): %s",- errorCodeToString(GetLastError()).toLatin1().constData());- }- m_semaphore_hnd = 0;- }-}-diff --git a/libs/ui/qtsingleapplication/README.txt b/libs/ui/qtsingleapplication/README.txtdeleted file mode 100644index 1909a33fca..0000000000--- a/libs/ui/qtsingleapplication/README.txt+++ /dev/null@@ -1,10 +0,0 @@-This is the src directory of the QtSingleApplication solution-integrated over from addons/main/utils/qtsingleapplication/src .--namespace.patch was applied to introduce the SharedTools namespace.--It additionally requires the QtLockedFile solution.--History:--16.05.2008 Integrateddiff --git a/libs/ui/qtsingleapplication/qtlocalpeer.cpp b/libs/ui/qtsingleapplication/qtlocalpeer.cppindex 099ac33bfc..7e99171f10 100644--- a/libs/ui/qtsingleapplication/qtlocalpeer.cpp+++ b/libs/ui/qtsingleapplication/qtlocalpeer.cpp@@ -1,37 +1,11 @@-/****************************************************************************-**-** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).-** Contact: http://www.qt-project.org/legal-**-** This file is part of Qt Creator.-**-** Commercial License Usage-** Licensees holding valid commercial Qt licenses may use this file in-** accordance with the commercial license agreement provided with the-** Software or, alternatively, in accordance with the terms contained in-** a written agreement between you and Digia. For licensing terms and-** conditions see https://www.qt.io/licensing. For further information-** use the contact form at https://www.qt.io/contact-us.-**-** GNU Lesser General Public License Usage-** Alternatively, this file may be used under the terms of the GNU Lesser-** General Public License version 2.1 or version 3 as published by the Free-** Software Foundation and appearing in the file LICENSE.LGPLv21 and-** LICENSE.LGPLv3 included in the packaging of this file. Please review the-** following information to ensure the GNU Lesser General Public License-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.-**-** In addition, as a special exception, Digia gives you certain additional-** rights. These rights are described in the Digia Qt LGPL Exception-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.-**-****************************************************************************/+// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).+// SPDX-License-Identifier: BSD-3-Clause-#include "qtlocalpeer.h"+#include "qtlocalpeer.h"#include <QCoreApplication>#include <QDataStream>+#include <QRegularExpression>#include <QTime>#if defined(Q_OS_WIN)@@ -40,47 +14,56 @@typedef BOOL(WINAPI*PProcessIdToSessionId)(DWORD,DWORD*);static PProcessIdToSessionId pProcessIdToSessionId = 0;#endif-#if defined(Q_OS_UNIX)+#include <sys/types.h>#include <time.h>#include <unistd.h>#endif+namespace QtLP_Private {+#include "qtlockedfile.cpp"+#if defined(Q_OS_WIN)+#include "qtlockedfile_win.cpp"+#else+#include "qtlockedfile_unix.cpp"+#endif+}+const char* QtLocalPeer::ack = "ack";-static const char ack[] = "ack";--QString QtLocalPeer::appSessionId(const QString &appId)+QtLocalPeer::QtLocalPeer(QObject* parent, const QString &appId)+ : QObject(parent), id(appId){- QByteArray idc = appId.toUtf8();+ QString prefix = id;+ if (id.isEmpty()) {+ id = QCoreApplication::applicationFilePath();+#if defined(Q_OS_WIN)+ id = id.toLower();+#endif+ prefix = id.section(QLatin1Char('/'), -1);+ }+ prefix.remove(QRegularExpression("[^a-zA-Z]"));+ prefix.truncate(6);++ QByteArray idc = id.toUtf8();quint16 idNum = qChecksum(idc.constData(), idc.size());- //### could do: two 16bit checksums over separate halves of id, for a 32bit result - improved uniqueness probability. Every-other-char split would be best.+ socketName = QLatin1String("qtsingleapp-") + prefix+ + QLatin1Char('-') + QString::number(idNum, 16);- QString res = QLatin1String("qtsingleapplication-")- + QString::number(idNum, 16);#if defined(Q_OS_WIN)if (!pProcessIdToSessionId) {- QLibrary lib(QLatin1String("kernel32"));+ QLibrary lib("kernel32");pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId");}if (pProcessIdToSessionId) {DWORD sessionId = 0;pProcessIdToSessionId(GetCurrentProcessId(), &sessionId);- res += QLatin1Char('-') + QString::number(sessionId, 16);+ socketName += QLatin1Char('-') + QString::number(sessionId, 16);}#else- res += QLatin1Char('-') + QString::number(::getuid(), 16);+ socketName += QLatin1Char('-') + QString::number(::getuid(), 16);#endif- return res;-}--QtLocalPeer::QtLocalPeer(QObject *parent, const QString &appId)- : QObject(parent), id(appId)-{- if (id.isEmpty())- id = QCoreApplication::applicationFilePath(); //### On win, check if this returns .../argv[0] without casefolding; .\MYAPP == .\myapp on Win- socketName = appSessionId(id);server = new QLocalServer(this);QString lockName = QDir(QDir::tempPath()).absolutePath()+ QLatin1Char('/') + socketName@@ -89,31 +72,39 @@ QtLocalPeer::QtLocalPeer(QObject *parent, const QString &appId)lockFile.open(QIODevice::ReadWrite);}++bool QtLocalPeer::isClient(){if (lockFile.isLocked())return false;- if (!lockFile.lock(QtLockedFile::WriteLock, false))+ if (!lockFile.lock(QtLP_Private::QtLockedFile::WriteLock, false))return true;- if (!QLocalServer::removeServer(socketName))- qWarning("QtSingleCoreApplication: could not cleanup socket");bool res = server->listen(socketName);+#if defined(Q_OS_UNIX) && (QT_VERSION >= QT_VERSION_CHECK(4,5,0))+ // ### Workaround+ if (!res && server->serverError() == QAbstractSocket::AddressInUseError) {+ QFile::remove(QDir::cleanPath(QDir::tempPath())+QLatin1Char('/')+socketName);+ res = server->listen(socketName);+ }+#endifif (!res)qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString()));QObject::connect(server, SIGNAL(newConnection()), SLOT(receiveConnection()));return false;}-bool QtLocalPeer::sendMessage(const QByteArray &message, int timeout, bool block)++bool QtLocalPeer::sendMessage(const QString &message, int timeout){if (!isClient())return false;QLocalSocket socket;bool connOk = false;- for (int i = 0; i < 2; i++) {+ for(int i = 0; i < 2; i++) {// Try twice, in case the other instance is just starting upsocket.connectToServer(socketName);connOk = socket.waitForConnected(timeout/2);@@ -124,35 +115,42 @@ bool QtLocalPeer::sendMessage(const QByteArray &message, int timeout, bool blockSleep(DWORD(ms));#elsestruct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };- nanosleep(&ts, 0);+ nanosleep(&ts, NULL);#endif}if (!connOk)return false;- QByteArray uMsg(message);+ QByteArray uMsg(message.toUtf8());QDataStream ds(&socket);ds.writeBytes(uMsg.constData(), uMsg.size());bool res = socket.waitForBytesWritten(timeout);- res &= socket.waitForReadyRead(timeout); // wait for ack- res &= (socket.read(qstrlen(ack)) == ack);- if (block) // block until peer disconnects- socket.waitForDisconnected(-1);+ if (res) {+ res &= socket.waitForReadyRead(timeout); // wait for ack+ if (res)+ res &= (socket.read(qstrlen(ack)) == ack);+ }return res;}+void QtLocalPeer::receiveConnection(){QLocalSocket* socket = server->nextPendingConnection();if (!socket)return;- // Why doesn't Qt have a blocking stream that takes care of this shait???- while (socket->bytesAvailable() < static_cast<int>(sizeof(quint32))) {- if (!socket->isValid()) // stale request+ while (true) {+ if (socket->state() == QLocalSocket::UnconnectedState) {+ qWarning("QtLocalPeer: Peer disconnected");+ delete socket;return;- socket->waitForReadyRead(1000);+ }+ if (socket->bytesAvailable() >= qint64(sizeof(quint32)))+ break;+ socket->waitForReadyRead();}+QDataStream ds(socket);QByteArray uMsg;quint32 remaining;@@ -160,21 +158,20 @@ void QtLocalPeer::receiveConnection()uMsg.resize(remaining);int got = 0;char* uMsgBuf = uMsg.data();- //dbgKrita << "RCV: remaining" << remaining;do {got = ds.readRawData(uMsgBuf, remaining);remaining -= got;uMsgBuf += got;- //qDebug() << "RCV: got" << got << "remaining" << remaining;} while (remaining && got >= 0 && socket->waitForReadyRead(2000));- //### error check: got<0if (got < 0) {- qWarning() << "QtLocalPeer: Message reception failed" << socket->errorString();+ qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData());delete socket;return;}- // ### async this+ QString message(QString::fromUtf8(uMsg));socket->write(ack, qstrlen(ack));socket->waitForBytesWritten(1000);- Q_EMIT messageReceived(uMsg, socket); // ##(might take a long time to return)+ socket->waitForDisconnected(1000); // make sure client reads ack+ delete socket;+ emit messageReceived(message); //### (might take a long time to return)}diff --git a/libs/ui/qtsingleapplication/qtlocalpeer.h b/libs/ui/qtsingleapplication/qtlocalpeer.hindex d103781c96..5e6db56c85 100644--- a/libs/ui/qtsingleapplication/qtlocalpeer.h+++ b/libs/ui/qtsingleapplication/qtlocalpeer.h@@ -1,55 +1,28 @@-/****************************************************************************-**-** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).-** Contact: http://www.qt-project.org/legal-**-** This file is part of Qt Creator.-**-** Commercial License Usage-** Licensees holding valid commercial Qt licenses may use this file in-** accordance with the commercial license agreement provided with the-** Software or, alternatively, in accordance with the terms contained in-** a written agreement between you and Digia. For licensing terms and-** conditions see https://www.qt.io/licensing. For further information-** use the contact form at https://www.qt.io/contact-us.-**-** GNU Lesser General Public License Usage-** Alternatively, this file may be used under the terms of the GNU Lesser-** General Public License version 2.1 or version 3 as published by the Free-** Software Foundation and appearing in the file LICENSE.LGPLv21 and-** LICENSE.LGPLv3 included in the packaging of this file. Please review the-** following information to ensure the GNU Lesser General Public License-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.-**-** In addition, as a special exception, Digia gives you certain additional-** rights. These rights are described in the Digia Qt LGPL Exception-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.-**-****************************************************************************/--#include <qtlockedfile.h>+// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).+// SPDX-License-Identifier: BSD-3-Clause++#ifndef QTLOCALPEER_H+#define QTLOCALPEER_H#include <QLocalServer>#include <QLocalSocket>#include <QDir>-+#include "qtlockedfile.h"class QtLocalPeer : public QObject{Q_OBJECTpublic:- explicit QtLocalPeer(QObject *parent = 0, const QString &appId = QString());+ QtLocalPeer(QObject *parent = 0, const QString &appId = QString());bool isClient();- bool sendMessage(const QByteArray &message, int timeout, bool block);+ bool sendMessage(const QString &message, int timeout);QString applicationId() const{ return id; }- static QString appSessionId(const QString &appId);Q_SIGNALS:- void messageReceived(const QByteArray &message, QObject *socket);+ void messageReceived(const QString &message);protected Q_SLOTS:void receiveConnection();@@ -58,5 +31,10 @@ protected:QString id;QString socketName;QLocalServer* server;- QtLockedFile lockFile;+ QtLP_Private::QtLockedFile lockFile;++private:+ static const char* ack;};++#endif // QTLOCALPEER_Hdiff --git a/libs/ui/qtsingleapplication/qtlockedfile.cpp b/libs/ui/qtsingleapplication/qtlockedfile.cppnew file mode 100644index 0000000000..78f20bc26a--- /dev/null+++ b/libs/ui/qtsingleapplication/qtlockedfile.cpp@@ -0,0 +1,156 @@+// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).+// SPDX-License-Identifier: BSD-3-Clause++#include "qtlockedfile.h"++/*!+ \class QtLockedFile++ \brief The QtLockedFile class extends QFile with advisory locking+ functions.++ A file may be locked in read or write mode. Multiple instances of+ \e QtLockedFile, created in multiple processes running on the same+ machine, may have a file locked in read mode. Exactly one instance+ may have it locked in write mode. A read and a write lock cannot+ exist simultaneously on the same file.++ The file locks are advisory. This means that nothing prevents+ another process from manipulating a locked file using QFile or+ file system functions offered by the OS. Serialization is only+ guaranteed if all processes that access the file use+ QLockedFile. Also, while holding a lock on a file, a process+ must not open the same file again (through any API), or locks+ can be unexpectedly lost.++ The lock provided by an instance of \e QtLockedFile is released+ whenever the program terminates. This is true even when the+ program crashes and no destructors are called.+*/++/*! \enum QtLockedFile::LockMode++ This enum describes the available lock modes.++ \value ReadLock A read lock.+ \value WriteLock A write lock.+ \value NoLock Neither a read lock nor a write lock.+*/++/*!+ Constructs an unlocked \e QtLockedFile object. This constructor+ behaves in the same way as \e QFile::QFile().++ \sa QFile::QFile()+*/+QtLockedFile::QtLockedFile()+ : QFile()+{+#ifdef Q_OS_WIN+ wmutex = 0;+ rmutex = 0;+#endif+ m_lock_mode = NoLock;+}++/*!+ Constructs an unlocked QtLockedFile object with file \a name. This+ constructor behaves in the same way as \e QFile::QFile(const+ QString&).++ \sa QFile::QFile()+*/+QtLockedFile::QtLockedFile(const QString &name)+ : QFile(name)+{+#ifdef Q_OS_WIN+ wmutex = 0;+ rmutex = 0;+#endif+ m_lock_mode = NoLock;+}++/*!+ Opens the file in OpenMode \a mode.++ This is identical to QFile::open(), with the one exception that the+ Truncate mode flag is disallowed. Truncation would conflict with the+ advisory file locking, since the file would be modified before the+ write lock is obtained. If truncation is required, use resize(0)+ after obtaining the write lock.++ Returns true if successful; otherwise false.++ \sa QFile::open(), QFile::resize()+*/+bool QtLockedFile::open(OpenMode mode)+{+ if (mode & QIODevice::Truncate) {+ qWarning("QtLockedFile::open(): Truncate mode not allowed.");+ return false;+ }+ return QFile::open(mode);+}++/*!+ Returns \e true if this object has a in read or write lock;+ otherwise returns \e false.++ \sa lockMode()+*/+bool QtLockedFile::isLocked() const+{+ return m_lock_mode != NoLock;+}++/*!+ Returns the type of lock currently held by this object, or \e+ QtLockedFile::NoLock.++ \sa isLocked()+*/+QtLockedFile::LockMode QtLockedFile::lockMode() const+{+ return m_lock_mode;+}++/*!+ \fn bool QtLockedFile::lock(LockMode mode, bool block = true)++ Obtains a lock of type \a mode. The file must be opened before it+ can be locked.++ If \a block is true, this function will block until the lock is+ aquired. If \a block is false, this function returns \e false+ immediately if the lock cannot be aquired.++ If this object already has a lock of type \a mode, this function+ returns \e true immediately. If this object has a lock of a+ different type than \a mode, the lock is first released and then a+ new lock is obtained.++ This function returns \e true if, after it executes, the file is+ locked by this object, and \e false otherwise.++ \sa unlock(), isLocked(), lockMode()+*/++/*!+ \fn bool QtLockedFile::unlock()++ Releases a lock.++ If the object has no lock, this function returns immediately.++ This function returns \e true if, after it executes, the file is+ not locked by this object, and \e false otherwise.++ \sa lock(), isLocked(), lockMode()+*/++/*!+ \fn QtLockedFile::~QtLockedFile()++ Destroys the \e QtLockedFile object. If any locks were held, they+ are released.+*/diff --git a/libs/ui/qtsingleapplication/qtlockedfile.h b/libs/ui/qtsingleapplication/qtlockedfile.hnew file mode 100644index 0000000000..71c780fa56--- /dev/null+++ b/libs/ui/qtsingleapplication/qtlockedfile.h@@ -0,0 +1,44 @@+// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).+// SPDX-License-Identifier: BSD-3-Clause++#ifndef QTLOCKEDFILE_H+#define QTLOCKEDFILE_H++#include <QFile>+#ifdef Q_OS_WIN+#include <QVector>+#endif++namespace QtLP_Private {++class QtLockedFile : public QFile+{+public:+ enum LockMode { NoLock = 0, ReadLock, WriteLock };++ QtLockedFile();+ QtLockedFile(const QString &name);+ ~QtLockedFile();++ bool open(OpenMode mode);++ bool lock(LockMode mode, bool block = true);+ bool unlock();+ bool isLocked() const;+ LockMode lockMode() const;++private:+#ifdef Q_OS_WIN+ Qt::HANDLE wmutex;+ Qt::HANDLE rmutex;+ QVector<Qt::HANDLE> rmutexes;+ QString mutexname;++ Qt::HANDLE getMutexHandle(int idx, bool doCreate);+ bool waitMutex(Qt::HANDLE mutex, bool doBlock);++#endif+ LockMode m_lock_mode;+};+}+#endifdiff --git a/libs/ui/qtsingleapplication/qtlockedfile_unix.cpp b/libs/ui/qtsingleapplication/qtlockedfile_unix.cppnew file mode 100644index 0000000000..8385d8b8b2--- /dev/null+++ b/libs/ui/qtsingleapplication/qtlockedfile_unix.cpp@@ -0,0 +1,78 @@+// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).+// SPDX-License-Identifier: BSD-3-Clause++#include <string.h>+#include <errno.h>+#include <unistd.h>+#include <fcntl.h>++#include "qtlockedfile.h"++bool QtLockedFile::lock(LockMode mode, bool block)+{+ if (!isOpen()) {+ qWarning("QtLockedFile::lock(): file is not opened");+ return false;+ }++ if (mode == NoLock)+ return unlock();++ if (mode == m_lock_mode)+ return true;++ if (m_lock_mode != NoLock)+ unlock();++ struct flock fl;+ fl.l_whence = SEEK_SET;+ fl.l_start = 0;+ fl.l_len = 0;+ fl.l_type = (mode == ReadLock) ? F_RDLCK : F_WRLCK;+ int cmd = block ? F_SETLKW : F_SETLK;+ int ret = fcntl(handle(), cmd, &fl);++ if (ret == -1) {+ if (errno != EINTR && errno != EAGAIN)+ qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno));+ return false;+ }+++ m_lock_mode = mode;+ return true;+}+++bool QtLockedFile::unlock()+{+ if (!isOpen()) {+ qWarning("QtLockedFile::unlock(): file is not opened");+ return false;+ }++ if (!isLocked())+ return true;++ struct flock fl;+ fl.l_whence = SEEK_SET;+ fl.l_start = 0;+ fl.l_len = 0;+ fl.l_type = F_UNLCK;+ int ret = fcntl(handle(), F_SETLKW, &fl);++ if (ret == -1) {+ qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno));+ return false;+ }++ m_lock_mode = NoLock;+ return true;+}++QtLockedFile::~QtLockedFile()+{+ if (isOpen())+ unlock();+}+diff --git a/libs/ui/qtsingleapplication/qtlockedfile_win.cpp b/libs/ui/qtsingleapplication/qtlockedfile_win.cppnew file mode 100644index 0000000000..28cf07259b--- /dev/null+++ b/libs/ui/qtsingleapplication/qtlockedfile_win.cpp@@ -0,0 +1,174 @@+// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).+// SPDX-License-Identifier: BSD-3-Clause++#include "qtlockedfile.h"+#include <qt_windows.h>+#include <QFileInfo>++#define MUTEX_PREFIX "QtLockedFile mutex "+// Maximum number of concurrent read locks. Must not be greater than MAXIMUM_WAIT_OBJECTS+#define MAX_READERS MAXIMUM_WAIT_OBJECTS++#if QT_VERSION >= 0x050000+#define QT_WA(unicode, ansi) unicode+#endif++Qt::HANDLE QtLockedFile::getMutexHandle(int idx, bool doCreate)+{+ if (mutexname.isEmpty()) {+ QFileInfo fi(*this);+ mutexname = QString::fromLatin1(MUTEX_PREFIX)+ + fi.absoluteFilePath().toLower();+ }+ QString mname(mutexname);+ if (idx >= 0)+ mname += QString::number(idx);++ Qt::HANDLE mutex;+ if (doCreate) {+ QT_WA( { mutex = CreateMutexW(NULL, FALSE, (TCHAR*)mname.utf16()); },+ { mutex = CreateMutexA(NULL, FALSE, mname.toLocal8Bit().constData()); } );+ if (!mutex) {+ qErrnoWarning("QtLockedFile::lock(): CreateMutex failed");+ return 0;+ }+ }+ else {+ QT_WA( { mutex = OpenMutexW(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, (TCHAR*)mname.utf16()); },+ { mutex = OpenMutexA(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, mname.toLocal8Bit().constData()); } );+ if (!mutex) {+ if (GetLastError() != ERROR_FILE_NOT_FOUND)+ qErrnoWarning("QtLockedFile::lock(): OpenMutex failed");+ return 0;+ }+ }+ return mutex;+}++bool QtLockedFile::waitMutex(Qt::HANDLE mutex, bool doBlock)+{+ Q_ASSERT(mutex);+ DWORD res = WaitForSingleObject(mutex, doBlock ? INFINITE : 0);+ switch (res) {+ case WAIT_OBJECT_0:+ case WAIT_ABANDONED:+ return true;+ break;+ case WAIT_TIMEOUT:+ break;+ default:+ qErrnoWarning("QtLockedFile::lock(): WaitForSingleObject failed");+ }+ return false;+}++++bool QtLockedFile::lock(LockMode mode, bool block)+{+ if (!isOpen()) {+ qWarning("QtLockedFile::lock(): file is not opened");+ return false;+ }++ if (mode == NoLock)+ return unlock();++ if (mode == m_lock_mode)+ return true;++ if (m_lock_mode != NoLock)+ unlock();++ if (!wmutex && !(wmutex = getMutexHandle(-1, true)))+ return false;++ if (!waitMutex(wmutex, block))+ return false;++ if (mode == ReadLock) {+ int idx = 0;+ for (; idx < MAX_READERS; idx++) {+ rmutex = getMutexHandle(idx, false);+ if (!rmutex || waitMutex(rmutex, false))+ break;+ CloseHandle(rmutex);+ }+ bool ok = true;+ if (idx >= MAX_READERS) {+ qWarning("QtLockedFile::lock(): too many readers");+ rmutex = 0;+ ok = false;+ }+ else if (!rmutex) {+ rmutex = getMutexHandle(idx, true);+ if (!rmutex || !waitMutex(rmutex, false))+ ok = false;+ }+ if (!ok && rmutex) {+ CloseHandle(rmutex);+ rmutex = 0;+ }+ ReleaseMutex(wmutex);+ if (!ok)+ return false;+ }+ else {+ Q_ASSERT(rmutexes.isEmpty());+ for (int i = 0; i < MAX_READERS; i++) {+ Qt::HANDLE mutex = getMutexHandle(i, false);+ if (mutex)+ rmutexes.append(mutex);+ }+ if (rmutexes.size()) {+ DWORD res = WaitForMultipleObjects(rmutexes.size(), rmutexes.constData(),+ TRUE, block ? INFINITE : 0);+ if (res != WAIT_OBJECT_0 && res != WAIT_ABANDONED) {+ if (res != WAIT_TIMEOUT)+ qErrnoWarning("QtLockedFile::lock(): WaitForMultipleObjects failed");+ m_lock_mode = WriteLock; // trick unlock() to clean up - semiyucky+ unlock();+ return false;+ }+ }+ }++ m_lock_mode = mode;+ return true;+}++bool QtLockedFile::unlock()+{+ if (!isOpen()) {+ qWarning("QtLockedFile::unlock(): file is not opened");+ return false;+ }++ if (!isLocked())+ return true;++ if (m_lock_mode == ReadLock) {+ ReleaseMutex(rmutex);+ CloseHandle(rmutex);+ rmutex = 0;+ }+ else {+ foreach(Qt::HANDLE mutex, rmutexes) {+ ReleaseMutex(mutex);+ CloseHandle(mutex);+ }+ rmutexes.clear();+ ReleaseMutex(wmutex);+ }++ m_lock_mode = QtLockedFile::NoLock;+ return true;+}++QtLockedFile::~QtLockedFile()+{+ if (isOpen())+ unlock();+ if (wmutex)+ CloseHandle(wmutex);+}diff --git a/libs/ui/qtsingleapplication/qtsingleapplication.cpp b/libs/ui/qtsingleapplication/qtsingleapplication.cppindex 60e0418e0b..a6f4516809 100644--- a/libs/ui/qtsingleapplication/qtsingleapplication.cpp+++ b/libs/ui/qtsingleapplication/qtsingleapplication.cpp@@ -1,187 +1,288 @@-/****************************************************************************-**-** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).-** Contact: http://www.qt-project.org/legal-**-** This file is part of Qt Creator.-**-** Commercial License Usage-** Licensees holding valid commercial Qt licenses may use this file in-** accordance with the commercial license agreement provided with the-** Software or, alternatively, in accordance with the terms contained in-** a written agreement between you and Digia. For licensing terms and-** conditions see https://www.qt.io/licensing. For further information-** use the contact form at https://www.qt.io/contact-us.-**-** GNU Lesser General Public License Usage-** Alternatively, this file may be used under the terms of the GNU Lesser-** General Public License version 2.1 or version 3 as published by the Free-** Software Foundation and appearing in the file LICENSE.LGPLv21 and-** LICENSE.LGPLv3 included in the packaging of this file. Please review the-** following information to ensure the GNU Lesser General Public License-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.-**-** In addition, as a special exception, Digia gives you certain additional-** rights. These rights are described in the Digia Qt LGPL Exception-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.-**-****************************************************************************/+// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).+// SPDX-License-Identifier: BSD-3-Clause+#include "qtsingleapplication.h"#include "qtlocalpeer.h"+#include <QWidget>-#include <qtlockedfile.h>-#include <QDir>-#include <QFileOpenEvent>-#include <QSharedMemory>-#include <QWidget>+/*!+ \class QtSingleApplication qtsingleapplication.h+ \brief The QtSingleApplication class provides an API to detect and+ communicate with running instances of an application.-static const int instancesSize = 1024;+ This class allows you to create applications where only one+ instance should be running at a time. I.e., if the user tries to+ launch another instance, the already running instance will be+ activated instead. Another usecase is a client-server system,+ where the first started instance will assume the role of server,+ and the later instances will act as clients of that server.-static QString instancesLockFilename(const QString &appSessionId)-{- const QChar slash(QLatin1Char('/'));- QString res = QDir::tempPath();- if (!res.endsWith(slash))- res += slash;- return res + appSessionId + QLatin1String("-instances");-}+ By default, the full path of the executable file is used to+ determine whether two processes are instances of the same+ application. You can also provide an explicit identifier string+ that will be compared instead.-QtSingleApplication::QtSingleApplication(const QString &appId, int &argc, char **argv)- : QApplication(argc, argv),- firstPeer(-1),- pidPeer(0)-{- this->appId = appId;+ The application should create the QtSingleApplication object early+ in the startup phase, and call isRunning() to find out if another+ instance of this application is already running. If isRunning()+ returns false, it means that no other instance is running, and+ this instance has assumed the role as the running instance. In+ this case, the application should continue with the initialization+ of the application user interface before entering the event loop+ with exec(), as normal.- const QString appSessionId = QtLocalPeer::appSessionId(appId);+ The messageReceived() signal will be emitted when the running+ application receives messages from another instance of the same+ application. When a message is received it might be helpful to the+ user to raise the application so that it becomes visible. To+ facilitate this, QtSingleApplication provides the+ setActivationWindow() function and the activateWindow() slot.- // This shared memory holds a zero-terminated array of active (or crashed) instances- instances = new QSharedMemory(appSessionId, this);- actWin = 0;- block = false;-- // First instance creates the shared memory, later instances attach to it- const bool created = instances->create(instancesSize);- if (!created) {- if (!instances->attach()) {- qWarning() << "Failed to initialize instances shared memory: "- << instances->errorString();- delete instances;- instances = 0;- return;- }+ If isRunning() returns true, another instance is already+ running. It may be alerted to the fact that another instance has+ started by using the sendMessage() function. Also data such as+ startup parameters (e.g. the name of the file the user wanted this+ new instance to open) can be passed to the running instance with+ this function. Then, the application should terminate (or enter+ client mode).++ If isRunning() returns true, but sendMessage() fails, that is an+ indication that the running instance is frozen.++ Here's an example that shows how to convert an existing+ application to use QtSingleApplication. It is very simple and does+ not make use of all QtSingleApplication's functionality (see the+ examples for that).++ \code+ // Original+ int main(int argc, char **argv)+ {+ QApplication app(argc, argv);++ MyMainWidget mmw;+ mmw.show();+ return app.exec();}- // QtLockedFile is used to workaround QTBUG-10364- QtLockedFile lockfile(instancesLockFilename(appSessionId));-- lockfile.open(QtLockedFile::ReadWrite);- lockfile.lock(QtLockedFile::WriteLock);- qint64 *pids = static_cast<qint64 *>(instances->data());- if (!created) {- // Find the first instance that it still running- // The whole list needs to be iterated in order to append to it- for (; *pids; ++pids) {- if (firstPeer == -1 && isRunning(*pids))- firstPeer = *pids;- }+ // Single instance+ int main(int argc, char **argv)+ {+ QtSingleApplication app(argc, argv);++ if (app.isRunning())+ return !app.sendMessage(someDataString);++ MyMainWidget mmw;+ app.setActivationWindow(&mmw);+ mmw.show();+ return app.exec();}- // Add current pid to list and terminate it- *pids++ = QCoreApplication::applicationPid();- *pids = 0;- pidPeer = new QtLocalPeer(this, appId + QLatin1Char('-') +- QString::number(QCoreApplication::applicationPid()));- connect(pidPeer, SIGNAL(messageReceived(QByteArray,QObject*)), SIGNAL(messageReceived(QByteArray,QObject*)));- pidPeer->isClient();- lockfile.unlock();+ \endcode++ Once this QtSingleApplication instance is destroyed (normally when+ the process exits or crashes), when the user next attempts to run the+ application this instance will not, of course, be encountered. The+ next instance to call isRunning() or sendMessage() will assume the+ role as the new running instance.++ For console (non-GUI) applications, QtSingleCoreApplication may be+ used instead of this class, to avoid the dependency on the QtGui+ library.++ \sa QtSingleCoreApplication+*/+++void QtSingleApplication::sysInit(const QString &appId)+{+ actWin = 0;+ peer = new QtLocalPeer(this, appId);+ connect(peer, SIGNAL(messageReceived(const QString&)), SIGNAL(messageReceived(const QString&)));}-QtSingleApplication::~QtSingleApplication()++/*!+ Creates a QtSingleApplication object. The application identifier+ will be QCoreApplication::applicationFilePath(). \a argc, \a+ argv, and \a GUIenabled are passed on to the QAppliation constructor.++ If you are creating a console application (i.e. setting \a+ GUIenabled to false), you may consider using+ QtSingleCoreApplication instead.+*/++QtSingleApplication::QtSingleApplication(int &argc, char **argv, bool GUIenabled)+ : QApplication(argc, argv, GUIenabled){- if (!instances)- return;- const qint64 appPid = QCoreApplication::applicationPid();- QtLockedFile lockfile(instancesLockFilename(QtLocalPeer::appSessionId(appId)));- lockfile.open(QtLockedFile::ReadWrite);- lockfile.lock(QtLockedFile::WriteLock);- // Rewrite array, removing current pid and previously crashed ones- qint64 *pids = static_cast<qint64 *>(instances->data());- qint64 *newpids = pids;- for (; *pids; ++pids) {- if (*pids != appPid && isRunning(*pids))- *newpids++ = *pids;- }- *newpids = 0;- lockfile.unlock();+ sysInit();}-bool QtSingleApplication::event(QEvent *event)++/*!+ Creates a QtSingleApplication object with the application+ identifier \a appId. \a argc and \a argv are passed on to the+ QAppliation constructor.+*/++QtSingleApplication::QtSingleApplication(const QString &appId, int &argc, char **argv)+ : QApplication(argc, argv){- if (event->type() == QEvent::FileOpen) {- QFileOpenEvent *foe = static_cast<QFileOpenEvent*>(event);- Q_EMIT fileOpenRequest(foe->file());- return true;- }- return QApplication::event(event);+ sysInit(appId);}-bool QtSingleApplication::isRunning(qint64 pid)+#if QT_VERSION < 0x050000++/*!+ Creates a QtSingleApplication object. The application identifier+ will be QCoreApplication::applicationFilePath(). \a argc, \a+ argv, and \a type are passed on to the QAppliation constructor.+*/+QtSingleApplication::QtSingleApplication(int &argc, char **argv, Type type)+ : QApplication(argc, argv, type){- if (pid == -1) {- pid = firstPeer;- if (pid == -1) {- return false;- }- }+ sysInit();+}- QtLocalPeer peer(this, appId + QLatin1Char('-') + QString::number(pid, 10));- return peer.isClient();+# if defined(Q_WS_X11)+/*!+ Special constructor for X11, ref. the documentation of+ QApplication's corresponding constructor. The application identifier+ will be QCoreApplication::applicationFilePath(). \a dpy, \a visual,+ and \a cmap are passed on to the QApplication constructor.+*/+QtSingleApplication::QtSingleApplication(Display* dpy, Qt::HANDLE visual, Qt::HANDLE cmap)+ : QApplication(dpy, visual, cmap)+{+ sysInit();}-bool QtSingleApplication::sendMessage(const QByteArray &message, int timeout, qint64 pid)+/*!+ Special constructor for X11, ref. the documentation of+ QApplication's corresponding constructor. The application identifier+ will be QCoreApplication::applicationFilePath(). \a dpy, \a argc, \a+ argv, \a visual, and \a cmap are passed on to the QApplication+ constructor.+*/+QtSingleApplication::QtSingleApplication(Display *dpy, int &argc, char **argv, Qt::HANDLE visual, Qt::HANDLE cmap)+ : QApplication(dpy, argc, argv, visual, cmap){- if (pid == -1) {- pid = firstPeer;- if (pid == -1)- return false;- }+ sysInit();+}- QtLocalPeer peer(this, appId + QLatin1Char('-') + QString::number(pid, 10));- return peer.sendMessage(message, timeout, block);+/*!+ Special constructor for X11, ref. the documentation of+ QApplication's corresponding constructor. The application identifier+ will be \a appId. \a dpy, \a argc, \a+ argv, \a visual, and \a cmap are passed on to the QApplication+ constructor.+*/+QtSingleApplication::QtSingleApplication(Display* dpy, const QString &appId, int argc, char **argv, Qt::HANDLE visual, Qt::HANDLE cmap)+ : QApplication(dpy, argc, argv, visual, cmap)+{+ sysInit(appId);}+# endif // Q_WS_X11+#endif // QT_VERSION < 0x050000+++/*!+ Returns true if another instance of this application is running;+ otherwise false.++ This function does not find instances of this application that are+ being run by a different user (on Windows: that are running in+ another session).-QString QtSingleApplication::applicationId() const+ \sa sendMessage()+*/++bool QtSingleApplication::isRunning(){- return appId;+ return peer->isClient();}-void QtSingleApplication::setBlock(bool value)++/*!+ Tries to send the text \a message to the currently running+ instance. The QtSingleApplication object in the running instance+ will emit the messageReceived() signal when it receives the+ message.++ This function returns true if the message has been sent to, and+ processed by, the current instance. If there is no instance+ currently running, or if the running instance fails to process the+ message within \a timeout milliseconds, this function return false.++ \sa isRunning(), messageReceived()+*/+bool QtSingleApplication::sendMessage(const QString &message, int timeout){- block = value;+ return peer->sendMessage(message, timeout);}-void QtSingleApplication::setActivationWindow(QWidget *aw, bool activateOnMessage)++/*!+ Returns the application identifier. Two processes with the same+ identifier will be regarded as instances of the same application.+*/+QString QtSingleApplication::id() const+{+ return peer->applicationId();+}+++/*!+ Sets the activation window of this application to \a aw. The+ activation window is the widget that will be activated by+ activateWindow(). This is typically the application's main window.++ If \a activateOnMessage is true (the default), the window will be+ activated automatically every time a message is received, just prior+ to the messageReceived() signal being emitted.++ \sa activateWindow(), messageReceived()+*/++void QtSingleApplication::setActivationWindow(QWidget* aw, bool activateOnMessage){actWin = aw;- if (!pidPeer)- return;if (activateOnMessage)- connect(pidPeer, SIGNAL(messageReceived(QByteArray,QObject*)), this, SLOT(activateWindow()));+ connect(peer, SIGNAL(messageReceived(const QString&)), this, SLOT(activateWindow()));else- disconnect(pidPeer, SIGNAL(messageReceived(QByteArray,QObject*)), this, SLOT(activateWindow()));+ disconnect(peer, SIGNAL(messageReceived(const QString&)), this, SLOT(activateWindow()));}+/*!+ Returns the applications activation window if one has been set by+ calling setActivationWindow(), otherwise returns 0.++ \sa setActivationWindow()+*/QWidget* QtSingleApplication::activationWindow() const{return actWin;}+/*!+ De-minimizes, raises, and activates this application's activation window.+ This function does nothing if no activation window has been set.++ This is a convenience function to show the user that this+ application instance has been activated when he has tried to start+ another instance.++ This function should typically be called in response to the+ messageReceived() signal. By default, that will happen+ automatically, if an activation window has been set.++ \sa setActivationWindow(), messageReceived(), initialize()+*/void QtSingleApplication::activateWindow(){if (actWin) {@@ -190,3 +291,20 @@ void QtSingleApplication::activateWindow()actWin->activateWindow();}}+++/*!+ \fn void QtSingleApplication::messageReceived(const QString& message)++ This signal is emitted when the current instance receives a \a+ message from another instance of this application.++ \sa sendMessage(), setActivationWindow(), activateWindow()+*/+++/*!+ \fn void QtSingleApplication::initialize(bool dummy = true)++ \obsolete+*/diff --git a/libs/ui/qtsingleapplication/qtsingleapplication.h b/libs/ui/qtsingleapplication/qtsingleapplication.hindex 6fb39e15d0..c36aa28273 100644--- a/libs/ui/qtsingleapplication/qtsingleapplication.h+++ b/libs/ui/qtsingleapplication/qtsingleapplication.h@@ -1,79 +1,53 @@-/****************************************************************************-**-** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).-** Contact: http://www.qt-project.org/legal-**-** This file is part of Qt Creator.-**-** Commercial License Usage-** Licensees holding valid commercial Qt licenses may use this file in-** accordance with the commercial license agreement provided with the-** Software or, alternatively, in accordance with the terms contained in-** a written agreement between you and Digia. For licensing terms and-** conditions see https://www.qt.io/licensing. For further information-** use the contact form at https://www.qt.io/contact-us.-**-** GNU Lesser General Public License Usage-** Alternatively, this file may be used under the terms of the GNU Lesser-** General Public License version 2.1 or version 3 as published by the Free-** Software Foundation and appearing in the file LICENSE.LGPLv21 and-** LICENSE.LGPLv3 included in the packaging of this file. Please review the-** following information to ensure the GNU Lesser General Public License-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.-**-** In addition, as a special exception, Digia gives you certain additional-** rights. These rights are described in the Digia Qt LGPL Exception-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.-**-****************************************************************************/--#ifndef QTSINGLEAPPLICATION-#define QTSINGLEAPPLICATION+// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).+// SPDX-License-Identifier: BSD-3-Clause+#ifndef QTSINGLEAPPLICATION_H+#define QTSINGLEAPPLICATION_H+#include <kritaui_export.h>#include <QApplication>-QT_FORWARD_DECLARE_CLASS(QSharedMemory)-class QtLocalPeer;-#include <kritaui_export.h>-class KRITAUI_EXPORT QtSingleApplication : public QApplication{Q_OBJECTpublic:+ QtSingleApplication(int &argc, char **argv, bool GUIenabled = true);QtSingleApplication(const QString &id, int &argc, char **argv);- ~QtSingleApplication() override;-- bool isRunning(qint64 pid = -1);+#if QT_VERSION < 0x050000+ QtSingleApplication(int &argc, char **argv, Type type);+# if defined(Q_WS_X11)+ QtSingleApplication(Display* dpy, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0);+ QtSingleApplication(Display *dpy, int &argc, char **argv, Qt::HANDLE visual = 0, Qt::HANDLE cmap= 0);+ QtSingleApplication(Display* dpy, const QString &appId, int argc, char **argv, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0);+# endif // Q_WS_X11+#endif // QT_VERSION < 0x050000++ bool isRunning();+ QString id() const;void setActivationWindow(QWidget* aw, bool activateOnMessage = true);QWidget* activationWindow() const;- bool event(QEvent *event) override;- QString applicationId() const;- void setBlock(bool value);+ // Obsolete:+ void initialize(bool dummy = true)+ { isRunning(); Q_UNUSED(dummy) }public Q_SLOTS:- bool sendMessage(const QByteArray &message, int timeout = 5000, qint64 pid = -1);+ bool sendMessage(const QString &message, int timeout = 5000);void activateWindow();+Q_SIGNALS:- void messageReceived(const QByteArray &message, QObject *socket);- void fileOpenRequest(const QString &file);+ void messageReceived(const QString &message);-private:- QString instancesFileName(const QString &appId);- qint64 firstPeer;- QSharedMemory *instances;- QtLocalPeer *pidPeer;+private:+ void sysInit(const QString &appId = QString());+ QtLocalPeer *peer;QWidget *actWin;- QString appId;- bool block;};-#endif+#endif // QTSINGLEAPPLICATION_Hdiff --git a/libs/ui/qtsingleapplication/qtsingleapplication.pri b/libs/ui/qtsingleapplication/qtsingleapplication.prideleted file mode 100644index 5ddc4b2cc7..0000000000--- a/libs/ui/qtsingleapplication/qtsingleapplication.pri+++ /dev/null@@ -1,14 +0,0 @@-INCLUDEPATH += $$PWD-DEPENDPATH += $$PWD-HEADERS += $$PWD/qtsingleapplication.h $$PWD/qtlocalpeer.h-SOURCES += $$PWD/qtsingleapplication.cpp $$PWD/qtlocalpeer.cpp--QT *= network widgets--gotqtlockedfile = $$find(HEADERS, .*qtlockedfile.h)-isEmpty(gotqtlockedfile):include(../../qtlockedfile/src/qtlockedfile.pri)---win32:contains(TEMPLATE, lib):contains(CONFIG, shared) {- DEFINES += QT_QTSINGLEAPPLICATION_EXPORT=__declspec(dllexport)-}