From 11866c0fb81bfd110fc46df5ce6c172259f92aba Mon Sep 17 00:00:00 2001 From: zhangjiaping Date: Mon, 21 Jun 2021 11:12:33 +0800 Subject: [PATCH 1/7] Fix:#61509 Lan icon is not white. --- src/onelancform.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/onelancform.cpp b/src/onelancform.cpp index e9943e8a..5ce133be 100644 --- a/src/onelancform.cpp +++ b/src/onelancform.cpp @@ -289,12 +289,14 @@ void OneLancForm::setIcon(bool isOn) if (isOn) { if (!QIcon::fromTheme("network-wired-connected-symbolic").isNull()) { ui->lbIcon->setPixmap(QIcon::fromTheme("network-wired-connected-symbolic").pixmap(32,32)); + ui->lbIcon->setProperty("useIconHighlightEffect", 0x10); } else { ui->lbIcon->setPixmap(QIcon(":/res/l/network-online.png").pixmap(32,32)); } } else { if (!QIcon::fromTheme("network-wired-disconnected-symbolic").isNull()) { ui->lbIcon->setPixmap(QIcon::fromTheme("network-wired-disconnected-symbolic").pixmap(32,32)); + ui->lbIcon->setProperty("useIconHighlightEffect", 0x10); } else { ui->lbIcon->setPixmap(QIcon(":/res/l/network-offline.png").pixmap(32,32)); } From b7331e626b93a5fceeb88d28abe9416b7e56d3e4 Mon Sep 17 00:00:00 2001 From: zhangjiaping Date: Mon, 21 Jun 2021 17:49:28 +0800 Subject: [PATCH 2/7] Fix:#61924 Button should be pressed to show password. --- src/oneconnform.cpp | 21 +++++++++------ src/oneconnform.h | 4 +-- src/wificonfigdialog.cpp | 21 +++++++++------ src/wificonfigdialog.h | 4 +-- src/wpawifidialog.cpp | 38 +++++++++++++++++----------- wireless-security/dlghidewifiwpa.cpp | 21 +++++++++------ wireless-security/dlghidewifiwpa.h | 4 +-- 7 files changed, 67 insertions(+), 46 deletions(-) diff --git a/src/oneconnform.cpp b/src/oneconnform.cpp index a8b82acc..d5a730b1 100644 --- a/src/oneconnform.cpp +++ b/src/oneconnform.cpp @@ -990,17 +990,22 @@ void OneConnForm::setlbPwdTipVisble(const bool &visible) } //设置密码隐藏或可见 -void OneConnForm::on_checkBoxPwd_pressed() +void OneConnForm::on_checkBoxPwd_clicked() { - ui->checkBoxPwd->setChecked(true); - ui->lePassword->setEchoMode(QLineEdit::Normal); + if (ui->lePassword->echoMode() == QLineEdit::Password) { + ui->checkBoxPwd->setChecked(true); + ui->lePassword->setEchoMode(QLineEdit::Normal); + } else { + ui->checkBoxPwd->setChecked(false); + ui->lePassword->setEchoMode(QLineEdit::Password); + } } -void OneConnForm::on_checkBoxPwd_released() -{ - ui->checkBoxPwd->setChecked(false); - ui->lePassword->setEchoMode(QLineEdit::Password); -} +//void OneConnForm::on_checkBoxPwd_released() +//{ +// ui->checkBoxPwd->setChecked(false); +// ui->lePassword->setEchoMode(QLineEdit::Password); +//} void OneConnForm::on_lePassword_textEdited(const QString &arg1) { diff --git a/src/oneconnform.h b/src/oneconnform.h index 047b3c3d..91612123 100644 --- a/src/oneconnform.h +++ b/src/oneconnform.h @@ -137,9 +137,7 @@ private slots: void on_btnCancel_clicked(); - void on_checkBoxPwd_pressed(); - - void on_checkBoxPwd_released(); + void on_checkBoxPwd_clicked(); bool onMenuTriggered(QAction *); diff --git a/src/wificonfigdialog.cpp b/src/wificonfigdialog.cpp index a3b3d00b..23d2d24e 100644 --- a/src/wificonfigdialog.cpp +++ b/src/wificonfigdialog.cpp @@ -145,17 +145,22 @@ void WiFiConfigDialog::toConfigWifi() } //切换密码明文 -void WiFiConfigDialog::on_checkBoxPwd_pressed() +void WiFiConfigDialog::on_checkBoxPwd_clicked() { - ui->checkBoxPwd->setChecked(true); - ui->leWifiPassword->setEchoMode(QLineEdit::Normal); + if (ui->leWifiPassword->echoMode() == QLineEdit::Password) { + ui->checkBoxPwd->setChecked(true); + ui->leWifiPassword->setEchoMode(QLineEdit::Normal); + } else { + ui->checkBoxPwd->setChecked(false); + ui->leWifiPassword->setEchoMode(QLineEdit::Password); + } } -void WiFiConfigDialog::on_checkBoxPwd_released() -{ - ui->checkBoxPwd->setChecked(false); - ui->leWifiPassword ->setEchoMode(QLineEdit::Password); -} +//void WiFiConfigDialog::on_checkBoxPwd_released() +//{ +// ui->checkBoxPwd->setChecked(false); +// ui->leWifiPassword ->setEchoMode(QLineEdit::Password); +//} void WiFiConfigDialog::on_leWifiId_textEdited(const QString &arg1) { diff --git a/src/wificonfigdialog.h b/src/wificonfigdialog.h index 87275d2d..90588783 100644 --- a/src/wificonfigdialog.h +++ b/src/wificonfigdialog.h @@ -37,9 +37,9 @@ private slots: void on_leWifiPassword_textEdited(const QString &arg1); - void on_checkBoxPwd_pressed(); + void on_checkBoxPwd_clicked(); - void on_checkBoxPwd_released(); +// void on_checkBoxPwd_released(); private: Ui::WiFiConfigDialog *ui; diff --git a/src/wpawifidialog.cpp b/src/wpawifidialog.cpp index fa8aa909..66afd836 100644 --- a/src/wpawifidialog.cpp +++ b/src/wpawifidialog.cpp @@ -513,16 +513,22 @@ void WpaWifiDialog::initConnect() { //连接按钮 connect(connectBtn, &QPushButton::clicked, this, &WpaWifiDialog::slot_on_connectBtn_clicked); //显示密码 - connect(pwdShowBtn, &QCheckBox::pressed, this, [ = ]() { - pwdShowBtn->setChecked(true); - pwdEditor->setEchoMode(QLineEdit::Normal); - m_pwd4PrivateKeyPWDEditor->setEchoMode(QLineEdit::Normal); - }); - connect(pwdShowBtn, &QCheckBox::released, this, [ = ]() { - pwdShowBtn->setChecked(false); - pwdEditor->setEchoMode(QLineEdit::Password); - m_pwd4PrivateKeyPWDEditor->setEchoMode(QLineEdit::Password); + connect(pwdShowBtn, &QCheckBox::clicked, this, [ = ]() { + if (pwdEditor->echoMode() == QLineEdit::Password) { + pwdShowBtn->setChecked(true); + pwdEditor->setEchoMode(QLineEdit::Normal); + m_pwd4PrivateKeyPWDEditor->setEchoMode(QLineEdit::Normal); + } else { + pwdShowBtn->setChecked(false); + pwdEditor->setEchoMode(QLineEdit::Password); + m_pwd4PrivateKeyPWDEditor->setEchoMode(QLineEdit::Password); + } }); +// connect(pwdShowBtn, &QCheckBox::released, this, [ = ]() { +// pwdShowBtn->setChecked(false); +// pwdEditor->setEchoMode(QLineEdit::Password); +// m_pwd4PrivateKeyPWDEditor->setEchoMode(QLineEdit::Password); +// }); connect(pwdEditor, &QLineEdit::textChanged, this, &WpaWifiDialog::slot_line_edit_changed); connect(userEditor, &QLineEdit::textChanged, this, &WpaWifiDialog::slot_line_edit_changed); connect(nameEditor, &QLineEdit::textChanged, this, &WpaWifiDialog::slot_line_edit_changed); @@ -708,8 +714,8 @@ void WpaWifiDialog::activateConnection() { timeout->deleteLater(); QString cmdStr_2 = "nmcli connection down '" + nameEditor->text() + "'"; Utils::m_system(cmdStr_2.toUtf8().data()); - //this->mw->is_stop_check_net_state = 0; - //this->mw->setTrayLoading(false); + this->mw->is_stop_check_net_state = 0; + this->mw->setTrayLoading(false); qDebug() << "qDebug: activate time out in function activateConnection"; qDebug() << "qDebug: 连接超时(30秒超时时间)"; }); @@ -722,8 +728,8 @@ void WpaWifiDialog::activateConnection() { //连接错误或连接超时 setEditorEnable(true); emit conn_failed(); - //this->mw->is_stop_check_net_state = 0; - //this->mw->setTrayLoading(false); + this->mw->is_stop_check_net_state = 0; + this->mw->setTrayLoading(false); } else { //连接成功 timeout->stop(); @@ -732,13 +738,15 @@ void WpaWifiDialog::activateConnection() { upThread->wait(); upThread->deleteLater(); emit conn_done(); - //this->mw->is_stop_check_net_state = 0; - //this->mw->setTrayLoading(false); + this->mw->is_stop_check_net_state = 0; + this->mw->setTrayLoading(false); qDebug() << "qDebug: activated wpa security wifi successfully"; this->close(); } }); upThread->start(); + this->mw->is_stop_check_net_state = 1; + this->mw->setTrayLoading(true); } QStringList WpaWifiDialog::getWifiInfo(QString wifiName) { diff --git a/wireless-security/dlghidewifiwpa.cpp b/wireless-security/dlghidewifiwpa.cpp index a6927689..7fe86a2d 100644 --- a/wireless-security/dlghidewifiwpa.cpp +++ b/wireless-security/dlghidewifiwpa.cpp @@ -340,17 +340,22 @@ void DlgHideWifiWpa::on_btnConnect_clicked() //} //切换密码明文 -void DlgHideWifiWpa::on_checkBoxPwd_pressed() +void DlgHideWifiWpa::on_checkBoxPwd_clicked() { - ui->checkBoxPwd->setChecked(true); - ui->lePassword->setEchoMode(QLineEdit::Normal); + if (ui->lePassword->echoMode() == QLineEdit::Password) { + ui->checkBoxPwd->setChecked(true); + ui->lePassword->setEchoMode(QLineEdit::Normal); + } else { + ui->checkBoxPwd->setChecked(false); + ui->lePassword->setEchoMode(QLineEdit::Password); + } } -void DlgHideWifiWpa::on_checkBoxPwd_released() -{ - ui->checkBoxPwd->setChecked(false); - ui->lePassword->setEchoMode(QLineEdit::Password); -} +//void DlgHideWifiWpa::on_checkBoxPwd_released() +//{ +// ui->checkBoxPwd->setChecked(false); +// ui->lePassword->setEchoMode(QLineEdit::Password); +//} void DlgHideWifiWpa::on_leNetName_textEdited(const QString &arg1) { diff --git a/wireless-security/dlghidewifiwpa.h b/wireless-security/dlghidewifiwpa.h index 0e599fa2..28e83489 100644 --- a/wireless-security/dlghidewifiwpa.h +++ b/wireless-security/dlghidewifiwpa.h @@ -60,9 +60,9 @@ private slots: // void finishedProcess(int res); - void on_checkBoxPwd_pressed(); + void on_checkBoxPwd_clicked(); - void on_checkBoxPwd_released(); +// void on_checkBoxPwd_released(); signals: void reSetWifiList(); From a10cf938b885afaced06d09abc520eceac575a62 Mon Sep 17 00:00:00 2001 From: zhangjiaping Date: Mon, 21 Jun 2021 17:50:02 +0800 Subject: [PATCH 3/7] Fix: peap wifi will connect failed when just created. --- src/wpawifidialog.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/wpawifidialog.cpp b/src/wpawifidialog.cpp index 66afd836..0c479a6d 100644 --- a/src/wpawifidialog.cpp +++ b/src/wpawifidialog.cpp @@ -701,6 +701,10 @@ void WpaWifiDialog::setEditorEnable(bool is_checking) { } void WpaWifiDialog::activateConnection() { + if (this->mw->is_stop_check_net_state == 1) { +// conn_failed(); + return; + } UpConnThread * upThread = new UpConnThread(userEditor->text(), pwdEditor->text()); upThread->conn_name = nameEditor->text(); //超时计时器 From 40a5d40d6bc4fc091fa493dfb102cf9e468a24cd Mon Sep 17 00:00:00 2001 From: zhangjiaping Date: Tue, 22 Jun 2021 15:04:42 +0800 Subject: [PATCH 4/7] Fix:#58755 Wifi signal changed after connected. --- src/mainwindow.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 7a98e83c..075a1344 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1055,7 +1055,10 @@ void MainWindow::getActiveInfoAndSetTrayIcon() else { setTrayLoading(true); } - + if (actWifiName != "--" && activeWifiSignalLv != 0) { + setTrayIconOfWifi(activeWifiSignalLv); + emit this->actWifiSignalLvChanaged(activeWifiSignalLv); + } } else if (actWifiName != "--" && activeWifiSignalLv != 0) { setTrayIconOfWifi(activeWifiSignalLv); emit this->actWifiSignalLvChanaged(activeWifiSignalLv); @@ -2833,10 +2836,10 @@ void MainWindow::loadWifiListDone(QStringList slist) //ccf->setRate(wrate); int signal; - if (wsignal.toInt() != 0) + if (wsignal.toInt() == 0) signal = ccf->getSignal(); else - signal = wsignal.toInt() + 11; + signal = wsignal.toInt(); ccf->setSignal(QString::number(signal), wsecu, wcate); setTrayIconOfWifi(wsignal.toInt()); activeWifiSignalLv = wsignal.toInt(); From 3d98f8748f034b68c45ffa83706bba626e915946 Mon Sep 17 00:00:00 2001 From: zhangjiaping Date: Tue, 22 Jun 2021 16:03:37 +0800 Subject: [PATCH 5/7] Update changelog. --- debian/changelog | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/debian/changelog b/debian/changelog index 4026f893..1a1ac688 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,11 @@ +kylin-nm (3.0.1-1kylin52) v101; urgency=medium + + * BUG号:#58755 #61924 #61509 #61783 + * 需求号:无 + * 其他改动:无 + + -- zhangjiaping Tue, 22 Jun 2021 15:17:42 +0800 + kylin-nm (3.0.1-1kylin51) v101; urgency=medium * BUG号:无 From 6c2e40b94dc4221b69241df336a24f6a832612fc Mon Sep 17 00:00:00 2001 From: chenlelin Date: Tue, 22 Jun 2021 21:09:47 +0800 Subject: [PATCH 6/7] =?UTF-8?q?Fix=20bug-61628=20wifi=E8=BE=93=E5=85=A5?= =?UTF-8?q?=E9=94=99=E8=AF=AF=E5=AF=86=E7=A0=81=E8=BF=9E=E6=8E=A5=E5=A4=B1?= =?UTF-8?q?=E8=B4=A5=E5=90=8E=EF=BC=8C=E5=88=A0=E9=99=A4=E5=AF=86=E7=A0=81?= =?UTF-8?q?=E9=87=8D=E6=96=B0=E8=BE=93=E5=85=A5=E5=90=8E=E7=82=B9=E5=87=BB?= =?UTF-8?q?=E8=BF=9E=E6=8E=A5=E6=97=A0=E5=8F=8D=E5=BA=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main.cpp | 2 +- src/mainwindow.cpp | 7 ++++++- src/oneconnform.cpp | 1 + src/onelancform.cpp | 1 + 4 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 8759f993..c53cb619 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -81,7 +81,7 @@ int main(int argc, char *argv[]) QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); QApplication a(argc, argv); - qInstallMessageHandler(messageOutput); + //qInstallMessageHandler(messageOutput); qDebug()<<"Kylin Network Manager Is Already Launched"; diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 7a98e83c..653ae685 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -2106,8 +2106,12 @@ void MainWindow::getConnListDone(QStringList slist) if (! is_stop_check_net_state) { this->is_stop_check_net_state = 1; BackThread *bt = new BackThread(); +// connect(bt, SIGNAL(connDone(int)), this, SLOT(connWifiDone(int))); + connect(bt, &BackThread::connDone, this, [ = ](int res) { + connWifiDone(res); + bt->deleteLater(); + }); bt->execConnWifi(lastAddedConn, objKyDBus->dbusWiFiCardName); - connect(bt, SIGNAL(connDone(int)), this, SLOT(connWifiDone(int))); } } oldConnSlist.clear(); @@ -3966,6 +3970,7 @@ void MainWindow::onExternalWifiChange() // //objKyDBus->showDesktopNotify(txt); // } if (m_connected_by_self) { + is_stop_check_net_state = 0; m_connected_by_self = false; return; } diff --git a/src/oneconnform.cpp b/src/oneconnform.cpp index a8b82acc..07f0508d 100644 --- a/src/oneconnform.cpp +++ b/src/oneconnform.cpp @@ -896,6 +896,7 @@ void OneConnForm::on_btnConnPWD_clicked() passwdFile->close(); // cmdStr = "nmcli connection up " + wifiName + " passwd-file " + homePath +"/.config/" + wifiName + ".psk"; } + mw->is_stop_check_net_state = 1; QThread *t = new QThread(); BackThread *bt = new BackThread(); diff --git a/src/onelancform.cpp b/src/onelancform.cpp index e9943e8a..16fd1403 100644 --- a/src/onelancform.cpp +++ b/src/onelancform.cpp @@ -398,6 +398,7 @@ void OneLancForm::toConnectWiredNetwork() if (mw->is_stop_check_net_state == 1) { return; } + mw->is_stop_check_net_state = 1; QThread *t = new QThread(); BackThread *bt = new BackThread(); From d5bd6d7e49db7adb99bf2eb018d646c686aec2e7 Mon Sep 17 00:00:00 2001 From: zhangjiaping Date: Tue, 22 Jun 2021 21:41:42 +0800 Subject: [PATCH 7/7] =?UTF-8?q?Fix:=20=E4=BF=AE=E5=A4=8D=E8=BF=9C=E7=A8=8B?= =?UTF-8?q?=E8=BF=9E=E6=8E=A5=E7=94=A8=E6=88=B7=E6=A1=8C=E9=9D=A2=E6=97=A0?= =?UTF-8?q?kylin-nm=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- kylin-nm.pro | 2 + src/main.cpp | 32 +- src/singleapplication/qt-local-peer.cpp | 205 ++++++++++ src/singleapplication/qt-local-peer.h | 80 ++++ src/singleapplication/qt-locked-file-unix.cpp | 113 ++++++ src/singleapplication/qt-locked-file.cpp | 189 ++++++++++ src/singleapplication/qt-locked-file.h | 97 +++++ .../qt-single-application.cpp | 357 ++++++++++++++++++ src/singleapplication/qt-single-application.h | 109 ++++++ .../qt-single-application.pri | 27 ++ 10 files changed, 1202 insertions(+), 9 deletions(-) create mode 100644 src/singleapplication/qt-local-peer.cpp create mode 100644 src/singleapplication/qt-local-peer.h create mode 100644 src/singleapplication/qt-locked-file-unix.cpp create mode 100644 src/singleapplication/qt-locked-file.cpp create mode 100644 src/singleapplication/qt-locked-file.h create mode 100644 src/singleapplication/qt-single-application.cpp create mode 100644 src/singleapplication/qt-single-application.h create mode 100644 src/singleapplication/qt-single-application.pri diff --git a/kylin-nm.pro b/kylin-nm.pro index f8b6933a..fa98d5c3 100644 --- a/kylin-nm.pro +++ b/kylin-nm.pro @@ -57,6 +57,8 @@ QMAKE_CFLAGS *= $(shell dpkg-buildflags --get CFLAGS) QMAKE_CXXFLAGS *= $(shell dpkg-buildflags --get CXXFLAGS) QMAKE_LFLAGS *= $(shell dpkg-buildflags --get LDFLAGS) +include(src/singleapplication/qt-single-application.pri) + SOURCES += \ src/backthread.cpp \ diff --git a/src/main.cpp b/src/main.cpp index 8759f993..8e911a04 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -23,7 +23,8 @@ #include "dbusadaptor.h" #include #include -#include +//#include +#include "qt-single-application.h" #include #include #include @@ -80,8 +81,19 @@ int main(int argc, char *argv[]) QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); - QApplication a(argc, argv); +// QApplication a(argc, argv); + QString id = QString("kylin-nm"+ QLatin1String(getenv("DISPLAY"))); + QtSingleApplication a(id, argc, argv); qInstallMessageHandler(messageOutput); + if (a.isRunning()) { + auto connection = QDBusConnection::sessionBus(); + QDBusInterface iface("com.kylin.network", + "/com/kylin/network", + "com.kylin.network", + connection); + iface.call("showMainWindow"); + return 0; + } qDebug()<<"Kylin Network Manager Is Already Launched"; @@ -113,17 +125,19 @@ int main(int argc, char *argv[]) DbusAdaptor adaptor(&w); Q_UNUSED(adaptor); + auto connection = QDBusConnection::sessionBus(); if (!connection.registerService("com.kylin.network") || !connection.registerObject("/com/kylin/network", &w)) { qCritical() << "QDbus register service failed reason:" << connection.lastError(); - QDBusInterface iface("com.kylin.network", - "/com/kylin/network", - "com.kylin.network", - connection); - iface.call("showMainWindow"); - - return 0; } +// QDBusInterface iface("com.kylin.network", +// "/com/kylin/network", +// "com.kylin.network", +// connection); +// iface.call("showMainWindow"); + +// return 0; +// } w.justShowTrayIcon(); diff --git a/src/singleapplication/qt-local-peer.cpp b/src/singleapplication/qt-local-peer.cpp new file mode 100644 index 00000000..4a62537c --- /dev/null +++ b/src/singleapplication/qt-local-peer.cpp @@ -0,0 +1,205 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies) +** 2020 KylinSoft Co., Ltd. +** Contact: http://www.qt-project.org/legal +** +** +** This file is part of the Qt Solutions component. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +** +****************************************************************************/ + + +#include "qt-local-peer.h" +#include +#include +#include + +#if defined(Q_OS_UNIX) +#include +#include +#include +#endif + +namespace QtLP_Private { +#include "qt-locked-file.cpp" +#include "qt-locked-file-unix.cpp" +} + +const char* QtLocalPeer::ack = "ack"; + +QtLocalPeer::QtLocalPeer(QObject* parent, const QString &appId) + : QObject(parent), id(appId) { + 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(QRegExp("[^a-zA-Z]")); //去掉名称中的非字母 + prefix.truncate(6); //取前六位 + + QByteArray idc = id.toUtf8(); + quint16 idNum = qChecksum(idc.constData(), idc.size()); + socketName = QLatin1String("qtsingleapp-") + prefix + + QLatin1Char('-') + QString::number(idNum, 16); + +#if defined(Q_OS_WIN) + if(!pProcessIdToSessionId) { + QLibrary lib("kernel32"); + pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId"); + } + if(pProcessIdToSessionId) { + DWORD sessionId = 0; + pProcessIdToSessionId(GetCurrentProcessId(), &sessionId); + socketName += QLatin1Char('-') + QString::number(sessionId, 16); + } +#else + socketName += QLatin1Char('-') + QString::number(::getuid(), 16); +#endif + + server = new QLocalServer(this); + QString lockName = QDir(QDir::tempPath()).absolutePath() + + QLatin1Char('/') + socketName + + QLatin1String("-lockfile"); //tmp目录下的锁文件 + lockFile.setFileName(lockName); + lockFile.open(QIODevice::ReadWrite); +} + + + +bool QtLocalPeer::isClient() { + if(lockFile.isLocked()) + return false; + + if(!lockFile.lock(QtLP_Private::QtLockedFile::WriteLock, false)) + return true; + + //由于文件锁的存在,仅当本进程第一次启动时能执行到此并使server进行监听和关联槽函数 + 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); + } +#endif + if(!res) + qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString())); + QObject::connect(server, &QLocalServer::newConnection, this, &QtLocalPeer::receiveConnection); + return false; +} + + +bool QtLocalPeer::sendMessage(const QString &message, int timeout) { + if(!isClient()) + return false; + + QLocalSocket socket; + bool connOk = false; + for(int i = 0; i < 2; i++) { + // Try twice, in case the other instance is just starting up + socket.connectToServer(socketName); + connOk = socket.waitForConnected(timeout / 2); + if(connOk || i) + break; + int ms = 250; +#if defined(Q_OS_WIN) + Sleep(DWORD(ms)); +#else + struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 }; + nanosleep(&ts, NULL); +#endif + } + if(!connOk) + return false; + + QByteArray uMsg(message.toUtf8()); + QDataStream ds(&socket); + ds.writeBytes(uMsg.constData(), uMsg.size()); + bool res = socket.waitForBytesWritten(timeout); + if(res) { + res &= socket.waitForReadyRead(timeout); // wait for ack + if(res) + res &= (socket.read(qstrlen(ack)) == ack); + } + return res; +} + +/** + * @brief QtLocalPeer::receiveConnection 当新进程启动时,会尝试连接此进程server,server接收到newConnection信号并触发此槽函数 + */ +void QtLocalPeer::receiveConnection() { + QLocalSocket* socket = server->nextPendingConnection(); //获取新进程的socket + if(!socket) + return; + + while(true) { + if(socket->state() == QLocalSocket::UnconnectedState) { + qWarning("QtLocalPeer: Peer disconnected"); + delete socket; + return; + } + if(socket->bytesAvailable() >= qint64(sizeof(quint32))) + break; + socket->waitForReadyRead(); + } + + QDataStream ds(socket); + QByteArray uMsg; + quint32 remaining; + ds >> remaining; + uMsg.resize(remaining); + int got = 0; + char* uMsgBuf = uMsg.data(); + do { + got = ds.readRawData(uMsgBuf, remaining); + remaining -= got; + uMsgBuf += got; + } while(remaining && got >= 0 && socket->waitForReadyRead(2000)); + if(got < 0) { + qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData()); + delete socket; + return; + } + QString message(QString::fromUtf8(uMsg)); + socket->write(ack, qstrlen(ack)); + socket->waitForBytesWritten(1000); + socket->waitForDisconnected(1000); // make sure client reads ack + delete socket; + Q_EMIT messageReceived(message); //获取新进程的启动信息并作为信号发送给前端 +} diff --git a/src/singleapplication/qt-local-peer.h b/src/singleapplication/qt-local-peer.h new file mode 100644 index 00000000..883aec2a --- /dev/null +++ b/src/singleapplication/qt-local-peer.h @@ -0,0 +1,80 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies) +** 2020 KylinSoft Co., Ltd. +** Contact: http://www.qt-project.org/legal +** +** +** This file is part of the Qt Solutions component. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +** +****************************************************************************/ + +#ifndef QTLOCALPEER_H +#define QTLOCALPEER_H + +#include +#include +#include + +#include "qt-locked-file.h" + +class QtLocalPeer : public QObject { + Q_OBJECT + +public: + QtLocalPeer(QObject *parent = 0, const QString &appId = QString()); + bool isClient(); + bool sendMessage(const QString &message, int timeout); + QString applicationId() const { + return id; + } + +Q_SIGNALS: + void messageReceived(const QString &message); + +protected Q_SLOTS: + void receiveConnection(); + +protected: + QString id; + QString socketName; + QLocalServer* server; + QtLP_Private::QtLockedFile lockFile; + +private: + static const char* ack; +}; + +#endif // QTLOCALPEER_H diff --git a/src/singleapplication/qt-locked-file-unix.cpp b/src/singleapplication/qt-locked-file-unix.cpp new file mode 100644 index 00000000..51472520 --- /dev/null +++ b/src/singleapplication/qt-locked-file-unix.cpp @@ -0,0 +1,113 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies) +** 2020 KylinSoft Co., Ltd. +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt Solutions component. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include + +#include "qt-locked-file.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/src/singleapplication/qt-locked-file.cpp b/src/singleapplication/qt-locked-file.cpp new file mode 100644 index 00000000..707b4cfa --- /dev/null +++ b/src/singleapplication/qt-locked-file.cpp @@ -0,0 +1,189 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies) +** 2020 KylinSoft Co., Ltd. +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt Solutions component. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qt-locked-file.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/src/singleapplication/qt-locked-file.h b/src/singleapplication/qt-locked-file.h new file mode 100644 index 00000000..332d648e --- /dev/null +++ b/src/singleapplication/qt-locked-file.h @@ -0,0 +1,97 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies) +** 2020 KylinSoft Co., Ltd. +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt Solutions component. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QTLOCKEDFILE_H +#define QTLOCKEDFILE_H + +#include +#ifdef Q_OS_WIN +#include +#endif + +#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 + +namespace QtLP_Private { + +class QT_QTLOCKEDFILE_EXPORT 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 rmutexes; + QString mutexname; + + Qt::HANDLE getMutexHandle(int idx, bool doCreate); + bool waitMutex(Qt::HANDLE mutex, bool doBlock); + +#endif + LockMode m_lock_mode; +}; +} +#endif diff --git a/src/singleapplication/qt-single-application.cpp b/src/singleapplication/qt-single-application.cpp new file mode 100644 index 00000000..b06144df --- /dev/null +++ b/src/singleapplication/qt-single-application.cpp @@ -0,0 +1,357 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies) +** 2020 KylinSoft Co., Ltd. +** Contact: http://www.qt-project.org/legal +** +** +** This file is part of the Qt Solutions component. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +** +****************************************************************************/ + + +#include "qt-single-application.h" +#include "qt-local-peer.h" +#include +#include +#include +#include +#include +#include "../mainwindow.h" + + +/*! + \class QtSingleApplication qtsingleapplication.h + \brief The QtSingleApplication class provides an API to detect and + communicate with running instances of an application. + + 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. + + 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. + + 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. + + 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. + + 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(); + } + + // 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(); + } + \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&))); + connect(peer, &QtLocalPeer::messageReceived, this, &QtSingleApplication::messageReceived); +} + + +/*! + 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) { + sysInit(); +} + + +/*! + 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) { + sysInit(appId); +} + +#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) { + sysInit(); +} + + +# 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(); +} + +/*! + 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) { + sysInit(); +} + +/*! + 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). + + \sa sendMessage() +*/ + +bool QtSingleApplication::isRunning() { + return peer->isClient(); +} + + +/*! + 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) { + return peer->sendMessage(message, timeout); +} + + +/*! + 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 (activateOnMessage) +// connect(peer, &QtLocalPeer::messageReceived, this, &QtSingleApplication::activateWindow); +// else +// disconnect(peer, &QtLocalPeer::messageReceived, this, &QtSingleApplication::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() { + //单例置顶策略,由于bootOptionsFilter in mainwindow自带置顶策略,故注掉此处 +// if (actWin) { +// if(this->applicationState() & Qt::ApplicationInactive) +// { +// MainWindow* w=qobject_cast(actWin); +//// w->loadMainWindow(); +// w->clearSearchResult(); +// actWin->setWindowState(actWin->windowState() & ~Qt::WindowMinimized); +// actWin->raise(); +// actWin->showNormal(); +// actWin->activateWindow(); +// } +// else { +// actWin->setWindowState(actWin->windowState() & Qt::WindowMinimized); +// actWin->hide(); +// } + +// } +} + + +/*! + \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/src/singleapplication/qt-single-application.h b/src/singleapplication/qt-single-application.h new file mode 100644 index 00000000..15df5a8b --- /dev/null +++ b/src/singleapplication/qt-single-application.h @@ -0,0 +1,109 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies) +** 2020 KylinSoft Co., Ltd. +** Contact: http://www.qt-project.org/legal +** +** +** This file is part of the Qt Solutions component. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +** +****************************************************************************/ + +#ifndef QTSINGLEAPPLICATION_H +#define QTSINGLEAPPLICATION_H + +#include + +class QtLocalPeer; + +#if defined(Q_OS_WIN) +# if !defined(QT_QTSINGLEAPPLICATION_EXPORT) && !defined(QT_QTSINGLEAPPLICATION_IMPORT) +# define QT_QTSINGLEAPPLICATION_EXPORT +# elif defined(QT_QTSINGLEAPPLICATION_IMPORT) +# if defined(QT_QTSINGLEAPPLICATION_EXPORT) +# undef QT_QTSINGLEAPPLICATION_EXPORT +# endif +# define QT_QTSINGLEAPPLICATION_EXPORT __declspec(dllimport) +# elif defined(QT_QTSINGLEAPPLICATION_EXPORT) +# undef QT_QTSINGLEAPPLICATION_EXPORT +# define QT_QTSINGLEAPPLICATION_EXPORT __declspec(dllexport) +# endif +#else +# define QT_QTSINGLEAPPLICATION_EXPORT +#endif + +class QT_QTSINGLEAPPLICATION_EXPORT QtSingleApplication : public QApplication { + Q_OBJECT + +public: + QtSingleApplication(int &argc, char **argv, bool GUIenabled = true); + QtSingleApplication(const QString &id, int &argc, char **argv); +#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; + + // Obsolete: + void initialize(bool dummy = true) { + isRunning(); + Q_UNUSED(dummy) + } + +public Q_SLOTS: + bool sendMessage(const QString &message, int timeout = 5000); + void activateWindow(); + + +Q_SIGNALS: + void messageReceived(const QString &message); + + +private: + void sysInit(const QString &appId = QString()); + QtLocalPeer *peer; + QWidget *actWin; +}; + +#endif // QTSINGLEAPPLICATION_H diff --git a/src/singleapplication/qt-single-application.pri b/src/singleapplication/qt-single-application.pri new file mode 100644 index 00000000..0a4ca9ae --- /dev/null +++ b/src/singleapplication/qt-single-application.pri @@ -0,0 +1,27 @@ +INCLUDEPATH += $$PWD +DEPENDPATH += $$PWD +QT *= network +greaterThan(QT_MAJOR_VERSION, 4): QT *= widgets + +qtsingleapplication-uselib:!qtsingleapplication-buildlib { + LIBS += -L$$QTSINGLEAPPLICATION_LIBDIR -l$$QTSINGLEAPPLICATION_LIBNAME +} else { + SOURCES += + HEADERS += +} + +win32 { + contains(TEMPLATE, lib):contains(CONFIG, shared):DEFINES += QT_QTSINGLEAPPLICATION_EXPORT + else:qtsingleapplication-uselib:DEFINES += QT_QTSINGLEAPPLICATION_IMPORT +} + +HEADERS += \ + $$PWD/qt-local-peer.h \ + $$PWD/qt-locked-file.h \ + $$PWD/qt-single-application.h + +SOURCES += \ + $$PWD/qt-local-peer.cpp \ + $$PWD/qt-locked-file-unix.cpp \ + $$PWD/qt-single-application.cpp \ + $$PWD/qt-locked-file.cpp