diff --git a/.gitignore b/.gitignore new file mode 100755 index 00000000..b9616cd3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,54 @@ +# C++ objects and libs +*.slo +*.lo +*.o +*.a +*.la +*.lai +*.so +*.so.* +*.dll +*.dylib + +# Qt-es +object_script.*.Release +object_script.*.Debug +*_plugin_import.cpp +/.qmake.cache +/.qmake.stash +*.pro.user +*.pro.user.* +*.qbs.user +*.qbs.user.* +*.moc +moc_*.cpp +moc_*.h +qrc_*.cpp +ui_*.h +*.qmlc +*.jsc +Makefile* +*build-* +*.prl + +# Qt unit tests +target_wrapper.* + +# QtCreator +*.autosave + +# QtCreator Qml +*.qmlproject.user +*.qmlproject.user.* + +# QtCreator CMake +CMakeLists.txt.user* + +# QtCreator 4.8< compilation database +compile_commands.json + +# QtCreator local machine specific files for imported projects +*creator.user* + +# OS X extra file +.DS_Store diff --git a/kylin-nm.pro b/kylin-nm.pro index 4999ff17..d995544b 100644 --- a/kylin-nm.pro +++ b/kylin-nm.pro @@ -1,13 +1,26 @@ TEMPLATE = subdirs -CONFIG += ordered \ - qt + +CONFIG += \ + ordered \ + qt SUBDIRS = \ - plugins/plugin.pro \ - src \ + plugins/plugin.pro \ + src-vpn/src-vpn.pro \ + src TRANSLATIONS += \ translations/kylin-nm_zh_CN.ts \ translations/kylin-nm_tr.ts \ - translations/kylin-nm_bo.ts + translations/kylin-nm_bo.ts \ + translations/kylin-nm_bo_CN.ts + +CONFIG(release, debug|release) { + !system($$PWD/translate_generation.sh): error("Failed to generate translation") +} + +qm_files.path = $${PREFIX}/share/kylin-nm/kylin-nm/ +qm_files.files = translations/*.qm + +INSTALLS += qm_files \ diff --git a/nmqrc.qrc b/nmqrc.qrc index db90969b..aea1ec48 100644 --- a/nmqrc.qrc +++ b/nmqrc.qrc @@ -17,9 +17,6 @@ res/h/right-pwd.png res/h/show-pwd.png res/h/no-pwd-wifi.png - translations/kylin-nm_bo.qm - translations/kylin-nm_tr.qm - translations/kylin-nm_zh_CN.qm res/x/fly-mode-off.svg res/x/fly-mode-on.svg res/x/hot-spot-off.svg diff --git a/plugins/component/AddBtn/addnetbtn.cpp b/plugins/component/AddBtn/addnetbtn.cpp index eb1bc6fb..f60ba82d 100644 --- a/plugins/component/AddBtn/addnetbtn.cpp +++ b/plugins/component/AddBtn/addnetbtn.cpp @@ -20,6 +20,7 @@ #include "addnetbtn.h" #include #include +#include #include #include #include @@ -33,35 +34,30 @@ AddNetBtn::AddNetBtn(bool isWlan, QWidget *parent) : QPushButton(parent) this->setMaximumSize(QSize(16777215, 60)); this->setProperty("useButtonPalette", true); this->setFlat(true); - QPalette pal = this->palette(); - QColor color = pal.color(QPalette::Button); - color.setAlphaF(0.5); - pal.setColor(QPalette::Button, color); - this->setPalette(pal); - QHBoxLayout *addLyt = new QHBoxLayout(this); + + QHBoxLayout *addLyt = new QHBoxLayout; QLabel *iconLabel = new QLabel(this); - textLabel = new QLabel(this); + m_textLabel = new QLabel(this); if (isWlan) { - textLabel->setText(tr("Add Others")); + m_textLabel->setText(tr("Add Others")); addLyt->addSpacing(8); - addLyt->addWidget(textLabel); + addLyt->addWidget(m_textLabel); } else { - textLabel->setText(tr("Add WiredNetork")); + m_textLabel->setText(tr("Add WiredNetork")); QIcon mAddIcon = QIcon::fromTheme("list-add-symbolic"); - iconLabel->setPixmap(mAddIcon.pixmap(mAddIcon.actualSize(QSize(24, 24)))); - iconLabel->setProperty("useIconHighlightEffect", true); - iconLabel->setProperty("iconHighlightEffectMode", 1); + iconLabel->setPixmap(mAddIcon.pixmap(mAddIcon.actualSize(QSize(16, 16)))); + iconLabel->setProperty("useIconHighlightEffect", 0x2); +// iconLabel->setProperty("iconHighlightEffectMode", 1); addLyt->addStretch(); addLyt->addWidget(iconLabel); - addLyt->addWidget(textLabel); + addLyt->addWidget(m_textLabel); } addLyt->addStretch(); this->setLayout(addLyt); - } AddNetBtn::~AddNetBtn() @@ -83,12 +79,18 @@ void AddNetBtn::leaveEvent(QEvent *event){ void AddNetBtn::paintEvent(QPaintEvent *event) { - QPalette pal = this->palette(); + QPalette pal = qApp->palette(); QPainter painter(this); painter.setRenderHint(QPainter:: Antialiasing, true); //设置渲染,启动反锯齿 painter.setPen(Qt::NoPen); - painter.setBrush(pal.color(QPalette::Base)); + + painter.setBrush(this->palette().base().color()); + + QColor color = pal.color(QPalette::Button); + color.setAlphaF(0.5); + pal.setColor(QPalette::Button, color); + this->setPalette(pal); QRect rect = this->rect(); QPainterPath path; diff --git a/plugins/component/AddBtn/addnetbtn.h b/plugins/component/AddBtn/addnetbtn.h index 60ba8028..85876755 100644 --- a/plugins/component/AddBtn/addnetbtn.h +++ b/plugins/component/AddBtn/addnetbtn.h @@ -34,8 +34,8 @@ public: AddNetBtn(bool isWlan, QWidget *parent = nullptr); ~AddNetBtn(); - void setTextLabel(QString str) { - textLabel->setText(str); + void setTextLabel(const QString str) { + m_textLabel->setText(str); } protected: @@ -44,7 +44,7 @@ protected: void paintEvent(QPaintEvent *event); private: - QLabel* textLabel; + QLabel *m_textLabel; Q_SIGNALS: void enterWidget(); diff --git a/plugins/component/AddBtn/grayinfobutton.cpp b/plugins/component/AddBtn/grayinfobutton.cpp new file mode 100644 index 00000000..daa4fa1d --- /dev/null +++ b/plugins/component/AddBtn/grayinfobutton.cpp @@ -0,0 +1,33 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#include "grayinfobutton.h" + +#include + +#define BUTTON_SIZE 36,36 +#define ICON_SIZE 16,16 + +GrayInfoButton::GrayInfoButton(QWidget *parent): QPushButton(parent) +{ + this->setFixedSize(BUTTON_SIZE); + this->setIcon(QIcon::fromTheme("preferences-system-details-symbolic")); + this->setProperty("useButtonPalette", true); + this->setFlat(true); +} diff --git a/plugins/component/AddBtn/grayinfobutton.h b/plugins/component/AddBtn/grayinfobutton.h new file mode 100644 index 00000000..0024f8b7 --- /dev/null +++ b/plugins/component/AddBtn/grayinfobutton.h @@ -0,0 +1,34 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#ifndef GRAYINFOBUTTON_H +#define GRAYINFOBUTTON_H + +#include +#include + +class GrayInfoButton : public QPushButton +{ + Q_OBJECT +public: + explicit GrayInfoButton(QWidget * parent = nullptr); + ~GrayInfoButton() = default; +}; + +#endif // GRAYINFOBUTTON_H diff --git a/plugins/component/DrownLabel/drownlabel.cpp b/plugins/component/DrownLabel/drownlabel.cpp index 4e46523a..356c7d23 100644 --- a/plugins/component/DrownLabel/drownlabel.cpp +++ b/plugins/component/DrownLabel/drownlabel.cpp @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "drownlabel.h" #include "deviceframe.h" diff --git a/plugins/component/DrownLabel/drownlabel.h b/plugins/component/DrownLabel/drownlabel.h index 806dc132..b4daf2a2 100644 --- a/plugins/component/DrownLabel/drownlabel.h +++ b/plugins/component/DrownLabel/drownlabel.h @@ -1,3 +1,23 @@ + +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef DROWNLABEL_H #define DROWNLABEL_H diff --git a/plugins/component/InfoButton/infobutton.cpp b/plugins/component/InfoButton/infobutton.cpp index 26ac05a2..edb8b2db 100644 --- a/plugins/component/InfoButton/infobutton.cpp +++ b/plugins/component/InfoButton/infobutton.cpp @@ -1,9 +1,28 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "infobutton.h" #include #include -#include #include #include +#include #define BUTTON_SIZE 36,36 #define ICON_SIZE 16,16 diff --git a/plugins/component/InfoButton/infobutton.h b/plugins/component/InfoButton/infobutton.h index 6376b028..f4607ade 100644 --- a/plugins/component/InfoButton/infobutton.h +++ b/plugins/component/InfoButton/infobutton.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef INFOBUTTON_H #define INFOBUTTON_H #include diff --git a/plugins/component/addbtn.pri b/plugins/component/addbtn.pri index c22c6e7c..f3961167 100644 --- a/plugins/component/addbtn.pri +++ b/plugins/component/addbtn.pri @@ -2,8 +2,10 @@ SOURCES += \ $$PWD/AddBtn/addnetbtn.cpp \ + $$PWD/AddBtn/grayinfobutton.cpp HEADERS += \ $$PWD/AddBtn/addnetbtn.h \ + $$PWD/AddBtn/grayinfobutton.h diff --git a/plugins/mobilehotspot/blacklistitem.cpp b/plugins/mobilehotspot/blacklistitem.cpp new file mode 100644 index 00000000..bc59735d --- /dev/null +++ b/plugins/mobilehotspot/blacklistitem.cpp @@ -0,0 +1,70 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#include "blacklistitem.h" +#include + +#define MAIN_LAYOUT_MARGINS 0,0,0,0 +#define MAIN_LAYOUT_SPACING 0 +#define ITEM_FRAME_MARGINS 0,0,0,0 +#define ITEM_FRAME_SPACING 10 +#define FRAME_WIDTH 395 +#define INFO_ICON_WIDTH 16 +#define INFO_ICON_HEIGHT 16 +#define LIGHT_HOVER_COLOR QColor(240,240,240,255) +#define DARK_HOVER_COLOR QColor(15,15,15,255) + +#define FRAME_MIN_SIZE 550, 60 +#define CONTECT_FRAME_MAX_SIZE 16777215, 60 +#define LABLE_MIN_WIDTH 188 +#define ITEM_MARGINS 16, 0, 16, 0 + +BlacklistItem::BlacklistItem(QString staMac, QString staName, QWidget *parent) : + QFrame(parent), + m_mac(staMac), + m_hostName(staName) +{ + this->setMinimumHeight(60); + this->setFixedHeight(60); + + QHBoxLayout *hItemLayout = new QHBoxLayout(this); + hItemLayout->setContentsMargins(ITEM_MARGINS); + QLabel *nameLabel = new QLabel(staName, this); + m_removeFromBlacklistBtn = new KBorderlessButton(this); + m_removeFromBlacklistBtn->setText(tr("Remove")); + hItemLayout->setSpacing(0); + hItemLayout->addWidget(nameLabel, Qt::AlignLeft); + hItemLayout->addStretch(); + hItemLayout->addWidget(m_removeFromBlacklistBtn, Qt::AlignRight); + + m_removeFromBlacklistBtn->installEventFilter(this); + this->setLayout(hItemLayout); +} + +bool BlacklistItem::eventFilter(QObject *w, QEvent *e) +{ + if (e->type() == QEvent::MouseButtonRelease) { + if (w == m_removeFromBlacklistBtn) { + emit onBtnClicked(m_mac, m_hostName); + return true; + } + } + return QWidget::eventFilter(w,e); +} + diff --git a/plugins/mobilehotspot/blacklistitem.h b/plugins/mobilehotspot/blacklistitem.h new file mode 100644 index 00000000..dab02aae --- /dev/null +++ b/plugins/mobilehotspot/blacklistitem.h @@ -0,0 +1,52 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#ifndef BLACKLISTITEM_H +#define BLACKLISTITEM_H +#include +#include +#include +#include +#include +#include +#include +#include "kborderlessbutton.h" + +using namespace kdk; + +class BlacklistItem : public QFrame +{ + Q_OBJECT +public: + BlacklistItem(QString staMac, QString staName, QWidget *parent = nullptr); + +protected: + KBorderlessButton *m_removeFromBlacklistBtn = nullptr; + + QString m_mac; + QString m_hostName; + bool eventFilter(QObject *w, QEvent *e); + +signals: + void onBtnClicked(QString staMac, QString staName); + + +}; + +#endif // LISTITEM_H diff --git a/plugins/mobilehotspot/blacklistpage.cpp b/plugins/mobilehotspot/blacklistpage.cpp new file mode 100644 index 00000000..d923749c --- /dev/null +++ b/plugins/mobilehotspot/blacklistpage.cpp @@ -0,0 +1,200 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#include "blacklistpage.h" +#include + +#define CONTENTS_MARGINS 0, 0, 0, 0 +#define FRAME_MIN_SIZE 550, 60 +#define FRAME_MAX_SIZE 16777215, 16777215 +#define LINE_MAX_SIZE 16777215, 1 +#define LINE_MIN_SIZE 0, 1 + +#define LOG_HEAD "[BlacklistPage]" + +BlacklistPage::BlacklistPage(QWidget *parent) : QWidget(parent) +{ + QVBoxLayout *Vlayout = new QVBoxLayout(this); + Vlayout->setContentsMargins(CONTENTS_MARGINS); + Vlayout->setSpacing(0); + + m_blacklistFrame = new QFrame(this); + m_blacklistFrame->setMinimumSize(FRAME_MIN_SIZE); + m_blacklistFrame->setMaximumSize(FRAME_MAX_SIZE); + m_blacklistFrame->setFrameShape(QFrame::Box); + + m_blacklistLayout = new QVBoxLayout(m_blacklistFrame); + m_blacklistLayout->setContentsMargins(0, 0, 0, 0); + m_blacklistLayout->setSpacing(0); + + m_titleLabel = new TitleLabel(this); + m_titleLabel->setText(tr("Blacklist")); + + Vlayout->addWidget(m_titleLabel); + Vlayout->addSpacing(8); + Vlayout->addWidget(m_blacklistFrame); +} + +QFrame* BlacklistPage::myLine() +{ + QFrame *line = new QFrame(this); + line->setMinimumSize(QSize(LINE_MIN_SIZE)); + line->setMaximumSize(QSize(LINE_MAX_SIZE)); + line->setLineWidth(0); + line->setFrameShape(QFrame::HLine); + line->setFrameShadow(QFrame::Sunken); + + return line; +} + +void BlacklistPage::getBlacklistDevice(QMap &blacklistMap) +{ + if (m_settingPathInterface == nullptr || !m_settingPathInterface->isValid()) { + qDebug() << LOG_HEAD << "dbus interface m_settingPathInterface is invaild"; + return; + } + + QDBusMessage reply = m_settingPathInterface->call("Getblacklist"); + if(reply.type() == QDBusMessage::ErrorMessage) + { + qWarning() << LOG_HEAD << "Getblacklist error:" << reply.errorMessage(); + return; + } + if (reply.arguments().isEmpty() + || reply.arguments().at(0).toString() == "" + || reply.arguments().at(1).toString() == "") { + qDebug() << LOG_HEAD << "Dbus interface call Getblacklist return is empty!"; + return; + } + QStringList macList = reply.arguments().at(0).toString().split(";"); + QStringList hostNameList = reply.arguments().at(1).toString().split(";"); + for (int index = 0; index < macList.count() && macList.at(index) != nullptr; index ++) { + QString macTemp = macList.at(index); + macTemp = macTemp.trimmed(); + if (!blacklistMap.contains(macTemp) && hostNameList.at(index) != nullptr) { + blacklistMap[macTemp] = hostNameList.at(index); + } + } +} + +void BlacklistPage::initBlacklistDev() +{ + QMap::const_iterator item = m_blacklistMap.cbegin(); + while (item != m_blacklistMap.cend()) { + addBlacklistDevFrame(item.key(), item.value()); + item ++; + if (item != m_blacklistMap.cend()) { + m_blacklistLayout->addWidget(myLine()); + } + } +} + +void BlacklistPage::onsetStaIntoBlacklist(QString staMac, QString staName) +{ + if (m_settingPathInterface == nullptr || !m_settingPathInterface->isValid()) { + qDebug() << LOG_HEAD << LOG_HEAD << "dbus interface m_settingPathInterface is invaild"; + return; + } + + QDBusMessage reply = m_settingPathInterface->call("Addblacklist", staMac, staName); + if(reply.type() == QDBusMessage::ErrorMessage) + { + qWarning() << LOG_HEAD << "Addblacklist error:" << reply.errorMessage(); + return; + } + + refreshBlacklist(); +} + +void BlacklistPage::addBlacklistDevFrame(QString staMac, QString staName) +{ + BlacklistItem *itemFrame = new BlacklistItem(staMac, staName, m_blacklistLayout->widget()); + m_blacklistLayout->addWidget(itemFrame); + connect(itemFrame, &BlacklistItem::onBtnClicked, this, &BlacklistPage::onRemoveFromBlacklistBtnClicked); +} + +void BlacklistPage::clearBlacklistLayout() +{ + if (m_blacklistLayout->layout() != NULL) { + QLayoutItem* layoutItem; + while ((layoutItem = m_blacklistLayout->layout()->takeAt(0)) != NULL) { + delete layoutItem->widget(); + delete layoutItem; + } + } +} + +bool BlacklistPage::removeStaFromBlacklist(QString staMac, QString staName) +{ + if (m_settingPathInterface == nullptr || !m_settingPathInterface->isValid()) { + qDebug() << LOG_HEAD << "dbus interface m_settingPathInterface is invaild"; + return false; + } + + QDBusMessage reply = m_settingPathInterface->call("Delblacklist", staMac, staName); + if(reply.type() == QDBusMessage::ErrorMessage) + { + qWarning() << LOG_HEAD << "Delblacklist error:" << reply.errorMessage(); + return false; + } + + return true; +} + +void BlacklistPage::resetLayoutHight() +{ + int height = 0; + for (int i = 0; i < m_blacklistLayout->count(); i ++) { + QWidget *w = m_blacklistLayout->itemAt(i)->widget(); + if (w != nullptr) { + height += w->height(); + } + } + m_blacklistFrame->setFixedHeight(height); + + if (m_blacklistMap.isEmpty()) { + this->hide(); + } else { + this->show(); + } + this->update(); +} + +void BlacklistPage::refreshBlacklist() +{ + m_blacklistMap.clear(); + getBlacklistDevice(m_blacklistMap); + clearBlacklistLayout(); + initBlacklistDev(); + resetLayoutHight(); +} + +void BlacklistPage::onRemoveFromBlacklistBtnClicked(QString staMac, QString staName) +{ + if (staMac.isNull() + || staMac.isEmpty() + || staName.isNull() + || staName.isEmpty()) { + qDebug() << LOG_HEAD <<"On remove from blacklist button clicked error! sta mac or name is empty!"; + return; + } + removeStaFromBlacklist(staMac, staName); + refreshBlacklist(); +} + diff --git a/plugins/mobilehotspot/blacklistpage.h b/plugins/mobilehotspot/blacklistpage.h new file mode 100644 index 00000000..8a511c1d --- /dev/null +++ b/plugins/mobilehotspot/blacklistpage.h @@ -0,0 +1,74 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#ifndef BLACKLISTPAGE_H +#define BLACKLISTPAGE_H + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "titlelabel.h" +#include "blacklistitem.h" + +using namespace kdk; + +class BlacklistPage : public QWidget +{ + Q_OBJECT +public: + explicit BlacklistPage(QWidget *parent = nullptr); + + void refreshBlacklist(); + bool setStaIntoBlacklist(QString staMac); + + inline void setInterface(QDBusInterface *settingInterface) { + m_settingPathInterface = settingInterface; + } + +private: + QFrame* myLine(); + + void getBlacklistDevice(QMap &blacklistMap); + bool removeStaFromBlacklist(QString staMac, QString staName); + void initBlacklistDev(); + void addBlacklistDevFrame(QString staMac, QString staName); + void clearBlacklistLayout(); + void resetLayoutHight(); + +private: + QFrame *m_blacklistFrame = nullptr; + TitleLabel *m_titleLabel = nullptr; + QVBoxLayout *m_blacklistLayout = nullptr; + QMap m_blacklistMap; + + QDBusInterface *m_settingPathInterface = nullptr; + +private slots: + void onsetStaIntoBlacklist(QString staMac, QString staName); + void onRemoveFromBlacklistBtnClicked(QString staMac, QString staName); +}; + +#endif // MOBILEHOTSPOTWIDGET_H diff --git a/plugins/mobilehotspot/connectdevlistitem.cpp b/plugins/mobilehotspot/connectdevlistitem.cpp new file mode 100644 index 00000000..a8107905 --- /dev/null +++ b/plugins/mobilehotspot/connectdevlistitem.cpp @@ -0,0 +1,70 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#include "connectdevlistitem.h" +#include + +#define MAIN_LAYOUT_MARGINS 0,0,0,0 +#define MAIN_LAYOUT_SPACING 0 +#define ITEM_FRAME_MARGINS 0,0,0,0 +#define ITEM_FRAME_SPACING 10 +#define FRAME_WIDTH 395 +#define INFO_ICON_WIDTH 16 +#define INFO_ICON_HEIGHT 16 +#define LIGHT_HOVER_COLOR QColor(240,240,240,255) +#define DARK_HOVER_COLOR QColor(15,15,15,255) + +#define FRAME_MIN_SIZE 550, 60 +#define CONTECT_FRAME_MAX_SIZE 16777215, 60 +#define LABLE_MIN_WIDTH 188 +#define ITEM_MARGINS 16, 0, 16, 0 + +ConnectDevListItem::ConnectDevListItem(QString staMac, QString staName, QWidget *parent) : + QFrame(parent), + m_mac(staMac), + m_hostName(staName) +{ + this->setMinimumSize(FRAME_MIN_SIZE); + this->setFixedHeight(60); + + QHBoxLayout *hItemLayout = new QHBoxLayout(this); + hItemLayout->setContentsMargins(ITEM_MARGINS); + QLabel *nameLabel = new QLabel(staName, this); + m_dragIntoBlackListBtn = new KBorderlessButton(this); + m_dragIntoBlackListBtn->setText(tr("drag into blacklist")); + hItemLayout->setSpacing(0); + hItemLayout->addWidget(nameLabel, Qt::AlignLeft); + hItemLayout->addStretch(); + hItemLayout->addWidget(m_dragIntoBlackListBtn, Qt::AlignRight); + + m_dragIntoBlackListBtn->installEventFilter(this); + this->setLayout(hItemLayout); +} + +bool ConnectDevListItem::eventFilter(QObject *w, QEvent *e) +{ + if (e->type() == QEvent::MouseButtonRelease) { + if (w == m_dragIntoBlackListBtn) { + emit onBtnClicked(m_mac, m_hostName); + return true; + } + } + return QWidget::eventFilter(w,e); +} + diff --git a/plugins/mobilehotspot/connectdevlistitem.h b/plugins/mobilehotspot/connectdevlistitem.h new file mode 100644 index 00000000..182d581e --- /dev/null +++ b/plugins/mobilehotspot/connectdevlistitem.h @@ -0,0 +1,52 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#ifndef CONNECTDEVLISTITEM_H +#define CONNECTDEVLISTITEM_H +#include +#include +#include +#include +#include +#include +#include +#include "kborderlessbutton.h" + +using namespace kdk; + +class ConnectDevListItem : public QFrame +{ + Q_OBJECT +public: + ConnectDevListItem(QString staMac, QString staName, QWidget *parent = nullptr); + +protected: + KBorderlessButton *m_dragIntoBlackListBtn = nullptr; + + QString m_mac; + QString m_hostName; + bool eventFilter(QObject *w, QEvent *e); + +signals: + void onBtnClicked(QString staMac, QString staName); + + +}; + +#endif // LISTITEM_H diff --git a/plugins/mobilehotspot/connectdevpage.cpp b/plugins/mobilehotspot/connectdevpage.cpp new file mode 100644 index 00000000..473a4c69 --- /dev/null +++ b/plugins/mobilehotspot/connectdevpage.cpp @@ -0,0 +1,191 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#include "connectdevpage.h" +#include + +#define CONTENTS_MARGINS 0, 0, 0, 0 +#define FRAME_MIN_SIZE 550, 60 +#define FRAME_MAX_SIZE 16777215, 16777215 +#define LINE_MAX_SIZE 16777215, 1 +#define LINE_MIN_SIZE 0, 1 + +#define LOG_HEAD "[ConnectdevPage]" + +ConnectdevPage::ConnectdevPage(QWidget *parent) : + QWidget(parent) +{ + QVBoxLayout *Vlayout = new QVBoxLayout(this); + Vlayout->setContentsMargins(CONTENTS_MARGINS); + Vlayout->setSpacing(0); + + m_staistFrame = new QFrame(this); + m_staistFrame->setMinimumSize(FRAME_MIN_SIZE); + m_staistFrame->setMaximumSize(FRAME_MAX_SIZE); + m_staistFrame->setFrameShape(QFrame::Box); + + m_staListLayout = new QVBoxLayout(m_staistFrame); + m_staListLayout->setContentsMargins(0, 0, 0, 0); + m_staListLayout->setSpacing(0); + + m_titleLabel = new TitleLabel(this); + m_titleLabel->setText(tr("Connect device")); + + Vlayout->addWidget(m_titleLabel); + Vlayout->addSpacing(8); + Vlayout->addWidget(m_staistFrame); +} + +QFrame* ConnectdevPage::myLine() +{ + QFrame *line = new QFrame(this); + line->setMinimumSize(QSize(LINE_MIN_SIZE)); + line->setMaximumSize(QSize(LINE_MAX_SIZE)); + line->setLineWidth(0); + line->setFrameShape(QFrame::HLine); + line->setFrameShadow(QFrame::Sunken); + + return line; +} + +void ConnectdevPage::getConnectStaDevice(QMap &staMap) +{ + staMap.clear(); + if (m_activePathInterface == nullptr || !m_activePathInterface->isValid()) { + qDebug() << LOG_HEAD << "dbus interface m_activePathInterface is invaild"; + return; + } + + QDBusMessage reply = m_activePathInterface->call("Getstainfo"); + if(reply.type() == QDBusMessage::ErrorMessage) + { + qWarning() << LOG_HEAD << "Getstainfo error:" << reply.errorMessage(); + return; + } + + if (reply.arguments().isEmpty() + || reply.arguments().at(0).toString() == "" + || reply.arguments().at(0).toString() == "[Invalid UTF-8]" + || reply.arguments().at(1).toString() == "") { + qDebug() << LOG_HEAD << "Dbus interface call Getstainfo return is empty!"; + return; + } + + QStringList macList = reply.arguments().at(0).toString().split(";"); + QStringList hostNameList = reply.arguments().at(1).toString().split(";"); + for (int index = 0; index < macList.count() && macList.at(index) != nullptr; index ++) { + if (!staMap.contains(macList.at(index)) && hostNameList.at(index) != nullptr) { + staMap[macList.at(index)] = hostNameList.at(index); + } + } + +} + +void ConnectdevPage::initStaDev() +{ + QMap::const_iterator item = m_staMap.cbegin(); + while (item != m_staMap.cend()) { + addStaDevFrame(item.key(), item.value()); + item ++; + if (item != m_staMap.cend()) { + m_staListLayout->addWidget(myLine()); + } + } +} + +void ConnectdevPage::addStaDevFrame(QString staMac, QString staName) +{ + ConnectDevListItem *itemFrame = new ConnectDevListItem(staMac, staName, m_staListLayout->widget()); + m_staListLayout->addWidget(itemFrame); + connect(itemFrame, &ConnectDevListItem::onBtnClicked, this, &ConnectdevPage::onDropIntoBlacklistBtnClicked); +} + +void ConnectdevPage::clearStaListLayout() +{ + + if (m_staListLayout->layout() != NULL) { + QLayoutItem* layoutItem; + while ((layoutItem = m_staListLayout->layout()->takeAt(0)) != NULL) { + delete layoutItem->widget(); + delete layoutItem; + } + } +} + +void ConnectdevPage::onStaDevAdded(bool istrue, QString staMac, QString staName) +{ + if (!m_staMap.contains(staMac)) { + m_staMap.insert(staMac, staName); + clearStaListLayout(); + initStaDev(); + resetLayoutHight(); + } +} + +void ConnectdevPage::onStaDevRemoved(bool istrue, QString staMac, QString staName) +{ + if (m_staMap.contains(staMac)) { + if (m_staMap.remove(staMac)) { + clearStaListLayout(); + initStaDev(); + resetLayoutHight(); + } + } +} + +void ConnectdevPage::resetLayoutHight() +{ + int height = 0; + for (int i = 0; i < m_staListLayout->count(); i ++) { + QWidget *w = m_staListLayout->itemAt(i)->widget(); + if (w != nullptr) { + height += w->height(); + } + } + m_staistFrame->setFixedHeight(height); + + if (m_staMap.isEmpty()) { + this->hide(); + } else { + this->show(); + } + this->update(); +} + +void ConnectdevPage::refreshStalist() +{ + m_staMap.clear(); + getConnectStaDevice(m_staMap); + clearStaListLayout(); + initStaDev(); + resetLayoutHight(); +} + +void ConnectdevPage::onDropIntoBlacklistBtnClicked(QString staMac, QString staName) +{ + if (staMac.isNull() + || staMac.isEmpty() + || staName.isNull() + || staName.isEmpty()) { + qDebug() << LOG_HEAD <<"On drop into blacklist button clicked error! sta mac or name is empty!"; + return; + } + + emit setStaIntoBlacklist(staMac, staName); +} diff --git a/plugins/mobilehotspot/connectdevpage.h b/plugins/mobilehotspot/connectdevpage.h new file mode 100644 index 00000000..ce9abb09 --- /dev/null +++ b/plugins/mobilehotspot/connectdevpage.h @@ -0,0 +1,84 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#ifndef CONNECTDEVPAGE_H +#define CONNECTDEVPAGE_H + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "titlelabel.h" +#include "connectdevlistitem.h" + +using namespace kdk; + +class ConnectdevPage : public QWidget +{ + Q_OBJECT +public: + explicit ConnectdevPage(QWidget *parent = nullptr); + + void refreshStalist(); + + inline void setInterface(QDBusInterface *activeInterface) { + m_activePathInterface = activeInterface; + } + +private: + QFrame* myLine(); + + void getConnectStaDevice(QMap &blacklistMap); + bool removeStaFromBlacklist(QString staMac); + void initStaDev(); + void addStaDevFrame(QString staMac, QString staName); + void clearStaListLayout(); + QString getActivePathByUuid(QDBusInterface *interface); + void initNmDbus(QDBusInterface *interface); + + void onStaDevChanged(bool istrue, QString staMac, QString staName); + void resetLayoutHight(); + +private: + QFrame *m_staistFrame = nullptr; + + TitleLabel *m_titleLabel = nullptr; + QVBoxLayout *m_staListLayout = nullptr; + QMap m_staMap; + + QDBusInterface *m_activePathInterface = nullptr; + +signals: + void setStaIntoBlacklist(QString staMac, QString staName); + +public slots: + void onStaDevAdded(bool istrue, QString staMac, QString staName); + void onStaDevRemoved(bool istrue, QString staMac, QString staName); + +private slots: + void onDropIntoBlacklistBtnClicked(QString staMac, QString staName); +}; + +#endif // MOBILEHOTSPOTWIDGET_H diff --git a/plugins/mobilehotspot/mobilehotspot.pro b/plugins/mobilehotspot/mobilehotspot.pro index c4916f46..90c84dab 100644 --- a/plugins/mobilehotspot/mobilehotspot.pro +++ b/plugins/mobilehotspot/mobilehotspot.pro @@ -25,10 +25,18 @@ PKGCONFIG += gsettings-qt \ #DEFINES += QT_DEPRECATED_WARNINGS SOURCES += \ + blacklistpage.cpp \ + blacklistitem.cpp \ + connectdevpage.cpp \ + connectdevlistitem.cpp \ mobilehotspot.cpp \ mobilehotspotwidget.cpp HEADERS += \ + blacklistpage.h \ + blacklistitem.h \ + connectdevpage.h \ + connectdevlistitem.h \ mobilehotspot.h \ mobilehotspotwidget.h \ libukcc_global.h @@ -40,4 +48,6 @@ INSTALLS += target \ TRANSLATIONS += \ translations/zh_CN.ts \ translations/tr.ts \ - translations/bo.ts + translations/bo.ts\ + translations/bo_CN.ts \ + translations/en_US.ts diff --git a/plugins/mobilehotspot/mobilehotspotwidget.cpp b/plugins/mobilehotspot/mobilehotspotwidget.cpp index 0b3fc081..a9fcb57d 100644 --- a/plugins/mobilehotspot/mobilehotspotwidget.cpp +++ b/plugins/mobilehotspot/mobilehotspotwidget.cpp @@ -1,5 +1,25 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "mobilehotspotwidget.h" #include +#include #define LABEL_RECT 17, 0, 105, 23 #define CONTENTS_MARGINS 0, 0, 0, 0 @@ -7,16 +27,30 @@ #define FRAME_MIN_SIZE 550, 60 #define FRAME_MAX_SIZE 16777215, 16777215 #define CONTECT_FRAME_MAX_SIZE 16777215, 60 + +#define HINT_TEXT_MARGINS 8, 0, 0, 0 +#define FRAME_MIN_SIZE 550, 60 + #define LABLE_MIN_WIDTH 188 #define COMBOBOX_MIN_WIDTH 200 #define LINE_MAX_SIZE 16777215, 1 #define LINE_MIN_SIZE 0, 1 #define ICON_SIZE 24,24 +#define PASSWORD_FRAME_MIN_HIGHT 60 +#define PASSWORD_FRAME_FIX_HIGHT 80 +#define PASSWORD_FRAME_MIN_SIZE 550, 60 +#define PASSWORD_FRAME_MAX_SIZE 16777215, 86 +#define PASSWORD_ITEM_MARGINS 16, 12, 16, 14 + #define WIRELESS 1 #define AP_NAME_MAX_LENGTH 32 +#define REFRESH_MSEC 20*1000 + +#define LOG_HEAD "[MobileHotspotWidget]" + const QByteArray GSETTINGS_SCHEMA = "org.ukui.kylin-nm.switch"; const QString WIRELESS_SWITCH = "wirelessswitch"; @@ -29,7 +63,7 @@ void MobileHotspotWidget::showDesktopNotify(const QString &message) QList args; args<<(tr("ukui control center")) <<((unsigned int) 0) - <setContentsMargins(CONTENTS_MARGINS); + m_Vlayout = new QVBoxLayout(this); + m_Vlayout->setContentsMargins(CONTENTS_MARGINS); + m_Vlayout->setSpacing(0); qDBusRegisterMetaType >(); qDBusRegisterMetaType >(); @@ -49,12 +86,18 @@ MobileHotspotWidget::MobileHotspotWidget(QWidget *parent) : QWidget(parent) qDBusRegisterMetaType >>(); initUI(); + +#ifdef HOTSPOT_CONTROL + initConnectDevPage(); + initBlackListPage(); +#endif + m_switchBtn->installEventFilter(this); m_interface = new QDBusInterface("com.kylin.network", "/com/kylin/network", "com.kylin.network", QDBusConnection::sessionBus()); if(!m_interface->isValid()) { - qDebug() << "dbus interface com.kylin.network is invaild"; + qDebug() << LOG_HEAD << "dbus interface com.kylin.network is invaild"; m_switchBtn->setChecked(false); setUiEnabled(false); } @@ -66,15 +109,30 @@ MobileHotspotWidget::MobileHotspotWidget(QWidget *parent) : QWidget(parent) initInterfaceInfo(); getApInfo(); +#ifdef HOTSPOT_CONTROL + initNmDbus(); +#endif + + this->setLayout(m_Vlayout); + m_Vlayout->addStretch(); + connect(m_switchBtn, &KSwitchButton::stateChanged, this, &MobileHotspotWidget::setUiEnabled); connect(m_interfaceComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, [=]() { m_interfaceName = m_interfaceComboBox->currentText(); updateBandCombox(); }); + +#ifdef HOTSPOT_CONTROL + m_connectDevPage->refreshStalist(); + m_blacklistPage->refreshBlacklist(); +#endif + this->update(); } MobileHotspotWidget::~MobileHotspotWidget() { + deleteActivePathInterface(); + deleteSettingPathInterface(); delete m_interface; } @@ -84,8 +142,9 @@ bool MobileHotspotWidget::eventFilter(QObject *watched, QEvent *event) return true; } - if (event->type() == QEvent::MouseButtonRelease) { - if (watched == m_switchBtn) { + + if (watched == m_switchBtn) { + if (event->type() == QEvent::MouseButtonRelease) { if (!m_interface->isValid()) { return true; } @@ -94,12 +153,19 @@ bool MobileHotspotWidget::eventFilter(QObject *watched, QEvent *event) return true; } if (m_switchBtn->isChecked()) { - showDesktopNotify(tr("start to close hotspot")); +// showDesktopNotify(tr("start to close hotspot")); QDBusReply reply = m_interface->call("deactiveWirelessAp", m_apNameLine->text(), m_uuid); if (!reply.isValid()) { - qDebug() << "[MobileHotspotWidget] call deactiveWirelessAp failed "; + qDebug() << LOG_HEAD << "call deactiveWirelessAp failed "; return true; } +#ifdef HOTSPOT_CONTROL + deleteActivePathInterface(); + m_connectDevPage->setInterface(nullptr); + m_connectDevPage->refreshStalist(); + m_blacklistPage->refreshBlacklist(); +#endif + this->update(); } else { if (m_apNameLine->text().isEmpty() || m_interfaceName.isEmpty()) { @@ -107,17 +173,17 @@ bool MobileHotspotWidget::eventFilter(QObject *watched, QEvent *event) return true; } if (m_pwdNameLine->text().length() < 8) { - showDesktopNotify(tr("can not create hotspot with password length less than eight!")); +// showDesktopNotify(tr("can not create hotspot with password length less than eight!")); return true; } - showDesktopNotify(tr("start to open hotspot ") + m_apNameLine->text()); +// showDesktopNotify(tr("start to open hotspot ") + m_apNameLine->text()); QDBusReply reply = m_interface->call("activeWirelessAp", - m_apNameLine->text(), - m_pwdNameLine->text(), - m_freqBandComboBox->currentText(), - m_interfaceComboBox->currentText()); + m_apNameLine->text(), + m_pwdNameLine->text(), + m_freqBandComboBox->currentText(), + m_interfaceComboBox->currentText()); if (!reply.isValid()) { - qDebug() << "[MobileHotspotWidget] call deactiveWirelessAp failed "; + qDebug() << LOG_HEAD << "call activeWirelessAp failed "; return true; } } @@ -132,15 +198,28 @@ void MobileHotspotWidget::paintEvent(QPaintEvent *event) QWidget::paintEvent(event); } +void MobileHotspotWidget::resetFrameSize() +{ + int height = 0; + for (int i = 0; i < m_hotspotFrame->layout()->count(); i ++) { + QWidget *w = m_hotspotFrame->layout()->itemAt(i)->widget(); + if (w != nullptr && !w->isHidden()) { + height += w->height(); + } + } + m_hotspotFrame->setFixedHeight(height); +} + void MobileHotspotWidget::initUI() { - QFrame *hotspotFrame = new QFrame(this); - hotspotFrame->setMinimumSize(FRAME_MIN_SIZE); - hotspotFrame->setMaximumSize(FRAME_MAX_SIZE); - hotspotFrame->setFrameShape(QFrame::Box); + m_hotspotFrame = new QFrame(this); + m_hotspotFrame->setMinimumSize(FRAME_MIN_SIZE); + m_hotspotFrame->setMaximumSize(FRAME_MAX_SIZE); + m_hotspotFrame->setFrameShape(QFrame::Box); - QVBoxLayout *hotspotLyt = new QVBoxLayout(hotspotFrame); + QVBoxLayout *hotspotLyt = new QVBoxLayout(this); hotspotLyt->setContentsMargins(0, 0, 0, 0); + m_hotspotFrame->setLayout(hotspotLyt); m_hotspotTitleLabel = new TitleLabel(this); m_hotspotTitleLabel->setText(tr("Hotspot")); @@ -156,7 +235,6 @@ void MobileHotspotWidget::initUI() pwdAndfreqBandLine = myLine(); freqBandAndInterfaceLine = myLine(); - /* add widget */ hotspotLyt->addWidget(m_switchFrame); hotspotLyt->addWidget(switchAndApNameLine); hotspotLyt->addWidget(m_ApNameFrame); @@ -168,10 +246,12 @@ void MobileHotspotWidget::initUI() hotspotLyt->addWidget(m_interfaceFrame); hotspotLyt->setSpacing(0); - mVlayout->addWidget(m_hotspotTitleLabel); - mVlayout->setSpacing(8); - mVlayout->addWidget(hotspotFrame); - mVlayout->addStretch(); + resetFrameSize(); + + m_Vlayout->addWidget(m_hotspotTitleLabel); + m_Vlayout->addSpacing(8); + m_Vlayout->addWidget(m_hotspotFrame); + } void MobileHotspotWidget::initDbusConnect() @@ -182,18 +262,20 @@ void MobileHotspotWidget::initDbusConnect() connect(m_interface,SIGNAL(deviceStatusChanged()), this, SLOT(onDeviceStatusChanged()), Qt::QueuedConnection); connect(m_interface,SIGNAL(deviceNameChanged(QString, QString, int)), this, SLOT(onDeviceNameChanged(QString, QString, int)), Qt::QueuedConnection); connect(m_interface,SIGNAL(hotspotDeactivated(QString, QString)), this, SLOT(onHotspotDeactivated(QString, QString)), Qt::QueuedConnection); - connect(m_interface,SIGNAL(hotspotActivated(QString, QString, QString)), this, SLOT(onHotspotActivated(QString, QString, QString)), Qt::QueuedConnection); + + connect(m_interface,SIGNAL(hotspotActivated(QString, QString, QString, QString, QString)), this, SLOT(onHotspotActivated(QString, QString, QString, QString, QString)), Qt::QueuedConnection); connect(m_interface, SIGNAL(wlanactiveConnectionStateChanged(QString, QString, QString, int)), this, SLOT(onActiveConnectionChanged(QString, QString, QString, int)), Qt::QueuedConnection); + + connect(m_interface, SIGNAL(wirelessSwitchBtnChanged(bool)), this, SLOT(onWirelessBtnChanged(bool)), Qt::QueuedConnection); } - if (QGSettings::isSchemaInstalled(GSETTINGS_SCHEMA)) { - m_switchGsettings = new QGSettings(GSETTINGS_SCHEMA); - onGsettingChanged(WIRELESS_SWITCH); - connect(m_switchGsettings, &QGSettings::changed, this, &MobileHotspotWidget::onGsettingChanged, Qt::QueuedConnection); - } connect(m_apNameLine, &QLineEdit::textEdited, this, &MobileHotspotWidget::onApLineEditTextEdit); +#ifdef HOTSPOT_CONTROL + connect(m_connectDevPage, SIGNAL(setStaIntoBlacklist(QString, QString)), m_blacklistPage, SLOT(onsetStaIntoBlacklist(QString, QString))); +#endif + connect(m_pwdNameLine, SIGNAL(textChanged(QString)), this, SLOT(onPwdTextChanged())); } void MobileHotspotWidget::onApLineEditTextEdit(QString text) @@ -211,6 +293,18 @@ void MobileHotspotWidget::onApLineEditTextEdit(QString text) m_apNameLine->setText(text.left(i)); } +void MobileHotspotWidget::onPwdTextChanged() +{ + if (m_pwdNameLine->text().length() < 8) { + m_passwordFrame->setFixedHeight(PASSWORD_FRAME_FIX_HIGHT); + m_pwdHintLabel->show(); + } else { + m_passwordFrame->setFixedHeight(PASSWORD_FRAME_MIN_HIGHT); + m_pwdHintLabel->hide(); + } + resetFrameSize(); + this->update(); +} void MobileHotspotWidget::onActiveConnectionChanged(QString deviceName, QString ssid, QString uuid, int status) { @@ -222,29 +316,14 @@ void MobileHotspotWidget::onActiveConnectionChanged(QString deviceName, QString } } -void MobileHotspotWidget::onGsettingChanged(const QString &key) +void MobileHotspotWidget::onWirelessBtnChanged(bool state) { - if (key == WIRELESS_SWITCH) { - bool status = m_switchGsettings->get(WIRELESS_SWITCH).toBool(); - if (!status) { -// if (m_switchBtn->isChecked()) { -// if(m_interface->isValid()) { -// QDBusReply reply = m_interface->call("deactiveWirelessAp", -// m_apNameLine->text(), -// m_pwdNameLine->text(), -// m_interfaceComboBox->currentText()); -// if (!reply.isValid()) { -// qDebug() << "[MobileHotspotWidget] call deactiveWirelessAp failed "; -// return true; -// } -// } -// } - m_switchBtn->setChecked(status); - m_uuid.clear(); - m_switchBtn->setCheckable(false); - } else { - m_switchBtn->setCheckable(true); - } + if (!state) { + m_switchBtn->setChecked(state); + m_uuid.clear(); + m_switchBtn->setCheckable(false); + } else { + m_switchBtn->setCheckable(true); } } @@ -257,7 +336,7 @@ void MobileHotspotWidget::initInterfaceInfo() QDBusReply > reply = m_interface->call("getDeviceListAndEnabled",WIRELESS); if (!reply.isValid()) { - qDebug()<<"execute dbus method 'getDeviceListAndEnabled' is invalid in func initInterfaceInfo()"; + qDebug() << LOG_HEAD <<"execute dbus method 'getDeviceListAndEnabled' is invalid in func initInterfaceInfo()"; setWidgetHidden(true); return; } @@ -265,7 +344,7 @@ void MobileHotspotWidget::initInterfaceInfo() QDBusReply > capReply = m_interface->call("getWirelessDeviceCap"); if (!capReply.isValid()) { - qDebug()<<"execute dbus method 'getWirelessDeviceCap' is invalid in func initInterfaceInfo()" <setCheckable(false); } else { @@ -292,7 +371,7 @@ void MobileHotspotWidget::initInterfaceInfo() updateBandCombox(); } } else { - qDebug() << "no useable wireless device"; + qDebug() << LOG_HEAD << "no useable wireless device"; setWidgetHidden(true); } } @@ -305,22 +384,22 @@ void MobileHotspotWidget::getApInfo() } if (m_interfaceComboBox->count() <= 0) { - m_switchBtn->setChecked(false); - setWidgetHidden(true); - qWarning() << "getApInfo but interface is empty"; - return; - } + m_switchBtn->setChecked(false); + setWidgetHidden(true); + qWarning() << LOG_HEAD << "getApInfo but interface is empty"; + return; + } QDBusReply reply = m_interface->call("getStoredApInfo"); if (!reply.isValid()) { - qDebug()<<"execute dbus method 'getStoredApInfo' is invalid in func getObjectPath()"; + qDebug() << LOG_HEAD <<"execute dbus method 'getStoredApInfo' is invalid in func getObjectPath()"; } QStringList apInfo = reply.value(); if (apInfo.isEmpty()) { - qDebug() << "no stored hotspot info"; + qDebug() << LOG_HEAD << "no stored hotspot info"; m_apNameLine->setText(m_hostName); m_pwdNameLine->setText("12345678"); return; @@ -338,9 +417,10 @@ void MobileHotspotWidget::getApInfo() } else { m_switchBtn->setChecked(false); setUiEnabled(false); + m_uuid = apInfo.at(4); } } else { - qDebug() << "no such interface " << apInfo.at(2); + qDebug() << LOG_HEAD << "no such interface " << apInfo.at(2); } } } @@ -353,7 +433,7 @@ void MobileHotspotWidget::setSwitchFrame() m_switchFrame->setMinimumSize(FRAME_MIN_SIZE); m_switchFrame->setMaximumSize(CONTECT_FRAME_MAX_SIZE); - QHBoxLayout *switchLayout = new QHBoxLayout(); + QHBoxLayout *switchLayout = new QHBoxLayout(m_switchFrame); m_switchLabel = new QLabel(tr("Open"), this); m_switchLabel->setMinimumWidth(LABLE_MIN_WIDTH); @@ -374,7 +454,7 @@ void MobileHotspotWidget::setApNameFrame() m_ApNameFrame->setMinimumSize(FRAME_MIN_SIZE); m_ApNameFrame->setMaximumSize(CONTECT_FRAME_MAX_SIZE); - QHBoxLayout *apNameHLayout = new QHBoxLayout(); + QHBoxLayout *apNameHLayout = new QHBoxLayout(m_ApNameFrame); m_apNameLabel = new QLabel(tr("Wi-Fi Name"), this); m_apNameLabel->setMinimumWidth(LABLE_MIN_WIDTH); @@ -394,22 +474,38 @@ void MobileHotspotWidget::setPasswordFrame() /* Password */ m_passwordFrame = new QFrame(this); m_passwordFrame->setFrameShape(QFrame::Shape::NoFrame); - m_passwordFrame->setMinimumSize(FRAME_MIN_SIZE); - m_passwordFrame->setMaximumSize(CONTECT_FRAME_MAX_SIZE); - - QHBoxLayout *passwordHLayout = new QHBoxLayout(); + m_passwordFrame->setMinimumSize(PASSWORD_FRAME_MIN_SIZE); + m_passwordFrame->setMaximumSize(PASSWORD_FRAME_MAX_SIZE); m_pwdLabel = new QLabel(tr("Password"), this); m_pwdLabel->setMinimumWidth(LABLE_MIN_WIDTH); m_pwdNameLine = new KPasswordEdit(this); m_pwdNameLine->setClearButtonEnabled(false);//禁用ClearBtn按钮X m_pwdNameLine->setMinimumWidth(COMBOBOX_MIN_WIDTH); - passwordHLayout->setContentsMargins(ITEM_MARGINS); - passwordHLayout->setSpacing(0); - passwordHLayout->addWidget(m_pwdLabel); - passwordHLayout->addWidget(m_pwdNameLine); + m_pwdHintLabel= new QLabel(this); + m_pwdHintLabel->setFixedHeight(20); + m_pwdHintLabel->setContentsMargins(HINT_TEXT_MARGINS); - m_passwordFrame->setLayout(passwordHLayout); + QPalette hintTextColor; + hintTextColor.setColor(QPalette::WindowText, Qt::red); + m_pwdHintLabel->setPalette(hintTextColor); + m_pwdHintLabel->setText(tr("Contains at least 8 characters")); //至少包含8个字符 + + QWidget *pwdInputWidget = new QWidget(m_passwordFrame); + QVBoxLayout *pwdInputVLayout = new QVBoxLayout(pwdInputWidget); + pwdInputVLayout->setContentsMargins(CONTENTS_MARGINS); + pwdInputVLayout->setSpacing(0); + pwdInputVLayout->addWidget(m_pwdNameLine); + pwdInputVLayout->addWidget(m_pwdHintLabel); + + QFormLayout *pwdLayout = new QFormLayout(m_passwordFrame); + pwdLayout->setContentsMargins(PASSWORD_ITEM_MARGINS); + pwdLayout->setSpacing(0); + pwdLayout->addRow(m_pwdLabel, pwdInputWidget); + + m_passwordFrame->setLayout(pwdLayout); + + m_pwdNameLine->installEventFilter(this); } void MobileHotspotWidget::setFreqBandFrame() @@ -420,7 +516,7 @@ void MobileHotspotWidget::setFreqBandFrame() m_freqBandFrame->setMinimumSize(FRAME_MIN_SIZE); m_freqBandFrame->setMaximumSize(CONTECT_FRAME_MAX_SIZE); - QHBoxLayout *freqBandHLayout = new QHBoxLayout(); + QHBoxLayout *freqBandHLayout = new QHBoxLayout(m_freqBandFrame); m_freqBandLabel = new QLabel(tr("Frequency band"), this); m_freqBandLabel->setMinimumWidth(LABLE_MIN_WIDTH); @@ -428,8 +524,8 @@ void MobileHotspotWidget::setFreqBandFrame() m_freqBandComboBox->setInsertPolicy(QComboBox::NoInsert); m_freqBandComboBox->setMinimumWidth(COMBOBOX_MIN_WIDTH); m_freqBandComboBox->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed); - m_freqBandComboBox->addItem("2.4Ghz"); - m_freqBandComboBox->addItem("5Ghz"); + m_freqBandComboBox->addItem("2.4GHz"); + m_freqBandComboBox->addItem("5GHz"); freqBandHLayout->setContentsMargins(ITEM_MARGINS); freqBandHLayout->setSpacing(0); freqBandHLayout->addWidget(m_freqBandLabel); @@ -446,7 +542,7 @@ void MobileHotspotWidget::setInterFaceFrame() m_interfaceFrame->setMinimumSize(FRAME_MIN_SIZE); m_interfaceFrame->setMaximumSize(CONTECT_FRAME_MAX_SIZE); - QHBoxLayout *interfaceHLayout = new QHBoxLayout; + QHBoxLayout *interfaceHLayout = new QHBoxLayout(m_interfaceFrame); m_interfaceLabel = new QLabel(tr("Net card"), this); m_interfaceLabel->setMinimumWidth(LABLE_MIN_WIDTH); @@ -513,12 +609,26 @@ void MobileHotspotWidget::onHotspotDeactivated(QString devName, QString ssid) } //热点连接 -void MobileHotspotWidget::onHotspotActivated(QString devName, QString ssid, QString uuid) +void MobileHotspotWidget::onHotspotActivated(QString devName, QString ssid, QString uuid, QString activePath, QString settingPath) { - qDebug() << "onHotspotActivated" <isChecked()) { return; } +#ifdef HOTSPOT_CONTROL + if (activePath != nullptr) { + deleteActivePathInterface(); + initActivePathInterface(activePath); + } + if (settingPath != nullptr) { + deleteSettingPathInterface(); + initSettingPathInterface(settingPath); + } + + m_connectDevPage->refreshStalist(); + m_blacklistPage->refreshBlacklist(); +#endif + this->update(); if (devName == m_interfaceComboBox->currentText() && ssid == m_apNameLine->text()) { m_switchBtn->setChecked(true); @@ -604,9 +714,11 @@ void MobileHotspotWidget::setWidgetHidden(bool isHidden) m_uuid = ""; } else { m_switchBtn->setCheckable(true); - onGsettingChanged(WIRELESS_SWITCH); + QDBusReply reply = m_interface->call("getWirelessSwitchBtnState"); + bool state = reply.value(); + onWirelessBtnChanged(state); } - + resetFrameSize(); } void MobileHotspotWidget::updateBandCombox() @@ -620,10 +732,10 @@ void MobileHotspotWidget::updateBandCombox() } QMap devCapMap = capReply.value(); if (devCapMap[m_interfaceName] & 0x02) { - m_freqBandComboBox->addItem("2.4Ghz"); + m_freqBandComboBox->addItem("2.4GHz"); } if (devCapMap[m_interfaceName] & 0x04) { - m_freqBandComboBox->addItem("5Ghz"); + m_freqBandComboBox->addItem("5GHz"); } } @@ -655,3 +767,120 @@ QString MobileHotspotWidget::getHostName() } return "default"; } + +QString MobileHotspotWidget::getSettingPathByUuid() +{ + if (!m_interface->isValid()) { + return nullptr; + } + + QDBusReply reply = m_interface->call("getApConnectionPath", m_uuid); + if (!reply.isValid()) { + return nullptr; + } + + return reply.value(); +} + +QString MobileHotspotWidget::getActivePathByUuid() +{ + if (!m_interface->isValid()) { + return nullptr; + } + + QDBusReply reply = m_interface->call("getActiveConnectionPath", m_uuid); + if (!reply.isValid()) { + return nullptr; + } + return reply.value(); +} + +void MobileHotspotWidget::initNmDbus() +{ + QString activePath = getActivePathByUuid(); + QString settingPath = getSettingPathByUuid(); + + if (activePath != nullptr) { + m_activePathInterface = new QDBusInterface("org.freedesktop.NetworkManager", + activePath, + "org.freedesktop.NetworkManager.Connection.Active", + QDBusConnection::systemBus()); + if (m_activePathInterface->isValid()) { + m_connectDevPage->setInterface(m_activePathInterface); + + connect(m_activePathInterface, SIGNAL(NewStaConnected(bool, QString, QString)), m_connectDevPage, SLOT(onStaDevAdded(bool, QString, QString)), Qt::QueuedConnection); + connect(m_activePathInterface, SIGNAL(StaRemoved(bool, QString, QString)), m_connectDevPage, SLOT(onStaDevRemoved(bool, QString, QString)), Qt::QueuedConnection); + } + } + + if (settingPath != nullptr) { + m_settingPathInterface = new QDBusInterface("org.freedesktop.NetworkManager", + settingPath, + "org.freedesktop.NetworkManager.Settings.Connection", + QDBusConnection::systemBus()); + if (m_settingPathInterface->isValid()) { + m_blacklistPage->setInterface(m_settingPathInterface); + } + } +} + +void MobileHotspotWidget::initActivePathInterface(QString path) +{ + if (path != nullptr){ + m_activePathInterface = new QDBusInterface("org.freedesktop.NetworkManager", + path, + "org.freedesktop.NetworkManager.Connection.Active", + QDBusConnection::systemBus()); + if (m_activePathInterface->isValid()) { + m_connectDevPage->setInterface(m_activePathInterface); + + connect(m_activePathInterface, SIGNAL(NewStaConnected(bool, QString, QString)), m_connectDevPage, SLOT(onStaDevAdded(bool, QString, QString)), Qt::QueuedConnection); + connect(m_activePathInterface, SIGNAL(StaRemoved(bool, QString, QString)), m_connectDevPage, SLOT(onStaDevRemoved(bool, QString, QString)), Qt::QueuedConnection); + } + } +} + +void MobileHotspotWidget::deleteActivePathInterface() +{ + if (m_activePathInterface != nullptr){ + disconnect(m_activePathInterface); + delete m_activePathInterface; + m_activePathInterface = nullptr; + } +} + +void MobileHotspotWidget::initSettingPathInterface(QString path) +{ + if (path != nullptr){ + m_settingPathInterface = new QDBusInterface("org.freedesktop.NetworkManager", + path, + "org.freedesktop.NetworkManager.Settings.Connection", + QDBusConnection::systemBus()); + if (m_settingPathInterface->isValid()) { + m_blacklistPage->setInterface(m_settingPathInterface); + } + } +} + +void MobileHotspotWidget::deleteSettingPathInterface() +{ + if (m_settingPathInterface != nullptr){ + disconnect(m_settingPathInterface); + delete m_settingPathInterface; + m_settingPathInterface = nullptr; + } +} + +void MobileHotspotWidget::initConnectDevPage() +{ + m_connectDevPage = new ConnectdevPage(this); + m_Vlayout->addSpacing(32); + m_Vlayout->addWidget(m_connectDevPage); +} + +void MobileHotspotWidget::initBlackListPage() +{ + m_blacklistPage = new BlacklistPage(this); + m_Vlayout->addSpacing(32); + m_Vlayout->addWidget(m_blacklistPage); +} diff --git a/plugins/mobilehotspot/mobilehotspotwidget.h b/plugins/mobilehotspot/mobilehotspotwidget.h index 8116811d..99e67bfe 100644 --- a/plugins/mobilehotspot/mobilehotspotwidget.h +++ b/plugins/mobilehotspot/mobilehotspotwidget.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef MOBILEHOTSPOTWIDGET_H #define MOBILEHOTSPOTWIDGET_H @@ -11,18 +30,22 @@ #include #include - +#include #include #include #include #include #include +#include #include "titlelabel.h" #include "kwidget.h" #include "kswitchbutton.h" #include "kpasswordedit.h" +#include "connectdevlistitem.h" +#include "blacklistpage.h" +#include "connectdevpage.h" using namespace kdk; @@ -34,6 +57,7 @@ public: ~MobileHotspotWidget(); private: + QFrame *m_hotspotFrame = nullptr; QFrame *m_switchFrame = nullptr; //开关 QFrame *m_ApNameFrame = nullptr; //wifi名称 QFrame *m_passwordFrame = nullptr; //密码 @@ -46,6 +70,7 @@ private: QLabel *m_switchLabel; QLabel *m_apNameLabel; QLabel *m_pwdLabel; + QLabel *m_pwdHintLabel; QLabel *m_freqBandLabel; QLabel *m_interfaceLabel; @@ -54,7 +79,7 @@ private: QFrame *pwdAndfreqBandLine; QFrame *freqBandAndInterfaceLine; - QVBoxLayout *mVlayout; + QVBoxLayout *m_Vlayout; QLineEdit *m_apNameLine; KPasswordEdit *m_pwdNameLine; @@ -71,6 +96,7 @@ private: QString m_uuid = ""; QString m_hostName = ""; + void resetFrameSize(); void initUI(); void initDbusConnect(); void initInterfaceInfo(); @@ -96,6 +122,21 @@ private: QFrame* myLine(); + QDBusInterface *m_activePathInterface = nullptr; + QDBusInterface *m_settingPathInterface = nullptr; + + ConnectdevPage * m_connectDevPage = nullptr; + BlacklistPage *m_blacklistPage = nullptr; + + QString getActivePathByUuid(); + QString getSettingPathByUuid(); + void initNmDbus(); + void initActivePathInterface(QString path); + void deleteActivePathInterface(); + void initSettingPathInterface(QString path); + void deleteSettingPathInterface(); + void initConnectDevPage(); + void initBlackListPage(); signals: private slots: @@ -107,14 +148,15 @@ private slots: //热点断开 void onHotspotDeactivated(QString devName, QString ssid); //热点连接 - void onHotspotActivated(QString devName, QString ssid, QString uuid); + void onHotspotActivated(QString devName, QString ssid, QString uuid, QString activePath, QString settingPath); - void onGsettingChanged(const QString &key); + void onWirelessBtnChanged(bool state); void onActiveConnectionChanged(QString deviceName, QString ssid, QString uuid, int status); void onApLineEditTextEdit(QString text); + void onPwdTextChanged(); }; #endif // MOBILEHOTSPOTWIDGET_H diff --git a/plugins/mobilehotspot/translations/bo.ts b/plugins/mobilehotspot/translations/bo.ts index fad9d3e2..2c1f8b3d 100644 --- a/plugins/mobilehotspot/translations/bo.ts +++ b/plugins/mobilehotspot/translations/bo.ts @@ -1,6 +1,38 @@ + + BlacklistItem + + + Remove + + + + + BlacklistPage + + + Blacklist + + + + + ConnectDevListItem + + + drag into blacklist + + + + + ConnectdevPage + + + Connect device + + + MobileHotspot @@ -24,79 +56,69 @@ MobileHotspotWidget - + ukui control center - + ukui control center desktop message - + wirless switch is close or no wireless device - - start to close hotspot - - - - + hotpots name or device is invalid - - can not create hotspot with password length less than eight! + + Contains at least 8 characters - - start to open hotspot - - - - + Hotspot - - + + hotspot already close - + Open - + Wi-Fi Name - + Password - + Frequency band - + Net card - - + + hotspot already open diff --git a/plugins/mobilehotspot/translations/bo_CN.qm b/plugins/mobilehotspot/translations/bo_CN.qm new file mode 100644 index 00000000..b9da303b Binary files /dev/null and b/plugins/mobilehotspot/translations/bo_CN.qm differ diff --git a/plugins/mobilehotspot/translations/bo_CN.ts b/plugins/mobilehotspot/translations/bo_CN.ts new file mode 100644 index 00000000..f2f82810 --- /dev/null +++ b/plugins/mobilehotspot/translations/bo_CN.ts @@ -0,0 +1,138 @@ + + + + + BlacklistItem + + + Remove + སྤོ་སྐྱོད་བྱས་པ། + + + + BlacklistPage + + + Blacklist + སྒྲིག་ཆས་ཀྱི་མིང་ཐོ་ནག་པོ། + + + + ConnectDevListItem + + + drag into blacklist + མིང་ཐོ་ནག་པོའི་ཁ་སྣོན་རྒྱག་པ། + + + + ConnectdevPage + + + Connect device + འབྲེལ་མཐུད་སྒྲིག་ཆས། + + + + MobileHotspot + + + MobileHotspot + སྒུལ་བདེའི་ཧའོ་ཚི་ཀུང་སི། + + + + mobilehotspot + སྒུལ་བདེའི་འཕྲུལ་ཆས། + /mobilehotspot/mobilehotspot + + + + mobilehotspot open + སྒུལ་བདེའི་འཕྲུལ་ཆས་ཀྱི་སྒོ་ཕྱེ་བ། + /mobilehotspot/mobilehotspot open + + + + MobileHotspotWidget + + + ukui control center + ཝུའུ་ཁི་ལན་གྱི་ཚོད་འཛིན་ལྟེ་གནས། + + + + ukui control center desktop message + ukui ཚོད་འཛིན་ལྟེ་གནས་ཀྱི་ཅོག་ངོས་ཆ་འཕྲིན། + + + + wirless switch is close or no wireless device + སྐུད་མེད་གློག་སྒོ་རྒྱག་པའམ་ཡང་ན་སྐུད་མེད་སྒྲིག་ཆས་མེད་པ། + + + start to close hotspot + སྒོ་རྒྱག་འགོ་བརྩམས། + + + + hotpots name or device is invalid + ཚ་བ་ཆེ་བའི་མིང་ངམ་སྒྲིག་ཆས་ལ་ནུས་པ་མེད། + + + can not create hotspot with password length less than eight! + གསང་གྲངས་ཀྱི་རིང་ཚད་ནི་གླེང་མང་བའི་གནད་དོན་བརྒྱད་ལས་ཆུང་བ་བྱེད་མི་རུང་།! + + + start to open hotspot + ཀུན་གྱིས་དོ་སྣང་བྱེད་ཡུལ་གསར་སྐྲུན་བྱེད་འགོ་ + + + + Contains at least 8 characters + མ་མཐར་ཡང་ཡིག་རྟགས་བརྒྱད་འདུས་ཡོད། + + + + Hotspot + ཚ་བ་ཆེ་བ། + + + + + hotspot already close + ཚ་བ་ཆེ་བའི་གནད་དོན་ཐག་ཉེ་རུ་སོང་ཡོད། + + + + Open + སྒོ་ཕྱེ་བ། + + + + Wi-Fi Name + Wi-Fiཡི་མིང་། + + + + Password + གསང་གྲངས། + + + + Frequency band + ཐེངས་གྲངས་ཀྱི་རོལ་ཆའི་རུ་ཁག + + + + Net card + དྲ་རྒྱའི་བྱང་བུ། + + + + + hotspot already open + ཚ་བ་ཆེ་བའི་གནད་དོན་དེ་སྒོ་ཕྱེ་ཟིན། + + + diff --git a/plugins/mobilehotspot/translations/en_US.ts b/plugins/mobilehotspot/translations/en_US.ts new file mode 100644 index 00000000..bb4f55f3 --- /dev/null +++ b/plugins/mobilehotspot/translations/en_US.ts @@ -0,0 +1,126 @@ + + + + + BlacklistItem + + + Remove + Remove + + + + BlacklistPage + + + Blacklist + Blacklist + + + + ConnectDevListItem + + + drag into blacklist + drag into blacklist + + + + ConnectdevPage + + + Connect device + Connect device + + + + MobileHotspot + + + MobileHotspot + MobileHotspot + + + + mobilehotspot + mobilehotspot + /mobilehotspot/mobilehotspot + + + + mobilehotspot open + mobilehotspot open + /mobilehotspot/mobilehotspot open + + + + MobileHotspotWidget + + + ukui control center + ukui control center + + + + ukui control center desktop message + ukui control center desktop message + + + + wirless switch is close or no wireless device + wirless switch is close or no wireless device + + + + hotpots name or device is invalid + hotpots name or device is invalid + + + + Hotspot + Hotspot + + + + + hotspot already close + hotspot already close + + + + Open + Open + + + + Wi-Fi Name + Wi-Fi Name + + + + Password + Password + + + + Contains at least 8 characters + Contains at least 8 characters + + + + Frequency band + Frequency band + + + + Net card + Net card + + + + + hotspot already open + hotspot already open + + + diff --git a/plugins/mobilehotspot/translations/tr.ts b/plugins/mobilehotspot/translations/tr.ts index fad9d3e2..2c1f8b3d 100644 --- a/plugins/mobilehotspot/translations/tr.ts +++ b/plugins/mobilehotspot/translations/tr.ts @@ -1,6 +1,38 @@ + + BlacklistItem + + + Remove + + + + + BlacklistPage + + + Blacklist + + + + + ConnectDevListItem + + + drag into blacklist + + + + + ConnectdevPage + + + Connect device + + + MobileHotspot @@ -24,79 +56,69 @@ MobileHotspotWidget - + ukui control center - + ukui control center desktop message - + wirless switch is close or no wireless device - - start to close hotspot - - - - + hotpots name or device is invalid - - can not create hotspot with password length less than eight! + + Contains at least 8 characters - - start to open hotspot - - - - + Hotspot - - + + hotspot already close - + Open - + Wi-Fi Name - + Password - + Frequency band - + Net card - - + + hotspot already open diff --git a/plugins/mobilehotspot/translations/zh_CN.qm b/plugins/mobilehotspot/translations/zh_CN.qm index 52e6c4f8..1b67cfd1 100644 Binary files a/plugins/mobilehotspot/translations/zh_CN.qm and b/plugins/mobilehotspot/translations/zh_CN.qm differ diff --git a/plugins/mobilehotspot/translations/zh_CN.ts b/plugins/mobilehotspot/translations/zh_CN.ts index 0867a0ec..a9fb2288 100644 --- a/plugins/mobilehotspot/translations/zh_CN.ts +++ b/plugins/mobilehotspot/translations/zh_CN.ts @@ -1,6 +1,38 @@ + + BlacklistItem + + + Remove + 移出 + + + + BlacklistPage + + + Blacklist + 设备黑名单 + + + + ConnectDevListItem + + + drag into blacklist + 添加进黑名单 + + + + ConnectdevPage + + + Connect device + 连接设备 + + MobileHotspot @@ -24,79 +56,81 @@ MobileHotspotWidget - + ukui control center 控制面板 - + ukui control center desktop message 控制面板桌面通知 - + wirless switch is close or no wireless device 无线开关已关闭或不存在有热点功能的无线网卡 - start to close hotspot - 开始关闭热点 + 开始关闭热点 - + hotpots name or device is invalid 热点名称或设备错误 - can not create hotspot with password length less than eight! - 不能创建密码长度小于八位的热点! + 不能创建密码长度小于八位的热点! - start to open hotspot - 开始创建热点 + 开始创建热点 - + + Contains at least 8 characters + 至少包含8个字符 + + + Hotspot 移动热点 - - + + hotspot already close 热点已关闭 - + Open 开启 - + Wi-Fi Name Wi-Fi名称 - + Password 网络密码 - + Frequency band 网络频带 - + Net card 共享网卡端口 - - + + hotspot already open 热点已开启 diff --git a/plugins/netconnect/deviceframe.cpp b/plugins/netconnect/deviceframe.cpp index 88f8fc0e..a90e9f67 100644 --- a/plugins/netconnect/deviceframe.cpp +++ b/plugins/netconnect/deviceframe.cpp @@ -1,8 +1,26 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "deviceframe.h" #include -#include -#define LAYOUT_MARGINS 18,0,24,0 +#define LAYOUT_MARGINS 16,0,16,0 #define FRAME_HEIGHT 58 #define RADIUS 6.0 @@ -17,6 +35,7 @@ DeviceFrame::DeviceFrame(QString devName, QWidget *parent) : QFrame(parent) deviceLabel = new QLabel(this); dropDownLabel = new DrownLabel(devName, this); deviceSwitch = new KSwitchButton(this); + deviceSwitch->installEventFilter(this); deviceLayout->addWidget(deviceLabel); deviceLayout->addStretch(); @@ -24,9 +43,15 @@ DeviceFrame::DeviceFrame(QString devName, QWidget *parent) : QFrame(parent) deviceLayout->addWidget(deviceSwitch); } -DeviceFrame::~DeviceFrame() +bool DeviceFrame::eventFilter(QObject *w,QEvent *e) { - + if (w == deviceSwitch) { + if (e->type() == QEvent::MouseButtonPress) { + emit deviceSwitchClicked(!deviceSwitch->isChecked()); + return true; + } + } + return QFrame::eventFilter(w, e); } void DeviceFrame::paintEvent(QPaintEvent *event) diff --git a/plugins/netconnect/deviceframe.h b/plugins/netconnect/deviceframe.h index 2807f067..9a5d0746 100644 --- a/plugins/netconnect/deviceframe.h +++ b/plugins/netconnect/deviceframe.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef DEVICEFRAME_H #define DEVICEFRAME_H #include @@ -16,9 +35,9 @@ using namespace kdk; class DeviceFrame : public QFrame { + Q_OBJECT public: DeviceFrame(QString devName, QWidget *parent = nullptr); - ~DeviceFrame(); public: QLabel * deviceLabel = nullptr; KSwitchButton * deviceSwitch = nullptr; @@ -26,11 +45,14 @@ public: protected: void paintEvent(QPaintEvent *event); + bool eventFilter(QObject *w,QEvent *e); private: bool isDropDown = false; int frameSize; +signals: + void deviceSwitchClicked(bool); }; #endif // DEVICEFRAME_H diff --git a/plugins/netconnect/itemframe.cpp b/plugins/netconnect/itemframe.cpp index 9fbea20f..17b83de7 100644 --- a/plugins/netconnect/itemframe.cpp +++ b/plugins/netconnect/itemframe.cpp @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "itemframe.h" #include @@ -30,11 +49,6 @@ ItemFrame::ItemFrame(QString devName, QWidget *parent) : QFrame(parent) connect(deviceFrame->dropDownLabel, &DrownLabel::labelClicked, this, &ItemFrame::onDrownLabelClicked); } -ItemFrame::~ItemFrame() -{ - -} - void ItemFrame::onDrownLabelClicked() { if (!deviceFrame->dropDownLabel->isChecked) { diff --git a/plugins/netconnect/itemframe.h b/plugins/netconnect/itemframe.h index 360b9e61..07aa0ee7 100644 --- a/plugins/netconnect/itemframe.h +++ b/plugins/netconnect/itemframe.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef ITEMFRAME_H #define ITEMFRAME_H #include @@ -12,7 +31,7 @@ class ItemFrame : public QFrame Q_OBJECT public: ItemFrame(QString devName, QWidget *parent = nullptr); - ~ItemFrame(); + //单设备整体layout QVBoxLayout * deviceLanLayout = nullptr; //单设备名称+下拉按钮Frame+d单设备开关 diff --git a/plugins/netconnect/lanitem.cpp b/plugins/netconnect/lanitem.cpp index f3536094..9e51efb1 100644 --- a/plugins/netconnect/lanitem.cpp +++ b/plugins/netconnect/lanitem.cpp @@ -1,4 +1,25 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "lanitem.h" +#include + #define FRAME_SPEED 150 #define LIMIT_TIME 60*1000 #define TOTAL_PAGE 8 @@ -20,9 +41,11 @@ LanItem::LanItem(bool isAcitve, QWidget *parent) iconLabel->setProperty("useIconHighlightEffect", 0x2); titileLabel = new FixLabel(this); statusLabel = new QLabel(this); + statusLabel->setProperty("useIconHighlightEffect", 0x2); statusLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); // statusLabel->setMinimumSize(36,36); - infoLabel = new InfoButton(this); + infoLabel = new GrayInfoButton(this); + //【更多】菜单 m_moreButton = new QToolButton(this); m_moreButton->setProperty("useButtonPalette", true); @@ -54,7 +77,6 @@ LanItem::LanItem(bool isAcitve, QWidget *parent) loadIcons.append(QIcon::fromTheme("ukui-loading-7-symbolic")); waitTimer = new QTimer(this); connect(waitTimer, &QTimer::timeout, this, &LanItem::updateIcon); - connect(m_connectAction, &QAction::triggered, this, &LanItem::onConnectTriggered); connect(m_deleteAction, &QAction::triggered, this, &LanItem::onDeletetTriggered); m_moreMenu->installEventFilter(this); @@ -121,12 +143,17 @@ void LanItem::onDeletetTriggered() void LanItem::paintEvent(QPaintEvent *event) { - QPalette pal = this->palette(); + QPalette pal = qApp->palette(); QPainter painter(this); painter.setRenderHint(QPainter:: Antialiasing, true); //设置渲染,启动反锯齿 painter.setPen(Qt::NoPen); - painter.setBrush(pal.color(QPalette::Base)); + painter.setBrush(this->palette().base().color()); + + QColor color = pal.color(QPalette::Button); + color.setAlphaF(0.5); + pal.setColor(QPalette::Button, color); + this->setPalette(pal); QRect rect = this->rect(); diff --git a/plugins/netconnect/lanitem.h b/plugins/netconnect/lanitem.h index e749ab5f..b27a9df2 100644 --- a/plugins/netconnect/lanitem.h +++ b/plugins/netconnect/lanitem.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef LANITEM_H #define LANITEM_H #include @@ -14,7 +33,8 @@ #include #include #include "fixlabel.h" -#include "infobutton.h" +//#include "infobutton.h" +#include "../component/AddBtn/grayinfobutton.h" class LanItem : public QPushButton { @@ -24,7 +44,7 @@ public: ~LanItem(); public: QLabel * iconLabel = nullptr; - InfoButton * infoLabel = nullptr; + GrayInfoButton * infoLabel = nullptr; FixLabel * titileLabel = nullptr; QLabel * statusLabel = nullptr; QToolButton* m_moreButton = nullptr; diff --git a/plugins/netconnect/netconnect.cpp b/plugins/netconnect/netconnect.cpp index da55d78d..32384507 100644 --- a/plugins/netconnect/netconnect.cpp +++ b/plugins/netconnect/netconnect.cpp @@ -32,7 +32,9 @@ #define ITEMHEIGH 50 #define LAN_TYPE 0 #define CONTROL_CENTER_WIFI "org.ukui.control-center.wifi.switch" - +#define KYLIN_APP_MANAGER_NAME "com.kylin.AppManager" +#define KYLIN_APP_MANAGER_PATH "/com/kylin/AppManager" +#define KYLIN_APP_MANAGER_INTERFACE "com.kylin.AppManager" const QString KLanSymbolic = "network-wired-connected-symbolic"; const QString NoNetSymbolic = "network-wired-disconnected-symbolic"; @@ -78,7 +80,7 @@ NetConnect::NetConnect() : mFirstLoad(true) { translator->load("/usr/share/kylin-nm/netconnect/" + QLocale::system().name()); QApplication::installTranslator(translator); - pluginName = tr("WiredConnect"); + pluginName = tr("LAN"); pluginType = NETWORK; } @@ -150,7 +152,7 @@ QString NetConnect::translationPath() const void NetConnect::initSearchText() { //~ contents_path /netconnect/Advanced settings" ui->detailBtn->setText(tr("Advanced settings")); - ui->titleLabel->setText(tr("Wired Network")); + ui->titleLabel->setText(tr("LAN")); //~ contents_path /netconnect/open ui->openLabel->setText(tr("open")); } @@ -168,7 +170,9 @@ bool NetConnect::eventFilter(QObject *w, QEvent *e) { if (!wiredSwitch->isCheckable()) { showDesktopNotify(tr("No ethernet device avaliable")); } else { - m_interface->call(QStringLiteral("setWiredSwitchEnable"), !wiredSwitch->isChecked()); + if (m_interface != nullptr && m_interface->isValid()) { + m_interface->call(QStringLiteral("setWiredSwitchEnable"), !wiredSwitch->isChecked()); + } return true; } } @@ -180,8 +184,10 @@ bool NetConnect::eventFilter(QObject *w, QEvent *e) { void NetConnect::initComponent() { wiredSwitch = new KSwitchButton(pluginWidget); ui->openWIifLayout->addWidget(wiredSwitch); + ui->openWIifLayout->setContentsMargins(0,0,8,0); ui->detailLayOut->setContentsMargins(MAIN_LAYOUT_MARGINS); ui->verticalLayout_3->setContentsMargins(NO_MARGINS); + ui->verticalLayout_3->setSpacing(8); ui->availableLayout->setSpacing(SPACING); ui->horizontalLayout->setContentsMargins(TOP_MARGINS); @@ -207,8 +213,8 @@ void NetConnect::initComponent() { getDeviceStatusMap(deviceStatusMap); if (deviceStatusMap.isEmpty()) { qDebug() << "[Netconnect] no device exist when init, set switch disable"; - wiredSwitch->setCheckable(false); wiredSwitch->setChecked(false); + wiredSwitch->setCheckable(false); } initNet(); @@ -240,7 +246,7 @@ void NetConnect::initComponent() { //获取网卡列表 void NetConnect::getDeviceStatusMap(QMap &map) { - if (!m_interface->isValid()) { + if (m_interface == nullptr || !m_interface->isValid()) { return; } qDebug() << "[NetConnect]call getDeviceListAndEnabled" << __LINE__; @@ -347,12 +353,6 @@ void NetConnect::initNet() } } -void NetConnect::runExternalApp() { - QString cmd = "nm-connection-editor"; - QProcess process(this); - process.startDetached(cmd); -} - //刪除 void NetConnect::deleteOneLan(QString ssid, int type) { @@ -361,8 +361,19 @@ void NetConnect::deleteOneLan(QString ssid, int type) qDebug() << "[NetConnect]call deleteConnect respond" << __LINE__; } +void NetConnect::runExternalApp() { + if (!LaunchApp("nm-connection-editor.desktop")){ + QString cmd = "nm-connection-editor"; + QProcess process(this); + process.startDetached(cmd); + } +} + //激活 void NetConnect::activeConnect(QString ssid, QString deviceName, int type) { + if (m_interface == nullptr || !m_interface->isValid()) { + return; + } qDebug() << "[NetConnect]call activateConnect" << __LINE__; m_interface->call(QStringLiteral("activateConnect"),type, deviceName, ssid); qDebug() << "[NetConnect]call activateConnect respond" << __LINE__; @@ -370,6 +381,9 @@ void NetConnect::activeConnect(QString ssid, QString deviceName, int type) { //断开 void NetConnect::deActiveConnect(QString ssid, QString deviceName, int type) { + if (m_interface == nullptr || !m_interface->isValid()) { + return; + } qDebug() << "[NetConnect]call deActivateConnect" << __LINE__; m_interface->call(QStringLiteral("deActivateConnect"),type, deviceName, ssid); qDebug() << "[NetConnect]call deActivateConnect respond" << __LINE__; @@ -383,7 +397,7 @@ void NetConnect::initNetListFromDevice(QString deviceName) qDebug() << "[NetConnect]initNetListFromDevice " << deviceName << " not exist"; return; } - if (!m_interface->isValid()) { + if (m_interface == nullptr || !m_interface->isValid()) { return; } qDebug() << "[NetConnect]call getWiredList" << __LINE__; @@ -446,9 +460,9 @@ void NetConnect::addLanItem(ItemFrame *frame, QString devName, QStringList infoL lanItem->uuid = infoList.at(1); lanItem->dbusPath = infoList.at(2); - connect(lanItem->infoLabel, &InfoButton::clicked, this, [=]{ + connect(lanItem->infoLabel, &GrayInfoButton::clicked, this, [=]{ // open landetail page - if (!m_interface->isValid()) { + if (m_interface == nullptr || !m_interface->isValid()) { return; } qDebug() << "[NetConnect]call showPropertyWidget" << __LINE__; @@ -486,6 +500,9 @@ void NetConnect::addLanItem(ItemFrame *frame, QString devName, QStringList infoL //增加设备 void NetConnect::addDeviceFrame(QString devName) { + if (m_interface == nullptr || !m_interface->isValid()) { + return; + } qDebug() << "[NetConnect]addDeviceFrame " << devName; qDebug() << "[NetConnect]call getDeviceListAndEnabled" << __LINE__; @@ -520,26 +537,32 @@ void NetConnect::addDeviceFrame(QString devName) deviceFrameMap.insert(devName, itemFrame); qDebug() << "[NetConnect]deviceFrameMap insert" << devName; - connect(itemFrame->deviceFrame->deviceSwitch, &KSwitchButton::stateChanged, this, [=] (bool checked) { + connect(itemFrame->deviceFrame, &DeviceFrame::deviceSwitchClicked ,this, [=] (bool checked) { qDebug() << "[NetConnect]call setDeviceEnable" << devName << checked << __LINE__; m_interface->call(QStringLiteral("setDeviceEnable"), devName, checked); qDebug() << "[NetConnect]call setDeviceEnable Respond" << __LINE__; + }); + + connect(itemFrame->deviceFrame->deviceSwitch, &KSwitchButton::stateChanged, this, [=] (bool checked) { + if (checked) { qDebug() << "[NetConnect]set " << devName << "status" << true; itemFrame->lanItemFrame->show(); itemFrame->deviceFrame->dropDownLabel->show(); + itemFrame->addLanWidget->show(); itemFrame->deviceFrame->dropDownLabel->setDropDownStatus(true); deviceStatusMap[devName] = true; } else { qDebug() << "[NetConnect]set " << devName << "status" << false; itemFrame->lanItemFrame->hide(); itemFrame->deviceFrame->dropDownLabel->hide(); + itemFrame->addLanWidget->hide(); deviceStatusMap[devName] = false; } }); connect(itemFrame->addLanWidget, &AddNetBtn::clicked, this, [=](){ - if (m_interface->isValid()) { + if (m_interface != nullptr && m_interface->isValid()) { qDebug() << "[NetConnect]call showCreateWiredConnectWidget" << devName << __LINE__; m_interface->call(QStringLiteral("showCreateWiredConnectWidget"), devName); qDebug() << "[NetConnect]call setDeviceEnable Respond" << __LINE__; @@ -612,13 +635,21 @@ void NetConnect::onDeviceStatusChanged() } deviceStatusMap = map; if (deviceStatusMap.isEmpty()) { - wiredSwitch->setCheckable(false); wiredSwitch->setChecked(false); + wiredSwitch->setCheckable(false); } else { wiredSwitch->setCheckable(true); setSwitchStatus(); } + QMap::iterator iter; + for (iter = deviceFrameMap.begin(); iter != deviceFrameMap.end(); iter++) { + if (deviceStatusMap.contains(iter.key())) { + if (iter.value()->deviceFrame->deviceSwitch->isChecked() != deviceStatusMap[iter.key()]) { + iter.value()->deviceFrame->deviceSwitch->setChecked(deviceStatusMap[iter.key()]); + } + } + } } void NetConnect::onDeviceNameChanged(QString oldName, QString newName, int type) @@ -726,9 +757,9 @@ void NetConnect::addOneLanFrame(ItemFrame *frame, QString deviceName, QStringLis lanItem->uuid = connUuid; lanItem->dbusPath = connDbusPath; - connect(lanItem->infoLabel, &InfoButton::clicked, this, [=]{ + connect(lanItem->infoLabel, &GrayInfoButton::clicked, this, [=]{ // open landetail page - if (!m_interface->isValid()) { + if (m_interface == nullptr || !m_interface->isValid()) { return; } qDebug() << "[NetConnect]call showPropertyWidget" << deviceName << connUuid << __LINE__; @@ -883,7 +914,7 @@ int NetConnect::getInsertPos(QString connName, QString deviceName) { qDebug() << "[NetConnect]getInsertPos" << connName << deviceName; int index = 0; - if(!m_interface->isValid()) { + if(m_interface == nullptr || !m_interface->isValid()) { index = 0; } else { qDebug() << "[NetConnect]call getWiredList" << __LINE__; @@ -914,3 +945,19 @@ int NetConnect::getInsertPos(QString connName, QString deviceName) } return index; } + +bool NetConnect::LaunchApp(QString desktopFile) +{ + QDBusInterface m_appManagerDbusInterface(KYLIN_APP_MANAGER_NAME, + KYLIN_APP_MANAGER_PATH, + KYLIN_APP_MANAGER_INTERFACE, + QDBusConnection::sessionBus());//局部变量 + + if (!m_appManagerDbusInterface.isValid()) { + qWarning()<<"m_appManagerDbusInterface init error"; + return false; + } else { + QDBusReply reply =m_appManagerDbusInterface.call("LaunchApp",desktopFile); + return reply; + } +} diff --git a/plugins/netconnect/netconnect.h b/plugins/netconnect/netconnect.h index ad89998e..e8858614 100644 --- a/plugins/netconnect/netconnect.h +++ b/plugins/netconnect/netconnect.h @@ -123,6 +123,7 @@ private: //单个lan连接状态变化 void itemActiveConnectionStatusChanged(LanItem *item, int status); + bool LaunchApp(QString desktopFile); protected: bool eventFilter(QObject *w,QEvent *e); diff --git a/plugins/netconnect/netconnect.pro b/plugins/netconnect/netconnect.pro index 539f2f97..500a3b7e 100644 --- a/plugins/netconnect/netconnect.pro +++ b/plugins/netconnect/netconnect.pro @@ -50,4 +50,6 @@ INSTALLS += target \ TRANSLATIONS += \ translations/zh_CN.ts \ translations/tr.ts \ - translations/bo.ts + translations/bo.ts \ + translations/bo_CN.ts \ + translations/en_US.ts diff --git a/plugins/netconnect/translations/bo.ts b/plugins/netconnect/translations/bo.ts index 80bbd9f4..9841010e 100644 --- a/plugins/netconnect/translations/bo.ts +++ b/plugins/netconnect/translations/bo.ts @@ -4,12 +4,12 @@ AddNetBtn - + Add Others - + Add WiredNetork @@ -17,19 +17,19 @@ LanItem - + Delete - - + + Disconnect - - + + Connect @@ -38,59 +38,59 @@ NetConnect - Wired Network - + open /netconnect/open - + Advanced settings /netconnect/Advanced settings" - + ukui control center - + ukui control center desktop message - - WiredConnect + + + LAN - + No ethernet device avaliable - - + + connected - - - + + + not connected - + card diff --git a/plugins/netconnect/translations/bo_CN.qm b/plugins/netconnect/translations/bo_CN.qm new file mode 100644 index 00000000..f41e3534 Binary files /dev/null and b/plugins/netconnect/translations/bo_CN.qm differ diff --git a/plugins/netconnect/translations/bo_CN.ts b/plugins/netconnect/translations/bo_CN.ts new file mode 100644 index 00000000..895a44e9 --- /dev/null +++ b/plugins/netconnect/translations/bo_CN.ts @@ -0,0 +1,102 @@ + + + + + AddNetBtn + + + Add Others + + + + + Add WiredNetork + སྐུད་ཡོད་བརྙན་འཕྲིན་ཁ་སྣོན་བྱས་ཡོད། + + + + LanItem + + + Delete + སུབ་དགོས། + + + + + Disconnect + བར་མཚམས་ཆད་པ་རེད། + + + + + Connect + འབྲེལ་མཐུད་བཅས་བྱ་དགོས། + + + + NetConnect + + + Wired Network + སྐུད་ཡོད་བརྙན་འཕྲིན་དྲ་བ། + + + + + open + སྒོ་ཕྱེ་བ། + /netconnect/open + + + + + Advanced settings + སྔོན་ཐོན་གྱི་སྒྲིག་བཀོད། + /netconnect/Advanced settings" + + + + ukui control center + ཝུའུ་ཁི་ལན་གྱི་ཚོད་འཛིན་ལྟེ་གནས། + + + + ukui control center desktop message + ukui ཚོད་འཛིན་ལྟེ་གནས་ཀྱི་ཅོག་ངོས་ཆ་འཕྲིན། + + + WiredConnect + སྐུད་ཡོད་སྦྲེལ་མཐུད། + + + + + LAN + སྐུད་ཡོད་དྲ་བ། + + + + No ethernet device avaliable + ཨེ་ཙི་དྲ་རྒྱའི་སྒྲིག་ཆས་ལ་བཙན་འཛུལ་བྱས་མི་ཆོག། + + + + + connected + འབྲེལ་མཐུད་བྱེད་པ། + + + + + + not connected + འབྲེལ་མཐུད་མ་བྱས་པ། + + + + card + བྱང་བུ། + + + diff --git a/plugins/netconnect/translations/en_US.ts b/plugins/netconnect/translations/en_US.ts new file mode 100644 index 00000000..67be9443 --- /dev/null +++ b/plugins/netconnect/translations/en_US.ts @@ -0,0 +1,98 @@ + + + + + AddNetBtn + + + Add Others + Add Others + + + + Add WiredNetork + Add WiredNetork + + + + LanItem + + + Delete + + + + + + Disconnect + + + + + + Connect + + + + + NetConnect + + + Wired Network + Wired Network + + + + + open + open + /netconnect/open + + + + + Advanced settings + Advanced settings + /netconnect/Advanced settings" + + + + ukui control center + ukui control center + + + + ukui control center desktop message + ukui control center desktop message + + + + + LAN + LAN + + + + No ethernet device avaliable + No ethernet device avaliable + + + + + connected + connected + + + + + + not connected + + + + + card + card + + + diff --git a/plugins/netconnect/translations/tr.ts b/plugins/netconnect/translations/tr.ts index 80bbd9f4..9841010e 100644 --- a/plugins/netconnect/translations/tr.ts +++ b/plugins/netconnect/translations/tr.ts @@ -4,12 +4,12 @@ AddNetBtn - + Add Others - + Add WiredNetork @@ -17,19 +17,19 @@ LanItem - + Delete - - + + Disconnect - - + + Connect @@ -38,59 +38,59 @@ NetConnect - Wired Network - + open /netconnect/open - + Advanced settings /netconnect/Advanced settings" - + ukui control center - + ukui control center desktop message - - WiredConnect + + + LAN - + No ethernet device avaliable - - + + connected - - - + + + not connected - + card diff --git a/plugins/netconnect/translations/zh_CN.qm b/plugins/netconnect/translations/zh_CN.qm index 549add6b..6ac7d043 100644 Binary files a/plugins/netconnect/translations/zh_CN.qm and b/plugins/netconnect/translations/zh_CN.qm differ diff --git a/plugins/netconnect/translations/zh_CN.ts b/plugins/netconnect/translations/zh_CN.ts index 112fe9ce..da195eef 100644 --- a/plugins/netconnect/translations/zh_CN.ts +++ b/plugins/netconnect/translations/zh_CN.ts @@ -4,12 +4,12 @@ AddNetBtn - + Add Others - 加入其他网络 + - + Add WiredNetork 添加有线网络 @@ -17,19 +17,19 @@ LanItem - + Delete 删除 - - + + Disconnect 断开 - - + + Connect 连接 @@ -38,59 +38,63 @@ NetConnect - Wired Network 有线网络 - + open 开启 /netconnect/open - + Advanced settings 高级设置 /netconnect/Advanced settings" - + ukui control center 控制面板 - + ukui control center desktop message 控制面板桌面通知 - WiredConnect + 有线网络 + + + + + LAN 有线网络 - + No ethernet device avaliable 未检测到有线设备 - - + + connected 已连接 - - - + + + not connected 未连接 - + card 网卡 diff --git a/plugins/plugin.pro b/plugins/plugin.pro index e2b6db16..1ef03f43 100644 --- a/plugins/plugin.pro +++ b/plugins/plugin.pro @@ -4,4 +4,4 @@ SUBDIRS = \ wlanconnect \ mobilehotspot \ proxy \ - vpn \ + vpn diff --git a/plugins/proxy/applistwidget.cpp b/plugins/proxy/applistwidget.cpp index c3c87109..dc2e5cd3 100644 --- a/plugins/proxy/applistwidget.cpp +++ b/plugins/proxy/applistwidget.cpp @@ -29,7 +29,7 @@ AppListWidget::AppListWidget(QString path, QWidget *parent) AppListWidget::~AppListWidget() { - + delete m_dbusInterface; } /** @@ -79,8 +79,9 @@ void AppListWidget::onAppCheckStateChanged() */ void AppListWidget::AddAppProxyConfig() { - if(!m_dbusInterface->isValid()) { + if(m_dbusInterface == nullptr || !m_dbusInterface->isValid()) { qWarning ()<< "init AppProxy dbus error"; + return; } qDebug() << "call QDBusInterface addAppIntoProxy"; @@ -93,8 +94,9 @@ void AppListWidget::AddAppProxyConfig() */ void AppListWidget::RemoveAppProxyConfig() { - if(!m_dbusInterface->isValid()) { + if(m_dbusInterface == nullptr || !m_dbusInterface->isValid()) { qWarning ()<< "init AppProxy dbus error"; + return; } qDebug() << "call QDBusInterface delAppIntoProxy"; @@ -116,7 +118,6 @@ void AppListWidget::initUI() mainLayout->setContentsMargins(17, 0, 17, 0); mainLayout->setSpacing(8); m_checkBox = new QCheckBox(this); - m_checkBox->setFixedSize(16, 16); m_checkBox->setAttribute(Qt::WA_TransparentForMouseEvents, true); //m_checkBox不响应鼠标事件,将其传递给父窗口 m_iconLabel = new QLabel(this); m_iconLabel->setFixedSize(24, 24); @@ -135,4 +136,7 @@ void AppListWidget::initDbus() "/org/ukui/SettingsDaemon/AppProxy", "org.ukui.SettingsDaemon.AppProxy", QDBusConnection::sessionBus()); + if(!m_dbusInterface->isValid()) { + qWarning() << qPrintable(QDBusConnection::sessionBus().lastError().message()); + } } diff --git a/plugins/proxy/proxy.cpp b/plugins/proxy/proxy.cpp index 0e89d9e5..268eaa6b 100644 --- a/plugins/proxy/proxy.cpp +++ b/plugins/proxy/proxy.cpp @@ -45,7 +45,7 @@ #define PROXY_HOST_KEY "host" #define PROXY_PORT_KEY "port" - +#define THEME_SCHAME "org.ukui.style" #define FRAME_LAYOUT_MARGINS 16,0,16,0 #define FRAME_LAYOUT_SPACING 8 #define LABEL_WIDTH 136 @@ -67,7 +67,8 @@ Proxy::Proxy() : mFirstLoad(true) Proxy::~Proxy() { if (!mFirstLoad) { - plugin_leave(); + plugin_leave(); + delete m_appProxyDbus; } } @@ -162,6 +163,11 @@ QIcon Proxy::icon() const return QIcon::fromTheme("ukui-network-agent-symbolic"); } +QString Proxy::translationPath() const +{ + return "/usr/share/kylin-nm/proxy/%1.ts"; +} + bool Proxy::isEnable() const { return true; @@ -702,6 +708,9 @@ void Proxy::initDbus() "/org/ukui/SettingsDaemon/AppProxy", "org.ukui.SettingsDaemon.AppProxy", QDBusConnection::sessionBus()); + if(!m_appProxyDbus->isValid()) { + qWarning() << qPrintable(QDBusConnection::sessionBus().lastError().message()); + } } void Proxy::initAppProxyStatus() @@ -752,8 +761,11 @@ void Proxy::setAptProxy(QString host, QString port, bool status) "/", "com.control.center.interface", QDBusConnection::systemBus()); - if (mAptproxyDbus->isValid()) + if (mAptproxyDbus->isValid()) { QDBusReply reply = mAptproxyDbus->call("setaptproxy", host, port , status); + } + delete mAptproxyDbus; + mAptproxyDbus = nullptr; } QHash Proxy::getAptProxy() @@ -786,6 +798,8 @@ QHash Proxy::getAptProxy() mAptInfo.insert(it.arg, it.out.variant()); } } + delete mAptproxyDbus; + mAptproxyDbus = nullptr; return mAptInfo; } @@ -814,8 +828,9 @@ void Proxy::reboot() "/org/gnome/SessionManager", "org.gnome.SessionManager", QDBusConnection::sessionBus()); - - rebootDbus->call("reboot"); + if (rebootDbus->isValid()) { + rebootDbus->call("reboot"); + } delete rebootDbus; rebootDbus = nullptr; } @@ -841,8 +856,9 @@ QFrame *Proxy::setLine(QFrame *frame) bool Proxy::getAppProxyState() { bool state = true; - if(!m_appProxyDbus->isValid()) { + if(m_appProxyDbus == nullptr || !m_appProxyDbus->isValid()) { qWarning ()<< "init AppProxy dbus error"; + return false; } //获取应用代理开启状态 @@ -859,7 +875,7 @@ bool Proxy::getAppProxyState() void Proxy::setAppProxyState(bool state) { - if(!m_appProxyDbus->isValid()) { + if(m_appProxyDbus == nullptr || !m_appProxyDbus->isValid()) { qWarning ()<< "init AppProxy dbus error"; return; } @@ -881,6 +897,7 @@ QStringList Proxy::getAppProxyConf() if(!dbusInterface.isValid()) { qWarning ()<< "init AppProxy dbus error"; + return info; } //获取应用代理配置信息 @@ -903,11 +920,12 @@ QStringList Proxy::getAppProxyConf() void Proxy::setAppProxyConf(QStringList list) { + //AppProxyConf 必填项数量为3 if (list.count() < 3) { return; } - if(!m_appProxyDbus->isValid()) { + if(m_appProxyDbus == nullptr || !m_appProxyDbus->isValid()) { qWarning ()<< "init AppProxy dbus error"; return; } @@ -1160,18 +1178,23 @@ void Proxy::setAppListFrameUi(QWidget *widget) m_allowAppProxyLabel->setText(tr("The following applications are allowed to use this configuration:")); //允许以下应用使用该配置: m_appListWidget = new QListWidget(m_appListFrame); m_appListWidget->setMinimumHeight(240); - m_appListWidget->setBackgroundRole(QPalette::Base); m_appListWidget->setFocusPolicy(Qt::FocusPolicy::NoFocus); m_appListWidget->setFrameShape(QFrame::Shape::Panel); appListLayout->addWidget(m_allowAppProxyLabel); appListLayout->addWidget(m_appListWidget); - QPalette mpal(m_appListWidget->palette()); - mpal.setColor(QPalette::Base, qApp->palette().base().color()); - mpal.setColor(QPalette::AlternateBase, qApp->palette().alternateBase().color()); - m_appListWidget->setAlternatingRowColors(true); - m_appListWidget->setPalette(mpal); + + onPaletteChanged(); + const QByteArray style_id(THEME_SCHAME); + if (QGSettings::isSchemaInstalled(style_id)) { + QGSettings * styleGsettings = new QGSettings(style_id, QByteArray(), this); + connect(styleGsettings, &QGSettings::changed, this, [=](QString key){ + if ("styleName" == key) { + onPaletteChanged(); + } + }); + } } void Proxy::appProxyInfoPadding() @@ -1240,7 +1263,6 @@ void Proxy::onAppProxyConfChanged() { if (!getipEditState(m_ipAddressLineEdit->text()) || m_portLineEdit->text().isEmpty()) { return; - qDebug() << "onAppProxyConfChanged return"; } if (m_ipAddressLineEdit->text().isEmpty()) { @@ -1257,8 +1279,6 @@ void Proxy::onAppProxyConfChanged() m_appProxyInfo.append(""); m_appProxyInfo.append(""); } - - qDebug() << m_appProxyInfo << Q_FUNC_INFO << __LINE__; } } @@ -1269,6 +1289,16 @@ void Proxy::onAppProxyConfEditFinished() } } +void Proxy::onPaletteChanged() +{ + QPalette mpal(m_appListWidget->palette()); + mpal.setColor(QPalette::Base, qApp->palette().base().color()); + mpal.setColor(QPalette::AlternateBase, qApp->palette().alternateBase().color()); + m_appListWidget->setBackgroundRole(QPalette::Base); + m_appListWidget->setAlternatingRowColors(true); + m_appListWidget->setPalette(mpal); +} + void Proxy::onappProxyEnableChanged(bool enable) { m_proxyTypeFrame->setVisible(enable); diff --git a/plugins/proxy/proxy.h b/plugins/proxy/proxy.h index 48d9cc30..6d690847 100644 --- a/plugins/proxy/proxy.h +++ b/plugins/proxy/proxy.h @@ -103,6 +103,7 @@ public: bool isShowOnHomePage() const Q_DECL_OVERRIDE; QIcon icon() const Q_DECL_OVERRIDE; bool isEnable() const Q_DECL_OVERRIDE; + QString translationPath() const Q_DECL_OVERRIDE; public: void initUi(QWidget *widget); @@ -262,8 +263,8 @@ private: QFileSystemWatcher *mfileWatch_1; QFileSystemWatcher *mfileWatch_2; - QDBusInterface *mAptproxyDbus; - QDBusInterface *m_appProxyDbus; +// QDBusInterface *mAptproxyDbus; + QDBusInterface *m_appProxyDbus = nullptr; bool isExistSettings = false; bool settingsCreate; @@ -277,6 +278,7 @@ private slots: void onipEditStateChanged(); //IP地址无效提示 void onAppProxyConfChanged(); //应用代理配置信息变化 void onAppProxyConfEditFinished(); + void onPaletteChanged(); // void onCancelBtnClicked(); // void onSaveBtnClicked(); // void setBtnEnable(); diff --git a/plugins/vpn/itemframe.cpp b/plugins/vpn/itemframe.cpp index 816828f7..29b6bf9c 100644 --- a/plugins/vpn/itemframe.cpp +++ b/plugins/vpn/itemframe.cpp @@ -25,36 +25,36 @@ ItemFrame::ItemFrame(QWidget *parent) :QFrame(parent) { - deviceLanLayout = new QVBoxLayout(this); - deviceLanLayout->setContentsMargins(MAIN_LAYOUT_MARGINS); - lanItemFrame = new QFrame(this); - lanItemFrame->setFrameShape(QFrame::Shape::NoFrame); - lanItemFrame->setContentsMargins(LAYOUT_MARGINS); + m_mainVLayout = new QVBoxLayout(this); + m_mainVLayout->setContentsMargins(MAIN_LAYOUT_MARGINS); + m_vpnFrame = new QFrame(this); + m_vpnFrame->setFrameShape(QFrame::Shape::NoFrame); + m_vpnFrame->setContentsMargins(LAYOUT_MARGINS); - lanItemLayout = new QVBoxLayout(this); - lanItemLayout->setContentsMargins(LAYOUT_MARGINS); - lanItemLayout->setSpacing(1); - addWlanWidget = new AddNetBtn(false, this); - addWlanWidget->setTextLabel(tr("Add Vpn")); + m_vpnVLayout = new QVBoxLayout(this); + m_vpnVLayout->setContentsMargins(LAYOUT_MARGINS); + m_vpnVLayout->setSpacing(1); + m_addVpnWidget = new AddNetBtn(false, this); + m_addVpnWidget->setTextLabel(tr("Add Vpn")); - deviceLanLayout->setSpacing(1); - setLayout(deviceLanLayout); - lanItemFrame->setLayout(lanItemLayout); + m_mainVLayout->setSpacing(1); + setLayout(m_mainVLayout); + m_vpnFrame->setLayout(m_vpnVLayout); - deviceLanLayout->addWidget(lanItemFrame); - deviceLanLayout->addWidget(addWlanWidget); + m_mainVLayout->addWidget(m_vpnFrame); + m_mainVLayout->addWidget(m_addVpnWidget); } void ItemFrame::filletStyleChange() { - if (lanItemLayout->isEmpty()) { + if (m_vpnVLayout->isEmpty()) { return; } - for (int i = 0; i < lanItemLayout->count(); ++i) { - QLayoutItem *it = lanItemLayout->itemAt(i); + for (int i = 0; i < m_vpnVLayout->count(); ++i) { + QLayoutItem *it = m_vpnVLayout->itemAt(i); VpnItem *itemFrame = (VpnItem*)(it->widget()); - if (i != lanItemLayout->count()-1) { + if (i != m_vpnVLayout->count()-1) { itemFrame->setHalfFillet(false); } else { itemFrame->setHalfFillet(true); diff --git a/plugins/vpn/itemframe.h b/plugins/vpn/itemframe.h index b41153fa..18595863 100644 --- a/plugins/vpn/itemframe.h +++ b/plugins/vpn/itemframe.h @@ -29,18 +29,18 @@ class ItemFrame : public QFrame Q_OBJECT public: ItemFrame(QWidget *parent = nullptr); - //单设备整体layout - QVBoxLayout * deviceLanLayout = nullptr; - //单设备列表Frame - QFrame * lanItemFrame = nullptr; + //VPN整体layout + QVBoxLayout * m_mainVLayout = nullptr; + //vpn列表Frame + QFrame * m_vpnFrame = nullptr; //单设备列表layout - QVBoxLayout * lanItemLayout = nullptr; + QVBoxLayout * m_vpnVLayout = nullptr; //item列表 - QMap itemMap; + QMap m_itemMap; // //已激活uuid // QString uuid = ""; //新建无线连接 - AddNetBtn * addWlanWidget = nullptr; + AddNetBtn * m_addVpnWidget = nullptr; void filletStyleChange(); }; diff --git a/plugins/vpn/vpn.cpp b/plugins/vpn/vpn.cpp index 143e06da..0ba36924 100644 --- a/plugins/vpn/vpn.cpp +++ b/plugins/vpn/vpn.cpp @@ -59,19 +59,19 @@ const QString VISIBLE = "visible"; const QByteArray GSETTINGS_SCHEMA = "org.ukui.kylin-nm.vpnicon"; -Vpn::Vpn() : mFirstLoad(true) +Vpn::Vpn() : m_firstLoad(true) { QTranslator* translator = new QTranslator(this); translator->load("/usr/share/kylin-nm/vpn/" + QLocale::system().name()); QApplication::installTranslator(translator); - pluginName = tr("Vpn"); - pluginType = NETWORK; + m_pluginName = tr("Vpn"); + m_pluginType = NETWORK; } Vpn::~Vpn() { - if (!mFirstLoad) { + if (!m_firstLoad) { delete ui; ui = nullptr; delete m_interface; @@ -80,25 +80,25 @@ Vpn::~Vpn() } QString Vpn::plugini18nName(){ - return pluginName; + return m_pluginName; } int Vpn::pluginTypes(){ - return pluginType; + return m_pluginType; } QWidget *Vpn::pluginUi(){ - if (mFirstLoad) { - mFirstLoad = false; + if (m_firstLoad) { + m_firstLoad = false; ui = new Ui::Vpn; - pluginWidget = new QWidget; - pluginWidget->setAttribute(Qt::WA_DeleteOnClose); - ui->setupUi(pluginWidget); + m_pluginWidget = new QWidget; + m_pluginWidget->setAttribute(Qt::WA_DeleteOnClose); + ui->setupUi(m_pluginWidget); qDBusRegisterMetaType>(); - m_interface = new QDBusInterface("com.kylin.network", - "/com/kylin/vpnTool", - "com.kylin.vpnTool", + m_interface = new QDBusInterface("com.kylin.kylinvpn", + "/com/kylin/kylinvpn", + "com.kylin.kylinvpn", QDBusConnection::sessionBus()); if(!m_interface->isValid()) { qWarning() << qPrintable(QDBusConnection::sessionBus().lastError().message()); @@ -108,7 +108,7 @@ QWidget *Vpn::pluginUi(){ initConnect(); initNet(); } - return pluginWidget; + return m_pluginWidget; } const QString Vpn::name() const { @@ -134,12 +134,12 @@ bool Vpn::isEnable() const void Vpn::initComponent(){ //在任务栏上显示图标 //显示已连接时间 - m_topFrame = new QFrame(pluginWidget); + m_topFrame = new QFrame(m_pluginWidget); m_topFrame->setMinimumSize(FRAME_MIN_SIZE); m_topFrame->setMaximumSize(FRAME_MAX_SIZE); m_topFrame->setFrameShape(QFrame::Box); - QVBoxLayout *hotspotLyt = new QVBoxLayout(pluginWidget); + QVBoxLayout *hotspotLyt = new QVBoxLayout(m_pluginWidget); hotspotLyt->setContentsMargins(0, 0, 0, 0); m_topFrame->setLayout(hotspotLyt); @@ -181,12 +181,13 @@ void Vpn::initComponent(){ hotspotLyt->setSpacing(0); //列表 - m_listFrame = new ItemFrame(pluginWidget); + + m_listFrame = new ItemFrame(m_pluginWidget); ui->verticalLayout_4->addWidget(m_topFrame); ui->verticalLayout_3->addWidget(m_listFrame); - connect(m_listFrame->addWlanWidget, &AddNetBtn::clicked, this, [=]() { + connect(m_listFrame->m_addVpnWidget, &AddNetBtn::clicked, this, [=]() { runExternalApp(); }); @@ -267,14 +268,18 @@ void Vpn::setShowSwitchStatus() } void Vpn::runExternalApp(){ - QString cmd = "nm-connection-editor"; - QProcess process(this); - process.startDetached(cmd); +// QString cmd = "nm-connection-editor"; +// QProcess process(this); +// process.startDetached(cmd); + + if (m_interface->isValid()) { + m_interface->call(QStringLiteral("showVpnAddWidget")); + } } QFrame* Vpn::myLine() { - QFrame *line = new QFrame(pluginWidget); + QFrame *line = new QFrame(m_pluginWidget); line->setMinimumSize(QSize(LINE_MIN_SIZE)); line->setMaximumSize(QSize(LINE_MAX_SIZE)); line->setLineWidth(0); @@ -295,6 +300,11 @@ void Vpn::activeConnect(QString uuid) { m_interface->call(QStringLiteral("activateVpn"), uuid); } +//详情页 +void Vpn::showDetailPage(QString uuid) { + m_interface->call(QStringLiteral("showDetailPage"), uuid); +} + //断开 void Vpn::deActiveConnect(QString uuid) { m_interface->call(QStringLiteral("deactivateVpn"), uuid); @@ -304,7 +314,12 @@ void Vpn::deActiveConnect(QString uuid) { //增加一项 void Vpn::addOneVirtualItem(QStringList infoList) { - if (m_listFrame->itemMap.contains(infoList.at(1))) { + if (infoList.size() < 4) { + qDebug() << "[Vpn]QStringList size less"; + return; + } + + if (m_listFrame->m_itemMap.contains(infoList.at(1))) { qDebug() << "[Vpn]Already exist a virtual " << infoList.at(1); return; } @@ -314,64 +329,55 @@ void Vpn::addOneVirtualItem(QStringList infoList) QString connUuid = infoList.at(1); QString connDbusPath = infoList.at(2); int status = infoList.at(3).toInt(); //1-连接中 2-已连接 3-断开中 4-已断开 - VpnItem * item = new VpnItem(pluginWidget); + VpnItem * item = new VpnItem(m_pluginWidget); QIcon searchIcon = QIcon::fromTheme(KVpnSymbolic); - item->iconLabel->setPixmap(searchIcon.pixmap(searchIcon.actualSize(QSize(ICON_SIZE)))); - item->titileLabel->setText(connName); + item->m_iconLabel->setPixmap(searchIcon.pixmap(searchIcon.actualSize(QSize(ICON_SIZE)))); + item->m_titileLabel->setText(connName); - item->uuid = connUuid; - item->dbusPath = connDbusPath; + item->m_uuid = connUuid; + item->m_dbusPath = connDbusPath; if (status == 1 || status == 3) { item->startLoading(); } - connect(item->infoLabel, &InfoButton::clicked, this, [=]{ - QDBusInterface appManagerDbusInterface(KYLIN_APP_MANAGER_NAME, - KYLIN_APP_MANAGER_PATH, - KYLIN_APP_MANAGER_INTERFACE, - QDBusConnection::sessionBus()); - - if (!appManagerDbusInterface.isValid()) { - qWarning()<<"appManagerDbusInterface init error"; - } else { - QDBusReply reply = appManagerDbusInterface.call("LaunchApp", "nm-connection-editor.desktop"); - } + connect(item->m_infoLabel, &GrayInfoButton::clicked, this, [=]{ + showDetailPage(item->m_uuid); }); - item->isAcitve = (status == 2); - item->setConnectActionText(item->isAcitve); + item->m_isAcitve = (status == 2); + item->setConnectActionText(item->m_isAcitve); - if (item->isAcitve) { - item->statusLabel->setText(tr("connected")); + if (item->m_isAcitve) { + item->m_statusLabel->setText(tr("connected")); } else { - item->statusLabel->setText(tr("not connected")); + item->m_statusLabel->setText(tr("not connected")); } connect(item, &QPushButton::clicked, this, [=] { - if (item->isAcitve || item->loading) { - deActiveConnect(item->uuid); + if (item->m_isAcitve || item->m_loading) { + deActiveConnect(item->m_uuid); } else { - activeConnect(item->uuid); + activeConnect(item->m_uuid); } }); connect(item, &VpnItem::connectActionTriggered, this, [=] { - activeConnect(item->uuid); + activeConnect(item->m_uuid); }); connect(item, &VpnItem::disconnectActionTriggered, this, [=] { - deActiveConnect(item->uuid); + deActiveConnect(item->m_uuid); }); connect(item, &VpnItem::deleteActionTriggered, this, [=] { - deleteVpn(item->uuid); + deleteVpn(item->m_uuid); }); - //记录到deviceFrame的itemMap中 - m_listFrame->itemMap.insert(connUuid, item); + //记录到deviceFrame的m_itemMap中 + m_listFrame->m_itemMap.insert(connUuid, item); int index = getInsertPos(connName); qDebug()<<"[Vpn]addOneVirtualItem " << connName << " at pos:" << index; - m_listFrame->lanItemLayout->insertWidget(index, item); + m_listFrame->m_vpnVLayout->insertWidget(index, item); } void Vpn::removeOneVirtualItem(QString dbusPath) @@ -379,13 +385,13 @@ void Vpn::removeOneVirtualItem(QString dbusPath) qDebug()<<"[Vpn]vpn remove dbus path:" << dbusPath; QMap::iterator itemIter; - for (itemIter = m_listFrame->itemMap.begin(); itemIter != m_listFrame->itemMap.end(); itemIter++) { - if (itemIter.value()->dbusPath == dbusPath) { - qDebug()<<"[Vpn]vpn remove " << dbusPath << " find in " << itemIter.value()->titileLabel->text(); + for (itemIter = m_listFrame->m_itemMap.begin(); itemIter != m_listFrame->m_itemMap.end(); itemIter++) { + if (itemIter.value()->m_dbusPath == dbusPath) { + qDebug()<<"[Vpn]vpn remove " << dbusPath << " find in " << itemIter.value()->m_titileLabel->text(); QString key = itemIter.key(); - m_listFrame->lanItemLayout->removeWidget(itemIter.value()); + m_listFrame->m_vpnVLayout->removeWidget(itemIter.value()); delete itemIter.value(); - m_listFrame->itemMap.remove(key); + m_listFrame->m_itemMap.remove(key); break; } } @@ -398,18 +404,18 @@ void Vpn::onVpnAdd(QStringList infoList) } //移出 -void Vpn::onVpnRemove(QString uuid) +void Vpn::onVpnRemove(QString path) { - removeOneVirtualItem(uuid); + removeOneVirtualItem(path); } //名称变化 void Vpn::onVpnUpdate(QStringList info) { - if (m_listFrame->itemMap.contains(info.at(1))) { - qDebug() << "[Vpn]" << m_listFrame->itemMap[info.at(1)]->titileLabel->text() << "change to" << info.at(0); - if (m_listFrame->itemMap[info.at(1)]->titileLabel->text() != info.at(0)) { - m_listFrame->itemMap[info.at(1)]->titileLabel->setText(info.at(0)); + if (m_listFrame->m_itemMap.contains(info.at(1))) { + qDebug() << "[Vpn]" << m_listFrame->m_itemMap[info.at(1)]->m_titileLabel->text() << "change to" << info.at(0); + if (m_listFrame->m_itemMap[info.at(1)]->m_titileLabel->text() != info.at(0)) { + m_listFrame->m_itemMap[info.at(1)]->m_titileLabel->setText(info.at(0)); } } } @@ -423,18 +429,18 @@ void Vpn::onVpnActiveConnectionStateChanged(QString uuid, int status) qDebug() << "[Vpn]onActiveConnectionChanged " << uuid << status; VpnItem * item= nullptr; - if (m_listFrame->itemMap.contains(uuid)) { - item = m_listFrame->itemMap[uuid]; + if (m_listFrame->m_itemMap.contains(uuid)) { + item = m_listFrame->m_itemMap[uuid]; if (status == ACTIVATED) { //为已连接则放到第一个 - m_listFrame->lanItemLayout->removeWidget(item); - m_listFrame->lanItemLayout->insertWidget(0,item); + m_listFrame->m_vpnVLayout->removeWidget(item); + m_listFrame->m_vpnVLayout->insertWidget(0,item); } else if (status == DEACTIVATED) { //为断开则重新插入 - int index = getInsertPos(item->titileLabel->text()); - qDebug() << "[Vpn]reinsert" << item->titileLabel->text() << "pos" << index << "because status changes to deactive"; - m_listFrame->lanItemLayout->removeWidget(item); - m_listFrame->lanItemLayout->insertWidget(index,item); + int index = getInsertPos(item->m_titileLabel->text()); + qDebug() << "[Vpn]reinsert" << item->m_titileLabel->text() << "pos" << index << "because status changes to deactive"; + m_listFrame->m_vpnVLayout->removeWidget(item); + m_listFrame->m_vpnVLayout->insertWidget(index,item); } itemActiveConnectionStatusChanged(item, status); } @@ -448,22 +454,22 @@ void Vpn::itemActiveConnectionStatusChanged(VpnItem *item, int status) } else if (status == ACTIVATED) { item->stopLoading(); // iconPath = KLanSymbolic; - item->statusLabel->clear(); - item->statusLabel->setMinimumSize(36,36); - item->statusLabel->setMaximumSize(16777215,16777215); - item->statusLabel->setText(tr("connected")); - item->isAcitve = true; + item->m_statusLabel->clear(); + item->m_statusLabel->setMinimumSize(36,36); + item->m_statusLabel->setMaximumSize(16777215,16777215); + item->m_statusLabel->setText(tr("connected")); + item->m_isAcitve = true; } else if (status == DEACTIVATING) { item->startLoading(); } else { item->stopLoading(); - item->statusLabel->setMinimumSize(36,36); - item->statusLabel->setMaximumSize(16777215,16777215); - item->statusLabel->clear(); - item->isAcitve = false; - item->statusLabel->setText(tr("not connected")); + item->m_statusLabel->setMinimumSize(36,36); + item->m_statusLabel->setMaximumSize(16777215,16777215); + item->m_statusLabel->clear(); + item->m_isAcitve = false; + item->m_statusLabel->setText(tr("not connected")); } - item->setConnectActionText(item->isAcitve); + item->setConnectActionText(item->m_isAcitve); } int Vpn::getInsertPos(QString connName) diff --git a/plugins/vpn/vpn.h b/plugins/vpn/vpn.h index 941f8f4f..82d89ea2 100644 --- a/plugins/vpn/vpn.h +++ b/plugins/vpn/vpn.h @@ -69,9 +69,9 @@ protected: private: Ui::Vpn *ui; - QString pluginName; - int pluginType; - QWidget * pluginWidget; + QString m_pluginName; + int m_pluginType; + QWidget * m_pluginWidget; QDBusInterface *m_interface = nullptr; @@ -85,7 +85,7 @@ private: KSwitchButton *m_timeBtn; ItemFrame *m_listFrame; - bool mFirstLoad; + bool m_firstLoad; QGSettings *m_switchGsettings; QFrame* myLine(); @@ -95,6 +95,7 @@ private: void deleteVpn(QString uuid); void activeConnect(QString uuid); void deActiveConnect(QString uuid); + void showDetailPage(QString uuid); //获取设备列表 void initNet(); diff --git a/plugins/vpn/vpnitem.cpp b/plugins/vpn/vpnitem.cpp index 57c2cff4..19b0e877 100644 --- a/plugins/vpn/vpnitem.cpp +++ b/plugins/vpn/vpnitem.cpp @@ -28,7 +28,7 @@ #define MODE_QT_KEY "style-name" VpnItem::VpnItem(bool bAcitve, QWidget *parent) - : isAcitve(bAcitve), QPushButton(parent) + : m_isAcitve(bAcitve), QPushButton(parent) { this->setMinimumSize(550, 58); this->setProperty("useButtonPalette", true); @@ -41,12 +41,12 @@ VpnItem::VpnItem(bool bAcitve, QWidget *parent) QHBoxLayout *mLanLyt = new QHBoxLayout(this); mLanLyt->setContentsMargins(16,0,16,0); mLanLyt->setSpacing(16); - iconLabel = new QLabel(this); - iconLabel->setProperty("useIconHighlightEffect", 0x2); - titileLabel = new FixLabel(this); - statusLabel = new QLabel(this); - statusLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); - infoLabel = new InfoButton(this); + m_iconLabel = new QLabel(this); + m_iconLabel->setProperty("useIconHighlightEffect", 0x2); + m_titileLabel = new FixLabel(this); + m_statusLabel = new QLabel(this); + m_statusLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); + m_infoLabel = new GrayInfoButton(this); m_moreButton = new QToolButton(this); m_moreButton->setProperty("useButtonPalette", true); @@ -56,29 +56,28 @@ VpnItem::VpnItem(bool bAcitve, QWidget *parent) m_moreMenu = new QMenu(m_moreButton); m_connectAction = new QAction(m_moreMenu); m_deleteAction = new QAction(tr("Delete"), m_moreMenu); - setConnectActionText(isAcitve); + setConnectActionText(m_isAcitve); m_moreMenu->addAction(m_connectAction); m_moreMenu->addAction(m_deleteAction); m_moreButton->setMenu(m_moreMenu); - - mLanLyt->addWidget(iconLabel); - mLanLyt->addWidget(titileLabel,Qt::AlignLeft); + mLanLyt->addWidget(m_iconLabel); + mLanLyt->addWidget(m_titileLabel,Qt::AlignLeft); mLanLyt->addStretch(); - mLanLyt->addWidget(statusLabel); - mLanLyt->addWidget(infoLabel); + mLanLyt->addWidget(m_statusLabel); + mLanLyt->addWidget(m_infoLabel); mLanLyt->addWidget(m_moreButton); - loadIcons.append(QIcon::fromTheme("ukui-loading-1-symbolic")); - loadIcons.append(QIcon::fromTheme("ukui-loading-2-symbolic")); - loadIcons.append(QIcon::fromTheme("ukui-loading-3-symbolic")); - loadIcons.append(QIcon::fromTheme("ukui-loading-4-symbolic")); - loadIcons.append(QIcon::fromTheme("ukui-loading-5-symbolic")); - loadIcons.append(QIcon::fromTheme("ukui-loading-6-symbolic")); - loadIcons.append(QIcon::fromTheme("ukui-loading-7-symbolic")); + m_loadIcons.append(QIcon::fromTheme("ukui-loading-1-symbolic")); + m_loadIcons.append(QIcon::fromTheme("ukui-loading-2-symbolic")); + m_loadIcons.append(QIcon::fromTheme("ukui-loading-3-symbolic")); + m_loadIcons.append(QIcon::fromTheme("ukui-loading-4-symbolic")); + m_loadIcons.append(QIcon::fromTheme("ukui-loading-5-symbolic")); + m_loadIcons.append(QIcon::fromTheme("ukui-loading-6-symbolic")); + m_loadIcons.append(QIcon::fromTheme("ukui-loading-7-symbolic")); - waitTimer = new QTimer(this); - connect(waitTimer, &QTimer::timeout, this, &VpnItem::updateIcon); + m_waitTimer = new QTimer(this); + connect(m_waitTimer, &QTimer::timeout, this, &VpnItem::updateIcon); connect(m_connectAction, &QAction::triggered, this, &VpnItem::onConnectTriggered); connect(m_deleteAction, &QAction::triggered, this, &VpnItem::onDeletetTriggered); @@ -87,22 +86,22 @@ VpnItem::VpnItem(bool bAcitve, QWidget *parent) void VpnItem::updateIcon() { - if (currentIconIndex > 6) { - currentIconIndex = 0; + if (m_currentIconIndex > 6) { + m_currentIconIndex = 0; } - statusLabel->setPixmap(loadIcons.at(currentIconIndex).pixmap(16,16)); - currentIconIndex ++; + m_statusLabel->setPixmap(m_loadIcons.at(m_currentIconIndex).pixmap(16,16)); + m_currentIconIndex ++; } void VpnItem::startLoading() { - waitTimer->start(FRAME_SPEED); - loading = true; + m_waitTimer->start(FRAME_SPEED); + m_loading = true; } void VpnItem::stopLoading(){ - waitTimer->stop(); - loading = false; + m_waitTimer->stop(); + m_loading = false; } void VpnItem::setConnectActionText(bool isAcitve) @@ -146,7 +145,7 @@ void VpnItem::paintEvent(QPaintEvent *event) QRect rect = this->rect(); #if 0 - if (!useHalfFillet) { + if (!m_useHalfFillet) { painter.drawRect(rect); } else { QPainterPath path; diff --git a/plugins/vpn/vpnitem.h b/plugins/vpn/vpnitem.h index 2df6a25a..bbe8a3ec 100644 --- a/plugins/vpn/vpnitem.h +++ b/plugins/vpn/vpnitem.h @@ -33,7 +33,7 @@ #include #include #include "fixlabel.h" -#include "infobutton.h" +#include "../component/AddBtn/grayinfobutton.h" class VpnItem : public QPushButton { @@ -41,37 +41,36 @@ class VpnItem : public QPushButton public: VpnItem(bool bAcitve, QWidget *parent = nullptr); public: - QLabel * iconLabel = nullptr; - InfoButton * infoLabel = nullptr; - FixLabel * titileLabel = nullptr; - QLabel * statusLabel = nullptr; + QLabel * m_iconLabel = nullptr; + GrayInfoButton * m_infoLabel = nullptr; + FixLabel * m_titileLabel = nullptr; + QLabel * m_statusLabel = nullptr; QToolButton* m_moreButton = nullptr; QMenu* m_moreMenu = nullptr; QAction* m_connectAction = nullptr; QAction* m_deleteAction = nullptr; - QString uuid = ""; - QString dbusPath = ""; + QString m_uuid = ""; + QString m_dbusPath = ""; - void setHalfFillet(bool flag) {useHalfFillet = flag; repaint();} + void setHalfFillet(bool flag) {m_useHalfFillet = flag; repaint();} public: void startLoading(); void stopLoading(); void setConnectActionText(bool isAcitve); - bool isAcitve = false; - bool loading = false; + bool m_isAcitve = false; + bool m_loading = false; protected: void paintEvent(QPaintEvent *event); bool eventFilter(QObject *watched, QEvent *event); private: - QTimer *waitTimer = nullptr; - QGSettings *themeGsettings = nullptr; - bool useHalfFillet = false; - QList loadIcons; - int currentIconIndex=0; + QTimer *m_waitTimer = nullptr; + bool m_useHalfFillet = false; + QList m_loadIcons; + int m_currentIconIndex=0; private slots: void updateIcon(); diff --git a/plugins/wlanconnect/deviceframe.cpp b/plugins/wlanconnect/deviceframe.cpp index 9765faef..a7822712 100644 --- a/plugins/wlanconnect/deviceframe.cpp +++ b/plugins/wlanconnect/deviceframe.cpp @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "deviceframe.h" #include #include diff --git a/plugins/wlanconnect/deviceframe.h b/plugins/wlanconnect/deviceframe.h index f70eda47..d6300e36 100644 --- a/plugins/wlanconnect/deviceframe.h +++ b/plugins/wlanconnect/deviceframe.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef DEVICEFRAME_H #define DEVICEFRAME_H #include diff --git a/plugins/wlanconnect/itemframe.cpp b/plugins/wlanconnect/itemframe.cpp index 05112f29..503e3b2b 100644 --- a/plugins/wlanconnect/itemframe.cpp +++ b/plugins/wlanconnect/itemframe.cpp @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "itemframe.h" #include diff --git a/plugins/wlanconnect/itemframe.h b/plugins/wlanconnect/itemframe.h index 4a980920..ee947279 100644 --- a/plugins/wlanconnect/itemframe.h +++ b/plugins/wlanconnect/itemframe.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef ITEMFRAME_H #define ITEMFRAME_H #include diff --git a/plugins/wlanconnect/translations/bo.ts b/plugins/wlanconnect/translations/bo.ts index f8fab3a1..824aac8c 100644 --- a/plugins/wlanconnect/translations/bo.ts +++ b/plugins/wlanconnect/translations/bo.ts @@ -4,12 +4,12 @@ AddNetBtn - + Add Others - + Add WiredNetork @@ -18,54 +18,54 @@ WlanConnect - WlanConnect - + + WLAN - + open /wlanconnect/open - + Advanced settings /wlanconnect/Advanced settings" - + ukui control center - + ukui control center desktop message - + No wireless network card detected - - - + + + connected - + card diff --git a/plugins/wlanconnect/translations/bo_CN.qm b/plugins/wlanconnect/translations/bo_CN.qm new file mode 100644 index 00000000..8f72b8c9 Binary files /dev/null and b/plugins/wlanconnect/translations/bo_CN.qm differ diff --git a/plugins/wlanconnect/translations/bo_CN.ts b/plugins/wlanconnect/translations/bo_CN.ts new file mode 100644 index 00000000..7be28fd3 --- /dev/null +++ b/plugins/wlanconnect/translations/bo_CN.ts @@ -0,0 +1,73 @@ + + + + + AddNetBtn + + + Add Others + དྲ་རྒྱ་གཞན་དག་ནང་ཞུགས་དགོས། + + + + Add WiredNetork + + + + + WlanConnect + + + WlanConnect + ཝུའུ་ལན་འབྲེལ་མཐུད། + + + + + + WLAN + སྐུད་མེད་ཅུས་ཁོངས་ཀྱི་དྲ་བ། + + + + + open + སྒོ་ཕྱེ་བ། + /wlanconnect/open + + + + + Advanced settings + སྔོན་ཐོན་གྱི་སྒྲིག་བཀོད། + /wlanconnect/Advanced settings" + + + + ukui control center + ཝུའུ་ཁི་ལན་གྱི་ཚོད་འཛིན་ལྟེ་གནས། + + + + ukui control center desktop message + ངོས་ལེབ་ངོས་ཀྱི་བརྡ་ཐོ་ཚོད་འཛིན་བྱ་དགོས། + + + + No wireless network card detected + སྐུད་མེད་དྲ་རྒྱའི་བྱང་བུ་མ་རྙེད་པ། + + + + + + connected + འབྲེལ་མཐུད་བྱེད་པ། + + + + card + བྱང་བུ། + + + diff --git a/plugins/wlanconnect/translations/en_US.ts b/plugins/wlanconnect/translations/en_US.ts new file mode 100644 index 00000000..01b3915e --- /dev/null +++ b/plugins/wlanconnect/translations/en_US.ts @@ -0,0 +1,73 @@ + + + + + AddNetBtn + + + Add Others + Add Others + + + + Add WiredNetork + Add WiredNetork + + + + WlanConnect + + + WlanConnect + WlanConnect + + + + + + WLAN + WLAN + + + + + open + open + /wlanconnect/open + + + + + Advanced settings + Advanced settings + /wlanconnect/Advanced settings" + + + + ukui control center + ukui control center + + + + ukui control center desktop message + ukui control center desktop message + + + + No wireless network card detected + No wireless network card detected + + + + + + connected + connected + + + + card + card + + + diff --git a/plugins/wlanconnect/translations/tr.ts b/plugins/wlanconnect/translations/tr.ts index f8fab3a1..824aac8c 100644 --- a/plugins/wlanconnect/translations/tr.ts +++ b/plugins/wlanconnect/translations/tr.ts @@ -4,12 +4,12 @@ AddNetBtn - + Add Others - + Add WiredNetork @@ -18,54 +18,54 @@ WlanConnect - WlanConnect - + + WLAN - + open /wlanconnect/open - + Advanced settings /wlanconnect/Advanced settings" - + ukui control center - + ukui control center desktop message - + No wireless network card detected - - - + + + connected - + card diff --git a/plugins/wlanconnect/translations/zh_CN.ts b/plugins/wlanconnect/translations/zh_CN.ts index a62ddac2..52d7a5cc 100644 --- a/plugins/wlanconnect/translations/zh_CN.ts +++ b/plugins/wlanconnect/translations/zh_CN.ts @@ -4,12 +4,12 @@ AddNetBtn - + Add Others 加入其它网络 - + Add WiredNetork @@ -18,54 +18,54 @@ WlanConnect - WlanConnect 无线局域网 - + + WLAN 无线局域网 - + open 开启 /wlanconnect/open - + Advanced settings 高级设置 /wlanconnect/Advanced settings" - + ukui control center 控制面板 - + ukui control center desktop message 控制面板桌面通知 - + No wireless network card detected 未检测到无线网卡 - - - + + + connected 已连接 - + card 网卡 diff --git a/plugins/wlanconnect/wlanconnect.cpp b/plugins/wlanconnect/wlanconnect.cpp index 4f174a56..2dcb4f9c 100644 --- a/plugins/wlanconnect/wlanconnect.cpp +++ b/plugins/wlanconnect/wlanconnect.cpp @@ -48,6 +48,10 @@ #define SIGNAL_NONE 5 #define ICON_SIZE 16,16 +#define KYLIN_APP_MANAGER_NAME "com.kylin.AppManager" +#define KYLIN_APP_MANAGER_PATH "/com/kylin/AppManager" +#define KYLIN_APP_MANAGER_INTERFACE "com.kylin.AppManager" + const QString WIRELESS_SWITCH = "wirelessswitch"; const QByteArray GSETTINGS_SCHEMA = "org.ukui.kylin-nm.switch"; @@ -137,7 +141,7 @@ WlanConnect::WlanConnect() : m_firstLoad(true) { translator->load("/usr/share/kylin-nm/wlanconnect/" + QLocale::system().name()); QApplication::installTranslator(translator); - pluginName = tr("WlanConnect"); + pluginName = tr("WLAN"); pluginType = NETWORK; } @@ -148,7 +152,6 @@ WlanConnect::~WlanConnect() ui = nullptr; } delete m_interface; - delete m_switchGsettings; } QString WlanConnect::plugini18nName() { @@ -174,6 +177,7 @@ QWidget *WlanConnect::pluginUi() { if(!m_interface->isValid()) { qWarning() << qPrintable(QDBusConnection::sessionBus().lastError().message()); } + initSearchText(); initComponent(); } return pluginWidget; @@ -224,10 +228,12 @@ bool WlanConnect::eventFilter(QObject *w, QEvent *e) { if (w == m_wifiSwitch) { if (e->type() == QMouseEvent::MouseButtonRelease) { - if (!m_wifiSwitch->isCheckable()) { + if (!getSwitchBtnEnable()) { showDesktopNotify(tr("No wireless network card detected")); } else { - m_interface->call(QStringLiteral("setWirelessSwitchEnable"), !m_wifiSwitch->isChecked()); + if (m_interface != nullptr && m_interface->isValid()) { + m_interface->call(QStringLiteral("setWirelessSwitchEnable"), !getSwitchBtnState()); + } return true; } } @@ -239,40 +245,27 @@ bool WlanConnect::eventFilter(QObject *w, QEvent *e) { void WlanConnect::initComponent() { m_wifiSwitch = new KSwitchButton(pluginWidget); ui->openWIifLayout->addWidget(m_wifiSwitch); + ui->openWIifLayout->setContentsMargins(0,0,8,0); ui->detailLayOut_3->setContentsMargins(MAIN_LAYOUT_MARGINS); ui->verticalLayout_3->setContentsMargins(NO_MARGINS); + ui->verticalLayout_3->setSpacing(8); ui->availableLayout->setSpacing(SPACING); m_wifiSwitch->installEventFilter(this); //开关 - if (QGSettings::isSchemaInstalled(GSETTINGS_SCHEMA)) { - m_switchGsettings = new QGSettings(GSETTINGS_SCHEMA); - - setSwitchStatus(); - - connect(m_switchGsettings, &QGSettings::changed, this, [=] (const QString &key) { - if (key == WIRELESS_SWITCH) { - setSwitchStatus(); - } - }); - } else { - m_wifiSwitch->blockSignals(true); - m_wifiSwitch->setChecked(true); - m_wifiSwitch->blockSignals(false); - qDebug()<<"[netconnect] org.ukui.kylin-nm.switch is not installed!"; - } + initSwtichState(); //获取设备列表 getDeviceList(deviceList); if (deviceList.isEmpty()) { qDebug() << "[WlanConnect]no device exist when init, set switch disable"; - m_wifiSwitch->setCheckable(false); - m_wifiSwitch->setChecked(false); + setSwitchBtnState(false); + setSwitchBtnEnable(false); } initNet(); - if (!m_wifiSwitch->isChecked() || deviceList.isEmpty() || !m_interface->isValid()) { + if (!getSwitchBtnState() || deviceList.isEmpty() || !m_interface->isValid()) { hideLayout(ui->availableLayout); } @@ -288,7 +281,7 @@ void WlanConnect::initComponent() { // connect(m_interface, SIGNAL(signalStrengthChange(QString, QString, int)), this, SLOT(updateStrengthList(QString, QString, int))); //网卡name处理 connect(m_interface, SIGNAL(deviceNameChanged(QString, QString, int)), this, SLOT(onDeviceNameChanged(QString, QString, int)), Qt::QueuedConnection); - + connect(m_interface, SIGNAL(wirelessSwitchBtnChanged(bool)), this, SLOT(onSwitchBtnChanged(bool)), Qt::QueuedConnection); connect(m_interface, SIGNAL(timeToUpdate()), this, SLOT(updateList()), Qt::QueuedConnection); //高级设置 connect(ui->detailBtn, &QPushButton::clicked, this, [=](bool checked) { @@ -310,7 +303,7 @@ void WlanConnect::initComponent() { void WlanConnect::reScan() { qDebug() << "time to rescan wifi"; - if (m_interface->isValid()) { + if (m_interface != nullptr && m_interface->isValid()) { qDebug() << "[WlanConnect]call reScan" << __LINE__; m_interface->call("reScan"); qDebug() << "[WlanConnect]call reScan respond" << __LINE__; @@ -320,11 +313,11 @@ void WlanConnect::reScan() //更新列表顺序 void WlanConnect::updateList() { - if (!m_wifiSwitch->isChecked()) { + if (!getSwitchBtnState()) { return; } qDebug() << "update list"; - if(m_interface->isValid()) { + if(m_interface != nullptr && m_interface->isValid()) { qDebug() << "[WlanConnect]call getWirelessList" << __LINE__; QDBusMessage result = m_interface->call(QStringLiteral("getWirelessList")); qDebug() << "[WlanConnect]call getWirelessList respond" << __LINE__; @@ -438,9 +431,9 @@ void WlanConnect::updateIcon(WlanItem *item, QString signalStrength, QString sec iconamePath = wifiIcon(isLock, sign, category); } QIcon searchIcon = QIcon::fromTheme(iconamePath); - if (iconamePath != KLanSymbolic && iconamePath != NoNetSymbolic) { - item->iconLabel->setProperty("useIconHighlightEffect", 0x10); - } +// if (iconamePath != KLanSymbolic && iconamePath != NoNetSymbolic) { +// item->iconLabel->setProperty("useIconHighlightEffect", 0x10); +// } item->iconLabel->setPixmap(searchIcon.pixmap(searchIcon.actualSize(QSize(ICON_SIZE)))); qDebug() << "updateIcon" << item->titileLabel->text() << " finish"; } @@ -525,11 +518,17 @@ void WlanConnect::onDeviceStatusChanged() } deviceList = list; if (deviceList.isEmpty()) { - m_wifiSwitch->setCheckable(false); - m_wifiSwitch->setChecked(false); + setSwitchBtnState(false); + setSwitchBtnEnable(false); } else { - m_wifiSwitch->setCheckable(true); - setSwitchStatus(); + setSwitchBtnEnable(true); + initSwtichState(); + } + + if (!getSwitchBtnState()) { + hideLayout(ui->availableLayout); + } else { + showLayout(ui->availableLayout); } } @@ -558,10 +557,24 @@ void WlanConnect::onDeviceNameChanged(QString oldName, QString newName, int type } } +void WlanConnect::onSwitchBtnChanged(bool state) +{ + if (getSwitchBtnState() == state) { + return; + } + setSwitchBtnEnable(true); + setSwitchBtnState(state); + if (!getSwitchBtnState()) { + hideLayout(ui->availableLayout); + } else { + showLayout(ui->availableLayout); + } +} + //activeconnect status change void WlanConnect::onActiveConnectionChanged(QString deviceName, QString ssid, QString uuid, int status) { - if (!m_wifiSwitch->isChecked()) { + if (!getSwitchBtnState()) { return; } if (uuid.isEmpty()) { @@ -623,7 +636,7 @@ void WlanConnect::onActiveConnectionChanged(QString deviceName, QString ssid, QS void WlanConnect::onNetworkAdd(QString deviceName, QStringList wlanInfo) { qDebug()<<"[WlanConnect]onNetworkAdd "<< deviceName << " " << wlanInfo; - if(!m_wifiSwitch->isChecked() || deviceName.isEmpty()) { + if(!getSwitchBtnState() || deviceName.isEmpty()) { return; } @@ -676,7 +689,7 @@ void WlanConnect::onNetworkRemove(QString deviceName, QString wlannName) //获取设备列表======================================================= void WlanConnect::getDeviceList(QStringList &list) { - if (!m_interface->isValid()) { + if (m_interface == nullptr || !m_interface->isValid()) { return; } qDebug() << "[WlanConnect]call getDeviceListAndEnabled" << __LINE__; @@ -693,25 +706,23 @@ void WlanConnect::getDeviceList(QStringList &list) list = map.keys(); } -//设置开关 -void WlanConnect::setSwitchStatus() +void WlanConnect::initSwtichState() { -// if (deviceList.size() == 0) { -// m_wifiSwitch->blockSignals(true); -// m_wifiSwitch->setChecked(false); -// m_wifiSwitch->blockSignals(false); -// return; -// } - bool status = m_switchGsettings->get(WIRELESS_SWITCH).toBool(); - qDebug() << "[WlanConnect]setSwitchStatus" << status; - m_wifiSwitch->blockSignals(true); - m_wifiSwitch->setChecked(status); - m_wifiSwitch->blockSignals(false); - if (!m_wifiSwitch->isChecked()) { - hideLayout(ui->availableLayout); - } else { - showLayout(ui->availableLayout); + if (m_interface == nullptr || !m_interface->isValid()) { + return; } + + QDBusMessage result = m_interface->call("getWirelessSwitchBtnState"); + qDebug() << "[WlanConnect]call getWirelessSwitchBtnState respond" << __LINE__; + if(result.type() == QDBusMessage::ErrorMessage) + { + qWarning() << "[WlanConnect]getWirelessSwitchBtnState error:" << result.errorMessage(); + return; + } + + bool state = result.arguments().at(0).toBool(); + setSwitchBtnEnable(true); + setSwitchBtnState(state); } //初始化整体列表和单设备列表 @@ -731,7 +742,7 @@ void WlanConnect::initNet() { void WlanConnect::initNetListFromDevice(QString deviceName) { qDebug() << "[WlanConnect]initNetListFromDevice " << deviceName; - if (!m_wifiSwitch->isChecked()) { + if (!getSwitchBtnState()) { qDebug() << "[WlanConnect]initNetListFromDevice " << deviceName << " switch off"; return; } @@ -739,7 +750,7 @@ void WlanConnect::initNetListFromDevice(QString deviceName) qDebug() << "[WlanConnect]initNetListFromDevice " << deviceName << " not exist"; return; } - if (!m_interface->isValid()) { + if (m_interface == nullptr || !m_interface->isValid()) { return; } qDebug() << "[WlanConnect]call getWirelessList" << __LINE__; @@ -777,9 +788,11 @@ void WlanConnect::initNetListFromDevice(QString deviceName) //高级设置 void WlanConnect::runExternalApp() { - QString cmd = "nm-connection-editor"; - QProcess process(this); - process.startDetached(cmd); + if (!LaunchApp("nm-connection-editor.desktop")){ + QString cmd = "nm-connection-editor"; + QProcess process(this); + process.startDetached(cmd); + } } //根据信号强度分级+安全性分图标 @@ -872,6 +885,9 @@ void WlanConnect::showLayout(QVBoxLayout * layout) { //获取应该插入哪个位置 int WlanConnect::sortWlanNet(QString deviceName, QString name, QString signal) { + if (m_interface == nullptr || !m_interface->isValid()) { + return 0; + } qDebug() << "[WlanConnect]call getWirelessList" << __LINE__; QDBusMessage result = m_interface->call(QStringLiteral("getWirelessList")); qDebug() << "[WlanConnect]call getWirelessList respond" << __LINE__; @@ -898,7 +914,7 @@ int WlanConnect::sortWlanNet(QString deviceName, QString name, QString signal) } void WlanConnect::activeConnect(QString netName, QString deviceName, int type) { - if (!m_interface->isValid()) { + if (m_interface == nullptr || !m_interface->isValid()) { return; } qDebug() << "[WlanConnect]call activateConnect" << __LINE__; @@ -907,7 +923,7 @@ void WlanConnect::activeConnect(QString netName, QString deviceName, int type) { } void WlanConnect::deActiveConnect(QString netName, QString deviceName, int type) { - if (!m_interface->isValid()) { + if (m_interface == nullptr || !m_interface->isValid()) { return; } qDebug() << "[WlanConnect]call deActivateConnect" << __LINE__; @@ -960,7 +976,7 @@ void WlanConnect::addDeviceFrame(QString devName) deviceFrameMap.insert(devName, itemFrame); connect(itemFrame->addWlanWidget, &AddNetBtn::clicked, this, [=](){ - if (m_interface->isValid()) { + if (m_interface != nullptr && m_interface->isValid()) { qDebug() << "[NetConnect]call showAddOtherWlanWidget" << devName << __LINE__; m_interface->call(QStringLiteral("showAddOtherWlanWidget"), devName); qDebug() << "[NetConnect]call setDeviceEnable Respond" << __LINE__; @@ -1012,9 +1028,9 @@ void WlanConnect::addOneWlanFrame(ItemFrame *frame, QString deviceName, QString } else { iconamePath = wifiIcon(isLock, sign, category); } - if (iconamePath != KLanSymbolic && iconamePath != NoNetSymbolic) { - wlanItem->iconLabel->setProperty("useIconHighlightEffect", 0x10); - } +// if (iconamePath != KLanSymbolic && iconamePath != NoNetSymbolic) { +// wlanItem->iconLabel->setProperty("useIconHighlightEffect", 0x10); +// } QIcon searchIcon = QIcon::fromTheme(iconamePath); wlanItem->iconLabel->setPixmap(searchIcon.pixmap(searchIcon.actualSize(QSize(ICON_SIZE)))); wlanItem->titileLabel->setText(name); @@ -1026,9 +1042,9 @@ void WlanConnect::addOneWlanFrame(ItemFrame *frame, QString deviceName, QString wlanItem->statusLabel->setText(""); } - connect(wlanItem->infoLabel, &InfoButton::clicked, this, [=]{ + connect(wlanItem->infoLabel, &GrayInfoButton::clicked, this, [=]{ // open detail page - if (!m_interface->isValid()) { + if (m_interface == nullptr || !m_interface->isValid()) { return; } qDebug() << "[WlanConnect]call showPropertyWidget" << __LINE__; @@ -1094,3 +1110,18 @@ void WlanConnect::itemActiveConnectionStatusChanged(WlanItem *item, int status) } } +bool WlanConnect::LaunchApp(QString desktopFile) +{ + QDBusInterface m_appManagerDbusInterface(KYLIN_APP_MANAGER_NAME, + KYLIN_APP_MANAGER_PATH, + KYLIN_APP_MANAGER_INTERFACE, + QDBusConnection::sessionBus());//局部变量 + + if (!m_appManagerDbusInterface.isValid()) { + qWarning()<<"m_appManagerDbusInterface init error"; + return false; + } else { + QDBusReply reply =m_appManagerDbusInterface.call("LaunchApp",desktopFile); + return reply; + } +} diff --git a/plugins/wlanconnect/wlanconnect.h b/plugins/wlanconnect/wlanconnect.h index 0a7800d5..abb2c8c0 100644 --- a/plugins/wlanconnect/wlanconnect.h +++ b/plugins/wlanconnect/wlanconnect.h @@ -98,7 +98,6 @@ private: //开关相关 - void setSwitchStatus(); void hideLayout(QVBoxLayout * layout); void showLayout(QVBoxLayout * layout); @@ -124,6 +123,33 @@ private: //单个wifi连接状态变化 void itemActiveConnectionStatusChanged(WlanItem *item, int status); + + void initSwtichState(); + inline void setSwitchBtnEnable(bool state) { + if (m_wifiSwitch != nullptr) { + m_wifiSwitch->setEnabled(state); + } + } + inline bool getSwitchBtnEnable() { + if (m_wifiSwitch != nullptr) { + return m_wifiSwitch->isEnabled(); + } + } + + inline void setSwitchBtnState(bool state) { + if (m_wifiSwitch != nullptr) { + m_wifiSwitch->blockSignals(true); + m_wifiSwitch->setChecked(state); + m_wifiSwitch->blockSignals(false); + } + } + inline bool getSwitchBtnState() { + if (m_wifiSwitch != nullptr) { + return m_wifiSwitch->isChecked(); + } + } + + bool LaunchApp(QString desktopFile); protected: bool eventFilter(QObject *w,QEvent *e); @@ -136,8 +162,6 @@ private: QDBusInterface *m_interface = nullptr; - QGSettings *m_switchGsettings = nullptr; - //设备列表 QStringList deviceList; //设备名 + 单设备frame @@ -162,6 +186,8 @@ private slots: void onDeviceStatusChanged(); void onDeviceNameChanged(QString, QString, int); + void onSwitchBtnChanged(bool); + void reScan(); diff --git a/plugins/wlanconnect/wlanconnect.pro b/plugins/wlanconnect/wlanconnect.pro index f6da053d..d558656a 100644 --- a/plugins/wlanconnect/wlanconnect.pro +++ b/plugins/wlanconnect/wlanconnect.pro @@ -50,4 +50,6 @@ INSTALLS += target \ TRANSLATIONS += \ translations/zh_CN.ts \ translations/tr.ts \ - translations/bo.ts + translations/bo.ts \ + translations/bo_CN.ts \ + translations/en_US.ts diff --git a/plugins/wlanconnect/wlanitem.cpp b/plugins/wlanconnect/wlanitem.cpp index 5e076437..f4576426 100644 --- a/plugins/wlanconnect/wlanitem.cpp +++ b/plugins/wlanconnect/wlanitem.cpp @@ -1,6 +1,26 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "wlanitem.h" #include #include +#include #define FRAME_SPEED 150 #define LIMIT_TIME 60*1000 #define TOTAL_PAGE 8 @@ -15,15 +35,18 @@ WlanItem::WlanItem(bool bAcitve, bool isLock, QWidget *parent) this->setMinimumSize(550, 58); this->setProperty("useButtonPalette", true); this->setFlat(true); + QHBoxLayout *mLanLyt = new QHBoxLayout(this); mLanLyt->setContentsMargins(16,0,16,0); mLanLyt->setSpacing(16); iconLabel = new QLabel(this); + iconLabel->setProperty("useIconHighlightEffect", 0x2); titileLabel = new FixLabel(this); statusLabel = new QLabel(this); + statusLabel->setProperty("useIconHighlightEffect", 0x2); statusLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); // statusLabel->setMinimumSize(36,36); - infoLabel = new InfoButton(this); + infoLabel = new GrayInfoButton(this); mLanLyt->addWidget(iconLabel); mLanLyt->addWidget(titileLabel,Qt::AlignLeft); mLanLyt->addStretch(); @@ -40,7 +63,6 @@ WlanItem::WlanItem(bool bAcitve, bool isLock, QWidget *parent) waitTimer = new QTimer(this); connect(waitTimer, &QTimer::timeout, this, &WlanItem::updateIcon); - } WlanItem::~WlanItem() @@ -70,12 +92,17 @@ void WlanItem::stopLoading(){ void WlanItem::paintEvent(QPaintEvent *event) { - QPalette pal = this->palette(); + QPalette pal = qApp->palette(); QPainter painter(this); painter.setRenderHint(QPainter:: Antialiasing, true); //设置渲染,启动反锯齿 painter.setPen(Qt::NoPen); - painter.setBrush(pal.color(QPalette::Base)); + painter.setBrush(this->palette().base().color()); + + QColor color = pal.color(QPalette::Button); + color.setAlphaF(0.5); + pal.setColor(QPalette::Button, color); + this->setPalette(pal); QRect rect = this->rect(); diff --git a/plugins/wlanconnect/wlanitem.h b/plugins/wlanconnect/wlanitem.h index 9d24757d..035daccf 100644 --- a/plugins/wlanconnect/wlanitem.h +++ b/plugins/wlanconnect/wlanitem.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef WLANITEM_H #define WLANITEM_H #include @@ -10,7 +29,8 @@ #include #include #include "fixlabel.h" -#include "infobutton.h" +//#include "infobutton.h" +#include "../component/AddBtn/grayinfobutton.h" class WlanItem : public QPushButton { @@ -19,7 +39,7 @@ public: ~WlanItem(); public: QLabel * iconLabel = nullptr; - InfoButton * infoLabel = nullptr; + GrayInfoButton * infoLabel = nullptr; FixLabel * titileLabel = nullptr; QLabel * statusLabel = nullptr; QString uuid = ""; diff --git a/src-vpn/backend/backend.pri b/src-vpn/backend/backend.pri new file mode 100644 index 00000000..3419c1f0 --- /dev/null +++ b/src-vpn/backend/backend.pri @@ -0,0 +1,10 @@ +INCLUDEPATH += $$PWD +include(../../src/backend/dbus-interface/dbus-interface.pri) + +HEADERS += \ + $$PWD/vpndbusadaptor.h + +SOURCES += \ + $$PWD/vpndbusadaptor.cpp + +DISTFILES += diff --git a/src-vpn/backend/vpndbusadaptor.cpp b/src-vpn/backend/vpndbusadaptor.cpp new file mode 100644 index 00000000..e94ab43b --- /dev/null +++ b/src-vpn/backend/vpndbusadaptor.cpp @@ -0,0 +1,78 @@ +/* + * This file was generated by qdbusxml2cpp version 0.8 + * Command line was: qdbusxml2cpp com.kylin.weather.xml -a VpnDbusAdaptor -c VpnDbusAdaptor -l MainWindow + * + * qdbusxml2cpp is Copyright (C) 2015 The Qt Company Ltd. + * + * This is an auto-generated file. + * Do not edit! All changes made to it will be lost. + */ + +#include "vpndbusadaptor.h" +#include +#include +#include +#include +#include +#include +#include + +/* + * Implementation of adaptor class VpnDbusAdaptor + */ + +VpnDbusAdaptor::VpnDbusAdaptor(vpnObject *parent) + : QDBusAbstractAdaptor(parent) +{ + qDBusRegisterMetaType >(); + qDBusRegisterMetaType >(); + qDBusRegisterMetaType >(); + setAutoRelaySignals(true); +} + +//虚拟连接列表 +QVector VpnDbusAdaptor::getVirtualList() +{ + QVector vector; + parent()->getVirtualList(vector); + return vector; +} + +//删除 +void VpnDbusAdaptor::deleteVpn(QString uuid) +{ + qDebug() << "delete vpn" << uuid; + parent()->deleteVpn(uuid); +} + +//连接 根据网卡类型 参数1 0:lan 1:wlan 参数3 为ssid/uuid +void VpnDbusAdaptor::activateVpn(const QString& connUuid) +{ + qDebug() << "activate vpn" << connUuid; + parent()->activateVpn(connUuid); +} + +//断开连接 根据网卡类型 参数1 0:lan 1:wlan 参数3 为ssid/uuid +void VpnDbusAdaptor::deactivateVpn(const QString& connUuid) +{ + qDebug() << "deactivate vpn" << connUuid; + parent()->deactivateVpn(connUuid); +} + +void VpnDbusAdaptor::showKylinVpn() +{ + parent()->onShowMainWindow(); +} + +void VpnDbusAdaptor::showVpnAddWidget() +{ + qDebug() << "showVpnAddWidget"; + parent()->showVpnAddWidget(); +} + +void VpnDbusAdaptor::showDetailPage(const QString& connUuid) +{ + qDebug() << "showDetailPage vpn" << connUuid; + parent()->showDetailPage(connUuid); +} + diff --git a/src-vpn/backend/vpndbusadaptor.h b/src-vpn/backend/vpndbusadaptor.h new file mode 100644 index 00000000..919f092e --- /dev/null +++ b/src-vpn/backend/vpndbusadaptor.h @@ -0,0 +1,64 @@ +/* + * This file was generated by qdbusxml2cpp version 0.8 + * Command line was: qdbusxml2cpp com.kylin.weather.xml -a dbusadaptor -c DbusAdaptor -l MainWindow + * + * qdbusxml2cpp is Copyright (C) 2015 The Qt Company Ltd. + * + * This is an auto-generated file. + * This file may have been hand-edited. Look for HAND-EDIT comments + * before re-generating it. + */ + +#ifndef VPNDBUSADAPTOR_H +#define VPNDBUSADAPTOR_H + +#include +#include +#include + +#include "singlepage.h" +#include "kylinnetworkdeviceresource.h" +#include "kyvpnconnectoperation.h" + +QT_BEGIN_NAMESPACE +class QByteArray; +template class QMap; +class QString; +class QStringList; +class QVariant; +template class QVector; +QT_END_NAMESPACE + +#include "vpnobject.h" + +class VpnDbusAdaptor: public QDBusAbstractAdaptor +{ + Q_OBJECT + Q_CLASSINFO("D-Bus Interface", "com.kylin.kylinvpn") +public: + VpnDbusAdaptor(vpnObject *parent); + + inline vpnObject *parent() const + { return static_cast(QObject::parent()); } + +public Q_SLOTS: + QVector getVirtualList(); + Q_NOREPLY void deleteVpn(QString uuid); + Q_NOREPLY void activateVpn(const QString& connUuid); + Q_NOREPLY void deactivateVpn(const QString& connUuid); + Q_NOREPLY void showVpnAddWidget(); + Q_NOREPLY void showDetailPage(const QString& connUuid); + + void showKylinVpn(); + +Q_SIGNALS: + void vpnAdd(QStringList info); + void vpnRemove(QString dbusPath); + void vpnUpdate(QStringList info); + void vpnActiveConnectionStateChanged(QString uuid, int status); + + void activateFailed(QString errorMessage); + void deactivateFailed(QString errorMessage); +}; + +#endif diff --git a/src-vpn/frontend/frontend.pri b/src-vpn/frontend/frontend.pri new file mode 100644 index 00000000..0d131ba1 --- /dev/null +++ b/src-vpn/frontend/frontend.pri @@ -0,0 +1,11 @@ +INCLUDEPATH += $$PWD +include(../../src/frontend/tools/tools.pri) +include(list-items/list-items.pri) +include(vpndetails/vpndetails.pri) +include(single-pages/single-pages.pri) + +HEADERS += \ + $$PWD/vpnobject.h + +SOURCES += \ + $$PWD/vpnobject.cpp diff --git a/src-vpn/frontend/list-items/list-items.pri b/src-vpn/frontend/list-items/list-items.pri new file mode 100644 index 00000000..fefdcbe8 --- /dev/null +++ b/src-vpn/frontend/list-items/list-items.pri @@ -0,0 +1,10 @@ +INCLUDEPATH += $$PWD + +HEADERS += \ + $$PWD/listitem.h \ + $$PWD/vpnlistitem.h + +SOURCES += \ + $$PWD/listitem.cpp \ + $$PWD/vpnlistitem.cpp + diff --git a/src-vpn/frontend/list-items/listitem.cpp b/src-vpn/frontend/list-items/listitem.cpp new file mode 100644 index 00000000..6ed14804 --- /dev/null +++ b/src-vpn/frontend/list-items/listitem.cpp @@ -0,0 +1,151 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#include "listitem.h" +#include + +#define MAIN_LAYOUT_MARGINS 0,0,0,0 +#define MAIN_LAYOUT_SPACING 0 +#define ITEM_FRAME_MARGINS 12,6,16,6 + +#define ITEM_FRAME_SPACING 8 +#define FRAME_WIDTH 404 +#define INFO_ICON_WIDTH 16 +#define INFO_ICON_HEIGHT 16 +#define LIGHT_HOVER_COLOR QColor(240,240,240,255) +#define DARK_HOVER_COLOR QColor(15,15,15,255) + +ListItem::ListItem(QWidget *parent) : QFrame(parent) +{ + m_connectState = UnknownState; + + initUI(); + initConnection(); + connect(qApp, &QApplication::paletteChanged, this, &ListItem::onPaletteChanged); +// m_itemFrame->installEventFilter(this); +} + +ListItem::~ListItem() +{ + if (nullptr != m_netButton) { + delete m_netButton; + m_netButton = nullptr; + } + + if (nullptr != m_infoButton) { + delete m_infoButton; + m_infoButton = nullptr; + } + +} + +void ListItem::setName(const QString &name) +{ + m_nameLabel->setText(name); +} + +//仅无线调用,有线自己获取 +void ListItem::setActive(const bool &isActive) +{ + m_netButton->setActive(isActive); + m_isActive = isActive; +} + +void ListItem::setConnectState(ConnectState state) +{ + m_connectState = state; +} + +void ListItem::mousePressEvent(QMouseEvent *event) +{ + qDebug()<<"[ListItem]"<<"mousePressEvent"; + if (event->button() == Qt::LeftButton) { + onNetButtonClicked(); + } else if (event->button() == Qt::RightButton) { + onRightButtonClicked(); + } + return QFrame::mousePressEvent(event); +} + +void ListItem::enterEvent(QEvent *event) +{ +} + +void ListItem::leaveEvent(QEvent *event) +{ +} + +void ListItem::paintEvent(QPaintEvent *event) +{ +} + +void ListItem::initUI() +{ + m_menu = new QMenu(this);//右键菜单 +// m_menu->setStyleSheet("QMenu::item{border:3px; border-radius:3px}"); +// m_menu->setStyleSheet("QMenu{border-radius:6px; margin:6px 6px 6px 6px}"); + connect(m_menu, &QMenu::triggered, this, &ListItem::onMenuTriggered); + + m_mainLayout = new QVBoxLayout(this); + m_mainLayout->setContentsMargins(MAIN_LAYOUT_MARGINS); + m_mainLayout->setSpacing(MAIN_LAYOUT_SPACING); + this->setLayout(m_mainLayout); + + m_itemFrame = new QFrame(this); + m_itemFrame->setFixedWidth(FRAME_WIDTH); + + m_hItemLayout = new QHBoxLayout(m_itemFrame); + m_hItemLayout->setContentsMargins(ITEM_FRAME_MARGINS); + m_hItemLayout->setSpacing(ITEM_FRAME_SPACING); + m_hItemLayout->setAlignment(Qt::AlignHCenter); + + m_netButton = new RadioItemButton(m_itemFrame); + m_nameLabel = new QLabel(m_itemFrame); + m_nameLabel->setMinimumWidth(262); + m_infoButton = new InfoButton(m_itemFrame); + m_infoButton->setIconSize(QSize(INFO_ICON_WIDTH,INFO_ICON_HEIGHT)); + + m_hItemLayout->addWidget(m_netButton); + m_hItemLayout->addWidget(m_nameLabel); + m_hItemLayout->addStretch(); + m_hItemLayout->addWidget(m_infoButton); + + m_mainLayout->addWidget(m_itemFrame); + +// this->setAutoFillBackground(true); +// this->setBackgroundRole(QPalette::Base); +// QPalette pal = qApp->palette(); +// pal.setColor(QPalette::Window, qApp->palette().base().color()); +// this->setPalette(pal); +} + + +void ListItem::initConnection() +{ + connect(this->m_netButton, &RadioItemButton::clicked, this, &ListItem::onNetButtonClicked); + // connect(this->m_infoButton, &InfoButton::clicked, this, &ListItem::onInfoButtonClicked); +} + +void ListItem::onPaletteChanged() +{ +// QPalette pal = qApp->palette(); +// pal.setColor(QPalette::Window, qApp->palette().base().color()); +// this->setPalette(pal); +} + diff --git a/src-vpn/frontend/list-items/listitem.h b/src-vpn/frontend/list-items/listitem.h new file mode 100644 index 00000000..8b6c843a --- /dev/null +++ b/src-vpn/frontend/list-items/listitem.h @@ -0,0 +1,87 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#ifndef LISTITEM_H +#define LISTITEM_H +#include +#include +#include +#include +#include +#include +#include +#include "radioitembutton.h" +#include "infobutton.h" + + +typedef enum{ + UnknownState = 0, /**< The active connection is in an unknown state */ + Activating, /**< The connection is activating */ + Activated, /**< The connection is activated */ + Deactivating, /**< The connection is being torn down and cleaned up */ + Deactivated /**< The connection is no longer active */ +}ConnectState; + +class ListItem : public QFrame +{ + Q_OBJECT +public: + ListItem(QWidget *parent = nullptr); + ~ListItem(); + void setName(const QString &name); + void setActive(const bool &isActive); + void setConnectState(ConnectState state); + static void showDesktopNotify(const QString &message, QString soundName); + +protected: + void mousePressEvent(QMouseEvent *event); + void enterEvent(QEvent *event); + void leaveEvent(QEvent *event); + void paintEvent(QPaintEvent *event); + virtual void onRightButtonClicked() = 0; + +protected: + QFrame * m_itemFrame = nullptr; + + QLabel * m_nameLabel = nullptr; + RadioItemButton * m_netButton = nullptr; + InfoButton * m_infoButton = nullptr; + + bool m_isActive = false; + ConnectState m_connectState; + + QMenu *m_menu = nullptr; +public: + QVBoxLayout * m_mainLayout = nullptr; + QHBoxLayout * m_hItemLayout = nullptr; + +private: + void initUI(); + void initConnection(); + +public Q_SLOTS: + virtual void onNetButtonClicked() = 0; + void onPaletteChanged(); + virtual void onMenuTriggered(QAction *action)=0; + +Q_SIGNALS: + void detailShow(bool isShow); +}; + +#endif // LISTITEM_H diff --git a/src-vpn/frontend/list-items/vpnlistitem.cpp b/src-vpn/frontend/list-items/vpnlistitem.cpp new file mode 100644 index 00000000..64679857 --- /dev/null +++ b/src-vpn/frontend/list-items/vpnlistitem.cpp @@ -0,0 +1,249 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#include "vpnlistitem.h" +#include "kylinconnectitem.h" + +#include + +#define LOG_FLAG "[VpnListItem]" + +VpnListItem::VpnListItem(const KyConnectItem *vpnConnectItem, QWidget *parent):ListItem(parent) +{ + m_connectOperation = new KyVpnConnectOperation(this); + m_deviceResource = new KyNetworkDeviceResourse(this); + + connectItemCopy(vpnConnectItem); + + m_nameLabel->setText(m_vpnConnectItem.m_connectName); + m_netButton->setButtonIcon(QIcon::fromTheme("ukui-vpn-symbolic")); + + qDebug() << "VpnListItem init:" << m_vpnConnectItem.m_connectName << m_vpnConnectItem.m_connectState << m_vpnConnectItem.m_ifaceName; + + if (Deactivated == m_vpnConnectItem.m_connectState || Activated == m_vpnConnectItem.m_connectState) { + m_netButton->stopLoading(); + if (m_vpnConnectItem.m_connectState == Activated) { + setIcon(true); + } else { + setIcon(false); + } + } else { + m_netButton->startLoading(); + } + + m_itemFrame->installEventFilter(this); + connect(this->m_infoButton, &InfoButton::clicked, this, &VpnListItem::onInfoButtonClicked); + connect(m_menu, &QMenu::triggered, this, &VpnListItem::onMenuTriggered); +} + + +VpnListItem::VpnListItem(QWidget *parent) : ListItem(parent) +{ + m_isActive = false; + m_netButton->setButtonIcon(QIcon::fromTheme("ukui-vpn-symbolic")); + setIcon(false); + const QString str=tr("Not connected"); + m_nameLabel->setText(str); + this->m_infoButton->hide(); +} + +VpnListItem::~VpnListItem() +{ + qDebug()<<"[LanPage] lan list item is deleted." << m_vpnConnectItem.m_connectName; +} + +void VpnListItem::setIcon(bool isOn) +{ + if (isOn) { + m_netButton->setActive(true); //设置图标显示不同颜色 + } else { + m_netButton->setActive(false); + } +} + +void VpnListItem::connectItemCopy(const KyConnectItem *vpnConnectItem) +{ + if (vpnConnectItem) { + m_vpnConnectItem.m_connectName = vpnConnectItem->m_connectName; + m_vpnConnectItem.m_connectPath = vpnConnectItem->m_connectPath; + m_vpnConnectItem.m_connectState = vpnConnectItem->m_connectState; + m_vpnConnectItem.m_connectUuid = vpnConnectItem->m_connectUuid; + m_vpnConnectItem.m_ifaceName = vpnConnectItem->m_ifaceName; + m_vpnConnectItem.m_itemType = vpnConnectItem->m_itemType; + } else { + qDebug() << LOG_FLAG <<"the connect item is nullptr"; + m_vpnConnectItem.m_connectName = ""; + m_vpnConnectItem.m_connectPath = ""; + m_vpnConnectItem.m_connectState = NetworkManager::ActiveConnection::State::Unknown; + m_vpnConnectItem.m_connectUuid = ""; + m_vpnConnectItem.m_ifaceName = ""; + m_vpnConnectItem.m_itemType = NetworkManager::ConnectionSettings::ConnectionType::Unknown; + } +} + +void VpnListItem::activeConnection() +{ + if (m_vpnConnectItem.m_connectUuid.isEmpty()) { + qDebug() << LOG_FLAG << "connect is empty, so can not connect or disconnect."; + return; + } + + if (Deactivated == m_vpnConnectItem.m_connectState) { + //断开的连接,点击激活连接 + m_connectOperation->activateVpnConnection(m_vpnConnectItem.m_connectUuid); + qDebug() << LOG_FLAG << "it will activate connection" << m_vpnConnectItem.m_connectName; + m_netButton->startLoading(); + } else { + qDebug() << LOG_FLAG <<"the connection" << m_vpnConnectItem.m_connectName + << "is not deactived, so it can not be operation."; + } +} + +void VpnListItem::onNetButtonClicked() +{ + if (m_vpnConnectItem.m_connectUuid.isEmpty()) { + qDebug() << LOG_FLAG << "connect is empty, so can not connect or disconnect."; + return; + } + + if (Deactivated == m_vpnConnectItem.m_connectState) { + //断开的连接,点击激活连接 + m_connectOperation->activateVpnConnection(m_vpnConnectItem.m_connectUuid); + qDebug() << LOG_FLAG << "it will activate connection" << m_vpnConnectItem.m_connectName; + m_netButton->startLoading(); + } else { + qDebug() << LOG_FLAG <<"the connection" << m_vpnConnectItem.m_connectName + << "is not deactived, so it can not be operation."; + } +} + +void VpnListItem::onRightButtonClicked() +{ + //右键点击事件 + qDebug()<< LOG_FLAG <<"onRightButtonClicked"; + if (!m_menu) { + return; + } + + m_menu->clear(); + if (Activated == m_vpnConnectItem.m_connectState || Activating == m_vpnConnectItem.m_connectState) { + m_menu->addAction(new QAction(tr("Disconnect"), this)); + } else if (Deactivated == m_vpnConnectItem.m_connectState) { + m_menu->addAction(new QAction(tr("Connect"), this)); + } else { + return; + } + + m_menu->move(cursor().pos()); + m_menu->show(); +} + +void VpnListItem::onMenuTriggered(QAction *action) +{ + if (action->text() == tr("Connect")) { + this->onNetButtonClicked(); + } else if (action->text() == tr("Disconnect")) { + m_connectOperation->deactivateVpnConnection(m_vpnConnectItem.m_connectName, m_vpnConnectItem.m_connectUuid); + qDebug() << LOG_FLAG << "it will disconnect connection" << m_vpnConnectItem.m_connectName; + m_netButton->startLoading(); + } +} + +bool VpnListItem::launchApp(QString desktopFile) +{ + QDBusInterface appManagerDbusInterface(KYLIN_APP_MANAGER_NAME, + KYLIN_APP_MANAGER_PATH, + KYLIN_APP_MANAGER_INTERFACE, + QDBusConnection::sessionBus()); + + if (!appManagerDbusInterface.isValid()) { + qWarning()<<"appManagerDbusInterface init error"; + return false; + } else { + QDBusReply reply = appManagerDbusInterface.call("LaunchApp", desktopFile); + return reply; + } +} + +void VpnListItem::runExternalApp() { + if (!launchApp("nm-connection-editor.desktop")){ + QString cmd = "nm-connection-editor"; + QProcess process(this); + process.startDetached(cmd); + } +} + +void VpnListItem::onInfoButtonClicked() +{ + if (m_vpnConnectItem.m_itemType != NetworkManager::ConnectionSettings::ConnectionType::Vpn) { + runExternalApp(); + return; + } + + if(m_vpnDetail != nullptr){ + m_vpnDetail->activateWindow(); + return; + } + m_vpnDetail = new VpnDetail(m_vpnConnectItem.m_connectUuid, getConnectionName()); + connect(m_vpnDetail, &VpnDetail::destroyed, [&](){ + if (m_vpnDetail != nullptr) { + m_vpnDetail = nullptr; + } + }); + + m_vpnDetail->show(); + m_vpnDetail->centerToScreen(); +} + +void VpnListItem::updateConnectionState(ConnectState state) +{ + m_vpnConnectItem.m_connectState = (NetworkManager::ActiveConnection::State)state; + + if (Deactivated == state || Activated == state) { + m_netButton->stopLoading(); + if (state == Activated) { + setIcon(true); + } else { + setIcon(false); + } + } else { + m_netButton->startLoading(); + } +} + +QString VpnListItem::getConnectionName() +{ + return m_vpnConnectItem.m_connectName; +} + +void VpnListItem::updateConnectionName(QString connectionName) +{ + m_vpnConnectItem.m_connectName = connectionName; + m_nameLabel->setText(m_vpnConnectItem.m_connectName); +} + +QString VpnListItem::getConnectionPath() +{ + return m_vpnConnectItem.m_connectPath; +} + +void VpnListItem::updateConnectionPath(QString connectionPath) +{ + m_vpnConnectItem.m_connectPath = connectionPath; +} diff --git a/src-vpn/frontend/list-items/vpnlistitem.h b/src-vpn/frontend/list-items/vpnlistitem.h new file mode 100644 index 00000000..b2be2edc --- /dev/null +++ b/src-vpn/frontend/list-items/vpnlistitem.h @@ -0,0 +1,88 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#ifndef VPNLISTITEM_H +#define VPNLISTITEM_H +#include "listitem.h" +#include "kylinactiveconnectresource.h" + +#include +#include +#include +#include + +#include "vpndetails/vpndetail.h" +#include "kylinconnectresource.h" +//#include "kylinwiredconnectoperation.h" +#include "kyvpnconnectoperation.h" + + +#define KYLIN_APP_MANAGER_NAME "com.kylin.AppManager" +#define KYLIN_APP_MANAGER_PATH "/com/kylin/AppManager" +#define KYLIN_APP_MANAGER_INTERFACE "com.kylin.AppManager" + +class VpnListItem : public ListItem +{ + Q_OBJECT + +public: + VpnListItem(const KyConnectItem *vpnConnectItem, QWidget *parent = nullptr); + VpnListItem(QWidget *parent = nullptr); + + ~VpnListItem(); + +public: + void updateConnectionState(ConnectState state); + + QString getConnectionName(); + void updateConnectionName(QString connectionName); + + QString getConnectionPath(); + void updateConnectionPath(QString connectionPath); + + void activeConnection(); + +protected: + void setIcon(bool isOn); + void onRightButtonClicked(); + bool launchApp(QString desktopFile); + void runExternalApp(); + +private: + void connectItemCopy(const KyConnectItem *vpnConnectItem); + +public Q_SLOTS: + void onInfoButtonClicked(); + +private Q_SLOTS: + void onNetButtonClicked(); + void onMenuTriggered(QAction *action); + +private: + KyConnectItem m_vpnConnectItem; + + KyVpnConnectOperation *m_connectOperation = nullptr; + KyNetworkDeviceResourse *m_deviceResource = nullptr; + + QString m_deviceName = ""; + + VpnDetail *m_vpnDetail = nullptr; +}; + +#endif // VPNLISTITEM_H diff --git a/src-vpn/frontend/single-pages/single-pages.pri b/src-vpn/frontend/single-pages/single-pages.pri new file mode 100644 index 00000000..96c70dc5 --- /dev/null +++ b/src-vpn/frontend/single-pages/single-pages.pri @@ -0,0 +1,10 @@ +INCLUDEPATH += $$PWD + +HEADERS += \ + $$PWD/vpnpage.h \ + $$PWD/singlepage.h + +SOURCES += \ + $$PWD/vpnpage.cpp \ + $$PWD/singlepage.cpp + diff --git a/src-vpn/frontend/single-pages/singlepage.cpp b/src-vpn/frontend/single-pages/singlepage.cpp new file mode 100644 index 00000000..695e75e2 --- /dev/null +++ b/src-vpn/frontend/single-pages/singlepage.cpp @@ -0,0 +1,185 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#include "singlepage.h" +#include +#include +#include +#include +#include + +#include + +SinglePage::SinglePage(QWidget *parent) : QWidget(parent) +{ + initUI(); + initWindowProperties(); + initTransparency(); +} + +SinglePage::~SinglePage() +{ +} + +void SinglePage::initUI() +{ + m_mainLayout = new QVBoxLayout(this); + m_mainLayout->setContentsMargins(MAIN_LAYOUT_MARGINS); + m_mainLayout->setSpacing(MAIN_LAYOUT_SPACING); + this->setLayout(m_mainLayout); + + m_titleFrame = new QFrame(this); + m_titleFrame->setFixedHeight(TITLE_FRAME_HEIGHT); + m_titleLayout = new QHBoxLayout(m_titleFrame); + m_titleLayout->setContentsMargins(TITLE_LAYOUT_MARGINS); + m_titleFrame->setLayout(m_titleLayout); + m_titleLabel = new QLabel(m_titleFrame); + m_titleLayout->addWidget(m_titleLabel); + m_titleLayout->addStretch(); + + m_netDivider = new Divider(this); + + m_listFrame = new QFrame(this); + m_listLayout = new QVBoxLayout(m_listFrame); + m_listLayout->setContentsMargins(NET_LAYOUT_MARGINS); + m_listFrame->setLayout(m_listLayout); + m_listWidget = new QListWidget(m_listFrame); + m_listLayout->addWidget(m_listWidget); + + m_setDivider = new Divider(this); + + m_settingsFrame = new QFrame(this); + m_settingsFrame->setFixedHeight(TITLE_FRAME_HEIGHT); + m_settingsLayout = new QHBoxLayout(m_settingsFrame); + m_settingsLayout->setContentsMargins(SETTINGS_LAYOUT_MARGINS); + m_settingsLabel = new KyLable(m_settingsFrame); + m_settingsLabel->setCursor(Qt::PointingHandCursor); + m_settingsLabel->setText(tr("Settings")); + m_settingsLabel->setScaledContents(true); + m_settingsLayout->addWidget(m_settingsLabel); + m_settingsLayout->addStretch(); + m_settingsFrame->setLayout(m_settingsLayout); + + m_mainLayout->addWidget(m_titleFrame); + m_mainLayout->addWidget(m_netDivider); + m_mainLayout->addWidget(m_listFrame); + m_mainLayout->addWidget(m_setDivider); + m_mainLayout->addWidget(m_settingsFrame); +} + +void SinglePage::initWindowProperties() +{ + QPalette pal = m_listFrame->palette(); + pal.setBrush(QPalette::Base, QColor(0,0,0,0)); //背景透明 + m_listFrame->setPalette(pal); + + this->setFixedWidth(MAX_WIDTH); + this->setAttribute(Qt::WA_TranslucentBackground); + this->setProperty("useStyleWindowManager", false); //禁用拖动 + //绘制毛玻璃特效 + QString platform = QGuiApplication::platformName(); + if(!platform.startsWith(QLatin1String("wayland"),Qt::CaseInsensitive)) + { + QPainterPath path; + auto rect = this->rect(); + path.addRoundedRect(rect, 12, 12); + path.addRect(rect); + KWindowEffects::enableBlurBehind(this->winId(), true, QRegion(path.toFillPolygon().toPolygon())); //背景模糊 + } +} + +void SinglePage::showDesktopNotify(const QString &message, QString soundName) +{ + QDBusInterface iface("org.freedesktop.Notifications", + "/org/freedesktop/Notifications", + "org.freedesktop.Notifications", + QDBusConnection::sessionBus()); + QStringList actions; //跳转动作 + actions.append("kylin-vpn"); + actions.append("default"); //默认动作:点击消息体时打开麒麟录音 + QMap hints; + if (!soundName.isEmpty()) { + hints.insert("sound-name",soundName); //添加声音 + } + QList args; + args<<(tr("Kylin VPN")) + <<((unsigned int) 0) + <palette().window().color(); + + QPainterPath rectPath; + + col.setAlphaF(m_transparency); + rectPath.addRoundedRect(this->rect(),12,12); + + painter.setBrush(col); + painter.drawPath(rectPath); + KWindowEffects::enableBlurBehind(this->winId(), true, QRegion(rectPath.toFillPolygon().toPolygon())); //背景模糊 +} + +void SinglePage::initTransparency() +{ + if(QGSettings::isSchemaInstalled(QByteArray(TRANSPARENCY_GSETTINGS))) { + m_transGsettings = new QGSettings(QByteArray(TRANSPARENCY_GSETTINGS)); + if(m_transGsettings->keys().contains(TRANSPARENCY)) { + m_transparency = m_transGsettings->get(TRANSPARENCY).toDouble() + 0.15; + m_transparency = (m_transparency > 1) ? 1 : m_transparency; + connect(m_transGsettings, &QGSettings::changed, this, &SinglePage::onTransChanged); + } + } +} + +void SinglePage::onTransChanged() +{ + m_transparency = m_transGsettings->get("transparency").toDouble() + 0.15; + m_transparency = (m_transparency > 1) ? 1 : m_transparency; + paintWithTrans(); +} + +void SinglePage::paintWithTrans() +{ + QPalette pal = this->palette(); + QColor color = qApp->palette().base().color(); + color.setAlphaF(m_transparency); + pal.setColor(QPalette::Window, color); + this->setPalette(pal); +} + +void SinglePage::keyPressEvent(QKeyEvent *event) +{ + if (event->key() == Qt::Key_Escape) { + this->hide(); + } + return QWidget::keyPressEvent(event); +} + + diff --git a/src-vpn/frontend/single-pages/singlepage.h b/src-vpn/frontend/single-pages/singlepage.h new file mode 100644 index 00000000..2855b96b --- /dev/null +++ b/src-vpn/frontend/single-pages/singlepage.h @@ -0,0 +1,112 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#ifndef SINGLEPAGE_H +#define SINGLEPAGE_H + +#include "divider.h" +#include "kylable.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "kylinnetworkdeviceresource.h" +#include "kwidget.h" +#include "kswitchbutton.h" + +using namespace kdk; + +#define MAIN_LAYOUT_MARGINS 0,0,0,0 +#define MAIN_LAYOUT_SPACING 0 +#define TITLE_FRAME_HEIGHT 60 //TabWidget的tab和widget有间隙,和设计稿看起来一致就不能设为设计稿里的高度 +#define TITLE_LAYOUT_MARGINS 24,0,24,0 +#define NET_LAYOUT_MARGINS 8,8,0,8 +#define TEXT_HEIGHT 20 +#define SETTINGS_LAYOUT_MARGINS 23,0,24,0 + +#define MAX_ITEMS 4 +#define MAX_WIDTH 412 +#define MIN_WIDTH 404 + +#define SCROLL_STEP 4 + +#define TRANSPARENCY "transparency" +#define TRANSPARENCY_GSETTINGS "org.ukui.control-center.personalise" + +class SinglePage : public QWidget +{ + Q_OBJECT +public: + explicit SinglePage(QWidget *parent = nullptr); + ~SinglePage(); + + static void showDesktopNotify(const QString &message, QString soundName); + +Q_SIGNALS: + void activateFailed(QString errorMessage); + void deactivateFailed(QString errorMessage); + +private Q_SLOTS: + void onTransChanged(); + +protected: + void paintEvent(QPaintEvent *event); + void keyPressEvent(QKeyEvent *event); + +protected: + void initUI(); + void initTransparency(); + void paintWithTrans(); + + +private: + void initWindowProperties(); + +protected: + QVBoxLayout * m_mainLayout = nullptr; + + QLabel * m_titleLabel = nullptr; + QFrame * m_titleFrame = nullptr; + QHBoxLayout * m_titleLayout = nullptr; + + QFrame * m_listFrame = nullptr; + QListWidget * m_listWidget = nullptr; + QVBoxLayout * m_listLayout = nullptr; + + QFrame * m_settingsFrame = nullptr; + QHBoxLayout * m_settingsLayout = nullptr; + KyLable * m_settingsLabel = nullptr; + + Divider * m_netDivider = nullptr; + Divider * m_setDivider = nullptr; + + + QGSettings * m_transGsettings = nullptr; + double m_transparency = 1.0; //透明度 + +}; + +#endif // TABPAGE_H diff --git a/src-vpn/frontend/single-pages/vpnpage.cpp b/src-vpn/frontend/single-pages/vpnpage.cpp new file mode 100644 index 00000000..e2cb274b --- /dev/null +++ b/src-vpn/frontend/single-pages/vpnpage.cpp @@ -0,0 +1,690 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#include "vpnpage.h" +#include +#include +#include "windowmanager/windowmanager.h" + + +VpnPage::VpnPage(QWidget *parent) : SinglePage(parent) +{ + m_activeResourse = new KyActiveConnectResourse(this); + m_connectResourse = new KyConnectResourse(this); + m_vpnConnectOperation = new KyVpnConnectOperation(this); + + initUI(); + initVpnArea(); + installEventFilter(this); + + connect(m_activeResourse, &KyActiveConnectResourse::stateChangeReason, this, &VpnPage::onConnectionStateChange); + connect(m_activeResourse, &KyActiveConnectResourse::activeConnectRemove, this, [=] (QString activeConnectUuid) { + sendVpnStateChangeSignal(activeConnectUuid,Deactivated); + } ); + + connect(m_connectResourse, &KyConnectResourse::connectionAdd, this, &VpnPage::onAddConnection); + connect(m_connectResourse, &KyConnectResourse::connectionRemove, this, &VpnPage::onRemoveConnection); + connect(m_connectResourse, &KyConnectResourse::connectionUpdate, this, &VpnPage::onUpdateConnection); + + connect(m_vpnConnectOperation, &KyVpnConnectOperation::activateConnectionError, this, &VpnPage::activateFailed); + connect(m_vpnConnectOperation, &KyVpnConnectOperation::deactivateConnectionError, this, &VpnPage::deactivateFailed); + + connect(KWindowSystem::self(), &KWindowSystem::activeWindowChanged, this, [&](WId activeWindowId){ + if (activeWindowId != this->winId() && activeWindowId != 0) { + hide(); + } + }); +} + +VpnPage::~VpnPage() +{ + +} + +void VpnPage::deleteConnectionMapItem(QMap &connectMap, + QListWidget *vpnListWidget, QString uuid) +{ + QListWidgetItem *p_listWidgetItem = connectMap.value(uuid); + if (p_listWidgetItem) { + connectMap.remove(uuid); + VpnListItem *p_vpnItem = (VpnListItem *)vpnListWidget->itemWidget(p_listWidgetItem); + vpnListWidget->removeItemWidget(p_listWidgetItem); + + delete p_vpnItem; + p_vpnItem = nullptr; + + delete p_listWidgetItem; + p_listWidgetItem = nullptr; + } + + return; +} + +void VpnPage::clearConnectionMap(QMap &connectMap, + QListWidget *vpnListWidget) +{ + QMap::iterator iter; + + iter = connectMap.begin(); + while (iter != connectMap.end()) { + qDebug()<<"[VpnPage] clear connection map item"<< iter.key(); + + QListWidgetItem *p_widgetItem = iter.value(); + VpnListItem *p_vpnItem = (VpnListItem *)vpnListWidget->itemWidget(p_widgetItem); + vpnListWidget->removeItemWidget(p_widgetItem); + + delete p_vpnItem; + p_vpnItem = nullptr; + + delete p_widgetItem; + p_widgetItem = nullptr; + + iter = connectMap.erase(iter); + } + + return; +} + +void VpnPage::constructItemArea() +{ + QList activedList; + QList netList; + + activedList.clear(); + netList.clear(); + clearConnectionMap(m_activeItemMap, m_listWidget); + clearConnectionMap(m_vpnItemMap, m_listWidget); + + m_connectResourse->getVpnAndVirtualConnections(netList); + KyConnectItem *p_newItem = nullptr; + if (!netList.isEmpty()) { + for (int index = 0; index < netList.size(); index++) { + KyConnectItem *p_netConnectionItem = netList.at(index); + p_newItem = m_activeResourse->getActiveConnectionByUuid(p_netConnectionItem->m_connectUuid); + if (p_newItem == nullptr) { + if (m_vpnItemMap.contains(p_netConnectionItem->m_connectUuid)) { + qDebug()<m_connectUuid; + } + QListWidgetItem *p_listWidgetItem = addNewItem(p_netConnectionItem, m_listWidget); + m_vpnItemMap.insert(p_netConnectionItem->m_connectUuid, p_listWidgetItem); + } else { + if (m_activeItemMap.contains(p_netConnectionItem->m_connectUuid)) { + qDebug()<m_connectUuid; + } + QListWidgetItem *p_listWidgetItem = addNewItem(p_newItem, m_listWidget); + m_activeItemMap.insert(p_netConnectionItem->m_connectUuid, p_listWidgetItem); + } + + delete p_netConnectionItem; + p_netConnectionItem = nullptr; + } + } + + if (QGSettings::isSchemaInstalled(GSETTINGS_VPNICON_VISIBLE)) { + QGSettings vpnGsettings(GSETTINGS_VPNICON_VISIBLE); + if (vpnGsettings.keys().contains(QString(VISIBLE))) { + if (!netList.isEmpty()) { + vpnGsettings.set(VISIBLE, true); + } else { + vpnGsettings.set(VISIBLE, false); + } + } + } + + resetListWidgetWidth(); +} + +void VpnPage::initVpnArea() +{ + constructItemArea(); +} + +void VpnPage::resetPageHeight() +{ + int height = 0; + int count = m_listWidget->count(); + m_listFrame->setFixedHeight((count >= 4) ? (MAX_ITEMS * ITEM_HEIGHT + ITEM_SPACE) : (count * ITEM_HEIGHT + ITEM_SPACE)); + + if (count == 0) { + m_listWidget->setHidden(true); + m_listFrame->setHidden(true); + m_netDivider->setHidden(true); + } else { + m_listWidget->show(); + m_listFrame->show(); + m_netDivider->show(); + } +} + +bool VpnPage::removeConnectionItem(QMap &connectMap, + QListWidget *vpnListWidget, QString path) +{ + QMap::iterator iter; + for (iter = connectMap.begin(); iter != connectMap.end(); ++iter) { + QListWidgetItem *p_listWidgetItem = iter.value(); + VpnListItem *p_vpnItem = (VpnListItem*)vpnListWidget->itemWidget(p_listWidgetItem); + if (p_vpnItem->getConnectionPath() == path) { + qDebug()<<"[VpnPage] Remove a connection from list"; + + vpnListWidget->removeItemWidget(p_listWidgetItem); + + delete p_vpnItem; + p_vpnItem = nullptr; + + delete p_listWidgetItem; + p_listWidgetItem = nullptr; + + iter = connectMap.erase(iter); + resetListWidgetWidth(); + return true; + } + } + + return false; +} + +void VpnPage::onRemoveConnection(QString path) //删除时后端会自动断开激活,将其从未激活列表中删除 +{ + //for dbus + qDebug() << "[VpnPage] emit lanRemove because onRemoveConnection " << path; + Q_EMIT vpnRemove(path); + + removeConnectionItem(m_vpnItemMap, m_listWidget, path); + removeConnectionItem(m_activeItemMap, m_listWidget, path); + resetPageHeight(); + resetWindowPosition(); + this->update(); +} + +void VpnPage::onAddConnection(QString uuid) //新增一个有线连接,将其加入到激活列表 +{ + if (!m_connectResourse->isVirtualConncection(uuid)) { + return; + } + + KyConnectItem *p_newItem = nullptr; + p_newItem = m_connectResourse->getConnectionItemByUuid(uuid); + if (nullptr == p_newItem) { + return; + } + + sendVpnAddSignal(p_newItem); + + qDebug()<<"[VpnPage] Add a new connection, name:"<m_connectName; + QListWidgetItem *p_listWidgetItem = insertNewItem(p_newItem, m_listWidget); + if (m_vpnItemMap.contains(p_newItem->m_connectUuid)) { + qDebug()<m_connectUuid; + } + m_vpnItemMap.insert(p_newItem->m_connectUuid, p_listWidgetItem); + + delete p_newItem; + p_newItem = nullptr; + resetListWidgetWidth(); + resetPageHeight(); + resetWindowPosition(); + this->update(); + return; +} + +void VpnPage::onShowControlCenter() +{ + QProcess process; + process.startDetached("ukui-control-center -m vpn"); +} + +void VpnPage::initUI() +{ + m_titleLabel->setText(tr("VPN")); + +// m_listFrame->setMaximumHeight(MAX_ITEMS * ITEM_HEIGHT + ITEM_SPACE); + + m_listWidget->setFrameShape(QFrame::Shape::NoFrame); + m_listWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + m_listWidget->setVerticalScrollMode(QAbstractItemView::ScrollMode::ScrollPerPixel); + m_listWidget->verticalScrollBar()->setProperty("drawScrollBarGroove",false); //去除滚动条的外侧黑框 + m_listWidget->verticalScrollBar()->setSingleStep(SCROLL_STEP); + m_listWidget->verticalScrollBar()->setContextMenuPolicy(Qt::NoContextMenu); + + m_settingsLabel->setText(tr("VPN Settings")); + m_settingsLabel->installEventFilter(this); +} + +QListWidgetItem *VpnPage::insertNewItem(KyConnectItem *itemData, QListWidget *listWidget) +{ + int index = 0; + + for(index = 0; index < m_listWidget->count(); index++) { + QListWidgetItem *p_listWidgetItem = m_listWidget->item(index); + VpnListItem *p_vpnItem = (VpnListItem *)m_listWidget->itemWidget(p_listWidgetItem); + QString name1 = p_vpnItem->getConnectionName(); + QString name2 = itemData->m_connectName; + if (QString::compare(name1, name2, Qt::CaseInsensitive) > 0) { + break; + } + } + + QListWidgetItem *p_sortListWidgetItem = new QListWidgetItem(); + p_sortListWidgetItem->setFlags(p_sortListWidgetItem->flags() & (~Qt::ItemIsSelectable)); //设置不可被选中 + p_sortListWidgetItem->setSizeHint(QSize(listWidget->width(),ITEM_HEIGHT)); + + listWidget->insertItem(index, p_sortListWidgetItem); + + VpnListItem *p_sortLanItem = nullptr; + p_sortLanItem = new VpnListItem(itemData); + listWidget->setItemWidget(p_sortListWidgetItem, p_sortLanItem); + + return p_sortListWidgetItem; +} + +QListWidgetItem *VpnPage::addNewItem(KyConnectItem *itemData, QListWidget *listWidget) +{ + QListWidgetItem *p_listWidgetItem = new QListWidgetItem(); + p_listWidgetItem->setFlags(p_listWidgetItem->flags() & (~Qt::ItemIsSelectable)); + p_listWidgetItem->setSizeHint(QSize(listWidget->width() - 16, ITEM_HEIGHT)); + listWidget->addItem(p_listWidgetItem); + VpnListItem *p_vpnItem = nullptr; + if (itemData != nullptr) { + p_vpnItem = new VpnListItem(itemData); + qDebug() << "[VpnPage] addNewItem, connection: " << itemData->m_connectName; + } else { + p_vpnItem = new VpnListItem(); + qDebug() << "[VpnPage] Add nullItem!"; + } + + listWidget->setItemWidget(p_listWidgetItem, p_vpnItem); + return p_listWidgetItem; +} + +void VpnPage::updateActivatedConnectionArea(KyConnectItem *p_newItem) +{ + if (m_activeItemMap.contains(p_newItem->m_connectUuid)) { + return; + } + + deleteConnectionMapItem(m_vpnItemMap, m_listWidget, p_newItem->m_connectUuid); + qDebug()<<"[VpnPage]update active connection item"<m_connectName; + deleteConnectionMapItem(m_activeItemMap, m_listWidget, p_newItem->m_connectUuid); + QListWidgetItem *p_listWidgetItem = addNewItem(p_newItem, m_listWidget); + m_activeItemMap.insert(p_newItem->m_connectUuid, p_listWidgetItem); + + resetListWidgetWidth(); + + return; +} + +void VpnPage::updateConnectionArea(KyConnectItem *p_newItem) +{ + if (m_vpnItemMap.contains(p_newItem->m_connectUuid)) { + return; + } + + deleteConnectionMapItem(m_activeItemMap, m_listWidget, p_newItem->m_connectUuid); + qDebug()<<"[VpnPage] update connection item"<m_connectName; + QListWidgetItem *p_listWidgetItem = insertNewItem(p_newItem, m_listWidget); + m_vpnItemMap.insert(p_newItem->m_connectUuid, p_listWidgetItem); + + resetListWidgetWidth(); +} + +void VpnPage::updateConnectionState(QMap &connectMap, + QListWidget *vpnListWidget, QString uuid, ConnectState state) +{ + qDebug() << LOG_FLAG << "update connection state"; + + QListWidgetItem *p_listWidgetItem = connectMap.value(uuid); + if (p_listWidgetItem) { + VpnListItem *p_vpnItem = (VpnListItem *)vpnListWidget->itemWidget(p_listWidgetItem); + p_vpnItem->updateConnectionState(state); + } + +} + +void VpnPage::onConnectionStateChange(QString uuid, + NetworkManager::ActiveConnection::State state, + NetworkManager::ActiveConnection::Reason reason) +{ + //VpnPage函数内持续监听连接状态的变化并记录供其他函数调用获取状态 + if (!m_connectResourse->isVirtualConncection(uuid)) { + qDebug() << "[VpnPage] connection state change signal but not vpn"; + return; + } + + sendVpnStateChangeSignal(uuid, (ConnectState)state); + + if (m_activeItemMap.keys().contains(uuid) && state == NetworkManager::ActiveConnection::State::Activated) { + return; + } + + qDebug()<<"[VpnPage] connection uuid"<< uuid + << "state change slot:"<< state; + + KyConnectItem *p_newItem = nullptr; + QString deviceName = ""; + QString ssid = ""; + + if (state == NetworkManager::ActiveConnection::State::Activated) { + p_newItem = m_activeResourse->getActiveConnectionByUuid(uuid); + if (nullptr == p_newItem) { + qWarning()<<"[VpnPage] get active connection failed, connection uuid" << uuid; + return; + } + + ssid = p_newItem->m_connectName; + updateActivatedConnectionArea(p_newItem); + updateConnectionState(m_activeItemMap, m_listWidget, uuid, (ConnectState)state); + } else if (state == NetworkManager::ActiveConnection::State::Deactivated) { + p_newItem = m_connectResourse->getConnectionItemByUuid(uuid); + qDebug() << "[VpnPage] deactivated reason" << reason; + if (nullptr == p_newItem) { + qWarning()<<"[VpnPage] get active connection failed, connection uuid" << uuid; + return; + } + + ssid = p_newItem->m_connectName; + updateConnectionArea(p_newItem); + updateConnectionState(m_vpnItemMap, m_listWidget, uuid, (ConnectState)state); + } else if (state == NetworkManager::ActiveConnection::State::Activating) { + updateConnectionState(m_vpnItemMap, m_listWidget, uuid, (ConnectState)state); + } else if (state == NetworkManager::ActiveConnection::State::Deactivating) { + updateConnectionState(m_activeItemMap, m_listWidget, uuid, (ConnectState)state); + } + + Q_EMIT vpnActiveConnectionStateChanged(uuid, state); + + if (p_newItem) { + delete p_newItem; + p_newItem = nullptr; + } + + return; +} + +void VpnPage::getVirtualList(QVector &vector) +{ + QList netConnectList; + vector.clear(); + m_connectResourse->getVpnAndVirtualConnections(netConnectList); //未激活列表的显示 + if (!netConnectList.isEmpty()) { + for (int i = 0; i < netConnectList.size(); i++) { + KyConnectItem *p_newItem = nullptr; + KyConnectItem *p_netConnectionItem = netConnectList.at(i); + p_newItem = m_activeResourse->getActiveConnectionByUuid(p_netConnectionItem->m_connectUuid); + NetworkManager::ActiveConnection::State state = p_netConnectionItem->m_connectState; + if (p_newItem != nullptr) { + state = NetworkManager::ActiveConnection::Activated; + } + vector.append(QStringList() << netConnectList.at(i)->m_connectName + << netConnectList.at(i)->m_connectUuid + << netConnectList.at(i)->m_connectPath + << QString::number(state)); + } + } + return; +} + +void VpnPage::sendVpnUpdateSignal(KyConnectItem *p_connectItem) +{ + QStringList info; + info << p_connectItem->m_connectName << p_connectItem->m_connectUuid << p_connectItem->m_connectPath; + Q_EMIT vpnUpdate(info); + + return; +} + +void VpnPage::sendVpnAddSignal(KyConnectItem *p_connectItem) +{ + QStringList info; + KyConnectItem *p_newItem = nullptr; + p_newItem = m_activeResourse->getActiveConnectionByUuid(p_connectItem->m_connectUuid); + NetworkManager::ActiveConnection::State state = p_connectItem->m_connectState; + if (p_newItem != nullptr) { + state = NetworkManager::ActiveConnection::Activated; + } + info << p_connectItem->m_connectName + << p_connectItem->m_connectUuid + << p_connectItem->m_connectPath + << QString::number(state); + qDebug() << "[VpnPage] emit vpnAdd because addConnection "; + Q_EMIT vpnAdd(info); + + return; +} + +void VpnPage::sendVpnStateChangeSignal(QString uuid, ConnectState state) +{ + if (state == Activating || state == Deactivating) { + if (m_activeResourse->connectionIsVirtual(uuid)) { + return; + } + } + + Q_EMIT this->vpnConnectChanged(state); + + return; +} + +void VpnPage::updateConnectionProperty(KyConnectItem *p_connectItem) +{ + QString newUuid = p_connectItem->m_connectUuid; + + if (m_vpnItemMap.contains(newUuid)) { + QListWidgetItem *p_listWidgetItem = m_vpnItemMap.value(newUuid); + VpnListItem *p_vpnItem = (VpnListItem*)m_listWidget->itemWidget(p_listWidgetItem); + if (p_connectItem->m_connectName != p_vpnItem->getConnectionName()){ + //只要名字改变就要删除,重新插入,主要是为了排序 + deleteConnectionMapItem(m_vpnItemMap, m_listWidget, newUuid); + QListWidgetItem *p_sortListWidgetItem = insertNewItem(p_connectItem, m_listWidget); + if (m_vpnItemMap.contains(newUuid)) { + qDebug()<m_connectPath != p_vpnItem->getConnectionPath()) { + p_vpnItem->updateConnectionPath(p_connectItem->m_connectPath); + } + } else if (!m_activeItemMap.contains(newUuid)){ + if (p_connectItem->m_ifaceName.isEmpty()) { + QListWidgetItem *p_listWidgetItem = insertNewItem(p_connectItem, m_listWidget); + if (m_vpnItemMap.contains(newUuid)) { + qDebug()<m_connectUuid; + + if (m_activeItemMap.contains(newUuid)) { + QListWidgetItem *p_listWidgetItem = m_activeItemMap.value(newUuid); + VpnListItem *p_vpnItem = (VpnListItem *)m_listWidget->itemWidget(p_listWidgetItem); + if (p_vpnItem->getConnectionName() != p_connectItem->m_connectName) { + p_vpnItem->updateConnectionName(p_connectItem->m_connectName); + } + + if (p_vpnItem->getConnectionName() != p_connectItem->m_connectPath) { + p_vpnItem->updateConnectionPath(p_connectItem->m_connectPath); + } + } + return; +} + +void VpnPage::onUpdateConnection(QString uuid) +{ + if (!m_connectResourse->isVirtualConncection(uuid)) { + return; + } + + qDebug() << "[VpnPage]:Connection property Changed." << Q_FUNC_INFO << __LINE__; + + KyConnectItem *p_newItem = nullptr; + if (m_connectResourse->isActivatedConnection(uuid)) { + p_newItem = m_activeResourse->getActiveConnectionByUuid(uuid); + if (nullptr == p_newItem) { + qWarning()<<"[VpnPage] get item failed, when update activate connection." + <<"connection uuid" << uuid; + return; + } + + updateActiveConnectionProperty(p_newItem); + } else { + p_newItem = m_connectResourse->getConnectionItemByUuid(uuid); + if (nullptr == p_newItem) { + qWarning()<<"[VpnPage] get item failed, when update connection." + <<"connection uuid"<type() == QEvent::MouseButtonRelease) { + onShowControlCenter(); + } + } + + return QWidget::eventFilter(watched, event); +} + +void VpnPage::deleteVpn(const QString &connUuid) +{ + qDebug() << "[VpnPage] deleteVpn" << connUuid; + if (connUuid == nullptr) { + return; + } + m_vpnConnectOperation->deleteVpnConnect(connUuid); +} + +void VpnPage::activateVpn(const QString& connUuid) +{ + if (m_vpnItemMap.contains(connUuid)) { + qDebug() << "[VpnPage] activateVpn" << connUuid; + m_vpnConnectOperation->activateVpnConnection(connUuid); + } +} + +void VpnPage::deactivateVpn(const QString& connUuid) +{ + qDebug() << "[VpnPage] deactivateVpn" << connUuid; + QString name(""); + m_vpnConnectOperation->deactivateVpnConnection(name, connUuid); +} + +void VpnPage::showDetailPage(QString uuid) +{ + QListWidgetItem * vpnlistItem = m_vpnItemMap.value(uuid); + VpnListItem *vpnItem = (VpnListItem *)m_listWidget->itemWidget(vpnlistItem); + vpnItem->onInfoButtonClicked(); +} + +void VpnPage::showUI() +{ + //2209中窗管在hide界面时会刷新属性,需要重新设置无图标属性 + const KWindowInfo info(this->winId(), NET::WMState); + if (!info.hasState(NET::SkipTaskbar) || !info.hasState(NET::SkipPager)) { + KWindowSystem::setState(this->winId(), NET::SkipTaskbar | NET::SkipPager); + } + + resetPageHeight(); + + showNormal(); + raise(); + activateWindow(); + resetWindowPosition(); + return; +} + +void VpnPage::resetWindowPosition() +{ + +#define MARGIN 4 +#define PANEL_TOP 1 +#define PANEL_LEFT 2 +#define PANEL_RIGHT 3 +//#define PANEL_BOTTOM 4 + if (!m_positionInterface) { + m_positionInterface = new QDBusInterface("org.ukui.panel", + "/panel/position", + "org.ukui.panel", + QDBusConnection::sessionBus()); + } + QRect rect; + QDBusReply reply = m_positionInterface->call("GetPrimaryScreenGeometry"); + //reply获取的参数共5个,分别是 主屏可用区域的起点x坐标,主屏可用区域的起点y坐标,主屏可用区域的宽度,主屏可用区域高度,任务栏位置 + if (!m_positionInterface->isValid() || !reply.isValid() || reply.value().size() < 5) { + qCritical() << QDBusConnection::sessionBus().lastError().message(); + kdk::WindowManager::setGeometry(this->windowHandle(), QRect(0, 0, this->width(), this->height())); + return; + } + QVariantList position_list = reply.value(); + int position = position_list.at(4).toInt(); + switch(position){ + case PANEL_TOP: + //任务栏位于上方 + rect = QRect(position_list.at(0).toInt() + position_list.at(2).toInt() - this->width() - MARGIN, + position_list.at(1).toInt() + MARGIN, + this->width(), this->height()); + break; + //任务栏位于左边 + case PANEL_LEFT: + rect = QRect(position_list.at(0).toInt() + MARGIN, + position_list.at(1).toInt() + reply.value().at(3).toInt() - this->height() - MARGIN, + this->width(), this->height()); + break; + //任务栏位于右边 + case PANEL_RIGHT: + rect = QRect(position_list.at(0).toInt() + position_list.at(2).toInt() - this->width() - MARGIN, + position_list.at(1).toInt() + reply.value().at(3).toInt() - this->height() - MARGIN, + this->width(), this->height()); + break; + //任务栏位于下方 + default: + rect = QRect(position_list.at(0).toInt() + position_list.at(2).toInt() - this->width() - MARGIN, + position_list.at(1).toInt() + reply.value().at(3).toInt() - this->height() - MARGIN, + this->width(), this->height()); + break; + } + kdk::WindowManager::setGeometry(this->windowHandle(), rect); + qDebug() << " Position of ukui-panel is " << position << "; Position of mainwindow is " << this->geometry() << "." << Q_FUNC_INFO << __LINE__; +} + +void VpnPage::resetListWidgetWidth() +{ + if (m_listWidget->count() <= MAX_ITEMS) { + m_listFrame->setFixedWidth(MIN_WIDTH); + } else { + m_listFrame->setFixedWidth(MAX_WIDTH); + } +} diff --git a/src-vpn/frontend/single-pages/vpnpage.h b/src-vpn/frontend/single-pages/vpnpage.h new file mode 100644 index 00000000..e5748723 --- /dev/null +++ b/src-vpn/frontend/single-pages/vpnpage.h @@ -0,0 +1,137 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#ifndef VPNPAGE_H +#define VPNPAGE_H + +#include "divider.h" +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "list-items/listitem.h" +#include "list-items/vpnlistitem.h" +#include "single-pages/singlepage.h" + +#define VPNPAGE_LAYOUT_MARGINS 0,0,0,0 +#define VPN_LIST_SPACING 0 +#define ITEM_HEIGHT 50 +#define ITEM_SPACE 16 +#define PAGE_SPACE 22 + +#define LOG_FLAG "[VpnPage]" + +#define VISIBLE "visible" +const QByteArray GSETTINGS_VPNICON_VISIBLE = "org.ukui.kylin-nm.vpnicon"; + +class VpnListItem; + +class VpnPage : public SinglePage +{ + Q_OBJECT +public: + explicit VpnPage(QWidget *parent = nullptr); + ~VpnPage(); + + //for dbus + void getVirtualList(QVector &vector); + void deleteVpn(const QString &connUuid); + void activateVpn(const QString& connUuid); + void deactivateVpn(const QString& connUuid); + void showDetailPage(QString uuid); + +protected: + bool eventFilter(QObject *watched, QEvent *event); + +private: + void initUI(); + void initVpnArea(); + void resetPageHeight(); + + inline void initDeviceCombox() { return; } + + QListWidgetItem *insertNewItem(KyConnectItem *itemData, QListWidget *listWidget); + QListWidgetItem *addNewItem(KyConnectItem *itemData, QListWidget *listWidget); + bool removeConnectionItem(QMap &connectMap, + QListWidget *vpnListWidget, QString path); + + void constructItemArea(); + + void updateConnectionArea(KyConnectItem *p_newItem); + void updateActivatedConnectionArea(KyConnectItem *p_newItem); + void updateConnectionState(QMap &connectMap, + QListWidget *vpnListWidget, QString uuid, ConnectState state); + + void updateActiveConnectionProperty(KyConnectItem *p_connectItem); + void updateConnectionProperty(KyConnectItem *p_connectItem); + + void sendVpnUpdateSignal(KyConnectItem *p_connectItem); + void sendVpnAddSignal(KyConnectItem *p_connectItem); + void sendVpnStateChangeSignal(QString uuid, ConnectState state); + + void clearConnectionMap(QMap &connectMap, + QListWidget *vpnListWidget); + void deleteConnectionMapItem(QMap &connectMap, + QListWidget *vpnListWidget, QString uuid); + + void resetWindowPosition(); + void resetListWidgetWidth(); + +Q_SIGNALS: + void vpnAdd(QStringList info); + void vpnRemove(QString dbusPath); + void vpnUpdate(QStringList info); + + void vpnActiveConnectionStateChanged(QString uuid, int status); + void vpnConnectChanged(int state); + +private Q_SLOTS: + void onConnectionStateChange(QString uuid, + NetworkManager::ActiveConnection::State state, + NetworkManager::ActiveConnection::Reason reason); + + void onAddConnection(QString uuid); + void onRemoveConnection(QString path); + void onUpdateConnection(QString uuid); + + void onShowControlCenter(); + +private: + KyVpnConnectOperation *m_vpnConnectOperation = nullptr; + KyActiveConnectResourse *m_activeResourse = nullptr; //激活的连接 + KyConnectResourse *m_connectResourse = nullptr; //未激活的连接 + + QMap m_vpnItemMap; + QMap m_activeItemMap; + + QDBusInterface * m_positionInterface = nullptr; + + + +public Q_SLOTS: + void showUI(); +}; + +#endif // LANPAGE_H diff --git a/src-vpn/frontend/vpndetails/vpnaddpage.cpp b/src-vpn/frontend/vpndetails/vpnaddpage.cpp new file mode 100644 index 00000000..087470d1 --- /dev/null +++ b/src-vpn/frontend/vpndetails/vpnaddpage.cpp @@ -0,0 +1,234 @@ +#include "vpnaddpage.h" +#include +#include "vpnconfigpage.h" + +vpnAddPage::vpnAddPage(QWidget *parent) : QWidget(parent) +{ + m_vpnConnOperation = new KyVpnConnectOperation(this); + initWindow(); + initUI(); + initConnection(); + centerToScreen(); +} + +void vpnAddPage::centerToScreen() +{ + QDesktopWidget* m = QApplication::desktop(); + QRect desk_rect = m->screenGeometry(m->screenNumber(QCursor::pos())); + int desk_x = desk_rect.width(); + int desk_y = desk_rect.height(); + int x = this->width(); + int y = this->height(); + this->move(desk_x / 2 - x / 2 + desk_rect.left(), desk_y / 2 - y / 2 + desk_rect.top()); +} + +void vpnAddPage::initWindow() +{ + this->setFixedSize(VPNADDPAGE_SIZE); + this->setWindowTitle(tr("create VPN")); + this->setWindowFlag(Qt::WindowMinMaxButtonsHint,false); + this->setAttribute(Qt::WA_DeleteOnClose); +} + +void vpnAddPage::initUI() +{ + QVBoxLayout *mainLayout = new QVBoxLayout(this); + mainLayout->setContentsMargins(VPNADDPAGE_MAINLAYOUT_MARGINS); + mainLayout->setSpacing(VPNADDPAGE_NULLSPACE); + + initVpnTypeFrame(); + initVpnNameFrame(); + initVpnServerFrame(); + initButtonFrame(); + onSetConfimBtnEnable(); + + mainLayout->addWidget(m_vpnTypeFrame); + mainLayout->addWidget(m_vpnNameFrame); + mainLayout->addWidget(m_vpnServerFrame); + mainLayout->addStretch(); + mainLayout->addWidget(m_buttonFrame); + this->setLayout(mainLayout); +} + +void vpnAddPage::initVpnTypeFrame() +{ + m_vpnTypeFrame = new QFrame(this); + m_vpnTypeFrame->setFrameShape(QFrame::Shape::NoFrame); + m_vpnTypeFrame->setFixedSize(VPNADDPAGE_FRAME_FIXEDSIZE); + + QHBoxLayout *typeLayout = new QHBoxLayout(m_vpnTypeFrame); + typeLayout->setContentsMargins(VPNADDPAGE_ITEM_MARGINS); + typeLayout->setSpacing(VPNADDPAGE_NULLSPACE); + + QLabel *vpnTypeLabel = new QLabel(tr("VPN Type"), this); + vpnTypeLabel->setFixedWidth(VPNADDPAGE_LABLE_FIXEDWIDTH); + + m_vpnTypeComboBox = new QComboBox(this); + m_vpnTypeComboBox->setInsertPolicy(QComboBox::NoInsert); + m_vpnTypeComboBox->setFixedWidth(VPNADDPAGE_COMBOBOX_FIXEDWIDTH); + m_vpnTypeComboBox->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed); + + m_vpnTypeComboBox->addItem("L2TP", L2TP); + m_vpnTypeComboBox->addItem("open VPN", OPEN_VPN); + m_vpnTypeComboBox->addItem("PPTP", PPTP); + m_vpnTypeComboBox->addItem("strong-swan", STRONG_SWAN); + + + typeLayout->addWidget(vpnTypeLabel); + typeLayout->addWidget(m_vpnTypeComboBox); + m_vpnTypeFrame->setLayout(typeLayout); +} + +void vpnAddPage::initVpnNameFrame() +{ + m_vpnNameFrame = new QFrame(this); + m_vpnNameFrame->setFrameShape(QFrame::Shape::NoFrame); + m_vpnNameFrame->setFixedSize(VPNADDPAGE_FRAME_FIXEDSIZE); + + QHBoxLayout *nameLayout = new QHBoxLayout(m_vpnNameFrame); + nameLayout->setContentsMargins(VPNADDPAGE_ITEM_MARGINS); + nameLayout->setSpacing(VPNADDPAGE_NULLSPACE); + + QLabel *vpnNameLabel = new QLabel(tr("VPN Name"), this); + vpnNameLabel->setFixedWidth(VPNADDPAGE_LABLE_FIXEDWIDTH); + + m_vpnNameLineEdit = new QLineEdit(this); + m_vpnNameLineEdit->setFixedWidth(VPNADDPAGE_INPUTBOX_FIXEDWIDTH); + m_vpnNameLineEdit->setMaxLength(VPNADDPAGE_NAME_MAX_LENGTH); + m_vpnNameLineEdit->setPlaceholderText(tr("Required")); //必填 + + nameLayout->addWidget(vpnNameLabel); + nameLayout->addWidget(m_vpnNameLineEdit); + m_vpnNameFrame->setLayout(nameLayout); +} + +void vpnAddPage::initVpnServerFrame() +{ + m_vpnServerFrame = new QFrame(this); + m_vpnServerFrame->setFrameShape(QFrame::Shape::NoFrame); + m_vpnServerFrame->setFixedSize(VPNADDPAGE_FRAME_FIXEDSIZE); + + QHBoxLayout *serverLayout = new QHBoxLayout(m_vpnServerFrame); + serverLayout->setContentsMargins(VPNADDPAGE_ITEM_MARGINS); + serverLayout->setSpacing(VPNADDPAGE_NULLSPACE); + + QLabel *vpnServerLabel = new QLabel(tr("VPN Server"), this); + vpnServerLabel->setFixedWidth(VPNADDPAGE_LABLE_FIXEDWIDTH); + + m_vpnServerLineEdit = new QLineEdit(this); + m_vpnServerLineEdit->setFixedWidth(VPNADDPAGE_INPUTBOX_FIXEDWIDTH); + m_vpnServerLineEdit->setPlaceholderText(tr("Required")); //必填 + + serverLayout->addWidget(vpnServerLabel); + serverLayout->addWidget(m_vpnServerLineEdit); + m_vpnServerFrame->setLayout(serverLayout); + + // IP的正则格式限制 + QRegExp rxIp("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"); + QRegExpValidator *ipExpVal = new QRegExpValidator(rxIp, this); + m_vpnServerLineEdit->setValidator(ipExpVal); +} + +void vpnAddPage::initButtonFrame() +{ + m_buttonFrame = new QFrame(this); + m_buttonFrame->setFixedSize(VPNDETAILPAGE_FRAME_FIXEDSIZE); + + QHBoxLayout *buttonLayout = new QHBoxLayout(m_buttonFrame); + buttonLayout->setContentsMargins(VPNDETAILPAGE_ITEM_MARGINS); + buttonLayout->setSpacing(VPNDETAILPAGE_NULLSPACE); + + QLabel *autoConnectLabel = new QLabel(this); + m_autoConnectBox = new QCheckBox(this); + autoConnectLabel->setText(tr("Auto Connection")); + QWidget *autoConWidget = new QWidget(this); + QHBoxLayout *autoLayout = new QHBoxLayout(autoConWidget); + + autoLayout->setContentsMargins(VPNDETAILPAGE_NULLMAGINS); + autoLayout->setSpacing(VPNDETAILPAGE_NULLSPACE); + autoLayout->addWidget(m_autoConnectBox); + autoLayout->addWidget(autoConnectLabel); + autoConWidget->setLayout(autoLayout); + + m_confimBtn = new QPushButton(this); + m_confimBtn->setFixedSize(VPNDETAILPAGE_BUTTON_FIXEDSIZE); + m_confimBtn->setText(tr("Confirm")); + m_cancelBtn = new QPushButton(this); + m_cancelBtn->setFixedSize(VPNDETAILPAGE_BUTTON_FIXEDSIZE); + m_cancelBtn->setText(tr("Cancel")); + + buttonLayout->addWidget(autoConWidget); + buttonLayout->addStretch(); + buttonLayout->addWidget(m_cancelBtn); + buttonLayout->addSpacing(VPNDETAILPAGE_BUTTON_SPACE); + buttonLayout->addWidget(m_confimBtn); + m_buttonFrame->setLayout(buttonLayout); +} + +void vpnAddPage::initConnection() +{ + if (m_vpnNameLineEdit != nullptr) { + connect(m_vpnNameLineEdit, &QLineEdit::textChanged, this, &vpnAddPage::onSetConfimBtnEnable); + } + + if (m_vpnServerLineEdit != nullptr) { + connect(m_vpnServerLineEdit, &QLineEdit::textChanged, this, &vpnAddPage::onSetConfimBtnEnable); + } + + if (m_cancelBtn != nullptr) { + connect(m_cancelBtn, &QPushButton::clicked, [&] () {this->close();}); + } + + if (m_confimBtn != nullptr) { + connect(m_confimBtn, &QPushButton::clicked, this, &vpnAddPage::onConfimBtnClicked); + } +} + +bool vpnAddPage::checkConfimBtnIsEnabled() +{ + if (m_vpnNameLineEdit->text().isEmpty()) { + qDebug() << "ipv4address empty or invalid"; + return false; + } + + if (m_vpnServerLineEdit->text().isEmpty()) { + qDebug() << "ipv4 netMask empty or invalid"; + return false; + } + return true; +} + +void vpnAddPage::onSetConfimBtnEnable() +{ + m_confimBtn->setEnabled(checkConfimBtnIsEnabled()); +} + +void vpnAddPage::onConfimBtnClicked() +{ + //新建有线连接 + qDebug() << "Confirm create vpn connect"; + if (!createVpnConnect()) { +// setNetdetailSomeEnable(true); +// return; + } + close(); +} + +bool vpnAddPage::createVpnConnect() +{ + KyVpnConfig vpnSetting; + QString connectName = m_vpnNameLineEdit->text(); + vpnSetting.m_gateway = m_vpnServerLineEdit->text(); + vpnSetting.setConnectName(connectName); + vpnSetting.m_vpnName = connectName; + vpnSetting.m_isAutoConnect = m_autoConnectBox->isChecked(); + vpnSetting.m_vpnType = (KyVpnType)m_vpnTypeComboBox->currentData().toInt(); + + m_vpnConnOperation->createVpnConnect(vpnSetting); + return true; +} + +vpnAddPage::~vpnAddPage() +{ + Q_EMIT this->closed(); +} diff --git a/src-vpn/frontend/vpndetails/vpnaddpage.h b/src-vpn/frontend/vpndetails/vpnaddpage.h new file mode 100644 index 00000000..19fe9c64 --- /dev/null +++ b/src-vpn/frontend/vpndetails/vpnaddpage.h @@ -0,0 +1,90 @@ +#ifndef VPNADDPAGE_H +#define VPNADDPAGE_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "kyvpnconnectoperation.h" + +#define VPNADDPAGE_MAINLAYOUT_MARGINS 0, 12, 0, 12 +#define VPNADDPAGE_ITEM_MARGINS 24, 0, 24, 0 +#define VPNADDPAGE_NULLMAGINS 0, 0, 0, 0 + +#define VPNADDPAGE_SIZE 520,312 +#define VPNADDPAGE_FRAME_FIXEDSIZE 520, 60 +#define VPNADDPAGE_BUTTON_FIXEDSIZE 96, 36 + +#define VPNADDPAGE_NULLSPACE 0 +#define VPNADDPAGE_BUTTON_SPACE 16 +#define VPNADDPAGE_NAME_MAX_LENGTH 32 +#define VPNADDPAGE_LABLE_FIXEDWIDTH 112 +#define VPNADDPAGE_COMBOBOX_FIXEDWIDTH 360 +#define VPNADDPAGE_INPUTBOX_FIXEDWIDTH 360 + +#define VPNDETAILPAGE_ITEM_MARGINS 24, 0, 24, 0 +#define VPNDETAILPAGE_NULLMAGINS 0, 0, 0, 0 + +#define VPNDETAILPAGE_FRAME_FIXEDSIZE 520, 60 +#define VPNDETAILPAGE_BUTTON_FIXEDSIZE 96, 36 + +#define VPNDETAILPAGE_NULLSPACE 0 +#define VPNDETAILPAGE_BUTTON_SPACE 16 + + + +class vpnAddPage : public QWidget +{ + Q_OBJECT +public: + explicit vpnAddPage(QWidget *parent = nullptr); + void centerToScreen(); + ~vpnAddPage(); + +private: + void initWindow(); + void initUI(); + void initVpnTypeFrame(); + void initVpnNameFrame(); + void initVpnServerFrame(); + void initButtonFrame(); + + void initConnection(); + + bool checkConfimBtnIsEnabled(); + bool createVpnConnect(); + +private: + QFrame *m_vpnTypeFrame = nullptr; + QFrame *m_vpnNameFrame = nullptr; + QFrame *m_vpnServerFrame = nullptr; + QFrame *m_buttonFrame = nullptr; + + QComboBox *m_vpnTypeComboBox = nullptr; + QLineEdit *m_vpnNameLineEdit = nullptr; + QLineEdit *m_vpnServerLineEdit = nullptr; + + QPushButton *m_confimBtn = nullptr; + QPushButton *m_cancelBtn = nullptr; + QCheckBox *m_autoConnectBox = nullptr; + + KyVpnConnectOperation *m_vpnConnOperation = nullptr; + +private Q_SLOTS: + void onConfimBtnClicked(); + void onSetConfimBtnEnable(); + +Q_SIGNALS: + void closed(); +}; + +#endif // VPNADDPAGE_H diff --git a/src-vpn/frontend/vpndetails/vpnadvancedpage.cpp b/src-vpn/frontend/vpndetails/vpnadvancedpage.cpp new file mode 100644 index 00000000..c8a3b08d --- /dev/null +++ b/src-vpn/frontend/vpndetails/vpnadvancedpage.cpp @@ -0,0 +1,1508 @@ +#include "vpnadvancedpage.h" + +#include +#include +#include +#define NO_LAYOUT_MARGINS 0, 0, 0, 0 +#define NO_SPACE 0 +#define LAYOUT_SPACING_SMALL 8 +#define HOR_LAYOUT_SPACING 24 +#define LAYOUT_ADD_SPACING 16 +#define VLAYOUT_ADD_SPACING 24 +#define LISTWIDGET_HEIGHT 184 +#define LISTWIDGET_HEIGHT_SMALL 112 +#define MIN_EDIT_WIDTH 150 +#define FIX_EDIT_WIDTH 200 +#define MIN_LABEL_WIDTH 140 +#define MAX_LABEL_WIDTH 240 +#define ONE_LABEL_WIDTH 440 +#define MAX_MRU_LENGTH 4 +#define ITEM_HEIGHT 36 +#define COMP_MODE_PROTOCOL 3 +#define COMP_MODE_ADDRESS 4 +#define LOG_FLAG "[VPN AdvancedPage]" + +VpnAdvancedPage::VpnAdvancedPage(QWidget *parent) : QFrame(parent) +{ + initUi(); + initConnect(); + initDefalutCheckState(); +} + +void VpnAdvancedPage::setL2tpOrPptpAdiaInfo(const KyVpnConfig &vpnInfo) +{ + //L2TP PPTP共有 + m_mppeECheckbox->setChecked(vpnInfo.m_mppeEnable); + if (m_mppeECheckbox->isChecked()) { + m_mppeECombox->setCurrentIndex((int)vpnInfo.m_mppeEncryptMethod); + } else { + m_mppeECombox->setEnabled(false); + } + m_useStatefulECheckbox->setChecked(vpnInfo.m_isAllowStatefulEncryption); + m_useStatefulECheckbox->setEnabled(vpnInfo.m_mppeEnable); + m_papAuthCheckbox->setEnabled(!vpnInfo.m_mppeEnable); + m_chapAuthCheckbox->setEnabled(!vpnInfo.m_mppeEnable); + m_eapAuthCheckbox->setEnabled(!vpnInfo.m_mppeEnable); + + m_sendPppEchoPkgCheckbox->setChecked(vpnInfo.m_sendPppPackage); + + //Auth Methods + m_papAuthCheckbox->setChecked(vpnInfo.m_authMethods.testFlag(KYAUTH2_PAP)); + m_chapAuthCheckbox->setChecked(vpnInfo.m_authMethods.testFlag(KYAUTH2_CHAP)); + m_mschapAuthCheckbox->setChecked(vpnInfo.m_authMethods.testFlag(KYAUTH2_MSCHAP)); + m_mschap2AuthCheckbox->setChecked(vpnInfo.m_authMethods.testFlag(KYAUTH2_MSCHAPV2)); + m_eapAuthCheckbox->setChecked(vpnInfo.m_authMethods.testFlag(KYAUTH2_EAP)); + + //Compress Methods + m_bsdCompModeCheckbox->setChecked(vpnInfo.m_compressMethods.testFlag(KYCOMP_BSD)); + m_defaultCompModeCheckbox->setChecked(vpnInfo.m_compressMethods.testFlag(KYCOMP_DEFLATE)); + m_tcpCompModeCheckbox->setChecked(vpnInfo.m_compressMethods.testFlag(KYCOMP_TCP)); + + + //L2TP + if (vpnInfo.m_vpnType == KYVPNTYPE_L2TP) { + m_protocolCompModeCheckbox->setChecked(vpnInfo.m_compressMethods.testFlag(KYCOMP_PROTO)); + m_addressCompModeCheckbox->setChecked(vpnInfo.m_compressMethods.testFlag(KYCOMP_ADDR)); + + m_mruEdit->setText(vpnInfo.m_mru); + m_mtuEdit->setText(vpnInfo.m_mtu); + } +} + +void VpnAdvancedPage::setOpenVpnAdiaInfo(const KyVpnConfig &vpnInfo) +{ + //General + m_customGatewayPortCheckbox->setChecked(vpnInfo.m_useAssignPort); + m_gatewayPortEdit->setText(vpnInfo.m_assignPort); + + m_customRenegotiaInrCheckbox->setChecked(vpnInfo.m_useRenegSeconds); + m_renogotiaInrEdit->setText(vpnInfo.m_renegSeconds); + + m_compressionCheckbox->setChecked(vpnInfo.m_useCompress); + m_compressionCombox->setCurrentIndex((int)vpnInfo.m_openvpnCompress); + + m_tcpConnCheckbox->setChecked(vpnInfo.m_useTcpLink); + + m_setVDevTypeCheckbox->setChecked(vpnInfo.m_setDevType); + m_setVDevTypeCombox->setCurrentIndex((int)vpnInfo.m_devType); + + m_setVDevNameCheckbox->setChecked(vpnInfo.m_setDevName); + m_setVDevNameEdit->setText(vpnInfo.m_devName); + + m_customMtuCheckbox->setChecked(vpnInfo.m_useTunnelMtu); + m_customMtuEdit->setText(vpnInfo.m_tunnelMtu); + + m_customUdpFragSizeCheckbox->setChecked(vpnInfo.m_useFragmentSize); + m_customUdpFragSizeEdit->setText(vpnInfo.m_fragmentSize); + + m_tcpMssCheckbox->setChecked(vpnInfo.m_mssfix); + + m_randomRemoteHostCheckbox->setChecked(vpnInfo.m_remoteRandom); + + m_ipv6TunLinkCheckbox->setChecked(vpnInfo.m_ipv6TunLink); + + m_specPingInrCheckbox->setChecked(vpnInfo.m_setPingCycle); + m_specPingInrEdit->setText(vpnInfo.m_pingCycle); + + m_specExitPingCheckbox->setChecked(vpnInfo.m_usePingMethod); + m_specExitRestarCombox->setCurrentIndex((int)vpnInfo.m_pingMethod); + m_specExRePingEdit->setText(vpnInfo.m_pingMethodTime); + + m_acceptAuthedPaksCheckbox->setChecked(vpnInfo.m_float); + + m_specMaxRouteCheckbox->setChecked(vpnInfo.m_setMaxRoute); + m_specMaxRouteEdit->setText(vpnInfo.m_maxRoute); + + + //TLS settings + m_serverCertCheckCombox->setCurrentIndex((int)vpnInfo.m_checkServerCa); + + m_subjectMatchEdit->setText(vpnInfo.m_verifyName); + + m_usePreviousCertCheckbox->setChecked(vpnInfo.m_useRemoteCertTls); + m_usePreviousCertCombox->setCurrentIndex((int)vpnInfo.m_remoteCertType); + + m_verifyPeerCertCheckbox->setChecked(vpnInfo.m_useNsCertTls); + m_verifyPeerCertCombox->setCurrentIndex((int)vpnInfo.m_nsCertType); + + m_tlsModeCombox->setCurrentIndex(vpnInfo.m_vpnTlsMode); + m_keyPathEdit->setText(vpnInfo.m_vpnKeyFile); + if (vpnInfo.m_vpnTlsMode == KYVPNTLS_AUTHENTICATION) { + if (vpnInfo.m_vpnTlsTaDir == KEY_DIRECTION_ZERO) { + m_keyDirectionCombox->setCurrentIndex(KEY_DIRECTION_ZERO_INDEX); + } else if (vpnInfo.m_vpnTlsTaDir == KEY_DIRECTION_ONE) { + m_keyDirectionCombox->setCurrentIndex(KEY_DIRECTION_ONE_INDEX); + } else { + m_keyDirectionCombox->setCurrentIndex(KEY_DIRECTION_NONE_INDEX); + } + } else { + m_keyDirectionCombox->setCurrentIndex(KEY_DIRECTION_NONE_INDEX); + } + + //Proxies + m_proxyTypeCombox->setCurrentIndex((int)vpnInfo.m_vpnProxyType); + m_proxyServerAddEdit->setText(vpnInfo.m_vpnProxyServer); + m_proxyPortEdit->setText(vpnInfo.m_vpnProxyPort); + m_infiniteRetryCheckbox->setChecked(vpnInfo.m_vpnProxyRetry); + m_proxyUsernameEdit->setText(vpnInfo.m_vpnProxyName); + m_proxyPwdEdit->setText(vpnInfo.m_vpnProxyPasswd); + + //Security + m_customKeySizeCheckbox->setChecked(vpnInfo.m_useKeysize); + m_customKeySizeEdit->setText(vpnInfo.m_keySize); + m_hmacAuthCombox->setCurrentIndex((int)vpnInfo.m_hmacAuthMethod); +} + +void VpnAdvancedPage::setStrongSwanAdiaInfo(const KyVpnConfig &vpnInfo) +{ + m_requestInIPCheckbox->setChecked(vpnInfo.m_virtual); + m_udpEncapCheckbox->setChecked(vpnInfo.m_encap); + m_ipCompCheckbox->setChecked(vpnInfo.m_ipcomp); + m_enablCustomCheckbox->setChecked(vpnInfo.m_proposal); + + if (vpnInfo.m_proposal) { + m_ikeEdit->setText(vpnInfo.m_ike); + m_espEdit->setText(vpnInfo.m_esp); + } +} + +bool VpnAdvancedPage::checkIsChanged(const KyVpnConfig &vpnInfo, VpnType &vpnType) +{ + bool isChanged = false; + switch (vpnType) { + case L2TP: + if (checkL2tpIsChanged(vpnInfo)) { + isChanged = true; + } + break; + case PPTP: + if (checkPptpIsChanged(vpnInfo)) { + isChanged = true; + } + break; + case OPEN_VPN: + if (checkOpenVpnIsChanged(vpnInfo)) { + isChanged = true; + } + break; + case STRONG_SWAN: + if (checkStrongSwanIsChanged(vpnInfo)) { + isChanged = true; + } + break; + default: + qDebug() << LOG_FLAG << "Unknow VPN Type" << vpnType; + break; + } + return isChanged; +} + +bool VpnAdvancedPage::checkL2tpIsChanged(const KyVpnConfig &vpnInfo) +{ + bool isChanged = false; + if (vpnInfo.m_mppeEnable != m_mppeECheckbox->isChecked() + || m_mppeECombox->currentData().toInt() != vpnInfo.m_mppeEncryptMethod + || vpnInfo.m_isAllowStatefulEncryption != m_useStatefulECheckbox->isChecked() + || vpnInfo.m_sendPppPackage != m_sendPppEchoPkgCheckbox->isChecked()) { + + isChanged = true; + } + + if (vpnInfo.m_authMethods.testFlag(KYAUTH2_PAP) != m_papAuthCheckbox->isChecked() + || vpnInfo.m_authMethods.testFlag(KYAUTH2_CHAP) != m_chapAuthCheckbox->isChecked() + || vpnInfo.m_authMethods.testFlag(KYAUTH2_MSCHAP) != m_mschapAuthCheckbox->isChecked() + || vpnInfo.m_authMethods.testFlag(KYAUTH2_MSCHAPV2) != m_mschap2AuthCheckbox->isChecked() + || vpnInfo.m_authMethods.testFlag(KYAUTH2_EAP) != m_eapAuthCheckbox->isChecked()) { + + isChanged = true; + } + + if (vpnInfo.m_compressMethods.testFlag(KYCOMP_BSD) != m_bsdCompModeCheckbox->isChecked() + || vpnInfo.m_compressMethods.testFlag(KYCOMP_DEFLATE) != m_defaultCompModeCheckbox->isChecked() + || vpnInfo.m_compressMethods.testFlag(KYCOMP_TCP) != m_tcpCompModeCheckbox->isChecked() + || vpnInfo.m_compressMethods.testFlag(KYCOMP_PROTO) != m_protocolCompModeCheckbox->isChecked() + || vpnInfo.m_compressMethods.testFlag(KYCOMP_ADDR) != m_addressCompModeCheckbox->isChecked()) { + + isChanged = true; + } + + if (vpnInfo.m_mru != m_mruEdit->text() || vpnInfo.m_mtu != m_mtuEdit->text()) { + isChanged = true; + } + + return isChanged; +} + +bool VpnAdvancedPage::checkPptpIsChanged(const KyVpnConfig &vpnInfo) +{ + bool isChanged = false; + if (vpnInfo.m_mppeEnable != m_mppeECheckbox->isChecked() + || m_mppeECombox->currentData().toInt() != vpnInfo.m_mppeEncryptMethod + || vpnInfo.m_isAllowStatefulEncryption != m_useStatefulECheckbox->isChecked() + || vpnInfo.m_sendPppPackage != m_sendPppEchoPkgCheckbox->isChecked()) { + + isChanged = true; + } + + if (vpnInfo.m_authMethods.testFlag(KYAUTH2_PAP) != m_papAuthCheckbox->isChecked() + || vpnInfo.m_authMethods.testFlag(KYAUTH2_CHAP) != m_chapAuthCheckbox->isChecked() + || vpnInfo.m_authMethods.testFlag(KYAUTH2_MSCHAP) != m_mschapAuthCheckbox->isChecked() + || vpnInfo.m_authMethods.testFlag(KYAUTH2_MSCHAPV2) != m_mschap2AuthCheckbox->isChecked() + || vpnInfo.m_authMethods.testFlag(KYAUTH2_EAP) != m_eapAuthCheckbox->isChecked()) { + + isChanged = true; + } + + if (vpnInfo.m_compressMethods.testFlag(KYCOMP_BSD) != m_bsdCompModeCheckbox->isChecked() + || vpnInfo.m_compressMethods.testFlag(KYCOMP_DEFLATE) != m_defaultCompModeCheckbox->isChecked() + || vpnInfo.m_compressMethods.testFlag(KYCOMP_TCP) != m_tcpCompModeCheckbox->isChecked()) { + + isChanged = true; + } + + return isChanged; +} + +bool VpnAdvancedPage::checkOpenVpnIsChanged(const KyVpnConfig &vpnInfo) +{ + bool isChanged = false; + //General + if (vpnInfo.m_useAssignPort != m_customGatewayPortCheckbox->isChecked() + || vpnInfo.m_assignPort != m_gatewayPortEdit->text()) { + isChanged = true; + } + + if (vpnInfo.m_useRenegSeconds != m_customRenegotiaInrCheckbox->isChecked() + || vpnInfo.m_renegSeconds != m_renogotiaInrEdit->text()) { + isChanged = true; + } + + if (vpnInfo.m_useCompress != m_compressionCheckbox->isChecked() + || vpnInfo.m_openvpnCompress != m_compressionCombox->currentData().toInt()) { + isChanged = true; + } + + if (vpnInfo.m_useTcpLink != m_tcpConnCheckbox->isChecked()) { + isChanged = true; + } + + if (vpnInfo.m_setDevType != m_setVDevTypeCheckbox->isChecked() + || vpnInfo.m_devType != m_setVDevTypeCombox->currentData().toInt()) { + isChanged = true; + } + + if (vpnInfo.m_setDevName != m_setVDevNameCheckbox->isChecked() + || vpnInfo.m_devName != m_setVDevNameEdit->text()) { + isChanged = true; + } + + if (vpnInfo.m_useTunnelMtu != m_customMtuCheckbox->isChecked() + || vpnInfo.m_tunnelMtu != m_customMtuEdit->text()) { + isChanged = true; + } + + if (vpnInfo.m_useFragmentSize != m_customUdpFragSizeCheckbox->isChecked() + || vpnInfo.m_fragmentSize != m_customUdpFragSizeEdit->text()) { + isChanged = true; + } + + if (vpnInfo.m_mssfix != m_tcpMssCheckbox->isChecked()) { + isChanged = true; + } + + if (vpnInfo.m_remoteRandom != m_randomRemoteHostCheckbox->isChecked()) { + isChanged = true; + } + + if (vpnInfo.m_ipv6TunLink != m_ipv6TunLinkCheckbox->isChecked()) { + isChanged = true; + } + + if (vpnInfo.m_setPingCycle != m_specPingInrCheckbox->isChecked() + || vpnInfo.m_pingCycle != m_specPingInrEdit->text()) { + isChanged = true; + } + + if (vpnInfo.m_usePingMethod != m_specExitPingCheckbox->isChecked() + || vpnInfo.m_pingMethod != m_specExitRestarCombox->currentData().toInt() + || vpnInfo.m_pingMethodTime != m_specExRePingEdit->text()) { + isChanged = true; + } + + if (vpnInfo.m_float != m_acceptAuthedPaksCheckbox->isChecked()) { + isChanged = true; + } + + if (vpnInfo.m_setMaxRoute != m_specMaxRouteCheckbox->isChecked() + || vpnInfo.m_maxRoute != m_specMaxRouteEdit->text()) { + isChanged = true; + } + + + //TLS settings + if (vpnInfo.m_checkServerCa != m_serverCertCheckCombox->currentData().toInt()) { + isChanged = true; + } + + if (vpnInfo.m_verifyName != m_subjectMatchEdit->text()) { + isChanged = true; + } + + if (vpnInfo.m_useRemoteCertTls != m_usePreviousCertCheckbox->isChecked() + || vpnInfo.m_remoteCertType != m_usePreviousCertCombox->currentData().toInt()) { + isChanged = true; + } + + if (vpnInfo.m_useNsCertTls != m_verifyPeerCertCheckbox->isChecked() + || vpnInfo.m_nsCertType != m_verifyPeerCertCombox->currentData().toInt()) { + isChanged = true; + } + + if (vpnInfo.m_vpnTlsMode != m_tlsModeCombox->currentData().toInt() + || vpnInfo.m_vpnKeyFile != m_keyPathEdit->text() + || vpnInfo.m_vpnTlsTaDir != m_keyDirectionCombox->currentData().toString()) { + isChanged = true; + } + + + //Proxies + int currentProxyType = m_proxyTypeCombox->currentData().toInt(); + if (vpnInfo.m_vpnProxyType != currentProxyType) { + isChanged = true; + } + + if (currentProxyType == HTTP || currentProxyType == SOCKS) { + if (vpnInfo.m_vpnProxyServer != m_proxyServerAddEdit->text() + || vpnInfo.m_vpnProxyPort != m_proxyPortEdit->text() + || vpnInfo.m_vpnProxyRetry != m_infiniteRetryCheckbox->isChecked()) { + isChanged = true; + } + + if (currentProxyType == HTTP) { + if (vpnInfo.m_vpnProxyName != m_proxyUsernameEdit->text() + || vpnInfo.m_vpnProxyPasswd != m_proxyPwdEdit->text()) { + isChanged = true; + } + } + } + + + //Security + if (vpnInfo.m_useKeysize != m_customKeySizeCheckbox->isChecked() + || vpnInfo.m_keySize != m_customKeySizeEdit->text() + || vpnInfo.m_hmacAuthMethod != m_hmacAuthCombox->currentData().toInt()) { + isChanged = true; + } + + + return isChanged; +} + +bool VpnAdvancedPage::checkStrongSwanIsChanged(const KyVpnConfig &vpnInfo) +{ + bool isChanged = false; + if (vpnInfo.m_virtual != m_requestInIPCheckbox->isChecked() + || vpnInfo.m_encap != m_udpEncapCheckbox->isChecked() + || vpnInfo.m_ipcomp != m_ipCompCheckbox->isChecked() + || vpnInfo.m_proposal != m_enablCustomCheckbox->isChecked()) { + + isChanged = true; + } + + if (m_enablCustomCheckbox->isChecked()) { + if (vpnInfo.m_ike != m_ikeEdit->text() || vpnInfo.m_esp != m_espEdit->text()) { + isChanged = true; + } + } + + return isChanged; +} + +void VpnAdvancedPage::updateL2tpOrPptpAdiaInfo(KyVpnConfig &vpnInfo) +{ + vpnInfo.m_mppeEnable = m_mppeECheckbox->isChecked(); + vpnInfo.m_mppeEncryptMethod = (KyMPPEMethod)m_mppeECombox->currentData().toInt(); + vpnInfo.m_isAllowStatefulEncryption = m_useStatefulECheckbox->isChecked(); + vpnInfo.m_sendPppPackage = m_sendPppEchoPkgCheckbox->isChecked(); + + vpnInfo.m_authMethods.setFlag(KYAUTH2_PAP, m_papAuthCheckbox->isChecked()); + vpnInfo.m_authMethods.setFlag(KYAUTH2_CHAP, m_chapAuthCheckbox->isChecked()); + vpnInfo.m_authMethods.setFlag(KYAUTH2_MSCHAP, m_mschapAuthCheckbox->isChecked()); + vpnInfo.m_authMethods.setFlag(KYAUTH2_MSCHAPV2, m_mschap2AuthCheckbox->isChecked()); + vpnInfo.m_authMethods.setFlag(KYAUTH2_EAP, m_eapAuthCheckbox->isChecked()); + + vpnInfo.m_compressMethods.setFlag(KYCOMP_BSD, m_bsdCompModeCheckbox->isChecked()); + vpnInfo.m_compressMethods.setFlag(KYCOMP_DEFLATE, m_defaultCompModeCheckbox->isChecked()); + vpnInfo.m_compressMethods.setFlag(KYCOMP_TCP, m_tcpCompModeCheckbox->isChecked()); + + if (!m_compModeListWidget->item(COMP_MODE_PROTOCOL)->isHidden() + && !m_compModeListWidget->item(COMP_MODE_ADDRESS)->isHidden()) { + vpnInfo.m_compressMethods.setFlag(KYCOMP_PROTO, m_protocolCompModeCheckbox->isChecked()); + vpnInfo.m_compressMethods.setFlag(KYCOMP_ADDR, m_addressCompModeCheckbox->isChecked()); + vpnInfo.m_mru = m_mruEdit->text(); + vpnInfo.m_mtu = m_mtuEdit->text(); + qDebug() << LOG_FLAG << "Update L2TP advanced info finished"; + + } else { + qDebug() << LOG_FLAG << "Update PPTP advanced info finished"; + } +} + +void VpnAdvancedPage::updateOpenVpnAdiaInfo(KyVpnConfig &vpnInfo) +{ + //General + vpnInfo.m_useAssignPort = m_customGatewayPortCheckbox->isChecked(); + vpnInfo.m_assignPort = m_gatewayPortEdit->text(); + + vpnInfo.m_useRenegSeconds = m_customRenegotiaInrCheckbox->isChecked(); + vpnInfo.m_renegSeconds = m_renogotiaInrEdit->text(); + + vpnInfo.m_useCompress = m_compressionCheckbox->isChecked(); + vpnInfo.m_openvpnCompress = (KyCompressMethod2)m_compressionCombox->currentData().toInt(); + + vpnInfo.m_useTcpLink = m_tcpConnCheckbox->isChecked(); + + vpnInfo.m_setDevType = m_setVDevTypeCheckbox->isChecked(); + vpnInfo.m_devType = (KyVirtualDeviceType)m_setVDevTypeCombox->currentData().toInt(); + + vpnInfo.m_setDevName = m_setVDevNameCheckbox->isChecked(); + vpnInfo.m_devName = m_setVDevNameEdit->text(); + + vpnInfo.m_useTunnelMtu = m_customMtuCheckbox->isChecked(); + vpnInfo.m_tunnelMtu = m_customMtuEdit->text(); + + vpnInfo.m_useFragmentSize = m_customUdpFragSizeCheckbox->isChecked(); + vpnInfo.m_fragmentSize = m_customUdpFragSizeEdit->text(); + + vpnInfo.m_mssfix = m_tcpMssCheckbox->isChecked(); + vpnInfo.m_remoteRandom = m_randomRemoteHostCheckbox->isChecked(); + vpnInfo.m_ipv6TunLink = m_ipv6TunLinkCheckbox->isChecked(); + + vpnInfo.m_setPingCycle = m_specPingInrCheckbox->isChecked(); + vpnInfo.m_pingCycle = m_specPingInrEdit->text(); + + vpnInfo.m_usePingMethod = m_specExitPingCheckbox->isChecked(); + vpnInfo.m_pingMethod = (KyVpnPingMethod)m_specExitRestarCombox->currentData().toInt(); + vpnInfo.m_pingMethodTime = m_specExRePingEdit->text(); + + vpnInfo.m_float = m_acceptAuthedPaksCheckbox->isChecked(); + + vpnInfo.m_setMaxRoute = m_specMaxRouteCheckbox->isChecked(); + vpnInfo.m_maxRoute = m_specMaxRouteEdit->text(); + + + //TLS settings + vpnInfo.m_checkServerCa = (KyVpnCheckServerMethod)m_serverCertCheckCombox->currentData().toInt(); + vpnInfo.m_verifyName = m_subjectMatchEdit->text(); + + vpnInfo.m_useRemoteCertTls = m_usePreviousCertCheckbox->isChecked(); + vpnInfo.m_remoteCertType = (KyVpnCertType)m_usePreviousCertCombox->currentData().toInt(); + + vpnInfo.m_useNsCertTls = m_verifyPeerCertCheckbox->isChecked(); + vpnInfo.m_nsCertType = (KyVpnCertType)m_verifyPeerCertCombox->currentData().toInt(); + + vpnInfo.m_vpnTlsMode = (KyVpnTlsMode)m_tlsModeCombox->currentData().toInt(); + vpnInfo.m_vpnKeyFile = m_keyPathEdit->text(); + vpnInfo.m_vpnTlsTaDir = m_keyDirectionCombox->currentData().toString(); + + + //Proxies + vpnInfo.m_vpnProxyType = (KyVpnProxyType)m_proxyTypeCombox->currentData().toInt(); + vpnInfo.m_vpnProxyServer = m_proxyServerAddEdit->text(); + vpnInfo.m_vpnProxyPort = m_proxyPortEdit->text(); + vpnInfo.m_vpnProxyRetry = m_infiniteRetryCheckbox->isChecked(); + vpnInfo.m_vpnProxyName = m_proxyUsernameEdit->text(); + vpnInfo.m_vpnProxyPasswd = m_proxyPwdEdit->text(); + + + //Security + vpnInfo.m_useKeysize = m_customKeySizeCheckbox->isChecked(); + vpnInfo.m_keySize = m_customKeySizeEdit->text(); + vpnInfo.m_hmacAuthMethod = (KyHMACAuthMethod)m_hmacAuthCombox->currentData().toInt(); + + qDebug() << LOG_FLAG << "Update open VPN advanced info finished"; +} + +void VpnAdvancedPage::updateStrongSwanAdiaInfo(KyVpnConfig &vpnInfo) +{ + vpnInfo.m_virtual = m_requestInIPCheckbox->isChecked(); + vpnInfo.m_encap = m_udpEncapCheckbox->isChecked(); + vpnInfo.m_ipcomp = m_ipCompCheckbox->isChecked(); + vpnInfo.m_proposal = m_enablCustomCheckbox->isChecked(); + + vpnInfo.m_ike = m_ikeEdit->text(); + vpnInfo.m_esp = m_espEdit->text(); + + qDebug() << LOG_FLAG << "update strong-swan advanced info finished"; +} + +void VpnAdvancedPage::setVpnAdvancedPage(const VpnType &type) +{ + switch (type) { + case L2TP: + showL2tpAdiaPage(); + break; + case OPEN_VPN: + showOpenVpnAdiaPage(); + break; + case PPTP: + showPptpAdiaPage(); + break; + case STRONG_SWAN: + showSSwanAdiaPage(); + break; + default: + break; + } +} + +void VpnAdvancedPage::paintEvent(QPaintEvent *event) +{ + if (m_authModeListWidget) { + QPalette mpal(m_authModeListWidget->palette()); + mpal.setColor(QPalette::Base, qApp->palette().base().color()); + mpal.setColor(QPalette::AlternateBase, qApp->palette().alternateBase().color()); + m_authModeListWidget->setBackgroundRole(QPalette::Base); + m_authModeListWidget->setAlternatingRowColors(true); + m_authModeListWidget->setPalette(mpal); + } + if (m_compModeListWidget) { + QPalette mpal(m_compModeListWidget->palette()); + mpal.setColor(QPalette::Base, qApp->palette().base().color()); + mpal.setColor(QPalette::AlternateBase, qApp->palette().alternateBase().color()); + m_compModeListWidget->setBackgroundRole(QPalette::Base); + m_compModeListWidget->setAlternatingRowColors(true); + m_compModeListWidget->setPalette(mpal); + } + if (m_optionsListWidget) { + QPalette mpal(m_optionsListWidget->palette()); + mpal.setColor(QPalette::Base, qApp->palette().base().color()); + mpal.setColor(QPalette::AlternateBase, qApp->palette().alternateBase().color()); + m_optionsListWidget->setBackgroundRole(QPalette::Base); + m_optionsListWidget->setAlternatingRowColors(true); + m_optionsListWidget->setPalette(mpal); + } +} + +void VpnAdvancedPage::initUi() +{ + m_defaultAdiaFrame = new QFrame(this); + m_openVpnAdiaFrame = new QFrame(this); + m_sSwanAdiaFrame = new QFrame(this); + + initDefaultAdiaFrame(); + initOpenVpnAdiaFrame(); + initSSwanAdiaFrame(); + + QVBoxLayout *mainLayout = new QVBoxLayout(this); + mainLayout->setContentsMargins(NO_LAYOUT_MARGINS); + mainLayout->setSpacing(NO_SPACE); + mainLayout->addWidget(m_defaultAdiaFrame); + mainLayout->addWidget(m_openVpnAdiaFrame); + mainLayout->addWidget(m_sSwanAdiaFrame); + mainLayout->addSpacing(3); + mainLayout->addStretch(); +} + +void VpnAdvancedPage::initConnect() +{ + connect(m_mppeECheckbox, &QCheckBox::stateChanged, this, [=](int state) { + m_mppeECombox->setEnabled(state); + m_useStatefulECheckbox->setEnabled(state); + + m_papAuthCheckbox->setEnabled(!state); + m_chapAuthCheckbox->setEnabled(!state); + m_eapAuthCheckbox->setEnabled(!state); + }); + + //strong-Swan + connect(m_enablCustomCheckbox, &QCheckBox::stateChanged, this, [=](int state) { + m_ikeEspFrame->setEnabled(state); + }); + + //open VPN General + connect(m_customGatewayPortCheckbox, &QCheckBox::stateChanged, this, [=](int state) { + m_gatewayPortEdit->setEnabled(state); + }); + connect(m_customRenegotiaInrCheckbox, &QCheckBox::stateChanged, this, [=](int state) { + m_renogotiaInrEdit->setEnabled(state); + }); + connect(m_compressionCheckbox, &QCheckBox::stateChanged, this, [=](int state) { + m_compressionCombox->setEnabled(state); + }); + connect(m_compressionCheckbox, &QCheckBox::stateChanged, this, [=](int state) { + if (state == Qt::CheckState::Unchecked) { + m_compressionCombox->setCurrentIndex(KYCOMP2_LZODISABLE); + } + }); + connect(m_setVDevTypeCheckbox, &QCheckBox::stateChanged, this, [=](int state) { + m_setVDevTypeCombox->setEnabled(state); + }); + connect(m_setVDevNameCheckbox, &QCheckBox::stateChanged, this, [=](int state) { + m_setVDevNameEdit->setEnabled(state); + }); + connect(m_customMtuCheckbox, &QCheckBox::stateChanged, this, [=](int state) { + m_customMtuEdit->setEnabled(state); + }); + connect(m_customUdpFragSizeCheckbox, &QCheckBox::stateChanged, this, [=](int state) { + m_customUdpFragSizeEdit->setEnabled(state); + }); + connect(m_specPingInrCheckbox, &QCheckBox::stateChanged, this, [=](int state) { + m_specPingInrEdit->setEnabled(state); + }); + connect(m_specExitPingCheckbox, &QCheckBox::stateChanged, this, [=](int state) { + m_specExitRestarCombox->setEnabled(state); + }); + connect(m_specExitPingCheckbox, &QCheckBox::stateChanged, this, [=](int state) { + m_specExRePingEdit->setEnabled(state); + }); + connect(m_specMaxRouteCheckbox, &QCheckBox::stateChanged, this, [=](int state) { + m_specMaxRouteEdit->setEnabled(state); + }); + + //open VPN TLS settings + connect(m_serverCertCheckCombox, QOverload::of(&QComboBox::currentIndexChanged), this, [=](int index) { + if (index == (int)KYCHECKSERVER_NONE) { + m_subjectMatchEdit->setEnabled(false); + } else { + m_subjectMatchEdit->setEnabled(true); + } + }); + connect(m_tlsModeCombox, QOverload::of(&QComboBox::currentIndexChanged), + this, &VpnAdvancedPage::onTlsModeComboxIndexChanged); + connect(m_usePreviousCertCheckbox, &QCheckBox::stateChanged, this, [=](int state) { + m_usePreviousCertCombox->setEnabled(state); + }); + connect(m_verifyPeerCertCheckbox, &QCheckBox::stateChanged, this, [=](int state) { + m_verifyPeerCertCombox->setEnabled(state); + }); + //open VPN proxies + connect(m_proxyTypeCombox, QOverload::of(&QComboBox::currentIndexChanged), + this, &VpnAdvancedPage::onProxyTypeComboxIndexChanged); + //open VPN security + connect(m_customKeySizeCheckbox, &QCheckBox::stateChanged, this, [=](int state) { + m_customKeySizeEdit->setEnabled(state); + }); + + connect(m_mruEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + connect(m_mtuEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + connect(m_gatewayPortEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + connect(m_renogotiaInrEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + connect(m_setVDevNameEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + connect(m_customMtuEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + connect(m_customUdpFragSizeEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + connect(m_specPingInrEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + connect(m_specExRePingEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + connect(m_subjectMatchEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + connect(m_specMaxRouteEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + connect(m_keyPathEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + connect(m_proxyServerAddEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + connect(m_proxyPortEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + connect(m_proxyUsernameEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + connect(m_proxyPwdEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + connect(m_customKeySizeEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + connect(m_ikeEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + connect(m_espEdit, &QLineEdit::textChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + + connect(m_customGatewayPortCheckbox, &QCheckBox::stateChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + connect(m_customRenegotiaInrCheckbox, &QCheckBox::stateChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + connect(m_setVDevNameCheckbox, &QCheckBox::stateChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + connect(m_customMtuCheckbox, &QCheckBox::stateChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + connect(m_customUdpFragSizeCheckbox, &QCheckBox::stateChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + connect(m_specPingInrCheckbox, &QCheckBox::stateChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + connect(m_specExitPingCheckbox, &QCheckBox::stateChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + connect(m_specMaxRouteCheckbox, &QCheckBox::stateChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + connect(m_customKeySizeCheckbox, &QCheckBox::stateChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + connect(m_enablCustomCheckbox, &QCheckBox::stateChanged, this, &VpnAdvancedPage::setEnableOfConfirmBtn); + + connect(m_serverCertCheckCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(setEnableOfConfirmBtn())); + connect(m_tlsModeCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(setEnableOfConfirmBtn())); + connect(m_proxyTypeCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(setEnableOfConfirmBtn())); + connect(m_keyPathChooseBtn, &QPushButton::clicked, this, &VpnAdvancedPage::onKeyPathButtonClicked); +} + +void VpnAdvancedPage::initDefaultAdiaFrame() +{ + /**********控件**********/ + m_mppeECheckbox = new QCheckBox(this); + m_useStatefulECheckbox = new QCheckBox(this); + m_sendPppEchoPkgCheckbox = new QCheckBox(this); + m_authModeLabel = new QLabel(this); + m_compModeLabel = new QLabel(this); + m_mruLabel = new QLabel(this); + m_mtuLabel = new QLabel(this); + + m_mppeECombox = new QComboBox(this); + m_authModeListWidget = new QListWidget(this); + m_papAuthCheckbox = new QCheckBox(this); + m_chapAuthCheckbox = new QCheckBox(this); + m_mschapAuthCheckbox = new QCheckBox(this); + m_mschap2AuthCheckbox = new QCheckBox(this); + m_eapAuthCheckbox = new QCheckBox(this); + + m_compModeListWidget = new QListWidget(this); + m_bsdCompModeCheckbox = new QCheckBox(this); + m_defaultCompModeCheckbox = new QCheckBox(this); + m_tcpCompModeCheckbox = new QCheckBox(this); + m_protocolCompModeCheckbox = new QCheckBox(this); + m_addressCompModeCheckbox = new QCheckBox(this); + + m_mruFrame = new QFrame(this); + m_mruEdit = new QLineEdit(this); + m_mtuEdit = new QLineEdit(this); + + m_authModeListWidget->setFocusPolicy(Qt::FocusPolicy::NoFocus); + m_authModeListWidget->setFrameShape(QFrame::Shape::StyledPanel); + addListItem(m_authModeListWidget, m_papAuthCheckbox); + addListItem(m_authModeListWidget, m_chapAuthCheckbox); + addListItem(m_authModeListWidget, m_mschapAuthCheckbox); + addListItem(m_authModeListWidget, m_mschap2AuthCheckbox); + addListItem(m_authModeListWidget, m_eapAuthCheckbox); + + m_compModeListWidget->setFocusPolicy(Qt::FocusPolicy::NoFocus); + m_compModeListWidget->setFrameShape(QFrame::Shape::StyledPanel); + addListItem(m_compModeListWidget, m_bsdCompModeCheckbox); + addListItem(m_compModeListWidget, m_defaultCompModeCheckbox); + addListItem(m_compModeListWidget, m_tcpCompModeCheckbox); + addListItem(m_compModeListWidget, m_protocolCompModeCheckbox); + addListItem(m_compModeListWidget, m_addressCompModeCheckbox); + + /**********布局**********/ + QVBoxLayout *defaultAdiaVLayout = new QVBoxLayout(m_defaultAdiaFrame); + defaultAdiaVLayout->setContentsMargins(NO_LAYOUT_MARGINS); + defaultAdiaVLayout->setSpacing(LAYOUT_SPACING_SMALL); + + QFrame *secuFrame= new QFrame(m_defaultAdiaFrame); + QFormLayout *secuLayout = new QFormLayout(secuFrame); + secuLayout->setContentsMargins(NO_LAYOUT_MARGINS); + secuLayout->setVerticalSpacing(LAYOUT_SPACING_SMALL); + secuLayout->setHorizontalSpacing(HOR_LAYOUT_SPACING); + secuLayout->addRow(m_mppeECheckbox, m_mppeECombox); + secuLayout->addRow(m_useStatefulECheckbox); + secuLayout->addRow(m_sendPppEchoPkgCheckbox); + m_mppeECheckbox->setMinimumWidth(MIN_LABEL_WIDTH); + + QHBoxLayout *mruHLayout = new QHBoxLayout(m_mruFrame); + mruHLayout->setContentsMargins(0, 16, 0, 0); + mruHLayout->setSpacing(HOR_LAYOUT_SPACING); + mruHLayout->addWidget(m_mruLabel); + mruHLayout->addWidget(m_mruEdit); + mruHLayout->addStretch(); + mruHLayout->addWidget(m_mtuLabel); + mruHLayout->addWidget(m_mtuEdit); + m_mruEdit->setFixedWidth(MIN_EDIT_WIDTH); + m_mtuEdit->setFixedWidth(MIN_EDIT_WIDTH); + + defaultAdiaVLayout->addWidget(secuFrame); + defaultAdiaVLayout->addSpacing(4); + defaultAdiaVLayout->addWidget(m_authModeLabel); + defaultAdiaVLayout->addWidget(m_authModeListWidget); + defaultAdiaVLayout->addSpacing(LAYOUT_ADD_SPACING); + defaultAdiaVLayout->addWidget(m_compModeLabel); + defaultAdiaVLayout->addWidget(m_compModeListWidget); + defaultAdiaVLayout->addWidget(m_mruFrame); + m_authModeListWidget->setFixedHeight(LISTWIDGET_HEIGHT); + m_compModeListWidget->setFixedHeight(LISTWIDGET_HEIGHT); + + /**********控件显示**********/ + m_mppeECheckbox->setText(tr("MPPE encryption algorithm:")); //MPPE加密算法: + m_useStatefulECheckbox->setText(tr("Use Stateful encryption")); //使用有状态加密 + m_sendPppEchoPkgCheckbox->setText(tr("Send PPP echo packets")); //发送PPP回显包 + m_authModeLabel->setText(tr("Authentication Mode:")); //认证方式: + m_papAuthCheckbox->setText(tr("PAP authentication")); //PAP认证 + m_chapAuthCheckbox->setText(tr("CHAP authentication")); //CHAP认证 + m_mschapAuthCheckbox->setText(tr("MSCHAP authentication")); //MSCHAP认证 + m_mschap2AuthCheckbox->setText(tr("MSCHAP2 authentication")); //MSCHAP2认证 + m_eapAuthCheckbox->setText(tr("EAP authentication")); //EAP认证 + m_compModeLabel->setText(tr("Compression Mode:")); //压缩方式: + m_bsdCompModeCheckbox->setText(tr("Allow BSD data compression")); //允许BSD压缩 + m_defaultCompModeCheckbox->setText(tr("Allow Default data compression")); //允许Default压缩 + m_tcpCompModeCheckbox->setText(tr("Allow TCP header compression")); //允许TCP头压缩 + m_protocolCompModeCheckbox->setText(tr("Use protocol field compression negotiation")); //使用协议域压缩协商 + m_addressCompModeCheckbox->setText(tr("Use Address/Control compression")); //使用地址/控制压缩 + m_mruLabel->setText("MRU"); + m_mtuLabel->setText("MTU"); + m_mruEdit->setText("0"); + m_mtuEdit->setText("0"); + + m_mppeECombox->addItem(tr("All Available"), KYMPPE_DEFAULT); //任意 + m_mppeECombox->addItem(tr("128-bit"), KYMPPE_REQUIRE128); //128位 + m_mppeECombox->addItem(tr("40-bit"), KYMPPE_REQUIRE40); //40位 + + //控件输入格式限制 + QRegExp rxNumber("^[0-9]+$"); + m_mruEdit->setValidator(new QRegExpValidator(rxNumber, this)); + m_mtuEdit->setValidator(new QRegExpValidator(rxNumber, this)); + m_mruEdit->setMaxLength(MAX_MRU_LENGTH); + m_mtuEdit->setMaxLength(MAX_MRU_LENGTH); +} + +void VpnAdvancedPage::initOpenVpnAdiaFrame() +{ + /**********控件**********/ + //General + QLabel *generalLabel = new QLabel(m_openVpnAdiaFrame); + m_customGatewayPortCheckbox = new QCheckBox(this); + m_customRenegotiaInrCheckbox = new QCheckBox(this); + m_compressionCheckbox = new QCheckBox(this); + m_tcpConnCheckbox = new QCheckBox(this); + m_setVDevTypeCheckbox = new QCheckBox(this); + m_setVDevNameCheckbox = new QCheckBox(this); + m_customMtuCheckbox = new QCheckBox(this); + m_customUdpFragSizeCheckbox = new QCheckBox(this); + m_tcpMssCheckbox = new QCheckBox(this); + m_randomRemoteHostCheckbox = new QCheckBox(this); + m_ipv6TunLinkCheckbox = new QCheckBox(this); + m_specPingInrCheckbox = new QCheckBox(this); + m_specExitPingCheckbox = new QCheckBox(this); + m_acceptAuthedPaksCheckbox = new QCheckBox(this); + m_specMaxRouteCheckbox = new QCheckBox(this); + + m_gatewayPortEdit = new QLineEdit(this); + m_renogotiaInrEdit = new QLineEdit(this); + m_setVDevNameEdit = new QLineEdit(this); + m_customMtuEdit = new QLineEdit(this); + m_customUdpFragSizeEdit = new QLineEdit(this); + m_specPingInrEdit = new QLineEdit(this); + m_specExRePingEdit = new QLineEdit(this); + m_specMaxRouteEdit = new QLineEdit(this); + m_compressionCombox = new QComboBox(this); + m_setVDevTypeCombox = new QComboBox(this); + m_specExitRestarCombox = new QComboBox(this); + m_customRenoInrLabel = new FixLabel(this); + m_customMtuLabel = new FixLabel(this); + m_acceptAuthedPaksLabel = new FixLabel(this); + m_customUdpLabel = new FixLabel(this); + + //TLS settings + QLabel *tlsSettingLabel = new QLabel(m_openVpnAdiaFrame); + QLabel *serverCertCheckLabel = new QLabel(m_openVpnAdiaFrame); + QLabel *tlsModeLabel = new QLabel(m_openVpnAdiaFrame); + + FixLabel *usePreviousCertLabel = new FixLabel(m_openVpnAdiaFrame); + FixLabel *verifyPeerCertLabel = new FixLabel(m_openVpnAdiaFrame); + + m_subjectMatchLabel = new QLabel(this); + m_keyPathLabel = new QLabel(this); + m_keyDirectionLabel = new QLabel(this); + m_subjectMatchEdit = new QLineEdit(this); + m_keyPathEdit = new QLineEdit(this); + m_keyPathChooseBtn = new QPushButton(this); + m_usePreviousCertCheckbox = new QCheckBox(this); + m_verifyPeerCertCheckbox = new QCheckBox(this); + m_serverCertCheckCombox = new QComboBox(this); + m_usePreviousCertCombox = new QComboBox(this); + m_verifyPeerCertCombox = new QComboBox(this); + m_tlsModeCombox = new QComboBox(this); + m_keyDirectionCombox = new QComboBox(this); + + //Proxies + QLabel *proxiesLabel = new QLabel(m_openVpnAdiaFrame); + QLabel *proxyTypeLabel = new QLabel(m_openVpnAdiaFrame); + m_proxyServerAddLabel = new QLabel(this); + m_proxyPortLabel = new QLabel(this); + m_proxyUsernameLabel = new QLabel(this); + m_proxyPwdLabel = new QLabel(this); + m_proxyTypeCombox = new QComboBox(this); + m_infiniteRetryCheckbox = new QCheckBox(this); + m_proxyServerAddEdit = new QLineEdit(this); + m_proxyPortEdit = new QLineEdit(this); + m_proxyUsernameEdit = new QLineEdit(this); + m_proxyPwdEdit = new KPasswordEdit(this); + m_proxyPwdEdit->setClearButtonEnabled(false); + + //Security + QLabel *securityLabel = new QLabel(m_openVpnAdiaFrame); + QLabel *hmacLabel = new QLabel(m_openVpnAdiaFrame); + m_customKeySizeCheckbox = new QCheckBox(this); + m_customKeySizeEdit = new QLineEdit(this); + m_hmacAuthCombox = new QComboBox(this); + + + /**********布局**********/ + QVBoxLayout *openVpnAdiaVLayout = new QVBoxLayout(m_openVpnAdiaFrame); + openVpnAdiaVLayout->setContentsMargins(NO_LAYOUT_MARGINS); + + //General + QFrame *generalFrame = new QFrame(m_openVpnAdiaFrame); + QFormLayout *generalLayout = new QFormLayout(generalFrame); + + QWidget *customRenoInrWidget = new QWidget(this); + initCheckWidget(m_customRenegotiaInrCheckbox, m_customRenoInrLabel, customRenoInrWidget); + + QWidget *customMtuWidget = new QWidget(this); + initCheckWidget(m_customMtuCheckbox, m_customMtuLabel, customMtuWidget); + + QWidget *customUdpWidget = new QWidget(this); + initCheckWidget(m_customUdpFragSizeCheckbox, m_customUdpLabel, customUdpWidget); + + QWidget *acceptAuthWidget = new QWidget(this); + initCheckWidget(m_acceptAuthedPaksCheckbox, m_acceptAuthedPaksLabel, acceptAuthWidget); + + QWidget *exitRestarWidget = new QWidget(this); + QHBoxLayout *exitRestarLayout = new QHBoxLayout(exitRestarWidget); + exitRestarLayout->setContentsMargins(NO_LAYOUT_MARGINS); + exitRestarLayout->addWidget(m_specExitRestarCombox); + exitRestarLayout->addWidget(m_specExRePingEdit); + + generalLayout->setContentsMargins(NO_LAYOUT_MARGINS); + generalLayout->addRow(m_customGatewayPortCheckbox, m_gatewayPortEdit); + generalLayout->addRow(customRenoInrWidget, m_renogotiaInrEdit); + generalLayout->addRow(m_compressionCheckbox, m_compressionCombox); + generalLayout->addRow(m_tcpConnCheckbox); + generalLayout->addRow(m_setVDevTypeCheckbox, m_setVDevTypeCombox); + generalLayout->addRow(m_setVDevNameCheckbox, m_setVDevNameEdit); + generalLayout->addRow(customMtuWidget, m_customMtuEdit); + generalLayout->addRow(customUdpWidget, m_customUdpFragSizeEdit); + generalLayout->addRow(m_tcpMssCheckbox); + generalLayout->addRow(m_randomRemoteHostCheckbox); + generalLayout->addRow(m_ipv6TunLinkCheckbox); + generalLayout->addRow(m_specPingInrCheckbox, m_specPingInrEdit); + generalLayout->addRow(m_specExitPingCheckbox, exitRestarWidget); + generalLayout->addRow(acceptAuthWidget); + generalLayout->addRow(m_specMaxRouteCheckbox, m_specMaxRouteEdit); + + //TLS settings + QFrame *tlsSettingsFrame = new QFrame(m_openVpnAdiaFrame); + QFormLayout *tlsLayout = new QFormLayout(tlsSettingsFrame); + + QWidget *usePreviousCertWidget = new QWidget(this); + initCheckWidget(m_usePreviousCertCheckbox, usePreviousCertLabel, usePreviousCertWidget); + + QWidget *verifyPeerCertWidget = new QWidget(this); + initCheckWidget(m_verifyPeerCertCheckbox, verifyPeerCertLabel, verifyPeerCertWidget); + + QWidget *keyfileWidget = new QWidget(this); + QGridLayout *keyfileLayout = new QGridLayout(keyfileWidget); + keyfileLayout->setContentsMargins(NO_LAYOUT_MARGINS); + keyfileLayout->addWidget(m_keyPathLabel, 0, 0); + keyfileLayout->addWidget(m_keyPathEdit, 0, 1); + keyfileLayout->addWidget(m_keyPathChooseBtn, 0, 2); + keyfileLayout->addWidget(m_keyDirectionLabel, 1, 0); + keyfileLayout->addWidget(m_keyDirectionCombox, 1, 1, 1, 2); + m_keyDirectionLabel->setMinimumWidth(MIN_LABEL_WIDTH); + + tlsLayout->setContentsMargins(NO_LAYOUT_MARGINS); + tlsLayout->addRow(serverCertCheckLabel, m_serverCertCheckCombox); + tlsLayout->addRow(m_subjectMatchLabel, m_subjectMatchEdit); + tlsLayout->addRow(usePreviousCertWidget, m_usePreviousCertCombox); + tlsLayout->addRow(verifyPeerCertWidget, m_verifyPeerCertCombox); + tlsLayout->addRow(tlsModeLabel, m_tlsModeCombox); + tlsLayout->addRow(keyfileWidget); + + //Proxies + QFrame *proxiesFrame = new QFrame(m_openVpnAdiaFrame); + QFormLayout *proxiesLayout = new QFormLayout(proxiesFrame); + proxiesLayout->setContentsMargins(NO_LAYOUT_MARGINS); + proxiesLayout->addRow(proxyTypeLabel, m_proxyTypeCombox); + proxiesLayout->addRow(m_proxyServerAddLabel, m_proxyServerAddEdit); + proxiesLayout->addRow(m_proxyPortLabel, m_proxyPortEdit); + proxiesLayout->addRow(nullptr, m_infiniteRetryCheckbox); + proxiesLayout->addRow(m_proxyUsernameLabel, m_proxyUsernameEdit); + proxiesLayout->addRow(m_proxyPwdLabel, m_proxyPwdEdit); + m_proxyUsernameLabel->setMinimumWidth(MIN_LABEL_WIDTH); + + //Security + QFrame *securityFrame = new QFrame(m_openVpnAdiaFrame); + QFormLayout *securityLayout = new QFormLayout(securityFrame); + securityLayout->setContentsMargins(NO_LAYOUT_MARGINS); + securityLayout->addRow(m_customKeySizeCheckbox, m_customKeySizeEdit); + securityLayout->addRow(hmacLabel, m_hmacAuthCombox); + + //all + openVpnAdiaVLayout->setSpacing(LAYOUT_SPACING_SMALL); + openVpnAdiaVLayout->addWidget(generalLabel); + openVpnAdiaVLayout->addWidget(generalFrame); + openVpnAdiaVLayout->addSpacing(VLAYOUT_ADD_SPACING); + openVpnAdiaVLayout->addWidget(tlsSettingLabel); + openVpnAdiaVLayout->addWidget(tlsSettingsFrame); + openVpnAdiaVLayout->addSpacing(VLAYOUT_ADD_SPACING); + openVpnAdiaVLayout->addWidget(proxiesLabel); + openVpnAdiaVLayout->addWidget(proxiesFrame); + openVpnAdiaVLayout->addSpacing(VLAYOUT_ADD_SPACING); + openVpnAdiaVLayout->addWidget(securityLabel); + openVpnAdiaVLayout->addWidget(securityFrame); + + /**********控件显示**********/ + m_customGatewayPortCheckbox->setText(tr("Use custom gateway port")); //使用自定义网关端口 + m_compressionCheckbox->setText(tr("Use compression")); //使用压缩 + m_tcpConnCheckbox->setText(tr("Use a TCP connection")); //使用TCP连接 + m_setVDevTypeCheckbox->setText(tr("Set virtual device type")); //设置虚拟设备类型 + m_setVDevNameCheckbox->setText(tr("Set virtual device name")); //设置虚拟设备名称 + m_tcpMssCheckbox->setText(tr("Limit TCP Maximum Segment Size(MSS)")); //限制TCP最大段尺寸(MSS) + m_randomRemoteHostCheckbox->setText(tr("Randomize remote hosts")); //随机化远程主机 + m_ipv6TunLinkCheckbox->setText(tr("IPv6 tun link")); //IPv6 tun连接 + m_specPingInrCheckbox->setText(tr("Specify ping interval")); //指定ping周期 + m_specExitPingCheckbox->setText(tr("Specify exit or restart ping")); //指定退出或重启的Ping + m_specMaxRouteCheckbox->setText(tr("Specify max routes")); //指定路由上限 + m_infiniteRetryCheckbox->setText(tr("Infinite retry on error")); //出错时无限重试 + m_customKeySizeCheckbox->setText(tr("Use custom key size")); //使用自定义密钥大小 + m_keyPathChooseBtn->setText(tr("Choose")); //选择 + + m_customRenoInrLabel->setFixedWidth(MAX_LABEL_WIDTH); + m_customRenoInrLabel->setLabelText(tr("Use custom renegotiation interval")); //使用自定义重协商间隔 + m_customMtuLabel->setFixedWidth(MAX_LABEL_WIDTH); + m_customMtuLabel->setLabelText(tr("Use custom tunnel Maximum Transmission Umit(MTU)")); //使用自定义隧道最大单元传输(MTU) + m_customUdpLabel->setFixedWidth(MAX_LABEL_WIDTH); + m_customUdpLabel->setLabelText(tr("Use custom UDP fragment size")); //使用自定义UDP分片大小 + m_acceptAuthedPaksLabel->setFixedWidth(440);//文本显示宽度 + m_acceptAuthedPaksLabel->setLabelText(tr("Accept authenticated packets from any address (Float)")); //接受来自任何地址(Float)已通过身份验证的数据包 + + m_subjectMatchLabel->setText(tr("Subject Match")); //主题匹配 + m_keyPathLabel->setText(tr("Key File")); //密钥文件 + m_keyDirectionLabel->setText(tr("Key Direction")); //密钥方向 + + m_proxyServerAddLabel->setText(tr("Server Address")); //服务器地址 + m_proxyPortLabel->setText(tr("Port")); //端口 + m_proxyUsernameLabel->setText(tr("Proxy USername")); //代理用户名 + m_proxyPwdLabel->setText(tr("Proxy Password")); //代理密码 + + generalLabel->setText(tr("General")); //常规 + tlsSettingLabel->setText(tr("TLS settings")); + serverCertCheckLabel->setText(tr("Server Certificate Check")); //服务器证书检验 + usePreviousCertLabel->setFixedWidth(MAX_LABEL_WIDTH); + usePreviousCertLabel->setLabelText(tr("Use the previous authentication end (server) certificate")); //使用前面验证端(服务器)证书 + verifyPeerCertLabel->setFixedWidth(MAX_LABEL_WIDTH); + verifyPeerCertLabel->setLabelText(tr("Verify peer (server) certificate nsCertType specification")); //验证对等点(服务器)证书nsCertType指定 + tlsModeLabel->setText(tr("Mode")); + proxiesLabel->setText(tr("Proxies")); + proxyTypeLabel->setText(tr("Proxy Type")); + securityLabel->setText(tr("Security")); + hmacLabel->setText(tr("HMAC Authentication")); //HMAC认证 + hmacLabel->setFixedWidth(268); //调整控件对齐=MAX_LABEL_WIDTH+28 + + QFont font = generalLabel->font(); + font.setWeight(QFont::Weight::Medium); + generalLabel->setFont(font); + tlsSettingLabel->setFont(font); + proxiesLabel->setFont(font); + securityLabel->setFont(font); + + m_setVDevNameEdit->setPlaceholderText(tr("Input content")); //输入内容 + + m_compressionCombox->addItem(tr("No"), KYCOMP2_LZODISABLE); //否 + m_compressionCombox->addItem("LZO", KYCOMP2_LZO); + m_compressionCombox->addItem("LZ4", KYCOMP2_LZ4); + m_compressionCombox->addItem("LZ4 v2", KYCOMP2_LZ4V2); + m_compressionCombox->addItem(tr("Self-adaption"), KYCOMP2_LZOADAPTIVE); //自适应 + m_compressionCombox->addItem(tr("Automatic"), KYCOMP2_AUTO); //自动 + + m_setVDevTypeCombox->addItem("TUN", KYVIRDEVTYPE_TUN); + m_setVDevTypeCombox->addItem("TAP", KYVIRDEVTYPE_TAP); + + m_specExitRestarCombox->addItem(tr("Exit"), KYVPNPING_EXIT); //退出 + m_specExitRestarCombox->addItem(tr("Restart"), KYVPNPING_RESTART); //重启 + + m_serverCertCheckCombox->addItem(tr("Don't verify certificate identification"), KYCHECKSERVER_NONE); //不验证证书标识 + m_serverCertCheckCombox->addItem(tr("Verify the entire subject exactly"), KYCHECKSERVER_ENTIRETHEME); //确切地验证整个主题 + m_serverCertCheckCombox->addItem(tr("Verify name exactly"), KYCHECKSERVER_ENTIRENAME); //精确验证名称 + m_serverCertCheckCombox->addItem(tr("Verify name by prefix"), KYCHECKSERVER_PRENAME); //按前缀验证名称 + + m_usePreviousCertCombox->addItem(tr("Server"), KYVPNCERT_SERVER); + m_usePreviousCertCombox->addItem(tr("Client"), KYVPNCERT_CLIENT); + + m_verifyPeerCertCombox->addItem(tr("Server"), KYVPNCERT_SERVER); + m_verifyPeerCertCombox->addItem(tr("Client"), KYVPNCERT_CLIENT); + + m_tlsModeCombox->addItem(tr("None"), NONE); //无 + m_tlsModeCombox->addItem(tr("TLS-Certification"), TLS_CERT); //TLS-认证 + m_tlsModeCombox->addItem(tr("TLS-Encryption"), TLS_ENCRYPTION); //TLS-加密 + + m_keyDirectionCombox->addItem(tr("None"), KEY_DIRECTION_NONE); //无 + m_keyDirectionCombox->addItem("0", KEY_DIRECTION_ZERO); + m_keyDirectionCombox->addItem("1", KEY_DIRECTION_ONE); + + m_proxyTypeCombox->addItem(tr("Not Required"), NO); //不需要 + m_proxyTypeCombox->addItem("HTTP", HTTP); + m_proxyTypeCombox->addItem("SOCKS", SOCKS); + + m_hmacAuthCombox->addItem(tr("Default"), KYHMACAUTH_DEFAULT); //默认 + m_hmacAuthCombox->addItem(tr("None"), KYHMACAUTH_NONE); //无 + m_hmacAuthCombox->addItem("MD-4", KYHMACAUTH_MD4); + m_hmacAuthCombox->addItem("MD-5", KYHMACAUTH_MD5); + m_hmacAuthCombox->addItem("SHA-1", KYHMACAUTH_SHA1); + m_hmacAuthCombox->addItem("SHA-224", KYHMACAUTH_SHA224); + m_hmacAuthCombox->addItem("SHA-256", KYHMACAUTH_SHA256); + m_hmacAuthCombox->addItem("SHA-384", KYHMACAUTH_SHA384); + m_hmacAuthCombox->addItem("SHA-512", KYHMACAUTH_SHA512); + m_hmacAuthCombox->addItem("RIPEMD-160", KYHMACAUTH_RIPEMD160); + + //控件输入格式限制 + QRegExp rxNumber("^[0-9]+$"); + m_gatewayPortEdit->setValidator(new QRegExpValidator(rxNumber, this)); + m_renogotiaInrEdit->setValidator(new QRegExpValidator(rxNumber, this)); + m_customMtuEdit->setValidator(new QRegExpValidator(rxNumber, this)); + m_customUdpFragSizeEdit->setValidator(new QRegExpValidator(rxNumber, this)); + m_specPingInrEdit->setValidator(new QRegExpValidator(rxNumber, this)); + m_specExRePingEdit->setValidator(new QRegExpValidator(rxNumber, this)); + m_specMaxRouteEdit->setValidator(new QRegExpValidator(rxNumber, this)); + + // IP的正则格式限制 + QRegExp rxIp("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"); + m_proxyServerAddEdit->setValidator(new QRegExpValidator(rxIp, this)); + + //default + m_gatewayPortEdit->setText("1194"); + m_renogotiaInrEdit->setText("0"); + m_customMtuEdit->setText("1500"); + m_customUdpFragSizeEdit->setText("1500"); + m_specPingInrEdit->setText("30"); + m_specExRePingEdit->setText("30"); + m_specMaxRouteEdit->setText("30"); + if (m_serverCertCheckCombox->currentData().toInt() == (int)KYCHECKSERVER_NONE) { + m_subjectMatchEdit->setEnabled(false); + } else { + m_subjectMatchEdit->setEnabled(true); + } + onTlsModeComboxIndexChanged(); + onProxyTypeComboxIndexChanged(); +} + +void VpnAdvancedPage::initSSwanAdiaFrame() +{ + /**********控件**********/ + QLabel *optionsLabel = new QLabel(this); + QLabel *ikeLabel = new QLabel(this); + QLabel *espLabel = new QLabel(this); + m_optionsListWidget = new QListWidget(this); + m_requestInIPCheckbox = new QCheckBox(this); + m_udpEncapCheckbox = new QCheckBox(this); + m_ipCompCheckbox = new QCheckBox(this); + m_enablCustomCheckbox = new QCheckBox(this); + m_ikeEdit = new QLineEdit(this); + m_espEdit = new QLineEdit(this); + m_ikeEspFrame = new QFrame(m_sSwanAdiaFrame); + + /**********布局**********/ + QVBoxLayout *sSwanAdiaVLayout = new QVBoxLayout(m_sSwanAdiaFrame); + sSwanAdiaVLayout->setContentsMargins(NO_LAYOUT_MARGINS); + sSwanAdiaVLayout->setSpacing(LAYOUT_SPACING_SMALL); + + QFormLayout *ikeEspFrameLayout = new QFormLayout(m_ikeEspFrame); + ikeEspFrameLayout->setContentsMargins(NO_LAYOUT_MARGINS); + ikeEspFrameLayout->setHorizontalSpacing(HOR_LAYOUT_SPACING); + ikeEspFrameLayout->setVerticalSpacing(LAYOUT_ADD_SPACING); + ikeEspFrameLayout->addRow(ikeLabel, m_ikeEdit); + ikeEspFrameLayout->addRow(espLabel, m_espEdit); + + sSwanAdiaVLayout->addWidget(optionsLabel); + sSwanAdiaVLayout->addWidget(m_optionsListWidget); + sSwanAdiaVLayout->addSpacing(LAYOUT_ADD_SPACING); + sSwanAdiaVLayout->addWidget(m_enablCustomCheckbox); + sSwanAdiaVLayout->addWidget(m_ikeEspFrame); + sSwanAdiaVLayout->addStretch(); + m_optionsListWidget->setFixedHeight(LISTWIDGET_HEIGHT_SMALL); + + /**********控件显示**********/ + optionsLabel->setText(tr("Options:")); //选项: + ikeLabel->setText("IKE"); + espLabel->setText("ESP"); + m_requestInIPCheckbox->setText(tr("Request an inner IP address")); //请求内部IP地址 + m_udpEncapCheckbox->setText(tr("Enforce UDP encapsulation")); //强制UDP封装 + m_ipCompCheckbox->setText(tr("Use IP compression")); //使用IP压缩 + m_enablCustomCheckbox->setText(tr("Enable custom password suggestions")); //启用自定义密码建议 + + m_optionsListWidget->setFocusPolicy(Qt::FocusPolicy::NoFocus); + m_optionsListWidget->setFrameShape(QFrame::Shape::StyledPanel); + addListItem(m_optionsListWidget, m_requestInIPCheckbox); + addListItem(m_optionsListWidget, m_udpEncapCheckbox); + addListItem(m_optionsListWidget, m_ipCompCheckbox); + + //strong-Swan default + m_enablCustomCheckbox->setChecked(false); + m_ikeEspFrame->setEnabled(false); +} + +void VpnAdvancedPage::initDefalutCheckState() +{ + m_mppeECheckbox->setChecked(false); + m_mppeECombox->setEnabled(m_mppeECheckbox->isChecked()); + + //openVPN + m_customGatewayPortCheckbox->setChecked(true); + m_customRenegotiaInrCheckbox->setChecked(true); + m_compressionCheckbox->setChecked(true); + m_tcpConnCheckbox->setChecked(true); + m_setVDevTypeCheckbox->setChecked(true); + m_setVDevNameCheckbox->setChecked(true); + m_customMtuCheckbox->setChecked(true); + m_customUdpFragSizeCheckbox->setChecked(true); + m_tcpMssCheckbox->setChecked(true); + m_randomRemoteHostCheckbox->setChecked(true); + m_ipv6TunLinkCheckbox->setChecked(true); + m_specPingInrCheckbox->setChecked(true); + m_specExitPingCheckbox->setChecked(true); + m_acceptAuthedPaksCheckbox->setChecked(true); + m_specMaxRouteCheckbox->setChecked(true); + + m_gatewayPortEdit->setEnabled(m_customGatewayPortCheckbox->isChecked()); + m_renogotiaInrEdit->setEnabled(m_customRenegotiaInrCheckbox->isChecked()); + m_setVDevNameEdit->setEnabled(m_setVDevNameCheckbox->isChecked()); + m_customMtuEdit->setEnabled(m_customMtuCheckbox->isChecked()); + m_customUdpFragSizeEdit->setEnabled(m_customUdpFragSizeCheckbox->isChecked()); + m_specPingInrEdit->setEnabled(m_specPingInrCheckbox->isChecked()); + m_specExRePingEdit->setEnabled(m_specExitPingCheckbox->isChecked()); + m_specMaxRouteEdit->setEnabled(m_specMaxRouteCheckbox->isChecked()); + m_compressionCombox->setEnabled(m_compressionCheckbox->isChecked()); + m_setVDevTypeCombox->setEnabled(m_setVDevTypeCheckbox->isChecked()); + m_specExitRestarCombox->setEnabled(m_specExitPingCheckbox->isChecked()); + + m_usePreviousCertCombox->setEnabled(m_usePreviousCertCheckbox->isChecked()); + m_verifyPeerCertCombox->setEnabled(m_verifyPeerCertCheckbox->isChecked()); + + m_customKeySizeEdit->setEnabled(m_customKeySizeCheckbox->isChecked()); +} + +void VpnAdvancedPage::addListItem(QListWidget *listWidget, QWidget *widget) +{ + QListWidgetItem *listWidgetItem = new QListWidgetItem(listWidget); + QWidget *itemWidget = new QWidget(listWidget); + QHBoxLayout *hLayout = new QHBoxLayout(itemWidget); + hLayout->setContentsMargins(16, 0, 0, 0); + hLayout->addWidget(widget); + listWidgetItem->setSizeHint(QSize(listWidget->width(), ITEM_HEIGHT)); + listWidgetItem->setFlags(Qt::NoItemFlags); + listWidget->addItem(listWidgetItem); + listWidget->setItemWidget(listWidgetItem, itemWidget); +} + +void VpnAdvancedPage::initCheckWidget(QCheckBox *checkBox, FixLabel *label, QWidget *widget) +{ + QHBoxLayout *hLayout = new QHBoxLayout(widget); + hLayout->setContentsMargins(NO_LAYOUT_MARGINS); + hLayout->setSpacing(4); + hLayout->addWidget(checkBox); + hLayout->addWidget(label); + hLayout->addStretch(); +} + +void VpnAdvancedPage::onProxyTypeComboxIndexChanged() +{ + switch (m_proxyTypeCombox->currentData().toInt()) { + case NO: + m_proxyServerAddEdit->clear(); + m_proxyPortEdit->clear(); + m_proxyUsernameEdit->clear(); + m_proxyPwdEdit->clear(); + m_infiniteRetryCheckbox->setChecked(false); + + m_proxyServerAddLabel->setEnabled(false); + m_proxyPortLabel->setEnabled(false); + m_proxyUsernameLabel->setEnabled(false); + m_proxyPwdLabel->setEnabled(false); + m_infiniteRetryCheckbox->setEnabled(false); + m_proxyServerAddEdit->setEnabled(false); + m_proxyPortEdit->setEnabled(false); + m_proxyUsernameEdit->setEnabled(false); + m_proxyPwdEdit->setEnabled(false); + break; + case HTTP: + m_proxyServerAddLabel->setEnabled(true); + m_proxyPortLabel->setEnabled(true); + m_proxyUsernameLabel->setEnabled(true); + m_proxyPwdLabel->setEnabled(true); + m_infiniteRetryCheckbox->setEnabled(true); + m_proxyServerAddEdit->setEnabled(true); + m_proxyPortEdit->setEnabled(true); + m_proxyUsernameEdit->setEnabled(true); + m_proxyPwdEdit->setEnabled(true); + break; + case SOCKS: + m_proxyServerAddLabel->setEnabled(true); + m_proxyPortLabel->setEnabled(true); + m_infiniteRetryCheckbox->setEnabled(true); + m_proxyServerAddEdit->setEnabled(true); + m_proxyPortEdit->setEnabled(true); + m_proxyUsernameLabel->setEnabled(false); + m_proxyPwdLabel->setEnabled(false); + m_proxyUsernameEdit->setEnabled(false); + m_proxyPwdEdit->setEnabled(false); + break; + default: + break; + } +} + +void VpnAdvancedPage::onTlsModeComboxIndexChanged() +{ + switch (m_tlsModeCombox->currentData().toInt()) { + case NONE: + m_keyPathLabel->setEnabled(false); + m_keyPathEdit->setEnabled(false); + m_keyPathChooseBtn->setEnabled(false); + m_keyDirectionLabel->setEnabled(false); + m_keyDirectionCombox->setEnabled(false); + break; + case TLS_CERT: + m_keyPathLabel->setEnabled(true); + m_keyPathEdit->setEnabled(true); + m_keyPathChooseBtn->setEnabled(true); + m_keyDirectionLabel->setEnabled(true); + m_keyDirectionCombox->setEnabled(true); + break; + case TLS_ENCRYPTION: + m_keyPathLabel->setEnabled(true); + m_keyPathEdit->setEnabled(true); + m_keyPathChooseBtn->setEnabled(true); + m_keyDirectionLabel->setEnabled(false); + m_keyDirectionCombox->setEnabled(false); + break; + default: + break; + } +} + +void VpnAdvancedPage::setEnableOfConfirmBtn() +{ + Q_EMIT setAdvancedPageState(checkConfirmBtnIsEnabled()); +} + +void VpnAdvancedPage::onKeyPathButtonClicked() +{ + QString fileName = QFileDialog::getOpenFileName(this, + tr("Choose a private key"), + "recent:///", + tr("Key Files (*.key *.pem *.der *.p12 *.pfx)")); + if (!fileName.isNull()) { + m_keyPathEdit->blockSignals(true); + m_keyPathEdit->setText(fileName); + m_keyPathEdit->blockSignals(false); + } +} + +void VpnAdvancedPage::showL2tpAdiaPage() +{ + m_defaultAdiaFrame->setHidden(false); + m_mruFrame->setHidden(false); + m_compModeListWidget->item(COMP_MODE_PROTOCOL)->setHidden(false); + m_compModeListWidget->item(COMP_MODE_ADDRESS)->setHidden(false); + m_compModeListWidget->setFixedHeight(LISTWIDGET_HEIGHT); + + m_openVpnAdiaFrame->setHidden(true); + m_sSwanAdiaFrame->setHidden(true); +} + +void VpnAdvancedPage::showPptpAdiaPage() +{ + m_defaultAdiaFrame->setHidden(false); + m_compModeListWidget->item(COMP_MODE_PROTOCOL)->setHidden(true); + m_compModeListWidget->item(COMP_MODE_ADDRESS)->setHidden(true); + m_compModeListWidget->setFixedHeight(LISTWIDGET_HEIGHT_SMALL); + + m_mruFrame->setHidden(true); + m_openVpnAdiaFrame->setHidden(true); + m_sSwanAdiaFrame->setHidden(true); +} + +void VpnAdvancedPage::showOpenVpnAdiaPage() +{ + m_openVpnAdiaFrame->setHidden(false); + + m_defaultAdiaFrame->setHidden(true); + m_mruFrame->setHidden(true); + m_sSwanAdiaFrame->setHidden(true); +} + +void VpnAdvancedPage::showSSwanAdiaPage() +{ + m_sSwanAdiaFrame->setHidden(false); + + m_defaultAdiaFrame->setHidden(true); + m_mruFrame->setHidden(true); + m_openVpnAdiaFrame->setHidden(true); +} + +bool VpnAdvancedPage::checkConfirmBtnIsEnabled() +{ + //L2TP + if (!m_mruFrame->isHidden()) { + if (m_mruEdit->text().isEmpty() || m_mtuEdit->text().isEmpty()) { + qDebug() << LOG_FLAG << "MRU or MTU is empty"; + return false; + } + } + + //PPTP 无必填项 + + //OPEN VPN + if (!m_openVpnAdiaFrame->isHidden()) { + if (m_customGatewayPortCheckbox->isChecked() && m_gatewayPortEdit->text().isEmpty()) { + return false; + } + + if (m_customRenegotiaInrCheckbox->isChecked() && m_renogotiaInrEdit->text().isEmpty()) { + return false; + } + + if (m_setVDevNameCheckbox->isChecked() && m_setVDevNameEdit->text().isEmpty()) { + return false; + } + + if (m_customMtuCheckbox->isChecked() && m_customMtuEdit->text().isEmpty()) { + return false; + } + + if (m_customUdpFragSizeCheckbox->isChecked() && m_customUdpFragSizeEdit->text().isEmpty()) { + return false; + } + + if (m_specPingInrCheckbox->isChecked() && m_specPingInrEdit->text().isEmpty()) { + return false; + } + + if (m_specExitPingCheckbox->isChecked() && m_specExRePingEdit->text().isEmpty()) { + return false; + } + + if (m_specMaxRouteCheckbox->isChecked() && m_specMaxRouteEdit->text().isEmpty()) { + return false; + } + + if (m_serverCertCheckCombox->currentData().toInt() != (int)KYCHECKSERVER_NONE + && m_subjectMatchEdit->text().isEmpty()) { + return false; + } + + if (m_tlsModeCombox->currentData().toInt() == TLS_CERT || m_tlsModeCombox->currentData().toInt() == TLS_ENCRYPTION) { + if (m_keyPathEdit->text().isEmpty()) { + return false; + } + } + + if (m_proxyTypeCombox->currentData().toInt() == HTTP || m_proxyTypeCombox->currentData().toInt() == SOCKS) { + if (m_proxyServerAddEdit->text().isEmpty() || !getTextEditState(m_proxyServerAddEdit->text())) { + return false; + } + if (m_proxyPortEdit->text().isEmpty()) { + return false; + } + } + + if(m_customKeySizeCheckbox->isChecked() && m_customKeySizeEdit->text().isEmpty()) { + return false; + } + } + + //strong-swan + if (!m_sSwanAdiaFrame->isHidden()) { + if (m_enablCustomCheckbox->isChecked()) { + if (m_ikeEdit->text().isEmpty() || m_espEdit->text().isEmpty()) { + return false; + } + } + } + return true; +} + +bool VpnAdvancedPage::getTextEditState(QString text) +{ + if (text.isEmpty()) { + return true; + } + QRegExp rx("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"); + + bool match = false; + match = rx.exactMatch(text); + + return match; +} diff --git a/src-vpn/frontend/vpndetails/vpnadvancedpage.h b/src-vpn/frontend/vpndetails/vpnadvancedpage.h new file mode 100644 index 00000000..4c6be900 --- /dev/null +++ b/src-vpn/frontend/vpndetails/vpnadvancedpage.h @@ -0,0 +1,197 @@ +#ifndef VPNADVANCEDPAGE_H +#define VPNADVANCEDPAGE_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "kylable.h" +#include "kwidget.h" +#include "kpasswordedit.h" +#include "vpnconfigpage.h" +#include "kyvpnconnectoperation.h" + +using namespace kdk; + +enum TlsMode { + NONE = 0, + TLS_CERT, + TLS_ENCRYPTION +}; + +enum ProxyType { + NO = 0, + HTTP, + SOCKS +}; + +class VpnAdvancedPage : public QFrame +{ + Q_OBJECT +public: + VpnAdvancedPage(QWidget *parent = nullptr); + ~VpnAdvancedPage() = default; + + //Adia: Advanced + void setL2tpOrPptpAdiaInfo(const KyVpnConfig &vpnInfo); + void setOpenVpnAdiaInfo(const KyVpnConfig &vpnInfo); + void setStrongSwanAdiaInfo(const KyVpnConfig &vpnInfo); + + bool checkIsChanged(const KyVpnConfig &vpnInfo, VpnType &vpnType); + bool checkL2tpIsChanged(const KyVpnConfig &vpnInfo); + bool checkPptpIsChanged(const KyVpnConfig &vpnInfo); + bool checkOpenVpnIsChanged(const KyVpnConfig &vpnInfo); + bool checkStrongSwanIsChanged(const KyVpnConfig &vpnInfo); + + void updateL2tpOrPptpAdiaInfo(KyVpnConfig &vpnInfo); + void updateOpenVpnAdiaInfo(KyVpnConfig &vpnInfo); + void updateStrongSwanAdiaInfo(KyVpnConfig &vpnInfo); + +protected: + void paintEvent(QPaintEvent *event); + +private: + bool m_isOpenVpn; + + QFrame *m_defaultAdiaFrame; + QFrame *m_mruFrame; + QFrame *m_openVpnAdiaFrame; + QFrame *m_sSwanAdiaFrame; + + //L2TP PPTP Encryption(E) + QCheckBox *m_mppeECheckbox = nullptr; + QCheckBox *m_useStatefulECheckbox = nullptr; + QCheckBox *m_sendPppEchoPkgCheckbox = nullptr; + + QLabel *m_authModeLabel; + QLabel *m_compModeLabel; + QLabel *m_mruLabel; + QLabel *m_mtuLabel; + QLineEdit *m_mruEdit; + QLineEdit *m_mtuEdit; + QComboBox *m_mppeECombox = nullptr; + //认证方式 + QListWidget *m_authModeListWidget = nullptr; + QCheckBox *m_papAuthCheckbox = nullptr; + QCheckBox *m_chapAuthCheckbox = nullptr; + QCheckBox *m_mschapAuthCheckbox = nullptr; + QCheckBox *m_mschap2AuthCheckbox = nullptr; + QCheckBox *m_eapAuthCheckbox = nullptr; + //压缩方式 + QListWidget *m_compModeListWidget = nullptr; + QCheckBox *m_bsdCompModeCheckbox = nullptr; + QCheckBox *m_defaultCompModeCheckbox = nullptr; + QCheckBox *m_tcpCompModeCheckbox = nullptr; + QCheckBox *m_protocolCompModeCheckbox = nullptr; + QCheckBox *m_addressCompModeCheckbox = nullptr; + + //Open VPN + //general + QCheckBox *m_customGatewayPortCheckbox = nullptr; + QCheckBox *m_customRenegotiaInrCheckbox = nullptr; + QCheckBox *m_compressionCheckbox = nullptr; + QCheckBox *m_tcpConnCheckbox = nullptr; + QCheckBox *m_setVDevTypeCheckbox = nullptr; + QCheckBox *m_setVDevNameCheckbox = nullptr; + QCheckBox *m_customMtuCheckbox = nullptr; + QCheckBox *m_customUdpFragSizeCheckbox = nullptr; + QCheckBox *m_tcpMssCheckbox = nullptr; + QCheckBox *m_randomRemoteHostCheckbox = nullptr; + QCheckBox *m_ipv6TunLinkCheckbox = nullptr; + QCheckBox *m_specPingInrCheckbox = nullptr; + QCheckBox *m_specExitPingCheckbox = nullptr; + QCheckBox *m_acceptAuthedPaksCheckbox = nullptr; + QCheckBox *m_specMaxRouteCheckbox = nullptr; + + QLineEdit *m_gatewayPortEdit; + QLineEdit *m_renogotiaInrEdit; + QLineEdit *m_setVDevNameEdit; + QLineEdit *m_customMtuEdit; + QLineEdit *m_customUdpFragSizeEdit; + QLineEdit *m_specPingInrEdit; + QLineEdit *m_specExRePingEdit; + QLineEdit *m_specMaxRouteEdit; + QComboBox *m_compressionCombox = nullptr; + QComboBox *m_setVDevTypeCombox = nullptr; + QComboBox *m_specExitRestarCombox = nullptr; + FixLabel *m_customRenoInrLabel; + FixLabel *m_customMtuLabel; + FixLabel *m_customUdpLabel; + FixLabel *m_acceptAuthedPaksLabel; + //TLS settings + QLabel *m_subjectMatchLabel; + QLabel *m_keyPathLabel; + QLabel *m_keyDirectionLabel; + QLineEdit *m_subjectMatchEdit; + QLineEdit *m_keyPathEdit; + QPushButton *m_keyPathChooseBtn; + QCheckBox *m_usePreviousCertCheckbox = nullptr; + QCheckBox *m_verifyPeerCertCheckbox = nullptr; + QComboBox *m_serverCertCheckCombox = nullptr; + QComboBox *m_usePreviousCertCombox = nullptr; + QComboBox *m_verifyPeerCertCombox = nullptr; + QComboBox *m_tlsModeCombox = nullptr; + QComboBox *m_keyDirectionCombox = nullptr; + //proxies + QLabel *m_proxyServerAddLabel; + QLabel *m_proxyPortLabel; + QLabel *m_proxyUsernameLabel; + QLabel *m_proxyPwdLabel; + QComboBox *m_proxyTypeCombox = nullptr; + QCheckBox *m_infiniteRetryCheckbox = nullptr; + QLineEdit *m_proxyServerAddEdit; + QLineEdit *m_proxyPortEdit; + QLineEdit *m_proxyUsernameEdit; + KPasswordEdit *m_proxyPwdEdit; + //security + QCheckBox *m_customKeySizeCheckbox = nullptr; + QLineEdit *m_customKeySizeEdit; + QComboBox *m_hmacAuthCombox = nullptr; + + //strongswan + QListWidget *m_optionsListWidget = nullptr; + QCheckBox *m_requestInIPCheckbox = nullptr; + QCheckBox *m_udpEncapCheckbox = nullptr; + QCheckBox *m_ipCompCheckbox = nullptr; + QCheckBox *m_enablCustomCheckbox = nullptr; + QFrame *m_ikeEspFrame; + QLineEdit *m_ikeEdit; + QLineEdit *m_espEdit; + + void initUi(); + void initConnect(); + void initDefaultAdiaFrame(); //L2TP PPTP + void initOpenVpnAdiaFrame(); //Open VPN + void initSSwanAdiaFrame(); //strong-swan + void initDefalutCheckState(); + void addListItem(QListWidget *listWidget, QWidget *widget); + void initCheckWidget(QCheckBox *checkBox, FixLabel *label, QWidget *widget); + + void showL2tpAdiaPage(); + void showPptpAdiaPage(); + void showOpenVpnAdiaPage(); + void showSSwanAdiaPage(); + bool checkConfirmBtnIsEnabled(); + bool getTextEditState(QString text); + +private Q_SLOTS: + void onProxyTypeComboxIndexChanged(); + void onTlsModeComboxIndexChanged(); + void setEnableOfConfirmBtn(); + void onKeyPathButtonClicked(); + +public Q_SLOTS: + void setVpnAdvancedPage(const VpnType &type); + +Q_SIGNALS: + void setAdvancedPageState(bool); +}; + +#endif // VPNADVANCEDPAGE_H diff --git a/src-vpn/frontend/vpndetails/vpnconfigpage.cpp b/src-vpn/frontend/vpndetails/vpnconfigpage.cpp new file mode 100644 index 00000000..eeb4e4da --- /dev/null +++ b/src-vpn/frontend/vpndetails/vpnconfigpage.cpp @@ -0,0 +1,1055 @@ +#include "vpnconfigpage.h" +#include +#include + +#define NO_LAYOUT_MARGINS 0, 0, 0, 0 +#define NO_SPACE 0 +#define HLAYOUT_SPACING 16 +#define VLAYOUT_SPACING 24 +#define LEFT_LABEL_WIDTH 100 +#define PIN_MAX_LENGTH 10 +#define PWD_OPTION_THISUSER_INDEX 0 +#define PWD_OPTION_ALLUSERS_INDEX 1 +#define PWD_OPTION_ASKEVERYTIME_INDEX 2 +#define PWD_OPTION_NOTREQUIRED_INDEX 3 +#define LOG_FLAG "[VPN ConfigPage]" + +VpnConfigPage::VpnConfigPage(QWidget *parent) : QFrame(parent) +{ + initUI(); + initConnect(); + onVpnTypeComboxIndexChanged(); +} + +VpnType VpnConfigPage::getVpnType() +{ + return VpnType(m_vpnTypeComboBox->currentData().toInt()); +} + +void VpnConfigPage::setVpnConfigInfo(const KyVpnConfig &vpnInfo) +{ + m_vpnNameEdit->setText(vpnInfo.m_vpnName); + m_serverAddressEdit->setText(vpnInfo.m_gateway); + m_vpnTypeComboBox->setCurrentIndex(vpnInfo.m_vpnType); + onVpnTypeComboxIndexChanged(); + + switch (vpnInfo.m_vpnType) { + case KYVPNTYPE_L2TP: + setL2tpConfigInfo(vpnInfo); + break; + case KYVPNTYPE_PPTP: + setPptpConfigInfo(vpnInfo); + break; + case KYVPNTYPE_OPENVPN: + setOpenVpnConfigInfo(vpnInfo); + break; + case KYVPNTYPE_STRONGSWAN: + setSSwanVpnConfigInfo(vpnInfo); + break; + default: + qDebug() << LOG_FLAG << "Unknow VPN Type" << vpnInfo.m_vpnType; + break; + } +} + +bool VpnConfigPage::checkIsChanged(const KyVpnConfig &vpnInfo) +{ + bool isChanged = false; + int currentVpnType = m_vpnTypeComboBox->currentData().toInt(); + + if (vpnInfo.m_vpnType != currentVpnType + || vpnInfo.m_vpnName != m_vpnNameEdit->text() + || vpnInfo.m_gateway != m_serverAddressEdit->text()) { + + isChanged = true; + } + + switch (currentVpnType) { + case L2TP: + if (checkL2tpIsChanged(vpnInfo)) { + isChanged = true; + } + break; + case PPTP: + if (checkPptpIsChanged(vpnInfo)) { + isChanged = true; + } + break; + case OPEN_VPN: + if (checkOpenVpnIsChanged(vpnInfo)) { + isChanged = true; + } + break; + case STRONG_SWAN: + if (checkStrongSwanIsChanged(vpnInfo)) { + isChanged = true; + } + default: + break; + } + + return isChanged; +} + +void VpnConfigPage::updateVpnConfigInfo(KyVpnConfig &vpnInfo) +{ + vpnInfo.m_vpnType = (KyVpnType)m_vpnTypeComboBox->currentData().toInt(); + vpnInfo.m_vpnName = m_vpnNameEdit->text(); + vpnInfo.m_gateway = m_serverAddressEdit->text(); + switch (m_vpnTypeComboBox->currentData().toInt()) { + case L2TP: + updateL2tpConfigInfo(vpnInfo); + break; + case OPEN_VPN: + updateOpenVpnConfigInfo(vpnInfo); + break; + case PPTP: + updatePptpConfigInfo(vpnInfo); + break; + case STRONG_SWAN: + updateSSwanVpnConfigInfo(vpnInfo); + break; + default: + break; + } +} + +void VpnConfigPage::initUI() +{ + /**********控件**********/ + //公有 + m_vpnTypeLabel = new QLabel(this); + m_vpnNameLabel = new QLabel(this); + m_serverAddressLabel = new FixLabel(this); + m_vpnTypeComboBox = new QComboBox(this); + m_vpnNameEdit = new QLineEdit(this); + m_serverAddressEdit = new QLineEdit(this); + + //认证方式 Authentication Mode + m_authModeLabel = new FixLabel(this); + m_authModeComboBox = new QComboBox(this); + + //证书 私钥 + m_caCertLabel = new FixLabel(this); + m_userCertLabel = new FixLabel(this); + m_privateKeyLabel = new FixLabel(this); + m_privateKeyPwdLabel = new FixLabel(this); + m_pwdOptionLabel = new FixLabel(this); + + m_caCertPathEdit = new QLineEdit(this); + m_userCertPathEdit = new QLineEdit(this); + m_privateKeyEdit = new QLineEdit(this); + m_privateKeyPwdEdit = new KPasswordEdit(this); + m_pwdOptionCombox = new QComboBox(this); + + m_caCertButton = new QPushButton(this); + m_userCertButton = new QPushButton(this); + m_privateKeyButton = new QPushButton(this); + + //静态密钥 + m_staticKeyLabel = new QLabel(this); + m_keyDirectionLabel = new FixLabel(this); + m_noticesLabel = new QLabel(this); + m_localIpLabel = new QLabel(this); + m_remoteIpLabel = new QLabel(this); + + m_staticKeyPathEdit = new QLineEdit(this); + m_staticKeyButton = new QPushButton(this); + m_keyDirectionCombox = new QComboBox(this); + m_localIpEdit = new QLineEdit(this); + m_remoteIpEdit = new QLineEdit(this); + + //智能卡 PIN码 + m_pinLabel = new QLabel(this); + m_pinEdit = new QLineEdit(this); + + //密码 + m_usernameLabel = new FixLabel(this); + m_userPwdLabel = new QLabel(this); + m_userPwdOptionLabel = new FixLabel(this); + m_usernameEdit = new QLineEdit(this); + m_userPwdEdit = new KPasswordEdit(this); + m_userPwdOptionCombox = new QComboBox(this); + + //L2TP PPTP公有 + m_ntDomainLabel = new QLabel(this); + m_ntDomainEdit = new QLineEdit(this); + + + /**********布局**********/ + m_vpnCommunalFrame = new QFrame(this); + m_authModeFrame = new QFrame(this); + m_caCertFrame = new QFrame(this); + m_userCertFrame = new QFrame(this); + m_staticKeysFrame = new QFrame(this); + m_pinFrame = new QFrame(this); + m_PrivateKeysFrame = new QFrame(this); + m_usersFrame = new QFrame(this); + m_userPwdOpFrame = new QFrame(this); + m_ntFrame = new QFrame(this); + + //布局 + QVBoxLayout *mainLayout = new QVBoxLayout(this); + mainLayout->setContentsMargins(NO_LAYOUT_MARGINS); + mainLayout->setSpacing(VLAYOUT_SPACING); + mainLayout->addWidget(m_vpnCommunalFrame); + mainLayout->addWidget(m_authModeFrame); + mainLayout->addWidget(m_caCertFrame); + mainLayout->addWidget(m_userCertFrame); + mainLayout->addWidget(m_staticKeysFrame); + mainLayout->addWidget(m_pinFrame); + mainLayout->addWidget(m_PrivateKeysFrame); + mainLayout->addWidget(m_usersFrame); + mainLayout->addWidget(m_userPwdOpFrame); + mainLayout->addWidget(m_ntFrame); + mainLayout->addSpacing(3); + mainLayout->addStretch(); + + QGridLayout *vpnCommLayout = new QGridLayout(m_vpnCommunalFrame); + vpnCommLayout->setContentsMargins(NO_LAYOUT_MARGINS); + vpnCommLayout->setHorizontalSpacing(HLAYOUT_SPACING); + vpnCommLayout->setVerticalSpacing(VLAYOUT_SPACING); + vpnCommLayout->addWidget(m_vpnTypeLabel, 0, 0); + vpnCommLayout->addWidget(m_vpnNameLabel, 1, 0); + vpnCommLayout->addWidget(m_serverAddressLabel, 2, 0); + vpnCommLayout->addWidget(m_vpnTypeComboBox, 0, 1); + vpnCommLayout->addWidget(m_vpnNameEdit, 1, 1); + vpnCommLayout->addWidget(m_serverAddressEdit, 2, 1); + m_vpnTypeLabel->setFixedWidth(LEFT_LABEL_WIDTH); + m_vpnNameLabel->setFixedWidth(LEFT_LABEL_WIDTH); + m_serverAddressLabel->setFixedWidth(LEFT_LABEL_WIDTH); + + QHBoxLayout *authMdLayout = new QHBoxLayout(m_authModeFrame); + authMdLayout->setContentsMargins(NO_LAYOUT_MARGINS); + authMdLayout->setSpacing(HLAYOUT_SPACING); + authMdLayout->addWidget(m_authModeLabel); + authMdLayout->addWidget(m_authModeComboBox); + m_authModeLabel->setFixedWidth(LEFT_LABEL_WIDTH); + + QHBoxLayout *caCertLayout = new QHBoxLayout(m_caCertFrame); + caCertLayout->setContentsMargins(NO_LAYOUT_MARGINS); + caCertLayout->setSpacing(HLAYOUT_SPACING); + caCertLayout->addWidget(m_caCertLabel); + caCertLayout->addWidget(m_caCertPathEdit); + caCertLayout->addWidget(m_caCertButton); + m_caCertLabel->setFixedWidth(LEFT_LABEL_WIDTH); + + QHBoxLayout *userLayout = new QHBoxLayout(m_userCertFrame); + userLayout->setContentsMargins(NO_LAYOUT_MARGINS); + userLayout->setSpacing(HLAYOUT_SPACING); + userLayout->addWidget(m_userCertLabel); + userLayout->addWidget(m_userCertPathEdit); + userLayout->addWidget(m_userCertButton); + m_userCertLabel->setFixedWidth(LEFT_LABEL_WIDTH); + + QGridLayout *staticKeyLayout = new QGridLayout(m_staticKeysFrame); + staticKeyLayout->setContentsMargins(NO_LAYOUT_MARGINS); + staticKeyLayout->setHorizontalSpacing(HLAYOUT_SPACING); + staticKeyLayout->setVerticalSpacing(VLAYOUT_SPACING); + staticKeyLayout->addWidget(m_staticKeyLabel, 0, 0); + staticKeyLayout->addWidget(m_staticKeyPathEdit, 0, 1); + staticKeyLayout->addWidget(m_staticKeyButton, 0, 2); + staticKeyLayout->addWidget(m_keyDirectionLabel, 1, 0); + staticKeyLayout->addWidget(m_keyDirectionCombox, 1, 1, 1, 2); + staticKeyLayout->addWidget(m_noticesLabel, 2, 0, 2, 3); + staticKeyLayout->addWidget(m_localIpLabel, 4, 0); + staticKeyLayout->addWidget(m_localIpEdit, 4, 1, 1, 2); + staticKeyLayout->addWidget(m_remoteIpLabel, 5, 0); + staticKeyLayout->addWidget(m_remoteIpEdit, 5, 1, 1, 2); + m_staticKeyLabel->setFixedWidth(LEFT_LABEL_WIDTH); + m_keyDirectionLabel->setFixedWidth(LEFT_LABEL_WIDTH); + m_localIpLabel->setFixedWidth(LEFT_LABEL_WIDTH); + m_remoteIpLabel->setFixedWidth(LEFT_LABEL_WIDTH); + + QHBoxLayout *pinLayout = new QHBoxLayout(m_pinFrame); + pinLayout->setContentsMargins(NO_LAYOUT_MARGINS); + pinLayout->setSpacing(HLAYOUT_SPACING); + pinLayout->addWidget(m_pinLabel); + pinLayout->addWidget(m_pinEdit); + m_pinLabel->setFixedWidth(LEFT_LABEL_WIDTH); + + QGridLayout *privateKeysLayout = new QGridLayout(m_PrivateKeysFrame); + privateKeysLayout->setContentsMargins(NO_LAYOUT_MARGINS); + privateKeysLayout->setHorizontalSpacing(HLAYOUT_SPACING); + privateKeysLayout->setVerticalSpacing(VLAYOUT_SPACING); + privateKeysLayout->addWidget(m_privateKeyLabel, 0, 0); + privateKeysLayout->addWidget(m_privateKeyPwdLabel, 1, 0); + privateKeysLayout->addWidget(m_pwdOptionLabel, 2, 0); + privateKeysLayout->addWidget(m_privateKeyEdit, 0, 1); + privateKeysLayout->addWidget(m_privateKeyButton, 0, 2); + privateKeysLayout->addWidget(m_privateKeyPwdEdit, 1, 1, 1, 2); + privateKeysLayout->addWidget(m_pwdOptionCombox, 2, 1, 1, 2); + m_privateKeyLabel->setFixedWidth(LEFT_LABEL_WIDTH); + m_privateKeyPwdLabel->setFixedWidth(LEFT_LABEL_WIDTH); + m_pwdOptionLabel->setFixedWidth(LEFT_LABEL_WIDTH); + + QGridLayout *usersLayout = new QGridLayout(m_usersFrame); + usersLayout->setContentsMargins(NO_LAYOUT_MARGINS); + usersLayout->setHorizontalSpacing(HLAYOUT_SPACING); + usersLayout->setVerticalSpacing(VLAYOUT_SPACING); + usersLayout->addWidget(m_usernameLabel, 0, 0); + usersLayout->addWidget(m_usernameEdit, 0, 1); + usersLayout->addWidget(m_userPwdLabel, 1, 0); + usersLayout->addWidget(m_userPwdEdit, 1, 1); + m_usernameLabel->setFixedWidth(LEFT_LABEL_WIDTH); + m_userPwdLabel->setFixedWidth(LEFT_LABEL_WIDTH); + + QHBoxLayout *userPwdOLayout = new QHBoxLayout(m_userPwdOpFrame); + userPwdOLayout->setContentsMargins(NO_LAYOUT_MARGINS); + userPwdOLayout->setSpacing(HLAYOUT_SPACING); + userPwdOLayout->addWidget(m_userPwdOptionLabel); + userPwdOLayout->addWidget(m_userPwdOptionCombox); + m_userPwdOptionLabel->setFixedWidth(LEFT_LABEL_WIDTH); + + QHBoxLayout *ntLayout = new QHBoxLayout(m_ntFrame); + ntLayout->setContentsMargins(NO_LAYOUT_MARGINS); + ntLayout->setSpacing(HLAYOUT_SPACING); + ntLayout->addWidget(m_ntDomainLabel); + ntLayout->addWidget(m_ntDomainEdit); + m_ntDomainLabel->setFixedWidth(LEFT_LABEL_WIDTH); + + /**********控件显示**********/ + m_vpnTypeLabel->setText(tr("Type")); //类型 + m_vpnNameLabel->setText(tr("Name")); //名称 + m_staticKeyLabel->setText(tr("Static Key")); //静态密钥 + m_localIpLabel->setText(tr("Local IP")); //本地IP地址 + m_remoteIpLabel->setText(tr("Remote IP")); //远程IP地址 + m_pinLabel->setText(tr("PIN Code")); //PIN码 + m_userPwdLabel->setText(tr("Password")); //密码 + m_ntDomainLabel->setText(tr("NT Domain")); //NT域 + + m_serverAddressLabel->setLabelText(tr("Server Address")); //服务器地址 + m_authModeLabel->setLabelText(tr("Authentication Mode")); //认证方式 + m_caCertLabel->setLabelText(tr("CA Certificate")); //CA证书 + m_userCertLabel->setLabelText(tr("User Certificate")); //用户证书 + m_keyDirectionLabel->setLabelText(tr("Key Direction")); //密钥方向 + m_privateKeyLabel->setLabelText(tr("Private Key")); //私钥 + m_privateKeyPwdLabel->setLabelText(tr("Private Key Password")); //私有密钥密码 + m_pwdOptionLabel->setLabelText(tr("Password Options")); //密码选项 + m_usernameLabel->setLabelText(tr("Username")); //用户名 + m_userPwdOptionLabel->setLabelText(tr("Password Options")); //密码选项 + + m_noticesLabel->setWordWrap(true); + m_noticesLabel->setText(tr("Notice:\nIf key direction is used, it must be opposite to the VPN side used. " + "If '1' is used, the connection must use '0'. " + "If you are not sure which value to use, please contact your system administrator.")); + QPalette pal; + pal.setColor(QPalette::WindowText, qApp->palette().color(QPalette::Mid)); + m_noticesLabel->setPalette(pal); + + m_caCertButton->setText(tr("Choose")); //选择 + m_userCertButton->setText(tr("Choose")); + m_staticKeyButton->setText(tr("Choose")); + m_privateKeyButton->setText(tr("Choose")); + + m_vpnTypeComboBox->addItem("L2TP", L2TP); + m_vpnTypeComboBox->addItem("open VPN", OPEN_VPN); + m_vpnTypeComboBox->addItem("PPTP", PPTP); + m_vpnTypeComboBox->addItem("strong-swan", STRONG_SWAN); + + m_keyDirectionCombox->addItem(tr("None"), KEY_DIRECTION_NONE); + m_keyDirectionCombox->addItem("0", KEY_DIRECTION_ZERO); + m_keyDirectionCombox->addItem("1", KEY_DIRECTION_ONE); + + m_pwdOptionCombox->addItem(tr("Save password only for this user"), KYPASSWD_FORTHISUSER); //仅对当前用户保存密码 + m_pwdOptionCombox->addItem(tr("Save password for all users"), KYPASSWD_FORALLUSER); //为所有用户保存密码 + m_pwdOptionCombox->addItem(tr("Ask password every time"), KYPASSWD_ASKEVERYTIME); //每次都询问 + m_pwdOptionCombox->addItem(tr("Don't require a password"), KYPASSWD_ISNOTREQUIRED);//不需要密码 + m_pwdOptionCombox->setCurrentIndex(PWD_OPTION_ASKEVERYTIME_INDEX); + + m_userPwdOptionCombox->addItem(tr("Save password only for this user"), KYPASSWD_FORTHISUSER); + m_userPwdOptionCombox->addItem(tr("Save password for all users"), KYPASSWD_FORALLUSER); + m_userPwdOptionCombox->addItem(tr("Ask password every time"), KYPASSWD_ASKEVERYTIME); + m_userPwdOptionCombox->addItem(tr("Don't require a password"), KYPASSWD_ISNOTREQUIRED); + m_userPwdOptionCombox->setCurrentIndex(PWD_OPTION_ASKEVERYTIME_INDEX); + + m_vpnNameEdit->setPlaceholderText(tr("Required")); //必填 + m_serverAddressEdit->setPlaceholderText(tr("Required")); + m_privateKeyPwdEdit->setClearButtonEnabled(false); + m_userPwdEdit->setClearButtonEnabled(false); + + //控件输入格式限制 + QRegExp rxNumber("^[0-9]+$"); + m_pinEdit->setValidator(new QRegExpValidator(rxNumber, this)); + m_pinEdit->setMaxLength(PIN_MAX_LENGTH); + // IP的正则格式限制 + QRegExp rxIp("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"); + QRegExpValidator *ipExpVal = new QRegExpValidator(rxIp, this); + m_serverAddressEdit->setValidator(ipExpVal); + m_localIpEdit->setValidator(ipExpVal); + m_remoteIpEdit->setValidator(ipExpVal); +} + +void VpnConfigPage::initConnect() +{ + connect(m_vpnTypeComboBox, QOverload::of(&QComboBox::currentIndexChanged), + this, &VpnConfigPage::onVpnTypeComboxIndexChanged); + connect(m_authModeComboBox, QOverload::of(&QComboBox::currentIndexChanged), + this, &VpnConfigPage::onAuthModeComboxIndexChanged); + + connect(m_vpnNameEdit, &QLineEdit::textChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); + connect(m_serverAddressEdit, &QLineEdit::textChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); + connect(m_caCertPathEdit, &QLineEdit::textChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); + connect(m_userCertPathEdit, &QLineEdit::textChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); + connect(m_privateKeyEdit, &QLineEdit::textChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); + connect(m_staticKeyPathEdit, &QLineEdit::textChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); + connect(m_localIpEdit, &QLineEdit::textChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); + connect(m_remoteIpEdit, &QLineEdit::textChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); + connect(m_pinEdit, &QLineEdit::textChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); + connect(m_usernameEdit, &QLineEdit::textChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); + connect(m_ntDomainEdit, &QLineEdit::textChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); + + connect(m_vpnTypeComboBox, &QComboBox::currentTextChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); + connect(m_authModeComboBox, &QComboBox::currentTextChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); + connect(m_pwdOptionCombox, &QComboBox::currentTextChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); + connect(m_userPwdOptionCombox, &QComboBox::currentTextChanged, this, &VpnConfigPage::setEnableOfConfirmBtn); + + connect(m_caCertButton, &QPushButton::clicked, this, &VpnConfigPage::onCaCertButtonClicked); + connect(m_userCertButton, &QPushButton::clicked, this, &VpnConfigPage::onUserCertButtonClicked); + connect(m_staticKeyButton, &QPushButton::clicked, this, &VpnConfigPage::onStaticKeyButtonClicked); + connect(m_privateKeyButton, &QPushButton::clicked, this, &VpnConfigPage::onPrivateKeyButtonClicked); +} + +void VpnConfigPage::showL2tpPwd() +{ + m_vpnCommunalFrame->setHidden(false); + m_authModeFrame->setHidden(false); + m_usersFrame->setHidden(false); + m_userPwdOpFrame->setHidden(false); + m_ntFrame->setHidden(false); + + m_PrivateKeysFrame->setHidden(true); + m_caCertFrame->setHidden(true); + m_userCertFrame->setHidden(true); + m_staticKeysFrame->setHidden(true); + m_pinFrame->setHidden(true); +} + +void VpnConfigPage::showPptpPwd() +{ + m_vpnCommunalFrame->setHidden(false); + m_usersFrame->setHidden(false); + m_userPwdOpFrame->setHidden(false); + m_ntFrame->setHidden(false); + + m_authModeFrame->setHidden(true); + m_PrivateKeysFrame->setHidden(true); + m_caCertFrame->setHidden(true); + m_userCertFrame->setHidden(true); + m_staticKeysFrame->setHidden(true); + m_pinFrame->setHidden(true); +} + +void VpnConfigPage::showOpenVpnTls() +{ + m_vpnCommunalFrame->setHidden(false); + m_authModeFrame->setHidden(false); + m_PrivateKeysFrame->setHidden(false); + m_caCertFrame->setHidden(false); + m_userCertFrame->setHidden(false); + + m_staticKeysFrame->setHidden(true); + m_pinFrame->setHidden(true); + m_usersFrame->setHidden(true); + m_userPwdOpFrame->setHidden(true); + m_ntFrame->setHidden(true); +} + +void VpnConfigPage::showOpenVpnPwd() +{ + m_vpnCommunalFrame->setHidden(false); + m_authModeFrame->setHidden(false); + m_caCertFrame->setHidden(false); + m_usersFrame->setHidden(false); + m_userPwdOpFrame->setHidden(false); + + m_userCertFrame->setHidden(true); + m_PrivateKeysFrame->setHidden(true); + m_staticKeysFrame->setHidden(true); + m_pinFrame->setHidden(true); + m_ntFrame->setHidden(true); +} + +void VpnConfigPage::showOpenVpnPwdTls() +{ + m_vpnCommunalFrame->setHidden(false); + m_authModeFrame->setHidden(false); + m_caCertFrame->setHidden(false); + m_userCertFrame->setHidden(false); + m_PrivateKeysFrame->setHidden(false); + m_usersFrame->setHidden(false); + m_userPwdOpFrame->setHidden(false); + + m_staticKeysFrame->setHidden(true); + m_pinFrame->setHidden(true); + m_ntFrame->setHidden(true); +} + +void VpnConfigPage::showOpenVpnStaticKey() +{ + m_vpnCommunalFrame->setHidden(false); + m_authModeFrame->setHidden(false); + m_staticKeysFrame->setHidden(false); + + m_caCertFrame->setHidden(true); + m_userCertFrame->setHidden(true); + m_PrivateKeysFrame->setHidden(true); + m_usersFrame->setHidden(true); + m_userPwdOpFrame->setHidden(true); + m_pinFrame->setHidden(true); + m_ntFrame->setHidden(true); +} + +void VpnConfigPage::showSswanCertPrivteKey() +{ + m_vpnCommunalFrame->setHidden(false); + m_authModeFrame->setHidden(false); + m_userCertFrame->setHidden(false); + m_PrivateKeysFrame->setHidden(false); + + m_caCertFrame->setHidden(true); + m_usersFrame->setHidden(true); + m_userPwdOpFrame->setHidden(true); + m_staticKeysFrame->setHidden(true); + m_pinFrame->setHidden(true); + m_ntFrame->setHidden(true); +} + +void VpnConfigPage::showSswanCertSsh() +{ + m_vpnCommunalFrame->setHidden(false); + m_authModeFrame->setHidden(false); + m_userCertFrame->setHidden(false); + + m_caCertFrame->setHidden(true); + m_PrivateKeysFrame->setHidden(true); + m_usersFrame->setHidden(true); + m_userPwdOpFrame->setHidden(true); + m_staticKeysFrame->setHidden(true); + m_pinFrame->setHidden(true); + m_ntFrame->setHidden(true); +} + +void VpnConfigPage::showSswanSmartCard() +{ + m_vpnCommunalFrame->setHidden(false); + m_authModeFrame->setHidden(false); + m_pinFrame->setHidden(false); + + m_caCertFrame->setHidden(true); + m_userCertFrame->setHidden(true); + m_PrivateKeysFrame->setHidden(true); + m_usersFrame->setHidden(true); + m_userPwdOpFrame->setHidden(true); + m_staticKeysFrame->setHidden(true); + m_ntFrame->setHidden(true); +} + +void VpnConfigPage::showSswanEap() +{ + m_vpnCommunalFrame->setHidden(false); + m_authModeFrame->setHidden(false); + m_usersFrame->setHidden(false); + + m_caCertFrame->setHidden(true); + m_userCertFrame->setHidden(true); + m_PrivateKeysFrame->setHidden(true); + m_userPwdOpFrame->setHidden(true); + m_staticKeysFrame->setHidden(true); + m_pinFrame->setHidden(true); + m_ntFrame->setHidden(true); +} + +bool VpnConfigPage::getTextEditState(QString text) +{ + if (text.isEmpty()) { + return true; + } + QRegExp rx("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"); + + bool match = false; + match = rx.exactMatch(text); + + return match; +} + +bool VpnConfigPage::checkConfirmBtnIsEnabled() +{ + if (m_vpnNameEdit->text().isEmpty()) { + qDebug() << LOG_FLAG << "VPN name empty or invalid"; + return false; + } + + if (m_serverAddressEdit->text().isEmpty() || !getTextEditState(m_serverAddressEdit->text())) { + qDebug() << LOG_FLAG << "VPN server address empty or invalid"; + return false; + } + + int currentAuthMethod = m_authModeComboBox->currentData().toInt(); + switch (currentAuthMethod) { + case KYAUTH_PASSWD: + case KYAUTH_EAP: + if (m_usernameEdit->text().isEmpty() && !m_userPwdEdit->text().isEmpty()) { + return false; + } + if (m_vpnTypeComboBox->currentData().toInt() == OPEN_VPN && m_caCertPathEdit->text().isEmpty()) { + return false; + } + break; + + case KYAUTH_CERTIFICATE: + if (m_caCertPathEdit->text().isEmpty() || m_userCertPathEdit->text().isEmpty() + || m_privateKeyEdit->text().isEmpty()) { + return false; + } + break; + + case KYAUTH_CERTIFICATEANDPASSWD: + if (m_caCertPathEdit->text().isEmpty() || m_userCertPathEdit->text().isEmpty() + || m_privateKeyEdit->text().isEmpty()) { + return false; + } + if (m_usernameEdit->text().isEmpty() && !m_userPwdEdit->text().isEmpty()) { + return false; + } + break; + + case KYAUTH_STATICPASSWD: + if (m_staticKeyPathEdit->text().isEmpty()) { + return false; + } + break; + + default: + break; + } + + return true; +} + +void VpnConfigPage::setPwdAuthInfo(const QString &username, const QString &userPwd, const KyPasswdPolicy &userPwdPolicy) +{ + m_usernameEdit->setText(username); + m_userPwdEdit->setText(userPwd); + if (userPwdPolicy == KYPASSWD_ISNOTREQUIRED) { + m_userPwdOptionCombox->setCurrentIndex(PWD_OPTION_NOTREQUIRED_INDEX); + } else { + m_userPwdOptionCombox->setCurrentIndex(userPwdPolicy); + } +} + +void VpnConfigPage::setCaCertAuthInfo(const QString &caCertificate) +{ + m_caCertPathEdit->setText(caCertificate); +} + +void VpnConfigPage::setKeyAuthInfo(const QString &userCert, const QString &privateKey, + const QString &privateKeyPwd, const KyPasswdPolicy &privatePwdPolicy) +{ + m_userCertPathEdit->setText(userCert); + m_privateKeyEdit->setText(privateKey); + m_privateKeyPwdEdit->setText(privateKeyPwd); + if (privatePwdPolicy == KYPASSWD_ISNOTREQUIRED) { + m_userPwdOptionCombox->setCurrentIndex(PWD_OPTION_NOTREQUIRED_INDEX); + } else { + m_userPwdOptionCombox->setCurrentIndex(privatePwdPolicy); + } +} + +void VpnConfigPage::setStaticKeyAuthInfo(const QString &staticKey, const QString &vpnKeyDirection, + const QString &localIp, const QString &remoteIp) +{ + m_staticKeyPathEdit->setText(staticKey); + m_localIpEdit->setText(localIp); + m_remoteIpEdit->setText(remoteIp); + if (vpnKeyDirection == KEY_DIRECTION_ZERO) { + m_keyDirectionCombox->setCurrentIndex(KEY_DIRECTION_ZERO_INDEX); + } else if (vpnKeyDirection == KEY_DIRECTION_ONE) { + m_keyDirectionCombox->setCurrentIndex(KEY_DIRECTION_ONE_INDEX); + } else { + m_keyDirectionCombox->setCurrentIndex(KEY_DIRECTION_NONE_INDEX); + } +} + +void VpnConfigPage::setAgentAuthInfo(const QString &userCert) +{ + m_userCertPathEdit->setText(userCert); +} + +void VpnConfigPage::setSmartCardAuthInfo(const QString &pin) +{ + m_pinEdit->setText(pin); +} + +void VpnConfigPage::setEapAuthInfo(const QString &username, const QString &userPwd) +{ + m_usernameEdit->setText(username); + m_userPwdEdit->setText(userPwd); +} + +void VpnConfigPage::setNtDomain(const QString &ntDomain) +{ + m_ntDomainEdit->setText(ntDomain); +} + +void VpnConfigPage::setL2tpConfigInfo(const KyVpnConfig &vpnInfo) +{ + if (vpnInfo.m_authMethod == KyAuthMethod::KYAUTH_PASSWD) { + m_authModeComboBox->setCurrentIndex(KYAUTH_PASSWD); + setPwdAuthInfo(vpnInfo.m_userName, vpnInfo.m_userPasswd, vpnInfo.m_passwdPolicy); + setNtDomain(vpnInfo.m_ntDomain); + } +} + +void VpnConfigPage::setPptpConfigInfo(const KyVpnConfig &vpnInfo) +{ + m_authModeComboBox->clear(); + setPwdAuthInfo(vpnInfo.m_userName, vpnInfo.m_userPasswd, vpnInfo.m_passwdPolicy); + setNtDomain(vpnInfo.m_ntDomain); +} + +void VpnConfigPage::setOpenVpnConfigInfo(const KyVpnConfig &vpnInfo) +{ + if (vpnInfo.m_authMethod == KyAuthMethod::KYAUTH_PASSWD) { + m_authModeComboBox->setCurrentIndex(PASSWD_INDEX); + setCaCertAuthInfo(vpnInfo.m_caCertificate); + setPwdAuthInfo(vpnInfo.m_userName, vpnInfo.m_userPasswd, vpnInfo.m_passwdPolicy); + + } else if (vpnInfo.m_authMethod == KyAuthMethod::KYAUTH_CERTIFICATE) { + m_authModeComboBox->setCurrentIndex(CERTIFICATE_INDEX); + setCaCertAuthInfo(vpnInfo.m_caCertificate); + setKeyAuthInfo(vpnInfo.m_userCertificate, vpnInfo.m_userKey, + vpnInfo.m_privatePasswd, vpnInfo.m_privatePasswdPolicy); + + } else if (vpnInfo.m_authMethod == KyAuthMethod::KYAUTH_STATICPASSWD) { + m_authModeComboBox->setCurrentIndex(STATICPASSWD_INDEX); + setStaticKeyAuthInfo(vpnInfo.m_staticKey, vpnInfo.m_vpnKeyDir, + vpnInfo.m_localAddress, vpnInfo.m_remoteAddress); + + } else if (vpnInfo.m_authMethod == KyAuthMethod::KYAUTH_CERTIFICATEANDPASSWD) { + m_authModeComboBox->setCurrentIndex(CERTIFICATEANDPASSWD_INDEX); + setCaCertAuthInfo(vpnInfo.m_caCertificate); + setKeyAuthInfo(vpnInfo.m_userCertificate, vpnInfo.m_userKey, + vpnInfo.m_privatePasswd, vpnInfo.m_privatePasswdPolicy); + setPwdAuthInfo(vpnInfo.m_userName, vpnInfo.m_userPasswd, vpnInfo.m_passwdPolicy); + } +} + +void VpnConfigPage::setSSwanVpnConfigInfo(const KyVpnConfig &vpnInfo) +{ + if (vpnInfo.m_authMethod == KyAuthMethod::KYAUTH_KEY) { + m_authModeComboBox->setCurrentIndex(KEY_INDEX); + setCaCertAuthInfo(vpnInfo.m_caCertificate); + setKeyAuthInfo(vpnInfo.m_userCertificate, vpnInfo.m_userKey, + vpnInfo.m_privatePasswd, vpnInfo.m_privatePasswdPolicy); + + } else if (vpnInfo.m_authMethod == KyAuthMethod::KYAUTH_AGENT) { + m_authModeComboBox->setCurrentIndex(AGENT_INDEX); + setAgentAuthInfo(vpnInfo.m_userCertificate); + + } else if (vpnInfo.m_authMethod == KyAuthMethod::KYAUTH_SMARTCARD) { + m_authModeComboBox->setCurrentIndex(SMARTCARD_INDEX); + setSmartCardAuthInfo(vpnInfo.m_pinId); + + } else if (vpnInfo.m_authMethod == KyAuthMethod::KYAUTH_EAP) { + m_authModeComboBox->setCurrentIndex(EAP_INDEX); + setEapAuthInfo(vpnInfo.m_userName, vpnInfo.m_userPasswd); + } +} + +void VpnConfigPage::updateL2tpConfigInfo(KyVpnConfig &vpnInfo) +{ + vpnInfo.m_authMethod = (KyAuthMethod)m_authModeComboBox->currentData().toInt(); + vpnInfo.m_ntDomain = m_ntDomainEdit->text(); + vpnInfo.m_userName = m_usernameEdit->text(); + vpnInfo.m_userPasswd = m_userPwdEdit->text(); + vpnInfo.m_passwdPolicy = (KyPasswdPolicy)m_userPwdOptionCombox->currentData().toInt(); +} + +void VpnConfigPage::updatePptpConfigInfo(KyVpnConfig &vpnInfo) +{ + vpnInfo.m_ntDomain = m_ntDomainEdit->text(); + vpnInfo.m_userName = m_usernameEdit->text(); + vpnInfo.m_userPasswd = m_userPwdEdit->text(); + vpnInfo.m_passwdPolicy = (KyPasswdPolicy)m_userPwdOptionCombox->currentData().toInt(); +} + +void VpnConfigPage::updateOpenVpnConfigInfo(KyVpnConfig &vpnInfo) +{ + vpnInfo.m_authMethod = (KyAuthMethod)m_authModeComboBox->currentData().toInt(); + if (vpnInfo.m_authMethod == KYAUTH_CERTIFICATE || vpnInfo.m_authMethod == KYAUTH_CERTIFICATEANDPASSWD) { + vpnInfo.m_caCertificate = m_caCertPathEdit->text(); + vpnInfo.m_userCertificate = m_userCertPathEdit->text(); + vpnInfo.m_userKey = m_privateKeyEdit->text(); + vpnInfo.m_privatePasswd = m_privateKeyPwdEdit->text(); + vpnInfo.m_privatePasswdPolicy = (KyPasswdPolicy)m_pwdOptionCombox->currentData().toInt(); + } + + if (vpnInfo.m_authMethod == KYAUTH_CERTIFICATEANDPASSWD || vpnInfo.m_authMethod == KYAUTH_PASSWD) { + vpnInfo.m_userName = m_usernameEdit->text(); + vpnInfo.m_userPasswd = m_userPwdEdit->text(); + vpnInfo.m_passwdPolicy = (KyPasswdPolicy)m_userPwdOptionCombox->currentData().toInt(); + vpnInfo.m_caCertificate = m_caCertPathEdit->text(); + } + + if (vpnInfo.m_authMethod == KYAUTH_STATICPASSWD) { + vpnInfo.m_staticKey = m_staticKeyPathEdit->text(); + vpnInfo.m_vpnKeyDir = m_keyDirectionCombox->currentData().toString(); + vpnInfo.m_localAddress = m_localIpEdit->text(); + vpnInfo.m_remoteAddress = m_remoteIpEdit->text(); + } +} + +void VpnConfigPage::updateSSwanVpnConfigInfo(KyVpnConfig &vpnInfo) +{ + vpnInfo.m_authMethod = (KyAuthMethod)m_authModeComboBox->currentData().toInt(); + if (vpnInfo.m_authMethod == KYAUTH_KEY) { + vpnInfo.m_caCertificate = m_caCertPathEdit->text(); + vpnInfo.m_userCertificate = m_userCertPathEdit->text(); + vpnInfo.m_userKey = m_privateKeyEdit->text(); + vpnInfo.m_privatePasswd = m_privateKeyPwdEdit->text(); + vpnInfo.m_privatePasswdPolicy = (KyPasswdPolicy)m_pwdOptionCombox->currentData().toInt(); + + } else if (vpnInfo.m_authMethod == KYAUTH_AGENT) { + vpnInfo.m_userCertificate = m_userCertPathEdit->text(); + + } else if (vpnInfo.m_authMethod == KYAUTH_SMARTCARD) { + vpnInfo.m_pinId = m_pinEdit->text(); + + } else if (vpnInfo.m_authMethod == KYAUTH_EAP) { + vpnInfo.m_userName = m_usernameEdit->text(); + vpnInfo.m_userPasswd = m_userPwdEdit->text(); + } +} + +void VpnConfigPage::onVpnTypeComboxIndexChanged() +{ + switch (m_vpnTypeComboBox->currentData().toInt()) { + case L2TP: + m_authModeComboBox->clear(); + m_authModeComboBox->addItem(tr("Password"), KYAUTH_PASSWD); + onAuthModeComboxIndexChanged(); + break; + case OPEN_VPN: + m_authModeComboBox->clear(); + m_authModeComboBox->addItem(tr("Certificate(TLS)"), KYAUTH_CERTIFICATE); + m_authModeComboBox->addItem(tr("Static key"), KYAUTH_STATICPASSWD); + m_authModeComboBox->addItem(tr("Password"), KYAUTH_PASSWD); + m_authModeComboBox->addItem(tr("Password and certificate(TLS)"), KYAUTH_CERTIFICATEANDPASSWD); + onAuthModeComboxIndexChanged(); + break; + case PPTP: + m_authModeComboBox->clear(); + showPptpPwd(); + break; + case STRONG_SWAN: + m_authModeComboBox->clear(); + m_authModeComboBox->addItem(tr("Certificate/Private key"), KYAUTH_KEY); + m_authModeComboBox->addItem(tr("Certificate/ssh-agent"), KYAUTH_AGENT); + m_authModeComboBox->addItem(tr("Smart card"), KYAUTH_SMARTCARD); + m_authModeComboBox->addItem("EAP", KYAUTH_EAP); + onAuthModeComboxIndexChanged(); + break; + default: + break; + } + Q_EMIT vpnTypeChanged(VpnType(m_vpnTypeComboBox->currentData().toInt())); +} + +void VpnConfigPage::onAuthModeComboxIndexChanged() +{ + switch (m_authModeComboBox->currentData().toInt()) { + case KYAUTH_PASSWD: + if (m_vpnTypeComboBox->currentData().toInt() == L2TP) { + showL2tpPwd(); + } else if (m_vpnTypeComboBox->currentData().toInt() == OPEN_VPN) { + showOpenVpnPwd(); + } + break; + case KYAUTH_KEY: + showSswanCertPrivteKey(); + break; + case KYAUTH_AGENT: + showSswanCertSsh(); + break; + case KYAUTH_SMARTCARD: + showSswanSmartCard(); + break; + case KYAUTH_EAP: + showSswanEap(); + break; + case KYAUTH_CERTIFICATE: + showOpenVpnTls(); + break; + case KYAUTH_CERTIFICATEANDPASSWD: + showOpenVpnPwdTls(); + break; + case KYAUTH_STATICPASSWD: + showOpenVpnStaticKey(); + break; + default: + qDebug() << LOG_FLAG << "Unknow VPN auth mothod"; + break; + } +} + +void VpnConfigPage::setEnableOfConfirmBtn() +{ + Q_EMIT setConfigPageState(checkConfirmBtnIsEnabled()); +} + +void VpnConfigPage::onPrivateKeyButtonClicked() +{ + QString fileName = QFileDialog::getOpenFileName(this, + tr("Choose a private key"), + "recent:///", + tr("Key Files (*.key *.pem *.der *.p12 *.pfx)")); + if (!fileName.isNull()) { + m_privateKeyEdit->blockSignals(true); + m_privateKeyEdit->setText(fileName); + m_privateKeyEdit->blockSignals(false); + } +} + +void VpnConfigPage::onCaCertButtonClicked() +{ + QString fileName = QFileDialog::getOpenFileName(this, + tr("Choose a CA certificate"), + "recent:///", + tr("CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx)")); + if (!fileName.isNull()) { + m_caCertPathEdit->blockSignals(true); + m_caCertPathEdit->setText(fileName); + m_caCertPathEdit->blockSignals(false); + } +} + +void VpnConfigPage::onUserCertButtonClicked() +{ + QString fileName = QFileDialog::getOpenFileName(this, + tr("Choose a User certificate"), + "recent:///", + tr("CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx)")); + if (!fileName.isNull()) { + m_userCertPathEdit->blockSignals(true); + m_userCertPathEdit->setText(fileName); + m_userCertPathEdit->blockSignals(false); + } +} + +void VpnConfigPage::onStaticKeyButtonClicked() +{ + QString fileName = QFileDialog::getOpenFileName(this, + tr("Choose a Static key"), + "recent:///", + tr("Key Files (*.key *.pem *.der *.p12 *.pfx)")); + if (!fileName.isNull()) { + m_staticKeyPathEdit->blockSignals(true); + m_staticKeyPathEdit->setText(fileName); + m_staticKeyPathEdit->blockSignals(false); + } +} + + +bool VpnConfigPage::checkL2tpIsChanged(const KyVpnConfig &vpnInfo) +{ + bool isChanged = false; + if (vpnInfo.m_ntDomain != m_ntDomainEdit->text() + || vpnInfo.m_userName != m_usernameEdit->text() + || vpnInfo.m_userPasswd != m_userPwdEdit->text() + || vpnInfo.m_passwdPolicy != m_userPwdOptionCombox->currentData().toInt()) { + + isChanged = true; + } + return isChanged; +} + +bool VpnConfigPage::checkPptpIsChanged(const KyVpnConfig &vpnInfo) +{ + bool isChanged = false; + if (vpnInfo.m_ntDomain != m_ntDomainEdit->text() + || vpnInfo.m_userName != m_usernameEdit->text() + || vpnInfo.m_userPasswd != m_userPwdEdit->text() + || vpnInfo.m_passwdPolicy != m_userPwdOptionCombox->currentData().toInt()) { + + isChanged = true; + } + return isChanged; +} + +bool VpnConfigPage::checkOpenVpnIsChanged(const KyVpnConfig &vpnInfo) +{ + bool isChanged = false; + int currentAuthMethod = m_authModeComboBox->currentData().toInt(); + if (vpnInfo.m_authMethod != currentAuthMethod) { + isChanged = true; + } + + if (currentAuthMethod == KYAUTH_PASSWD || currentAuthMethod == KYAUTH_CERTIFICATEANDPASSWD) { + if (vpnInfo.m_userName != m_usernameEdit->text() + || vpnInfo.m_userPasswd != m_userPwdEdit->text() + || vpnInfo.m_passwdPolicy != m_userPwdOptionCombox->currentData().toInt() + || vpnInfo.m_caCertificate != m_caCertPathEdit->text()) { + + isChanged = true; + } + } + + if (currentAuthMethod == KYAUTH_CERTIFICATEANDPASSWD || currentAuthMethod == KYAUTH_CERTIFICATE) { + if (vpnInfo.m_caCertificate != m_caCertPathEdit->text() + || vpnInfo.m_userCertificate != m_userCertPathEdit->text() + || vpnInfo.m_userKey != m_privateKeyEdit->text() + || vpnInfo.m_privatePasswd != m_privateKeyPwdEdit->text() + || vpnInfo.m_privatePasswdPolicy != m_pwdOptionCombox->currentData().toInt()) { + + isChanged = true; + } + + } + if (currentAuthMethod == KYAUTH_STATICPASSWD) { + if (vpnInfo.m_staticKey != m_staticKeyPathEdit->text() + || vpnInfo.m_vpnKeyDir != m_keyDirectionCombox->currentData().toString() + || vpnInfo.m_localAddress != m_localIpEdit->text() + || vpnInfo.m_remoteAddress != m_localIpEdit->text()) { + + isChanged = true; + } + } + + return isChanged; +} + +bool VpnConfigPage::checkStrongSwanIsChanged(const KyVpnConfig &vpnInfo) +{ + bool isChanged = false; + int currentAuthMethod = m_authModeComboBox->currentData().toInt(); + + if (vpnInfo.m_authMethod != currentAuthMethod) { + isChanged = true; + } + + if (currentAuthMethod == KYAUTH_KEY) { + if (vpnInfo.m_caCertificate != m_caCertPathEdit->text() + || vpnInfo.m_userCertificate != m_userCertPathEdit->text() + || vpnInfo.m_userKey != m_privateKeyEdit->text() + || vpnInfo.m_privatePasswd != m_privateKeyPwdEdit->text() + || vpnInfo.m_privatePasswdPolicy != m_pwdOptionCombox->currentData().toInt()) { + + isChanged = true; + + } + }else if (currentAuthMethod == KYAUTH_AGENT) { + if (vpnInfo.m_userCertificate != m_userCertPathEdit->text()) { + isChanged = true; + } + } else if (currentAuthMethod == KYAUTH_SMARTCARD) { + if (vpnInfo.m_pinId != m_pinEdit->text()) { + isChanged = true; + } + } else if (currentAuthMethod == KYAUTH_EAP) { + if (vpnInfo.m_userName != m_usernameEdit->text() || vpnInfo.m_userPasswd != m_userPwdEdit->text()) { + isChanged = true; + } + } + return isChanged; +} diff --git a/src-vpn/frontend/vpndetails/vpnconfigpage.h b/src-vpn/frontend/vpndetails/vpnconfigpage.h new file mode 100644 index 00000000..e5d60ba5 --- /dev/null +++ b/src-vpn/frontend/vpndetails/vpnconfigpage.h @@ -0,0 +1,198 @@ +#ifndef VPNCONFIGPAGE_H +#define VPNCONFIGPAGE_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "kylable.h" +#include "kwidget.h" +#include "kpasswordedit.h" +#include "kyvpnconnectoperation.h" + +using namespace kdk; + +#define KEY_DIRECTION_NONE_INDEX 0 +#define KEY_DIRECTION_ZERO_INDEX 1 +#define KEY_DIRECTION_ONE_INDEX 2 + +#define KEY_DIRECTION_NONE "None" +#define KEY_DIRECTION_ZERO "0" +#define KEY_DIRECTION_ONE "1" + +enum VpnType { + UNKNOW = -1, + L2TP = 0, + OPEN_VPN, + PPTP, + STRONG_SWAN +}; + +enum OpenVpnAuthMethodIndex { + CERTIFICATE_INDEX = 0, + STATICPASSWD_INDEX, + PASSWD_INDEX, + CERTIFICATEANDPASSWD_INDEX, +}; +enum StrongSwanAuthMethodIndex { + KEY_INDEX = 0, + AGENT_INDEX, + SMARTCARD_INDEX, + EAP_INDEX, +}; + +class VpnConfigPage : public QFrame +{ + Q_OBJECT +public: + explicit VpnConfigPage(QWidget *parent = nullptr); + ~VpnConfigPage() = default; + + VpnType getVpnType(); + void setVpnConfigInfo(const KyVpnConfig &vpnInfo); + bool checkIsChanged(const KyVpnConfig &vpnInfo); + + void updateVpnConfigInfo(KyVpnConfig &vpnInfo); + +private: + QFrame *m_vpnCommunalFrame; + QFrame *m_authModeFrame; + QFrame *m_caCertFrame; + QFrame *m_userCertFrame; + QFrame *m_staticKeysFrame; + QFrame *m_pinFrame; + QFrame *m_PrivateKeysFrame; + QFrame *m_usersFrame; + QFrame *m_userPwdOpFrame; + QFrame *m_ntFrame; + + //公有 + QLabel *m_vpnTypeLabel; + QLabel *m_vpnNameLabel; + FixLabel *m_serverAddressLabel; + QComboBox *m_vpnTypeComboBox = nullptr; + QLineEdit *m_vpnNameEdit = nullptr; + QLineEdit *m_serverAddressEdit = nullptr; + + //认证方式 Authentication Mode + FixLabel *m_authModeLabel; + QComboBox *m_authModeComboBox = nullptr; + + //证书 私钥 + FixLabel *m_caCertLabel; + FixLabel *m_userCertLabel; + FixLabel *m_privateKeyLabel; + FixLabel *m_privateKeyPwdLabel; + FixLabel *m_pwdOptionLabel; + + QLineEdit *m_caCertPathEdit; + QLineEdit *m_userCertPathEdit; + QLineEdit *m_privateKeyEdit; + KPasswordEdit *m_privateKeyPwdEdit; + QComboBox *m_pwdOptionCombox; + + QPushButton *m_caCertButton; + QPushButton *m_userCertButton; + QPushButton *m_privateKeyButton; + + //静态密钥 + QLabel *m_staticKeyLabel; + FixLabel *m_keyDirectionLabel; + QLabel *m_noticesLabel; + QLabel *m_localIpLabel; + QLabel *m_remoteIpLabel; + + QLineEdit *m_staticKeyPathEdit; + QPushButton *m_staticKeyButton; + QComboBox *m_keyDirectionCombox; + QLineEdit *m_localIpEdit; + QLineEdit *m_remoteIpEdit; + + //智能卡 PIN码 + QLabel *m_pinLabel; + QLineEdit *m_pinEdit; + + //密码 + FixLabel *m_usernameLabel; + QLabel *m_userPwdLabel; + FixLabel *m_userPwdOptionLabel; + QLineEdit *m_usernameEdit; + KPasswordEdit *m_userPwdEdit; + QComboBox *m_userPwdOptionCombox; + + //L2TP PPTP公有 + QLabel *m_ntDomainLabel; + QLineEdit *m_ntDomainEdit; + + + void initUI(); + void initConnect(); + void showL2tpPwd(); + void showPptpPwd(); + void showOpenVpnTls(); + void showOpenVpnPwd(); + void showOpenVpnPwdTls(); + void showOpenVpnStaticKey(); + void showSswanCertPrivteKey(); + void showSswanCertSsh(); + void showSswanSmartCard(); + void showSswanEap(); + + bool getTextEditState(QString text); + bool checkConfirmBtnIsEnabled(); + + + //填充VPN认证信息 + void setPwdAuthInfo(const QString &username, const QString &userPwd, const KyPasswdPolicy &userPwdPolicy); + void setCaCertAuthInfo(const QString &caCertificate); + + void setKeyAuthInfo(const QString &userCert, const QString &privateKey, + const QString &privateKeyPwd, const KyPasswdPolicy &privatePwdPolicy); + + void setStaticKeyAuthInfo(const QString &staticKey, const QString &vpnKeyDirection, + const QString &localIp, const QString &remoteIp); + + void setAgentAuthInfo(const QString &userCert); + void setSmartCardAuthInfo(const QString &pin); + void setEapAuthInfo(const QString &username, const QString &userPwd); + void setNtDomain(const QString &ntDomain); + + //set info + void setL2tpConfigInfo(const KyVpnConfig &vpnInfo); + void setPptpConfigInfo(const KyVpnConfig &vpnInfo); + void setOpenVpnConfigInfo(const KyVpnConfig &vpnInfo); + void setSSwanVpnConfigInfo(const KyVpnConfig &vpnInfo); + + //check change + bool checkL2tpIsChanged(const KyVpnConfig &vpnInfo); + bool checkPptpIsChanged(const KyVpnConfig &vpnInfo); + bool checkOpenVpnIsChanged(const KyVpnConfig &vpnInfo); + bool checkStrongSwanIsChanged(const KyVpnConfig &vpnInfo); + + //update + void updateL2tpConfigInfo(KyVpnConfig &vpnInfo); + void updatePptpConfigInfo(KyVpnConfig &vpnInfo); + void updateOpenVpnConfigInfo(KyVpnConfig &vpnInfo); + void updateSSwanVpnConfigInfo(KyVpnConfig &vpnInfo); + +private Q_SLOTS: + void onVpnTypeComboxIndexChanged(); + void onAuthModeComboxIndexChanged(); + void setEnableOfConfirmBtn(); + void onCaCertButtonClicked(); + void onUserCertButtonClicked(); + void onStaticKeyButtonClicked(); + void onPrivateKeyButtonClicked(); + +Q_SIGNALS: + void setConfigPageState(bool); + void vpnTypeChanged(VpnType type); +}; + +#endif // VPNCONFIGPAGE_H diff --git a/src-vpn/frontend/vpndetails/vpndetail.cpp b/src-vpn/frontend/vpndetails/vpndetail.cpp new file mode 100644 index 00000000..bc4150ee --- /dev/null +++ b/src-vpn/frontend/vpndetails/vpndetail.cpp @@ -0,0 +1,439 @@ +#include "vpndetail.h" + +#define WINDOW_WIDTH 520 +#define WINDOW_HEIGHT 562 +#define NO_LAYOUT_MARGINS 0,0,0,0 +#define HLAYOUT_MARGINS 24,0,24,0 +#define CENTER_LAYOUT_MARGINS 24,0,0,0 +#define NO_SPACE 0 +#define HLAYOUT_SPACING 16 +#define VLAYOUT_SPACING 24 +#define BOTTOM_WIDGET_HEIGHT 85 +#define TAB_HEIGHT 36 +#define TAB_WIDTH 80 +#define MAX_TAB_TEXT_LENGTH 44 +#define VPNTAB_WIDTH 240 +#define PAGE_WIDTH 472 +#define SCRO_WIDTH 496 +#define CONFIG_PAGE_NUM 0 +#define IPV4_PAGE_NUM 1 +#define IPV6_PAGE_NUM 2 +#define ADVANCED_PAGE_NUM 3 +#define NORMAL_PAGE_COUNT 3 +#define LOG_FLAG "[VPN Detail]" +#define TAB_HEIGHT_TABLET 48 + +VpnDetail::VpnDetail(QString vpnUuid, QString vpnName, QWidget *parent) : + m_vpnName(vpnName), + m_uuid(vpnUuid), + QWidget(parent) +{ + initWindow(); + centerToScreen(); + getVpnConfig(m_uuid, m_vpnInfo); + + initUI(); + initConnection(); + pagePadding(m_isOpenVpn); + + m_isConfigOk = true; + m_isIpv4Ok = true; + m_isIpv6Ok = true; + m_isAdvancedOk = true; + setConfirmEnable(); +} + +void VpnDetail::paintEvent(QPaintEvent *event) +{ + QPalette pal = qApp->palette(); + QPainter painter(this); + painter.setBrush(pal.color(QPalette::Base)); + painter.drawRect(this->rect()); + painter.fillRect(rect(), QBrush(pal.color(QPalette::Base))); + + return QWidget::paintEvent(event); +} + + +void VpnDetail::initWindow() +{ + this->setFixedSize(WINDOW_WIDTH, WINDOW_HEIGHT); + this->setWindowTitle(tr("VPN")); + this->setAttribute(Qt::WA_DeleteOnClose); +} + +void VpnDetail::initTabBar() +{ + //文本长度超出显示区域设置tooltip + int tabCount = m_vpnTabBar->count(); + for (int i = 0; i< tabCount; ++i) { + QFontMetrics fontMetrics(m_vpnTabBar->font()); + int fontSize = fontMetrics.width(m_vpnTabBar->tabText(i)); + if (fontSize > MAX_TAB_TEXT_LENGTH) { + m_vpnTabBar->setTabToolTip(i, m_vpnTabBar->tabText(i)); + } else { + m_vpnTabBar->setTabToolTip(i, ""); + } + } +} + +void VpnDetail::initUI() +{ + //控件 + m_topWidget = new QWidget(this); + m_centerWidget = new QWidget(this); + m_bottomWidget = new QWidget(this); + m_divider = new Divider(this); + m_vpnTabBar = new VpnTabBar(this); + m_autoConnectBox = new QCheckBox(this); + m_autoConnectLabel = new QLabel(this); + m_cancelBtn = new QPushButton(this); + m_confimBtn = new QPushButton(this); + m_stackWidget = new QStackedWidget(m_centerWidget); + + m_configPage = new VpnConfigPage(this); + m_ipv4Page = new VpnIpv4Page(this); + m_ipv6Page = new VpnIpv6Page(this); + m_advancedPage = new VpnAdvancedPage(this); + + m_configScroArea = new QScrollArea(m_centerWidget); + m_configScroArea->setFrameShape(QFrame::NoFrame); + m_configScroArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + m_configScroArea->setWidget(m_configPage); + m_configScroArea->setWidgetResizable(true); + + m_ipv4ScroArea = new QScrollArea(m_centerWidget); + m_ipv4ScroArea->setFrameShape(QFrame::NoFrame); + m_ipv4ScroArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + m_ipv4ScroArea->setWidget(m_ipv4Page); + m_ipv4ScroArea->setWidgetResizable(true); + + m_ipv6ScroArea = new QScrollArea(m_centerWidget); + m_ipv6ScroArea->setFrameShape(QFrame::NoFrame); + m_ipv6ScroArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + m_ipv6ScroArea->setWidget(m_ipv6Page); + m_ipv6ScroArea->setWidgetResizable(true); + + m_advancedScroArea = new QScrollArea(m_centerWidget); + m_advancedScroArea->setFrameShape(QFrame::NoFrame); + m_advancedScroArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + m_advancedScroArea->setWidget(m_advancedPage); + m_advancedScroArea->setWidgetResizable(true); + + QPalette pal = m_configScroArea->palette(); + pal.setBrush(QPalette::Window, Qt::transparent); + m_configScroArea->setPalette(pal); + m_ipv4ScroArea->setPalette(pal); + m_ipv6ScroArea->setPalette(pal); + m_advancedScroArea->setPalette(pal); + + m_configPage->setFixedWidth(PAGE_WIDTH); + m_ipv4Page->setFixedWidth(PAGE_WIDTH); + m_ipv6Page->setFixedWidth(PAGE_WIDTH); + m_advancedPage->setFixedWidth(PAGE_WIDTH); + m_configScroArea->setFixedWidth(SCRO_WIDTH); + m_ipv4ScroArea->setFixedWidth(SCRO_WIDTH); + m_ipv6ScroArea->setFixedWidth(SCRO_WIDTH); + m_advancedScroArea->setFixedWidth(SCRO_WIDTH); + + m_stackWidget->addWidget(m_configScroArea); + m_stackWidget->addWidget(m_ipv4ScroArea); + m_stackWidget->addWidget(m_ipv6ScroArea); + m_stackWidget->addWidget(m_advancedScroArea); + + //控件显示文本 + m_vpnTabBar->addTab(tr("VPN")); + m_vpnTabBar->addTab(tr("IPv4")); + if (m_isOpenVpn) { + m_vpnTabBar->addTab(tr("IPv6")); + m_vpnTabBar->setFixedWidth(VPNTAB_WIDTH + TAB_WIDTH); + } else { + m_vpnTabBar->setFixedWidth(VPNTAB_WIDTH); + } + m_vpnTabBar->addTab(tr("Advanced")); + m_vpnTabBar->setFixedHeight(TAB_HEIGHT); + initTabBar(); + + m_autoConnectBox->setChecked(false); + m_autoConnectLabel->setText(tr("Auto Connection")); + m_cancelBtn->setText(tr("Cancel")); + m_confimBtn->setText(tr("Confirm")); + + //布局 + QVBoxLayout *mainLayout = new QVBoxLayout(this); + mainLayout->setContentsMargins(NO_LAYOUT_MARGINS); + mainLayout->setSpacing(NO_SPACE); + mainLayout->addSpacing(HLAYOUT_SPACING); + mainLayout->addWidget(m_topWidget); + mainLayout->addSpacing(VLAYOUT_SPACING); + mainLayout->addWidget(m_centerWidget); + mainLayout->addStretch(); + mainLayout->addWidget(m_divider); + mainLayout->addWidget(m_bottomWidget); + m_bottomWidget->setFixedHeight(BOTTOM_WIDGET_HEIGHT); + + QHBoxLayout *topLayout = new QHBoxLayout(m_topWidget); + topLayout->setContentsMargins(HLAYOUT_MARGINS); + topLayout->addWidget(m_vpnTabBar, Qt::AlignCenter); + + QVBoxLayout *centerlayout = new QVBoxLayout(m_centerWidget); + centerlayout->setContentsMargins(CENTER_LAYOUT_MARGINS); // 右边距为0,为安全页滚动区域留出空间 + centerlayout->addWidget(m_stackWidget); + + QHBoxLayout *bottomLayout = new QHBoxLayout(m_bottomWidget); + bottomLayout->setContentsMargins(HLAYOUT_MARGINS); + bottomLayout->setSpacing(NO_SPACE); + bottomLayout->addWidget(m_autoConnectBox); + bottomLayout->addSpacing(8); + bottomLayout->addWidget(m_autoConnectLabel); + bottomLayout->addStretch(); + bottomLayout->addWidget(m_cancelBtn); + bottomLayout->addSpacing(HLAYOUT_SPACING); + bottomLayout->addWidget(m_confimBtn); + + m_advancedPage->setVpnAdvancedPage(m_configPage->getVpnType()); +} + +void VpnDetail::initConnection() +{ + connect(m_vpnTabBar, &VpnTabBar::currentChanged, this, &VpnDetail::onTabCurrentRowChange); + connect(m_cancelBtn, &QPushButton::clicked, [&] () {this->close();}); + connect(m_confimBtn, &QPushButton::clicked, this, &VpnDetail::onConfimBtnClicked); + + connect(m_configPage, &VpnConfigPage::setConfigPageState, this, [=] (bool state) { + m_isConfigOk = state; + setConfirmEnable(); + }); + connect(m_ipv4Page, &VpnIpv4Page::setIpv4PageState, this, [=] (bool state) { + m_isIpv4Ok = state; + setConfirmEnable(); + }); + connect(m_ipv6Page, &VpnIpv6Page::setIpv6PageState, this, [=] (bool state) { + m_isIpv6Ok = state; + setConfirmEnable(); + }); + connect(m_advancedPage, &VpnAdvancedPage::setAdvancedPageState, this, [=] (bool state) { + m_isAdvancedOk = state; + setConfirmEnable(); + }); + + connect(m_configPage, &VpnConfigPage::vpnTypeChanged, m_advancedPage, &VpnAdvancedPage::setVpnAdvancedPage); + + connect(m_configPage, &VpnConfigPage::vpnTypeChanged, this, [=](VpnType type) { + if (type == OPEN_VPN) { + if (m_vpnTabBar->count() == NORMAL_PAGE_COUNT) { + m_vpnTabBar->insertTab(IPV6_PAGE_NUM, tr("IPv6")); + m_vpnTabBar->setFixedWidth(VPNTAB_WIDTH + TAB_WIDTH); + } + } else { + if (m_vpnTabBar->count() > NORMAL_PAGE_COUNT) { + m_vpnTabBar->removeTab(IPV6_PAGE_NUM); + m_vpnTabBar->setFixedWidth(VPNTAB_WIDTH); + } + } + }); +} + +void VpnDetail::centerToScreen() +{ + QDesktopWidget* m = QApplication::desktop(); + QRect desk_rect = m->screenGeometry(m->screenNumber(QCursor::pos())); + int desk_x = desk_rect.width(); + int desk_y = desk_rect.height(); + int x = this->width(); + int y = this->height(); + this->move(desk_x / 2 - x / 2 + desk_rect.left(), desk_y / 2 - y / 2 + desk_rect.top()); +} + +void VpnDetail::setConfirmEnable() +{ + bool isConfirmBtnEnable = false; + if (m_isConfigOk && m_isIpv4Ok && m_isAdvancedOk) { + if (m_isOpenVpn && !m_isIpv6Ok) { + isConfirmBtnEnable = false; + } else { + isConfirmBtnEnable = true; + } + } + m_confimBtn->setEnabled(isConfirmBtnEnable); +} + +void VpnDetail::getVpnConfig(QString connectUuid, KyVpnConfig &vpnInfo) +{ + KyVpnConnectOperation vpnConnect(this); + vpnInfo = vpnConnect.getVpnConfig(connectUuid); + m_isOpenVpn = m_vpnInfo.m_vpnType == KYVPNTYPE_OPENVPN; +} + +void VpnDetail::pagePadding(bool isOpenVpn) +{ + m_autoConnectBox->setChecked(m_vpnInfo.m_isAutoConnect); + + //配置页面填充 + m_configPage->setVpnConfigInfo(m_vpnInfo); + + //IPv4页面填充 + m_ipv4Page->setVpnIpv4Info(m_vpnInfo); + if (!m_vpnInfo.m_ipv4Dns.isEmpty()) { + m_ipv4Page->setDns(m_vpnInfo.m_ipv4Dns.at(0).toString()); + } + if (!m_vpnInfo.m_ipv4DnsSearch.isEmpty()) { + m_ipv4Page->setSearchDomain(m_vpnInfo.m_ipv4DnsSearch.at(0)); + } + m_ipv4Page->setDhcpClientId(m_vpnInfo.m_ipv4DhcpClientId); + //IPv6页面填充 + if (isOpenVpn) { + m_ipv6Page->setVpnIpv6Info(m_vpnInfo); + if (!m_vpnInfo.m_ipv6Dns.isEmpty()) { + m_ipv6Page->setDns(m_vpnInfo.m_ipv6Dns.at(0).toString()); + } + if (!m_vpnInfo.m_ipv6DnsSearch.isEmpty()) { + m_ipv6Page->setSearchDomain(m_vpnInfo.m_ipv6DnsSearch.at(0)); + } + } + + //高级页面填充 + if (m_vpnInfo.m_vpnType == KYVPNTYPE_L2TP || m_vpnInfo.m_vpnType == KYVPNTYPE_PPTP) { + m_advancedPage->setL2tpOrPptpAdiaInfo(m_vpnInfo); + } else if (m_vpnInfo.m_vpnType == KYVPNTYPE_OPENVPN) { + m_advancedPage->setOpenVpnAdiaInfo(m_vpnInfo); + } else if (m_vpnInfo.m_vpnType == KYVPNTYPE_STRONGSWAN) { + m_advancedPage->setStrongSwanAdiaInfo(m_vpnInfo); + } +} + +bool VpnDetail::updateVpnCnofig() +{ + KyVpnConnectOperation vpnConnect(this); + KyVpnConfig vpnConfig = m_vpnInfo; + bool needUpdate = false; + VpnType vpnType = m_configPage->getVpnType(); + + if (m_vpnInfo.m_isAutoConnect != m_autoConnectBox->isChecked()) { + vpnConfig.m_isAutoConnect = m_autoConnectBox->isChecked(); + needUpdate = true; + } + + if (m_configPage->checkIsChanged(m_vpnInfo)) { + m_configPage->updateVpnConfigInfo(vpnConfig); + needUpdate = true; + } + + if (m_ipv4Page->checkIsChanged(m_vpnInfo)) { + m_ipv4Page->updateVpnIpv4Info(vpnConfig); + needUpdate = true; + } + + if (vpnType == OPEN_VPN) { + if (m_ipv6Page->checkIsChanged(m_vpnInfo)) { + m_ipv6Page->updateVpnIpv6Info(vpnConfig); + needUpdate = true; + } + } + + if (m_advancedPage->checkIsChanged(m_vpnInfo, vpnType)) { + if (vpnType == L2TP || vpnType == PPTP) { + m_advancedPage->updateL2tpOrPptpAdiaInfo(vpnConfig); + needUpdate = true; + } else if (vpnType == OPEN_VPN) { + m_advancedPage->updateOpenVpnAdiaInfo(vpnConfig); + needUpdate = true; + } else if (vpnType == STRONG_SWAN) { + m_advancedPage->updateStrongSwanAdiaInfo(vpnConfig); + needUpdate = true; + } + } + + if (needUpdate) { + vpnConnect.setVpnConfig(m_uuid, vpnConfig); + } + + return true; +} + +void VpnDetail::setVpndetailSomeEnable(bool on) +{ + m_configPage->setEnabled(on); + m_ipv4Page->setEnabled(on); + m_ipv6Page->setEnabled(on); + m_advancedPage->setEnabled(on); + m_cancelBtn->setEnabled(on); + m_confimBtn->setEnabled(on); +} + +void VpnDetail::onTabCurrentRowChange(int row) +{ + if (row < 2) { + m_stackWidget->setCurrentIndex(row); + } else { + if (m_configPage->getVpnType() == OPEN_VPN) { + m_stackWidget->setCurrentIndex(row); + } else { + m_stackWidget->setCurrentIndex(ADVANCED_PAGE_NUM); + } + } +} + +void VpnDetail::onConfimBtnClicked() +{ + qDebug() << "onConfimBtnClicked"; + setVpndetailSomeEnable(false); + //更新连接 + qDebug() << "Confirm update connect"; + if (!updateVpnCnofig()) { + setVpndetailSomeEnable(true); + return; + } + close(); +} + + +VpnTabBar::VpnTabBar(QWidget *parent) + :KTabBar(KTabBarStyle::SegmentDark, parent) +{ + //模式切换 + QDBusConnection::sessionBus().connect(QString("com.kylin.statusmanager.interface"), + QString("/"), + QString("com.kylin.statusmanager.interface"), + QString("mode_change_signal"), this, SLOT(onModeChanged(bool))); + //模式获取 + QDBusInterface interface(QString("com.kylin.statusmanager.interface"), + QString("/"), + QString("com.kylin.statusmanager.interface"), + QDBusConnection::sessionBus()); + if(!interface.isValid()) { + this->setFixedHeight(TAB_HEIGHT); + return; + } + QDBusReply reply = interface.call("get_current_tabletmode"); + if (!reply.isValid()) { + this->setFixedHeight(TAB_HEIGHT); + return; + } + onModeChanged(reply.value()); +} + +QSize VpnTabBar::sizeHint() const +{ + QSize size = KTabBar::sizeHint(); + size.setWidth(TAB_WIDTH); + return size; +} + +QSize VpnTabBar::minimumTabSizeHint(int index) const +{ + Q_UNUSED(index) + QSize size = KTabBar::minimumTabSizeHint(index); + size.setWidth(TAB_WIDTH); + return size; +} + +void VpnTabBar::onModeChanged(bool mode) +{ + if (mode) { + this->setFixedHeight(TAB_HEIGHT_TABLET); // 平板模式 + } else { + this->setFixedHeight(TAB_HEIGHT); // PC模式 + } + +} diff --git a/src-vpn/frontend/vpndetails/vpndetail.h b/src-vpn/frontend/vpndetails/vpndetail.h new file mode 100644 index 00000000..c98585af --- /dev/null +++ b/src-vpn/frontend/vpndetails/vpndetail.h @@ -0,0 +1,111 @@ +#ifndef VPNDETAIL_H +#define VPNDETAIL_H + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "kwidget.h" +#include "ktabbar.h" +#include "../tools/divider.h" +#include "vpnconfigpage.h" +#include "vpnipv4page.h" +#include "vpnipv6page.h" +#include "vpnadvancedpage.h" + +#include "kyvpnconnectoperation.h" + + +using namespace kdk; + +class VpnTabBar : public KTabBar +{ + Q_OBJECT +public: + explicit VpnTabBar(QWidget *parent = nullptr); + ~VpnTabBar() = default; + +protected: + QSize sizeHint() const; + QSize minimumTabSizeHint(int index) const; + +private Q_SLOTS: + void onModeChanged(bool mode); + +}; + +class VpnDetail : public QWidget +{ + Q_OBJECT +public: + explicit VpnDetail(QString vpnUuid, QString vpnName, QWidget *parent = nullptr); + void centerToScreen(); + +protected: + void paintEvent(QPaintEvent *event); + +private: + void initUI(); + void initWindow(); + void initTabBar(); + + void initConnection(); + void setConfirmEnable(); + + void getVpnConfig(QString connectUuid, KyVpnConfig &vpnInfo); + void pagePadding(bool isOpenVpn); + + bool updateVpnCnofig(); + void setVpndetailSomeEnable(bool on); + + bool m_isOpenVpn = false; + QString m_vpnName; + QString m_uuid; + KyVpnConfig m_vpnInfo; + + QStackedWidget * m_stackWidget; + QWidget *m_topWidget; + QWidget *m_centerWidget; + Divider *m_divider = nullptr; + QWidget *m_bottomWidget; + + VpnConfigPage *m_configPage = nullptr; + VpnIpv4Page *m_ipv4Page = nullptr; + VpnIpv6Page *m_ipv6Page = nullptr; + VpnAdvancedPage *m_advancedPage = nullptr; + + QScrollArea *m_configScroArea = nullptr; + QScrollArea *m_ipv4ScroArea = nullptr; + QScrollArea *m_ipv6ScroArea = nullptr; + QScrollArea *m_advancedScroArea = nullptr; + VpnTabBar *m_vpnTabBar = nullptr; + QCheckBox *m_autoConnectBox = nullptr; + QLabel *m_autoConnectLabel; + QPushButton *m_cancelBtn; + QPushButton *m_confimBtn; + + bool m_isConfigOk = false; + bool m_isIpv4Ok = false; + bool m_isIpv6Ok = false; + bool m_isAdvancedOk = false; + +protected Q_SLOTS: + void onTabCurrentRowChange(int row); + void onConfimBtnClicked(); + +Q_SIGNALS: + void currentChanged(int); + +}; + +#endif // VPNDETAIL_H diff --git a/src-vpn/frontend/vpndetails/vpndetails.pri b/src-vpn/frontend/vpndetails/vpndetails.pri new file mode 100644 index 00000000..e80cdfa7 --- /dev/null +++ b/src-vpn/frontend/vpndetails/vpndetails.pri @@ -0,0 +1,17 @@ +INCLUDEPATH += $$PWD + +HEADERS += \ + $$PWD/vpnaddpage.h \ + $$PWD/vpnadvancedpage.h \ + $$PWD/vpnconfigpage.h \ + $$PWD/vpndetail.h \ + $$PWD/vpnipv4page.h \ + $$PWD/vpnipv6page.h + +SOURCES += \ + $$PWD/vpnaddpage.cpp \ + $$PWD/vpnadvancedpage.cpp \ + $$PWD/vpnconfigpage.cpp \ + $$PWD/vpndetail.cpp \ + $$PWD/vpnipv4page.cpp \ + $$PWD/vpnipv6page.cpp diff --git a/src-vpn/frontend/vpndetails/vpnipv4page.cpp b/src-vpn/frontend/vpndetails/vpnipv4page.cpp new file mode 100644 index 00000000..fa49a9cd --- /dev/null +++ b/src-vpn/frontend/vpndetails/vpnipv4page.cpp @@ -0,0 +1,284 @@ +#include "vpnipv4page.h" +#include "math.h" +#include + +#define NO_LAYOUT_MARGINS 0, 0, 0, 0 +#define NO_SPACE 0 +#define HLAYOUT_SPACING 16 +#define VLAYOUT_SPACING 24 +#define AUTO_CONFIG 0 +#define MANUAL_CONFIG 1 +#define LOG_FLAG "[VPN IPv4Page]" + +VpnIpv4Page::VpnIpv4Page(QWidget *parent) : QFrame(parent) +{ + initUI(); + initConnect(); +} + +void VpnIpv4Page::setVpnIpv4Info(const KyVpnConfig &vpnInfo) +{ + if (vpnInfo.m_ipv4ConfigIpType == CONFIG_IP_DHCP) { + m_ipv4ConfigCombox->setCurrentIndex(AUTO_CONFIG); + } else { + m_ipv4ConfigCombox->setCurrentIndex(MANUAL_CONFIG); + if (!vpnInfo.m_ipv4Address.isEmpty()) { + m_ipv4addressEdit->setText(vpnInfo.m_ipv4Address.at(0).ip().toString()); + m_netMaskEdit->setText(vpnInfo.m_ipv4Address.at(0).netmask().toString()); + m_gateWayEdit->setText(vpnInfo.m_ipv4Address.at(0).gateway().toString()); + } + } +} + +void VpnIpv4Page::setDns(const QString &firstDns) +{ + m_dnsServerEdit->setText(firstDns); +} + +void VpnIpv4Page::setSearchDomain(const QString &searchDomain) +{ + m_searchDomainEdit->setText(searchDomain); +} + +void VpnIpv4Page::setDhcpClientId(const QString &dhcpId) +{ + m_dhcpClientIdEdit->setText(dhcpId); +} + +bool VpnIpv4Page::checkIsChanged(const KyVpnConfig &vpnInfo) +{ + bool isChanged = false; + + if (m_ipv4ConfigCombox->currentIndex() == AUTO_CONFIG) { + if (vpnInfo.m_ipv4ConfigIpType != CONFIG_IP_DHCP) { + qDebug() << LOG_FLAG << "ipv4ConfigType change to Auto"; + isChanged = true; + } + } else { + if (vpnInfo.m_ipv4ConfigIpType != CONFIG_IP_MANUAL) { + qDebug() << LOG_FLAG << "ipv4ConfigType change to Manual"; + isChanged = true; + } + + if (!vpnInfo.m_ipv4Address.isEmpty()) { + if(vpnInfo.m_ipv4Address.at(0).ip().toString() != m_ipv4addressEdit->text() + || vpnInfo.m_ipv4Address.at(0).netmask().toString() != getNetMaskText(m_netMaskEdit->text()) + || vpnInfo.m_ipv4Address.at(0).gateway().toString() != m_gateWayEdit->text()) { + + isChanged = true; + } + } + } + + if (!vpnInfo.m_ipv4Dns.isEmpty() && vpnInfo.m_ipv4Dns.at(0).toString() != m_dnsServerEdit->text()) { + isChanged = true; + } + + if (!vpnInfo.m_ipv4DnsSearch.isEmpty() && vpnInfo.m_ipv4DnsSearch.at(0) != m_searchDomainEdit->text()) { + isChanged = true; + } + if (vpnInfo.m_ipv4DhcpClientId != m_dhcpClientIdEdit->text()){ + isChanged = true; + } + return isChanged; +} + +void VpnIpv4Page::updateVpnIpv4Info(KyVpnConfig &vpnInfo) +{ + if (m_ipv4ConfigCombox->currentIndex() == AUTO_CONFIG) { + QString ipv4address(""); + QString netMask(""); + QString gateWay(""); + vpnInfo.setIpConfigType(IPADDRESS_V4, CONFIG_IP_DHCP); + vpnInfo.ipv4AddressConstruct(ipv4address, netMask, gateWay); + qDebug() << LOG_FLAG << "IPv4 method" << vpnInfo.m_ipv4ConfigIpType; + qDebug() << LOG_FLAG << "Update IPv4 info finished"; + } else { + QString ipv4address =m_ipv4addressEdit->text(); + QString netMask = getNetMaskText(m_netMaskEdit->text()); + QString gateWay = m_gateWayEdit->text(); + qDebug() << ipv4address << netMask << gateWay; + vpnInfo.setIpConfigType(IPADDRESS_V4, CONFIG_IP_MANUAL); + vpnInfo.ipv4AddressConstruct(ipv4address, netMask, gateWay); + vpnInfo.dumpInfo(); + qDebug() << LOG_FLAG << "Update IPv4 info finished"; + } + + QList ipv4DnsList; + ipv4DnsList.clear(); + if (!m_dnsServerEdit->text().isEmpty()) { + ipv4DnsList.append(QHostAddress(m_dnsServerEdit->text())); + } + vpnInfo.ipv4DnsConstruct(ipv4DnsList); + + vpnInfo.m_ipv4DnsSearch.clear(); + vpnInfo.m_ipv4DnsSearch.append(m_searchDomainEdit->text()); + vpnInfo.m_ipv4DhcpClientId = m_dhcpClientIdEdit->text(); +} + +void VpnIpv4Page::initUI() +{ + /**********控件**********/ + m_configLabel = new QLabel(this); + m_addressLabel = new QLabel(this); + m_maskLabel = new QLabel(this); + m_gateWayLabel = new QLabel(this); + m_dnsServerLabel = new QLabel(this); + m_searchDomainLabel = new QLabel(this); + m_dhcpClientIdLabel = new QLabel(this); + + m_ipv4ConfigCombox =new QComboBox(this); + m_ipv4addressEdit = new QLineEdit(this); + m_netMaskEdit = new QLineEdit(this); + m_gateWayEdit = new QLineEdit(this); + m_dnsServerEdit = new QLineEdit(this); + m_searchDomainEdit = new QLineEdit(this); + m_dhcpClientIdEdit = new QLineEdit(this); + + + /**********布局**********/ + QFormLayout *mainLayout = new QFormLayout(this); + mainLayout->setContentsMargins(NO_LAYOUT_MARGINS); + mainLayout->setHorizontalSpacing(HLAYOUT_SPACING); + mainLayout->setVerticalSpacing(VLAYOUT_SPACING); + mainLayout->addRow(m_configLabel, m_ipv4ConfigCombox); + mainLayout->addRow(m_addressLabel, m_ipv4addressEdit); + mainLayout->addRow(m_maskLabel, m_netMaskEdit); + mainLayout->addRow(m_gateWayLabel, m_gateWayEdit); + mainLayout->addRow(m_dnsServerLabel, m_dnsServerEdit); + mainLayout->addRow(m_searchDomainLabel, m_searchDomainEdit); + mainLayout->addRow(m_dhcpClientIdLabel, m_dhcpClientIdEdit); + + + /**********控件显示**********/ + m_configLabel->setText(tr("IPv4 Config")); + m_addressLabel->setText(tr("Address")); + m_maskLabel->setText(tr("Netmask")); + m_gateWayLabel->setText(tr("Default Gateway")); + m_dnsServerLabel->setText(tr("DNS Server")); + m_searchDomainLabel->setText(tr("Search Domain")); //搜索域 + m_dhcpClientIdLabel->setText(tr("DHCP Client ID")); //DHCP客户端ID + + m_ipv4ConfigCombox->addItem(tr("Auto(DHCP)"), AUTO_CONFIG); //"自动(DHCP)" + m_ipv4ConfigCombox->addItem(tr("Manual"), MANUAL_CONFIG); //"手动" + + // IP的正则格式限制 + QRegExp rxIp("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"); + QRegExpValidator *ipExpVal = new QRegExpValidator(rxIp, this); + m_ipv4addressEdit->setValidator(ipExpVal); + m_netMaskEdit->setValidator(ipExpVal); + m_gateWayEdit->setValidator(ipExpVal); + m_dnsServerEdit->setValidator(ipExpVal); +} + +void VpnIpv4Page::initConnect() +{ + if (m_ipv4ConfigCombox->currentIndex() == AUTO_CONFIG) { + setManualEnabled(false); + } else if (m_ipv4ConfigCombox->currentIndex() == MANUAL_CONFIG) { + setManualEnabled(true); + } + connect(m_ipv4ConfigCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(onConfigChanged(int))); + connect(m_ipv4ConfigCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(setEnableOfConfirmBtn())); + connect(m_ipv4addressEdit, &QLineEdit::textChanged, this, &VpnIpv4Page::setEnableOfConfirmBtn); + connect(m_netMaskEdit, &QLineEdit::textChanged, this, &VpnIpv4Page::setEnableOfConfirmBtn); + connect(m_gateWayEdit, &QLineEdit::textChanged, this, &VpnIpv4Page::setEnableOfConfirmBtn); + connect(m_dnsServerEdit, &QLineEdit::textChanged, this, &VpnIpv4Page::setEnableOfConfirmBtn); + connect(m_searchDomainEdit, &QLineEdit::textChanged, this, &VpnIpv4Page::setEnableOfConfirmBtn); + connect(m_dhcpClientIdEdit, &QLineEdit::textChanged, this, &VpnIpv4Page::setEnableOfConfirmBtn); +} + +void VpnIpv4Page::setManualEnabled(bool state) +{ + m_addressLabel->setEnabled(state); + m_maskLabel->setEnabled(state); + m_gateWayLabel->setEnabled(state); + m_ipv4addressEdit->setEnabled(state); + m_netMaskEdit->setEnabled(state); + m_gateWayEdit->setEnabled(state); +} + +bool VpnIpv4Page::getTextEditState(QString text) +{ + if (text.isEmpty()) { + return true; + } + QRegExp rx("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"); + + bool match = false; + match = rx.exactMatch(text); + + return match; +} + +bool VpnIpv4Page::netMaskIsValide(QString text) +{ + if (getTextEditState(text)) { + return true; + } else { + if (text.length() > 0 && text.length() < 3) { + int num = text.toInt(); + if (num > 0 && num < 33) { + return true; + } + } + } + return false; +} + +QString VpnIpv4Page::getNetMaskText(QString text) +{ + if (text.length() > 2) { + return text; + } + + int num = text.toInt(); + QStringList list; + list << "0" << "0" << "0" << "0"; + int count = 0; + while (num - 8 >= 0) { + list[count] = "255"; + num = num - 8; + count ++; + } + if (num > 0) { + int size = pow(2, 8) - pow(2,(8-num)); + list[count] = QString::number(size); + } + return QString("%1.%2.%3.%4").arg(list[0],list[1],list[2],list[3]); +} + +bool VpnIpv4Page::checkConfirmBtnIsEnabled() +{ + if (m_ipv4ConfigCombox->currentIndex() == AUTO_CONFIG) { + return true; + } else { + if (m_ipv4addressEdit->text().isEmpty() || !getTextEditState(m_ipv4addressEdit->text())) { + qDebug() << LOG_FLAG << "IPv4 address empty or invalid"; + return false; + } + + if (m_netMaskEdit->text().isEmpty() || !netMaskIsValide(m_netMaskEdit->text())) { + qDebug() << LOG_FLAG << "IPv4 netMask empty or invalid"; + return false; + } + } + return true; +} + +void VpnIpv4Page::setEnableOfConfirmBtn() +{ + Q_EMIT setIpv4PageState(checkConfirmBtnIsEnabled()); +} + +void VpnIpv4Page::onConfigChanged(int index) +{ + if (index == AUTO_CONFIG) { + m_ipv4addressEdit->clear(); + m_netMaskEdit->clear(); + m_gateWayEdit->clear(); + setManualEnabled(false); + } else if (index == MANUAL_CONFIG) { + setManualEnabled(true); + } +} diff --git a/src-vpn/frontend/vpndetails/vpnipv4page.h b/src-vpn/frontend/vpndetails/vpnipv4page.h new file mode 100644 index 00000000..ee73d5fe --- /dev/null +++ b/src-vpn/frontend/vpndetails/vpnipv4page.h @@ -0,0 +1,62 @@ +#ifndef VPNIPV4PAGE_H +#define VPNIPV4PAGE_H + +#include +#include +#include +#include +#include +#include + +#include "kyvpnconnectoperation.h" + +class VpnIpv4Page : public QFrame +{ + Q_OBJECT +public: + VpnIpv4Page(QWidget *parent = nullptr); + ~VpnIpv4Page() = default; + + void setVpnIpv4Info(const KyVpnConfig &vpnInfo); + void setDns(const QString &firstDns); + void setSearchDomain(const QString &searchDomain); + void setDhcpClientId(const QString &dhcpId); + + bool checkIsChanged(const KyVpnConfig &vpnInfo); + void updateVpnIpv4Info(KyVpnConfig &vpnInfo); + +private: + QLabel *m_configLabel; + QLabel *m_addressLabel; + QLabel *m_maskLabel; + QLabel *m_gateWayLabel; + QLabel *m_dnsServerLabel; + QLabel *m_searchDomainLabel; + QLabel *m_dhcpClientIdLabel; + + QComboBox *m_ipv4ConfigCombox; + QLineEdit *m_ipv4addressEdit; + QLineEdit *m_netMaskEdit; + QLineEdit *m_gateWayEdit; + QLineEdit *m_dnsServerEdit; + QLineEdit *m_searchDomainEdit; + QLineEdit *m_dhcpClientIdEdit; + + void initUI(); + void initConnect(); + void setManualEnabled(bool state); + + bool getTextEditState(QString text); + bool netMaskIsValide(QString text); + QString getNetMaskText(QString text); + bool checkConfirmBtnIsEnabled(); + +private Q_SLOTS: + void setEnableOfConfirmBtn(); + void onConfigChanged(int index); + +Q_SIGNALS: + void setIpv4PageState(bool); +}; + +#endif // VPNIPV4PAGE_H diff --git a/src-vpn/frontend/vpndetails/vpnipv6page.cpp b/src-vpn/frontend/vpndetails/vpnipv6page.cpp new file mode 100644 index 00000000..87e921ab --- /dev/null +++ b/src-vpn/frontend/vpndetails/vpnipv6page.cpp @@ -0,0 +1,240 @@ +#include "vpnipv6page.h" +#include "math.h" +#include + +#define NO_LAYOUT_MARGINS 0, 0, 0, 0 +#define NO_SPACE 0 +#define HLAYOUT_SPACING 16 +#define VLAYOUT_SPACING 24 +#define AUTO_CONFIG 0 +#define MANUAL_CONFIG 1 +#define LOG_FLAG "[VPN IPv6Page]" + +VpnIpv6Page::VpnIpv6Page(QWidget *parent) : QFrame(parent) +{ + initUI(); + initConnect(); +} + +void VpnIpv6Page::setVpnIpv6Info(const KyVpnConfig &vpnInfo) +{ + if (vpnInfo.m_ipv6ConfigIpType == CONFIG_IP_DHCP) { + m_ipv6ConfigCombox->setCurrentIndex(AUTO_CONFIG); + } else { + m_ipv6ConfigCombox->setCurrentIndex(MANUAL_CONFIG); + if (!vpnInfo.m_ipv6Address.isEmpty()) { + m_ipv6addressEdit->setText(vpnInfo.m_ipv6Address.at(0).ip().toString()); + m_netMaskEdit->setText(vpnInfo.m_ipv6Address.at(0).netmask().toString()); + m_gateWayEdit->setText(vpnInfo.m_ipv6Address.at(0).gateway().toString()); + } + } +} + +void VpnIpv6Page::setDns(const QString &firstDns) +{ + m_dnsServerEdit->setText(firstDns); +} + +void VpnIpv6Page::setSearchDomain(const QString &searchDomain) +{ + m_searchDomainEdit->setText(searchDomain); +} + +bool VpnIpv6Page::checkIsChanged(const KyVpnConfig &vpnInfo) +{ + bool isChanged = false; + + if (m_ipv6ConfigCombox->currentIndex() == AUTO_CONFIG) { + if (vpnInfo.m_ipv6ConfigIpType != CONFIG_IP_DHCP) { + qDebug() << LOG_FLAG << "ipv6ConfigType change to Auto"; + isChanged = true; + } + } else { + if (vpnInfo.m_ipv6ConfigIpType != CONFIG_IP_MANUAL) { + qDebug() << LOG_FLAG << "ipv6ConfigType change to Manual"; + isChanged = true; + } + + if (!vpnInfo.m_ipv6Address.isEmpty()) { + if(vpnInfo.m_ipv6Address.at(0).ip().toString() != m_ipv6addressEdit->text() + || vpnInfo.m_ipv6Address.at(0).netmask().toString() != m_netMaskEdit->text() + || vpnInfo.m_ipv6Address.at(0).gateway().toString() != m_gateWayEdit->text()) { + + isChanged = true; + } + } + } + + if (!vpnInfo.m_ipv6Dns.isEmpty() && vpnInfo.m_ipv6Dns.at(0).toString() != m_dnsServerEdit->text()) { + isChanged = true; + } + + if (!vpnInfo.m_ipv6DnsSearch.isEmpty() && vpnInfo.m_ipv6DnsSearch.at(0) != m_searchDomainEdit->text()) { + isChanged = true; + } + + return isChanged; +} + +void VpnIpv6Page::updateVpnIpv6Info(KyVpnConfig &vpnInfo) +{ + if (m_ipv6ConfigCombox->currentIndex() == AUTO_CONFIG) { + QString ipv6address(""); + QString netMask(""); + QString gateWay(""); + vpnInfo.setIpConfigType(IPADDRESS_V6, CONFIG_IP_DHCP); + vpnInfo.ipv6AddressConstruct(ipv6address, netMask, gateWay); + qDebug() << LOG_FLAG << "IPv6 method" << vpnInfo.m_ipv6ConfigIpType; + qDebug() << LOG_FLAG << "Update IPv6 info finished"; + } else { + QString ipv6address =m_ipv6addressEdit->text(); + QString netMask = m_netMaskEdit->text(); + QString gateWay = m_gateWayEdit->text(); + qDebug() << ipv6address << netMask << gateWay; + vpnInfo.setIpConfigType(IPADDRESS_V6, CONFIG_IP_MANUAL); + vpnInfo.ipv6AddressConstruct(ipv6address, netMask, gateWay); + vpnInfo.dumpInfo(); + qDebug() << LOG_FLAG << "Update IPv6 info finished"; + } + + QList ipv6DnsList; + ipv6DnsList.clear(); + if (!m_dnsServerEdit->text().isEmpty()) { + ipv6DnsList.append(QHostAddress(m_dnsServerEdit->text())); + } + vpnInfo.ipv6DnsConstruct(ipv6DnsList); + + vpnInfo.m_ipv6DnsSearch.clear(); + vpnInfo.m_ipv6DnsSearch.append(m_searchDomainEdit->text()); +} + +void VpnIpv6Page::initUI() +{ + /**********控件**********/ + m_configLabel = new QLabel(this); + m_addressLabel = new QLabel(this); + m_maskLabel = new QLabel(this); + m_gateWayLabel = new QLabel(this); + m_dnsServerLabel = new QLabel(this); + m_searchDomainLabel = new QLabel(this); + + m_ipv6ConfigCombox =new QComboBox(this); + m_ipv6addressEdit = new QLineEdit(this); + m_netMaskEdit = new QLineEdit(this); + m_gateWayEdit = new QLineEdit(this); + m_dnsServerEdit = new QLineEdit(this); + m_searchDomainEdit = new QLineEdit(this); + + + /**********布局**********/ + QFormLayout *mainLayout = new QFormLayout(this); + mainLayout->setContentsMargins(NO_LAYOUT_MARGINS); + mainLayout->setHorizontalSpacing(HLAYOUT_SPACING); + mainLayout->setVerticalSpacing(VLAYOUT_SPACING); + mainLayout->addRow(m_configLabel, m_ipv6ConfigCombox); + mainLayout->addRow(m_addressLabel, m_ipv6addressEdit); + mainLayout->addRow(m_maskLabel, m_netMaskEdit); + mainLayout->addRow(m_gateWayLabel, m_gateWayEdit); + mainLayout->addRow(m_dnsServerLabel, m_dnsServerEdit); + mainLayout->addRow(m_searchDomainLabel, m_searchDomainEdit); + + + /**********控件显示**********/ + m_configLabel->setText(tr("IPv6 Config")); + m_addressLabel->setText(tr("Address")); + m_maskLabel->setText(tr("Netmask")); + m_gateWayLabel->setText(tr("Default Gateway")); + m_dnsServerLabel->setText(tr("DNS Server")); + m_searchDomainLabel->setText(tr("Search Domain")); //搜索域 + + m_ipv6ConfigCombox->addItem(tr("Auto(DHCP)"), AUTO_CONFIG); //"自动(DHCP)" + m_ipv6ConfigCombox->addItem(tr("Manual"), MANUAL_CONFIG); //"手动" + + // IP的正则格式限制 + QRegExp ipv6_rx("^\\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?\\s*$"); + QRegExpValidator *ipv6ExpVal = new QRegExpValidator(ipv6_rx, this); + m_ipv6addressEdit->setValidator(ipv6ExpVal); + m_gateWayEdit->setValidator(ipv6ExpVal); + m_dnsServerEdit->setValidator(ipv6ExpVal); + + QRegExp prefix_rx("\\b(?:(?:12[0-8]|1[0-1][0-9]|^[1-9][0-9]?$)\\.){3}(?:12[0-8]|1[0-1][0-9]|^[1-9][0-9]?$)\\b"); + m_netMaskEdit->setValidator(new QRegExpValidator(prefix_rx,this)); +} + +void VpnIpv6Page::initConnect() +{ + if (m_ipv6ConfigCombox->currentIndex() == AUTO_CONFIG) { + setManualEnabled(false); + } else if (m_ipv6ConfigCombox->currentIndex() == MANUAL_CONFIG) { + setManualEnabled(true); + } + connect(m_ipv6ConfigCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(onConfigChanged(int))); + connect(m_ipv6ConfigCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(setEnableOfConfirmBtn())); + connect(m_ipv6addressEdit, &QLineEdit::textChanged, this, &VpnIpv6Page::setEnableOfConfirmBtn); + connect(m_netMaskEdit, &QLineEdit::textChanged, this, &VpnIpv6Page::setEnableOfConfirmBtn); + connect(m_gateWayEdit, &QLineEdit::textChanged, this, &VpnIpv6Page::setEnableOfConfirmBtn); + connect(m_dnsServerEdit, &QLineEdit::textChanged, this, &VpnIpv6Page::setEnableOfConfirmBtn); + connect(m_searchDomainEdit, &QLineEdit::textChanged, this, &VpnIpv6Page::setEnableOfConfirmBtn); +} + +void VpnIpv6Page::setManualEnabled(bool state) +{ + m_addressLabel->setEnabled(state); + m_maskLabel->setEnabled(state); + m_gateWayLabel->setEnabled(state); + m_ipv6addressEdit->setEnabled(state); + m_netMaskEdit->setEnabled(state); + m_gateWayEdit->setEnabled(state); +} + +bool VpnIpv6Page::getIpv6EditState(QString text) +{ + if (text.isEmpty()) { + return true; + } + QRegExp rx("^\\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?\\s*$"); + + bool match = false; + match = rx.exactMatch(text); + + return match; +} + +bool VpnIpv6Page::checkConfirmBtnIsEnabled() +{ + if (m_ipv6ConfigCombox->currentIndex() == AUTO_CONFIG) { + return true; + } else { + if (m_ipv6addressEdit->text().isEmpty() || !getIpv6EditState(m_ipv6addressEdit->text())) { + qDebug() << "IPv6 address empty or invalid"; + return false; + } + + if (m_netMaskEdit->text().isEmpty()) { + qDebug() << "IPv6 netMask empty or invalid"; + return false; + } + if (m_gateWayEdit->text().isEmpty() || !getIpv6EditState(m_gateWayEdit->text())) { + qDebug() << "IPv6 gateway empty or invalid"; + return false; + } + } + return true; +} + +void VpnIpv6Page::setEnableOfConfirmBtn() +{ + Q_EMIT setIpv6PageState(checkConfirmBtnIsEnabled()); +} + +void VpnIpv6Page::onConfigChanged(int index) +{ + if (index == AUTO_CONFIG) { + m_ipv6addressEdit->clear(); + m_netMaskEdit->clear(); + m_gateWayEdit->clear(); + setManualEnabled(false); + } else if (index == MANUAL_CONFIG) { + setManualEnabled(true); + } +} diff --git a/src-vpn/frontend/vpndetails/vpnipv6page.h b/src-vpn/frontend/vpndetails/vpnipv6page.h new file mode 100644 index 00000000..21debab3 --- /dev/null +++ b/src-vpn/frontend/vpndetails/vpnipv6page.h @@ -0,0 +1,57 @@ +#ifndef VPNIPV6PAGE_H +#define VPNIPV6PAGE_H + +#include +#include +#include +#include +#include +#include + +#include "kyvpnconnectoperation.h" + +class VpnIpv6Page : public QFrame +{ + Q_OBJECT +public: + VpnIpv6Page(QWidget *parent = nullptr); + ~VpnIpv6Page() = default; + + void setVpnIpv6Info(const KyVpnConfig &vpnInfo); + void setDns(const QString &firstDns); + void setSearchDomain(const QString &searchDomain); + bool checkIsChanged(const KyVpnConfig &vpnInfo); + + void updateVpnIpv6Info(KyVpnConfig &vpnInfo); + +private: + QLabel *m_configLabel; + QLabel *m_addressLabel; + QLabel *m_maskLabel; + QLabel *m_gateWayLabel; + QLabel *m_dnsServerLabel; + QLabel *m_searchDomainLabel; + + QComboBox *m_ipv6ConfigCombox; + QLineEdit *m_ipv6addressEdit; + QLineEdit *m_netMaskEdit; + QLineEdit *m_gateWayEdit; + QLineEdit *m_dnsServerEdit; + QLineEdit *m_searchDomainEdit; + + void initUI(); + void initConnect(); + void setManualEnabled(bool state); + + bool getIpv6EditState(QString text); + bool checkConfirmBtnIsEnabled(); + +private Q_SLOTS: + void setEnableOfConfirmBtn(); + void onConfigChanged(int index); + +Q_SIGNALS: + void setIpv6PageState(bool); +}; + +#endif // VPNIPV6PAGE_H diff --git a/src-vpn/frontend/vpnobject.cpp b/src-vpn/frontend/vpnobject.cpp new file mode 100644 index 00000000..9b163f20 --- /dev/null +++ b/src-vpn/frontend/vpnobject.cpp @@ -0,0 +1,138 @@ +#include "vpnobject.h" +#include + +#include "ukuistylehelper/ukuistylehelper.h" + +vpnObject::vpnObject(QMainWindow *parent) : QMainWindow(parent) +{ + initUI(); + initTrayIcon(); + initDbusConnnect(); +} + +vpnObject::~vpnObject() +{ + if (m_vpnGsettings != nullptr) { + delete m_vpnGsettings; + m_vpnGsettings = nullptr; + } +} + +void vpnObject::initUI() +{ + m_vpnPage = new VpnPage(nullptr); + m_vpnPage->update(); + +} + +void vpnObject::initTrayIcon() +{ + m_vpnTrayIcon = new QSystemTrayIcon(this); + m_vpnTrayIcon->setToolTip(QString(tr("vpn tool"))); + m_vpnTrayIcon->setIcon(QIcon::fromTheme("ukui-vpn-symbolic")); + m_vpnTrayIcon->setVisible(true); + initVpnIconVisible(); + connect(m_vpnTrayIcon, &QSystemTrayIcon::activated, this, &vpnObject::onTrayIconActivated); +} + +void vpnObject::initVpnIconVisible() +{ + if (QGSettings::isSchemaInstalled(QByteArray(GSETTINGS_VPNICON_VISIBLE))) { + m_vpnGsettings = new QGSettings(QByteArray(GSETTINGS_VPNICON_VISIBLE)); + if (m_vpnGsettings->keys().contains(QString(VISIBLE))) { + m_vpnTrayIcon->setVisible(m_vpnGsettings->get(VISIBLE).toBool()); + connect(m_vpnGsettings, &QGSettings::changed, this, [=]() { + m_vpnTrayIcon->setVisible(m_vpnGsettings->get(VISIBLE).toBool()); + }); + } + } +} + +/** + * @brief vpnObject::onTrayIconActivated 点击托盘图标的槽函数 + */ +void vpnObject::onTrayIconActivated(QSystemTrayIcon::ActivationReason reason) +{ + switch(reason) { + case QSystemTrayIcon::Trigger: + if(m_vpnPage->isActiveWindow()) { + m_vpnPage->hide(); + } else { + onShowMainWindow(); + } + break; + + default: + break; + } +} + +void vpnObject::getVirtualList(QVector &vector) +{ + vector.clear(); + if (nullptr != m_vpnPage) { + m_vpnPage->getVirtualList(vector); + } +} + +//Vpn连接删除 +void vpnObject::deleteVpn(const QString &connUuid) +{ + m_vpnPage->deleteVpn(connUuid); +} + +//Vpn连接断开 +void vpnObject::activateVpn(const QString& connUuid) +{ + m_vpnPage->activateVpn(connUuid); +} +void vpnObject::deactivateVpn(const QString& connUuid) +{ + m_vpnPage->deactivateVpn(connUuid); +} + +void vpnObject::showDetailPage(const QString& connUuid) +{ + m_vpnPage->showDetailPage(connUuid); +} + + +void vpnObject::onShowMainWindow() +{ + kdk::UkuiStyleHelper::self()->removeHeader(m_vpnPage); + m_vpnPage->showUI(); +} + +void vpnObject::initDbusConnnect() +{ + connect(m_vpnPage, &VpnPage::activateFailed, this, &vpnObject::activateFailed); + connect(m_vpnPage, &VpnPage::deactivateFailed, this, &vpnObject::deactivateFailed); + + connect(m_vpnPage, &VpnPage::vpnAdd, this, &vpnObject::vpnAdd); + connect(m_vpnPage, &VpnPage::vpnRemove, this, &vpnObject::vpnRemove); + connect(m_vpnPage, &VpnPage::vpnUpdate, this, &vpnObject::vpnUpdate); + connect(m_vpnPage, &VpnPage::vpnActiveConnectionStateChanged, this, &vpnObject::vpnActiveConnectionStateChanged); + //模式切换 + QDBusConnection::sessionBus().connect(QString("com.kylin.statusmanager.interface"), + QString("/"), + QString("com.kylin.statusmanager.interface"), + QString("mode_change_signal"), this, SLOT(onTabletModeChanged(bool))); +} + +void vpnObject::onTabletModeChanged(bool mode) +{ + qDebug() << "TabletMode change" << mode; + Q_UNUSED(mode) + //模式切换时,隐藏主界面 + m_vpnPage->hide(); +} + +void vpnObject::showVpnAddWidget() +{ + if (m_vpnAddPage == nullptr) { + m_vpnAddPage = new vpnAddPage(); + connect(m_vpnAddPage, &vpnAddPage::closed, [&] () {m_vpnAddPage = nullptr;}); + m_vpnAddPage->show(); + } + m_vpnAddPage->raise(); +} diff --git a/src-vpn/frontend/vpnobject.h b/src-vpn/frontend/vpnobject.h new file mode 100644 index 00000000..20c3ab57 --- /dev/null +++ b/src-vpn/frontend/vpnobject.h @@ -0,0 +1,75 @@ +#ifndef VPNOBJECT_H +#define VPNOBJECT_H + +#include +#include +#include +#include +#include + +#include "vpnpage.h" +#include "vpnaddpage.h" +class VpnPage; + +#define VISIBLE "visible" +#define GSETTINGS_VPNICON_VISIBLE "org.ukui.kylin-nm.vpnicon" +//const QByteArray GSETTINGS_VPNICON_VISIBLE = "org.ukui.kylin-nm.vpnicon"; + + +class vpnObject : public QMainWindow +{ + Q_OBJECT +public: + explicit vpnObject(QMainWindow *parent = nullptr); + ~vpnObject(); + + void getVirtualList(QVector &vector); + //Vpn连接删除 + void deleteVpn(const QString &connUuid); + //有线连接断开 + void activateVpn(const QString& connUuid); + void deactivateVpn(const QString& connUuid); + + void showDetailPage(const QString& connUuid); + + void showVpnAddWidget(); + +private: + void initUI(); + void initTrayIcon(); + void initVpnIconVisible(); + void initDbusConnnect(); + + +private: + VpnPage *m_vpnPage = nullptr; + QSystemTrayIcon * m_vpnTrayIcon = nullptr; + QGSettings * m_vpnGsettings; //VPN配置文件 + double tran =1; + QGSettings *StyleSettings = nullptr; + QWidget * vpnWidget = nullptr; + + QDBusInterface * m_positionInterface = nullptr; + bool m_isShowInCenter = false; + + vpnAddPage *m_vpnAddPage = nullptr; + +public Q_SLOTS: + void onShowMainWindow(); + +private Q_SLOTS: + void onTrayIconActivated(QSystemTrayIcon::ActivationReason reason); + void onTabletModeChanged(bool mode); + + +Q_SIGNALS: + void vpnAdd(QStringList info); + void vpnRemove(QString dbusPath); + void vpnUpdate(QStringList info); + void vpnActiveConnectionStateChanged(QString uuid, int status); + void activateFailed(QString errorMessage); + void deactivateFailed(QString errorMessage); + void mainWindowVisibleChanged(const bool &visible); +}; + +#endif // VPNOBJECT_H diff --git a/src-vpn/kylin-vpn.desktop b/src-vpn/kylin-vpn.desktop new file mode 100644 index 00000000..464e2869 --- /dev/null +++ b/src-vpn/kylin-vpn.desktop @@ -0,0 +1,18 @@ +[Desktop Entry] +Encoding=UTF-8 +Name=Kylin VPN +Name[zh_CN]=麒麟VPN设置工具 +Name[zh_HK]=麒麟VPN設置工具 +Name[zh_TW]=麒麟VPN設置工具 +Icon=gnome-dev-ethernet +Comment=Beautiful Network Config Applet +Comment[zh_CN]=麒麟VPN设置工具,提供查看和简单设置功能,拥有美观的界面和舒适的操作. +Keywords=applet;vpn;network;network-manager; +Exec=/usr/bin/kylin-vpn +StartupNotify=false +Terminal=false +Type=Application +OnlyShowIn=UKUI +X-UKUI-AutoRestart=true +NoDisplay=true +X-UKUI-Autostart-Phase=Application diff --git a/src-vpn/main.cpp b/src-vpn/main.cpp new file mode 100644 index 00000000..f7f309e7 --- /dev/null +++ b/src-vpn/main.cpp @@ -0,0 +1,137 @@ +/* + * Copyright (C) 2020 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see +#include +#include "qt-single-application.h" +#include +#include +#include +#include +#if (QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)) +#include "xatom-helper.h" +#endif + +#include "vpnobject.h" + +#define LOG_IDENT "kylin_vpn" + +const QString QT_TRANSLATE_FILE = "/usr/share/qt5/translations/qt_zh_CN.qm"; + +void messageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg) +{ + QByteArray localMsg = msg.toLocal8Bit(); + QByteArray currentDateTime = QDateTime::currentDateTime().toString().toLocal8Bit(); + + bool showDebug = true; + QString logFilePath = QStandardPaths::writableLocation(QStandardPaths::HomeLocation) + "/.config/ukui/kylin-nm.log"; + FILE *log_file = nullptr; + + if (showDebug) { + log_file = fopen(logFilePath.toLocal8Bit().constData(), "a+"); + } + + const char *file = context.file ? context.file : ""; + const char *function = context.function ? context.function : ""; + switch (type) { + case QtDebugMsg: + if (!log_file) { + break; + } + fprintf(log_file, "Debug: %s: %s (%s:%u, %s)\n", currentDateTime.constData(), localMsg.constData(), file, context.line, function); + break; + case QtInfoMsg: + fprintf(log_file? log_file: stdout, "Info: %s: %s (%s:%u, %s)\n", currentDateTime.constData(), localMsg.constData(), file, context.line, function); + break; + case QtWarningMsg: + fprintf(log_file? log_file: stderr, "Warning: %s: %s (%s:%u, %s)\n", currentDateTime.constData(), localMsg.constData(), file, context.line, function); + break; + case QtCriticalMsg: + fprintf(log_file? log_file: stderr, "Critical: %s: %s (%s:%u, %s)\n", currentDateTime.constData(), localMsg.constData(), file, context.line, function); + break; + case QtFatalMsg: + fprintf(log_file? log_file: stderr, "Fatal: %s: %s (%s:%u, %s)\n", currentDateTime.constData(), localMsg.constData(), file, context.line, function); + break; + } + + if (log_file) + fclose(log_file); +} + +int main(int argc, char *argv[]) +{ + initUkuiLog4qt("kylin-vpn"); + + QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); + QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); + + QString id = QString("kylin-vpn"+ QLatin1String(getenv("DISPLAY"))); + QtSingleApplication a(id, argc, argv); + + QApplication::setQuitOnLastWindowClosed(false); + + QThread thread; + KyNetworkResourceManager *p_networkResource = KyNetworkResourceManager::getInstance(); + p_networkResource->moveToThread(&thread); + QObject::connect(&thread, SIGNAL(started()), p_networkResource, SLOT(onInitNetwork())); + thread.start(); + + // Internationalization + QString locale = QLocale::system().name(); + QTranslator trans_global; + qDebug() << "QLocale " << QLocale(); + if (trans_global.load(QLocale(), "kylin-vpn", "_", ":/translations/")) + { + a.installTranslator(&trans_global); + qDebug()<<"Translations load success"; + } else { + qWarning() << "Translations load fail"; + } + + QTranslator qtBaseTranslator; + if (qtBaseTranslator.load(QLocale(), "qt", "_", "/usr/share/qt5/translations/")) + { + a.installTranslator(&qtBaseTranslator); + qDebug()<<"QtBase Translations load success"; + } else { + qWarning() << "QtBase Translations load fail"; + } + + while (!p_networkResource->NetworkManagerIsInited()) { + ::usleep(1000); + } + + vpnObject vpnobject; + a.setActivationWindow(&vpnobject); + vpnobject.setProperty("useStyleWindowManager", false); //禁用拖动 + a.setWindowIcon(QIcon::fromTheme("ukui-vpn-symbolic")); + + VpnDbusAdaptor vpnAdaptor(&vpnobject); + Q_UNUSED(vpnAdaptor); + + auto connection = QDBusConnection::sessionBus(); + if (!connection.registerService("com.kylin.kylinvpn") + || !connection.registerObject("/com/kylin/kylinvpn", &vpnobject)) { + qCritical() << "QDbus register service failed reason:" << connection.lastError(); + } + + return a.exec(); +} diff --git a/src-vpn/org.ukui.kylin-vpn.switch.gschema.xml b/src-vpn/org.ukui.kylin-vpn.switch.gschema.xml new file mode 100644 index 00000000..47add632 --- /dev/null +++ b/src-vpn/org.ukui.kylin-vpn.switch.gschema.xml @@ -0,0 +1,9 @@ + + + + false + vpnicon visible + vpnicon visible.true is visible,false is invisible. + + + diff --git a/src-vpn/singleapplication/qt-local-peer.cpp b/src-vpn/singleapplication/qt-local-peer.cpp new file mode 100644 index 00000000..4a62537c --- /dev/null +++ b/src-vpn/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-vpn/singleapplication/qt-local-peer.h b/src-vpn/singleapplication/qt-local-peer.h new file mode 100644 index 00000000..883aec2a --- /dev/null +++ b/src-vpn/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-vpn/singleapplication/qt-locked-file-unix.cpp b/src-vpn/singleapplication/qt-locked-file-unix.cpp new file mode 100644 index 00000000..51472520 --- /dev/null +++ b/src-vpn/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-vpn/singleapplication/qt-locked-file.cpp b/src-vpn/singleapplication/qt-locked-file.cpp new file mode 100644 index 00000000..707b4cfa --- /dev/null +++ b/src-vpn/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-vpn/singleapplication/qt-locked-file.h b/src-vpn/singleapplication/qt-locked-file.h new file mode 100644 index 00000000..332d648e --- /dev/null +++ b/src-vpn/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-vpn/singleapplication/qt-single-application.cpp b/src-vpn/singleapplication/qt-single-application.cpp new file mode 100644 index 00000000..b829be13 --- /dev/null +++ b/src-vpn/singleapplication/qt-single-application.cpp @@ -0,0 +1,351 @@ +/**************************************************************************** +** +** 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 +#include "../vpnobject.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) { + m_activateWindow = 0; + m_peer = new QtLocalPeer(this, appId); + connect(m_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 m_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 m_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 m_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) { + m_activateWindow = aw; + if (activateOnMessage) + connect(m_peer, &QtLocalPeer::messageReceived, this, &QtSingleApplication::activateWindow); + else + disconnect(m_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 m_activateWindow; +} + + +/*! + 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 (m_activateWindow) { + if(this->applicationState() & Qt::ApplicationInactive) + { + m_activateWindow->setWindowState(m_activateWindow->windowState() & ~Qt::WindowMinimized); + m_activateWindow->raise(); + m_activateWindow->showNormal(); + m_activateWindow->activateWindow(); + } + else { + m_activateWindow->setWindowState(m_activateWindow->windowState() & Qt::WindowMinimized); + m_activateWindow->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-vpn/singleapplication/qt-single-application.h b/src-vpn/singleapplication/qt-single-application.h new file mode 100644 index 00000000..084b9b7c --- /dev/null +++ b/src-vpn/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 *m_peer; + QWidget *m_activateWindow; +}; + +#endif // QTSINGLEAPPLICATION_H diff --git a/src-vpn/singleapplication/qt-single-application.pri b/src-vpn/singleapplication/qt-single-application.pri new file mode 100644 index 00000000..0a4ca9ae --- /dev/null +++ b/src-vpn/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 diff --git a/src-vpn/src-vpn.pro b/src-vpn/src-vpn.pro new file mode 100644 index 00000000..a03ca247 --- /dev/null +++ b/src-vpn/src-vpn.pro @@ -0,0 +1,73 @@ +#------------------------------------------------- +# +# Project created by QtCreator 2018-10-19T15:29:47 +# +#------------------------------------------------- + +QT += core gui x11extras dbus KWindowSystem svg concurrent network + +greaterThan(QT_MAJOR_VERSION, 4): QT += widgets + +TARGET = kylin-vpn +TEMPLATE = app + +CONFIG += c++14 qt warn_on link_pkgconfig no_keywords +#CONFIG += release + +PKGCONFIG +=gio-2.0 glib-2.0 gio-unix-2.0 libnm libnma libsecret-1 gtk+-3.0 gsettings-qt libcap kysdk-qtwidgets kysdk-waylandhelper +PKGCONFIG +=kysdk-sysinfo + +INCLUDEPATH += /usr/include/KF5/NetworkManagerQt + +LIBS += -L/usr/lib/ -lgsettings-qt -lX11 -lKF5NetworkManagerQt -lukui-log4qt -lkysec + +target.path = /usr/bin +target.source += $$TARGET +desktop.path = /etc/xdg/autostart/ +desktop.files = kylin-vpn.desktop +gschema.files = org.ukui.kylin-vpn.switch.gschema.xml +gschema.path = /usr/share/glib-2.0/schemas/ + +INSTALLS += target \ + desktop \ + gschema \ + +# The following define makes your compiler emit warnings if you use +# any feature of Qt which has been marked as deprecated (the exact warnings +# depend on your compiler). Please consult the documentation of the +# deprecated API in order to know how to port your code away from it. +DEFINES += QT_DEPRECATED_WARNINGS + +# You can also make your code fail to compile if you use deprecated APIs. +# In order to do so, uncomment the following line. +# You can also select to disable deprecated APIs only up to a certain version of Qt. +#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 + +# QMAKE_CXXFLAGS += -Wno-unused-parameter +QMAKE_CPPFLAGS *= $(shell dpkg-buildflags --get CPPFLAGS) +QMAKE_CFLAGS *= $(shell dpkg-buildflags --get CFLAGS) +QMAKE_CXXFLAGS *= $(shell dpkg-buildflags --get CXXFLAGS) +QMAKE_LFLAGS *= $(shell dpkg-buildflags --get LDFLAGS) + +include(singleapplication/qt-single-application.pri) +include(backend/backend.pri) +include(frontend/frontend.pri) + +RESOURCES += \ + vpnqrc.qrc + +SOURCES += \ + main.cpp + +unix { + UI_DIR = .ui + MOC_DIR = .moc + OBJECTS_DIR = .obj +} + +DISTFILES += \ + org.ukui.kylin-vpn.switch.gschema.xml + +TRANSLATIONS += \ + translations/kylin-vpn_zh_CN.ts \ + translations/kylin-vpn_bo_CN.ts diff --git a/translations/kylin-nm_bo.qm b/src-vpn/translations/kylin-vpn_bo_CN.qm similarity index 100% rename from translations/kylin-nm_bo.qm rename to src-vpn/translations/kylin-vpn_bo_CN.qm diff --git a/src-vpn/translations/kylin-vpn_bo_CN.ts b/src-vpn/translations/kylin-vpn_bo_CN.ts new file mode 100644 index 00000000..ebebae3d --- /dev/null +++ b/src-vpn/translations/kylin-vpn_bo_CN.ts @@ -0,0 +1,144 @@ + + + + + SinglePage + + + Settings + + + + + Kylin VPN + + + + + kylin vpn applet desktop message + + + + + VpnListItem + + + Not connected + + + + + + Disconnect + + + + + + Connect + + + + + VpnPage + + + VPN + + + + + VPN Settings + + + + + vpnAddPage + + + create VPN + + + + + VPN Type + + + + + VPN Name + + + + + + Required + + + + + VPN Server + + + + + VPN + + + + + Auto Connection + + + + + Confirm + + + + + Cancel + + + + + vpnConfigPage + + + VPN Type + + + + + VpnDetail + + + + VPN + + + + + IPv4 + + + + + IPv6 + + + + + Advanced + + + + + vpnObject + + + vpn tool + + + + diff --git a/src-vpn/translations/kylin-vpn_zh_CN.qm b/src-vpn/translations/kylin-vpn_zh_CN.qm new file mode 100644 index 00000000..75c3ce3e Binary files /dev/null and b/src-vpn/translations/kylin-vpn_zh_CN.qm differ diff --git a/src-vpn/translations/kylin-vpn_zh_CN.ts b/src-vpn/translations/kylin-vpn_zh_CN.ts new file mode 100644 index 00000000..29c04c79 --- /dev/null +++ b/src-vpn/translations/kylin-vpn_zh_CN.ts @@ -0,0 +1,835 @@ + + + + + SinglePage + + + Settings + 设置 + + + + Kylin VPN + VPN工具 + + + + kylin vpn applet desktop message + vpn配置桌面提示 + + + + VpnAdvancedPage + + + MPPE encryption algorithm: + MPPE加密算法: + + + + Use Stateful encryption + 使用有状态加密 + + + + Send PPP echo packets + 发送PPP回显包 + + + + Authentication Mode: + 认证方式: + + + + PAP authentication + PAP认证 + + + + CHAP authentication + CHAP认证 + + + + MSCHAP authentication + MSCHAP认证 + + + + MSCHAP2 authentication + MSCHAP2认证 + + + + EAP authentication + EAP认证 + + + + Compression Mode: + 压缩方式: + + + + Allow BSD data compression + 允许BSD压缩 + + + + Allow Default data compression + 允许Default压缩 + + + + Allow TCP header compression + 允许TCP头压缩 + + + + Use protocol field compression negotiation + 使用协议域压缩协商 + + + + Use Address/Control compression + 使用地址/控制压缩 + + + + All Available + 任意 + + + + 128-bit + 128位 + + + + 40-bit + 40位 + + + + Use custom gateway port + 使用自定义网关端口 + + + + Use compression + 使用压缩 + + + + Use a TCP connection + 使用TCP连接 + + + + Set virtual device type + 设置虚拟设备类型 + + + + Set virtual device name + 设置虚拟设备名称 + + + + Limit TCP Maximum Segment Size(MSS) + 限制TCP最大段尺寸(MSS) + + + + Randomize remote hosts + 随机化远程主机 + + + + IPv6 tun link + IPv6 tun连接 + + + + Specify ping interval + 指定Ping周期 + + + + Specify exit or restart ping + 指定退出或重启的Ping + + + + Specify max routes + 指定路由上限 + + + + Infinite retry on error + 出错时无限重试 + + + + Use custom key size + 使用自定义密钥大小 + + + + Choose + 选择 + + + + Use custom renegotiation interval + 使用自定义重协商间隔 + + + + Use custom tunnel Maximum Transmission Umit(MTU) + 使用自定义隧道最大单元传输(MTU) + + + + Use custom UDP fragment size + 使用自定义UDP分片大小 + + + + Accept authenticated packets from any address (Float) + 接受来自任何地址(Float)已通过身份验证的数据包 + + + + Subject Match + 主题匹配 + + + + Key File + 密钥文件 + + + + Key Direction + 密钥方向 + + + + Server Address + 服务器地址 + + + + Port + 端口 + + + + Proxy USername + 代理用户名 + + + + Proxy Password + 代理密码 + + + + General + 常规 + + + + TLS settings + TLS设置 + + + + Server Certificate Check + 服务器证书检验 + + + + Use the previous authentication end (server) certificate + 使用前面验证端(服务器)证书 + + + + Verify peer (server) certificate nsCertType specification + 验证对等点(服务器)证书nsCertType指定 + + + + Mode + 模式 + + + + Proxies + 代理 + + + + Proxy Type + 代理类型 + + + + Security + 安全 + + + + HMAC Authentication + HMAC认证 + + + + Input content + 输入内容 + + + + No + + + + + Self-adaption + 自适应 + + + + Automatic + 自动 + + + + Exit + 退出 + + + + Restart + 重启 + + + + Don't verify certificate identification + 不验证证书标识 + + + + Verify the entire subject exactly + 确切地验证整个主题 + + + + Verify name exactly + 精确验证名称 + + + + Verify name by prefix + 按前缀验证名称 + + + + + Server + 服务器 + + + + + Client + 客户端 + + + + + + None + + + + + TLS-Certification + TLS-认证 + + + + TLS-Encryption + TLS-加密 + + + + Not Required + 不需要 + + + + Default + 默认 + + + + Options: + 选项: + + + + Request an inner IP address + 请求内部IP地址 + + + + Enforce UDP encapsulation + 强制UDP封装 + + + + Use IP compression + 使用IP压缩 + + + + Enable custom password suggestions + 启用自定义密码建议 + + + + VpnConfigPage + + + Type + 类型 + + + + Name + 名称 + + + + Static Key + 静态密钥 + + + + Local IP + 本地IP地址 + + + + Remote IP + 远程IP地址 + + + + PIN Code + PIN码 + + + + + + Password + 密码 + + + + NT Domain + NT域 + + + + Server Address + 服务器地址 + + + + Authentication Mode + 认证方式 + + + + CA Certificate + CA证书 + + + + User Certificate + 用户证书 + + + + Key Direction + 密钥方向 + + + + Private Key + 私钥 + + + + Private Key Password + 私有密钥密码 + + + + + Password Options + 密码选项 + + + + Username + 用户名 + + + + Notice: +If key direction is used, it must be opposite to the VPN side used. If '1' is used, the connection must use '0'. If you are not sure which value to use, please contact your system administrator. + 注意: +如果使用了密钥方向,它必须和使用的VPN端相反。如果使用了“1”,连接必须要使用“0”。如果不确定使用哪个值,请联系您的系统管理员。 + + + + + + + Choose + 选择 + + + + None + + + + + + Save password only for this user + 仅对当前用户保存密码 + + + + + Save password for all users + 为所有用户保存密码 + + + + + Ask password every time + 每次都询问 + + + + + Don't require a password + 不需要密码 + + + + + Required + 必填 + + + + Certificate(TLS) + 证书(TLS) + + + + Static key + 静态密钥 + + + + Password and certificate(TLS) + 密码和证书(TLS) + + + + Certificate/Private key + 证书/私钥 + + + + Certificate/ssh-agent + 证书/ssh-agent + + + + Smart card + 智能卡 + + + + Choose a private key + 选择私钥 + + + + + Key Files (*.key *.pem *.der *.p12 *.pfx) + 私钥文件(*.key *.pem *.der *.p12 *.pfx) + + + + Choose a CA certificate + 选择CA证书 + + + + + CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) + CA文件 (*.pem *.der *.p12 *.crt *.cer *.pfx) + + + + Choose a User certificate + 选择用户证书 + + + + Choose a Static key + 选择静态密钥 + + + + VpnIpv4Page + + + IPv4 Config + IPv4配置 + + + + Address + 地址 + + + + Netmask + 子网掩码 + + + + Default Gateway + 默认网关 + + + + DNS Server + DNS服务器 + + + + Search Domain + 搜索域 + + + + DHCP Client ID + DHCP客户端ID + + + + Auto(DHCP) + 自动(DHCP) + + + + Manual + 手动 + + + + VpnIpv6Page + + + IPv6 Config + IPv6配置 + + + + Address + 地址 + + + + Netmask + 子网掩码 + + + + Default Gateway + 默认网关 + + + + DNS Server + DNS服务器 + + + + Search Domain + 搜索域 + + + + Auto(DHCP) + 自动(DHCP) + + + + Manual + 手动 + + + + VpnListItem + + + Not connected + 未连接 + + + + + Disconnect + 断开 + + + + + Connect + 连接 + + + + VpnPage + + + VPN + + + + + VPN Settings + VPN设置 + + + + vpnAddPage + + + create VPN + 创建VPN + + + + VPN Type + VPN类型 + + + + VPN Name + VPN名称 + + + + + Required + 必填 + + + + VPN Server + 服务器地址 + + + + VPN + + + + + Auto Connection + 自动连接 + + + + Confirm + 确定 + + + + Cancel + 取消 + + + + vpnConfigPage + + VPN Type + VPN类型 + + + + VpnDetail + + + + VPN + + + + + IPv4 + + + + + + IPv6 + + + + + Advanced + 高级 + + + + Auto Connection + 自动连接 + + + + Cancel + 取消 + + + + Confirm + 确定 + + + + vpnObject + + + vpn tool + VPN工具 + + + diff --git a/src-vpn/vpnqrc.qrc b/src-vpn/vpnqrc.qrc new file mode 100644 index 00000000..13fa41d8 --- /dev/null +++ b/src-vpn/vpnqrc.qrc @@ -0,0 +1,6 @@ + + + translations/kylin-vpn_zh_CN.qm + translations/kylin-vpn_bo_CN.qm + + diff --git a/src/backend/backend.pri b/src/backend/backend.pri index 10314e58..feb4853f 100644 --- a/src/backend/backend.pri +++ b/src/backend/backend.pri @@ -4,7 +4,6 @@ include(dbus-interface/dbus-interface.pri) HEADERS += \ $$PWD/dbusadaptor.h \ - $$PWD/vpndbusadaptor.h \ $$PWD/kylinarping.h \ $$PWD/kylinipv4arping.h \ $$PWD/kylinipv6arping.h \ @@ -14,7 +13,6 @@ HEADERS += \ SOURCES += \ $$PWD/dbusadaptor.cpp \ - $$PWD/vpndbusadaptor.cpp \ $$PWD/kylinipv4arping.cpp \ $$PWD/kylinipv6arping.cpp \ $$PWD/sysdbusregister.cpp \ diff --git a/src/backend/dbus-interface/dbus-interface.pri b/src/backend/dbus-interface/dbus-interface.pri index 056901df..679a1934 100644 --- a/src/backend/dbus-interface/dbus-interface.pri +++ b/src/backend/dbus-interface/dbus-interface.pri @@ -21,6 +21,7 @@ HEADERS += \ $$PWD/kywirelessconnectoperation.h \ $$PWD/kywirelessnetitem.h \ $$PWD/kywirelessnetresource.h \ + $$PWD/kyvpnconnectoperation.h \ $$PWD/nm-macros-internal.h SOURCES += \ @@ -42,5 +43,6 @@ SOURCES += \ $$PWD/kylinwiredconnectoperation.cpp \ $$PWD/kywirelessconnectoperation.cpp \ $$PWD/kywirelessnetitem.cpp \ + $$PWD/kyvpnconnectoperation.cpp \ $$PWD/kywirelessnetresource.cpp diff --git a/src/backend/dbus-interface/gsystem-local-alloc.h b/src/backend/dbus-interface/gsystem-local-alloc.h index b74cc0aa..54ea4818 100644 --- a/src/backend/dbus-interface/gsystem-local-alloc.h +++ b/src/backend/dbus-interface/gsystem-local-alloc.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef __GSYSTEM_LOCAL_ALLOC_H__ #define __GSYSTEM_LOCAL_ALLOC_H__ diff --git a/src/backend/dbus-interface/kyenterpricesettinginfo.cpp b/src/backend/dbus-interface/kyenterpricesettinginfo.cpp index 37a0e957..9ff68dd5 100644 --- a/src/backend/dbus-interface/kyenterpricesettinginfo.cpp +++ b/src/backend/dbus-interface/kyenterpricesettinginfo.cpp @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "kyenterpricesettinginfo.h" void assembleEapMethodTlsSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodTlsInfo &info) diff --git a/src/backend/dbus-interface/kyenterpricesettinginfo.h b/src/backend/dbus-interface/kyenterpricesettinginfo.h index 1f7d144a..593b504a 100644 --- a/src/backend/dbus-interface/kyenterpricesettinginfo.h +++ b/src/backend/dbus-interface/kyenterpricesettinginfo.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef KYENTERPRICESETTINGINFO_H #define KYENTERPRICESETTINGINFO_H diff --git a/src/backend/dbus-interface/kylinactiveconnectresource.cpp b/src/backend/dbus-interface/kylinactiveconnectresource.cpp index e56de5ac..07b13d09 100644 --- a/src/backend/dbus-interface/kylinactiveconnectresource.cpp +++ b/src/backend/dbus-interface/kylinactiveconnectresource.cpp @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "kylinutil.h" #include "kylinactiveconnectresource.h" #include "kywirelessconnectoperation.h" @@ -88,6 +107,7 @@ KyConnectItem *KyActiveConnectResourse::getActiveConnectionByUuid(QString connec continue; } else { isFind = true; + break; } } @@ -715,3 +735,47 @@ bool KyActiveConnectResourse::checkWirelessStatus(NetworkManager::ActiveConnecti return false; } + +QString KyActiveConnectResourse::getAcitveConnectionPathByUuid(QString connectUuid) +{ + NetworkManager::ActiveConnection::Ptr activeAonnectPtr = nullptr; + + activeAonnectPtr = m_networkResourceInstance->getActiveConnect(connectUuid); + if (nullptr == activeAonnectPtr) { + return nullptr; + } + + return activeAonnectPtr->path(); +} + +int KyActiveConnectResourse::getAcivateWifiSignal() +{ + int signalStrength = 0; + KyNetworkDeviceResourse devResource; + QStringList devList; + devResource.getNetworkDeviceList(NetworkManager::Device::Type::Wifi, devList); + + for (int i = 0; i < devList.size(); ++i) { + + NetworkManager::Device::Ptr connectDevice = + m_networkResourceInstance->findDeviceInterface(devList.at(i)); + + if (nullptr == connectDevice || !connectDevice->isValid()) { + qWarning()<< LOG_FLAG <<"getDeviceActiveAPInfo failed, the device" << devList.at(i) << "is not existed"; + continue; + } + + if (connectDevice->type() == NetworkManager::Device::Wifi) { + NetworkManager::WirelessDevice *wirelessDevicePtr = + qobject_cast(connectDevice.data()); + NetworkManager::AccessPoint::Ptr apPtr = wirelessDevicePtr->activeAccessPoint(); + if (apPtr.isNull()) { + continue; + } + signalStrength = apPtr->signalStrength(); + break; + } + } + + return signalStrength; +} diff --git a/src/backend/dbus-interface/kylinactiveconnectresource.h b/src/backend/dbus-interface/kylinactiveconnectresource.h index db781917..6c648fa6 100644 --- a/src/backend/dbus-interface/kylinactiveconnectresource.h +++ b/src/backend/dbus-interface/kylinactiveconnectresource.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef KYLINACTIVECONNECTRESOURCE_H #define KYLINACTIVECONNECTRESOURCE_H @@ -40,6 +59,8 @@ public: bool connectionIsVirtual(QString uuid); bool wiredConnectIsActived(); bool checkWirelessStatus(NetworkManager::ActiveConnection::State state); + QString getAcitveConnectionPathByUuid(QString uuid); + int getAcivateWifiSignal(); private: void getActiveConnectIp(NetworkManager::ActiveConnection::Ptr activeConnectPtr, @@ -56,7 +77,7 @@ private: KyBluetoothConnectItem *getBtActiveConnectItem(NetworkManager::ActiveConnection::Ptr activeConnectPtr); KyApConnectItem *getApActiveConnectItem(NetworkManager::ActiveConnection::Ptr activeConnectPtr); -signals: +Q_SIGNALS: void activeConnectAdd(QString activeConnectUuid); void updateActiveConnect(QString activeConnectUuid); void activeConnectRemove(QString activeConnectUuid); diff --git a/src/backend/dbus-interface/kylinagent.h b/src/backend/dbus-interface/kylinagent.h index 82ec3445..8b11f044 100644 --- a/src/backend/dbus-interface/kylinagent.h +++ b/src/backend/dbus-interface/kylinagent.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef __KYLINNMANGENT_H__ #define __KYLINNMANGENT_H__ diff --git a/src/backend/dbus-interface/kylinagentinterface.h b/src/backend/dbus-interface/kylinagentinterface.h index 2a097923..972033e7 100644 --- a/src/backend/dbus-interface/kylinagentinterface.h +++ b/src/backend/dbus-interface/kylinagentinterface.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef __KYLINAGENTINTERFACE_H__ #define __KYLINAGENTINTERFACE_H__ #ifdef __cplusplus diff --git a/src/backend/dbus-interface/kylinapconnectitem.cpp b/src/backend/dbus-interface/kylinapconnectitem.cpp index 1f8945d7..ab3052d8 100644 --- a/src/backend/dbus-interface/kylinapconnectitem.cpp +++ b/src/backend/dbus-interface/kylinapconnectitem.cpp @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "kylinapconnectitem.h" diff --git a/src/backend/dbus-interface/kylinapconnectitem.h b/src/backend/dbus-interface/kylinapconnectitem.h index f7a1e27d..63f69b87 100644 --- a/src/backend/dbus-interface/kylinapconnectitem.h +++ b/src/backend/dbus-interface/kylinapconnectitem.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef KYLINAPCONNECTITEM_H #define KYLINAPCONNECTITEM_H diff --git a/src/backend/dbus-interface/kylinbluetoothconnectitem.cpp b/src/backend/dbus-interface/kylinbluetoothconnectitem.cpp index 1fc2897b..dd9dd643 100644 --- a/src/backend/dbus-interface/kylinbluetoothconnectitem.cpp +++ b/src/backend/dbus-interface/kylinbluetoothconnectitem.cpp @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "kylinbluetoothconnectitem.h" diff --git a/src/backend/dbus-interface/kylinbluetoothconnectitem.h b/src/backend/dbus-interface/kylinbluetoothconnectitem.h index 3bedeb21..0b485d0f 100644 --- a/src/backend/dbus-interface/kylinbluetoothconnectitem.h +++ b/src/backend/dbus-interface/kylinbluetoothconnectitem.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef KYLINBLUETOOTHCONNECTITEM_H #define KYLINBLUETOOTHCONNECTITEM_H diff --git a/src/backend/dbus-interface/kylinconnectitem.cpp b/src/backend/dbus-interface/kylinconnectitem.cpp index 011dee63..27b573e5 100644 --- a/src/backend/dbus-interface/kylinconnectitem.cpp +++ b/src/backend/dbus-interface/kylinconnectitem.cpp @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "kylinconnectitem.h" diff --git a/src/backend/dbus-interface/kylinconnectitem.h b/src/backend/dbus-interface/kylinconnectitem.h index 4cdaa1ae..d8fb0722 100644 --- a/src/backend/dbus-interface/kylinconnectitem.h +++ b/src/backend/dbus-interface/kylinconnectitem.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef KYLINCONNECTITEM_H #define KYLINCONNECTITEM_H diff --git a/src/backend/dbus-interface/kylinconnectoperation.cpp b/src/backend/dbus-interface/kylinconnectoperation.cpp index daf8234f..023c613c 100644 --- a/src/backend/dbus-interface/kylinconnectoperation.cpp +++ b/src/backend/dbus-interface/kylinconnectoperation.cpp @@ -201,7 +201,7 @@ void KyConnectOperation::activateConnection(const QString connectUuid, const QSt if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("activate connection failed: ") + watcher->error().message(); qWarning()<activateConnectionError(errorMessage); + Q_EMIT this->activateConnectionError(errorMessage); } else { qWarning()<<"active wired connect complete."; } @@ -237,7 +237,7 @@ void KyConnectOperation::deactivateConnection(const QString activeConnectName, c + watcher->error().message(); qWarning()<deactivateConnectionError(errorMessage); + Q_EMIT this->deactivateConnectionError(errorMessage); } else { qWarning() << "deactive connect operation finished" << activateConnectPtr->connection()->name(); } diff --git a/src/backend/dbus-interface/kylinconnectoperation.h b/src/backend/dbus-interface/kylinconnectoperation.h index fc735d7e..8fae0bc2 100644 --- a/src/backend/dbus-interface/kylinconnectoperation.h +++ b/src/backend/dbus-interface/kylinconnectoperation.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef KYLINCONNECTOPERATION_H #define KYLINCONNECTOPERATION_H @@ -30,7 +49,7 @@ public: bool bAutoConnect); inline void errorProcess(QString errorMessage); -signals: +Q_SIGNALS: void createConnectionError(QString errorMessage); void updateConnectionError(QString errorMessage); void deleteConnectionError(QString errorMessage); diff --git a/src/backend/dbus-interface/kylinconnectresource.cpp b/src/backend/dbus-interface/kylinconnectresource.cpp index 6f52488b..489cded3 100644 --- a/src/backend/dbus-interface/kylinconnectresource.cpp +++ b/src/backend/dbus-interface/kylinconnectresource.cpp @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "kylinconnectresource.h" #include "kywirelessconnectoperation.h" @@ -23,11 +42,36 @@ static bool subLanListSort(const KyConnectItem* info1, const KyConnectItem* info return result; } +static bool subVpnListSort(const KyConnectItem* info1, const KyConnectItem* info2) +{ + if (info1->m_connectState != info2->m_connectState) { + if (info1->m_connectState == 2) { + return true; + } + + if (info2->m_connectState == 2) { + return false; + } + } + QString name1 = info1->m_connectName; + QString name2 = info2->m_connectName; + bool result = true; + if (QString::compare(name1, name2, Qt::CaseInsensitive) > 0) { + result = false; + } + return result; +} + static void lanListSort(QList &list) { qSort(list.begin(), list.end(), subLanListSort); } +static void vpnListSort(QList &list) +{ + qSort(list.begin(), list.end(), subVpnListSort); +} + KyConnectResourse::KyConnectResourse(QObject *parent) : QObject(parent) { m_networkResourceInstance = KyNetworkResourceManager::getInstance(); @@ -106,7 +150,7 @@ bool KyConnectResourse::isActiveDevice(QString conUuid, QString devName) return false; } -KyConnectItem * KyConnectResourse::getConnectionItemByUuid(QString connectUuid, bool checkActive) +KyConnectItem * KyConnectResourse::getConnectionItemByUuid(QString connectUuid) { NetworkManager::Connection::Ptr connectPtr = m_networkResourceInstance->getConnect(connectUuid); @@ -116,7 +160,7 @@ KyConnectItem * KyConnectResourse::getConnectionItemByUuid(QString connectUuid, return nullptr; } - if (checkActive && m_networkResourceInstance->isActiveConnection(connectPtr->uuid())) { + if (m_networkResourceInstance->isActiveConnection(connectPtr->uuid())) { qDebug()<<"[KyConnectResourse]"<name()<<"is active connection"; return nullptr; } @@ -130,6 +174,25 @@ KyConnectItem * KyConnectResourse::getConnectionItemByUuid(QString connectUuid, return nullptr; } +KyConnectItem * KyConnectResourse::getConnectionItemByUuidWithoutActivateChecking(QString connectUuid) +{ + NetworkManager::Connection::Ptr connectPtr = + m_networkResourceInstance->getConnect(connectUuid); + + if (nullptr == connectPtr) { + qWarning()<< "[KyConnectResourse]" <<"get connect failed, connect uuid"<dumpInfo(); + return connectItem; + } + + return nullptr; +} + KyConnectItem * KyConnectResourse::getConnectionItemByUuid(QString connectUuid, QString deviceName) { NetworkManager::Connection::Ptr connectPtr = @@ -211,6 +274,10 @@ void KyConnectResourse::getVpnAndVirtualConnections(QList &conn connectPtr = nullptr; } + + if (connectItemList.size() > 1) { + vpnListSort(connectItemList); + } } void KyConnectResourse::getConnectionList(QString deviceName, @@ -656,11 +723,13 @@ KyApConnectItem *KyConnectResourse::getApConnectItem(NetworkManager::Connection: return nullptr; } +#ifdef CHECKDEVICE KyNetworkDeviceResourse deviceResource; if (!deviceResource.wirelessDeviceIsExist(settingPtr->interfaceName())) { qDebug() << "[KyConnectResourse]" <<"get ap item failed, the ap device is not exist yet"; return nullptr; } +#endif QByteArray rawSsid = wirelessSetting->ssid(); @@ -703,6 +772,18 @@ KyApConnectItem *KyConnectResourse::getApConnectionByUuid(QString connectUuid) return connectItem; } +QString KyConnectResourse::getApConnectionPathByUuid(QString connectUuid) +{ + NetworkManager::Connection::Ptr connectPtr = nullptr; + + connectPtr = m_networkResourceInstance->getConnect(connectUuid); + if (nullptr == connectPtr) { + return nullptr; + } + + return connectPtr->path(); +} + void KyConnectResourse::getApConnections(QList &apConnectItemList) { QList apActiveConnectItemList; diff --git a/src/backend/dbus-interface/kylinconnectresource.h b/src/backend/dbus-interface/kylinconnectresource.h index fb8ece0a..8c1228a2 100644 --- a/src/backend/dbus-interface/kylinconnectresource.h +++ b/src/backend/dbus-interface/kylinconnectresource.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef KYLINCONNECTRESOURCE_H #define KYLINCONNECTRESOURCE_H @@ -18,7 +37,8 @@ public: ~KyConnectResourse(); public: - KyConnectItem *getConnectionItemByUuid(QString connectUuid, bool checkActive = true); + KyConnectItem *getConnectionItemByUuid(QString connectUuid); + KyConnectItem *getConnectionItemByUuidWithoutActivateChecking(QString connectUuid); KyConnectItem *getConnectionItemByUuid(QString connectUuid, QString deviceName); void getVpnAndVirtualConnections(QList &connectItemList); void getConnectionList(QString deviceName, @@ -29,6 +49,8 @@ public: void getBluetoothConnections(QList &bluetoothConnectItemList); void getApConnections(QList &apConnectItemList); KyApConnectItem *getApConnectionByUuid(QString connectUuid); + QString getApConnectionPathByUuid(QString connectUuid); + QString getApAcitveConnectionPathByUuid(QString connectUuid); void getConnectionSetting(QString connectUuid, KyConnectSetting &connectSetting); bool getInterfaceByUuid(QString &deviceName, const QString connUuid); @@ -59,7 +81,7 @@ private: void getIpv6ConnectSetting(NetworkManager::Ipv6Setting::Ptr &ipv6Setting, KyConnectSetting &connectSetting); -signals: +Q_SIGNALS: void connectionAdd(QString uuid); void connectionUpdate(QString uuid); void connectionRemove(QString path); diff --git a/src/backend/dbus-interface/kylinconnectsetting.cpp b/src/backend/dbus-interface/kylinconnectsetting.cpp index f77c74a0..22700aad 100644 --- a/src/backend/dbus-interface/kylinconnectsetting.cpp +++ b/src/backend/dbus-interface/kylinconnectsetting.cpp @@ -89,8 +89,6 @@ void KyConnectSetting::ipv6AddressConstruct(QString &ipv6Address, QString &ipv6N nmIpv6Address.setPrefixLength(ipv6NetMask.toInt()); m_ipv6Address.clear(); m_ipv6Address << nmIpv6Address; - - return ; } void KyConnectSetting::ipv4DnsConstruct(QList &ipv4DnsList) diff --git a/src/backend/dbus-interface/kylinnetworkdeviceresource.cpp b/src/backend/dbus-interface/kylinnetworkdeviceresource.cpp index f534fb48..6eb71beb 100644 --- a/src/backend/dbus-interface/kylinnetworkdeviceresource.cpp +++ b/src/backend/dbus-interface/kylinnetworkdeviceresource.cpp @@ -1,12 +1,34 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "kylinnetworkdeviceresource.h" #include "kywirelessnetitem.h" +#include "kylinutil.h" #define VIRTURAL_DEVICE_PATH "/sys/devices/virtual/net" #define LOG_FLAG "KyNetworkDeviceResourse" KyNetworkDeviceResourse::KyNetworkDeviceResourse(QObject *parent) : QObject(parent) { + qRegisterMetaType("NetworkManager::Device::State"); + qRegisterMetaType("NetworkManager::Device::StateChangeReason"); m_networkResourceInstance = KyNetworkResourceManager::getInstance(); m_deviceMap.clear(); @@ -14,11 +36,14 @@ KyNetworkDeviceResourse::KyNetworkDeviceResourse(QObject *parent) : QObject(pare initDeviceMap(); connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceAdd, - this, &KyNetworkDeviceResourse::onDeviceAdd, Qt::ConnectionType::DirectConnection); + this, &KyNetworkDeviceResourse::onDeviceAdd/*, Qt::ConnectionType::DirectConnection*/); connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceRemove, - this, &KyNetworkDeviceResourse::onDeviceRemove, Qt::ConnectionType::DirectConnection); + this, &KyNetworkDeviceResourse::onDeviceRemove/*, Qt::ConnectionType::DirectConnection*/); connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceUpdate, - this, &KyNetworkDeviceResourse::onDeviceUpdate, Qt::ConnectionType::DirectConnection); + this, &KyNetworkDeviceResourse::onDeviceUpdate/*, Qt::ConnectionType::DirectConnection*/); + + connect(m_networkResourceInstance, &KyNetworkResourceManager::stateChanged, + this, &KyNetworkDeviceResourse::stateChanged/*, Qt::ConnectionType::DirectConnection*/); connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceCarrierChanage, this, &KyNetworkDeviceResourse::carrierChanage); @@ -28,7 +53,8 @@ KyNetworkDeviceResourse::KyNetworkDeviceResourse(QObject *parent) : QObject(pare this, &KyNetworkDeviceResourse::deviceMacAddressChanage); connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceActiveChanage, this, &KyNetworkDeviceResourse::deviceActiveChanage); - + connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceManagedChange, + this, &KyNetworkDeviceResourse::deviceManagedChange); } KyNetworkDeviceResourse::~KyNetworkDeviceResourse() @@ -186,6 +212,42 @@ void KyNetworkDeviceResourse::setDeviceRefreshRate(QString deviceName, int ms) return; } +qulonglong KyNetworkDeviceResourse::getDeviceRxRefreshRate(QString deviceName) +{ + NetworkManager::Device::Ptr connectDevice = + m_networkResourceInstance->findDeviceInterface(deviceName); + if (connectDevice->isValid()) { + NetworkManager::DeviceStatistics::Ptr deviceStatistics = connectDevice->deviceStatistics(); + qulonglong rx = 0; + rx = deviceStatistics->rxBytes(); + if (rx != 0) { + return rx; + } else { + qDebug() << "connectDevice is invalid we do not get rxrate"; + } + } + + return 0; +} + +qulonglong KyNetworkDeviceResourse::getDeviceTxRefreshRate(QString deviceName) +{ + NetworkManager::Device::Ptr connectDevice = + m_networkResourceInstance->findDeviceInterface(deviceName); + if (connectDevice->isValid()) { + NetworkManager::DeviceStatistics::Ptr deviceStatistics = connectDevice->deviceStatistics(); + qulonglong tx = 0; + tx = deviceStatistics->txBytes(); + if (tx != 0){ + return tx; + } else { + qDebug() << "connectDevice is invalid we do not get txrate"; + } + } + + return 0; +} + bool KyNetworkDeviceResourse::getActiveConnectionInfo(const QString devName, int &signalStrength, QString &uni, QString &secuType) { signalStrength = 0; @@ -289,16 +351,14 @@ int KyNetworkDeviceResourse::getWirelessDeviceCapability(const QString deviceNam void KyNetworkDeviceResourse::onDeviceAdd(QString deviceName, QString uni, NetworkManager::Device::Type deviceType) { m_deviceMap.insert(uni, deviceName); - emit deviceAdd(deviceName, deviceType); - + Q_EMIT deviceAdd(deviceName, deviceType); return; } void KyNetworkDeviceResourse::onDeviceRemove(QString deviceName, QString uni) { m_deviceMap.remove(uni); - emit deviceRemove(deviceName); - + Q_EMIT deviceRemove(deviceName); return; } @@ -308,7 +368,7 @@ void KyNetworkDeviceResourse::onDeviceUpdate(QString interface, QString dbusPath if (m_deviceMap[dbusPath] != interface) { QString oldName = m_deviceMap[dbusPath]; m_deviceMap[dbusPath] = interface; - emit deviceNameUpdate(oldName, interface); + Q_EMIT deviceNameUpdate(oldName, interface); } } @@ -339,3 +399,29 @@ bool KyNetworkDeviceResourse::deviceIsWired(QString deviceName) return false; } + +void KyNetworkDeviceResourse::setDeviceManaged(QString devName, bool managed) +{ + QString dbusPath; + NetworkManager::Device::Ptr connectDevice = + m_networkResourceInstance->findDeviceInterface(devName); + if (connectDevice->isValid()) { + dbusPath = connectDevice->uni(); + } else { + qWarning()<<"[KyNetworkDeviceResourse] can not find device " << devName; + return; + } + setDeviceManagedByGDbus(dbusPath, managed); +} + +bool KyNetworkDeviceResourse::getDeviceManaged(QString deviceName) +{ + NetworkManager::Device::Ptr connectDevice = + m_networkResourceInstance->findDeviceInterface(deviceName); + if (connectDevice != nullptr && connectDevice->isValid()) { + return connectDevice->managed(); + } else { + qWarning()<<"[KyNetworkDeviceResourse] can not find device " << deviceName; + return false; + } +} diff --git a/src/backend/dbus-interface/kylinnetworkdeviceresource.h b/src/backend/dbus-interface/kylinnetworkdeviceresource.h index 638b00e7..4ad5881a 100644 --- a/src/backend/dbus-interface/kylinnetworkdeviceresource.h +++ b/src/backend/dbus-interface/kylinnetworkdeviceresource.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef KYLINNETORKDEVICERESOURCE_H #define KYLINNETORKDEVICERESOURCE_H @@ -13,7 +32,7 @@ public: explicit KyNetworkDeviceResourse(QObject *parent = nullptr); ~KyNetworkDeviceResourse(); -signals: +Q_SIGNALS: void deviceAdd(QString deviceName, NetworkManager::Device::Type deviceType); void deviceRemove(QString deviceName); void deviceUpdate(QString deviceName); @@ -25,8 +44,10 @@ signals: void deviceBitRateChanage(QString deviceName, int bitRate); void deviceMacAddressChanage(QString deviceName, const QString &hwAddress); void deviceActiveChanage(QString deviceName, bool deivceActive); + void deviceManagedChange(QString deviceName, bool managed); + void stateChanged(NetworkManager::Device::State newstate, NetworkManager::Device::State oldstate, NetworkManager::Device::StateChangeReason reason); -public slots: +public Q_SLOTS: void onDeviceAdd(QString deviceName, QString uni, NetworkManager::Device::Type deviceType); void onDeviceRemove(QString deviceName, QString uni); void onDeviceUpdate(QString interface, QString dbusPath); @@ -45,6 +66,12 @@ public: void setDeviceRefreshRate(QString deviceName, int ms); + void setDeviceManaged(QString devName, bool managed); + bool getDeviceManaged(QString devName); + + qulonglong getDeviceRxRefreshRate(QString deviceName); + qulonglong getDeviceTxRefreshRate(QString deviceName); + private: KyWiredConnectOperation wiredOperation; KyNetworkResourceManager *m_networkResourceInstance = nullptr; diff --git a/src/backend/dbus-interface/kylinnetworkresourcemanager.cpp b/src/backend/dbus-interface/kylinnetworkresourcemanager.cpp index a6c2ada7..bf27def8 100644 --- a/src/backend/dbus-interface/kylinnetworkresourcemanager.cpp +++ b/src/backend/dbus-interface/kylinnetworkresourcemanager.cpp @@ -26,6 +26,31 @@ #define LOG_FLAG "[KyNetworkResourceManager]" +QString enumToQstring(NetworkManager::AccessPoint::Capabilities cap, NetworkManager::AccessPoint::WpaFlags wpa_flags,NetworkManager::AccessPoint::WpaFlags rsn_flags) +{ + QString out; + if ( (cap & NM_802_11_AP_FLAGS_PRIVACY) + && (wpa_flags == NM_802_11_AP_SEC_NONE) + && (rsn_flags == NM_802_11_AP_SEC_NONE)) { + out += "WEP "; + } + if (wpa_flags != NM_802_11_AP_SEC_NONE) { + out += "WPA1 "; + } + if ((rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_PSK) + || (rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_802_1X)) { + out += "WPA2 "; + } + if (rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_SAE) { + out += "WPA3 "; + } + if ( (wpa_flags & NM_802_11_AP_SEC_KEY_MGMT_802_1X) + || (rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_802_1X)) { + out += "802.1X "; + } + return out; +} + KyNetworkResourceManager* KyNetworkResourceManager::m_pInstance = nullptr; KyNetworkResourceManager* KyNetworkResourceManager::getInstance() @@ -50,11 +75,18 @@ KyNetworkResourceManager::KyNetworkResourceManager(QObject *parent) : QObject(pa qRegisterMetaType("NetworkManager::Connectivity"); qRegisterMetaType("NetworkManager::ActiveConnection::Reason"); qRegisterMetaType("NetworkManager::Device::Type"); + qRegisterMetaType("NetworkManager::Device::State"); + qRegisterMetaType("NetworkManager::Device::StateChangeReason"); QDBusConnection::systemBus().connect(QString("org.freedesktop.DBus"), QString("/org/freedesktop/DBus"), QString("org.freedesktop.DBus"), QString("NameOwnerChanged"), this, SLOT(onServiceAppear(QString,QString,QString))); + + QDBusConnection::systemBus().connect(QString("org.freedesktop.NetworkManager"), + QString("/org/freedesktop/NetworkManager"), + QString("org.freedesktop.NetworkManager"), + QString("PropertiesChanged"), this, SLOT(onPropertiesChanged(QVariantMap))); } void KyNetworkResourceManager::onInitNetwork() @@ -154,7 +186,7 @@ void KyNetworkResourceManager::removeConnection(int pos) QString path = m_connections.at(pos)->path(); NetworkManager::Connection::Ptr conn = m_connections.takeAt(pos); conn->disconnect(this); - emit connectionRemove(path); + Q_EMIT connectionRemove(path); } void KyNetworkResourceManager::clearConnections() @@ -225,12 +257,12 @@ void KyNetworkResourceManager::addDevice(NetworkManager::Device::Ptr device) #endif connect(device.data(), &NetworkManager::Device::activeConnectionChanged, this, &KyNetworkResourceManager::onDeviceActiveChanage); connect(device.data(), &NetworkManager::Device::interfaceNameChanged, this, &KyNetworkResourceManager::onDeviceUpdated); + connect(device.data(), &NetworkManager::Device::managedChanged, this, &KyNetworkResourceManager::onDeviceManagedChange); #if 0 connect(device.data(), &NetworkManager::Device::ipV4AddressChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::ipV4ConfigChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::ipV6ConfigChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::ipInterfaceChanged, this, &KyNetworkResourceManager::onDeviceUpdated); - connect(device.data(), &NetworkManager::Device::managedChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::physicalPortIdChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::mtuChanged, this, &KyNetworkResourceManager::onDeviceUpdated); connect(device.data(), &NetworkManager::Device::nmPluginMissingChanged, this, &KyNetworkResourceManager::onDeviceUpdated); @@ -264,6 +296,7 @@ void KyNetworkResourceManager::addDevice(NetworkManager::Device::Ptr device) #endif connect(qobject_cast(device.data()), &NetworkManager::WirelessDevice::networkAppeared, this, &KyNetworkResourceManager::onWifiNetworkAppeared); connect(qobject_cast(device.data()), &NetworkManager::WirelessDevice::networkDisappeared, this, &KyNetworkResourceManager::onWifiNetworkDisappeared); + connect(device.data(), &NetworkManager::Device::stateChanged, this, &KyNetworkResourceManager::stateChanged); break; default: //TODO: other device types! @@ -303,7 +336,12 @@ void KyNetworkResourceManager::addWifiNetwork(NetworkManager::WirelessNetwork::P //device signals connect(net.data(), &NetworkManager::WirelessNetwork::signalStrengthChanged, this, &KyNetworkResourceManager::onUpdateWirelessNet); connect(net.data(), &NetworkManager::WirelessNetwork::referenceAccessPointChanged, this, &KyNetworkResourceManager::onUpdateWirelessNet); + connect(net.data(), &NetworkManager::WirelessNetwork::referenceAccessPointChanged, this, &KyNetworkResourceManager::onReferenceAccessPointChanged); connect(net.data(), &NetworkManager::WirelessNetwork::disappeared, this, &KyNetworkResourceManager::onUpdateWirelessNet); + connect(net->referenceAccessPoint().data(), &NetworkManager::AccessPoint::wpaFlagsChanged, this, &KyNetworkResourceManager::onWifiNetworkSecuChang, + Qt::UniqueConnection); + connect(net->referenceAccessPoint().data(), &NetworkManager::AccessPoint::rsnFlagsChanged, this, &KyNetworkResourceManager::onWifiNetworkSecuChang, + Qt::UniqueConnection); } void KyNetworkResourceManager::insertWifiNetworks() @@ -318,7 +356,7 @@ void KyNetworkResourceManager::insertWifiNetworks() for (auto const & net : w_dev->networks()) { if (!net.isNull()) { addWifiNetwork(net); - emit wifiNetworkAdded(device->interfaceName(),net->ssid()); + Q_EMIT wifiNetworkAdded(device->interfaceName(),net->ssid()); } } } @@ -542,6 +580,17 @@ void KyNetworkResourceManager::onServiceAppear(QString interface, QString oldOwn } } +void KyNetworkResourceManager::onPropertiesChanged(QVariantMap qvm) +{ + for(QString keyStr : qvm.keys()) { + //收到wifi开关打开或关闭的信号后,进行处理 + if (keyStr == "WiredEnabled") { + bool wiredEnable = qvm.value("WiredEnabled").toBool(); + Q_EMIT wiredEnabledChanged(wiredEnable); + } + } +} + void KyNetworkResourceManager::onConnectionUpdated() { NetworkManager::Connection *connectPtr = @@ -549,7 +598,7 @@ void KyNetworkResourceManager::onConnectionUpdated() if (nullptr != connectPtr && connectPtr->isValid()) { qDebug()<< LOG_FLAG <<"connection will Update, connection name"<name() << "connection uuid" << connectPtr->uuid(); - emit connectionUpdate(connectPtr->uuid()); + Q_EMIT connectionUpdate(connectPtr->uuid()); } else { qWarning()<< LOG_FLAG <<"onConnectionUpdate failed, the connect is invalid"; @@ -560,7 +609,7 @@ void KyNetworkResourceManager::onConnectionUpdated() void KyNetworkResourceManager::onActiveConnectionUpdated() { - //emit activeConnectionUpdate(qobject_cast(sender())); + //Q_EMIT activeConnectionUpdate(qobject_cast(sender())); } void KyNetworkResourceManager::onActiveConnectionChangedReason( @@ -572,7 +621,7 @@ void KyNetworkResourceManager::onActiveConnectionChangedReason( if (nullptr != activeConnect && activeConnect->isValid()) { qDebug()<< LOG_FLAG <<"connect uuid"<uuid() <<"state change"<uuid(), state, reason); + Q_EMIT activeConnectStateChangeReason(activeConnect->uuid(), state, reason); } else { qWarning() << LOG_FLAG << "onActiveConnectionChangedReason failed, the connection is invalid."; } @@ -594,7 +643,7 @@ void KyNetworkResourceManager::onActiveConnectionChanged( ::usleep(EMIT_DELAY); } - emit activeConnectStateChangeReason(activeConnect->uuid(), state, + Q_EMIT activeConnectStateChangeReason(activeConnect->uuid(), state, NetworkManager::ActiveConnection::Reason::UknownReason); } else { qWarning() << LOG_FLAG << "onActiveConnectionChanged failed, the connection is invalid."; @@ -612,7 +661,7 @@ void KyNetworkResourceManager::onVpnActiveConnectChanagedReason(NetworkManager:: if (nullptr != activeConnect && activeConnect->isValid()) { qDebug()<<"vpn connect uuid" << activeConnect->uuid() <<"state change " <uuid(), state, reason); + Q_EMIT vpnActiveConnectStateChangeReason(activeConnect->uuid(), state, reason); } else { qWarning() << LOG_FLAG << "onVpnActiveConnectChanagedReason failed, the connection is invalid."; } @@ -634,7 +683,7 @@ void KyNetworkResourceManager::onDeviceActiveChanage() qDebug()<< LOG_FLAG << "device active change, device name " << deviceName << "active state" << isActive; - emit deviceActiveChanage(deviceName, isActive); + Q_EMIT deviceActiveChanage(deviceName, isActive); return; } @@ -649,11 +698,24 @@ void KyNetworkResourceManager::onDeviceUpdated() QString deviceName = p_device->interfaceName(); QString deviceUni = p_device->uni(); - emit deviceUpdate(deviceName, deviceUni); + Q_EMIT deviceUpdate(deviceName, deviceUni); return; } +void KyNetworkResourceManager::onDeviceManagedChange() +{ + NetworkManager::Device *p_device = qobject_cast(sender()); + if (nullptr == p_device) { + return; + } + + QString deviceName = p_device->interfaceName(); + bool managed = p_device->managed(); + + Q_EMIT deviceManagedChange(deviceName, managed); +} + void KyNetworkResourceManager::onDeviceCarrierChanage(bool pluged) { NetworkManager::WiredDevice * networkDevice @@ -661,7 +723,7 @@ void KyNetworkResourceManager::onDeviceCarrierChanage(bool pluged) qDebug()<< LOG_FLAG<<"device carrier chanage"<< pluged; if (nullptr !=networkDevice && networkDevice->isValid()) { - emit deviceCarrierChanage(networkDevice->interfaceName(), pluged); + Q_EMIT deviceCarrierChanage(networkDevice->interfaceName(), pluged); } else { qWarning()<< LOG_FLAG<<"onDeviceCarrierChanage failed."; } @@ -676,7 +738,7 @@ void KyNetworkResourceManager::onDeviceBitRateChanage(int bitRate) if (nullptr != networkDevice && networkDevice->isValid()) { - emit deviceBitRateChanage(networkDevice->interfaceName(), bitRate); + Q_EMIT deviceBitRateChanage(networkDevice->interfaceName(), bitRate); } else { qWarning()<< LOG_FLAG <<"the device is not invalid with bitrate" << bitRate; } @@ -690,7 +752,7 @@ void KyNetworkResourceManager::onDeviceMacAddressChanage(const QString &hwAddres = qobject_cast(sender()); if (nullptr !=networkDevice && networkDevice->isValid()) { - emit deviceMacAddressChanage(networkDevice->interfaceName(), hwAddress); + Q_EMIT deviceMacAddressChanage(networkDevice->interfaceName(), hwAddress); } else { qWarning()<< LOG_FLAG <<"the device is not invalid with mac" << hwAddress; } @@ -729,7 +791,7 @@ void KyNetworkResourceManager::onWifiNetworkAdd(NetworkManager::Device * dev, QS NetworkManager::AccessPoint::Ptr accessPoitPtr = net->referenceAccessPoint(); QByteArray rawSsid = accessPoitPtr->rawSsid(); QString wifiSsid = getSsidFromByteArray(rawSsid); - emit wifiNetworkAdded(dev->interfaceName(), wifiSsid); + Q_EMIT wifiNetworkAdded(dev->interfaceName(), wifiSsid); } return; @@ -741,37 +803,46 @@ void KyNetworkResourceManager::onWifiNetworkUpdate(NetworkManager::WirelessNetwo return; } + bool bFlag = false; + QString devIface; + NetworkManager::Device::Ptr dev = findDeviceUni(net->device()); + if(dev.isNull()) { + qDebug()<< LOG_FLAG << "device invalid"; + bFlag = true; + } else { + devIface = dev->interfaceName(); + } + if(bFlag) { + //device invalid + qDebug() << LOG_FLAG << "wifiNetworkDeviceDisappear"; + Q_EMIT wifiNetworkDeviceDisappear(); + return; + } + + auto index = std::find(m_wifiNets.cbegin(), m_wifiNets.cend(), net); if (m_wifiNets.cend() != index) { if (net->accessPoints().isEmpty()) { - //emit - bool bFlag = false; - QString devIface; - NetworkManager::Device::Ptr dev = findDeviceUni(net->device()); - if(dev.isNull()) { - qDebug()<< LOG_FLAG << "device invalid"; - bFlag = true; - } else { - devIface = dev->interfaceName(); - } - //remove auto pos = index - m_wifiNets.cbegin(); removeWifiNetwork(pos); - if(bFlag) { - //device invalid - qDebug() << LOG_FLAG << "wifiNetworkDeviceDisappear"; - emit wifiNetworkDeviceDisappear(); - } else { - qDebug()<< LOG_FLAG << "wifiNetwork disappear" << net << net->ssid(); - NetworkManager::AccessPoint::Ptr accessPoitPtr = net->referenceAccessPoint(); - QByteArray rawSsid = accessPoitPtr->rawSsid(); - QString wifiSsid = getSsidFromByteArray(rawSsid); - emit wifiNetworkRemoved(devIface, wifiSsid); - } + qDebug()<< LOG_FLAG << "wifiNetwork disappear" << net << net->ssid(); + NetworkManager::AccessPoint::Ptr accessPoitPtr = net->referenceAccessPoint(); + QByteArray rawSsid = accessPoitPtr->rawSsid(); + QString wifiSsid = getSsidFromByteArray(rawSsid); + Q_EMIT wifiNetworkRemoved(devIface, wifiSsid); } else { - qDebug()<< LOG_FLAG << "wifiNetworkPropertyChange " << net << net->ssid(); - emit wifiNetworkPropertyChange(net); + NetworkManager::AccessPoint::Ptr accessPointPtr = net->referenceAccessPoint(); + if (accessPointPtr.isNull()) { + return; + } + QByteArray rawSsid = accessPointPtr->rawSsid(); + QString wifiSsid = getSsidFromByteArray(rawSsid); + QString bssid = accessPointPtr->hardwareAddress(); + QString secuType = enumToQstring(accessPointPtr->capabilities(), + accessPointPtr->wpaFlags(), + accessPointPtr->rsnFlags()); + Q_EMIT wifiNetworkPropertyChange(devIface, wifiSsid, net->signalStrength(), bssid, secuType); } } @@ -794,7 +865,7 @@ void KyNetworkResourceManager::onWifiNetworkRemove(NetworkManager::Device * dev, NetworkManager::AccessPoint::Ptr accessPoitPtr = net->referenceAccessPoint(); QByteArray rawSsid = accessPoitPtr->rawSsid(); QString wifiSsid = getSsidFromByteArray(rawSsid); - emit wifiNetworkRemoved(dev->interfaceName(), wifiSsid); + Q_EMIT wifiNetworkRemoved(dev->interfaceName(), wifiSsid); } } @@ -810,7 +881,7 @@ void KyNetworkResourceManager::onWifiNetworkAppeared(QString const & ssid) QString deviceName = p_device->interfaceName(); QString deviceUni = p_device->uni(); - emit deviceUpdate(deviceName, deviceUni); + Q_EMIT deviceUpdate(deviceName, deviceUni); } else { qWarning()<< LOG_FLAG << "onWifiNetworkAppeared failed."; } @@ -827,7 +898,7 @@ void KyNetworkResourceManager::onWifiNetworkDisappeared(QString const & ssid) QString deviceName = p_device->interfaceName(); QString deviceUni = p_device->uni(); - emit deviceUpdate(deviceName, deviceUni); + Q_EMIT deviceUpdate(deviceName, deviceUni); } else { qWarning()<< LOG_FLAG << "onWifiNetworkDisappeared failed."; } @@ -835,6 +906,31 @@ void KyNetworkResourceManager::onWifiNetworkDisappeared(QString const & ssid) return; } +void KyNetworkResourceManager::onReferenceAccessPointChanged() +{ + NetworkManager::WirelessNetwork *p_wirelessNet = + qobject_cast(sender()); + if (nullptr != p_wirelessNet) { + onAccessPointUpdate(p_wirelessNet); + } +} + +void KyNetworkResourceManager::onAccessPointUpdate(NetworkManager::WirelessNetwork * net) +{ + if (nullptr == net) { + return; + } + auto index = std::find(m_wifiNets.cbegin(), m_wifiNets.cend(), net); + if (m_wifiNets.cend() != index) { + if (!net->referenceAccessPoint().isNull()) { + connect(net->referenceAccessPoint().data(), &NetworkManager::AccessPoint::wpaFlagsChanged, this, &KyNetworkResourceManager::onWifiNetworkSecuChang, + Qt::UniqueConnection); + connect(net->referenceAccessPoint().data(), &NetworkManager::AccessPoint::rsnFlagsChanged, this, &KyNetworkResourceManager::onWifiNetworkSecuChang, + Qt::UniqueConnection); + } + } +} + void KyNetworkResourceManager::onUpdateWirelessNet() { NetworkManager::WirelessNetwork *p_wirelessNet = @@ -846,6 +942,13 @@ void KyNetworkResourceManager::onUpdateWirelessNet() return; } +void KyNetworkResourceManager::onWifiNetworkSecuChang() +{ + NetworkManager::AccessPoint *p_wirelessNet = + qobject_cast(sender()); + Q_EMIT wifiNetworkSecuChange(p_wirelessNet); +} + void KyNetworkResourceManager::onDeviceAdded(QString const & uni) { qDebug()<< "onDeviceAdded"< m_devices.indexOf(networkDevice)) { addDevice(networkDevice); - emit deviceAdd(networkDevice->interfaceName(), networkDevice->uni(), networkDevice->type()); + Q_EMIT deviceAdd(networkDevice->interfaceName(), networkDevice->uni(), networkDevice->type()); } else { qWarning() << networkDevice->interfaceName() <<"the device is exist in network device list."; } @@ -885,7 +988,7 @@ void KyNetworkResourceManager::onDeviceRemoved(QString const & uni) if (m_devices.cend() != index) { const int pos = index - m_devices.cbegin(); removeDevice(pos); - emit deviceRemove(networkDevice->interfaceName(), networkDevice->uni()); + Q_EMIT deviceRemove(networkDevice->interfaceName(), networkDevice->uni()); } return; @@ -908,11 +1011,11 @@ void KyNetworkResourceManager::onActiveConnectionAdded(QString const & path) if (0 > m_activeConns.indexOf(activeConnectPtr)) { addActiveConnection(activeConnectPtr); - emit activeConnectionAdd(activeConnectPtr->uuid()); + Q_EMIT activeConnectionAdd(activeConnectPtr->uuid()); } else { //TODO: onActiveConnectionUpdate qWarning() << "[KyNetworkResourceManager]" << "update active connection to do"; - //emit activeConnectionUpdate(conn->uuid()); + //Q_EMIT activeConnectionUpdate(conn->uuid()); } return; @@ -933,7 +1036,7 @@ void KyNetworkResourceManager::onActiveConnectionRemoved(QString const & path) if (m_activeConns.cend() != index) { const int pos = index - m_activeConns.cbegin(); removeActiveConnection(pos); - emit activeConnectionRemove(activeConnectPtr->uuid()); + Q_EMIT activeConnectionRemove(activeConnectPtr->uuid()); } return; @@ -961,7 +1064,7 @@ void KyNetworkResourceManager::onConnectionAdded(QString const & path) if (0 > m_connections.indexOf(connectPtr)) { addConnection(connectPtr); - emit connectionAdd(connectPtr->uuid()); + Q_EMIT connectionAdd(connectPtr->uuid()); } else { //TODO::updateconnect qWarning() << "[KyNetworkResourceManager]" << connectPtr->uuid() <<" connect is exist in connect list."; diff --git a/src/backend/dbus-interface/kylinnetworkresourcemanager.h b/src/backend/dbus-interface/kylinnetworkresourcemanager.h index 14e4ec27..b43b0dcf 100644 --- a/src/backend/dbus-interface/kylinnetworkresourcemanager.h +++ b/src/backend/dbus-interface/kylinnetworkresourcemanager.h @@ -45,6 +45,8 @@ #include #include +QString enumToQstring(NetworkManager::AccessPoint::Capabilities cap, NetworkManager::AccessPoint::WpaFlags wpa_flags,NetworkManager::AccessPoint::WpaFlags rsn_flags); + class KyNetworkResourceManager : public QObject { Q_OBJECT @@ -104,7 +106,7 @@ public: bool NetworkManagerIsInited(); -signals: +Q_SIGNALS: void connectionAdd(QString uuid); void connectionUpdate(QString uuid); void connectionRemove(QString path); @@ -112,6 +114,7 @@ signals: void deviceAdd(QString deviceName, QString uni, NetworkManager::Device::Type deviceType); void deviceUpdate(QString deviceName, QString deviceUni); void deviceRemove(QString deviceName, QString uni); + void deviceManagedChange(QString deviceName, bool managed); void deviceActiveChanage(QString deviceName, bool deviceActive); void deviceCarrierChanage(QString deviceName, bool pluged); @@ -121,9 +124,11 @@ signals: //to KyWirelessNetResource void wifiNetworkRemoved(QString, QString); void wifiNetworkAdded(QString, QString); - void wifiNetworkPropertyChange(NetworkManager::WirelessNetwork * net); + void wifiNetworkPropertyChange(QString, QString, int, QString, QString); + void wifiNetworkSecuChange(NetworkManager::AccessPoint *); void wifiNetworkDeviceDisappear(); void wifiEnabledChanged(bool); + void wiredEnabledChanged(bool); void activeConnectionsReset(); void activeConnectionAdd(QString uuid); @@ -137,14 +142,17 @@ signals: NetworkManager::VpnConnection::StateChangeReason reason); void connectivityChanged(NetworkManager::Connectivity connectivity); + void stateChanged(NetworkManager::Device::State newstate, NetworkManager::Device::State oldstate, NetworkManager::Device::StateChangeReason reason); -public slots: + +public Q_SLOTS: void onInitNetwork(); void setWirelessNetworkEnabled(bool enabled); -private slots: +private Q_SLOTS: void insertWifiNetworks(); void onServiceAppear(QString, QString, QString); + void onPropertiesChanged(QVariantMap qvm); //connection void onConnectionUpdated(); //void onConnectionRemoved(); @@ -163,6 +171,7 @@ private slots: void onDeviceActiveChanage(); void onDeviceUpdated(); + void onDeviceManagedChange(); void onDeviceCarrierChanage(bool pluged); void onDeviceBitRateChanage(int bitRate); void onDeviceMacAddressChanage(const QString &hwAddress); @@ -175,6 +184,7 @@ private slots: //wifi network void onUpdateWirelessNet(); + void onWifiNetworkSecuChang(); //notifier void onDeviceAdded(QString const & uni); @@ -191,6 +201,9 @@ private: void onWifiNetworkUpdate(NetworkManager::WirelessNetwork * net); void onWifiNetworkRemove(NetworkManager::Device * dev, QString const & ssid); + void onAccessPointUpdate(NetworkManager::WirelessNetwork * net); + void onReferenceAccessPointChanged(); + private: bool m_initFinished = false; diff --git a/src/backend/dbus-interface/kylinutil.cpp b/src/backend/dbus-interface/kylinutil.cpp index 6fce5409..7e9ed0cc 100644 --- a/src/backend/dbus-interface/kylinutil.cpp +++ b/src/backend/dbus-interface/kylinutil.cpp @@ -1,6 +1,30 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "kylinutil.h" #include +#include +#include +#include +#include + #define LOG_FLAG "[kylin-util]" QString getConnectTypeByDbus(QString &connectPath) @@ -35,10 +59,7 @@ QString getConnectTypeByDbus(QString &connectPath) connectType = connectMap.value(KEY_CONNECT_TYPE).toString(); -// qDebug() << LOG_FLAG << "connection type" << connectType; - return connectType; - } QString getSsidFromByteArray(QByteArray &rawSsid) @@ -69,17 +90,131 @@ QString getSsidFromByteArray(QByteArray &rawSsid) wifiSsid = rawSsid; } -// if (!QString::fromUtf8(rawSsid).contains("?")) { -// QTextCodec *p_textGBK = QTextCodec::codecForName("GB2312"); -// wifiSsid = p_textGBK->toUnicode(rawSsid); - -// qDebug() << LOG_FLAG <<"gb2312 to string ssid" << wifiSsid; -// //qDebug() << LOG_FLAG << "-------------> GB2312 " << byteArrayGB; -// } else { -// wifiSsid = QString::fromUtf8(rawSsid); - -// qDebug()<< LOG_FLAG <<" UTF-8 ssid: " < UTF-8 " << bytearray; -// } return wifiSsid; } + +void setWiredEnabledByGDbus(bool enabled) +{ + GDBusProxy *props_proxy; + GVariant *ret = NULL; + GError *error = NULL; + + /* Create a D-Bus object proxy for the active connection object's properties */ + props_proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM, + G_DBUS_PROXY_FLAGS_NONE, + NULL, + "org.freedesktop.NetworkManager", + "/org/freedesktop/NetworkManager", + "org.freedesktop.DBus.Properties", + NULL, NULL); + g_assert (props_proxy); + + /* Get the object path of the Connection details */ + ret = g_dbus_proxy_call_sync (props_proxy, + "Set", + g_variant_new ("(ssv)", + "org.freedesktop.NetworkManager", + "WiredEnabled", + g_variant_new_boolean(enabled)), + G_DBUS_CALL_FLAGS_NONE, -1, + NULL, &error); + if (!ret) { + g_dbus_error_strip_remote_error (error); + qDebug() << "failed to setWiredEnabledByGDbus"; + g_error_free (error); + } + +out: + if (ret) + g_variant_unref (ret); + g_object_unref (props_proxy); +} + +bool getWiredEnabledByGDbus() +{ + GDBusProxy *props_proxy; + GVariant *ret = NULL, *path_value = NULL; + GError *error = NULL; + gboolean bRet = false; + + /* Create a D-Bus object proxy for the active connection object's properties */ + props_proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM, + G_DBUS_PROXY_FLAGS_NONE, + NULL, + "org.freedesktop.NetworkManager", + "/org/freedesktop/NetworkManager", + "org.freedesktop.DBus.Properties", + NULL, NULL); + g_assert (props_proxy); + + /* Get the object path of the Connection details */ + ret = g_dbus_proxy_call_sync (props_proxy, + "Get", + g_variant_new ("(ss)", + "org.freedesktop.NetworkManager", + "WiredEnabled"), + G_DBUS_CALL_FLAGS_NONE, -1, + NULL, &error); + if (!ret) { + g_dbus_error_strip_remote_error (error); + qDebug() << "failed to setWiredEnabledByGDbus"; + g_error_free (error); + } + + g_variant_get (ret, "(v)", &path_value); + if (!g_variant_is_of_type (path_value, G_VARIANT_TYPE_BOOLEAN)) { + g_warning ("Unexpected type returned getting Connection property: %s", + g_variant_get_type_string (path_value)); + goto out; + } + + bRet = g_variant_get_boolean (path_value); + +out: + if (path_value) + g_variant_unref (path_value); + if (ret) + g_variant_unref (ret); + g_object_unref (props_proxy); + + return bRet; +} + + +void setDeviceManagedByGDbus(QString dbusPath, bool managed) +{ + GDBusProxy *props_proxy; + GVariant *ret = NULL; + GError *error = NULL; + + /* Create a D-Bus object proxy for the active connection object's properties */ + props_proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM, + G_DBUS_PROXY_FLAGS_NONE, + NULL, + "org.freedesktop.NetworkManager", + dbusPath.toStdString().c_str(), + "org.freedesktop.DBus.Properties", + NULL, NULL); + g_assert (props_proxy); + + /* Get the object path of the Connection details */ + ret = g_dbus_proxy_call_sync (props_proxy, + "Set", + g_variant_new ("(ssv)", + "org.freedesktop.NetworkManager.Device", + "Managed", + g_variant_new_boolean(managed)), + G_DBUS_CALL_FLAGS_NONE, -1, + NULL, &error); + if (!ret) { + g_dbus_error_strip_remote_error (error); + qDebug() << "failed to setWiredEnabledByGDbus"; + g_error_free (error); + } + +out: + if (ret) + g_variant_unref (ret); + g_object_unref (props_proxy); +} + diff --git a/src/backend/dbus-interface/kylinutil.h b/src/backend/dbus-interface/kylinutil.h index 08c980b8..3925b419 100644 --- a/src/backend/dbus-interface/kylinutil.h +++ b/src/backend/dbus-interface/kylinutil.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef KYLINUTIL_H #define KYLINUTIL_H @@ -16,5 +35,8 @@ QString getConnectTypeByDbus(QString &connectPath); QString getSsidFromByteArray(QByteArray &rawSsid); +void setWiredEnabledByGDbus(bool enabled); +void setDeviceManagedByGDbus(QString dbusPath, bool managed); +bool getWiredEnabledByGDbus(); #endif // KYLINUTIL_H diff --git a/src/backend/dbus-interface/kylinvpnconnectitem.cpp b/src/backend/dbus-interface/kylinvpnconnectitem.cpp index 7b770089..7eb0c5be 100644 --- a/src/backend/dbus-interface/kylinvpnconnectitem.cpp +++ b/src/backend/dbus-interface/kylinvpnconnectitem.cpp @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "kylinvpnconnectitem.h" diff --git a/src/backend/dbus-interface/kylinvpnconnectitem.h b/src/backend/dbus-interface/kylinvpnconnectitem.h index e4340fbb..704cc3ae 100644 --- a/src/backend/dbus-interface/kylinvpnconnectitem.h +++ b/src/backend/dbus-interface/kylinvpnconnectitem.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef KYLINVPNCONNECTITEM_H #define KYLINVPNCONNECTITEM_H diff --git a/src/backend/dbus-interface/kylinvpnrequest.h b/src/backend/dbus-interface/kylinvpnrequest.h index a779acd0..266f085e 100644 --- a/src/backend/dbus-interface/kylinvpnrequest.h +++ b/src/backend/dbus-interface/kylinvpnrequest.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef KYLIN_VPN_REQUEST_H #define KYLIN_VPN_REQUEST_H diff --git a/src/backend/dbus-interface/kylinwiredconnectoperation.cpp b/src/backend/dbus-interface/kylinwiredconnectoperation.cpp index 0f477c6f..03c7f1ba 100644 --- a/src/backend/dbus-interface/kylinwiredconnectoperation.cpp +++ b/src/backend/dbus-interface/kylinwiredconnectoperation.cpp @@ -17,6 +17,7 @@ */ #include "kylinwiredconnectoperation.h" +#include "kylinutil.h" #include #include @@ -26,13 +27,24 @@ KyWiredConnectOperation::KyWiredConnectOperation(QObject *parent) : KyConnectOperation(parent) { - + connect(m_networkResourceInstance, &KyNetworkResourceManager::wiredEnabledChanged, + this, &KyWiredConnectOperation::wiredEnabledChanged); } KyWiredConnectOperation::~KyWiredConnectOperation() { } +void KyWiredConnectOperation::setWiredEnabled(bool enabled) +{ + setWiredEnabledByGDbus(enabled); +} + +bool KyWiredConnectOperation::getWiredEnabled() +{ + return getWiredEnabledByGDbus(); +} + void KyWiredConnectOperation::createWiredConnect(KyConnectSetting &connectSettingsInfo) { qDebug()<<"[KyWiredConnectOperation]" << "create connect "; @@ -56,7 +68,7 @@ void KyWiredConnectOperation::createWiredConnect(KyConnectSetting &connectSettin if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("create wired connection failed: ") + watcher->error().message(); qWarning()<createConnectionError(errorMessage); + Q_EMIT this->createConnectionError(errorMessage); } else { qDebug()<<"create wired connect complete"; } @@ -74,7 +86,7 @@ void KyWiredConnectOperation::updateWiredConnect(const QString &connectUuid, con if (nullptr == connectPtr) { QString errorMessage = tr("it can not find connection") + connectUuid; qWarning()<settings()->connectionType()) { - QString errorMessage = tr("the connect type is") - + connectPtr->settings()->connectionType() - + tr(", but it is not vpn"); - qWarning()<path(); - connectName = connectPtr->name(); - //deviceName = connectPtr->settings()->interfaceName(); - specificObject = deviceIdentifier = QStringLiteral("/"); - - qDebug() <<"active wired connect: path "<< connectPath - << "device identify " << deviceIdentifier - << "connect name " << connectName - // << "device name" << deviceName - << "specific parameter"<< specificObject; - - QDBusPendingCallWatcher * watcher; - watcher = new QDBusPendingCallWatcher{NetworkManager::activateConnection(connectPath, deviceIdentifier, specificObject), this}; - connect(watcher, &QDBusPendingCallWatcher::finished, [this, connectName] (QDBusPendingCallWatcher * watcher) { - if (watcher->isError() || !watcher->isValid()) { - QString errorMessage = tr("activate vpn connection failed: ") + watcher->error().message(); - qWarning()<activateConnectionError(errorMessage); - } else { - qWarning()<<"active vpn connect complete."; - } - - watcher->deleteLater(); - }); - - return; -} - void KyWiredConnectOperation::saveActiveConnection(QString &deviceName, QString &connectUuid) { QSettings *p_settings = new QSettings(WIRED_NETWORK_STATE_CONF_FILE, QSettings::IniFormat); diff --git a/src/backend/dbus-interface/kylinwiredconnectoperation.h b/src/backend/dbus-interface/kylinwiredconnectoperation.h index 4a0e0ee6..14c7393b 100644 --- a/src/backend/dbus-interface/kylinwiredconnectoperation.h +++ b/src/backend/dbus-interface/kylinwiredconnectoperation.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef KYLINWIREDCONNECTOPERATION_H #define KYLINWIREDCONNECTOPERATION_H @@ -18,16 +37,21 @@ public: ~KyWiredConnectOperation(); public: + //无线开关 + void setWiredEnabled(bool enabled); + bool getWiredEnabled(); + void createWiredConnect(KyConnectSetting &connectSettingsInfo); void updateWiredConnect(const QString &connectUuid, const KyConnectSetting &connectSettingsInfo); void deleteWiredConnect(const QString &connectUuid); void activateWiredConnection(const QString connectUuid, const QString devName); - void activateVpnConnection(const QString connectUuid); void deactivateWiredConnection(const QString activeConnectName, const QString &activeConnectUuid); int closeWiredNetworkWithDevice(QString deviceName); int openWiredNetworkWithDevice(QString deviceName); +Q_SIGNALS: + void wiredEnabledChanged(bool); private: void getActiveConnection(QString &deviceName, QString &connectUuid); void saveActiveConnection(QString &deviceName, QString &connectUuid); diff --git a/src/backend/dbus-interface/kyvpnconnectoperation.cpp b/src/backend/dbus-interface/kyvpnconnectoperation.cpp new file mode 100644 index 00000000..adee3ffb --- /dev/null +++ b/src/backend/dbus-interface/kyvpnconnectoperation.cpp @@ -0,0 +1,1530 @@ +/* + * Copyright (C) 2020 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see toMap()), this}; + connect(watcher, &QDBusPendingCallWatcher::finished, [this](QDBusPendingCallWatcher * watcher) { + if (watcher->isError() || !watcher->isValid()) { + QString errorMessage = tr("create vpn connection failed: ") + watcher->error().message(); + qWarning()<createConnectionError(errorMessage); + } else { + qDebug()<<"create vpn connect complete"; + } + watcher->deleteLater(); + }); + + return; +} + +void KyVpnConnectOperation::getConnectionSetting(QString connectUuid, KyVpnConfig &connectSetting) +{ + qDebug() <<"[KyConnectResourse]" << connectUuid <<"get connect setting info, connect uuid"; + KyNetworkResourceManager *networkResourceInstance = KyNetworkResourceManager::getInstance(); + + NetworkManager::Connection::Ptr connectPtr = + networkResourceInstance->getConnect(connectUuid); + + if (nullptr == connectPtr || !connectPtr->isValid()) { + qWarning() <<"[KyConnectResourse]" << "it can not find valid connection" << connectUuid; + return; + } + + connectSetting.m_connectName = connectPtr->name(); + + NetworkManager::ConnectionSettings::Ptr connectionSettings = connectPtr->settings(); + connectSetting.m_ifaceName = connectionSettings->interfaceName(); + connectSetting.m_isAutoConnect = connectionSettings->autoconnect(); + + if (connectionSettings->connectionType() != NetworkManager::ConnectionSettings::Vpn) { + return ; + } + + QDBusPendingReply reply = connectPtr->secrets(KYVPN_VPN_KEY); + QMap secretMap(reply.value()); + QVariantMap vpnSecretMap; + vpnSecretMap.clear(); + if (secretMap.contains(KYVPN_VPN_KEY)) { + vpnSecretMap = secretMap.value(KYVPN_VPN_KEY); + } + + connectSetting.m_vpnName = connectionSettings->id(); + NetworkManager::VpnSetting::Ptr vpnSettings = connectionSettings->setting(NetworkManager::Setting::Vpn).dynamicCast(); + m_vpnData.clear(); + m_vpnData = vpnSettings->data(); + m_vpnSecrets.clear(); + if (!vpnSecretMap.isEmpty()) { + vpnSettings->secretsFromMap(vpnSecretMap); + } + m_vpnSecrets = vpnSettings->secrets(); + connectSetting.m_gateway.clear(); + if (vpnSettings->serviceType() == VPN_SERVERTYPE_L2TP) { + connectSetting.m_vpnType = KYVPNTYPE_L2TP; + if (m_vpnData.contains(KYVPN_GATEWAY_KEY)) { + connectSetting.m_gateway = m_vpnData.value(KYVPN_GATEWAY_KEY); + } + } else if (vpnSettings->serviceType() == VPN_SERVERTYPE_PPTP) { + connectSetting.m_vpnType = KYVPNTYPE_PPTP; + if (m_vpnData.contains(KYVPN_GATEWAY_KEY)) { + connectSetting.m_gateway = m_vpnData.value(KYVPN_GATEWAY_KEY); + } + } else if (vpnSettings->serviceType() == VPN_SERVERTYPE_OPENVPN) { + connectSetting.m_vpnType = KYVPNTYPE_OPENVPN; + if (m_vpnData.contains(KYVPN_REMOTE_KEY)) { + connectSetting.m_gateway = m_vpnData.value(KYVPN_REMOTE_KEY); + } + } else if (vpnSettings->serviceType() == VPN_SERVERTYPE_STRONGSWAN) { + connectSetting.m_vpnType = KYVPNTYPE_STRONGSWAN; + if (m_vpnData.contains(KYVPN_ADDRESS_KEY)) { + connectSetting.m_gateway = m_vpnData.value(KYVPN_ADDRESS_KEY); + } + } else { + connectSetting.m_vpnType = KYVPNTYPE_UNKNOWN; + } + + NetworkManager::Ipv4Setting::Ptr ipv4Settings = connectionSettings->setting(NetworkManager::Setting::Ipv4).dynamicCast(); + connectSetting.m_ipv4DnsSearch = ipv4Settings->dnsSearch(); + connectSetting.m_ipv4DhcpClientId = ipv4Settings->dhcpClientId(); + if (NetworkManager::Ipv4Setting::Automatic == ipv4Settings->method()) { + connectSetting.m_ipv4ConfigIpType = CONFIG_IP_DHCP; + connectSetting.m_ipv4Dns = ipv4Settings->dns(); + } else { + connectSetting.m_ipv4ConfigIpType = CONFIG_IP_MANUAL; + connectSetting.m_ipv4Address = ipv4Settings->addresses(); + connectSetting.m_ipv4Dns = ipv4Settings->dns(); + } + + NetworkManager::Ipv6Setting::Ptr ipv6Settings = connectionSettings->setting(NetworkManager::Setting::Ipv6).dynamicCast(); + connectSetting.m_ipv6DnsSearch = ipv6Settings->dnsSearch(); + if (NetworkManager::Ipv6Setting::Automatic == ipv6Settings->method()) { + connectSetting.m_ipv6ConfigIpType = CONFIG_IP_DHCP; + connectSetting.m_ipv6Dns = ipv6Settings->dns(); + } else { + connectSetting.m_ipv6ConfigIpType = CONFIG_IP_MANUAL; + connectSetting.m_ipv6Address = ipv6Settings->addresses(); + connectSetting.m_ipv6Dns = ipv6Settings->dns(); + } + + return; +} + +KyVpnConfig KyVpnConnectOperation::getVpnConfig(QString connectUuid) +{ + KyVpnConfig vpnConfig; + getConnectionSetting(connectUuid, vpnConfig); + + switch (vpnConfig.m_vpnType) { + case KYVPNTYPE_L2TP: + getL2tpConfig(vpnConfig); + break; + case KYVPNTYPE_PPTP: + getPptpConfig(vpnConfig); + break; + case KYVPNTYPE_STRONGSWAN: + getStrongswanConfig(vpnConfig); + break; + case KYVPNTYPE_OPENVPN: + getOpenvpnConfig(vpnConfig); + break; + default : + break; + } + return vpnConfig; +} + +NMVariantMapMap KyVpnConnectOperation::setIpConfig(NetworkManager::ConnectionSettings::Ptr connectionSettings, KyVpnConfig &vpnConfig) +{ + NetworkManager::Ipv4Setting::Ptr ipv4Settings = connectionSettings->setting(NetworkManager::Setting::Ipv4).dynamicCast(); + ipv4SettingSet(ipv4Settings, vpnConfig); + if (!vpnConfig.m_ipv4DnsSearch.isEmpty()) { + ipv4Settings->setDnsSearch(vpnConfig.m_ipv4DnsSearch); + } else { + QStringList emptyList; + emptyList.clear(); + ipv4Settings->setDnsSearch({""}); + } + if (!vpnConfig.m_ipv4DhcpClientId.isEmpty()) { + ipv4Settings->setDhcpClientId(vpnConfig.m_ipv4DhcpClientId); + } else { + ipv4Settings->setDhcpClientId(""); + } + + NetworkManager::Ipv6Setting::Ptr ipv6Settings = connectionSettings->setting(NetworkManager::Setting::Ipv6).dynamicCast(); + ipv6SettingSet(ipv6Settings, vpnConfig); + if (!vpnConfig.m_ipv6DnsSearch.isEmpty()) { + ipv6Settings->setDnsSearch(vpnConfig.m_ipv6DnsSearch); + } + + NMVariantMapMap connectionSettingMap = connectionSettings->toMap(); + if (connectionSettingMap.contains("ipv4")) { + QVariantMap ipv4Map = connectionSettingMap.value(QLatin1String("ipv4")); + bool isAuto = false; + if (ipv4Map.contains("method") && ipv4Map["method"] == "auto") { + qDebug() << "[KyVpnConnectOperation] set ipv4 method auto, clear address-data && addresses && gateway"; + isAuto = true; + } + if (isAuto) { + if (ipv4Map.contains("address-data")) { + ipv4Map.remove("address-data"); + } + if (ipv4Map.contains("addresses")) { + ipv4Map.remove("addresses"); + } + if (ipv4Map.contains("gateway")) { + ipv4Map.remove("gateway"); + } + connectionSettingMap["ipv4"] = ipv4Map; + } + } + + if (connectionSettingMap.contains("ipv6")) { + QVariantMap ipv6Map = connectionSettingMap.value(QLatin1String("ipv6")); + bool isAuto = false; + if (ipv6Map.contains("method") && ipv6Map["method"] == "auto") { + qDebug() << "[KyVpnConnectOperation] set ipv6 method auto, clear address-data && addresses && gateway"; + isAuto = true; + } + if (isAuto) { + if (ipv6Map.contains("address-data")) { + ipv6Map.remove("address-data"); + } + if (ipv6Map.contains("addresses")) { + ipv6Map.remove("addresses"); + } + if (ipv6Map.contains("gateway")) { + ipv6Map.remove("gateway"); + } + connectionSettingMap["ipv6"] = ipv6Map; + } + } + + return connectionSettingMap; +} + +void KyVpnConnectOperation::setVpnConfig(QString connectUuid, KyVpnConfig &vpnConfig) +{ + qDebug() <<"[KyVpnConnectOperation]" << connectUuid <<"get connect setting info, connect uuid"; + KyNetworkResourceManager *networkResourceInstance = KyNetworkResourceManager::getInstance(); + + NetworkManager::Connection::Ptr connectPtr = + networkResourceInstance->getConnect(connectUuid); + + if (nullptr == connectPtr || !connectPtr->isValid()) { + qWarning() <<"[KyVpnConnectOperation]" << "it can not find valid connection" << connectUuid; + return; + } + NetworkManager::ConnectionSettings::Ptr connectionSettings = connectPtr->settings(); + setConnectionSetting(connectionSettings, vpnConfig); + NMVariantMapMap connectionSettingMap = setIpConfig(connectionSettings, vpnConfig); + connectPtr->update(connectionSettingMap); + return ; +} + +void KyVpnConnectOperation::setConnectionSetting(NetworkManager::ConnectionSettings::Ptr connectionSettings, KyVpnConfig &vpnConfig) +{ + connectionSettings->setId(vpnConfig.m_connectName); + connectionSettings->setUuid(NetworkManager::ConnectionSettings::createNewUuid()); + if (!vpnConfig.m_ifaceName.isEmpty()) { + connectionSettings->setInterfaceName(vpnConfig.m_ifaceName); + } + connectionSettings->setAutoconnect(vpnConfig.m_isAutoConnect); + + NetworkManager::VpnSetting::Ptr vpnSettings = connectionSettings->setting(NetworkManager::Setting::Vpn).dynamicCast(); + vpnSettings->setInitialized(true); + m_vpnData.clear(); + m_vpnSecrets.clear(); + + switch (vpnConfig.m_vpnType) { + case KYVPNTYPE_L2TP: + vpnSettings->setServiceType(VPN_SERVERTYPE_L2TP); + setL2tpConfig(vpnConfig); + break; + case KYVPNTYPE_PPTP: + vpnSettings->setServiceType(VPN_SERVERTYPE_PPTP); + setPptpConfig(vpnConfig); + break; + case KYVPNTYPE_STRONGSWAN: + vpnSettings->setServiceType(VPN_SERVERTYPE_STRONGSWAN); + setStrongswanConfig(vpnConfig); + break; + case KYVPNTYPE_OPENVPN: + vpnSettings->setServiceType(VPN_SERVERTYPE_OPENVPN); + setOpenvpnConfig(vpnConfig); + break; + default : + break; + } + + vpnSettings->setData(m_vpnData); + vpnSettings->setSecrets(m_vpnSecrets); + return; +} + +void KyVpnConnectOperation::getL2tpConfig(KyVpnConfig &vpnConfig) +{ + vpnConfig.m_authMethod = KYAUTH_PASSWD; + + //获取用户名 + vpnConfig.m_userName.clear(); + if (m_vpnData.contains(KYVPN_USER_KEY)) { + vpnConfig.m_userName = m_vpnData.value(KYVPN_USER_KEY); + } + //获取密码和加密策略 + getUsrPasswdAndPolicy(vpnConfig); + //获取NT域 + vpnConfig.m_ntDomain.clear(); + if (m_vpnData.contains(KYVPN_DOMAIN_KEY) && !m_vpnData.value(KYVPN_DOMAIN_KEY).isEmpty()) { + vpnConfig.m_ntDomain = m_vpnData.value(KYVPN_DOMAIN_KEY); + } + + if (m_vpnData.contains(KYVPN_MRU_KEY) && !m_vpnData.value(KYVPN_MRU_KEY).isEmpty()) { + vpnConfig.m_mru = m_vpnData.value(KYVPN_MRU_KEY); + } + if (m_vpnData.contains(KYVPN_MTU_KEY) && !m_vpnData.value(KYVPN_MTU_KEY).isEmpty()) { + vpnConfig.m_mtu = m_vpnData.value(KYVPN_MTU_KEY); + } + + vpnConfig.m_authMethods.setFlag(KYAUTH2_ALL); + if (m_vpnData.contains(KYVPN_REFUSEPAP_KEY) && m_vpnData.value(KYVPN_REFUSEPAP_KEY) == KYVPN_YES) { + vpnConfig.m_authMethods.setFlag(KYAUTH2_PAP, false); + } + if (m_vpnData.contains(KYVPN_REFUSECHAP_KEY) && m_vpnData.value(KYVPN_REFUSECHAP_KEY) == KYVPN_YES) { + vpnConfig.m_authMethods.setFlag(KYAUTH2_CHAP, false); + } + if (m_vpnData.contains(KYVPN_REFUSEMSCHAP_KEY) && m_vpnData.value(KYVPN_REFUSEMSCHAP_KEY) == KYVPN_YES) { + vpnConfig.m_authMethods.setFlag(KYAUTH2_MSCHAP, false); + } + if (m_vpnData.contains(KYVPN_REFUSEMSCHAPV2_KEY) && m_vpnData.value(KYVPN_REFUSEMSCHAPV2_KEY) == KYVPN_YES) { + vpnConfig.m_authMethods.setFlag(KYAUTH2_MSCHAPV2, false); + } + if (m_vpnData.contains(KYVPN_REFUSEEAP_KEY) && m_vpnData.value(KYVPN_REFUSEEAP_KEY) == KYVPN_YES) { + vpnConfig.m_authMethods.setFlag(KYAUTH2_EAP, false); + } + + vpnConfig.m_compressMethods.setFlag(KYCOMP_ALL); + if (m_vpnData.contains(KYVPN_NOBSDCOMP_KEY) && m_vpnData.value(KYVPN_NOBSDCOMP_KEY) == KYVPN_YES) { + vpnConfig.m_compressMethods.setFlag(KYCOMP_BSD, false); + } + if (m_vpnData.contains(KYVPN_NODEFLATE_KEY) && m_vpnData.value(KYVPN_NODEFLATE_KEY) == KYVPN_YES) { + vpnConfig.m_compressMethods.setFlag(KYCOMP_DEFLATE, false); + } + if (m_vpnData.contains(KYVPN_NOVJCOMP_KEY) && m_vpnData.value(KYVPN_NOVJCOMP_KEY) == KYVPN_YES) { + vpnConfig.m_compressMethods.setFlag(KYCOMP_TCP, false); + } + if (m_vpnData.contains(KYVPN_NOPCOMP_KEY) && m_vpnData.value(KYVPN_NOPCOMP_KEY) == KYVPN_YES) { + vpnConfig.m_compressMethods.setFlag(KYCOMP_PROTO, false); + } + if (m_vpnData.contains(KYVPN_NOACCOMP_KEY) && m_vpnData.value(KYVPN_NOACCOMP_KEY) == KYVPN_YES) { + vpnConfig.m_compressMethods.setFlag(KYCOMP_ADDR, false); + } + + vpnConfig.m_mppeEnable = false; + if (m_vpnData.contains(KYVPN_REQUIREMPPE_KEY)) { + vpnConfig.m_mppeEnable = true; + if (m_vpnData.contains(KYVPN_REQUIREMPPE128_KEY)) { + vpnConfig.m_mppeEncryptMethod = KYMPPE_REQUIRE128; + } else if (m_vpnData.contains(KYVPN_REQUIREMPPE40_KEY)) { + vpnConfig.m_mppeEncryptMethod = KYMPPE_REQUIRE40; + } else { + vpnConfig.m_mppeEncryptMethod = KYMPPE_DEFAULT; + } + vpnConfig.m_authMethods.setFlag(KYAUTH2_EAP, false); + vpnConfig.m_authMethods.setFlag(KYAUTH2_PAP, false); + vpnConfig.m_authMethods.setFlag(KYAUTH2_CHAP, false); + } + + vpnConfig.m_isAllowStatefulEncryption = false; + if (m_vpnData.contains(KYVPN_MPPESTATEFUL_KEY)) { + vpnConfig.m_isAllowStatefulEncryption = true; + } + + vpnConfig.m_sendPppPackage = false; + if (m_vpnData.contains(KYVPN_LCPECHOFAILURE_KEY) && m_vpnData.contains(KYVPN_LCPECHOINTERVAL_KEY)) { + vpnConfig.m_sendPppPackage = true; + } +} + +void KyVpnConnectOperation::setL2tpConfig(KyVpnConfig &vpnConfig) +{ + //设置用户名 + if (!vpnConfig.m_userName.isEmpty()) { + m_vpnData.insert(KYVPN_USER_KEY, vpnConfig.m_userName); + } + //设置密码和密码策略 + setUsrPasswdAndPolicy(vpnConfig); + //设置地址 + if (!vpnConfig.m_gateway.isEmpty()) { + m_vpnData.insert(KYVPN_GATEWAY_KEY, vpnConfig.m_gateway); + } + //设置NT域 + if (!vpnConfig.m_ntDomain.isEmpty()) { + m_vpnData.insert(KYVPN_DOMAIN_KEY, vpnConfig.m_ntDomain); + } + + //设置MRU 最大接收单元 + if (!vpnConfig.m_mru.isEmpty()) { + m_vpnData.insert(KYVPN_MRU_KEY, vpnConfig.m_mru); + } + //设置MTU 最大传输单元 + if (!vpnConfig.m_mtu.isEmpty()) { + m_vpnData.insert(KYVPN_MTU_KEY, vpnConfig.m_mtu); + } + + //设置认证方式 + //不设置PAP认证,若未勾选,则对应字段设置YES + if (!vpnConfig.m_authMethods.testFlag(KYAUTH2_PAP)) { + m_vpnData.insert(KYVPN_REFUSEPAP_KEY, KYVPN_YES); + } + //不设置CHAP认证,若未勾选,则对应字段设置YES + if (!vpnConfig.m_authMethods.testFlag(KYAUTH2_CHAP)) { + m_vpnData.insert(KYVPN_REFUSECHAP_KEY, KYVPN_YES); + } + //不设置MSCHAP认证,若未勾选,则对应字段设置YES + if (!vpnConfig.m_authMethods.testFlag(KYAUTH2_MSCHAP)) { + m_vpnData.insert(KYVPN_REFUSEMSCHAP_KEY, KYVPN_YES); + } + //不设置MSCHAPV2认证,若未勾选,则对应字段设置YES + if (!vpnConfig.m_authMethods.testFlag(KYAUTH2_MSCHAPV2)) { + m_vpnData.insert(KYVPN_REFUSEMSCHAPV2_KEY, KYVPN_YES); + } + //不设置EAP认证,若未勾选,则对应字段设置YES + if (!vpnConfig.m_authMethods.testFlag(KYAUTH2_EAP)) { + m_vpnData.insert(KYVPN_REFUSEEAP_KEY, KYVPN_YES); + } + + //设置压缩方式 + //不允许BSD压缩,若未勾选,则对应字段设置YES + if (!vpnConfig.m_compressMethods.testFlag(KYCOMP_BSD)) { + m_vpnData.insert(KYVPN_NOBSDCOMP_KEY, KYVPN_YES); + } + //不允许Deflate压缩,若未勾选,则对应字段设置YES + if (!vpnConfig.m_compressMethods.testFlag(KYCOMP_DEFLATE)) { + m_vpnData.insert(KYVPN_NODEFLATE_KEY, KYVPN_YES); + } + //不允许TCP头压缩,若未勾选,则对应字段设置YES + if (!vpnConfig.m_compressMethods.testFlag(KYCOMP_TCP)) { + m_vpnData.insert(KYVPN_NOVJCOMP_KEY, KYVPN_YES); + } + //不使用协议域压缩协商,若未勾选,则对应字段设置YES + if (!vpnConfig.m_compressMethods.testFlag(KYCOMP_PROTO)) { + m_vpnData.insert(KYVPN_NOPCOMP_KEY, KYVPN_YES); + } + //不使用地址/控制压缩,若未勾选,则对应字段设置YES + if (!vpnConfig.m_compressMethods.testFlag(KYCOMP_ADDR)) { + m_vpnData.insert(KYVPN_NOACCOMP_KEY, KYVPN_YES); + } + + //设置MPPE加密算法 + if (vpnConfig.m_mppeEnable) { + //设置MPPE加密算法方法为默认加密 + m_vpnData.insert(KYVPN_REQUIREMPPE_KEY, KYVPN_YES); + switch (vpnConfig.m_mppeEncryptMethod) { + case KYMPPE_REQUIRE128: + //设置MPPE加密算法方法为128位加密 + m_vpnData.insert(KYVPN_REQUIREMPPE128_KEY, KYVPN_YES); + break; + case KYMPPE_REQUIRE40: + //设置MPPE加密算法方法为40位加密 + m_vpnData.insert(KYVPN_REQUIREMPPE40_KEY, KYVPN_YES); + break; + case KYMPPE_DEFAULT: + default: + break; + } + + //若使用MPPE加密算法,则不设置PAP认证、不设置CHAP认证、不设置EAP认证 + m_vpnData.insert(KYVPN_REFUSEPAP_KEY, KYVPN_YES); + m_vpnData.insert(KYVPN_REFUSECHAP_KEY, KYVPN_YES); + m_vpnData.insert(KYVPN_REFUSEEAP_KEY, KYVPN_YES); + } + + //允许有状态的加密 + if (vpnConfig.m_isAllowStatefulEncryption) { + m_vpnData.insert(KYVPN_MPPESTATEFUL_KEY, KYVPN_YES); + } + //发送PPP回显包 + if (vpnConfig.m_sendPppPackage) { + m_vpnData.insert(KYVPN_LCPECHOFAILURE_KEY, "5"); + m_vpnData.insert(KYVPN_LCPECHOINTERVAL_KEY, "30"); + } +} + +void KyVpnConnectOperation::getPptpConfig(KyVpnConfig &vpnConfig) +{ + vpnConfig.m_authMethod = KYAUTH_PASSWD; + + vpnConfig.m_userName.clear(); + if (m_vpnData.contains(KYVPN_USER_KEY)) { + vpnConfig.m_userName = m_vpnData.value(KYVPN_USER_KEY); + } + + getUsrPasswdAndPolicy(vpnConfig); + + vpnConfig.m_ntDomain.clear(); + if (m_vpnData.contains(KYVPN_DOMAIN_KEY)) { + vpnConfig.m_ntDomain = m_vpnData.value(KYVPN_DOMAIN_KEY); + } + + vpnConfig.m_authMethods.setFlag(KYAUTH2_ALL); + if (m_vpnData.contains(KYVPN_REFUSEPAP_KEY) && m_vpnData.value(KYVPN_REFUSEPAP_KEY) == KYVPN_YES) { + vpnConfig.m_authMethods.setFlag(KYAUTH2_PAP, false); + } + if (m_vpnData.contains(KYVPN_REFUSECHAP_KEY) && m_vpnData.value(KYVPN_REFUSECHAP_KEY) == KYVPN_YES) { + vpnConfig.m_authMethods.setFlag(KYAUTH2_CHAP, false); + } + if (m_vpnData.contains(KYVPN_REFUSEMSCHAP_KEY) && m_vpnData.value(KYVPN_REFUSEMSCHAP_KEY) == KYVPN_YES) { + vpnConfig.m_authMethods.setFlag(KYAUTH2_MSCHAP, false); + } + if (m_vpnData.contains(KYVPN_REFUSEMSCHAPV2_KEY) && m_vpnData.value(KYVPN_REFUSEMSCHAPV2_KEY) == KYVPN_YES) { + vpnConfig.m_authMethods.setFlag(KYAUTH2_MSCHAPV2, false); + } + if (m_vpnData.contains(KYVPN_REFUSEEAP_KEY) && m_vpnData.value(KYVPN_REFUSEEAP_KEY) == KYVPN_YES) { + vpnConfig.m_authMethods.setFlag(KYAUTH2_EAP, false); + } + + vpnConfig.m_compressMethods.setFlag(KYCOMP_ALL); + vpnConfig.m_compressMethods.setFlag(KYCOMP_PROTO, false); + vpnConfig.m_compressMethods.setFlag(KYCOMP_ADDR, false); + if (m_vpnData.contains(KYVPN_NOBSDCOMP_KEY) && m_vpnData.value(KYVPN_NOBSDCOMP_KEY) == KYVPN_YES) { + vpnConfig.m_compressMethods.setFlag(KYCOMP_BSD, false); + } + if (m_vpnData.contains(KYVPN_NODEFLATE_KEY) && m_vpnData.value(KYVPN_NODEFLATE_KEY) == KYVPN_YES) { + vpnConfig.m_compressMethods.setFlag(KYCOMP_DEFLATE, false); + } + if (m_vpnData.contains(KYVPN_NOVJCOMP_KEY) && m_vpnData.value(KYVPN_NOVJCOMP_KEY) == KYVPN_YES) { + vpnConfig.m_compressMethods.setFlag(KYCOMP_TCP, false); + } + + vpnConfig.m_mppeEnable = false; + if (m_vpnData.contains(KYVPN_REQUIREMPPE_KEY)) { + vpnConfig.m_mppeEnable = true; + if (m_vpnData.contains(KYVPN_REQUIREMPPE128_KEY)) { + vpnConfig.m_mppeEncryptMethod = KYMPPE_REQUIRE128; + } else if (m_vpnData.contains(KYVPN_REQUIREMPPE40_KEY)) { + vpnConfig.m_mppeEncryptMethod = KYMPPE_REQUIRE40; + } else { + vpnConfig.m_mppeEncryptMethod = KYMPPE_DEFAULT; + } + vpnConfig.m_authMethods.setFlag(KYAUTH2_EAP, false); + vpnConfig.m_authMethods.setFlag(KYAUTH2_PAP, false); + vpnConfig.m_authMethods.setFlag(KYAUTH2_CHAP, false); + } + + vpnConfig.m_isAllowStatefulEncryption = false; + if (m_vpnData.contains(KYVPN_MPPESTATEFUL_KEY)) { + vpnConfig.m_isAllowStatefulEncryption = true; + } + + vpnConfig.m_sendPppPackage = false; + if (m_vpnData.contains(KYVPN_LCPECHOFAILURE_KEY) && m_vpnData.contains(KYVPN_LCPECHOINTERVAL_KEY)) { + vpnConfig.m_sendPppPackage = true; + } +} + +void KyVpnConnectOperation::setPptpConfig(KyVpnConfig &vpnConfig) +{ + //设置用户名 + if (!vpnConfig.m_userName.isEmpty()) { + m_vpnData.insert(KYVPN_USER_KEY, vpnConfig.m_userName); + } + //设置密码和密码策略 + setUsrPasswdAndPolicy(vpnConfig); + //设置地址 + if (!vpnConfig.m_gateway.isEmpty()) { + m_vpnData.insert(KYVPN_GATEWAY_KEY, vpnConfig.m_gateway); + } + //设置NT域 + if (!vpnConfig.m_ntDomain.isEmpty()) { + m_vpnData.insert(KYVPN_DOMAIN_KEY, vpnConfig.m_ntDomain); + } + + //设置认证方式 + //不设置PAP认证,若未勾选,则对应字段设置YES + if (!vpnConfig.m_authMethods.testFlag(KYAUTH2_PAP)) { + m_vpnData.insert(KYVPN_REFUSEPAP_KEY, KYVPN_YES); + } + //不设置CHAP认证,若未勾选,则对应字段设置YES + if (!vpnConfig.m_authMethods.testFlag(KYAUTH2_CHAP)) { + m_vpnData.insert(KYVPN_REFUSECHAP_KEY, KYVPN_YES); + } + //不设置MSCHAP认证,若未勾选,则对应字段设置YES + if (!vpnConfig.m_authMethods.testFlag(KYAUTH2_MSCHAP)) { + m_vpnData.insert(KYVPN_REFUSEMSCHAP_KEY, KYVPN_YES); + } + //不设置MSCHAPV2认证,若未勾选,则对应字段设置YES + if (!vpnConfig.m_authMethods.testFlag(KYAUTH2_MSCHAPV2)) { + m_vpnData.insert(KYVPN_REFUSEMSCHAPV2_KEY, KYVPN_YES); + } + //不设置EAP认证,若未勾选,则对应字段设置YES + if (!vpnConfig.m_authMethods.testFlag(KYAUTH2_EAP)) { + m_vpnData.insert(KYVPN_REFUSEEAP_KEY, KYVPN_YES); + } + + //设置压缩方式 + //不允许BSD压缩,若未勾选,则对应字段设置YES + if (!vpnConfig.m_compressMethods.testFlag(KYCOMP_BSD)) { + m_vpnData.insert(KYVPN_NOBSDCOMP_KEY, KYVPN_YES); + } + //不允许Deflate压缩,若未勾选,则对应字段设置YES + if (!vpnConfig.m_compressMethods.testFlag(KYCOMP_DEFLATE)) { + m_vpnData.insert(KYVPN_NODEFLATE_KEY, KYVPN_YES); + } + //不允许TCP头压缩,若未勾选,则对应字段设置YES + if (!vpnConfig.m_compressMethods.testFlag(KYCOMP_TCP)) { + m_vpnData.insert(KYVPN_NOVJCOMP_KEY, KYVPN_YES); + } + + //设置MPPE加密算法 + if (vpnConfig.m_mppeEnable) { + //设置MPPE加密算法方法为默认加密 + m_vpnData.insert(KYVPN_REQUIREMPPE_KEY, KYVPN_YES); + switch (vpnConfig.m_mppeEncryptMethod) { + case KYMPPE_REQUIRE128: + //设置MPPE加密算法方法为128位加密 + m_vpnData.insert(KYVPN_REQUIREMPPE128_KEY, KYVPN_YES); + break; + case KYMPPE_REQUIRE40: + //设置MPPE加密算法方法为40位加密 + m_vpnData.insert(KYVPN_REQUIREMPPE40_KEY, KYVPN_YES); + break; + case KYMPPE_DEFAULT: + default: + break; + } + + //若使用MPPE加密算法,则不设置PAP认证、不设置CHAP认证、不设置EAP认证 + m_vpnData.insert(KYVPN_REFUSEPAP_KEY, KYVPN_YES); + m_vpnData.insert(KYVPN_REFUSECHAP_KEY, KYVPN_YES); + m_vpnData.insert(KYVPN_REFUSEEAP_KEY, KYVPN_YES); + } + + //允许有状态的加密 + if (vpnConfig.m_isAllowStatefulEncryption) { + m_vpnData.insert(KYVPN_MPPESTATEFUL_KEY, KYVPN_YES); + } + //发送PPP回显包 + if (vpnConfig.m_sendPppPackage) { + m_vpnData.insert(KYVPN_LCPECHOFAILURE_KEY, "5"); + m_vpnData.insert(KYVPN_LCPECHOINTERVAL_KEY, "30"); + } +} + +void KyVpnConnectOperation::getStrongswanConfig(KyVpnConfig &vpnConfig) +{ + vpnConfig.m_authMethod = KYAUTH_ERROR; + if (m_vpnData.contains(KYVPN_METHOD_KEY)) { + vpnConfig.m_authMethod = getAuthMethod(m_vpnData.value(KYVPN_METHOD_KEY)); + } + + vpnConfig.m_userCertificate.clear(); + vpnConfig.m_userKey.clear(); + vpnConfig.m_userName.clear(); + vpnConfig.m_pinId.clear(); + switch (vpnConfig.m_authMethod) { + case KYAUTH_KEY: + if (m_vpnData.contains(KYVPN_USERCERT_KEY)) { + vpnConfig.m_userCertificate = m_vpnData.value(KYVPN_USERCERT_KEY); + } + if (m_vpnData.contains(KYVPN_USERKEY_KEY)) { + vpnConfig.m_userKey = m_vpnData.value(KYVPN_USERKEY_KEY); + } + getCertPasswdAndPolicy(vpnConfig); + break; + case KYAUTH_AGENT: + if (m_vpnData.contains(KYVPN_USERCERT_KEY)) { + vpnConfig.m_userCertificate = m_vpnData.value(KYVPN_USERCERT_KEY); + } + break; + case KYAUTH_SMARTCARD: + if (m_vpnData.contains(KYVPN_PIN_KEY)) { + vpnConfig.m_pinId = m_vpnData.value(KYVPN_PIN_KEY); + } + break; + case KYAUTH_EAP: + if (m_vpnData.contains(KYVPN_USER_KEY)) { + vpnConfig.m_userName = m_vpnData.value(KYVPN_USER_KEY); + } + getUsrPasswdAndPolicy(vpnConfig); + break; + default : + break; + } + + vpnConfig.m_virtual = false; + if (m_vpnData.contains(KYVPN_VIRTUAL_KEY) && m_vpnData.value(KYVPN_VIRTUAL_KEY) == KYVPN_YES) { + vpnConfig.m_virtual = true; + } + + vpnConfig.m_encap = false; + if (m_vpnData.contains(KYVPN_ENCAP_KEY) && m_vpnData.value(KYVPN_ENCAP_KEY) == KYVPN_YES) { + vpnConfig.m_encap = true; + } + + vpnConfig.m_ipcomp = false; + if (m_vpnData.contains(KYVPN_IPCOMP_KEY) && m_vpnData.value(KYVPN_IPCOMP_KEY) == KYVPN_YES) { + vpnConfig.m_ipcomp = true; + } + + vpnConfig.m_proposal = false; + if (m_vpnData.contains(KYVPN_PROPOSAL_KEY) && m_vpnData.value(KYVPN_PROPOSAL_KEY) == KYVPN_YES) { + vpnConfig.m_proposal = true; + } + + vpnConfig.m_ike.clear(); + if (m_vpnData.contains(KYVPN_IKE_KEY)) { + vpnConfig.m_ike = m_vpnData.value(KYVPN_IKE_KEY); + } + + vpnConfig.m_esp.clear(); + if (m_vpnData.contains(KYVPN_ESP_KEY)) { + vpnConfig.m_esp = m_vpnData.value(KYVPN_ESP_KEY); + } +} + +void KyVpnConnectOperation::setStrongswanConfig(KyVpnConfig &vpnConfig) +{ + m_vpnData.insert(KYVPN_METHOD_KEY, m_authMethodMap.key(vpnConfig.m_authMethod)); + + if (!vpnConfig.m_gateway.isEmpty()) { + m_vpnData.insert(KYVPN_ADDRESS_KEY, vpnConfig.m_gateway); + } + + switch (vpnConfig.m_authMethod) { + case KYAUTH_KEY: + if (!vpnConfig.m_userCertificate.isEmpty()) { + m_vpnData.insert(KYVPN_USERCERT_KEY, vpnConfig.m_userCertificate); + } else { + m_vpnData.remove(KYVPN_USERCERT_KEY); + } + if (!vpnConfig.m_userKey.isEmpty()) { + m_vpnData.insert(KYVPN_USERKEY_KEY, vpnConfig.m_userKey); + } else { + m_vpnData.remove(KYVPN_USERKEY_KEY); + } + setCertPasswdAndPolicy(vpnConfig); + break; + case KYAUTH_AGENT: + if (!vpnConfig.m_userCertificate.isEmpty()) { + m_vpnData.insert(KYVPN_USERCERT_KEY, vpnConfig.m_userCertificate); + } + break; + case KYAUTH_SMARTCARD: + if (!vpnConfig.m_pinId.isEmpty()) { + m_vpnData.insert(KYVPN_PIN_KEY, vpnConfig.m_pinId); + } + break; + case KYAUTH_EAP: + if (!vpnConfig.m_userName.isEmpty()) { + m_vpnData.insert(KYVPN_USER_KEY, vpnConfig.m_userName); + } + vpnConfig.m_passwdPolicy = KYPASSWD_FORALLUSER; + setUsrPasswdAndPolicy(vpnConfig); + break; + default : + break; + } + + if (vpnConfig.m_virtual) { + m_vpnData.insert(KYVPN_VIRTUAL_KEY, KYVPN_YES); + } else { + m_vpnData.insert(KYVPN_VIRTUAL_KEY, KYVPN_NO); + } + + if (vpnConfig.m_encap) { + m_vpnData.insert(KYVPN_ENCAP_KEY, KYVPN_YES); + } else { + m_vpnData.insert(KYVPN_ENCAP_KEY, KYVPN_NO); + } + + if (vpnConfig.m_ipcomp) { + m_vpnData.insert(KYVPN_IPCOMP_KEY, KYVPN_YES); + } else { + m_vpnData.insert(KYVPN_IPCOMP_KEY, KYVPN_NO); + } + + if (vpnConfig.m_proposal) { + m_vpnData.insert(KYVPN_PROPOSAL_KEY, KYVPN_YES); + if (!vpnConfig.m_ike.isEmpty()) { + m_vpnData.insert(KYVPN_IKE_KEY, vpnConfig.m_ike); + } + + if (!vpnConfig.m_esp.isEmpty()) { + m_vpnData.insert(KYVPN_ESP_KEY, vpnConfig.m_esp); + } + } else { + m_vpnData.insert(KYVPN_PROPOSAL_KEY, KYVPN_NO); + m_vpnData.remove(KYVPN_IKE_KEY); + m_vpnData.remove(KYVPN_ESP_KEY); + } +} + +void KyVpnConnectOperation::getOpenvpnConfig(KyVpnConfig &vpnConfig) +{ + vpnConfig.m_authMethod = KYAUTH_ERROR; + if (m_vpnData.contains(KYVPN_CONNECTIONTYPE_KEY)) { + vpnConfig.m_authMethod = getAuthMethod(m_vpnData.value(KYVPN_CONNECTIONTYPE_KEY)); + } + + vpnConfig.m_caCertificate.clear(); + vpnConfig.m_userCertificate.clear(); + vpnConfig.m_userKey.clear(); + vpnConfig.m_userName.clear(); + vpnConfig.m_staticKey.clear(); + vpnConfig.m_vpnKeyDir.clear(); + vpnConfig.m_localAddress.clear(); + vpnConfig.m_remoteAddress.clear(); + switch (vpnConfig.m_authMethod) { + case KYAUTH_CERTIFICATE: + if (m_vpnData.contains(KYVPN_CA_KEY)) { + vpnConfig.m_caCertificate = m_vpnData.value(KYVPN_CA_KEY); + } + if (m_vpnData.contains(KYVPN_CERT_KEY)) { + vpnConfig.m_userCertificate = m_vpnData.value(KYVPN_CERT_KEY); + } + if (m_vpnData.contains(KYVPN_USERKEY_KEY)) { + vpnConfig.m_userKey = m_vpnData.value(KYVPN_USERKEY_KEY); + } + getCertPasswdAndPolicy(vpnConfig); + break; + + case KYAUTH_PASSWD: + if (m_vpnData.contains(KYVPN_CA_KEY)) { + vpnConfig.m_caCertificate = m_vpnData.value(KYVPN_CA_KEY); + } + if (m_vpnData.contains(KYVPN_USERNAME_KEY)) { + vpnConfig.m_userName = m_vpnData.value(KYVPN_USERNAME_KEY); + } + getUsrPasswdAndPolicy(vpnConfig); + break; + + case KYAUTH_CERTIFICATEANDPASSWD: + if (m_vpnData.contains(KYVPN_CA_KEY)) { + vpnConfig.m_caCertificate = m_vpnData.value(KYVPN_CA_KEY); + } + if (m_vpnData.contains(KYVPN_CERT_KEY)) { + vpnConfig.m_userCertificate = m_vpnData.value(KYVPN_CERT_KEY); + } + if (m_vpnData.contains(KYVPN_USERKEY_KEY)) { + vpnConfig.m_userKey = m_vpnData.value(KYVPN_USERKEY_KEY); + } + if (m_vpnData.contains(KYVPN_USERNAME_KEY)) { + vpnConfig.m_userName = m_vpnData.value(KYVPN_USERNAME_KEY); + } + getUsrPasswdAndPolicy(vpnConfig); + getCertPasswdAndPolicy(vpnConfig); + break; + + case KYAUTH_STATICPASSWD: + if (m_vpnData.contains(KYVPN_STATICKEY_KEY)) { + vpnConfig.m_staticKey = m_vpnData.value(KYVPN_STATICKEY_KEY); + } + if (m_vpnData.contains(KYVPN_STATICKEYDIR_KEY)) { + vpnConfig.m_vpnKeyDir = m_vpnData.value(KYVPN_STATICKEYDIR_KEY); + } + if (m_vpnData.contains(KYVPN_LOCALIP_KEY)) { + vpnConfig.m_localAddress = m_vpnData.value(KYVPN_LOCALIP_KEY); + } + if (m_vpnData.contains(KYVPN_REMOTEIP_KEY)) { + vpnConfig.m_remoteAddress = m_vpnData.value(KYVPN_REMOTEIP_KEY); + } + break; + + default : + break; + } + + vpnConfig.m_useAssignPort = false; + vpnConfig.m_assignPort.clear(); + if (m_vpnData.contains(KYVPN_PORT_KEY)) { + vpnConfig.m_useAssignPort = true; + vpnConfig.m_assignPort = m_vpnData.value(KYVPN_PORT_KEY); + } + + vpnConfig.m_useRenegSeconds = false; + vpnConfig.m_renegSeconds.clear(); + if (m_vpnData.contains(KYVPN_RENEGSEC_KEY)) { + vpnConfig.m_useRenegSeconds = true; + vpnConfig.m_renegSeconds = m_vpnData.value(KYVPN_RENEGSEC_KEY); + } + + vpnConfig.m_useCompress = false; + vpnConfig.m_openvpnCompress = KYCOMP2_LZODISABLE; + if (m_vpnData.contains(KYVPN_COMPLZO_KEY)) { + vpnConfig.m_useCompress = true; + if (m_vpnData.value(KYVPN_COMPLZO_KEY) == COMPLZO_LZODISABLE) { + vpnConfig.m_openvpnCompress = KYCOMP2_LZODISABLE; + } else if (m_vpnData.value(KYVPN_COMPLZO_KEY) == COMPLZO_ADAPTIVE) { + vpnConfig.m_openvpnCompress = KYCOMP2_LZOADAPTIVE; + } + } else if (m_vpnData.contains(KYVPN_COMPRESS_KEY)) { + vpnConfig.m_useCompress = true; + if (m_vpnData.value(KYVPN_COMPRESS_KEY) == COMPRESS_LZO) { + vpnConfig.m_openvpnCompress = KYCOMP2_LZO; + } else if (m_vpnData.value(KYVPN_COMPRESS_KEY) == COMPRESS_LZ4) { + vpnConfig.m_openvpnCompress = KYCOMP2_LZ4; + } else if (m_vpnData.value(KYVPN_COMPRESS_KEY) == COMPRESS_LZ4V2) { + vpnConfig.m_openvpnCompress = KYCOMP2_LZ4V2; + } else if (m_vpnData.value(KYVPN_COMPRESS_KEY) == KYVPN_YES) { + vpnConfig.m_openvpnCompress = KYCOMP2_AUTO; + } + } + + vpnConfig.m_useTcpLink = false; + if (m_vpnData.contains(KYVPN_PROTOTCP_KEY) && m_vpnData.value(KYVPN_PROTOTCP_KEY) == KYVPN_YES) { + vpnConfig.m_useTcpLink = true; + } + + vpnConfig.m_setDevType = false; + if (m_vpnData.contains(KYVPN_DEVTYPE_KEY)) { + vpnConfig.m_setDevType = true; + if (m_vpnData.value(KYVPN_DEVTYPE_KEY) == DEVTYPE_TUN) { + vpnConfig.m_devType = KYVIRDEVTYPE_TUN; + } else if (m_vpnData.value(KYVPN_DEVTYPE_KEY) == DEVTYPE_TAP) { + vpnConfig.m_devType = KYVIRDEVTYPE_TAP; + } + } + + vpnConfig.m_setDevName = false; + vpnConfig.m_devName.clear(); + if (m_vpnData.contains(KYVPN_DEV_KEY)) { + vpnConfig.m_setDevName = true; + vpnConfig.m_devName = m_vpnData.value(KYVPN_DEV_KEY); + } + + vpnConfig.m_useTunnelMtu = false; + vpnConfig.m_tunnelMtu.clear(); + if (m_vpnData.contains(KYVPN_TUNNELMTU_KEY)) { + vpnConfig.m_useTunnelMtu = true; + vpnConfig.m_tunnelMtu = m_vpnData.value(KYVPN_TUNNELMTU_KEY); + } + + vpnConfig.m_useFragmentSize = false; + vpnConfig.m_fragmentSize.clear(); + if (m_vpnData.contains(KYVPN_FRAGMENTSIZE_KEY)) { + vpnConfig.m_useFragmentSize = true; + vpnConfig.m_fragmentSize = m_vpnData.value(KYVPN_FRAGMENTSIZE_KEY); + } + + vpnConfig.m_mssfix = false; + if (m_vpnData.contains(KYVPN_MSSFIX_KEY) && m_vpnData.value(KYVPN_MSSFIX_KEY) == KYVPN_YES) { + vpnConfig.m_mssfix = true; + } + + vpnConfig.m_remoteRandom = false; + if (m_vpnData.contains(KYVPN_REMOTERANDOM_KEY) && m_vpnData.value(KYVPN_REMOTERANDOM_KEY) == KYVPN_YES) { + vpnConfig.m_remoteRandom = true; + } + + vpnConfig.m_ipv6TunLink = false; + if (m_vpnData.contains(KYVPN_TUNIPV6_KEY) && m_vpnData.value(KYVPN_TUNIPV6_KEY) == KYVPN_YES) { + vpnConfig.m_ipv6TunLink = true; + } + + vpnConfig.m_setPingCycle = false; + vpnConfig.m_pingCycle.clear(); + if (m_vpnData.contains(KYVPN_PING_KEY)) { + vpnConfig.m_setPingCycle = true; + vpnConfig.m_pingCycle = m_vpnData.value(KYVPN_PING_KEY); + } + + vpnConfig.m_usePingMethod = false; + vpnConfig.m_pingMethod = KYVPNPING_EXIT; + vpnConfig.m_pingMethodTime.clear(); + if (m_vpnData.contains(KYVPN_PINGEXIT_KEY)) { + vpnConfig.m_usePingMethod = true; + vpnConfig.m_pingMethod = KYVPNPING_EXIT; + vpnConfig.m_pingMethodTime = m_vpnData.value(KYVPN_PINGEXIT_KEY); + } else if (m_vpnData.contains(KYVPN_PINGRESTART_KEY)) { + vpnConfig.m_usePingMethod = true; + vpnConfig.m_pingMethod = KYVPNPING_RESTART; + vpnConfig.m_pingMethodTime = m_vpnData.value(KYVPN_PINGRESTART_KEY); + } + + vpnConfig.m_float = false; + if (m_vpnData.contains(KYVPN_FLOAT_KEY) && m_vpnData.value(KYVPN_FLOAT_KEY) == KYVPN_YES) { + vpnConfig.m_float = true; + } + + vpnConfig.m_setMaxRoute = false; + vpnConfig.m_maxRoute.clear(); + if (m_vpnData.contains(KYVPN_MAXROUTES_KEY)) { + vpnConfig.m_setMaxRoute = true; + vpnConfig.m_maxRoute = m_vpnData.value(KYVPN_MAXROUTES_KEY); + } + + vpnConfig.m_checkServerCa = KYCHECKSERVER_NONE; + vpnConfig.m_verifyName.clear(); + if (m_vpnData.contains(KYVPN_VERIFYX509NAME_KEY)) { + QString nameValue = m_vpnData.value(KYVPN_VERIFYX509NAME_KEY); + QString nameType = nameValue.section(":", 0, 0); + if (nameType == X509NAME_SUBJECT) { + vpnConfig.m_checkServerCa = KYCHECKSERVER_ENTIRETHEME; + } else if (nameType == X509NAME_NAME) { + vpnConfig.m_checkServerCa = KYCHECKSERVER_ENTIRENAME; + } else if (nameType == X509NAME_NAMEPREFIX) { + vpnConfig.m_checkServerCa = KYCHECKSERVER_PRENAME; + } + vpnConfig.m_verifyName = nameValue.section(":", 1, 1); + } + + vpnConfig.m_useRemoteCertTls = false; + vpnConfig.m_remoteCertType = KYVPNCERT_SERVER; + if (m_vpnData.contains(KYVPN_REMOTECERTTLS_KEY)) { + vpnConfig.m_useRemoteCertTls = true; + if (m_vpnData.value(KYVPN_REMOTECERTTLS_KEY) == KYVPN_SERVER) { + vpnConfig.m_remoteCertType = KYVPNCERT_SERVER; + } else if (m_vpnData.value(KYVPN_REMOTECERTTLS_KEY) == KYVPN_CLIENT) { + vpnConfig.m_remoteCertType = KYVPNCERT_CLIENT; + } + } + + vpnConfig.m_useNsCertTls = false; + vpnConfig.m_nsCertType = KYVPNCERT_SERVER; + if (m_vpnData.contains(KYVPN_NSCERTTYPE_KEY)) { + vpnConfig.m_useNsCertTls = true; + if (m_vpnData.value(KYVPN_NSCERTTYPE_KEY) == KYVPN_SERVER) { + vpnConfig.m_nsCertType = KYVPNCERT_SERVER; + } else if (m_vpnData.value(KYVPN_NSCERTTYPE_KEY) == KYVPN_CLIENT) { + vpnConfig.m_nsCertType = KYVPNCERT_CLIENT; + } + } + + vpnConfig.m_vpnTlsMode = KYVPNTLS_NONE; + if (m_vpnData.contains(KYVPN_TA_KEY)) { + vpnConfig.m_vpnTlsMode = KYVPNTLS_AUTHENTICATION; + vpnConfig.m_vpnKeyFile = m_vpnData.value(KYVPN_TA_KEY); + } else if (m_vpnData.contains(KYVPN_TLSCRYPT_KEY)) { + vpnConfig.m_vpnTlsMode = KYVPNTLS_CRYPT; + vpnConfig.m_vpnKeyFile = m_vpnData.value(KYVPN_TLSCRYPT_KEY); + } + + vpnConfig.m_vpnTlsTaDir.clear(); + if (m_vpnData.contains(KYVPN_TADIR_KEY)) { + vpnConfig.m_vpnTlsTaDir = m_vpnData.value(KYVPN_TADIR_KEY); + } + + vpnConfig.m_vpnProxyType = KYVPNPROXY_NONE; + vpnConfig.m_vpnProxyServer.clear(); + vpnConfig.m_vpnProxyPort.clear(); + vpnConfig.m_vpnProxyRetry = false; + vpnConfig.m_vpnProxyName.clear(); + if (m_vpnData.contains(KYVPN_PROXYTYPE_KEY)) { + if (m_vpnData.value(KYVPN_PROXYTYPE_KEY) == PROXYTYPE_HTTP) { + vpnConfig.m_vpnProxyType = KYVPNPROXY_HTTP; + } else if (m_vpnData.value(KYVPN_PROXYTYPE_KEY) == PROXYTYPE_SOCKS) { + vpnConfig.m_vpnProxyType = KYVPNPROXY_SOCKS; + } + if (m_vpnData.contains(KYVPN_PROXYSERVER_KEY)) { + vpnConfig.m_vpnProxyServer = m_vpnData.value(KYVPN_PROXYSERVER_KEY); + } + if (m_vpnData.contains(KYVPN_PROXYPORT_KEY)) { + vpnConfig.m_vpnProxyPort = m_vpnData.value(KYVPN_PROXYPORT_KEY); + } + if (m_vpnData.contains(KYVPN_PROXYRETRY_KEY) && m_vpnData.value(KYVPN_PROXYRETRY_KEY) == KYVPN_YES) { + vpnConfig.m_vpnProxyRetry = true; + } + if (m_vpnData.contains(KYVPN_HTTPPROXYUSERNAME_KEY)) { + vpnConfig.m_vpnProxyName = m_vpnData.value(KYVPN_HTTPPROXYUSERNAME_KEY); + } + if (m_vpnData.contains(KYVPN_HTTPPROXYPASSWDFLAGS_KEY)) { + switch (m_vpnData.value(KYVPN_HTTPPROXYPASSWDFLAGS_KEY).toInt()) { + case 1: + vpnConfig.m_vpnProxyPasswdPolicy = KYPASSWD_FORTHISUSER; + break; + case 2: + vpnConfig.m_vpnProxyPasswdPolicy = KYPASSWD_ASKEVERYTIME; + break; + case 4: + vpnConfig.m_vpnProxyPasswdPolicy = KYPASSWD_ISNOTREQUIRED; + break; + default : + break; + } + } + if (m_vpnSecrets.contains(KYVPN_HTTPPROXYPASSWD_KEY)) { + vpnConfig.m_vpnProxyPasswd = m_vpnSecrets.value(KYVPN_HTTPPROXYPASSWD_KEY); + } + } + + vpnConfig.m_useKeysize = false; + vpnConfig.m_keySize.clear(); + vpnConfig.m_hmacAuthMethod = KYHMACAUTH_DEFAULT; + if (m_vpnData.contains(KYVPN_KEYSIZE_KEY)) { + vpnConfig.m_useKeysize = true; + vpnConfig.m_keySize = m_vpnData.value(KYVPN_KEYSIZE_KEY); + if (m_vpnData.contains(KYVPN_AUTH_KEY)) { + vpnConfig.m_hmacAuthMethod = getHmacAuthMethod(m_vpnData.value(KYVPN_AUTH_KEY)); + + } + } +} + +void KyVpnConnectOperation::setOpenvpnConfig(KyVpnConfig &vpnConfig) +{ + m_vpnData.insert(KYVPN_CONNECTIONTYPE_KEY, m_authMethodMap.key(vpnConfig.m_authMethod)); + + if (!vpnConfig.m_gateway.isEmpty()) { + m_vpnData.insert(KYVPN_REMOTE_KEY, vpnConfig.m_gateway); + } + + switch (vpnConfig.m_authMethod) { + case KYAUTH_CERTIFICATE: + if (!vpnConfig.m_caCertificate.isEmpty()) { + m_vpnData.insert(KYVPN_CA_KEY, vpnConfig.m_caCertificate); + } + if (!vpnConfig.m_userCertificate.isEmpty()) { + m_vpnData.insert(KYVPN_CERT_KEY, vpnConfig.m_userCertificate); + } + if (!vpnConfig.m_userKey.isEmpty()) { + m_vpnData.insert(KYVPN_USERKEY_KEY, vpnConfig.m_userKey); + } + setCertPasswdAndPolicy(vpnConfig); + break; + case KYAUTH_PASSWD: + if (!vpnConfig.m_caCertificate.isEmpty()) { + m_vpnData.insert(KYVPN_CA_KEY, vpnConfig.m_caCertificate); + } + if (!vpnConfig.m_userName.isEmpty()) { + m_vpnData.insert(KYVPN_USERNAME_KEY, vpnConfig.m_userName); + } + setUsrPasswdAndPolicy(vpnConfig); + break; + case KYAUTH_CERTIFICATEANDPASSWD: + if (!vpnConfig.m_caCertificate.isEmpty()) { + m_vpnData.insert(KYVPN_CA_KEY, vpnConfig.m_caCertificate); + } + if (!vpnConfig.m_userCertificate.isEmpty()) { + m_vpnData.insert(KYVPN_CERT_KEY, vpnConfig.m_userCertificate); + } + if (!vpnConfig.m_userKey.isEmpty()) { + m_vpnData.insert(KYVPN_USERKEY_KEY, vpnConfig.m_userKey); + } + if (!vpnConfig.m_userName.isEmpty()) { + m_vpnData.insert(KYVPN_USERNAME_KEY, vpnConfig.m_userName); + } + setUsrPasswdAndPolicy(vpnConfig); + setCertPasswdAndPolicy(vpnConfig); + break; + case KYAUTH_STATICPASSWD: + if (!vpnConfig.m_staticKey.isEmpty()) { + m_vpnData.insert(KYVPN_STATICKEY_KEY, vpnConfig.m_staticKey); + } + if (!vpnConfig.m_vpnKeyDir.isEmpty()) { + m_vpnData.insert(KYVPN_STATICKEYDIR_KEY, vpnConfig.m_vpnKeyDir); + } + if (!vpnConfig.m_localAddress.isEmpty()) { + m_vpnData.insert(KYVPN_LOCALIP_KEY, vpnConfig.m_localAddress); + } + if (!vpnConfig.m_remoteAddress.isEmpty()) { + m_vpnData.insert(KYVPN_REMOTEIP_KEY, vpnConfig.m_remoteAddress); + } + break; + + default : + break; + } + + if (vpnConfig.m_useAssignPort && !vpnConfig.m_assignPort.isEmpty()) { + m_vpnData.insert(KYVPN_PORT_KEY, vpnConfig.m_assignPort); + } + + if (vpnConfig.m_useRenegSeconds && !vpnConfig.m_renegSeconds.isEmpty()) { + m_vpnData.insert(KYVPN_RENEGSEC_KEY, vpnConfig.m_renegSeconds); + } + + if (vpnConfig.m_useCompress) { + switch (vpnConfig.m_openvpnCompress) { + case KYCOMP2_LZODISABLE: + m_vpnData.insert(KYVPN_COMPLZO_KEY, COMPLZO_LZODISABLE); + break; + case KYCOMP2_LZOADAPTIVE: + m_vpnData.insert(KYVPN_COMPLZO_KEY, COMPLZO_ADAPTIVE); + break; + case KYCOMP2_LZO: + m_vpnData.insert(KYVPN_COMPRESS_KEY, COMPRESS_LZO); + break; + case KYCOMP2_LZ4: + m_vpnData.insert(KYVPN_COMPRESS_KEY, COMPRESS_LZ4); + break; + case KYCOMP2_LZ4V2: + m_vpnData.insert(KYVPN_COMPRESS_KEY, COMPRESS_LZ4V2); + break; + case KYCOMP2_AUTO: + m_vpnData.insert(KYVPN_COMPRESS_KEY, KYVPN_YES); + break; + } + } + + if (vpnConfig.m_useTcpLink) { + m_vpnData.insert(KYVPN_PROTOTCP_KEY, KYVPN_YES); + } + + if (vpnConfig.m_setDevType) { + switch (vpnConfig.m_devType) { + case KYVIRDEVTYPE_TUN: + m_vpnData.insert(KYVPN_DEVTYPE_KEY, DEVTYPE_TUN); + break; + case KYVIRDEVTYPE_TAP: + m_vpnData.insert(KYVPN_DEVTYPE_KEY, DEVTYPE_TAP); + break; + default : + break; + } + } + + if (vpnConfig.m_setDevName && !vpnConfig.m_devName.isEmpty()) { + m_vpnData.insert(KYVPN_DEV_KEY, vpnConfig.m_devName); + } + + if (vpnConfig.m_useTunnelMtu && !vpnConfig.m_tunnelMtu.isEmpty()) { + m_vpnData.insert(KYVPN_TUNNELMTU_KEY, vpnConfig.m_tunnelMtu); + } + + if (vpnConfig.m_useFragmentSize && !vpnConfig.m_fragmentSize.isEmpty()) { + m_vpnData.insert(KYVPN_FRAGMENTSIZE_KEY, vpnConfig.m_fragmentSize); + } + + if (vpnConfig.m_mssfix) { + m_vpnData.insert(KYVPN_MSSFIX_KEY, KYVPN_YES); + } + + if (vpnConfig.m_remoteRandom) { + m_vpnData.insert(KYVPN_REMOTERANDOM_KEY, KYVPN_YES); + } + + if (vpnConfig.m_ipv6TunLink) { + m_vpnData.insert(KYVPN_TUNIPV6_KEY, KYVPN_YES); + } + + if (vpnConfig.m_setPingCycle && !vpnConfig.m_pingCycle.isEmpty()) { + m_vpnData.insert(KYVPN_PING_KEY, vpnConfig.m_pingCycle); + } + + if (vpnConfig.m_usePingMethod) { + switch (vpnConfig.m_pingMethod) { + case KYVPNPING_EXIT: + m_vpnData.insert(KYVPN_PINGEXIT_KEY, vpnConfig.m_pingMethodTime); + break; + case KYVPNPING_RESTART: + m_vpnData.insert(KYVPN_PINGRESTART_KEY, vpnConfig.m_pingMethodTime); + break; + default : + break; + } + } + + if (vpnConfig.m_float) { + m_vpnData.insert(KYVPN_FLOAT_KEY, KYVPN_YES); + } + + if (vpnConfig.m_setMaxRoute && !vpnConfig.m_maxRoute.isEmpty()) { + m_vpnData.insert(KYVPN_MAXROUTES_KEY, vpnConfig.m_maxRoute); + } + + if (vpnConfig.m_checkServerCa != KYCHECKSERVER_NONE && !vpnConfig.m_verifyName.isEmpty()) { + QString nameStr; + nameStr.clear(); + switch (vpnConfig.m_checkServerCa) { + case KYCHECKSERVER_ENTIRETHEME: + nameStr = X509NAME_SUBJECT + QString(":") + vpnConfig.m_verifyName; + break; + case KYCHECKSERVER_ENTIRENAME: + nameStr = X509NAME_NAME + QString(":") + vpnConfig.m_verifyName; + break; + case KYCHECKSERVER_PRENAME: + nameStr = X509NAME_NAMEPREFIX + QString(":") + vpnConfig.m_verifyName; + break; + default : + break; + } + m_vpnData.insert(KYVPN_VERIFYX509NAME_KEY, nameStr); + } + + if (vpnConfig.m_useRemoteCertTls) { + switch (vpnConfig.m_remoteCertType) { + case KYVPNCERT_SERVER: + m_vpnData.insert(KYVPN_REMOTECERTTLS_KEY, KYVPN_SERVER); + break; + case KYVPNCERT_CLIENT: + m_vpnData.insert(KYVPN_REMOTECERTTLS_KEY, KYVPN_CLIENT); + break; + default : + break; + } + } + + if (vpnConfig.m_useNsCertTls) { + switch (vpnConfig.m_nsCertType) { + case KYVPNCERT_SERVER: + m_vpnData.insert(KYVPN_NSCERTTYPE_KEY, KYVPN_SERVER); + break; + case KYVPNCERT_CLIENT: + m_vpnData.insert(KYVPN_NSCERTTYPE_KEY, KYVPN_CLIENT); + break; + default : + break; + } + } + + switch (vpnConfig.m_vpnTlsMode) { + case KYVPNTLS_AUTHENTICATION: + m_vpnData.insert(KYVPN_TA_KEY, vpnConfig.m_vpnKeyFile); + break; + case KYVPNTLS_CRYPT: + m_vpnData.insert(KYVPN_TLSCRYPT_KEY, vpnConfig.m_vpnKeyFile); + break; + default : + break; + } + + if (!vpnConfig.m_vpnTlsTaDir.isEmpty() && vpnConfig.m_vpnTlsTaDir != "None") { + m_vpnData.insert(KYVPN_TADIR_KEY, vpnConfig.m_vpnTlsTaDir); + } + + switch (vpnConfig.m_vpnProxyType) { + case KYVPNPROXY_HTTP: + m_vpnData.insert(KYVPN_PROXYTYPE_KEY, PROXYTYPE_HTTP); + break; + case KYVPNPROXY_SOCKS: + m_vpnData.insert(KYVPN_PROXYTYPE_KEY, PROXYTYPE_SOCKS); + break; + default : + break; + } + if (!vpnConfig.m_vpnProxyServer.isEmpty()) { + m_vpnData.insert(KYVPN_PROXYSERVER_KEY, vpnConfig.m_vpnProxyServer); + } + if (!vpnConfig.m_vpnProxyPort.isEmpty()) { + m_vpnData.insert(KYVPN_PROXYPORT_KEY, vpnConfig.m_vpnProxyPort); + } + if (vpnConfig.m_vpnProxyRetry) { + m_vpnData.insert(KYVPN_PROXYRETRY_KEY, KYVPN_YES); + } + if (!vpnConfig.m_vpnProxyName.isEmpty()) { + m_vpnData.insert(KYVPN_HTTPPROXYUSERNAME_KEY, vpnConfig.m_vpnProxyName); + } + + vpnConfig.m_vpnProxyPasswdPolicy = KYPASSWD_FORALLUSER; + if (vpnConfig.m_vpnProxyPasswdPolicy == KYPASSWD_FORALLUSER && !vpnConfig.m_vpnProxyPasswd.isEmpty()) { + m_vpnData.insert(KYVPN_HTTPPROXYPASSWDFLAGS_KEY, "0"); + m_vpnSecrets.insert(KYVPN_HTTPPROXYPASSWD_KEY, vpnConfig.m_vpnProxyPasswd); + } + + if (vpnConfig.m_useKeysize) { + m_vpnData.insert(KYVPN_KEYSIZE_KEY, vpnConfig.m_keySize); + m_vpnData.insert(KYVPN_AUTH_KEY, m_hmacMap.key(vpnConfig.m_hmacAuthMethod)); + } +} + +KyHMACAuthMethod KyVpnConnectOperation::getHmacAuthMethod(const QString method) +{ + if (m_hmacMap.contains(method)) { + return m_hmacMap.value(method); + } + return KYHMACAUTH_DEFAULT; +} + +KyAuthMethod KyVpnConnectOperation::getAuthMethod(const QString method) +{ + if (m_authMethodMap.contains(method)) { + return m_authMethodMap.value(method); + } + return KYAUTH_ERROR; +} + +void KyVpnConnectOperation::getUsrPasswdAndPolicy(KyVpnConfig &vpnConfig) +{ + vpnConfig.m_userPasswd.clear(); + vpnConfig.m_passwdPolicy = KYPASSWD_ASKEVERYTIME; + if (m_vpnData.contains(KYVPN_PASSWDFLAGS_KEY)) { + switch (m_vpnData.value(KYVPN_PASSWDFLAGS_KEY).toInt()) { + case 0: + vpnConfig.m_passwdPolicy = KYPASSWD_FORALLUSER; + if (m_vpnSecrets.contains(KYVPN_PASSWD_KEY)) { + vpnConfig.m_userPasswd = m_vpnSecrets.value(KYVPN_PASSWD_KEY); + } + break; + case 1: + vpnConfig.m_passwdPolicy = KYPASSWD_FORTHISUSER; + break; + case 2: + vpnConfig.m_passwdPolicy = KYPASSWD_ASKEVERYTIME; + break; + case 4: + vpnConfig.m_passwdPolicy = KYPASSWD_ISNOTREQUIRED; + break; + default : + break; + } + } +} + +void KyVpnConnectOperation::setUsrPasswdAndPolicy(KyVpnConfig &vpnConfig) +{ + switch (vpnConfig.m_passwdPolicy) { + case KYPASSWD_FORTHISUSER: + m_vpnData.insert(KYVPN_PASSWDFLAGS_KEY, "1"); + break ; + case KYPASSWD_FORALLUSER: + m_vpnData.insert(KYVPN_PASSWDFLAGS_KEY, "0"); + break ; + case KYPASSWD_ASKEVERYTIME: + m_vpnData.insert(KYVPN_PASSWDFLAGS_KEY, "2"); + break ; + case KYPASSWD_ISNOTREQUIRED: + m_vpnData.insert(KYVPN_PASSWDFLAGS_KEY, "4"); + break ; + default : + break; + } + if (vpnConfig.m_passwdPolicy == KYPASSWD_FORALLUSER && !vpnConfig.m_userPasswd.isEmpty()) { + m_vpnSecrets.insert(KYVPN_PASSWD_KEY, vpnConfig.m_userPasswd); + } +} + +void KyVpnConnectOperation::getCertPasswdAndPolicy(KyVpnConfig &vpnConfig) +{ + vpnConfig.m_privatePasswd.clear(); + vpnConfig.m_privatePasswdPolicy = KYPASSWD_ASKEVERYTIME; + if (m_vpnData.contains(KYVPN_CERTPASSWDFLAGS_KEY)) { + switch (m_vpnData.value(KYVPN_CERTPASSWDFLAGS_KEY).toInt()) { + case 0: + vpnConfig.m_privatePasswdPolicy = KYPASSWD_FORALLUSER; + if (m_vpnSecrets.contains(KYVPN_CERTPASSWD_KEY)) { + vpnConfig.m_privatePasswd = m_vpnSecrets.value(KYVPN_CERTPASSWD_KEY); + } + break; + case 1: + vpnConfig.m_privatePasswdPolicy = KYPASSWD_FORTHISUSER; + break; + case 2: + vpnConfig.m_privatePasswdPolicy = KYPASSWD_ASKEVERYTIME; + break; + case 4: + vpnConfig.m_privatePasswdPolicy = KYPASSWD_ISNOTREQUIRED; + break; + default : + break; + } + } +} + +void KyVpnConnectOperation::setCertPasswdAndPolicy(KyVpnConfig &vpnConfig) +{ + switch (vpnConfig.m_privatePasswdPolicy) { + case KYPASSWD_FORTHISUSER: + m_vpnData.insert(KYVPN_CERTPASSWDFLAGS_KEY, "1"); + break ; + case KYPASSWD_FORALLUSER: + m_vpnData.insert(KYVPN_CERTPASSWDFLAGS_KEY, "0"); + break ; + case KYPASSWD_ASKEVERYTIME: + m_vpnData.insert(KYVPN_CERTPASSWDFLAGS_KEY, "2"); + break ; + case KYPASSWD_ISNOTREQUIRED: + m_vpnData.insert(KYVPN_CERTPASSWDFLAGS_KEY, "4"); + break ; + default : + break; + } + + if (vpnConfig.m_privatePasswdPolicy == KYPASSWD_FORALLUSER && !vpnConfig.m_privatePasswd.isEmpty()) { + m_vpnSecrets.insert(KYVPN_CERTPASSWD_KEY, vpnConfig.m_privatePasswd); + } +} + + +void KyVpnConnectOperation::activateVpnConnection(const QString connectUuid) +{ + QString connectPath = ""; + QString deviceIdentifier = ""; + QString connectName = ""; + QString specificObject = ""; + NetworkManager::Connection::Ptr connectPtr = nullptr; + + qDebug()<<"it will activate vpn connect"<settings()->connectionType()) { + QString errorMessage = tr("the connect type is") + + connectPtr->settings()->connectionType() + + tr(", but it is not vpn"); + qWarning()<path(); + connectName = connectPtr->name(); + specificObject = deviceIdentifier = QStringLiteral("/"); + + QDBusPendingCallWatcher * watcher; + watcher = new QDBusPendingCallWatcher{NetworkManager::activateConnection(connectPath, deviceIdentifier, specificObject), this}; + connect(watcher, &QDBusPendingCallWatcher::finished, [this, connectName] (QDBusPendingCallWatcher * watcher) { + if (watcher->isError() || !watcher->isValid()) { + QString errorMessage = tr("activate vpn connection failed: ") + watcher->error().message(); + qWarning()<activateConnectionError(errorMessage); + } else { + qWarning()<<"active vpn connect complete."; + } + + watcher->deleteLater(); + }); + + return; +} + +void KyVpnConnectOperation::deactivateVpnConnection(const QString activeConnectName, const QString &activeConnectUuid) +{ + qDebug()<<"deactivetate connect name"< +#include + +#include "kylinnetworkresourcemanager.h" +#include "kylinconnectsetting.h" +#include "kylinconnectoperation.h" +#include "kylinconnectresource.h" +#include "kyenterpricesettinginfo.h" +#include + + +#define VPN_SERVERTYPE_L2TP "org.freedesktop.NetworkManager.l2tp" +#define VPN_SERVERTYPE_PPTP "org.freedesktop.NetworkManager.pptp" +#define VPN_SERVERTYPE_OPENVPN "org.freedesktop.NetworkManager.openvpn" +#define VPN_SERVERTYPE_STRONGSWAN "org.freedesktop.NetworkManager.strongswan" + +#define KYVPN_VPN_KEY "vpn" + +#define KYVPN_GATEWAY_KEY "gateway" +#define KYVPN_REMOTE_KEY "remote" +#define KYVPN_ADDRESS_KEY "address" + +#define KYVPN_USER_KEY "user" +#define KYVPN_PASSWD_KEY "password" +#define KYVPN_SECRETS_KEY "secrets" +#define KYVPN_PASSWDFLAGS_KEY "password-flags" + +#define KYVPN_REFUSEPAP_KEY "refuse-pap" +#define KYVPN_REFUSECHAP_KEY "refuse-chap" +#define KYVPN_REFUSEEAP_KEY "refuse-eap" +#define KYVPN_REFUSEMSCHAP_KEY "refuse-mschap" +#define KYVPN_REFUSEMSCHAPV2_KEY "refuse-mschapv2" + +#define KYVPN_NOVJCOMP_KEY "no-vj-comp" +#define KYVPN_NOACCOMP_KEY "noaccomp" +#define KYVPN_NOBSDCOMP_KEY "nobsdcomp" +#define KYVPN_NODEFLATE_KEY "nodeflate" +#define KYVPN_NOPCOMP_KEY "nopcomp" + +#define KYVPN_DOMAIN_KEY "domain" +#define KYVPN_REQUIREMPPE_KEY "require-mppe" +#define KYVPN_MPPESTATEFUL_KEY "mppe-stateful" +#define KYVPN_LCPECHOFAILURE_KEY "lcp-echo-failure" +#define KYVPN_LCPECHOINTERVAL_KEY "lcp-echo-interval" +#define KYVPN_MRU_KEY "mru" +#define KYVPN_MTU_KEY "mtu" + +#define KYVPN_REQUIREMPPE128_KEY "require-mppe-128" +#define KYVPN_REQUIREMPPE40_KEY "require-mppe-40" + +#define KYVPN_USERCERT_KEY "usercert" +#define KYVPN_USERKEY_KEY "userkey" +#define KYVPN_CERTPASSWD_KEY "cert-pass" +#define KYVPN_CERTPASSWDFLAGS_KEY "cert-pass-flags" +#define KYVPN_PIN_KEY "pin" +#define KYVPN_VIRTUAL_KEY "virtual" +#define KYVPN_ENCAP_KEY "encap" +#define KYVPN_IPCOMP_KEY "ipcomp" +#define KYVPN_PROPOSAL_KEY "proposal" +#define KYVPN_IKE_KEY "ike" +#define KYVPN_ESP_KEY "esp" + +//openvpn +#define KYVPN_CONNECTIONTYPE_KEY "connection-type" + +#define KYVPN_CA_KEY "ca" +#define KYVPN_CERT_KEY "cert" +#define KYVPN_KEY_KEY "key" + +#define KYVPN_USERNAME_KEY "username" +#define KYVPN_STATICKEY_KEY "static-key" +#define KYVPN_STATICKEYDIR_KEY "static-key-direction" +#define KYVPN_LOCALIP_KEY "local-ip" +#define KYVPN_REMOTEIP_KEY "remote-ip" + +#define KYVPN_PORT_KEY "port" +#define KYVPN_RENEGSEC_KEY "reneg-seconds" +#define KYVPN_COMPLZO_KEY "comp-lzo" +#define KYVPN_COMPRESS_KEY "compress" +#define COMPLZO_LZODISABLE "no-by-default" +#define COMPLZO_ADAPTIVE "adaptive" +#define COMPRESS_LZO "lzo" +#define COMPRESS_LZ4 "lz4" +#define COMPRESS_LZ4V2 "lz4-v2" + +#define KYVPN_PROTOTCP_KEY "proto-tcp" +#define KYVPN_DEVTYPE_KEY "dev-type" +#define DEVTYPE_TUN "tun" +#define DEVTYPE_TAP "tap" +#define KYVPN_DEV_KEY "dev" +#define KYVPN_TUNNELMTU_KEY "tunnel-mtu" +#define KYVPN_FRAGMENTSIZE_KEY "fragment-size" +#define KYVPN_MSSFIX_KEY "mssfix" +#define KYVPN_REMOTERANDOM_KEY "remote-random" +#define KYVPN_TUNIPV6_KEY "tun-ipv6" +#define KYVPN_PING_KEY "ping" +#define KYVPN_PINGEXIT_KEY "ping-exit" +#define KYVPN_PINGRESTART_KEY "ping-restart" +#define KYVPN_FLOAT_KEY "float" +#define KYVPN_MAXROUTES_KEY "max-routes" +#define KYVPN_VERIFYX509NAME_KEY "verify-x509-name" +#define X509NAME_SUBJECT "subject" +#define X509NAME_NAME "name" +#define X509NAME_NAMEPREFIX "name-prefix" + +#define KYVPN_REMOTECERTTLS_KEY "remote-cert-tls" +#define KYVPN_NSCERTTYPE_KEY "ns-cert-type" +#define KYVPN_SERVER "server" +#define KYVPN_CLIENT "client" + +#define KYVPN_TA_KEY "ta" +#define KYVPN_TLSCRYPT_KEY "tls-crypt" +#define KYVPN_TADIR_KEY "ta-dir" + +#define KYVPN_PROXYTYPE_KEY "proxy-type" +#define PROXYTYPE_HTTP "http" +#define PROXYTYPE_SOCKS "socks" +#define KYVPN_PROXYSERVER_KEY "proxy-server" +#define KYVPN_PROXYPORT_KEY "proxy-port" +#define KYVPN_PROXYRETRY_KEY "proxy-retry" +#define KYVPN_HTTPPROXYUSERNAME_KEY "http-proxy-username" +#define KYVPN_HTTPPROXYPASSWD_KEY "http-proxy-password" +#define KYVPN_HTTPPROXYPASSWDFLAGS_KEY "http-proxy-password-flags" + +#define KYVPN_KEYSIZE_KEY "keysize" +#define KYVPN_AUTH_KEY "auth" + +#define KYVPN_METHOD_KEY "method" + +#define KYVPN_YES "yes" +#define KYVPN_NO "no" + +//VPN类型 +enum KyVpnType{ + KYVPNTYPE_UNKNOWN = -1, + KYVPNTYPE_L2TP = 0, + KYVPNTYPE_OPENVPN, + KYVPNTYPE_PPTP, + KYVPNTYPE_STRONGSWAN +}; + +//密码策略 +enum KyPasswdPolicy{ + KYPASSWD_FORTHISUSER = 0, + KYPASSWD_FORALLUSER, + KYPASSWD_ASKEVERYTIME, + KYPASSWD_ISNOTREQUIRED = 4 +}; + +//认证方式 +enum KyAuthMethod2 { + KYAUTH2_PAP = 1u << 0, //PAP认证 + KYAUTH2_CHAP = 1u << 1, //CHAP认证 + KYAUTH2_MSCHAP = 1u << 2, //MSCHAP认证 + KYAUTH2_MSCHAPV2 = 1u << 3, //MSCHAPV2认证 + KYAUTH2_EAP = 1u << 4, //EAP认证 + KYAUTH2_ALL = KYAUTH2_PAP | KYAUTH2_CHAP | KYAUTH2_MSCHAP | KYAUTH2_MSCHAPV2 | KYAUTH2_EAP +}; +Q_DECLARE_FLAGS(KyAuthMethods, KyAuthMethod2) + +//压缩方式 +enum KyCompressMethod { + KYCOMP_BSD = 1u << 0, //允许BSD压缩 + KYCOMP_DEFLATE = 1u << 1, //允许Deflate压缩 + KYCOMP_TCP = 1u << 2, //允许TCP头压缩 + KYCOMP_PROTO = 1u << 3, //使用协议域压缩协商 + KYCOMP_ADDR = 1u << 4, //使用地址/控制压缩 + KYCOMP_ALL = KYCOMP_BSD | KYCOMP_DEFLATE | KYCOMP_TCP | KYCOMP_PROTO | KYCOMP_ADDR +}; +Q_DECLARE_FLAGS(KyCompressMethods, KyCompressMethod) + +//高级设置 +enum KyMPPEMethod { + KYMPPE_DEFAULT = 0, //默认MPPE加密 + KYMPPE_REQUIRE128, //128位加密 + KYMPPE_REQUIRE40 //40位加密 +}; + +enum KyAuthMethod{ + KYAUTH_ERROR = -1, + KYAUTH_PASSWD = 0, + KYAUTH_KEY, + KYAUTH_AGENT, + KYAUTH_SMARTCARD, + KYAUTH_EAP, + KYAUTH_CERTIFICATE, + KYAUTH_CERTIFICATEANDPASSWD, + KYAUTH_STATICPASSWD +}; + +enum KyCompressMethod2{ + KYCOMP2_LZODISABLE = 0, + KYCOMP2_LZO, + KYCOMP2_LZ4, + KYCOMP2_LZ4V2, + KYCOMP2_LZOADAPTIVE, + KYCOMP2_AUTO +}; + +enum KyVirtualDeviceType{ + KYVIRDEVTYPE_TUN = 0, + KYVIRDEVTYPE_TAP +}; + +enum KyVpnPingMethod{ + KYVPNPING_EXIT = 0, + KYVPNPING_RESTART +}; + +enum KyVpnCheckServerMethod{ + KYCHECKSERVER_NONE = 0, + KYCHECKSERVER_ENTIRETHEME, + KYCHECKSERVER_ENTIRENAME, + KYCHECKSERVER_PRENAME +}; + +enum KyVpnCertType{ + KYVPNCERT_SERVER = 0, + KYVPNCERT_CLIENT +}; + +enum KyVpnTlsMode{ + KYVPNTLS_NONE = 0, + KYVPNTLS_AUTHENTICATION, + KYVPNTLS_CRYPT +}; + +enum KyVpnProxyType{ + KYVPNPROXY_NONE = 0, + KYVPNPROXY_HTTP, + KYVPNPROXY_SOCKS +}; + +enum KyHMACAuthMethod{ + KYHMACAUTH_DEFAULT = 0, + KYHMACAUTH_NONE, + KYHMACAUTH_MD4, + KYHMACAUTH_MD5, + KYHMACAUTH_SHA1, + KYHMACAUTH_SHA224, + KYHMACAUTH_SHA256, + KYHMACAUTH_SHA384, + KYHMACAUTH_SHA512, + KYHMACAUTH_RIPEMD160 +}; + +class KyVpnConfig : public KyConnectSetting +{ +public: + KyVpnType m_vpnType; + QString m_vpnName; + QString m_gateway; + + //认证方式 + KyAuthMethod m_authMethod; + //VPN用户密码信息 + QString m_userName; + //用户密码 + QString m_userPasswd; + //密码策略 + KyPasswdPolicy m_passwdPolicy = KYPASSWD_ASKEVERYTIME; + //NT域 + QString m_ntDomain; + + //CA证书 + QString m_caCertificate; + //用户证书 + QString m_userCertificate; + //用户私钥 + QString m_userKey; + //静态密钥 + QString m_staticKey; + //用户私有密钥密码 + QString m_privatePasswd; + //用户私有密码策略 + KyPasswdPolicy m_privatePasswdPolicy = KYPASSWD_ASKEVERYTIME; + //密钥方向 + QString m_vpnKeyDir; + //本地IP地址 + QString m_localAddress; + //远程IP地址 + QString m_remoteAddress; + //PIN码 + QString m_pinId; + + //MPPE加密开关 + bool m_mppeEnable = false; + //MPPE加密算法 + KyMPPEMethod m_mppeEncryptMethod = KYMPPE_DEFAULT; + //使用有状态加密 + bool m_isAllowStatefulEncryption = false; + //发送PPP回显包 + bool m_sendPppPackage = false; + //认证方式 + KyAuthMethods m_authMethods = KYAUTH2_ALL; + //压缩方式 + KyCompressMethods m_compressMethods = KYCOMP_ALL; + //MRU 最大接收单元 + QString m_mru; + //MTU 最大传输单元 + QString m_mtu; + //请求使用内部IP + bool m_virtual; + //强制UDP封装 + bool m_encap; + //使用IP压缩 + bool m_ipcomp; + //启用自定义密码建议 + bool m_proposal; + //IKE + QString m_ike; + //ESP + QString m_esp; + + //使用自定义网关端口 + bool m_useAssignPort; + QString m_assignPort; + + //使用自定义重协商间隔 + bool m_useRenegSeconds; + QString m_renegSeconds; + + //使用压缩 + bool m_useCompress; + KyCompressMethod2 m_openvpnCompress; + + //使用TCP连接 + bool m_useTcpLink; + + //设置虚拟设备类型 + bool m_setDevType; + KyVirtualDeviceType m_devType; + + //设置虚拟设备名称 + bool m_setDevName; + QString m_devName; + + //使用自定义隧道最大单元传输 + bool m_useTunnelMtu; + QString m_tunnelMtu; + + //使用自定义UDP分片大小 + bool m_useFragmentSize; + QString m_fragmentSize; + + //限制TCP最大段尺寸 + bool m_mssfix; + + //随机化远程主机 + bool m_remoteRandom; + + //IPv6 tun link + bool m_ipv6TunLink; + + //指定Ping周期 + bool m_setPingCycle; + QString m_pingCycle; + + //指定退出或重启Ping + bool m_usePingMethod; + KyVpnPingMethod m_pingMethod; + QString m_pingMethodTime; + + //接受来自任何地址(Float)已通过身份验证的数据包 + bool m_float; + + //指定路由上限 + bool m_setMaxRoute; + QString m_maxRoute; + + //服务器证书检验 + KyVpnCheckServerMethod m_checkServerCa; + + //主题匹配 + QString m_verifyName; + + //验证对等(服务器)证书用法签名 + bool m_useRemoteCertTls; + KyVpnCertType m_remoteCertType; + + //验证对等(服务器)证书nsCertType签名 + bool m_useNsCertTls; + KyVpnCertType m_nsCertType; + + //其他TLS身份验证 + //模式 + KyVpnTlsMode m_vpnTlsMode; + //密钥文件 + QString m_vpnKeyFile; + //密钥方向 + QString m_vpnTlsTaDir; + + //代理 + //代理类型 + KyVpnProxyType m_vpnProxyType; + //服务器地址 + QString m_vpnProxyServer; + //端口 + QString m_vpnProxyPort; + //出错时无限重试 + bool m_vpnProxyRetry; + //代理用户名 + QString m_vpnProxyName; + //代理用户名 + QString m_vpnProxyPasswd; + //代理密码策略 + KyPasswdPolicy m_vpnProxyPasswdPolicy = KYPASSWD_ASKEVERYTIME; + + //安全 + //使用自定义密钥大小 + bool m_useKeysize; + QString m_keySize; + //HMAC认证 + KyHMACAuthMethod m_hmacAuthMethod; + + //IPv4Setting + QStringList m_ipv4DnsSearch; + QString m_ipv4DhcpClientId; + + //IPv6Setting + QStringList m_ipv6DnsSearch; +}; + + + +class KyVpnConnectOperation : public KyConnectOperation +{ + Q_OBJECT +public: + explicit KyVpnConnectOperation(QObject *parent = nullptr); + +public: + void createVpnConnect(KyVpnConfig &vpnSettings); + void setVpnConfig(QString connectUuid, KyVpnConfig &vpnConfig); + KyVpnConfig getVpnConfig(QString connectUuid); + + void activateVpnConnection(const QString connectUuid); + void deactivateVpnConnection(const QString activeConnectName, const QString &activeConnectUuid); + void deleteVpnConnect(const QString &connectUuid); + +private: + KyHMACAuthMethod getHmacAuthMethod(const QString method); + KyAuthMethod getAuthMethod(const QString method); + + void getConnectionSetting(QString connectUuid, KyVpnConfig &vpnConfig); + void setConnectionSetting(NetworkManager::ConnectionSettings::Ptr connectionSettings, KyVpnConfig &vpnConfig); + + void getL2tpConfig(KyVpnConfig &vpnConfig); + void setL2tpConfig(KyVpnConfig &vpnConfig); + void getPptpConfig(KyVpnConfig &vpnConfig); + void setPptpConfig(KyVpnConfig &vpnConfig); + void getStrongswanConfig(KyVpnConfig &vpnConfig); + void setStrongswanConfig(KyVpnConfig &vpnConfig); + void getOpenvpnConfig(KyVpnConfig &vpnConfig); + void setOpenvpnConfig(KyVpnConfig &vpnConfig); + + void getUsrPasswdAndPolicy(KyVpnConfig &vpnConfig); + void setUsrPasswdAndPolicy(KyVpnConfig &vpnConfig); + + void getCertPasswdAndPolicy(KyVpnConfig &vpnConfig); + void setCertPasswdAndPolicy(KyVpnConfig &vpnConfig); + + NMVariantMapMap setIpConfig(NetworkManager::ConnectionSettings::Ptr connectionSettings, KyVpnConfig &vpnConfig); + +private: + QMap m_authMethodMap = { + {"password" , KYAUTH_PASSWD }, + {"key" , KYAUTH_KEY }, + {"agent" , KYAUTH_AGENT }, + {"smartcard" , KYAUTH_SMARTCARD }, + {"eap" , KYAUTH_EAP }, + {"tls" , KYAUTH_CERTIFICATE }, + {"password-tls" , KYAUTH_CERTIFICATEANDPASSWD }, + {"static-password" , KYAUTH_STATICPASSWD } + }; + + QMap m_hmacMap = { + {"none" , KYHMACAUTH_NONE }, + {"RSA-MD4" , KYHMACAUTH_MD4 }, + {"MD5" , KYHMACAUTH_MD5 }, + {"SHA1" , KYHMACAUTH_SHA1 }, + {"SHA224" , KYHMACAUTH_SHA224 }, + {"SHA256" , KYHMACAUTH_SHA256 }, + {"SHA384" , KYHMACAUTH_SHA384 }, + {"SHA512" , KYHMACAUTH_SHA512 }, + {"RIPEMD160" , KYHMACAUTH_RIPEMD160 } + }; + + NMStringMap m_vpnData; + NMStringMap m_vpnSecrets; +}; + +#endif // KYVPNCONNECTOPERATION_H diff --git a/src/backend/dbus-interface/kywirelessconnectoperation.cpp b/src/backend/dbus-interface/kywirelessconnectoperation.cpp index 972178c5..8cde9ded 100644 --- a/src/backend/dbus-interface/kywirelessconnectoperation.cpp +++ b/src/backend/dbus-interface/kywirelessconnectoperation.cpp @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "kywirelessconnectoperation.h" #include "kylinutil.h" @@ -166,7 +185,7 @@ void KyWirelessConnectOperation::addConnect(const KyWirelessConnectSetting &conn if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("create wireless connection failed: ") + watcher->error().message(); qWarning()<createConnectionError(errorMessage); + Q_EMIT this->createConnectionError(errorMessage); } else { qDebug()<<"create wireless connect complete"; } @@ -200,7 +219,7 @@ void KyWirelessConnectOperation::addTlsConnect(const KyWirelessConnectSetting &c if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("create wireless tls connection failed: ") + watcher->error().message(); qWarning()<createConnectionError(errorMessage); + Q_EMIT this->createConnectionError(errorMessage); } else { qDebug()<<"create wireless connect complete"; } @@ -234,7 +253,7 @@ void KyWirelessConnectOperation::addPeapConnect(const KyWirelessConnectSetting & if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("create wireless peap connection failed: ") + watcher->error().message(); qWarning()<createConnectionError(errorMessage); + Q_EMIT this->createConnectionError(errorMessage); } else { qDebug()<<"create wireless connect complete"; } @@ -268,7 +287,7 @@ void KyWirelessConnectOperation::addTtlsConnect(const KyWirelessConnectSetting & if (watcher->isError() || !watcher->isValid()) { QString errorMessage = tr("create wireless ttls connection failed: ") + watcher->error().message(); qWarning()<createConnectionError(errorMessage); + Q_EMIT this->createConnectionError(errorMessage); } else { qDebug()<<"create wireless connect complete"; } @@ -379,7 +398,6 @@ void KyWirelessConnectOperation::addFastConnect(const KyWirelessConnectSetting & } watcher->deleteLater(); }); - } void KyWirelessConnectOperation::setWirelessAutoConnect(const QString &uuid, bool bAutoConnect) @@ -389,7 +407,7 @@ void KyWirelessConnectOperation::setWirelessAutoConnect(const QString &uuid, boo if (nullptr == connectPtr) { QString errorMessage = tr("it can not find connection") + uuid; qWarning()<settings(); @@ -476,7 +494,7 @@ void KyWirelessConnectOperation::updateIpv4AndIpv6SettingInfo(const QString &uui if (nullptr == connectPtr) { QString errorMessage = tr("it can not find connection") + uuid; qWarning()<settings(); @@ -493,7 +511,7 @@ void KyWirelessConnectOperation::updateWirelessPersonalConnect(const QString &uu if (nullptr == connectPtr) { QString errorMessage = tr("it can not find connection") + uuid; qWarning()<settings(); @@ -520,7 +538,7 @@ void KyWirelessConnectOperation::updateWirelessEnterPriseTlsConnect(const QStrin if (connectPtr.isNull()) { QString errorMessage = tr("it can not find connection") + uuid; qWarning()<settings(); @@ -538,7 +556,7 @@ void KyWirelessConnectOperation::updateWirelessEnterPrisePeapConnect(const QStri if (nullptr == connectPtr) { QString errorMessage = tr("it can not find connection") + uuid; qWarning()<settings(); @@ -556,7 +574,7 @@ void KyWirelessConnectOperation::updateWirelessEnterPriseTtlsConnect(const QStri if (nullptr == connectPtr) { QString errorMessage = tr("it can not find connection") + uuid; qWarning()<settings(); @@ -642,7 +660,7 @@ void KyWirelessConnectOperation::addAndActiveWirelessConnect(QString & devIface, auto dev = m_networkResourceInstance->findDeviceInterface(devIface); if (dev.isNull()) { - emit addAndActivateConnectionError("can not find device"); + Q_EMIT addAndActivateConnectionError("can not find device"); return; } @@ -708,7 +726,7 @@ void KyWirelessConnectOperation::addAndActiveWirelessConnect(QString & devIface, if (watcher->isError() || !watcher->isValid()) { QString errorMessage = watcher->error().message(); qDebug() << "activation of connection failed " << errorMessage; - emit addAndActivateConnectionError(errorMessage); + Q_EMIT addAndActivateConnectionError(errorMessage); } watcher->deleteLater(); }); @@ -749,7 +767,7 @@ void KyWirelessConnectOperation::addAndActiveWirelessEnterPriseTlsConnect(KyEapM auto dev = m_networkResourceInstance->findDeviceInterface(devIface); if (dev.isNull()) { - emit addAndActivateConnectionError("can not find device"); + Q_EMIT addAndActivateConnectionError("can not find device"); return; } dev_uni = dev->uni(); @@ -770,7 +788,7 @@ void KyWirelessConnectOperation::addAndActiveWirelessEnterPriseTlsConnect(KyEapM if (watcher->isError() || !watcher->isValid()) { QString errorMessage = watcher->error().message(); qDebug() << "addAndActiveWirelessEnterPriseTlsConnect failed " << errorMessage; - emit addAndActivateConnectionError(errorMessage); + Q_EMIT addAndActivateConnectionError(errorMessage); } watcher->deleteLater(); }); @@ -803,7 +821,7 @@ void KyWirelessConnectOperation::addAndActiveWirelessEnterPrisePeapConnect(KyEap auto dev = m_networkResourceInstance->findDeviceInterface(devIface); if (dev.isNull()) { - emit addAndActivateConnectionError("can not find device"); + Q_EMIT addAndActivateConnectionError("can not find device"); return; } dev_uni = dev->uni(); @@ -824,7 +842,7 @@ void KyWirelessConnectOperation::addAndActiveWirelessEnterPrisePeapConnect(KyEap if (watcher->isError() || !watcher->isValid()) { QString errorMessage = watcher->error().message(); qDebug() << "addAndActiveWirelessEnterPrisePeapConnect failed " << errorMessage; - emit addAndActivateConnectionError(errorMessage); + Q_EMIT addAndActivateConnectionError(errorMessage); } watcher->deleteLater(); }); @@ -856,7 +874,7 @@ void KyWirelessConnectOperation::addAndActiveWirelessEnterPriseTtlsConnect(KyEap auto dev = m_networkResourceInstance->findDeviceInterface(devIface); if (dev.isNull()) { - emit addAndActivateConnectionError("can not find device"); + Q_EMIT addAndActivateConnectionError("can not find device"); return; } dev_uni = dev->uni(); @@ -878,7 +896,7 @@ void KyWirelessConnectOperation::addAndActiveWirelessEnterPriseTtlsConnect(KyEap if (watcher->isError() || !watcher->isValid()) { QString errorMessage = watcher->error().message(); qDebug() << "addAndActiveWirelessEnterPriseTtlsConnect failed " << errorMessage; - emit addAndActivateConnectionError(errorMessage); + Q_EMIT addAndActivateConnectionError(errorMessage); } watcher->deleteLater(); }); @@ -1043,7 +1061,7 @@ void KyWirelessConnectOperation::addAndActiveWirelessEnterPriseFastConnect(KyEap //无线网络开关设置 void KyWirelessConnectOperation::setWirelessEnabled(bool enabled) { - emit enabledWirelessNetwork(enabled); + Q_EMIT enabledWirelessNetwork(enabled); return; } @@ -1121,6 +1139,40 @@ NetworkManager::ConnectionSettings::Ptr return connectionSettings; } +QStringList KyWirelessConnectOperation::getBlackListHostName(QString apConnectPath) +{ + QStringList blackList; + blackList.clear(); + + QDBusInterface dbusInterface("org.freedesktop.NetworkManager", + apConnectPath, + "org.freedesktop.NetworkManager.Settings.Connection", + QDBusConnection::systemBus()); + if (!dbusInterface.isValid()) { + qWarning()<(); + QMap> map; + dbusArg1st >> map; + if (map.isEmpty()) { + qWarning() << Q_FUNC_INFO << __LINE__ <<"map is empty!"; + return blackList; + } + + QMap wirelessMap = map.value(KEY_802_11_WIRELESS); + if (wirelessMap.isEmpty()) { + qWarning() << Q_FUNC_INFO << __LINE__ <<"wirelessMap is empty!"; + return blackList; + } + if (wirelessMap.contains(KEY_BLACKLIST_HOSTNAME)) { + blackList = wirelessMap.value(KEY_BLACKLIST_HOSTNAME).toStringList(); + } + return blackList; +} + void KyWirelessConnectOperation::updateWirelessApSetting( NetworkManager::Connection::Ptr apConnectPtr, const QString apName, const QString apPassword, @@ -1145,7 +1197,6 @@ void KyWirelessConnectOperation::updateWirelessApSetting( wirelessSetting->setBand(NetworkManager::WirelessSetting::FrequencyBand::Automatic); } - NetworkManager::WirelessSecuritySetting::Ptr wirelessSecuritySetting = apConnectSettingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); if (apPassword.isEmpty()) { @@ -1156,7 +1207,12 @@ void KyWirelessConnectOperation::updateWirelessApSetting( wirelessSecuritySetting->setPsk(apPassword); } - apConnectPtr->update(apConnectSettingPtr->toMap()); + QStringList blackList = getBlackListHostName(apConnectPtr->path()); + NMVariantMapMap newMap = apConnectSettingPtr->toMap(); + if (newMap.contains(KEY_802_11_WIRELESS)) { + newMap[KEY_802_11_WIRELESS].insert(KEY_BLACKLIST_HOSTNAME, blackList); + } + apConnectPtr->update(newMap); } void KyWirelessConnectOperation::activeWirelessAp(const QString apUuid, const QString apName, @@ -1164,7 +1220,7 @@ void KyWirelessConnectOperation::activeWirelessAp(const QString apUuid, const QS const QString wirelessBand) { - qDebug() << "activeWirelessAp]" << apUuid << apName << apPassword << apDevice << wirelessBand; + qDebug() << "[activeWirelessAp]" << apUuid << apName << apPassword << apDevice << wirelessBand; //1、检查连接是否存在 NetworkManager::Connection::Ptr connectPtr = m_networkResourceInstance->getConnect(apUuid); if (nullptr == connectPtr) { @@ -1172,7 +1228,7 @@ void KyWirelessConnectOperation::activeWirelessAp(const QString apUuid, const QS if (devicePtr.isNull()) { QString errorMsg ="Create hotspot faild. " + apDevice + " is not existed"; qWarning()<< errorMsg; - emit addAndActivateConnectionError(errorMsg); + Q_EMIT addAndActivateConnectionError(errorMsg); return; } @@ -1187,7 +1243,7 @@ void KyWirelessConnectOperation::activeWirelessAp(const QString apUuid, const QS if (watcher->isError() || !watcher->isValid()) { QString errorMsg = "Create hotspot faild. " + watcher->error().message(); qWarning() << errorMsg; - emit addAndActivateConnectionError(errorMsg); + Q_EMIT addAndActivateConnectionError(errorMsg); } watcher->deleteLater(); }); @@ -1294,7 +1350,7 @@ void KyWirelessConnectOperation::activateApConnectionByUuid(const QString apUuid QString connectPath = ""; QString deviceIdentifier = ""; QString connectName = ""; - QString specificObject = ""; + QString specificObject = "/"; qDebug()<<"it will activate hotspot connect"<isError() || !watcher->isValid()) { QString errorMessage = tr("Create hotspot faild. ") + watcher->error().message(); qWarning()<activateConnectionError(errorMessage); + Q_EMIT this->activateConnectionError(errorMessage); } else { qWarning()<<"active wired connect complete."; } diff --git a/src/backend/dbus-interface/kywirelessconnectoperation.h b/src/backend/dbus-interface/kywirelessconnectoperation.h index 07725a66..94d91858 100644 --- a/src/backend/dbus-interface/kywirelessconnectoperation.h +++ b/src/backend/dbus-interface/kywirelessconnectoperation.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef KYWIRELESSCONNECTOPERATION_H #define KYWIRELESSCONNECTOPERATION_H @@ -8,6 +27,9 @@ #include "kylinconnectoperation.h" #include "kyenterpricesettinginfo.h" +#define KEY_802_11_WIRELESS "802-11-wireless" +#define KEY_BLACKLIST_HOSTNAME "blacklist-hostname" + const QByteArray GSETTINGS_SCHEMA = "org.ukui.kylin-nm.switch"; const QString WIRELESS_SWITCH = "wirelessswitch"; @@ -96,7 +118,7 @@ public: void addAndActiveWirelessEnterPriseLeapConnect(KyEapMethodLeapInfo &info, KyWirelessConnectSetting &connSettingInfo, QString & devIface, bool isHidden); void addAndActiveWirelessEnterPrisePwdConnect(KyEapMethodPwdInfo &info, KyWirelessConnectSetting &connSettingInfo, - QString & devIface, bool isHidden); + QString & devIface, bool isHidden); void addAndActiveWirelessEnterPriseFastConnect(KyEapMethodFastInfo &info, KyWirelessConnectSetting &connSettingInfo, QString & devIface, bool isHidden); //属性页 page1 AutoConnect @@ -138,8 +160,10 @@ private: const QString apPassword, const QString apDevice, const QString wirelessBand); + QStringList getBlackListHostName(QString apConnectPath); -signals: + +Q_SIGNALS: void wifiEnabledChanged(bool); void enabledWirelessNetwork(bool enabled); void addAndActivateConnectionError(QString errorMessage); diff --git a/src/backend/dbus-interface/kywirelessnetitem.cpp b/src/backend/dbus-interface/kywirelessnetitem.cpp index 78ef649b..39e6dad2 100644 --- a/src/backend/dbus-interface/kywirelessnetitem.cpp +++ b/src/backend/dbus-interface/kywirelessnetitem.cpp @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "kywirelessnetitem.h" #include #include "kylinutil.h" @@ -6,30 +25,7 @@ const QString ENTERPRICE_TYPE = "802.1X"; const QString WPA1_AND_WPA2 = "WPA"; const QString WPA3 = "WPA3"; -QString enumToQstring(NetworkManager::AccessPoint::Capabilities cap, NetworkManager::AccessPoint::WpaFlags wpa_flags,NetworkManager::AccessPoint::WpaFlags rsn_flags) -{ - QString out; - if ( (cap & NM_802_11_AP_FLAGS_PRIVACY) - && (wpa_flags == NM_802_11_AP_SEC_NONE) - && (rsn_flags == NM_802_11_AP_SEC_NONE)) { - out += "WEP "; - } - if (wpa_flags != NM_802_11_AP_SEC_NONE) { - out += "WPA1 "; - } - if ((rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_PSK) - || (rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_802_1X)) { - out += "WPA2 "; - } - if (rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_SAE) { - out += "WPA3 "; - } - if ( (wpa_flags & NM_802_11_AP_SEC_KEY_MGMT_802_1X) - || (rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_802_1X)) { - out += "802.1X "; - } - return out; -} +#define FREQ_5GHZ 5000 KyWirelessNetItem::KyWirelessNetItem(NetworkManager::WirelessNetwork::Ptr net) { @@ -44,6 +40,7 @@ KyWirelessNetItem::KyWirelessNetItem(NetworkManager::WirelessNetwork::Ptr net) m_kySecuType = NONE; m_device = ""; m_channel = 0; + m_isMix = false; init(net); } @@ -70,16 +67,70 @@ void KyWirelessNetItem::init(NetworkManager::WirelessNetwork::Ptr net) NetworkManager::AccessPoint::WpaFlags wpaFlag = net->referenceAccessPoint()->wpaFlags(); NetworkManager::AccessPoint::WpaFlags rsnFlag = net->referenceAccessPoint()->rsnFlags(); m_secuType = enumToQstring(cap, wpaFlag, rsnFlag); - if (m_secuType.indexOf(ENTERPRICE_TYPE) >= 0) { - m_kySecuType = WPA_AND_WPA2_ENTERPRISE; - } else if (m_secuType.indexOf(WPA3) >= 0) { - m_kySecuType = WPA3_PERSONAL; - } else if ( m_secuType.indexOf(WPA1_AND_WPA2) >= 0) { - m_kySecuType = WPA_AND_WPA2_PERSONAL; - } +// if (m_secuType.indexOf(ENTERPRICE_TYPE) >= 0) { +// m_kySecuType = WPA_AND_WPA2_ENTERPRISE; +// } else if (m_secuType.indexOf(WPA3) >= 0) { +// m_kySecuType = WPA3_PERSONAL; +// } else if ( m_secuType.indexOf(WPA1_AND_WPA2) >= 0) { +// m_kySecuType = WPA_AND_WPA2_PERSONAL; +// } + setKySecuType(m_secuType); m_bssid = net->referenceAccessPoint()->hardwareAddress(); m_device = net->device(); m_uni = net->referenceAccessPoint()->uni(); + + NetworkManager::Device::Ptr devicePtr = nullptr; + devicePtr = m_networkResourceInstance->findDeviceInterface(m_device); + if (!devicePtr.isNull()) { + QString devUni = devicePtr->uni(); + NetworkManager::WirelessNetwork::Ptr wirelessPtr = nullptr; + wirelessPtr = m_networkResourceInstance->findWifiNetwork(m_NetSsid, devUni); + if (!wirelessPtr.isNull()) { + NetworkManager::AccessPoint::List apList = wirelessPtr->accessPoints(); + bool b2G = false; + bool b5G = false; + if (!apList.empty()) { + for (int i = 0; i < apList.count(); ++i) { + if (apList.at(i)->frequency() < FREQ_5GHZ) { + b2G = true; + } + if (apList.at(i)->frequency() >= FREQ_5GHZ) { + b5G = true; + } + if (b2G && b5G) { + m_isMix = true; + break; + } + } + } + devicePtr = m_networkResourceInstance->findDeviceInterface(m_device); + if (!devicePtr.isNull()) { + QString devUni = devicePtr->uni(); + NetworkManager::WirelessNetwork::Ptr wirelessPtr = nullptr; + wirelessPtr = m_networkResourceInstance->findWifiNetwork(m_NetSsid, devUni); + if (!wirelessPtr.isNull()) { + NetworkManager::AccessPoint::List apList = wirelessPtr->accessPoints(); + bool b2G = false; + bool b5G = false; + if (!apList.empty()) { + for (int i = 0; i < apList.count(); ++i) { + if (apList.at(i)->frequency() < FREQ_5GHZ) { + b2G = true; + } + if (apList.at(i)->frequency() >= FREQ_5GHZ) { + b5G = true; + } + if (b2G && b5G) { + m_isMix = true; + break; + } + + } + } + } + } + } + } initInfoBySsid(); } @@ -132,3 +183,16 @@ int KyWirelessNetItem::getCategory(QString uni) } } + +void KyWirelessNetItem::setKySecuType(QString strSecuType) +{ + if (strSecuType.indexOf(ENTERPRICE_TYPE) >= 0) { + m_kySecuType = WPA_AND_WPA2_ENTERPRISE; + } else if (strSecuType.indexOf(WPA3) >= 0) { + m_kySecuType = WPA3_PERSONAL; + } else if ( strSecuType.indexOf(WPA1_AND_WPA2) >= 0) { + m_kySecuType = WPA_AND_WPA2_PERSONAL; + } else { + m_kySecuType = NONE; + } +} diff --git a/src/backend/dbus-interface/kywirelessnetitem.h b/src/backend/dbus-interface/kywirelessnetitem.h index fcb03af8..533e6ca6 100644 --- a/src/backend/dbus-interface/kywirelessnetitem.h +++ b/src/backend/dbus-interface/kywirelessnetitem.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef KYWIRELESSNETITEM_H #define KYWIRELESSNETITEM_H @@ -6,8 +25,6 @@ #include "kylinnetworkresourcemanager.h" #include "kywirelessconnectoperation.h" -QString enumToQstring(NetworkManager::AccessPoint::Capabilities, NetworkManager::AccessPoint::WpaFlags, NetworkManager::AccessPoint::WpaFlags); - class KyWirelessNetItem { public: @@ -28,6 +45,7 @@ public: QString m_secuType; KySecuType m_kySecuType; QString m_uni; + bool m_isMix; //only for m_isConfiged = true bool m_isConfigured; @@ -36,6 +54,7 @@ public: uint m_channel; int getCategory(QString uni); + void setKySecuType(QString strSecuType); private: KyNetworkResourceManager *m_networkResourceInstance = nullptr; diff --git a/src/backend/dbus-interface/kywirelessnetresource.cpp b/src/backend/dbus-interface/kywirelessnetresource.cpp index 435269ee..bee368d8 100644 --- a/src/backend/dbus-interface/kywirelessnetresource.cpp +++ b/src/backend/dbus-interface/kywirelessnetresource.cpp @@ -1,7 +1,29 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "kywirelessnetresource.h" #include "kylinutil.h" #define LOG_FLAG "[KyWirelessNetResource]" +const QString ENTERPRICE_TYPE = "802.1X"; +const QString WPA1_AND_WPA2 = "WPA"; +const QString WPA3 = "WPA3"; static bool subWifiListSort(const KyWirelessNetItem info1, const KyWirelessNetItem info2) { @@ -39,13 +61,15 @@ KyWirelessNetResource::KyWirelessNetResource(QObject *parent) //TODO:connect device signal connect(m_networkResourceInstance, &KyNetworkResourceManager::wifiNetworkAdded, - this, &KyWirelessNetResource::onWifiNetworkAdded, Qt::ConnectionType::DirectConnection); + this, &KyWirelessNetResource::onWifiNetworkAdded/*, Qt::ConnectionType::DirectConnection*/); connect(m_networkResourceInstance, &KyNetworkResourceManager::wifiNetworkRemoved, - this, &KyWirelessNetResource::onWifiNetworkRemoved, Qt::ConnectionType::DirectConnection); + this, &KyWirelessNetResource::onWifiNetworkRemoved/*, Qt::ConnectionType::DirectConnection*/); connect(m_networkResourceInstance, &KyNetworkResourceManager::wifiNetworkPropertyChange, - this, &KyWirelessNetResource::onWifiNetworkPropertyChange, Qt::ConnectionType::DirectConnection); + this, &KyWirelessNetResource::onWifiNetworkPropertyChange/*, Qt::ConnectionType::DirectConnection*/); + connect(m_networkResourceInstance, &KyNetworkResourceManager::wifiNetworkSecuChange, + this, &KyWirelessNetResource::onWifiNetworkSecuChange/*, Qt::ConnectionType::DirectConnection*/); connect(m_networkResourceInstance, &KyNetworkResourceManager::wifiNetworkDeviceDisappear, - this, &KyWirelessNetResource::onWifiNetworkDeviceDisappear, Qt::ConnectionType::DirectConnection); + this, &KyWirelessNetResource::onWifiNetworkDeviceDisappear/*, Qt::ConnectionType::DirectConnection*/); connect(m_networkResourceInstance, &KyNetworkResourceManager::connectionAdd, this, &KyWirelessNetResource::onConnectionAdd); @@ -387,7 +411,7 @@ void KyWirelessNetResource::onWifiNetworkAdded(QString devIfaceName, QString ssi m_WifiNetworkList.insert(devIfaceName,list); } - emit wifiNetworkAdd(devIfaceName, item); + Q_EMIT wifiNetworkAdd(devIfaceName, item); } void KyWirelessNetResource::onWifiNetworkRemoved(QString devIfaceName, QString ssid) @@ -403,52 +427,66 @@ void KyWirelessNetResource::onWifiNetworkRemoved(QString devIfaceName, QString s if (m_WifiNetworkList.value(devIfaceName).isEmpty()) { m_WifiNetworkList.remove(devIfaceName); } - emit wifiNetworkRemove(devIfaceName,ssid); + Q_EMIT wifiNetworkRemove(devIfaceName,ssid); } } -void KyWirelessNetResource::onWifiNetworkPropertyChange(NetworkManager::WirelessNetwork * net) +void KyWirelessNetResource::onWifiNetworkSecuChange(NetworkManager::AccessPoint *accessPointPtr) { - if (nullptr == net) { - return; - } + QString secuType = enumToQstring(accessPointPtr->capabilities(), + accessPointPtr->wpaFlags(), + accessPointPtr->rsnFlags()); - NetworkManager::AccessPoint::Ptr accessPointPtr = net->referenceAccessPoint(); - QByteArray rawSsid = accessPointPtr->rawSsid(); - QString wifiSsid = getSsidFromByteArray(rawSsid); - - if (net->device().isEmpty()) { - return; - } - - QString devIface = m_networkResourceInstance->findDeviceUni(net->device())->interfaceName(); - if (m_WifiNetworkList.contains(devIface)) { - QList::iterator iter = m_WifiNetworkList[devIface].begin(); - while (iter != m_WifiNetworkList[devIface].end()) { - if (iter->m_NetSsid == wifiSsid) { -// qDebug()<< LOG_FLAG <<"recive properity changed signal, sender is" << iter->m_NetSsid; - if (iter->m_signalStrength != net->signalStrength()) { - iter->m_signalStrength = net->signalStrength(); - emit signalStrengthChange(devIface, wifiSsid, iter->m_signalStrength); - } - - if (iter->m_bssid != accessPointPtr->hardwareAddress()) { - iter->m_bssid = accessPointPtr->hardwareAddress(); - emit bssidChange(devIface, wifiSsid, iter->m_bssid); - } - - QString secuType = enumToQstring(accessPointPtr->capabilities(), - accessPointPtr->wpaFlags(), - accessPointPtr->rsnFlags()); - if (iter->m_secuType != secuType) { - iter->m_secuType = secuType; - emit secuTypeChange(devIface, wifiSsid, secuType); - } + QMap >::iterator iter = m_WifiNetworkList.begin(); + while (iter != m_WifiNetworkList.end()) { + QList::iterator itemIter = iter.value().begin(); + while (itemIter != iter.value().end()) { + if (itemIter->m_NetSsid == accessPointPtr->ssid()) { + QString devName = iter.key(); + itemIter->m_secuType = secuType; + itemIter->setKySecuType(secuType); + //qDebug() << "!!!!" << itemIter->m_NetSsid << itemIter->m_secuType << itemIter->m_kySecuType; + Q_EMIT secuTypeChange(devName, accessPointPtr->ssid(), secuType); break; } - iter++; + itemIter++; } + iter++; + } + +} + +void KyWirelessNetResource::onWifiNetworkPropertyChange(QString interface, QString ssid, int signal, QString bssid, QString sec) +{ + + if (m_WifiNetworkList.contains(interface)) { + QList::iterator iter = m_WifiNetworkList[interface].begin(); + while (iter != m_WifiNetworkList[interface].end()) { + qDebug() << iter->m_NetSsid; + if (iter->m_NetSsid == ssid) { + // qDebug()<< LOG_FLAG <<"recive properity changed signal, sender is" << iter->m_NetSsid; + if (iter->m_signalStrength != signal) { + iter->m_signalStrength = signal; + Q_EMIT signalStrengthChange(interface, ssid, iter->m_signalStrength); + } + + if (iter->m_bssid != bssid) { + qDebug() << "bssid"; + iter->m_bssid = bssid; + Q_EMIT bssidChange(interface, ssid, iter->m_bssid); + } + + if (iter->m_secuType != sec) { + iter->setKySecuType(sec); + Q_EMIT secuTypeChange(interface, ssid, sec); + } + + break; + } + + iter++; + } } } @@ -749,7 +787,7 @@ void KyWirelessNetResource::onConnectionAdd(QString uuid) for(auto var = map.cbegin(); var != map.cend(); var++) { QString devIfaceName = var.key(); QString ssid = var.value(); - emit connectionAdd(devIfaceName, ssid); + Q_EMIT connectionAdd(devIfaceName, ssid); } } } @@ -787,7 +825,7 @@ void KyWirelessNetResource::onConnectionRemove(QString path) for(auto var = map.cbegin(); var != map.cend(); var++) { QString devIfaceName = var.key(); QString ssid = var.value(); - emit connectionRemove(devIfaceName, ssid); + Q_EMIT connectionRemove(devIfaceName, ssid, path); } } @@ -810,7 +848,7 @@ void KyWirelessNetResource::onConnectionUpdate(QString uuid) m_WifiNetworkList.clear(); kyWirelessNetItemListInit(); - emit wifiNetworkUpdate(); + Q_EMIT wifiNetworkUpdate(); } diff --git a/src/backend/dbus-interface/kywirelessnetresource.h b/src/backend/dbus-interface/kywirelessnetresource.h index e663e4c4..ac1e5f5b 100644 --- a/src/backend/dbus-interface/kywirelessnetresource.h +++ b/src/backend/dbus-interface/kywirelessnetresource.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef KYWIRELESSNETRESOURCE_H #define KYWIRELESSNETRESOURCE_H @@ -44,10 +63,11 @@ private: QString getDeviceIFace(NetworkManager::WirelessNetwork::Ptr net); QString getDeviceIFace(NetworkManager::ActiveConnection::Ptr actConn, QString &wirelessNetResourcessid); -public slots: +public Q_SLOTS: void onWifiNetworkAdded(QString, QString); void onWifiNetworkRemoved(QString, QString); - void onWifiNetworkPropertyChange(NetworkManager::WirelessNetwork * net); + void onWifiNetworkPropertyChange(QString interface, QString ssid, int signal, QString bssid, QString sec); + void onWifiNetworkSecuChange(NetworkManager::AccessPoint *accessPointPtr); void onWifiNetworkDeviceDisappear(); void onConnectionAdd(QString uuid); @@ -58,11 +78,11 @@ public slots: void onDeviceRemove(QString deviceName); void onDeviceNameUpdate(QString oldName, QString newName); -signals: +Q_SIGNALS: void signalStrengthChange(QString, QString, int); void bssidChange(QString, QString, QString); void secuTypeChange(QString, QString, QString); - void connectionRemove(QString, QString); + void connectionRemove(QString, QString, QString); void connectionAdd(QString, QString); void wifiNetworkUpdate(); void wifiNetworkAdd(QString, KyWirelessNetItem&); diff --git a/src/backend/dbus-interface/nm-macros-internal.h b/src/backend/dbus-interface/nm-macros-internal.h index 300ff43e..38b15954 100644 --- a/src/backend/dbus-interface/nm-macros-internal.h +++ b/src/backend/dbus-interface/nm-macros-internal.h @@ -1,3 +1,23 @@ + +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef __NM_MACROS_INTERNAL_H__ #define __NM_MACROS_INTERNAL_H__ diff --git a/src/backend/dbusadaptor.cpp b/src/backend/dbusadaptor.cpp index 7dd269c7..d3325af3 100644 --- a/src/backend/dbusadaptor.cpp +++ b/src/backend/dbusadaptor.cpp @@ -50,6 +50,11 @@ QMap > DbusAdaptor::getWirelessList() return map; } +bool DbusAdaptor::getWirelessSwitchBtnState() +{ + return parent()->getWirelessSwitchBtnState(); +} + //有线列表 QMap> DbusAdaptor::getWiredList() { @@ -95,7 +100,6 @@ void DbusAdaptor::setWirelessSwitchEnable(bool enable) void DbusAdaptor::setDeviceEnable(QString devName, bool enable) { parent()->setWiredDeviceEnable(devName, enable); - saveDeviceEnableState(devName, enable); } //设置默认网卡 @@ -239,6 +243,24 @@ QStringList DbusAdaptor::getStoredApInfo() return list; } +//获取热点path +QString DbusAdaptor::getApConnectionPath(QString uuid) +{ + QString path; + path.clear(); + parent()->getApConnectionPath(path, uuid); + return path; +} + +//获取热点path +QString DbusAdaptor::getActiveConnectionPath(QString uuid) +{ + QString path; + path.clear(); + parent()->getActiveConnectionPath(path, uuid); + return path; +} + QStringList DbusAdaptor::getApInfoBySsid(QString devName, QString ssid) { QStringList list; diff --git a/src/backend/dbusadaptor.h b/src/backend/dbusadaptor.h index c7bfa749..3185e3c7 100644 --- a/src/backend/dbusadaptor.h +++ b/src/backend/dbusadaptor.h @@ -85,6 +85,8 @@ public Q_SLOTS: // METHODS //获取热点 QStringList getStoredApInfo(); QStringList getApInfoBySsid(QString devName, QString ssid); + QString getApConnectionPath(QString uuid); + QString getActiveConnectionPath(QString uuid); //wifi扫描 void reScan(); //keyring @@ -92,6 +94,9 @@ public Q_SLOTS: // METHODS void keyRingClear(); //just show void showKylinNM(int type); + + bool getWirelessSwitchBtnState(); + Q_SIGNALS: // SIGNALS // void wirelessActivating(QString devName, QString ssid); // void wiredActivating(QString devName, QString ssid); @@ -108,11 +113,11 @@ Q_SIGNALS: // SIGNALS //设备插拔 void deviceStatusChanged(); void deviceNameChanged(QString oldName, QString newName, int type); + void wirelessSwitchBtnChanged(bool state); //热点断开 void hotspotDeactivated(QString devName, QString ssid); //热点连接 - void hotspotActivated(QString devName, QString ssid, QString uuid); - + void hotspotActivated(QString devName, QString ssid, QString uuid, QString activePath, QString settingPath); //信号强度变化 void signalStrengthChange(QString devName, QString ssid, int strength); //安全性变化 diff --git a/src/backend/hotspot/dlghotspotcreate.cpp b/src/backend/hotspot/dlghotspotcreate.cpp index afeb5b9d..ba48b4f2 100644 --- a/src/backend/hotspot/dlghotspotcreate.cpp +++ b/src/backend/hotspot/dlghotspotcreate.cpp @@ -85,7 +85,7 @@ void DlgHotspotCreate::mouseMoveEvent(QMouseEvent *event){ void DlgHotspotCreate::on_btnCancel_clicked() { this->close(); - emit btnHotspotState(); + Q_EMIT btnHotspotState(); } void DlgHotspotCreate::on_btnOk_clicked() @@ -101,7 +101,7 @@ void DlgHotspotCreate::on_btnOk_clicked() Utils::m_system(str.toUtf8().data()); this->close(); - emit updateHotspotList(); + Q_EMIT updateHotspotList(); } void DlgHotspotCreate::on_checkBoxPwd_stateChanged(int arg1) diff --git a/src/backend/hotspot/dlghotspotcreate.h b/src/backend/hotspot/dlghotspotcreate.h index ee0ec0d2..d3aa5387 100644 --- a/src/backend/hotspot/dlghotspotcreate.h +++ b/src/backend/hotspot/dlghotspotcreate.h @@ -35,10 +35,10 @@ public: explicit DlgHotspotCreate(QString wiFiCardName, QWidget *parent = nullptr); ~DlgHotspotCreate(); -public slots: +public Q_SLOTS: void changeDialog(); -private slots: +private Q_SLOTS: void on_btnCancel_clicked(); void on_btnOk_clicked(); @@ -61,7 +61,7 @@ private: QPoint winPos; QPoint dragPos; -signals: +Q_SIGNALS: void updateHotspotList(); void btnHotspotState(); }; diff --git a/src/backend/kylinarping.h b/src/backend/kylinarping.h index 79346955..b1aa98be 100644 --- a/src/backend/kylinarping.h +++ b/src/backend/kylinarping.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef KYLINARPING_H #define KYLINARPING_H diff --git a/src/backend/kylinipv4arping.cpp b/src/backend/kylinipv4arping.cpp index 2592d973..2cbdefbe 100644 --- a/src/backend/kylinipv4arping.cpp +++ b/src/backend/kylinipv4arping.cpp @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "kylinipv4arping.h" #include diff --git a/src/backend/kylinipv4arping.h b/src/backend/kylinipv4arping.h index 1cb8ea36..9aa9cb91 100644 --- a/src/backend/kylinipv4arping.h +++ b/src/backend/kylinipv4arping.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef KYLIN_IPV4_ARPING #define KYLIN_IPV4_ARPING diff --git a/src/backend/kylinipv6arping.cpp b/src/backend/kylinipv6arping.cpp index 79d2ee12..a6969a6b 100644 --- a/src/backend/kylinipv6arping.cpp +++ b/src/backend/kylinipv6arping.cpp @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "kylinipv6arping.h" #include @@ -168,6 +187,18 @@ int KyIpv6Arping::parseIpv6Packet(const uint8_t *buf, size_t len, const struct s /* looks for Target Link-layer address option */ ptr = buf + sizeof (struct nd_neighbor_advert); + int index; + char macAddress[64] = {0}; + uint8_t hw_addr[6] = {0}; + getLocalMacAddress(m_ifaceName.toUtf8().constData(), hw_addr); + for (index = 0; index < 6; index++) { + snprintf(&macAddress[strlen(macAddress)], sizeof(macAddress) - strlen(macAddress), "%02X", hw_addr[index]); + if (index != 5) { + snprintf(&macAddress[strlen(macAddress)], sizeof(macAddress) - strlen(macAddress), "%s", ":"); + } + } + QString localAddr(macAddress); + while (len >= 8) { uint16_t optlen; @@ -193,6 +224,9 @@ int KyIpv6Arping::parseIpv6Packet(const uint8_t *buf, size_t len, const struct s optlen -= 2; saveMacAddress (ptr, optlen); + if (!localAddr.isEmpty() && getConflictMacAddress() == localAddr) { + break; + } setIpv6ConflictFlag(true); return 0; } diff --git a/src/backend/kylinipv6arping.h b/src/backend/kylinipv6arping.h index 7f92c8ee..faa08c25 100644 --- a/src/backend/kylinipv6arping.h +++ b/src/backend/kylinipv6arping.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef KYLINIPV6ARPING_H #define KYLINIPV6ARPING_H diff --git a/src/backend/sysdbusregister.h b/src/backend/sysdbusregister.h index 942a54f3..cbbe2b61 100644 --- a/src/backend/sysdbusregister.h +++ b/src/backend/sysdbusregister.h @@ -41,11 +41,11 @@ public: private: // QString m_name; -signals: +Q_SIGNALS: // Q_SCRIPTABLE void nameChanged(QString); // Q_SCRIPTABLE void computerinfo(QString); -public slots: +public Q_SLOTS: Q_SCRIPTABLE void systemRun(QString cmd); Q_SCRIPTABLE QStringList getWifiInfo(QString wifiName); diff --git a/src/backend/utils.h b/src/backend/utils.h index 7cbc23f6..90a549f3 100644 --- a/src/backend/utils.h +++ b/src/backend/utils.h @@ -73,7 +73,7 @@ public: static int m_system(char *cmd); -public slots: +public Q_SLOTS: void onRequestSendDesktopNotify(QString message); }; diff --git a/src/backend/wifi-auth-thread.cpp b/src/backend/wifi-auth-thread.cpp index 3ad12ca0..a53b8e83 100644 --- a/src/backend/wifi-auth-thread.cpp +++ b/src/backend/wifi-auth-thread.cpp @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "wifi-auth-thread.h" #include diff --git a/src/backend/wifi-auth-thread.h b/src/backend/wifi-auth-thread.h index f02ecebb..ab461685 100644 --- a/src/backend/wifi-auth-thread.h +++ b/src/backend/wifi-auth-thread.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef WIFI_AUTH_THREAD_H #define WIFI_AUTH_THREAD_H #include diff --git a/src/frontend/customstyle.cpp b/src/frontend/customstyle.cpp index 7c5c3397..829550f9 100644 --- a/src/frontend/customstyle.cpp +++ b/src/frontend/customstyle.cpp @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "customstyle.h" CustomStyle::CustomStyle(const QString &proxyStyleName) : QProxyStyle (proxyStyleName) diff --git a/src/frontend/customstyle.h b/src/frontend/customstyle.h index 85245ccb..db7f0c1b 100644 --- a/src/frontend/customstyle.h +++ b/src/frontend/customstyle.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef CUSTOMSTYLE_H #define CUSTOMSTYLE_H diff --git a/src/frontend/enterprise-wlan/enterprisewlandialog.cpp b/src/frontend/enterprise-wlan/enterprisewlandialog.cpp index 8479836c..e7e41087 100644 --- a/src/frontend/enterprise-wlan/enterprisewlandialog.cpp +++ b/src/frontend/enterprise-wlan/enterprisewlandialog.cpp @@ -1,28 +1,56 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "enterprisewlandialog.h" #include #include #include "xatom-helper.h" -#define MAIN_SIZE_EXPAND 400,500 -#define MAIN_SIZE_NARROW 400,400 +#define MAIN_SIZE_EXPAND 480,580 +#define MAIN_SIZE_NARROW 480,484 +#define SCROAREA_WIDTH 480 +#define MAIN_LAYOUT_MARGINS 0,0,0,0 +#define CENTER_LAYOUT_MARGINS 24, 16, 24, 8 +#define BUTTON_LAYOUT_MARGINS 24, 24, 24, 24 +#define MAIN_LAYOUT_SPACING 0 +#define BUTTON_SPACING 16 +#define LABEL_MIN_WIDTH 146 +#define MEDIUM_WEIGHT_VALUE 57 #define THEME_SCHAME "org.ukui.style" #define COLOR_THEME "styleName" EnterpriseWlanDialog::EnterpriseWlanDialog(KyWirelessNetItem &wirelessNetItem, QString device, QWidget *parent) : QWidget(parent) { - //设置窗口无边框,阴影 -#if (QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)) - MotifWmHints window_hints; - window_hints.flags = MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS; - window_hints.functions = MWM_FUNC_ALL; - window_hints.decorations = MWM_DECOR_BORDER; - XAtomHelper::getInstance()->setWindowMotifHint(this->winId(), window_hints); -#else - this->setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint); -#endif +// //设置窗口无边框,阴影 +//#if (QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)) +// MotifWmHints window_hints; +// window_hints.flags = MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS; +// window_hints.functions = MWM_FUNC_ALL; +// window_hints.decorations = MWM_DECOR_BORDER; +// XAtomHelper::getInstance()->setWindowMotifHint(this->winId(), window_hints); +//#else +// this->setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint); +//#endif this->setAttribute(Qt::WA_DeleteOnClose); this->setWindowFlag(Qt::Window); - this->setWindowTitle(tr("Connect Enterprise WLAN")); +// this->setWindowTitle(tr("Connect Enterprise WLAN")); + this->setWindowIcon(QIcon::fromTheme("kylin-network")); m_wirelessNetItem = wirelessNetItem; m_deviceName = device; @@ -47,53 +75,88 @@ EnterpriseWlanDialog::~EnterpriseWlanDialog() { void EnterpriseWlanDialog::closeEvent(QCloseEvent *event) { - emit this->enterpriseWlanDialogClose(false); + Q_EMIT this->enterpriseWlanDialogClose(false); return QWidget::closeEvent(event); } +void EnterpriseWlanDialog::paintEvent(QPaintEvent *event) +{ +// QPalette pal = qApp->palette(); +// QPainter painter(this); +// painter.setBrush(pal.color(QPalette::Base)); +// painter.drawRect(this->rect()); +// painter.fillRect(rect(), QBrush(pal.color(QPalette::Base))); + + return QWidget::paintEvent(event); +} + void EnterpriseWlanDialog::initUI() { -#define MAIN_LAYOUT_MARGINS 8,8,8,8 -#define SSID_LAYOUT_MARGINS 8,8,8,0 -#define MAIN_LAYOUT_SPACING 0 -#define BUTTON_SPACING 8 - m_mainLayout = new QVBoxLayout(this); this->setLayout(m_mainLayout); m_mainLayout->setContentsMargins(MAIN_LAYOUT_MARGINS); m_mainLayout->setSpacing(MAIN_LAYOUT_SPACING); - m_ssidLayout = new QHBoxLayout(); - m_ssidLayout->setContentsMargins(SSID_LAYOUT_MARGINS); - m_ssidTitleLabel = new QLabel(this); - m_ssidTitleLabel->setText("SSID"); + m_centerWidget = new QWidget(this); + QVBoxLayout *centerLayout = new QVBoxLayout(m_centerWidget); + centerLayout->setContentsMargins(CENTER_LAYOUT_MARGINS); + centerLayout->setSpacing(MAIN_LAYOUT_SPACING); + + m_descriptionLabel = new QLabel(this); + m_descriptionLabel->setText(tr("Wi-Fi network requires authentication")); //Wi-Fi网络要求认证 + QFont font = m_descriptionLabel->font(); + font.setWeight(MEDIUM_WEIGHT_VALUE); + m_descriptionLabel->setFont(font); m_ssidLabel = new QLabel(this); - m_ssidLabel->setText(m_wirelessNetItem.m_NetSsid); - - m_ssidLayout->addWidget(m_ssidTitleLabel); - m_ssidLayout->addStretch(); - m_ssidLayout->addWidget(m_ssidLabel); - - m_securityPage = new SecurityPage(this); + QString str = tr("Access to Wi-Fi network \""); //访问Wi-Fi网络 + str.append(m_wirelessNetItem.m_NetSsid); + str.append(tr("\" requires a password or encryption key.")); //需要密码或加密秘钥 + m_ssidLabel->setText(str); + m_ssidLabel->setWordWrap(true); + m_securityPage = new SecurityPage(false, this); m_securityPage->setSecurity(KySecuType::WPA_AND_WPA2_ENTERPRISE); - m_securityPage->setSecurityVisible(false); +// m_securityPage->setSecurityVisible(false); - m_btnLayout = new QHBoxLayout(); - m_btnLayout->setSpacing(BUTTON_SPACING); + centerLayout->addWidget(m_descriptionLabel); + centerLayout->addSpacing(8); + centerLayout->addWidget(m_ssidLabel); + centerLayout->addSpacing(BUTTON_SPACING); + centerLayout->addWidget(m_securityPage); + centerLayout->addStretch(); + m_enterWlanScrollArea = new QScrollArea(this); + m_enterWlanScrollArea->setFrameShape(QFrame::NoFrame); + m_enterWlanScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + m_centerWidget->setFixedWidth(SCROAREA_WIDTH); + m_enterWlanScrollArea->setFixedWidth(SCROAREA_WIDTH); + m_enterWlanScrollArea->setWidget(m_centerWidget); + m_enterWlanScrollArea->setWidgetResizable(true); + + QPalette pal = m_enterWlanScrollArea->palette(); + pal.setBrush(QPalette::Base, QColor(0,0,0,0)); + m_enterWlanScrollArea->setPalette(pal); + m_enterWlanScrollArea->setWidgetResizable(true); + + m_bottomDivider = new Divider(this); + + QWidget *bottomWidget = new QWidget(this); + QHBoxLayout *btnLayout = new QHBoxLayout(bottomWidget); + btnLayout->setContentsMargins(BUTTON_LAYOUT_MARGINS); + btnLayout->setSpacing(BUTTON_SPACING); m_cancelBtn = new QPushButton(this); m_connectBtn = new QPushButton(this); m_cancelBtn->setText(tr("Cancel")); m_connectBtn->setText(tr("Connect")); m_connectBtn->setEnabled(false); - m_btnLayout->addStretch(); - m_btnLayout->addWidget(m_cancelBtn); - m_btnLayout->addWidget(m_connectBtn); - m_mainLayout->addLayout(m_ssidLayout); - m_mainLayout->addWidget(m_securityPage); - m_mainLayout->addLayout(m_btnLayout); - m_mainLayout->addStretch(); + btnLayout->addStretch(); + btnLayout->addWidget(m_cancelBtn); + btnLayout->addWidget(m_connectBtn); + + m_mainLayout->addWidget(m_enterWlanScrollArea); + m_mainLayout->addWidget(m_bottomDivider); + m_mainLayout->addWidget(bottomWidget); this->setFixedSize(MAIN_SIZE_EXPAND); + this->setWindowTitle(m_wirelessNetItem.m_NetSsid); initConnections(); onPaletteChanged(); } @@ -120,6 +183,16 @@ void EnterpriseWlanDialog::initConnections() }); connect(qApp, &QApplication::paletteChanged, this, &EnterpriseWlanDialog::onPaletteChanged); + + const QByteArray id(THEME_SCHAME); + if(QGSettings::isSchemaInstalled(id)){ + QGSettings * fontSetting = new QGSettings(id, QByteArray(), this); + connect(fontSetting, &QGSettings::changed,[=](QString key) { + if ("themeColor" == key) { + onPaletteChanged(); + } + }); + } } void EnterpriseWlanDialog::onPaletteChanged() @@ -135,10 +208,15 @@ void EnterpriseWlanDialog::onPaletteChanged() pal = lightPalette(this); } } - + pal.setColor(QPalette::Background, pal.base().color()); this->setPalette(pal); setFramePalette(m_securityPage, pal); + + if (styleGsettings != nullptr) { + delete styleGsettings; + styleGsettings = nullptr; + } } void EnterpriseWlanDialog::initData() @@ -165,7 +243,7 @@ void EnterpriseWlanDialog::onBtnConnectClicked() KyWirelessConnectSetting connetSetting; connetSetting.setConnectName(m_wirelessNetItem.m_NetSsid); connetSetting.setIfaceName(m_deviceName); - connetSetting.isAutoConnect = true; //ZJP_TODO 自动连接选项 + connetSetting.isAutoConnect = m_securityPage->getAutoConnectState(); //ZJP_TODO 自动连接选项 connetSetting.m_type = KyKeyMgmt::WpaEap; connetSetting.m_ssid = m_wirelessNetItem.m_NetSsid; connetSetting.m_secretFlag = 0; @@ -190,7 +268,7 @@ void EnterpriseWlanDialog::onBtnConnectClicked() } else if (eapType == KyEapMethodType::FAST) { m_securityPage->updateFastChange(m_info.fastInfo); m_connectOperation->addAndActiveWirelessEnterPriseFastConnect(m_info.fastInfo, connetSetting, m_deviceName, false); - } else { + } else { qWarning() << "Connect enterprise wlan failed!(Unknown eap type)" << Q_FUNC_INFO << __LINE__; } close(); diff --git a/src/frontend/enterprise-wlan/enterprisewlandialog.h b/src/frontend/enterprise-wlan/enterprisewlandialog.h index 3b094592..e193b1be 100644 --- a/src/frontend/enterprise-wlan/enterprisewlandialog.h +++ b/src/frontend/enterprise-wlan/enterprisewlandialog.h @@ -1,8 +1,31 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef ENTERPRISEWLANDIALOG_H #define ENTERPRISEWLANDIALOG_H #include #include +#include +#include + #include "securitypage.h" +#include "divider.h" #include "kywirelessnetitem.h" #include "coninfo.h" @@ -15,6 +38,7 @@ public: protected: void closeEvent(QCloseEvent *event); + void paintEvent(QPaintEvent *event); private: void initUI(); //初始化UI界面 @@ -43,22 +67,25 @@ private: QLabel *m_titleLabel = nullptr; QPushButton *m_closeBtn = nullptr; - QHBoxLayout *m_ssidLayout = nullptr; - QLabel *m_ssidTitleLabel = nullptr; + QWidget *m_centerWidget = nullptr; + QLabel *m_descriptionLabel = nullptr; QLabel *m_ssidLabel = nullptr; SecurityPage *m_securityPage = nullptr; - QHBoxLayout *m_btnLayout = nullptr; + QScrollArea *m_enterWlanScrollArea = nullptr; + + Divider *m_bottomDivider = nullptr; + QPushButton *m_cancelBtn = nullptr; QPushButton *m_connectBtn = nullptr; -private slots: +private Q_SLOTS: void onBtnConnectClicked(); void onEapTypeChanged(const KyEapMethodType &type); void onPaletteChanged(); -signals: +Q_SIGNALS: void enterpriseWlanDialogClose(bool); }; diff --git a/src/frontend/frontend.pri b/src/frontend/frontend.pri index fb35339b..b7703595 100644 --- a/src/frontend/frontend.pri +++ b/src/frontend/frontend.pri @@ -5,7 +5,7 @@ include(tab-pages/tab-pages.pri) include(list-items/list-items.pri) include(netdetails/netdetails.pri) include(enterprise-wlan/enterprise-wlan.pri) -include(single-pages/single-pages.pri) +include(networkmode/networkmode.pri) FORMS += \ $$PWD/wificonfigdialog.ui @@ -13,11 +13,12 @@ FORMS += \ HEADERS += \ $$PWD/customstyle.h \ $$PWD/mainwindow.h \ - $$PWD/wificonfigdialog.h \ - $$PWD/vpnobject.h + $$PWD/wificonfigdialog.h SOURCES += \ $$PWD/customstyle.cpp \ $$PWD/mainwindow.cpp \ - $$PWD/wificonfigdialog.cpp \ - $$PWD/vpnobject.cpp + $$PWD/wificonfigdialog.cpp + +DISTFILES += \ + $$PWD/networkmode/networkmode.pri diff --git a/src/frontend/list-items/lanlistitem.cpp b/src/frontend/list-items/lanlistitem.cpp index a311dbc3..2f740298 100644 --- a/src/frontend/list-items/lanlistitem.cpp +++ b/src/frontend/list-items/lanlistitem.cpp @@ -1,9 +1,31 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "lanlistitem.h" #include "backend/dbus-interface/kylinconnectitem.h" #include #define LOG_FLAG "[LanListItem]" +#define NAMELABLE_MAX_WIDTH_HOVER 220 +#define NAMELABLE_MAX_WIDTH_ACTIVATED 190 +#define NAMELABLE_MAX_WIDTH_DEACTIVATED 326 LanListItem::LanListItem(const KyConnectItem *lanConnectItem, const QString &deviceName, QWidget *parent):ListItem(parent) @@ -13,8 +35,7 @@ LanListItem::LanListItem(const KyConnectItem *lanConnectItem, connectItemCopy(lanConnectItem); m_deviceName = deviceName; - - m_nameLabel->setText(m_lanConnectItem.m_connectName); + m_nameLabel->setLabelText(m_lanConnectItem.m_connectName); m_netButton->setButtonIcon(QIcon::fromTheme("network-wired-connected-symbolic")); qDebug() << "LanListItem init:" << m_lanConnectItem.m_connectName << m_lanConnectItem.m_connectState << m_lanConnectItem.m_ifaceName; @@ -23,16 +44,19 @@ LanListItem::LanListItem(const KyConnectItem *lanConnectItem, m_netButton->stopLoading(); if (m_lanConnectItem.m_connectState == Activated) { setIcon(true); + m_nameLabel->setLabelMaximumWidth(NAMELABLE_MAX_WIDTH_ACTIVATED); } else { setIcon(false); + m_nameLabel->setLabelMaximumWidth(NAMELABLE_MAX_WIDTH_DEACTIVATED); } } else { m_netButton->startLoading(); } m_itemFrame->installEventFilter(this); - connect(this->m_infoButton, &InfoButton::clicked, this, &LanListItem::onInfoButtonClicked); +// connect(this->m_infoButton, &InfoButton::clicked, this, &LanListItem::onInfoButtonClicked); connect(m_menu, &QMenu::triggered, this, &LanListItem::onMenuTriggered); + connect(m_hoverButton, &FixPushButton::clicked, this, &LanListItem::onNetButtonClicked); } @@ -42,8 +66,8 @@ LanListItem::LanListItem(QWidget *parent) : ListItem(parent) m_netButton->setButtonIcon(QIcon::fromTheme("network-wired-disconnected-symbolic")); setIcon(false); const QString str=tr("Not connected"); - m_nameLabel->setText(str); - this->m_infoButton->hide(); + m_nameLabel->setLabelText(str); +// this->m_infoButton->hide(); } LanListItem::~LanListItem() @@ -101,8 +125,7 @@ void LanListItem::onNetButtonClicked() this->showDesktopNotify(tr("Wired Device not carried"), "networkwrong"); } } else { - qDebug() << LOG_FLAG <<"the connection" << m_lanConnectItem.m_connectName - << "is not deactived, so it can not be operation."; + m_connectOperation->deactivateWiredConnection(m_lanConnectItem.m_connectName, m_lanConnectItem.m_connectUuid); } return; @@ -125,9 +148,10 @@ void LanListItem::onRightButtonClicked() } else { return; } + m_menu->addAction(new QAction(tr("Property"), this)); + m_menu->addAction(new QAction(tr("Delete"), this)); - m_menu->move(cursor().pos()); - m_menu->show(); + m_menu->popup(cursor().pos()); return; } @@ -140,6 +164,10 @@ void LanListItem::onMenuTriggered(QAction *action) qDebug() << LOG_FLAG << "it will disconnect connection" << m_lanConnectItem.m_connectName << ". it's device is" << m_deviceName; m_netButton->startLoading(); + } else if (action->text() == tr("Property")) { + onInfoButtonClicked(); + } else if (action->text() == tr("Delete")) { + m_connectOperation->deleteConnect(m_lanConnectItem.m_connectUuid); } return; } @@ -152,16 +180,16 @@ void LanListItem::onInfoButtonClicked() return; } - if(netDetail != nullptr){ - netDetail->activateWindow(); - return; - } +// if(netDetail != nullptr){ +// netDetail->activateWindow(); +// return; +// } qDebug()<< LOG_FLAG << "the info button of lan is clicked! uuid = " << m_lanConnectItem.m_connectUuid << "; name = " << m_lanConnectItem.m_connectName << "." <show(); - emit this->detailShow(true); +#endif + Q_EMIT this->detailShow(m_deviceName, m_lanConnectItem.m_connectUuid); return; } @@ -207,7 +236,7 @@ QString LanListItem::getConnectionName() void LanListItem::updateConnectionName(QString connectionName) { m_lanConnectItem.m_connectName = connectionName; - m_nameLabel->setText(m_lanConnectItem.m_connectName); + m_nameLabel->setLabelText(m_lanConnectItem.m_connectName); return; } @@ -220,3 +249,40 @@ void LanListItem::updateConnectionPath(QString connectionPath) { m_lanConnectItem.m_connectPath = connectionPath; } + +void LanListItem::enterEvent(QEvent *event) +{ + m_nameLabel->setLabelMaximumWidth(NAMELABLE_MAX_WIDTH_HOVER); + if (m_lanConnectItem.m_connectState != UnknownState) { + if (Deactivated != m_lanConnectItem.m_connectState) { + m_hoverButton->setProperty("useButtonPalette", true); + m_hoverButton->setProperty("isImportant", false); + m_hoverButton->setButtonText(tr("Disconnect")); + } else { + m_hoverButton->setProperty("isImportant", true); + m_hoverButton->setProperty("useButtonPalette", false); + m_hoverButton->setButtonText(tr("Connect")); + } + m_hoverButton->show(); + m_lbLoadUp->hide(); + m_lbLoadDown->hide(); + m_lbLoadDownImg->hide(); + m_lbLoadUpImg->hide(); + } + return ListItem::enterEvent(event); +} + +void LanListItem::leaveEvent(QEvent *event) +{ + m_hoverButton->hide(); + if (m_lanConnectItem.m_connectState == Activated) { + m_nameLabel->setLabelMaximumWidth(NAMELABLE_MAX_WIDTH_ACTIVATED); + m_lbLoadUp->show(); + m_lbLoadDown->show(); + m_lbLoadDownImg->show(); + m_lbLoadUpImg->show(); + } else { + m_nameLabel->setLabelMaximumWidth(NAMELABLE_MAX_WIDTH_DEACTIVATED); + } + return ListItem::leaveEvent(event); +} diff --git a/src/frontend/list-items/lanlistitem.h b/src/frontend/list-items/lanlistitem.h index c778e7eb..d6acd958 100644 --- a/src/frontend/list-items/lanlistitem.h +++ b/src/frontend/list-items/lanlistitem.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef LANLISTITEM_H #define LANLISTITEM_H #include "listitem.h" @@ -29,11 +48,13 @@ public: protected: void setIcon(bool isOn); void onRightButtonClicked(); + void enterEvent(QEvent *event); + void leaveEvent(QEvent *event); private: void connectItemCopy(const KyConnectItem *lanConnectItem); -private slots: +private Q_SLOTS: void onInfoButtonClicked(); void onNetButtonClicked(); void onMenuTriggered(QAction *action); diff --git a/src/frontend/list-items/list-items.pri b/src/frontend/list-items/list-items.pri index 42550113..8fdc468e 100644 --- a/src/frontend/list-items/list-items.pri +++ b/src/frontend/list-items/list-items.pri @@ -8,13 +8,11 @@ HEADERS += \ $$PWD/lanlistitem.h \ $$PWD/listitem.h \ $$PWD/wlanlistitem.h \ - $$PWD/wlanmoreitem.h \ - $$PWD/vpnlistitem.h + $$PWD/wlanmoreitem.h SOURCES += \ $$PWD/lanlistitem.cpp \ $$PWD/listitem.cpp \ $$PWD/wlanlistitem.cpp \ - $$PWD/wlanmoreitem.cpp \ - $$PWD/vpnlistitem.cpp + $$PWD/wlanmoreitem.cpp diff --git a/src/frontend/list-items/listitem.cpp b/src/frontend/list-items/listitem.cpp index 88c8d72a..6be2743b 100644 --- a/src/frontend/list-items/listitem.cpp +++ b/src/frontend/list-items/listitem.cpp @@ -1,16 +1,115 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "listitem.h" #include #define MAIN_LAYOUT_MARGINS 0,0,0,0 #define MAIN_LAYOUT_SPACING 0 -#define ITEM_FRAME_MARGINS 16,6,16,6 -#define ITEM_FRAME_SPACING 10 -#define FRAME_WIDTH 395 +#define ITEM_FRAME_MARGINS 12,6,16,6 + +#define ITEM_FRAME_SPACING 8 +#define FRAME_WIDTH 404 #define INFO_ICON_WIDTH 16 #define INFO_ICON_HEIGHT 16 #define LIGHT_HOVER_COLOR QColor(240,240,240,255) #define DARK_HOVER_COLOR QColor(15,15,15,255) +#define CONNECT_BUTTON_WIDTH 96 +#define PWD_AREA_HEIGHT 36 + +#define FREQLABLE_HIGHT 18 +#define FREQLABLE_MARGINS 4,0,4,0 +#define LOADIMG_SIZE 16,16 + +FreqLabel::FreqLabel(QWidget *parent) : QLabel(parent) +{ + const QByteArray id("org.ukui.style"); + QGSettings * fontSetting = new QGSettings(id, QByteArray(), this); + if(QGSettings::isSchemaInstalled(id)){ + connect(fontSetting, &QGSettings::changed,[=](QString key) { + if ("systemFontSize" ==key) { + changedFontSlot(); + } + }); + } + changedFontSlot(); +} + +void FreqLabel::changedFontSlot() +{ + const QByteArray id("org.ukui.style"); + if(QGSettings::isSchemaInstalled(id)){ + QGSettings * fontSetting = new QGSettings(id, QByteArray(), this); + QVariant fontVariant = fontSetting->get("systemFontSize"); + QFont font; + font.setPointSize(fontVariant.toInt()*0.85); + this->setFont(font); + } +} + +void FreqLabel::paintEvent(QPaintEvent *event) +{ + QPainter painter(this); + painter.setRenderHint(QPainter::Antialiasing); //抗锯齿效果 + auto rect = this->rect(); + painter.drawRoundedRect(rect, 6, 6); + QLabel::paintEvent(event); +} + +FixPushButton::FixPushButton(QWidget *parent) : + QPushButton(parent) +{ + const QByteArray id("org.ukui.style"); + QGSettings * fontSetting = new QGSettings(id, QByteArray(), this); + if(QGSettings::isSchemaInstalled(id)){ + connect(fontSetting, &QGSettings::changed,[=](QString key) { + if ("systemFont" == key || "systemFontSize" ==key) { + changedLabelSlot(); + } + }); + } +} + + +void FixPushButton::setButtonText(QString text) { + + mStr = text; + changedLabelSlot(); +} + +QString FixPushButton::getText(){ + return mStr; +} + +void FixPushButton::changedLabelSlot() { + QFontMetrics fontMetrics(this->font()); + int fontSize = fontMetrics.width(mStr); + if (fontSize > 65) { + setText(fontMetrics.elidedText(mStr, Qt::ElideRight, 65)); + setToolTip(mStr); + } else { + setText(mStr); + setToolTip(""); + } +} + ListItem::ListItem(QWidget *parent) : QFrame(parent) { m_connectState = UnknownState; @@ -28,16 +127,16 @@ ListItem::~ListItem() m_netButton = nullptr; } - if (nullptr != m_infoButton) { - delete m_infoButton; - m_infoButton = nullptr; - } +// if (nullptr != m_infoButton) { +// delete m_infoButton; +// m_infoButton = nullptr; +// } } void ListItem::setName(const QString &name) { - m_nameLabel->setText(name); + m_nameLabel->setLabelText(name); } //仅无线调用,有线自己获取 @@ -80,14 +179,21 @@ void ListItem::showDesktopNotify(const QString &message, QString soundName) void ListItem::mousePressEvent(QMouseEvent *event) { qDebug()<<"[ListItem]"<<"mousePressEvent"; - if (event->button() == Qt::LeftButton) { - onNetButtonClicked(); - } else if (event->button() == Qt::RightButton) { + if (event->button() == Qt::RightButton) { onRightButtonClicked(); } return QFrame::mousePressEvent(event); } +void ListItem::mouseReleaseEvent(QMouseEvent *event) +{ + qDebug()<<"[ListItem]"<<"mouseReleaseEvent"; + if (event->button() == Qt::LeftButton) { + onNetButtonClicked(); + } + return QFrame::mouseReleaseEvent(event); +} + void ListItem::enterEvent(QEvent *event) { // QPalette pal = qApp->palette(); @@ -136,20 +242,65 @@ void ListItem::initUI() m_hItemLayout = new QHBoxLayout(m_itemFrame); m_hItemLayout->setContentsMargins(ITEM_FRAME_MARGINS); -// m_hItemLayout->setSpacing(ITEM_FRAME_SPACING); + m_hItemLayout->setSpacing(0); + m_hItemLayout->setAlignment(Qt::AlignHCenter); m_netButton = new RadioItemButton(m_itemFrame); - m_nameLabel = new FixLabel(m_itemFrame); - m_infoButton = new InfoButton(m_itemFrame); - m_infoButton->setIconSize(QSize(INFO_ICON_WIDTH,INFO_ICON_HEIGHT)); + m_freq = new FreqLabel(m_itemFrame); + m_freq->setEnabled(false); + m_freq->setText("..."); + m_freq->setAlignment(Qt::AlignCenter); + m_freq->hide(); + m_freq->setFixedHeight(FREQLABLE_HIGHT); + m_freq->setContentsMargins(FREQLABLE_MARGINS); + m_nameLabel = new NameLabel(m_itemFrame); + m_hoverButton = new FixPushButton(m_itemFrame); + m_hoverButton->setProperty("needTranslucent", true); + m_hoverButton->setFixedSize(CONNECT_BUTTON_WIDTH, PWD_AREA_HEIGHT); +// m_infoButton = new InfoButton(m_itemFrame); +// m_infoButton->setIconSize(QSize(INFO_ICON_WIDTH,INFO_ICON_HEIGHT)); + + m_lbLoadUp = new QLabel(m_itemFrame); + m_lbLoadUp->setAlignment(Qt::AlignCenter); + m_lbLoadDown = new QLabel(m_itemFrame); + m_lbLoadDown->setAlignment(Qt::AlignCenter); + m_lbLoadDownImg = new QLabel(m_itemFrame); + m_lbLoadUpImg = new QLabel(m_itemFrame); + m_lbLoadUp->hide(); + m_lbLoadDown->hide(); + m_lbLoadDownImg->hide(); + m_lbLoadUpImg->hide(); + m_lbLoadDownImg->setFixedSize(LOADIMG_SIZE); + m_lbLoadDownImg->setAlignment(Qt::AlignCenter); + m_lbLoadUpImg->setFixedSize(LOADIMG_SIZE); + m_lbLoadUpImg->setAlignment(Qt::AlignCenter); + QFont font; + font.setPointSize(10); + m_lbLoadUp->setFont(font); + m_lbLoadDown->setFont(font); + m_lbLoadUp->setText("0KB/s"); + m_lbLoadDown->setText("0KB/s"); + m_lbLoadDownImg->setPixmap(QPixmap(QLatin1String(":/res/x/load-down.png"))); + m_lbLoadUpImg->setPixmap(QPixmap(QLatin1String(":/res/x/load-up.png"))); m_hItemLayout->addWidget(m_netButton); + m_hItemLayout->addSpacing(10); m_hItemLayout->addWidget(m_nameLabel); + m_hItemLayout->addSpacing(8); + m_hItemLayout->addWidget(m_freq); m_hItemLayout->addStretch(); - m_hItemLayout->addWidget(m_infoButton); + m_hItemLayout->addWidget(m_lbLoadUpImg); + m_hItemLayout->addWidget(m_lbLoadUp); + m_hItemLayout->addSpacing(2); + m_hItemLayout->addWidget(m_lbLoadDownImg); + m_hItemLayout->addWidget(m_lbLoadDown); + m_hItemLayout->addSpacing(2); + m_hItemLayout->addWidget(m_hoverButton); +// m_hItemLayout->addWidget(m_infoButton); m_mainLayout->addWidget(m_itemFrame); + m_hoverButton->hide(); // this->setAutoFillBackground(true); // this->setBackgroundRole(QPalette::Base); // QPalette pal = qApp->palette(); @@ -171,3 +322,45 @@ void ListItem::onPaletteChanged() // this->setPalette(pal); } +NameLabel::NameLabel(QWidget *parent) + :QLabel(parent) +{ + const QByteArray id("org.ukui.style"); + QGSettings * fontSetting = new QGSettings(id, QByteArray(), this); + if(QGSettings::isSchemaInstalled(id)){ + connect(fontSetting, &QGSettings::changed,[=](QString key) { + if ("systemFont" == key || "systemFontSize" ==key) { + changedLabelSlot(); + } + }); + } +} + +void NameLabel::setLabelText(QString text) +{ + m_name = text; + changedLabelSlot(); +} + +void NameLabel::setLabelMaximumWidth(int width) +{ + m_maximumWidth = width; + this->setMaximumWidth(m_maximumWidth); + if (m_name != nullptr) { + changedLabelSlot(); + } +} + +void NameLabel::changedLabelSlot() +{ + QFontMetrics fontMetrics(this->font()); + int fontSize = fontMetrics.width(m_name); + if (fontSize > m_maximumWidth) { + setText(fontMetrics.elidedText(m_name, Qt::ElideRight, m_maximumWidth)); + setToolTip(m_name); + } else { + this->setFixedWidth(fontMetrics.width(m_name)); + setText(m_name); + setToolTip(""); + } +} diff --git a/src/frontend/list-items/listitem.h b/src/frontend/list-items/listitem.h index 19acb44f..bb5b956c 100644 --- a/src/frontend/list-items/listitem.h +++ b/src/frontend/list-items/listitem.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef LISTITEM_H #define LISTITEM_H #include @@ -18,6 +37,54 @@ typedef enum{ Deactivated /**< The connection is no longer active */ }ConnectState; +class FreqLabel : public QLabel +{ + Q_OBJECT +public: + FreqLabel(QWidget *parent = nullptr); + ~FreqLabel() = default; +protected: + void paintEvent(QPaintEvent *event); + +private Q_SLOTS: + void changedFontSlot(); +}; + +class FixPushButton : public QPushButton +{ + Q_OBJECT +public: + explicit FixPushButton(QWidget *parent = 0); + +public: + void setButtonText(QString text); + QString getText(); + +private Q_SLOTS: + void changedLabelSlot(); +private: + QString mStr; + +}; + +class NameLabel : public QLabel +{ + Q_OBJECT +public: + explicit NameLabel(QWidget *parent = 0); + ~NameLabel() = default; + void setLabelText(QString text); + void setLabelMaximumWidth(int width); + +private: + QString m_name; + int m_maximumWidth = 120; + +private Q_SLOTS: + void changedLabelSlot(); + +}; + class ListItem : public QFrame { Q_OBJECT @@ -31,6 +98,7 @@ public: protected: void mousePressEvent(QMouseEvent *event); + void mouseReleaseEvent(QMouseEvent *event); void enterEvent(QEvent *event); void leaveEvent(QEvent *event); void paintEvent(QPaintEvent *event); @@ -39,9 +107,9 @@ protected: protected: QFrame * m_itemFrame = nullptr; - FixLabel * m_nameLabel = nullptr; + NameLabel * m_nameLabel = nullptr; RadioItemButton * m_netButton = nullptr; - InfoButton * m_infoButton = nullptr; +// InfoButton * m_infoButton = nullptr; bool m_isActive = false; ConnectState m_connectState; @@ -51,18 +119,26 @@ public: QVBoxLayout * m_mainLayout = nullptr; QHBoxLayout * m_hItemLayout = nullptr; + QLabel *m_lbLoadDown = nullptr; + QLabel *m_lbLoadUp = nullptr; + QLabel *m_lbLoadDownImg = nullptr; + QLabel *m_lbLoadUpImg = nullptr; + QLabel *m_freq = nullptr; + NetDetail *netDetail = nullptr; + + FixPushButton *m_hoverButton = nullptr; private: void initUI(); void initConnection(); -public slots: +public Q_SLOTS: virtual void onNetButtonClicked() = 0; void onPaletteChanged(); virtual void onMenuTriggered(QAction *action)=0; -signals: - void detailShow(bool isShow); +Q_SIGNALS: + void detailShow(QString, QString); }; #endif // LISTITEM_H diff --git a/src/frontend/list-items/wlanlistitem.cpp b/src/frontend/list-items/wlanlistitem.cpp index 1f1adfc0..908facc4 100644 --- a/src/frontend/list-items/wlanlistitem.cpp +++ b/src/frontend/list-items/wlanlistitem.cpp @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "wlanlistitem.h" #include #include @@ -6,6 +25,15 @@ #define EMPTY_SSID "EMPTY_SSID" #define LOG_FLAG "[WlanListItem]" #define WAIT_US 10*1000 +#define ENABLE_BUTTON_COLOR qApp->palette().highlight().color() +#define UNABLE_BUTTON_COLOR qApp->palette().button().color() +#define NAMELABLE_MAX_WIDTH_HOVER 176 +#define NAMELABLE_MAX_WIDTH_ACTIVATED 142 +#define NAMELABLE_MAX_WIDTH_DEACTIVATED 276 + +const QString ENTERPRICE_TYPE = "802.1X"; +const QString WPA1_AND_WPA2 = "WPA"; +const QString WPA3 = "WPA3"; WlanListItem::WlanListItem(KyWirelessNetItem &wirelessNetItem, QString device, bool isApMode, QWidget *parent) : WlanListItem(wirelessNetItem, device, parent) @@ -24,8 +52,9 @@ WlanListItem::WlanListItem(KyWirelessNetItem &wirelessNetItem, QString device, Q initWlanUI(); setExpanded(false); - connect(this->m_infoButton, &InfoButton::clicked, this, &WlanListItem::onInfoButtonClicked); +// connect(this->m_infoButton, &InfoButton::clicked, this, &WlanListItem::onInfoButtonClicked); connect(m_menu, &QMenu::triggered, this, &WlanListItem::onMenuTriggered); + connect(m_hoverButton, &FixPushButton::clicked, this, &WlanListItem::onNetButtonClicked); m_wirelessConnectOperation = new KyWirelessConnectOperation(this); m_deviceResource = new KyNetworkDeviceResourse(this); @@ -44,7 +73,7 @@ WlanListItem::WlanListItem(QWidget *parent) : ListItem(parent) setExpanded(false); this->setName(name); // this->m_netButton->setEnabled(false); - this->m_infoButton->hide(); +// this->m_infoButton->hide(); } WlanListItem::~WlanListItem() @@ -57,6 +86,16 @@ QString WlanListItem::getSsid() return m_wirelessNetItem.m_NetSsid; } +QString WlanListItem::getUuid() +{ + return m_wirelessNetItem.m_connectUuid; +} + +QString WlanListItem::getPath() +{ + return m_wirelessNetItem.m_connDbusPath; +} + void WlanListItem::setSignalStrength(const int &signal) { m_wirelessNetItem.m_signalStrength = signal; @@ -98,11 +137,13 @@ void WlanListItem::setExpanded(const bool &expanded) if (expanded) { m_pwdLineEdit->setFocus(); setFixedHeight(EXPANDED_HEIGHT); + m_hoverButton->hide(); + m_nameLabel->setLabelMaximumWidth(NAMELABLE_MAX_WIDTH_DEACTIVATED); } else { setFixedHeight(NORMAL_HEIGHT); } - emit this->itemHeightChanged(expanded, m_wirelessNetItem.m_NetSsid); + Q_EMIT this->itemHeightChanged(expanded, m_wirelessNetItem.m_NetSsid); return; } @@ -142,11 +183,12 @@ void WlanListItem::onRightButtonClicked() } if (m_wirelessNetItem.m_isConfigured) { + m_menu->addAction(new QAction(tr("Property"), this)); m_menu->addAction(new QAction(tr("Forget"), this)); } - m_menu->move(cursor().pos()); - m_menu->show(); +// m_menu->move(cursor().pos()); + m_menu->popup(cursor().pos()); return; } @@ -155,6 +197,23 @@ void WlanListItem::enterEvent(QEvent *event) { //qDebug()<< LOG_FLAG <<"enterEvent" << m_wirelessNetItem.m_NetSsid; m_mouseIsOut = false; + if (m_pwdFrame != nullptr && !m_pwdFrame->isVisible()) { + if (Deactivated != m_connectState) { + m_hoverButton->setProperty("useButtonPalette", true); + m_hoverButton->setProperty("isImportant", false); + m_hoverButton->setButtonText(tr("Disconnect")); + } else { + m_hoverButton->setProperty("isImportant", true); + m_hoverButton->setProperty("useButtonPalette", false); + m_hoverButton->setButtonText(tr("Connect")); + } + m_hoverButton->show(); + m_lbLoadUp->hide(); + m_lbLoadDown->hide(); + m_lbLoadDownImg->hide(); + m_lbLoadUpImg->hide(); + } + m_nameLabel->setLabelMaximumWidth(NAMELABLE_MAX_WIDTH_HOVER); return ListItem::enterEvent(event); } @@ -162,6 +221,16 @@ void WlanListItem::leaveEvent(QEvent *event) { //qDebug()<< LOG_FLAG <<"leaveEvent"<< m_wirelessNetItem.m_NetSsid; m_mouseIsOut = true; + m_hoverButton->hide(); + if (m_connectState == Activated) { + m_nameLabel->setLabelMaximumWidth(NAMELABLE_MAX_WIDTH_ACTIVATED); + m_lbLoadUp->show(); + m_lbLoadDown->show(); + m_lbLoadDownImg->show(); + m_lbLoadUpImg->show(); + } else { + m_nameLabel->setLabelMaximumWidth(NAMELABLE_MAX_WIDTH_DEACTIVATED); + } if (m_pwdFrame && m_pwdFrame->isVisible()) { if (m_focusIsOut) { setExpanded(false); @@ -206,6 +275,17 @@ void WlanListItem::keyPressEvent(QKeyEvent *event) return QFrame::keyPressEvent(event); } +void WlanListItem::paintEvent(QPaintEvent *event) +{ + QPalette pal = qApp->palette(); + if (m_pwdLineEdit != nullptr) { + pal.setColor(QPalette::Base, pal.color(QPalette::Base)); + m_pwdLineEdit->setPalette(pal); + } + + return QWidget::paintEvent(event); +} + void WlanListItem::initWlanUI() { m_hasPwd = (m_wirelessNetItem.m_secuType.isEmpty() || m_wirelessNetItem.m_secuType == "") ? false : true; @@ -232,6 +312,8 @@ void WlanListItem::initWlanUI() m_pwdLineEdit = new KPasswordEdit(m_pwdFrame); m_pwdLineEdit->setFixedWidth(LINEEDIT_WIDTH); + m_pwdLineEdit->setProperty("needTranslucent", true); + m_pwdLineEdit->setUseCustomPalette(true); m_pwdLineEdit->setClearButtonEnabled(false); //禁用ClearBtn按钮 m_pwdLineEdit->setAttribute(Qt::WA_InputMethodEnabled, true); //打开输入法 // m_pwdLineEdit->setAttribute(Qt::WA_InputMethodEnabled, false); @@ -246,9 +328,11 @@ void WlanListItem::initWlanUI() m_pwdLineEdit->setFixedHeight(PWD_AREA_HEIGHT); m_pwdFrameLyt->addWidget(m_pwdLineEdit); - m_connectButton = new QPushButton(m_pwdFrame); + m_connectButton = new FixPushButton(m_pwdFrame); + m_connectButton->setProperty("isImportant", true); + m_connectButton->setProperty("needTranslucent", true); m_connectButton->setFixedSize(CONNECT_BUTTON_WIDTH, PWD_AREA_HEIGHT); - m_connectButton->setText(tr("Connect")); + m_connectButton->setButtonText(tr("Connect")); m_connectButton->setEnabled(false); connect(m_connectButton, &QPushButton::clicked, this, &WlanListItem::onConnectButtonClicked); m_pwdFrameLyt->addWidget(m_connectButton); @@ -275,9 +359,13 @@ void WlanListItem::initWlanUI() m_mainLayout->addWidget(m_pwdFrame); m_mainLayout->addWidget(m_autoConnectFrame); + m_mainLayout->addStretch(); m_pwdFrame->hide(); m_autoConnectFrame->hide(); + + this->m_freq->show(); + this->setFrequency(); } QString getIcon(bool isEncrypted, int signalStrength, int category) { @@ -385,17 +473,17 @@ void WlanListItem::refreshIcon(bool isActivated) void WlanListItem::onInfoButtonClicked() { //ZJP_TODO 呼出无线详情页 - if(netDetail != nullptr){ - netDetail->activateWindow(); - return; - } +// if(netDetail != nullptr){ +// netDetail->activateWindow(); +// return; +// } qDebug() << LOG_FLAG << "Net active or not:"<< m_connectState; qDebug() << LOG_FLAG << "On wlan info button clicked! ssid = " << m_wirelessNetItem.m_NetSsid << "; name = " << m_wirelessNetItem.m_connName << "." <show(); - emit this->detailShow(true); +#endif + Q_EMIT this->detailShow(m_wlanDevice, m_wirelessNetItem.m_NetSsid); } void WlanListItem::onNetButtonClicked() @@ -421,24 +510,45 @@ void WlanListItem::onNetButtonClicked() } if (Deactivated != m_connectState) { - qDebug() << LOG_FLAG <<"the connection" << m_wirelessNetItem.m_connName - << "is not deactived, so it can not be operation." << Q_FUNC_INFO << __LINE__; + m_wirelessConnectOperation->deActivateWirelessConnection(m_wlanDevice, m_wirelessNetItem.m_connectUuid); return; } + //获取有配置网络的安全类型 + KyKeyMgmt type = m_wirelessConnectOperation->getConnectKeyMgmt(m_wirelessNetItem.m_connectUuid); + KySecuType kySecuType = NONE; + if (type == WpaNone || type == Unknown) { + kySecuType = NONE; + } else if (type == WpaPsk) { + kySecuType = WPA_AND_WPA2_PERSONAL; + } else if (type == SAE) { + kySecuType = WPA3_PERSONAL; + } else if (type == WpaEap) { + kySecuType = WPA_AND_WPA2_ENTERPRISE; + } else { + qDebug() << "KeyMgmt not support now " << type; + } + //qDebug() << "!!!!" << m_wirelessNetItem.m_kySecuType << kySecuType; //有配置或者无密码的wifi直接连接 if (m_wirelessNetItem.m_isConfigured) { - m_wirelessConnectOperation->activeWirelessConnect(m_wlanDevice, m_wirelessNetItem.m_connectUuid); - qDebug()<<"[WlanListItem] Has configuration, will be activated. ssid = " - << m_wirelessNetItem.m_NetSsid << Q_FUNC_INFO << __LINE__; - m_netButton->startLoading(); - return; + if (m_wirelessNetItem.m_kySecuType == kySecuType) { + //安全类型不变直接连接 + m_wirelessConnectOperation->activeWirelessConnect(m_wlanDevice, m_wirelessNetItem.m_connectUuid); + qDebug()<<"[WlanListItem] Has configuration, will be activated. ssid = " + << m_wirelessNetItem.m_NetSsid << Q_FUNC_INFO << __LINE__; + m_netButton->startLoading(); + return; + } else { + //安全类型改变则删除连接 + m_wirelessConnectOperation->deleteWirelessConnect(m_wirelessNetItem.m_connectUuid); + } } if (!this->m_connectButton->isVisible() && m_wirelessNetItem.m_secuType != "") { if (m_wirelessNetItem.m_secuType.contains("802.1x", Qt::CaseInsensitive)) { if (isEnterpriseWlanDialogShow && enterpriseWlanDialog != nullptr) { qDebug() << LOG_FLAG <<"EnterpriseWlanDialog is show do not show again!"; + KWindowSystem::activateWindow(enterpriseWlanDialog->winId()); KWindowSystem::raiseWindow(enterpriseWlanDialog->winId()); return; } else { @@ -464,7 +574,7 @@ void WlanListItem::updateWirelessNetSecurity(QString ssid, QString securityType) } qDebug() << LOG_FLAG << "Security changed! ssid = " << m_wirelessNetItem.m_NetSsid - << "; security = " << m_wirelessNetItem.m_secuType << "." <stopLoading(); m_netButton->setActive(true); + m_hoverButton->setProperty("useButtonPalette", true); + m_hoverButton->setProperty("isImportant", false); + m_hoverButton->setButtonText(tr("Disconnect")); + if (m_hoverButton->isHidden()) { + m_nameLabel->setLabelMaximumWidth(NAMELABLE_MAX_WIDTH_ACTIVATED); + } } else if(Deactivated == state) { qDebug() << "[WlanListItem] stop loading connect state:" << state; m_netButton->stopLoading(); m_netButton->setActive(false); + m_hoverButton->setProperty("isImportant", true); + m_hoverButton->setProperty("useButtonPalette", false); + m_hoverButton->setButtonText(tr("Connect")); + if (m_hoverButton->isHidden()) { + m_nameLabel->setLabelMaximumWidth(NAMELABLE_MAX_WIDTH_DEACTIVATED); + } } else { qDebug() << "[WlanListItem] start loading connect state:" << state; m_netButton->startLoading(); + m_hoverButton->setProperty("useButtonPalette", true); + m_hoverButton->setProperty("isImportant", false); + m_hoverButton->setButtonText(tr("Disconnect")); } return; @@ -572,6 +699,8 @@ void WlanListItem::onMenuTriggered(QAction *action) m_pwdLineEdit->clear(); } m_wirelessConnectOperation->deleteWirelessConnect(m_wirelessNetItem.m_connectUuid); + } else if (action->text() == tr("Property")) { + onInfoButtonClicked(); } return; @@ -592,4 +721,20 @@ void WlanListItem::forgetPwd() } } +void WlanListItem::setFrequency() +{ + uint freq = m_wirelessNetItem.m_frequency; + bool isMix = m_wirelessNetItem.m_isMix; + if (isMix) { + this->m_freq->setText("2.4/5G"); + return; + } + if (freq < FREQ_5GHZ) { + this->m_freq->setText("2.4G"); + } else { + this->m_freq->setText("5G"); + } + + return; +} diff --git a/src/frontend/list-items/wlanlistitem.h b/src/frontend/list-items/wlanlistitem.h index ff0e26b4..a14b1615 100644 --- a/src/frontend/list-items/wlanlistitem.h +++ b/src/frontend/list-items/wlanlistitem.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef WLANLISTITEM_H #define WLANLISTITEM_H #include "listitem.h" @@ -29,6 +48,8 @@ using namespace kdk; #define LOW_SIGNAL 5 #define NONE_SIGNAL 0 +#define FREQ_5GHZ 5000 + class WlanListItem : public ListItem { Q_OBJECT @@ -41,6 +62,10 @@ public: public: QString getSsid(); + QString getUuid(); + + QString getPath(); + void setSignalStrength(const int &signal); int getSignalStrength(); @@ -57,6 +82,8 @@ public: void forgetPwd(); + void setFrequency(); + protected: void resizeEvent(QResizeEvent *event); void onRightButtonClicked(); @@ -64,8 +91,9 @@ protected: void leaveEvent(QEvent *event); bool eventFilter(QObject *watched, QEvent *event); void keyPressEvent(QKeyEvent *event); + void paintEvent(QPaintEvent *event); -signals: +Q_SIGNALS: void itemHeightChanged(const bool isExpanded, const QString &ssid); private: @@ -87,7 +115,7 @@ private: QFrame *m_pwdFrame = nullptr; QHBoxLayout *m_pwdFrameLyt = nullptr; KPasswordEdit *m_pwdLineEdit = nullptr; - QPushButton *m_connectButton = nullptr; + FixPushButton *m_connectButton = nullptr; //自动连接选择区域UI QFrame *m_autoConnectFrame = nullptr; @@ -101,10 +129,10 @@ private: bool m_forgetConnection = false; bool m_isApMode = false; -protected slots: +protected Q_SLOTS: void onInfoButtonClicked(); -private slots: +private Q_SLOTS: void onNetButtonClicked(); void onPwdEditorTextChanged(); void onConnectButtonClicked(); diff --git a/src/frontend/list-items/wlanmoreitem.cpp b/src/frontend/list-items/wlanmoreitem.cpp index 7284d703..576e3363 100644 --- a/src/frontend/list-items/wlanmoreitem.cpp +++ b/src/frontend/list-items/wlanmoreitem.cpp @@ -1,11 +1,31 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "wlanmoreitem.h" WlanMoreItem::WlanMoreItem(QWidget *parent) : ListItem(parent) { setObjectName(WMI_OB_NAME); m_netButton->setVisible(false); - m_infoButton->setVisible(false); - m_nameLabel->setText(tr("Add Others...")); +// m_infoButton->setVisible(false); + m_nameLabel->setLabelMaximumWidth(326); + m_nameLabel->setLabelText(tr("Add Others...")); } WlanMoreItem::~WlanMoreItem() { @@ -13,7 +33,7 @@ WlanMoreItem::~WlanMoreItem() { } void WlanMoreItem::onNetButtonClicked() { - emit hiddenWlanClicked(); + Q_EMIT hiddenWlanClicked(); } void WlanMoreItem::onRightButtonClicked() { diff --git a/src/frontend/list-items/wlanmoreitem.h b/src/frontend/list-items/wlanmoreitem.h index 52183403..81218517 100644 --- a/src/frontend/list-items/wlanmoreitem.h +++ b/src/frontend/list-items/wlanmoreitem.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef WLANMOREITEM_H #define WLANMOREITEM_H @@ -19,7 +38,7 @@ public: void onNetButtonClicked(); void onMenuTriggered(QAction *action); -signals: +Q_SIGNALS: void hiddenWlanClicked(); }; diff --git a/src/frontend/mainwindow.cpp b/src/frontend/mainwindow.cpp index 767c909d..e0ca8160 100644 --- a/src/frontend/mainwindow.cpp +++ b/src/frontend/mainwindow.cpp @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "mainwindow.h" #include "customstyle.h" #include @@ -6,7 +25,6 @@ #include #include #include -#include #include #include "kylinnetworkdeviceresource.h" @@ -14,7 +32,7 @@ #include "ukuistylehelper/ukuistylehelper.h" #include "windowmanager/windowmanager.h" - +#include "kysdk/kysdk-system/libkysysinfo.h" #define MAINWINDOW_WIDTH 420 #define MAINWINDOW_HEIGHT 476 @@ -26,11 +44,32 @@ const QString v10Sp1 = "V10SP1"; const QString intel = "V10SP1-edu"; +#define LANPAGE 0 +#define WLANPAGE 1 +#define AUTOSELET 2 + #define KEY_PRODUCT_FEATURES "PRODUCT_FEATURES" +#define MW_EXCELLENT_SIGNAL 80 +#define MW_GOOD_SIGNAL 55 +#define MW_OK_SIGNAL 30 +#define MW_LOW_SIGNAL 5 +#define MW_NONE_SIGNAL 0 + +#define EXCELLENT_SIGNAL_ICON "network-wireless-signal-excellent-symbolic" +#define GOOD_SIGNAL_ICON "network-wireless-signal-good-symbolic" +#define OK_SIGNAL_ICON "network-wireless-signal-ok-symbolic" +#define LOW_SIGNAL_ICON "network-wireless-signal-weak-symbolic" +#define NONE_SIGNAL_ICON "network-wireless-signal-none-symbolic" + +#define EXCELLENT_SIGNAL_LIMIT_ICON "ukui-network-wireless-signal-excellent-error-symbolic" +#define GOOD_SIGNAL_LIMIT_ICON "ukui-network-wireless-signal-good-error-symbolic" +#define OK_SIGNAL_LIMIT_ICON "ukui-network-wireless-signal-ok-error-symbolic" +#define LOW_SIGNAL_LIMIT_ICON "ukui-network-wireless-signal-weak-error-symbolic" +#define NONE_SIGNAL_LIMIT_ICON "ukui-network-wireless-signal-none-error-symbolic" + #include #include -#include "kysdk/kysdk-system/libkysysinfo.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { @@ -62,7 +101,7 @@ void MainWindow::showMainwindow() this->showByWaylandHelper(); this->raise(); this->activateWindow(); - emit this->mainWindowVisibleChanged(true); + Q_EMIT this->mainWindowVisibleChanged(true); #ifdef WITHKYSEC if (!kysec_is_disabled() && kysec_get_3adm_status() && (getuid() || geteuid())){ if (nullptr != m_wlanWidget) { @@ -89,7 +128,7 @@ void MainWindow::showMainwindow() void MainWindow::hideMainwindow() { this->hide(); - emit this->mainWindowVisibleChanged(false); + Q_EMIT this->mainWindowVisibleChanged(false); } /** @@ -121,7 +160,6 @@ void MainWindow::firstlyStart() initWindowTheme(); initTrayIcon(); initPlatform(); - installEventFilter(this); m_secondaryStartTimer = new QTimer(this); connect(m_secondaryStartTimer, &QTimer::timeout, this, [ = ]() { m_secondaryStartTimer->stop(); @@ -131,6 +169,10 @@ void MainWindow::firstlyStart() m_createPagePtrMap.clear(); + m_networkMode = new NetworkMode(this); + m_networkMode->initWiredNetworkMode(); + m_networkMode->initWirelessNetworkMode(); + //加载key ring agent_init(); } @@ -150,19 +192,19 @@ void MainWindow::secondaryStart() */ void MainWindow::initPlatform() { - char* projectName = kdk_system_get_projectName(); - QString strProjectName(projectName); - free(projectName); - projectName = NULL; - if(v10Sp1.compare(strProjectName,Qt::CaseInsensitive) == 0) { - unsigned int feature = kdk_system_get_productFeatures(); - if (feature == 3) { - m_isShowInCenter = true; - } - } else if (intel.compare(strProjectName,Qt::CaseInsensitive) == 0) { - m_isShowInCenter = true; - } - qDebug() << "projectName" << projectName << m_isShowInCenter; +// char* projectName = kdk_system_get_projectName(); +// QString strProjectName(projectName); +// free(projectName); +// projectName = NULL; +// if(v10Sp1.compare(strProjectName,Qt::CaseInsensitive) == 0) { +// unsigned int feature = kdk_system_get_productFeatures(); +// if (feature == 3) { +// m_isShowInCenter = true; +// } +// } else if (intel.compare(strProjectName,Qt::CaseInsensitive) == 0) { +// m_isShowInCenter = true; +// } +// qDebug() << "projectName" << projectName << m_isShowInCenter; } /** @@ -188,6 +230,30 @@ void MainWindow::initWindowProperties() } } +/** + * @brief MainWindow::registerTrayIcon 注册托盘图标 + */ +void MainWindow::registerTrayIcon() +{ + m_registerCount++; + if (QSystemTrayIcon::isSystemTrayAvailable() || m_registerCount > 10) { + m_trayIcon = new QSystemTrayIcon(); + if (nullptr == m_trayIcon) { + qWarning()<< "分配空间trayIcon失败"; + return ; + } + m_trayIcon->setIcon(QIcon::fromTheme("network-wired-signal-excellent-symbolic")); + m_trayIcon->setToolTip(QString(tr("kylin-nm"))); + + } else { + if (m_registerCount <= 10) { + QTimer::singleShot(m_intervalTime,[this] { + registerTrayIcon(); + }); + } + } +} + void MainWindow::paintEvent(QPaintEvent *event) { QPainter painter(this); @@ -243,6 +309,7 @@ void MainWindow::initUI() this->setCentralWidget(m_centralWidget); m_centralWidget->tabBar()->setFixedWidth(this->width()+1); m_centralWidget->tabBar()->setProperty("setRadius", 12); +// m_centralWidget->tabBar()->setStyleSheet("QTabBar::tab{min-height:40px}"); m_lanWidget = new LanPage(m_centralWidget); m_wlanWidget = new WlanPage(m_centralWidget); connect(this, &MainWindow::mainWindowVisibleChanged, m_wlanWidget, &WlanPage::onMainWindowVisibleChanged); @@ -266,57 +333,29 @@ void MainWindow::initUI() paintWithTrans(); } -/** - * @brief MainWindow::registerTrayIcon 注册托盘图标 - */ -void MainWindow::registerTrayIcon() -{ - m_registerCount++; - if (QSystemTrayIcon::isSystemTrayAvailable() || m_registerCount > 10) { - m_trayIcon = new QSystemTrayIcon(); - if (nullptr == m_trayIcon) { - qWarning()<< "分配空间trayIcon失败"; - return ; - } - m_trayIcon->setIcon(QIcon::fromTheme("network-wired-signal-excellent-symbolic")); - m_trayIcon->setToolTip(QString(tr("kylin-nm"))); - - } else { - if (m_registerCount <= 10) { - QTimer::singleShot(m_intervalTime,[this] { - registerTrayIcon(); - }); - } - } -} - /** * @brief MainWindow::initTrayIcon 初始化托盘图标和托盘右键菜单 */ void MainWindow::initTrayIcon() { - loadIcons.append(QIcon::fromTheme("kylin-network-1")); - loadIcons.append(QIcon::fromTheme("kylin-network-2")); - loadIcons.append(QIcon::fromTheme("kylin-network-3")); - loadIcons.append(QIcon::fromTheme("kylin-network-4")); - loadIcons.append(QIcon::fromTheme("kylin-network-5")); - loadIcons.append(QIcon::fromTheme("kylin-network-6")); - loadIcons.append(QIcon::fromTheme("kylin-network-7")); - loadIcons.append(QIcon::fromTheme("kylin-network-8")); - loadIcons.append(QIcon::fromTheme("kylin-network-9")); - loadIcons.append(QIcon::fromTheme("kylin-network-10")); - loadIcons.append(QIcon::fromTheme("kylin-network-11")); - loadIcons.append(QIcon::fromTheme("kylin-network-12")); + loadIcons.append(QIcon::fromTheme("ukui-loading-0-symbolic")); + loadIcons.append(QIcon::fromTheme("ukui-loading-1-symbolic")); + loadIcons.append(QIcon::fromTheme("ukui-loading-2-symbolic")); + loadIcons.append(QIcon::fromTheme("ukui-loading-3-symbolic")); + loadIcons.append(QIcon::fromTheme("ukui-loading-4-symbolic")); + loadIcons.append(QIcon::fromTheme("ukui-loading-5-symbolic")); + loadIcons.append(QIcon::fromTheme("ukui-loading-6-symbolic")); + loadIcons.append(QIcon::fromTheme("ukui-loading-7-symbolic")); iconTimer = new QTimer(this); connect(iconTimer, &QTimer::timeout, this, &MainWindow::onSetTrayIconLoading); m_trayIconMenu = new QMenu(); m_showMainwindowAction = new QAction(tr("Show MainWindow"),this); m_showSettingsAction = new QAction(tr("Settings"),this); + m_showSettingsAction->setIcon(QIcon::fromTheme("document-page-setup-symbolic", QIcon(":/res/x/setup.png")) ); // m_trayIconMenu->addAction(m_showMainwindowAction); m_trayIconMenu->addAction(m_showSettingsAction); - m_trayIcon->setContextMenu(m_trayIconMenu); iconStatus = IconActiveType::LAN_CONNECTED; onRefreshTrayIcon(); @@ -333,6 +372,7 @@ void MainWindow::initDbusConnnect() connect(m_lanWidget, &LanPage::deviceNameChanged, this, &MainWindow::deviceNameChanged); connect(m_wlanWidget, &WlanPage::deviceStatusChanged, this, &MainWindow::deviceStatusChanged); connect(m_wlanWidget, &WlanPage::deviceNameChanged, this, &MainWindow::deviceNameChanged); + connect(m_wlanWidget, &WlanPage::wirelessSwitchBtnChanged, this, &MainWindow::wirelessSwitchBtnChanged); connect(m_wlanWidget, &WlanPage::activateFailed, this, &MainWindow::activateFailed); connect(m_wlanWidget, &WlanPage::deactivateFailed, this, &MainWindow::deactivateFailed); @@ -363,6 +403,12 @@ void MainWindow::initDbusConnnect() QString("/"), QString("com.kylin.statusmanager.interface"), QString("mode_change_signal"), this, SLOT(onTabletModeChanged(bool))); + + connect(KWindowSystem::self(), &KWindowSystem::activeWindowChanged, this,[&](WId activeWindowId){ + if (activeWindowId != this->winId() && activeWindowId != 0) { + hideMainwindow(); + } + }); } /** @@ -380,7 +426,7 @@ void MainWindow::resetWindowPosition() return; } -#define MARGIN 4 +#define MARGIN 8 #define PANEL_TOP 1 #define PANEL_LEFT 2 #define PANEL_RIGHT 3 @@ -482,12 +528,12 @@ void MainWindow::resetWindowTheme() if(currentTheme == "ukui-dark" || currentTheme == "ukui-black"){ app->setStyle(new CustomStyle("ukui-dark")); qDebug() << "Has set color theme to ukui-dark." << Q_FUNC_INFO << __LINE__; - emit qApp->paletteChanged(qApp->palette()); + Q_EMIT qApp->paletteChanged(qApp->palette()); return; } app->setStyle(new CustomStyle("ukui-light")); qDebug() << "Has set color theme to " << currentTheme << Q_FUNC_INFO << __LINE__; - emit qApp->paletteChanged(qApp->palette()); + Q_EMIT qApp->paletteChanged(qApp->palette()); return; } @@ -514,11 +560,27 @@ void MainWindow::showByWaylandHelper() } +void MainWindow::setCentralWidgetType(IconActiveType iconStatus) +{ + if (iconStatus == WLAN_CONNECTED || iconStatus == WLAN_CONNECTED_LIMITED) { + m_centralWidget->setCurrentIndex(WLAN_PAGE_INDEX); + } else if (iconStatus == ACTIVATING) { + if (m_wlanWidget->checkWlanStatus(NetworkManager::ActiveConnection::State::Activating)) { + m_centralWidget->setCurrentIndex(WLAN_PAGE_INDEX); + } else { + m_centralWidget->setCurrentIndex(LAN_PAGE_INDEX); + } + } else { + m_centralWidget->setCurrentIndex(LAN_PAGE_INDEX); + } +} + /** * @brief MainWindow::onTrayIconActivated 点击托盘图标的槽函数 */ void MainWindow::onTrayIconActivated(QSystemTrayIcon::ActivationReason reason) { + setCentralWidgetType(iconStatus); if (reason == QSystemTrayIcon::ActivationReason::Context) { m_trayIconMenu->popup(QCursor::pos()); } else { @@ -548,7 +610,7 @@ void MainWindow::onThemeChanged(const QString &key) qDebug() << "Received signal of theme changed, will reset theme." << Q_FUNC_INFO << __LINE__; // resetWindowTheme(); paintWithTrans(); - emit qApp->paletteChanged(qApp->palette()); + Q_EMIT qApp->paletteChanged(qApp->palette()); } else { qDebug() << "Received signal of theme changed, key=" << key << " will do nothing." << Q_FUNC_INFO << __LINE__; } @@ -557,12 +619,14 @@ void MainWindow::onThemeChanged(const QString &key) void MainWindow::onRefreshTrayIcon() { //更新托盘图标显示 + int signalStrength = 0; iconTimer->stop(); if (m_lanWidget->lanIsConnected()) { m_trayIcon->setIcon(QIcon::fromTheme("network-wired-connected-symbolic")); iconStatus = IconActiveType::LAN_CONNECTED; } else if (m_wlanWidget->checkWlanStatus(NetworkManager::ActiveConnection::State::Activated)){ - m_trayIcon->setIcon(QIcon::fromTheme("network-wireless-connected-symbolic")); +// m_trayIcon->setIcon(QIcon::fromTheme("network-wireless-connected-symbolic")); + signalStrength = m_wlanWidget->getAcivateWifiSignal(); iconStatus = IconActiveType::WLAN_CONNECTED; } else { m_trayIcon->setIcon(QIcon::fromTheme("network-wired-disconnected-symbolic")); @@ -577,15 +641,42 @@ void MainWindow::onRefreshTrayIcon() iconStatus = IconActiveType::LAN_CONNECTED_LIMITED; } else if (iconStatus == IconActiveType::WLAN_CONNECTED) { //todo 信号强度 - m_trayIcon->setIcon(QIcon::fromTheme("network-wireless-signal-excellent-error-symbolic")); +// m_trayIcon->setIcon(QIcon::fromTheme("network-wireless-signal-excellent-error-symbolic")); iconStatus = IconActiveType::WLAN_CONNECTED_LIMITED; } } + + if (iconStatus == IconActiveType::WLAN_CONNECTED + || iconStatus == IconActiveType::WLAN_CONNECTED_LIMITED) { + if (signalStrength > MW_EXCELLENT_SIGNAL){ + m_trayIcon->setIcon(QIcon::fromTheme(EXCELLENT_SIGNAL_ICON)); + } else if (signalStrength > MW_GOOD_SIGNAL) { + m_trayIcon->setIcon(QIcon::fromTheme(GOOD_SIGNAL_ICON)); + } else if (signalStrength > MW_OK_SIGNAL) { + m_trayIcon->setIcon(QIcon::fromTheme(OK_SIGNAL_ICON)); + } else if (signalStrength > MW_LOW_SIGNAL) { + m_trayIcon->setIcon(QIcon::fromTheme(LOW_SIGNAL_ICON)); + } else { + m_trayIcon->setIcon(QIcon::fromTheme(NONE_SIGNAL_ICON)); + } + } else if (iconStatus == IconActiveType::WLAN_CONNECTED_LIMITED) { + if (signalStrength > MW_EXCELLENT_SIGNAL){ + m_trayIcon->setIcon(QIcon::fromTheme(EXCELLENT_SIGNAL_LIMIT_ICON)); + } else if (signalStrength > MW_GOOD_SIGNAL) { + m_trayIcon->setIcon(QIcon::fromTheme(GOOD_SIGNAL_LIMIT_ICON)); + } else if (signalStrength > MW_OK_SIGNAL) { + m_trayIcon->setIcon(QIcon::fromTheme(OK_SIGNAL_LIMIT_ICON)); + } else if (signalStrength > MW_LOW_SIGNAL) { + m_trayIcon->setIcon(QIcon::fromTheme(LOW_SIGNAL_LIMIT_ICON)); + } else { + m_trayIcon->setIcon(QIcon::fromTheme(NONE_SIGNAL_LIMIT_ICON)); + } + } } void MainWindow::onSetTrayIconLoading() { - if (currentIconIndex > 11) { + if (currentIconIndex > 7) { currentIconIndex = 0; } m_trayIcon->setIcon(loadIcons.at(currentIconIndex)); @@ -634,10 +725,16 @@ void MainWindow::onTabletModeChanged(bool mode) void MainWindow::onShowMainWindow(int type) { - m_centralWidget->setCurrentIndex(type); + if (type == LANPAGE || type == WLANPAGE) { + m_centralWidget->setCurrentIndex(type); - if(QApplication::activeWindow() != this) { - this->showMainwindow(); + if(QApplication::activeWindow() != this) { + this->showMainwindow(); + } + } else if (type == AUTOSELET) { + onTrayIconActivated(QSystemTrayIcon::ActivationReason::Trigger); + } else { + qWarning() << "unsupport parameter"; } } @@ -666,22 +763,6 @@ void MainWindow::keyPressEvent(QKeyEvent *event) return QWidget::keyPressEvent(event); } -/** - * @brief MainWindow::eventFilter 事件过滤器 - * @param watched - * @param event - * @return - */ -bool MainWindow::eventFilter(QObject *watched, QEvent *event) -{ - if (event->type() == QEvent::ActivationChange) { - if(QApplication::activeWindow() != this) { - hideMainwindow(); - } - } - return QMainWindow::eventFilter(watched,event); -} - /** * @brief MainWindow::getWirelessList 获取wifi列表,供dbus调用 * @param map @@ -694,6 +775,13 @@ void MainWindow::getWirelessList(QMap > &map) } } +bool MainWindow::getWirelessSwitchBtnState() +{ + if (nullptr != m_wlanWidget) { + return m_wlanWidget->getWirelessSwitchBtnState(); + } +} + /** * @brief MainWindow::getWiredList 获取lan列表,供dbus调用 * @param map @@ -740,6 +828,16 @@ void MainWindow::getStoredApInfo(QStringList &list) m_wlanWidget->getStoredApInfo(list); } +void MainWindow::getApConnectionPath(QString &path, QString uuid) +{ + m_wlanWidget->getApConnectionPath(path, uuid); +} + +void MainWindow::getActiveConnectionPath(QString &path, QString uuid) +{ + m_wlanWidget->getActiveConnectionPath(path, uuid); +} + //无线开关 void MainWindow::setWirelessSwitchEnable(bool enable) { @@ -787,6 +885,7 @@ void MainWindow::showCreateWiredConnectWidget(const QString devName) if (m_createPagePtrMap[devName] != nullptr) { qDebug() << "showCreateWiredConnectWidget" << devName << "already create,just raise"; + KWindowSystem::activateWindow(m_createPagePtrMap[devName]->winId()); KWindowSystem::raiseWindow(m_createPagePtrMap[devName]->winId()); return; } @@ -799,28 +898,13 @@ void MainWindow::showCreateWiredConnectWidget(const QString devName) }); m_createPagePtrMap.insert(devName, netDetail); netDetail->show(); + netDetail->centerToScreen(); } void MainWindow::showAddOtherWlanWidget(QString devName) { qDebug() << "showAddOtherWlanWidget! devName = " << devName; - if (m_addOtherPagePtrMap.contains(devName)) { - if (m_addOtherPagePtrMap[devName] != nullptr) { - qDebug() << "showAddOtherWlanWidget" << devName << "already create,just raise"; - - KWindowSystem::raiseWindow(m_addOtherPagePtrMap[devName]->winId()); - return; - } - } - NetDetail *netDetail = new NetDetail(devName, "", "", false, true, true, this); - connect(netDetail, &NetDetail::createPageClose, [&](QString interfaceName){ - if (m_addOtherPagePtrMap.contains(interfaceName)) { - m_addOtherPagePtrMap[interfaceName] = nullptr; - } - }); - m_addOtherPagePtrMap.insert(devName, netDetail); - netDetail->show(); - + m_wlanWidget->showAddOtherPage(devName); } void MainWindow::getWirelessDeviceCap(QMap &map) diff --git a/src/frontend/mainwindow.h b/src/frontend/mainwindow.h index 8917d3bf..d673fe6a 100644 --- a/src/frontend/mainwindow.h +++ b/src/frontend/mainwindow.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef MAINWINDOW_H #define MAINWINDOW_H @@ -14,6 +33,11 @@ #include "lanpage.h" #include "wlanpage.h" #include "netdetails/netdetail.h" +#include "netdetails/joinhiddenwifipage.h" +//安全中心-网络防火墙模式配置 +#include "networkmodeconfig.h" +//删除此头文件,别在添加 +//#include #ifdef WITHKYSEC #include @@ -54,6 +78,11 @@ public: //获取热点 void getStoredApInfo(QStringList &list); void getApInfoBySsid(QString devName, QString ssid, QStringList &list); + + //获取热点path + void getApConnectionPath(QString &path, QString uuid); + //获取热点ActivePath + void getActiveConnectionPath(QString &path, QString uuid); //删除有线连接 void deleteWired(const QString& connUuid); //有线连接断开 @@ -81,11 +110,14 @@ public: void keyRingInit(); void keyRingClear(); -signals: + bool getWirelessSwitchBtnState(); + +Q_SIGNALS: //设备插拔 void deviceStatusChanged(); //设备名称变化 void deviceNameChanged(QString oldName, QString newName, int type); + void wirelessSwitchBtnChanged(bool state); //有线无线列表更新(有线增删、无线增加减少) void lanAdd(QString devName, QStringList info); void lanRemove(QString dbusPath); @@ -98,7 +130,7 @@ signals: void deactivateFailed(QString errorMessage); //热点断开 void hotspotDeactivated(QString devName, QString ssid); - void hotspotActivated(QString devName, QString ssid, QString uuid); + void hotspotActivated(QString devName, QString ssid, QString uuid, QString activePath, QString settingPath); //信号强度变化 void signalStrengthChange(QString devName, QString ssid, int strength); //安全性变化 @@ -106,11 +138,11 @@ signals: void mainWindowVisibleChanged(const bool &visible); //列表排序 void timeToUpdate(); -public slots: + +public Q_SLOTS: protected: void keyPressEvent(QKeyEvent *event); - bool eventFilter(QObject *watched, QEvent *event) override; void paintEvent(QPaintEvent *event); private: @@ -131,6 +163,8 @@ private: void resetWindowTheme(); void showControlCenter(); void showByWaylandHelper(); + + void setCentralWidgetType(IconActiveType iconStatus); double m_transparency=1.0; //透明度 QGSettings * m_transGsettings; //透明度配置文件 int currentIconIndex=0; @@ -158,8 +192,6 @@ private: QMenu * m_trayIconMenu = nullptr; QAction * m_showMainwindowAction = nullptr; QAction * m_showSettingsAction = nullptr; - uint m_intervalTime = 100; - uint m_registerCount = 0; bool m_lanIsLoading = false; bool m_wlanIsLoading = false; @@ -169,12 +201,16 @@ private: IconActiveType iconStatus = IconActiveType::NOT_CONNECTED; QMap m_createPagePtrMap; - QMap m_addOtherPagePtrMap; -public slots: + NetworkMode *m_networkMode; + + uint m_intervalTime = 100; + uint m_registerCount = 0; + +public Q_SLOTS: void onShowMainWindow(int type); -private slots: +private Q_SLOTS: void onTransChanged(); void onTrayIconActivated(QSystemTrayIcon::ActivationReason reason); void onShowMainwindowActionTriggled(); diff --git a/src/frontend/netdetails/configpage.cpp b/src/frontend/netdetails/configpage.cpp new file mode 100644 index 00000000..ebb5fb94 --- /dev/null +++ b/src/frontend/netdetails/configpage.cpp @@ -0,0 +1,126 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#include "configpage.h" + +#include + +#define VERTICAL_SPACING 24 +#define KSC_FIREWALL_NOCONFIG -1 +#define KSC_FIREWALL_PUBLIC 0 +#define KSC_FIREWALL_PRIVATE 1 + +ConfigPage::ConfigPage(QWidget *parent) +{ + initUi(); + initComponent(); +} + +void ConfigPage::initUi() +{ + m_descriptionLabel = new QLabel(this); + m_publicButton = new QRadioButton(this); + m_privateButton = new QRadioButton(this); + m_publicLabel = new QLabel(this); + m_privateLabel = new QLabel(this); + m_congigBtn = new KBorderlessButton(this); + + QWidget *centerWidget = new QWidget(this); + QGridLayout *gridLayout = new QGridLayout(centerWidget); + gridLayout->setContentsMargins(0, 0, 0, 0); + gridLayout->setVerticalSpacing(VERTICAL_SPACING); + gridLayout->addWidget(m_publicButton, 0, 0, Qt::AlignTop); + gridLayout->addWidget(m_publicLabel, 0, 1); + gridLayout->addWidget(m_privateButton, 1, 0, Qt::AlignTop); + gridLayout->addWidget(m_privateLabel, 1, 1); + + m_vBoxLayout = new QVBoxLayout(this); + m_vBoxLayout->setContentsMargins(0, 0, 0, 0); + m_vBoxLayout->setSpacing(VERTICAL_SPACING); + m_vBoxLayout->addWidget(m_descriptionLabel); + m_vBoxLayout->addWidget(centerWidget); + m_vBoxLayout->addWidget(m_congigBtn); + m_vBoxLayout->addStretch(); + + //网络配置文件类型 + m_descriptionLabel->setText(tr("Network profile type")); + m_descriptionLabel->setAlignment(Qt::AlignLeft); + //公用(推荐) 网络中的设备不可发现此电脑。一般情况下适用于公共场所中的网络,如机场或咖啡店等等。 + m_publicLabel->setText(tr("Public(recommended) Devices on the network cannot discover this computer. Generally, " + "it is suitable for networks in public places, such as airports or coffee shops, etc.")); + m_publicLabel->setWordWrap(true); + //专用 网络中的设备可发现此电脑。一般情况下适用于家庭或工作单位的网络,您认识并信任网络上的个人和设备。 + m_privateLabel->setText(tr("Private Devices on the network can discover this computer. Generally applicable to a network " + "at home or work where you know and trust the individuals and devices on the network.")); + m_privateLabel->setWordWrap(true); + //配置防火墙和安全设置 + m_congigBtn->setText(tr("Config firewall and security settings")); + + QPalette btnPal; + QColor btnColor = palette().highlight().color(); + btnPal.setColor(QPalette::ButtonText, btnColor); + m_congigBtn->setPalette(btnPal); +} + +void ConfigPage::initComponent() +{ + connect(m_congigBtn, &KBorderlessButton::clicked, this, &ConfigPage::onConfigButtonClicked); +} + +void ConfigPage::setConfigState(int type) +{ + if (type == KSC_FIREWALL_PUBLIC) { + m_publicButton->setChecked(true); + + } else if (type == KSC_FIREWALL_PRIVATE) { + m_privateButton->setChecked(true); + } + +} + +bool ConfigPage::checkIsChanged(int type) +{ + if (type == KSC_FIREWALL_PUBLIC && m_publicButton->isChecked()) { + return false; + } else if (type == KSC_FIREWALL_PRIVATE && m_privateButton->isChecked()) { + return false; + } else { + return true; + } +} + +int ConfigPage::getConfigState() +{ + if (m_publicButton->isChecked()) { + return KSC_FIREWALL_PUBLIC; + } else if (m_privateButton->isChecked()) { + return KSC_FIREWALL_PRIVATE; + } + return KSC_FIREWALL_NOCONFIG; +} + + +void ConfigPage::onConfigButtonClicked() +{ + qDebug() << "show ksc defender net protect"; + + QProcess process; + process.startDetached("/usr/sbin/ksc-defender --net-protect"); + +} diff --git a/src/frontend/netdetails/configpage.h b/src/frontend/netdetails/configpage.h new file mode 100644 index 00000000..bc35baa2 --- /dev/null +++ b/src/frontend/netdetails/configpage.h @@ -0,0 +1,66 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#ifndef CONFIGPAGE_H +#define CONFIGPAGE_H + +#include +#include +#include +#include +#include +#include + +#include "kwidget.h" +#include "kborderlessbutton.h" + +using namespace kdk; + +class ConfigPage : public QFrame +{ + Q_OBJECT +public: + ConfigPage(QWidget *parent = nullptr); + ~ConfigPage() = default; + + void setConfigState(int type); + bool checkIsChanged(int type); + int getConfigState(); + +private: + void initUi(); + void initComponent(); + + QLabel *m_descriptionLabel = nullptr; + QRadioButton *m_publicButton = nullptr; + QRadioButton *m_privateButton = nullptr; + QLabel *m_publicLabel = nullptr; + QLabel *m_privateLabel = nullptr; + KBorderlessButton *m_congigBtn = nullptr; + QVBoxLayout *m_vBoxLayout = nullptr; + +private Q_SLOTS: + void onConfigButtonClicked(); + +Q_SIGNALS: + void publicConfig(); + void privateConfig(); +}; + +#endif // CONFIGPAGE_H diff --git a/src/frontend/netdetails/coninfo.h b/src/frontend/netdetails/coninfo.h index 0daad27c..330165e6 100644 --- a/src/frontend/netdetails/coninfo.h +++ b/src/frontend/netdetails/coninfo.h @@ -1,6 +1,26 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef CONINFO_H #define CONINFO_H +#include #include #include #include @@ -84,16 +104,12 @@ public: KyIpConfigType ipv4ConfigType = CONFIG_IP_DHCP; QString strIPV4Address; QString strIPV4NetMask; -// QString strIPV4FirDns; -// QString strIPV4SecDns; QString strIPV4GateWay; QList ipv4DnsList; KyIpConfigType ipv6ConfigType = CONFIG_IP_DHCP; QString strIPV6Address; int iIPV6Prefix; -// QString strIPV6FirDns; -// QString strIPV6SecDns; QString strIPV6GateWay; QList ipv6DnsList; @@ -123,11 +139,12 @@ static void setFramePalette(QFrame *widget, QPalette &pal) { static QPalette lightPalette(QWidget *widget) { - auto palette = widget->palette(); - //ukui-light palette UKUI3.1 + QPalette palette = qApp->palette(); + + //ukui-light palette UKUI3.1 亮主题色板 QColor windowText_at(38, 38, 38), - windowText_iat(38, 38, 38), - windowText_dis(166, 166, 166), + windowText_iat(0, 0, 0, 255 * 0.55), + windowText_dis(0, 0, 0, 255 * 0.3), button_at(230, 230, 230), button_iat(230, 230, 230), button_dis(233, 233, 233), @@ -145,10 +162,10 @@ static QPalette lightPalette(QWidget *widget) mid_dis(102, 102, 102), text_at(38, 38, 38), text_iat(38, 38, 38), - text_dis(140, 140, 140), - brightText_at(89, 89, 89), - brightText_iat(89, 89, 89), - brightText_dis(77, 77, 77), + text_dis(0, 0, 0, 255 * 0.3), + brightText_at(0, 0, 0), + brightText_iat(0, 0, 0), + brightText_dis(0, 0, 0), buttonText_at(38, 38, 38), buttonText_iat(38, 38, 38), buttonText_dis(179, 179, 179), @@ -158,24 +175,12 @@ static QPalette lightPalette(QWidget *widget) window_at(245, 245, 245), window_iat(237, 237, 237), window_dis(230, 230, 230), - shadow_at(0, 0, 0, 16), - shadow_iat(0, 0, 0, 16), - shadow_dis(0, 0, 0, 21), -// shadow_at(214, 214, 214), -// shadow_iat(214, 214, 214), -// shadow_dis(201, 201, 201), - highLight_at(55, 144, 250), - highLight_iat(55, 144, 250), - highLight_dis(233, 233, 233), + shadow_at(0, 0, 0, 255 * 0.16), + shadow_iat(0, 0, 0, 255 * 0.16), + shadow_dis(0, 0, 0, 255 * 0.21), highLightText_at(255, 255, 255), highLightText_iat(255, 255, 255), highLightText_dis(179, 179, 179), - link_at(55, 144, 250), - link_iat(55, 144, 250), - link_dis(55, 144, 250), - linkVisited_at(114, 46, 209), - linkVisited_iat(114, 46, 209), - linkVisited_dis(114, 46, 209), alternateBase_at(245, 245, 245), alternateBase_iat(245, 245, 245), alternateBase_dis(245, 245, 245), @@ -188,11 +193,9 @@ static QPalette lightPalette(QWidget *widget) toolTipText_at(38, 38, 38), toolTipText_iat(38, 38, 38), toolTipText_dis(38, 38, 38), - placeholderText_at(38, 38, 38), - placeholderText_iat(38, 38, 38), - placeholderText_dis(38, 38, 38); - - + placeholderText_at(0, 0, 0, 255 * 0.35), + placeholderText_iat(0, 0, 0, 255 * 0.35), + placeholderText_dis(0, 0, 0, 255 * 0.3); palette.setColor(QPalette::Active, QPalette::WindowText, windowText_at); palette.setColor(QPalette::Inactive, QPalette::WindowText, windowText_iat); @@ -242,22 +245,10 @@ static QPalette lightPalette(QWidget *widget) palette.setColor(QPalette::Inactive, QPalette::Shadow, shadow_iat); palette.setColor(QPalette::Disabled, QPalette::Shadow, shadow_dis); - palette.setColor(QPalette::Active, QPalette::Highlight, highLight_at); - palette.setColor(QPalette::Inactive, QPalette::Highlight, highLight_iat); - palette.setColor(QPalette::Disabled, QPalette::Highlight, highLight_dis); - palette.setColor(QPalette::Active, QPalette::HighlightedText, highLightText_at); palette.setColor(QPalette::Inactive, QPalette::HighlightedText, highLightText_iat); palette.setColor(QPalette::Disabled, QPalette::HighlightedText, highLightText_dis); - palette.setColor(QPalette::Active, QPalette::Link, link_at); - palette.setColor(QPalette::Inactive, QPalette::Link, link_iat); - palette.setColor(QPalette::Disabled, QPalette::Link, link_dis); - - palette.setColor(QPalette::Active, QPalette::LinkVisited, linkVisited_at); - palette.setColor(QPalette::Inactive, QPalette::LinkVisited, linkVisited_iat); - palette.setColor(QPalette::Disabled, QPalette::LinkVisited, linkVisited_dis); - palette.setColor(QPalette::Active, QPalette::AlternateBase, alternateBase_at); palette.setColor(QPalette::Inactive, QPalette::AlternateBase, alternateBase_iat); palette.setColor(QPalette::Disabled, QPalette::AlternateBase, alternateBase_dis); diff --git a/src/frontend/netdetails/creatnetpage.cpp b/src/frontend/netdetails/creatnetpage.cpp index f8bbb0df..a526e88a 100644 --- a/src/frontend/netdetails/creatnetpage.cpp +++ b/src/frontend/netdetails/creatnetpage.cpp @@ -1,7 +1,28 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "creatnetpage.h" #include "math.h" #define MAX_NAME_LENGTH 32 +#define HINT_TEXT_MARGINS 8, 1, 0, 3 +#define LABEL_HEIGHT 24 CreatNetPage::CreatNetPage(QWidget *parent):QFrame(parent) { @@ -24,24 +45,60 @@ void CreatNetPage::initUI() m_maskLabel = new QLabel(this); m_gateWayLabel = new QLabel(this); - m_connNameLabel->setText(tr("Connection Name")); - m_configLabel->setText(tr("Ipv4Config")); - m_addressLabel->setText(tr("Address")); - m_maskLabel->setText(tr("Netmask")); - m_gateWayLabel->setText(tr("Default Gateway")); - // IP的正则格式限制 QRegExp rx("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"); m_dnsWidget = new MultipleDnsWidget(rx, this); + QLabel *nameEmptyLabel = new QLabel(this); + QLabel *configEmptyLabel = new QLabel(this); + QLabel *gateWayEmptyLabel = new QLabel(this); + nameEmptyLabel->setFixedHeight(LABEL_HEIGHT); + configEmptyLabel->setFixedHeight(LABEL_HEIGHT); + gateWayEmptyLabel->setFixedHeight(LABEL_HEIGHT); + + m_addressHintLabel = new QLabel(this); + m_maskHintLabel = new QLabel(this); + m_addressHintLabel->setFixedHeight(LABEL_HEIGHT); + m_maskHintLabel->setFixedHeight(LABEL_HEIGHT); + m_addressHintLabel->setContentsMargins(HINT_TEXT_MARGINS); + m_maskHintLabel->setContentsMargins(HINT_TEXT_MARGINS); + + QPalette hintTextColor; + hintTextColor.setColor(QPalette::WindowText, Qt::red); + m_addressHintLabel->setPalette(hintTextColor); + m_maskHintLabel->setPalette(hintTextColor); + + QWidget *addressWidget = new QWidget(this); + QVBoxLayout *addressLayout = new QVBoxLayout(addressWidget); + addressLayout->setContentsMargins(0, 0, 0, 0); + addressLayout->setSpacing(0); + addressLayout->addWidget(ipv4addressEdit); + addressLayout->addWidget(m_addressHintLabel); + + QWidget *maskWidget = new QWidget(this); + QVBoxLayout *maskLayout = new QVBoxLayout(maskWidget); + maskLayout->setContentsMargins(0, 0, 0, 0); + maskLayout->setSpacing(0); + maskLayout->addWidget(netMaskEdit); + maskLayout->addWidget(m_maskHintLabel); + + m_connNameLabel->setText(tr("Connection Name")); + m_configLabel->setText(tr("IPv4Config")); + m_addressLabel->setText(tr("Address")); + m_maskLabel->setText(tr("Netmask")); + m_gateWayLabel->setText(tr("Default Gateway")); + m_detailLayout = new QFormLayout(this); + m_detailLayout->setVerticalSpacing(0); m_detailLayout->setContentsMargins(0, 0, 0, 0); - m_detailLayout->setSpacing(24); m_detailLayout->addRow(m_connNameLabel,connNameEdit); + m_detailLayout->addRow(nameEmptyLabel); m_detailLayout->addRow(m_configLabel,ipv4ConfigCombox); - m_detailLayout->addRow(m_addressLabel,ipv4addressEdit); - m_detailLayout->addRow(m_maskLabel,netMaskEdit); + m_detailLayout->addRow(configEmptyLabel); + m_detailLayout->addRow(m_addressLabel, addressWidget); + m_detailLayout->addRow(m_maskLabel, maskWidget); m_detailLayout->addRow(m_gateWayLabel,gateWayEdit); + m_detailLayout->addRow(gateWayEmptyLabel); m_detailLayout->addRow(m_dnsWidget); ipv4ConfigCombox->addItem(tr("Auto(DHCP)"), AUTO_CONFIG); //"自动(DHCP)" @@ -64,6 +121,9 @@ void CreatNetPage::initComponent() { connect(ipv4ConfigCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(setEnableOfSaveBtn())); connect(netMaskEdit, SIGNAL(textChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(gateWayEdit, SIGNAL(textChanged(QString)), this, SLOT(setEnableOfSaveBtn())); + + connect(ipv4addressEdit, SIGNAL(textChanged(QString)), this, SLOT(onAddressTextChanged())); + connect(netMaskEdit, SIGNAL(textChanged(QString)), this, SLOT(onNetMaskTextChanged())); } bool CreatNetPage::checkConnectBtnIsEnabled() @@ -85,27 +145,6 @@ bool CreatNetPage::checkConnectBtnIsEnabled() qDebug() << "create ipv4 netMask empty or invalid"; return false; } - - if (gateWayEdit->text().isEmpty() || !getTextEditState(gateWayEdit->text())) { - qDebug() << "create ipv4 gateway empty or invalid"; - return false; - } -#if 0 - if (firstDnsEdit->text().isEmpty() && !secondDnsEdit->text().isEmpty()) { - qDebug() << "create ipv4 dns sort invalid"; - return false; - } - - if (!getTextEditState(firstDnsEdit->text())) { - qDebug() << "create ipv4 first dns invalid"; - return false; - } - - if (!getTextEditState(secondDnsEdit->text())) { - qDebug() << "create ipv4 second dns invalid"; - return false; - } -#endif } return true; } @@ -119,6 +158,24 @@ void CreatNetPage::configChanged(int index) { } } +void CreatNetPage::onAddressTextChanged() +{ + if (!getTextEditState(ipv4addressEdit->text())) { + m_addressHintLabel->setText(tr("Invalid address")); + } else { + m_addressHintLabel->clear(); + } +} + +void CreatNetPage::onNetMaskTextChanged() +{ + if (!netMaskIsValide(netMaskEdit->text())) { + m_maskHintLabel->setText(tr("Invalid subnet mask")); + } else { + m_maskHintLabel->clear(); + } +} + void CreatNetPage::setLineEnabled(bool check) { ipv4addressEdit->setEnabled(check); @@ -139,7 +196,7 @@ void CreatNetPage::setLineEnabled(bool check) { } void CreatNetPage::setEnableOfSaveBtn() { - emit setCreatePageState(checkConnectBtnIsEnabled()); + Q_EMIT setCreatePageState(checkConnectBtnIsEnabled()); } bool CreatNetPage::getTextEditState(QString text) @@ -169,9 +226,13 @@ void CreatNetPage::constructIpv4Info(KyConnectSetting &setting) ipv4dnsList.clear(); ipv4dnsList = m_dnsWidget->getDns(); - setting.setIpConfigType(IPADDRESS_V4, CONFIG_IP_DHCP); - setting.ipv4AddressConstruct(ipv4address, netMask, gateWay); - setting.ipv4DnsConstruct(ipv4dnsList); + if (ipv4ConfigCombox->currentData() == AUTO_CONFIG) { + setting.setIpConfigType(IPADDRESS_V4, CONFIG_IP_DHCP); + } else { + setting.setIpConfigType(IPADDRESS_V4, CONFIG_IP_MANUAL); + setting.ipv4AddressConstruct(ipv4address, netMask, gateWay); + setting.ipv4DnsConstruct(ipv4dnsList); + } } bool CreatNetPage::netMaskIsValide(QString text) diff --git a/src/frontend/netdetails/creatnetpage.h b/src/frontend/netdetails/creatnetpage.h index 5152535f..1eb2934f 100644 --- a/src/frontend/netdetails/creatnetpage.h +++ b/src/frontend/netdetails/creatnetpage.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef CREATNETPAGE_H #define CREATNETPAGE_H @@ -28,9 +47,10 @@ private: LineEdit *ipv4addressEdit; LineEdit *netMaskEdit; LineEdit *gateWayEdit; -// LineEdit *firstDnsEdit; -// LineEdit *secondDnsEdit; + LineEdit *firstDnsEdit; + LineEdit *secondDnsEdit; +private: QFormLayout *m_detailLayout; QVBoxLayout *mvBoxLayout; QLabel *m_connNameLabel; @@ -38,8 +58,10 @@ private: QLabel *m_addressLabel; QLabel *m_maskLabel; QLabel *m_gateWayLabel; -// QLabel *m_dnsLabel; -// QLabel *m_secDnsLabel; + + QLabel *m_addressHintLabel; + QLabel *m_maskHintLabel; + MultipleDnsWidget *m_dnsWidget = nullptr; private: void initUI(); @@ -52,9 +74,12 @@ private: bool netMaskIsValide(QString text); QString getNetMaskText(QString text); -private slots: +private Q_SLOTS: void setEnableOfSaveBtn(); void configChanged(int index); + void onAddressTextChanged(); + void onNetMaskTextChanged(); + Q_SIGNALS: void setCreatePageState(bool); diff --git a/src/frontend/netdetails/customtabstyle.cpp b/src/frontend/netdetails/customtabstyle.cpp index c8683cc8..23e0745d 100644 --- a/src/frontend/netdetails/customtabstyle.cpp +++ b/src/frontend/netdetails/customtabstyle.cpp @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "customtabstyle.h" diff --git a/src/frontend/netdetails/customtabstyle.h b/src/frontend/netdetails/customtabstyle.h index 75a09825..005ddef0 100644 --- a/src/frontend/netdetails/customtabstyle.h +++ b/src/frontend/netdetails/customtabstyle.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef CUSTOMTABSTYLE_H #define CUSTOMTABSTYLE_H diff --git a/src/frontend/netdetails/detailpage.cpp b/src/frontend/netdetails/detailpage.cpp index 0a9c4c9d..a80cc0e8 100644 --- a/src/frontend/netdetails/detailpage.cpp +++ b/src/frontend/netdetails/detailpage.cpp @@ -1,16 +1,36 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "detailpage.h" #include #include #define MAX_NAME_LENGTH 32 #define MAX_LABEL_WIDTH 250 +#define MAX_SSID_WIDTH 133 extern void qt_blurImage(QImage &blurImage, qreal radius, bool quality, int transposed); DetailPage::DetailPage(bool isWlan, bool isCreate, QWidget *parent) : m_IsWlan(isWlan), m_IsCreate(isCreate), QFrame(parent) { - this->setFrameShape(QFrame::Shape::StyledPanel); +// this->setFrameShape(QFrame::Shape::StyledPanel); this->setMaximumWidth(960); initUI(); if (isCreate) { @@ -31,10 +51,10 @@ void DetailPage::setSSID(const QString &ssid) { return; } m_formerSSID = ssid; - QFontMetrics fontMetrics(this->font()); + QFontMetrics fontMetrics(m_SSIDLabel->font()); int fontSize = fontMetrics.width(ssid); - if (fontSize > this->width()) { - this->m_SSIDLabel->setText(fontMetrics.elidedText(ssid, Qt::ElideRight, this->width())); + if (fontSize > MAX_SSID_WIDTH) { + this->m_SSIDLabel->setText(fontMetrics.elidedText(ssid, Qt::ElideRight, MAX_SSID_WIDTH)); this->setToolTip(ssid); } else { this->m_SSIDLabel->setText(ssid); @@ -67,12 +87,12 @@ void DetailPage::setIpv4(const QString &ipv4) { } void DetailPage::setIpv4Dns(const QString &ipv4Dns) { - this->m_IPV4Dns->setText(ipv4Dns); + this->m_IPV4Dns->setLabelText(ipv4Dns); } void DetailPage::setIpv6(const QString &ipv6) { m_formerIPV6 = ipv6; - this->m_IPV6->setText(ipv6); + this->m_IPV6->setLabelText(ipv6); } void DetailPage::setMac(const QString &mac) { @@ -122,7 +142,7 @@ void DetailPage::newCopiedTip() //设置“复制成功”消息弹窗格式 m_copiedTip = new KBallonTip(); m_copiedTip->setTipType(Normal); - m_copiedTip->setContentsMargins(16, 0, 16, 0); + m_copiedTip->setContentsMargins(16, 14, 16, 14); m_copiedTip->setFixedHeight(48); m_copiedTip->setWindowFlags(Qt::FramelessWindowHint); m_copiedTip->setAttribute(Qt::WA_TranslucentBackground, true); @@ -133,27 +153,29 @@ QPalette DetailPage::getTheme() { //获取当前主题的颜色 QPalette pal = qApp->palette(); - QGSettings * styleGsettings = nullptr; - const QByteArray style_id(THEME_SCHAME); - if (QGSettings::isSchemaInstalled(style_id)) { - styleGsettings = new QGSettings(style_id); - QString currentTheme = styleGsettings->get(COLOR_THEME).toString(); - if(currentTheme == "ukui-default"){ - pal = lightPalette(this); - } - } - if (styleGsettings != nullptr) { - delete styleGsettings; - styleGsettings = nullptr; - } +// QGSettings * styleGsettings = nullptr; +// const QByteArray style_id(THEME_SCHAME); +// if (QGSettings::isSchemaInstalled(style_id)) { +// styleGsettings = new QGSettings(style_id); +// QString currentTheme = styleGsettings->get(COLOR_THEME).toString(); +// if(currentTheme == "ukui-default"){ +// pal = lightPalette(this); +// } +// } +// if (styleGsettings != nullptr) { +// delete styleGsettings; +// styleGsettings = nullptr; +// } return pal; } void DetailPage::initUI() { m_layout = new QVBoxLayout(this); m_layout->setContentsMargins(0,0,0,0); + m_layout->setSpacing(0); QWidget *mDetailFrame = new QFrame(this); + mDetailFrame->setFixedHeight(362); m_DetailLayout = new QVBoxLayout(mDetailFrame); m_DetailLayout->setContentsMargins(0,0,0,0); @@ -163,6 +185,8 @@ void DetailPage::initUI() { m_listWidget->setFocusPolicy(Qt::FocusPolicy::NoFocus); m_DetailLayout->addWidget(m_listWidget); + m_listWidget->setFrameShape(QFrame::Shape::StyledPanel); + if (!m_IsCreate) { m_SSIDLabel = new QLabel(this); m_SSIDLabel->adjustSize(); @@ -220,19 +244,19 @@ void DetailPage::initUI() { m_IPV4 = new QLabel(this); m_ipv4Widget = new DetailWidget(qobject_cast(m_IPV4), m_listWidget); - m_ipv4Widget->setKey(tr("IPV4:")); + m_ipv4Widget->setKey(tr("IPv4:")); m_IPV4Dns = new FixLabel(this); m_IPV4Dns->setFixedWidth(MAX_LABEL_WIDTH); m_IPV4Dns->setAlignment(Qt::AlignRight | Qt::AlignVCenter); m_ipv4DnsWidget = new DetailWidget(qobject_cast(m_IPV4Dns), m_listWidget); - m_ipv4DnsWidget->setKey(tr("IPV4 Dns:")); + m_ipv4DnsWidget->setKey(tr("IPv4 DNS:")); m_IPV6 = new FixLabel(this); m_IPV6->setFixedWidth(MAX_LABEL_WIDTH); m_IPV6->setAlignment(Qt::AlignRight | Qt::AlignVCenter); m_ipv6Widget = new DetailWidget(qobject_cast(m_IPV6), m_listWidget); - m_ipv6Widget->setKey(tr("IPV6:")); + m_ipv6Widget->setKey(tr("IPv6:")); m_Mac = new QLabel(this); m_macWidget = new DetailWidget(qobject_cast(m_Mac), m_listWidget); @@ -243,7 +267,9 @@ void DetailPage::initUI() { m_forgetNetBox = new QCheckBox(this); m_autoConnect->setText(tr("Auto Connection")); - m_AutoLayout = new QHBoxLayout(this); + + m_autoConWidget = new QWidget(this); + m_AutoLayout = new QHBoxLayout(m_autoConWidget); QSpacerItem *horizontalSpacer; horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); @@ -275,8 +301,10 @@ void DetailPage::initUI() { m_layout->addWidget(mDetailFrame); if (m_IsWlan) { - m_layout->addLayout(m_AutoLayout); +// m_layout->addLayout(m_AutoLayout); + m_layout->addWidget(m_autoConWidget); } + m_layout->addStretch(); } void DetailPage::setEnableOfSaveBtn() { @@ -284,7 +312,7 @@ void DetailPage::setEnableOfSaveBtn() { if (m_IsCreate) { saveEnable = !m_SSIDEdit->text().isEmpty(); } - emit setDetailPageState(saveEnable); + Q_EMIT setDetailPageState(saveEnable); } //获取列表信息 @@ -297,9 +325,9 @@ void DetailPage::on_btnCopyNetDetail_clicked() QString hzCopy= tr ("Hz:"); QString chanCopy= tr ("Chan:"); QString bandwithCopy = tr("BandWidth:"); - QString ipv4Copy = tr("IPV4:"); - QString ipv4dnsCopy = tr("IPV4 Dns:"); - QString ipv6Copy = tr("IPV6:"); + QString ipv4Copy = tr("IPv4:"); + QString ipv4dnsCopy = tr("IPv4 DNS:"); + QString ipv6Copy = tr("IPv6:"); QString macCopy = tr("Mac:"); QString netDetailCopyText; diff --git a/src/frontend/netdetails/detailpage.h b/src/frontend/netdetails/detailpage.h index 913e3138..208b15d1 100644 --- a/src/frontend/netdetails/detailpage.h +++ b/src/frontend/netdetails/detailpage.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef DETAILPAGE_H #define DETAILPAGE_H #include @@ -72,7 +91,7 @@ public: QLabel *m_Chan; QLabel *m_BandWidth; QLabel *m_IPV4; - FixLabel *m_IPV4Dns; + FixLabel *m_IPV4Dns; FixLabel *m_IPV6; QLabel *m_Mac; QLabel *m_autoConnect; @@ -87,14 +106,16 @@ private: bool m_IsWlan; bool m_IsCreate; + QWidget *m_autoConWidget; + QString m_formerSSID; QString m_formerIPV6; -private slots: +private Q_SLOTS: void setEnableOfSaveBtn(); void on_btnCopyNetDetail_clicked(); -signals: +Q_SIGNALS: void setDetailPageState(bool); }; diff --git a/src/frontend/netdetails/detailwidget.cpp b/src/frontend/netdetails/detailwidget.cpp index 0b4f4584..8a02c59a 100644 --- a/src/frontend/netdetails/detailwidget.cpp +++ b/src/frontend/netdetails/detailwidget.cpp @@ -1,44 +1,30 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "detailwidget.h" -#include #include #define ITEM_HEIGHT 36 #define ITEM_MARGINS 18,0,16,0 - -#define MAX_LABEL_WIDTH 138 - -FixLabel::FixLabel(QWidget *parent): - QLabel(parent) -{ - -} - -FixLabel::~FixLabel() -{ - -} - -void FixLabel::paintEvent(QPaintEvent *event) -{ - QFontMetrics fontMetrics(this->font()); - int fontSize = fontMetrics.width(mStr); - if (fontSize > this->width()) { - this->setText(fontMetrics.elidedText(mStr, Qt::ElideRight, this->width()), false); - this->setToolTip(mStr); - } else { - this->setText(mStr, false); - this->setToolTip(""); - } - QLabel::paintEvent(event); -} - -void FixLabel::setText(const QString & text, bool saveTextFlag) -{ - if (saveTextFlag) { - mStr = text; - } - QLabel::setText(text); -} +#define MIN_LABEL_WIDTH 146 +#define MAX_LABEL_WIDTH 154 +#define MAX_WIDGET_WIDTH 270 DetailWidget::DetailWidget(QWidget *valueWidget, QWidget *parent, QWidget *buttonWidget) : m_valueWidget(valueWidget) , QWidget(parent) , m_copyButton(buttonWidget) @@ -59,6 +45,7 @@ void DetailWidget::initUI() m_mainLayout->setContentsMargins(ITEM_MARGINS); m_keyLabel = new FixLabel(this); + m_keyLabel->setMinimumWidth(MIN_LABEL_WIDTH); m_keyLabel->setMaximumWidth(MAX_LABEL_WIDTH); m_keyLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); @@ -70,13 +57,10 @@ void DetailWidget::initUI() m_mainLayout->addWidget(m_copyButton); } m_mainLayout->addWidget(m_valueWidget); - m_valueWidget->setMaximumWidth(100000000000); + m_valueWidget->setMaximumWidth(MAX_WIDGET_WIDTH); } void DetailWidget::setKey(const QString &keyLabel) { - m_keyLabel->setText(keyLabel); + m_keyLabel->setLabelText(keyLabel); } - - - diff --git a/src/frontend/netdetails/detailwidget.h b/src/frontend/netdetails/detailwidget.h index c97ac877..096d779e 100644 --- a/src/frontend/netdetails/detailwidget.h +++ b/src/frontend/netdetails/detailwidget.h @@ -1,25 +1,29 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef DetailWidget_H #define DetailWidget_H #include #include #include - -//文本长自动省略并添加悬浮 -class FixLabel : public QLabel -{ - - Q_OBJECT -public: - FixLabel(QWidget *parent = nullptr); - ~FixLabel(); - void setText(const QString &text, bool saveTextFlag = true); -private: - void paintEvent(QPaintEvent *event); - -private: - QString mStr; -}; +#include "kylable.h" class DetailWidget : public QWidget { @@ -37,9 +41,6 @@ private: QWidget *m_copyButton; void initUI(); - -signals: - }; #endif // DetailWidget_H diff --git a/src/frontend/netdetails/ipv4page.cpp b/src/frontend/netdetails/ipv4page.cpp index 39d38847..77b88f0f 100644 --- a/src/frontend/netdetails/ipv4page.cpp +++ b/src/frontend/netdetails/ipv4page.cpp @@ -1,7 +1,33 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "ipv4page.h" #include "netdetail.h" #include "math.h" +#define LAYOUT_MARGINS 0,0,0,0 +#define LAYOUT_SPACING 0 +#define HINT_TEXT_MARGINS 8, 1, 0, 3 +#define LABEL_HEIGHT 24 +#define FRAME_SPEED 150 +#define ICON_SIZE 16,16 + Ipv4Page::Ipv4Page(QWidget *parent):QFrame(parent) { initUI(); @@ -13,34 +39,70 @@ void Ipv4Page::initUI() { ipv4addressEdit = new LineEdit(this); netMaskEdit = new LineEdit(this); gateWayEdit = new LineEdit(this); -// firstDnsEdit = new LineEdit(this); -// secondDnsEdit = new LineEdit(this); m_configLabel = new QLabel(this); m_addressLabel = new QLabel(this); m_maskLabel = new QLabel(this); m_gateWayLabel = new QLabel(this); -// m_dnsLabel = new QLabel(this); -// m_secDnsLabel = new QLabel(this); - m_configLabel->setText(tr("Ipv4Config")); + m_configEmptyLabel = new QLabel(this); + m_configEmptyLabel->setFixedHeight(LABEL_HEIGHT); + + m_addressHintLabel = new QLabel(this); + m_addressHintLabel->setFixedHeight(LABEL_HEIGHT); + m_addressHintLabel->setContentsMargins(HINT_TEXT_MARGINS); + initConflictHintLable(); + + m_maskHintLabel = new QLabel(this); + m_maskHintLabel->setFixedHeight(LABEL_HEIGHT); + m_maskHintLabel->setContentsMargins(HINT_TEXT_MARGINS); + + m_gateWayEmptyLabel = new QLabel(this); + m_gateWayEmptyLabel->setFixedHeight(LABEL_HEIGHT); + + m_configLabel->setText(tr("IPv4Config")); m_addressLabel->setText(tr("Address")); m_maskLabel->setText(tr("Netmask")); m_gateWayLabel->setText(tr("Default Gateway")); -// m_dnsLabel->setText(tr("Prefs DNS")); -// m_secDnsLabel->setText(tr("Alternative DNS")); + + m_statusLabel = new QLabel(this); + m_statusLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); + QHBoxLayout *pPwdLayout = new QHBoxLayout(ipv4addressEdit); + pPwdLayout->addStretch(); + pPwdLayout->addWidget(m_statusLabel); + + QPalette hintTextColor; + hintTextColor.setColor(QPalette::WindowText, Qt::red); + m_addressHintLabel->setPalette(hintTextColor); + m_maskHintLabel->setPalette(hintTextColor); + + QWidget *addressWidget = new QWidget(this); + QVBoxLayout *addressLayout = new QVBoxLayout(addressWidget); + addressLayout->setContentsMargins(LAYOUT_MARGINS); + addressLayout->setSpacing(LAYOUT_SPACING); + addressLayout->addWidget(ipv4addressEdit); + addressLayout->addWidget(m_addressHintLabel); + + QWidget *maskWidget = new QWidget(this); + QVBoxLayout *maskLayout = new QVBoxLayout(maskWidget); + maskLayout->setContentsMargins(LAYOUT_MARGINS); + maskLayout->setSpacing(LAYOUT_SPACING); + maskLayout->addWidget(netMaskEdit); + maskLayout->addWidget(m_maskHintLabel); // IP的正则格式限制 QRegExp rx("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"); m_dnsWidget = new MultipleDnsWidget(rx, this); m_detailLayout = new QFormLayout(this); + m_detailLayout->setVerticalSpacing(0); + m_detailLayout->setContentsMargins(LAYOUT_MARGINS); m_detailLayout->addRow(m_configLabel,ipv4ConfigCombox); - m_detailLayout->addRow(m_addressLabel,ipv4addressEdit); - m_detailLayout->addRow(m_maskLabel,netMaskEdit); + m_detailLayout->addRow(m_configEmptyLabel); + m_detailLayout->addRow(m_addressLabel,addressWidget); + m_detailLayout->addRow(m_maskLabel,maskWidget); m_detailLayout->addRow(m_gateWayLabel,gateWayEdit); -// m_detailLayout->addRow(m_dnsLabel,firstDnsEdit); -// m_detailLayout->addRow(m_secDnsLabel,secondDnsEdit); + m_detailLayout->addRow(m_gateWayEmptyLabel); m_detailLayout->addRow(m_dnsWidget); ipv4ConfigCombox->addItem(tr("Auto(DHCP)")); //"自动(DHCP)" @@ -56,8 +118,8 @@ void Ipv4Page::initUI() { ipv4addressEdit->setValidator(new QRegExpValidator(rx, this)); gateWayEdit->setValidator(new QRegExpValidator(rx, this)); netMaskEdit->setValidator(new QRegExpValidator(rx, this)); -// firstDnsEdit->setValidator(new QRegExpValidator(rx, this)); -// secondDnsEdit->setValidator(new QRegExpValidator(rx, this)); + + initLoadingIcon(); } void Ipv4Page::initComponent() { @@ -68,6 +130,9 @@ void Ipv4Page::initComponent() { } connect(ipv4ConfigCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(configChanged(int))); + connect(ipv4addressEdit, SIGNAL(textChanged(QString)), this, SLOT(onAddressTextChanged())); + connect(ipv4addressEdit, SIGNAL(editingFinished()), this, SLOT(onAddressEidtFinished())); + connect(netMaskEdit, SIGNAL(textChanged(QString)), this, SLOT(onNetMaskTextChanged())); connect(ipv4ConfigCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(setEnableOfSaveBtn())); connect(ipv4addressEdit, SIGNAL(textChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(netMaskEdit, SIGNAL(textChanged(QString)), this, SLOT(setEnableOfSaveBtn())); @@ -97,17 +162,7 @@ void Ipv4Page::setMulDns(const QList &dns) { m_dnsWidget->setDnsListText(dns); } -#if 0 -void Ipv4Page::setIpv4FirDns(const QString &ipv4FirDns) -{ - firstDnsEdit->setText(ipv4FirDns); -} -void Ipv4Page::setIpv4SecDns(const QString &ipv4SecDns) -{ - secondDnsEdit->setText(ipv4SecDns); -} -#endif void Ipv4Page::setGateWay(const QString &gateWay) { gateWayEdit->setText(gateWay); @@ -116,6 +171,7 @@ void Ipv4Page::setGateWay(const QString &gateWay) bool Ipv4Page::checkIsChanged(const ConInfo info, KyConnectSetting &setting) { bool isChanged = false; + QList ipv4DnsList; ipv4DnsList.clear(); ipv4DnsList = m_dnsWidget->getDns(); @@ -132,6 +188,7 @@ bool Ipv4Page::checkIsChanged(const ConInfo info, KyConnectSetting &setting) QString ipv4address(""); QString netMask(""); QString gateWay(""); + qDebug() << ipv4address << netMask << gateWay; setting.ipv4AddressConstruct(ipv4address, netMask, gateWay); isChanged = true; @@ -177,27 +234,6 @@ bool Ipv4Page::checkConnectBtnIsEnabled() qDebug() << "ipv4 netMask empty or invalid"; return false; } - -// if (gateWayEdit->text().isEmpty() || !getTextEditState(gateWayEdit->text())) { -// qDebug() << "ipv4 gateway empty or invalid"; -// return false; -// } -#if 0 - if (firstDnsEdit->text().isEmpty() && !secondDnsEdit->text().isEmpty()) { - qDebug() << "ipv4 dns sort invalid"; - return false; - } - - if (!getTextEditState(firstDnsEdit->text())) { - qDebug() << "ipv4 first dns invalid"; - return false; - } - - if (!getTextEditState(secondDnsEdit->text())) { - qDebug() << "ipv4 second dns invalid"; - return false; - } -#endif } return true; } @@ -211,21 +247,57 @@ void Ipv4Page::configChanged(int index) { } } +void Ipv4Page::onAddressTextChanged() +{ + m_iconLabel->hide(); + m_textLabel->hide(); + + if (!getTextEditState(ipv4addressEdit->text())) { + m_addressHintLabel->setText(tr("Invalid address")); + } else { + m_addressHintLabel->clear(); + } +} + +void Ipv4Page::onNetMaskTextChanged() +{ + if (!netMaskIsValide(netMaskEdit->text())) { + m_maskHintLabel->setText(tr("Invalid subnet mask")); + } else { + m_maskHintLabel->clear(); + } +} + +void Ipv4Page::onAddressEidtFinished() +{ + if (ipv4addressEdit->isModified()) { + if (!ipv4addressEdit->text().isEmpty() && getTextEditState(ipv4addressEdit->text())) { + Q_EMIT ipv4EditFinished(ipv4addressEdit->text()); + } + } +} + void Ipv4Page::setLineEnabled(bool check) { - - ipv4addressEdit->setEnabled(check); - netMaskEdit->setEnabled(check); - gateWayEdit->setEnabled(check); - if (!check) { ipv4addressEdit->clear(); netMaskEdit->clear(); gateWayEdit->clear(); + + ipv4addressEdit->setPlaceholderText(" "); + netMaskEdit->setPlaceholderText(" "); + + } else { + ipv4addressEdit->setPlaceholderText(tr("Required")); //必填 + netMaskEdit->setPlaceholderText(tr("Required")); //必填 } + + ipv4addressEdit->setEnabled(check); + netMaskEdit->setEnabled(check); + gateWayEdit->setEnabled(check); } void Ipv4Page::setEnableOfSaveBtn() { - emit setIpv4PageState(checkConnectBtnIsEnabled()); + Q_EMIT setIpv4PageState(checkConnectBtnIsEnabled()); } bool Ipv4Page::getTextEditState(QString text) @@ -277,3 +349,64 @@ QString Ipv4Page::getNetMaskText(QString text) } return QString("%1.%2.%3.%4").arg(list[0],list[1],list[2],list[3]); } + +void Ipv4Page::initConflictHintLable() +{ + QIcon icon = QIcon::fromTheme("dialog-warning"); + m_iconLabel = new QLabel(m_addressHintLabel); + m_iconLabel->setPixmap(icon.pixmap(ICON_SIZE)); + m_textLabel = new QLabel(m_addressHintLabel); + m_textLabel->setText(tr("Address conflict")); + QHBoxLayout *conflictHintLayout = new QHBoxLayout(m_addressHintLabel); + conflictHintLayout->setContentsMargins(0, 0, 0, 0); + conflictHintLayout->addWidget(m_iconLabel); + conflictHintLayout->addWidget(m_textLabel); + conflictHintLayout->addStretch(); + m_addressHintLabel->setLayout(conflictHintLayout); + m_iconLabel->hide(); + m_textLabel->hide(); +} + +void Ipv4Page::initLoadingIcon() +{ + m_loadIcons.append(QIcon::fromTheme("ukui-loading-1-symbolic")); + m_loadIcons.append(QIcon::fromTheme("ukui-loading-2-symbolic")); + m_loadIcons.append(QIcon::fromTheme("ukui-loading-3-symbolic")); + m_loadIcons.append(QIcon::fromTheme("ukui-loading-4-symbolic")); + m_loadIcons.append(QIcon::fromTheme("ukui-loading-5-symbolic")); + m_loadIcons.append(QIcon::fromTheme("ukui-loading-6-symbolic")); + m_loadIcons.append(QIcon::fromTheme("ukui-loading-7-symbolic")); + m_iconTimer = new QTimer(this); + connect(m_iconTimer, &QTimer::timeout, this, &Ipv4Page::updateIcon); +} + +void Ipv4Page::updateIcon() +{ + if (m_currentIconIndex > 6) { + m_currentIconIndex = 0; + } + m_statusLabel->setPixmap(m_loadIcons.at(m_currentIconIndex).pixmap(ICON_SIZE)); + m_currentIconIndex ++; +} + +void Ipv4Page::startLoading() +{ + m_iconTimer->start(FRAME_SPEED); +} + +void Ipv4Page::stopLoading() +{ + m_iconTimer->stop(); + m_statusLabel->clear(); +} + +void Ipv4Page::showIpv4AddressConflict(bool isConflict) +{ + if (isConflict) { + m_iconLabel->show(); + m_textLabel->show(); + } else { + m_iconLabel->hide(); + m_textLabel->hide(); + } +} diff --git a/src/frontend/netdetails/ipv4page.h b/src/frontend/netdetails/ipv4page.h index 6d9b4e9c..b56b212a 100644 --- a/src/frontend/netdetails/ipv4page.h +++ b/src/frontend/netdetails/ipv4page.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef IPV4PAGE_H #define IPV4PAGE_H @@ -24,32 +43,44 @@ public: void setIpv4Config(KyIpConfigType ipv4Config); void setIpv4(const QString &ipv4); void setNetMask(const QString &netMask); -// void setIpv4FirDns(const QString &ipv4FirDns); -// void setIpv4SecDns(const QString &ipv4SecDns); void setMulDns(const QList &dns); void setGateWay(const QString &gateWay); - QString getNetMaskText(QString text); - bool checkIsChanged(const ConInfo info, KyConnectSetting &setting); + + void startLoading(); + void stopLoading(); + void showIpv4AddressConflict(bool isConflict); + + QString getNetMaskText(QString text); private: QComboBox *ipv4ConfigCombox; LineEdit *ipv4addressEdit; LineEdit *netMaskEdit; LineEdit *gateWayEdit; -// LineEdit *firstDnsEdit; -// LineEdit *secondDnsEdit; -private: QFormLayout *m_detailLayout; QVBoxLayout *mvBoxLayout; QLabel *m_configLabel; QLabel *m_addressLabel; QLabel *m_maskLabel; QLabel *m_gateWayLabel; -// QLabel *m_dnsLabel; -// QLabel *m_secDnsLabel; + + QLabel *m_configEmptyLabel; + QLabel *m_addressHintLabel; + QLabel *m_maskHintLabel; + QLabel *m_gateWayEmptyLabel; + MultipleDnsWidget *m_dnsWidget = nullptr; + + QLabel *m_statusLabel = nullptr; + QList m_loadIcons; + QTimer *m_iconTimer = nullptr; + int m_currentIconIndex =0; + + QLabel *m_iconLabel; + QLabel *m_textLabel; + private: void initUI(); void initComponent(); @@ -57,16 +88,21 @@ private: void configSave(); bool getTextEditState(QString text); bool netMaskIsValide(QString text); - bool checkConnectBtnIsEnabled(); + void initConflictHintLable(); + void initLoadingIcon(); - -private slots: +private Q_SLOTS: void setEnableOfSaveBtn(); void configChanged(int index); + void onAddressTextChanged(); + void onNetMaskTextChanged(); + void onAddressEidtFinished(); + void updateIcon(); + Q_SIGNALS: void setIpv4PageState(bool); - + void ipv4EditFinished(const QString &address); }; #endif // IPV4PAGE_H diff --git a/src/frontend/netdetails/ipv6page.cpp b/src/frontend/netdetails/ipv6page.cpp index bd6c67ee..aff4d26b 100644 --- a/src/frontend/netdetails/ipv6page.cpp +++ b/src/frontend/netdetails/ipv6page.cpp @@ -1,6 +1,32 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "ipv6page.h" #include "netdetail.h" +#define LAYOUT_MARGINS 0,0,0,0 +#define LAYOUT_SPACING 0 +#define HINT_TEXT_MARGINS 8, 1, 0, 3 +#define LABEL_HEIGHT 24 +#define FRAME_SPEED 150 +#define ICON_SIZE 16,16 + Ipv6Page::Ipv6Page(QWidget *parent):QFrame(parent) { initUI(); @@ -30,17 +56,7 @@ void Ipv6Page::setMulDns(const QList &dns) { m_dnsWidget->setDnsListText(dns); } -#if 0 -void Ipv6Page::setIpv6FirDns(const QString &ipv6FirDns) -{ - firstDnsEdit->setText(ipv6FirDns); -} -void Ipv6Page::setIpv6SecDns(const QString &ipv6SecDns) -{ - secondDnsEdit->setText(ipv6SecDns); -} -#endif void Ipv6Page::setGateWay(const QString &gateWay) { gateWayEdit->setText(gateWay); @@ -49,6 +65,7 @@ void Ipv6Page::setGateWay(const QString &gateWay) bool Ipv6Page::checkIsChanged(const ConInfo info, KyConnectSetting &setting) { bool isChanged = false; + QList ipv6DnsList; ipv6DnsList.clear(); ipv6DnsList = m_dnsWidget->getDns(); @@ -74,7 +91,9 @@ bool Ipv6Page::checkIsChanged(const ConInfo info, KyConnectSetting &setting) setting.setIpConfigType(IPADDRESS_V6, CONFIG_IP_MANUAL); isChanged = true; } - + QList ipv6dnsList; + ipv6dnsList.clear(); + ipv6dnsList = m_dnsWidget->getDns(); if(info.strIPV6Address != ipv6AddressEdit->text() || info.iIPV6Prefix != lengthEdit->text().toInt() || info.strIPV6GateWay != gateWayEdit->text()) { @@ -97,34 +116,69 @@ void Ipv6Page::initUI() { ipv6AddressEdit = new LineEdit(this); lengthEdit = new LineEdit(this); gateWayEdit = new LineEdit(this); -// firstDnsEdit = new LineEdit(this); -// secondDnsEdit = new LineEdit(this); m_configLabel = new QLabel(this); m_addressLabel = new QLabel(this); m_subnetLabel = new QLabel(this); m_gateWayLabel = new QLabel(this); -// m_dnsLabel = new QLabel(this); -// m_secDnsLabel = new QLabel(this); + m_configEmptyLabel = new QLabel(this); + m_configEmptyLabel->setFixedHeight(LABEL_HEIGHT); - m_configLabel->setText(tr("Ipv6Config")); + m_addressHintLabel = new QLabel(this); + m_addressHintLabel->setFixedHeight(LABEL_HEIGHT); + m_addressHintLabel->setContentsMargins(HINT_TEXT_MARGINS); + initConflictHintLable(); + + m_gateWayHintLabel = new QLabel(this); + m_gateWayHintLabel->setFixedHeight(LABEL_HEIGHT); + m_gateWayHintLabel->setContentsMargins(HINT_TEXT_MARGINS); + + m_subnetEmptyLabel = new QLabel(this); + m_subnetEmptyLabel->setFixedHeight(LABEL_HEIGHT); + + m_configLabel->setText(tr("IPv6Config")); m_addressLabel->setText(tr("Address")); m_subnetLabel->setText(tr("Subnet prefix Length")); m_gateWayLabel->setText(tr("Default Gateway")); -// m_dnsLabel->setText(tr("Prefs DNS")); -// m_secDnsLabel->setText(tr("Alternative DNS")); + + m_statusLabel = new QLabel(this); + m_statusLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); + QHBoxLayout *pPwdLayout = new QHBoxLayout(ipv6AddressEdit); + pPwdLayout->addStretch(); + pPwdLayout->addWidget(m_statusLabel); + + QPalette hintTextColor; + hintTextColor.setColor(QPalette::WindowText, Qt::red); + m_addressHintLabel->setPalette(hintTextColor); + m_gateWayHintLabel->setPalette(hintTextColor); + + QWidget *addressWidget = new QWidget(this); + QVBoxLayout *addressLayout = new QVBoxLayout(addressWidget); + addressLayout->setContentsMargins(LAYOUT_MARGINS); + addressLayout->setSpacing(LAYOUT_SPACING); + addressLayout->addWidget(ipv6AddressEdit); + addressLayout->addWidget(m_addressHintLabel); + + QWidget *gateWayWidget = new QWidget(this); + QVBoxLayout *gateWayLayout = new QVBoxLayout(gateWayWidget); + gateWayLayout->setContentsMargins(LAYOUT_MARGINS); + gateWayLayout->setSpacing(LAYOUT_SPACING); + gateWayLayout->addWidget(gateWayEdit); + gateWayLayout->addWidget(m_gateWayHintLabel); QRegExp ipv6_rx("^\\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?\\s*$"); m_dnsWidget = new MultipleDnsWidget(ipv6_rx, this); m_detailLayout = new QFormLayout(this); + m_detailLayout->setContentsMargins(0, 0, 0, 0); + m_detailLayout->setVerticalSpacing(0); m_detailLayout->addRow(m_configLabel,ipv6ConfigCombox); - m_detailLayout->addRow(m_addressLabel,ipv6AddressEdit); + m_detailLayout->addRow(m_configEmptyLabel); + m_detailLayout->addRow(m_addressLabel,addressWidget); m_detailLayout->addRow(m_subnetLabel,lengthEdit); - m_detailLayout->addRow(m_gateWayLabel,gateWayEdit); -// m_detailLayout->addRow(m_dnsLabel,firstDnsEdit); -// m_detailLayout->addRow(m_secDnsLabel,secondDnsEdit); + m_detailLayout->addRow(m_subnetEmptyLabel); + m_detailLayout->addRow(m_gateWayLabel,gateWayWidget); m_detailLayout->addRow(m_dnsWidget); ipv6ConfigCombox->addItem(tr("Auto(DHCP)")); //"自动(DHCP)" @@ -132,11 +186,11 @@ void Ipv6Page::initUI() { ipv6AddressEdit->setValidator(new QRegExpValidator(ipv6_rx, this)); gateWayEdit->setValidator(new QRegExpValidator(ipv6_rx, this)); -// firstDnsEdit->setValidator(new QRegExpValidator(ipv6_rx, this)); -// secondDnsEdit->setValidator(new QRegExpValidator(ipv6_rx, this)); QRegExp prefix_rx("\\b(?:(?:12[0-8]|1[0-1][0-9]|^[1-9][0-9]?$)\\.){3}(?:12[0-8]|1[0-1][0-9]|^[1-9][0-9]?$)\\b"); lengthEdit->setValidator(new QRegExpValidator(prefix_rx,this)); + + initLoadingIcon(); } void Ipv6Page::initComponent() { @@ -146,6 +200,9 @@ void Ipv6Page::initComponent() { setControlEnabled(true); } connect(ipv6ConfigCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(configChanged(int))); + connect(ipv6AddressEdit, SIGNAL(textChanged(QString)), this, SLOT(onAddressTextChanged())); + connect(ipv6AddressEdit, SIGNAL(editingFinished()), this, SLOT(onAddressEidtFinished())); + connect(gateWayEdit, SIGNAL(textChanged(QString)), this, SLOT(onGatewayTextChanged())); connect(ipv6ConfigCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(setEnableOfSaveBtn())); connect(ipv6AddressEdit, SIGNAL(textChanged(QString)), this, SLOT(setEnableOfSaveBtn())); @@ -164,21 +221,57 @@ void Ipv6Page::configChanged(int index) { void Ipv6Page::setControlEnabled(bool check) { - ipv6AddressEdit->setEnabled(check); - lengthEdit->setEnabled(check); - gateWayEdit->setEnabled(check); - - if (!check) { ipv6AddressEdit->clear(); lengthEdit->clear(); gateWayEdit->clear(); + + ipv6AddressEdit->setPlaceholderText(" "); + lengthEdit->setPlaceholderText(" "); + gateWayEdit->setPlaceholderText(" "); + } else { + ipv6AddressEdit->setPlaceholderText(tr("Required")); //必填 + lengthEdit->setPlaceholderText(tr("Required")); //必填 } + + ipv6AddressEdit->setEnabled(check); + lengthEdit->setEnabled(check); + gateWayEdit->setEnabled(check); } void Ipv6Page::setEnableOfSaveBtn() { - emit setIpv6PageState(checkConnectBtnIsEnabled()); + Q_EMIT setIpv6PageState(checkConnectBtnIsEnabled()); +} + +void Ipv6Page::onAddressTextChanged() +{ + m_iconLabel->hide(); + m_textLabel->hide(); + + if (!getIpv6EditState(ipv6AddressEdit->text())) { + m_addressHintLabel->setText(tr("Invalid address")); + } else { + m_addressHintLabel->clear(); + } +} + +void Ipv6Page::onGatewayTextChanged() +{ + if (!getIpv6EditState(gateWayEdit->text())) { + m_gateWayHintLabel->setText(tr("Invalid gateway")); + } else { + m_gateWayHintLabel->clear(); + } +} + +void Ipv6Page::onAddressEidtFinished() +{ + if (ipv6AddressEdit->isModified()) { + if (!ipv6AddressEdit->text().isEmpty() && getIpv6EditState(ipv6AddressEdit->text())) { + Q_EMIT ipv6EditFinished(ipv6AddressEdit->text()); + } + } } bool Ipv6Page::checkConnectBtnIsEnabled() @@ -195,31 +288,27 @@ bool Ipv6Page::checkConnectBtnIsEnabled() qDebug() << "ipv6 prefix length empty"; return false; } - - if (gateWayEdit->text().isEmpty() || !getIpv6EditState(gateWayEdit->text())) { - qDebug() << "ipv6 gateway empty or invalid"; - return false; - } -#if 0 - if (firstDnsEdit->text().isEmpty() && !secondDnsEdit->text().isEmpty()) { - qDebug() << "ipv6 dns sort invalid"; - return false; - } - - if (!getIpv6EditState(firstDnsEdit->text())) { - qDebug() << "ipv6 first dns invalid"; - return false; - } - - if (!getIpv6EditState(secondDnsEdit->text())) { - qDebug() << "ipv6 second dns invalid"; - return false; - } -#endif } return true; } +void Ipv6Page::initConflictHintLable() +{ + QIcon icon = QIcon::fromTheme("dialog-warning"); + m_iconLabel = new QLabel(m_addressHintLabel); + m_iconLabel->setPixmap(icon.pixmap(ICON_SIZE)); + m_textLabel = new QLabel(m_addressHintLabel); + m_textLabel->setText(tr("Address conflict")); + QHBoxLayout *conflictHintLayout = new QHBoxLayout(m_addressHintLabel); + conflictHintLayout->setContentsMargins(0, 0, 0, 0); + conflictHintLayout->addWidget(m_iconLabel); + conflictHintLayout->addWidget(m_textLabel); + conflictHintLayout->addStretch(); + m_addressHintLabel->setLayout(conflictHintLayout); + m_iconLabel->hide(); + m_textLabel->hide(); +} + bool Ipv6Page::getIpv6EditState(QString text) { if (text.isEmpty()) { @@ -256,3 +345,46 @@ int Ipv6Page::getPerfixLength(QString text) return length; } +void Ipv6Page::initLoadingIcon() +{ + m_loadIcons.append(QIcon::fromTheme("ukui-loading-1-symbolic")); + m_loadIcons.append(QIcon::fromTheme("ukui-loading-2-symbolic")); + m_loadIcons.append(QIcon::fromTheme("ukui-loading-3-symbolic")); + m_loadIcons.append(QIcon::fromTheme("ukui-loading-4-symbolic")); + m_loadIcons.append(QIcon::fromTheme("ukui-loading-5-symbolic")); + m_loadIcons.append(QIcon::fromTheme("ukui-loading-6-symbolic")); + m_loadIcons.append(QIcon::fromTheme("ukui-loading-7-symbolic")); + m_iconTimer = new QTimer(this); + connect(m_iconTimer, &QTimer::timeout, this, &Ipv6Page::updateIcon); +} + +void Ipv6Page::updateIcon() +{ + if (m_currentIconIndex > 6) { + m_currentIconIndex = 0; + } + m_statusLabel->setPixmap(m_loadIcons.at(m_currentIconIndex).pixmap(ICON_SIZE)); + m_currentIconIndex ++; +} + +void Ipv6Page::startLoading() +{ + m_iconTimer->start(FRAME_SPEED); +} + +void Ipv6Page::stopLoading() +{ + m_iconTimer->stop(); + m_statusLabel->clear(); +} + +void Ipv6Page::showIpv6AddressConflict(bool isConflict) +{ + if (isConflict) { + m_iconLabel->show(); + m_textLabel->show(); + } else { + m_iconLabel->hide(); + m_textLabel->hide(); + } +} diff --git a/src/frontend/netdetails/ipv6page.h b/src/frontend/netdetails/ipv6page.h index 178f5dfa..b077efad 100644 --- a/src/frontend/netdetails/ipv6page.h +++ b/src/frontend/netdetails/ipv6page.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef IPV6PAGE_H #define IPV6PAGE_H @@ -24,8 +43,6 @@ public: void setIpv6Config(KyIpConfigType ipv6Config); void setIpv6(const QString &ipv4); void setIpv6Perfix(const int &ipv6Perfix); -// void setIpv6FirDns(const QString &ipv6FirDns); -// void setIpv6SecDns(const QString &ipv6SecDns); void setMulDns(const QList &dns); void setGateWay(const QString &gateWay); @@ -33,23 +50,37 @@ public: int getPerfixLength(QString text); -private: + void startLoading(); + void stopLoading(); + void showIpv6AddressConflict(bool isConflict); + +public: QComboBox *ipv6ConfigCombox; LineEdit *ipv6AddressEdit; LineEdit *lengthEdit; LineEdit *gateWayEdit; -// LineEdit *firstDnsEdit; -// LineEdit *secondDnsEdit; + private: QFormLayout *m_detailLayout; QLabel *m_configLabel; QLabel *m_addressLabel; QLabel *m_subnetLabel; QLabel *m_gateWayLabel; -// QLabel *m_dnsLabel; -// QLabel *m_secDnsLabel; + + QLabel *m_configEmptyLabel; + QLabel *m_addressHintLabel; + QLabel *m_subnetEmptyLabel; + QLabel *m_gateWayHintLabel; MultipleDnsWidget *m_dnsWidget = nullptr; + + QLabel *m_statusLabel = nullptr; + QList m_loadIcons; + QTimer *m_iconTimer = nullptr; + int m_currentIconIndex =0; + + QLabel *m_iconLabel; + QLabel *m_textLabel; private: void initUI(); void initComponent(); @@ -59,12 +90,20 @@ private: bool checkConnectBtnIsEnabled(); -private slots: + void initConflictHintLable(); + void initLoadingIcon(); + +private Q_SLOTS: void configChanged(int index); void setEnableOfSaveBtn(); + void onAddressTextChanged(); + void onGatewayTextChanged(); + void onAddressEidtFinished(); + void updateIcon(); -signals: +Q_SIGNALS: void setIpv6PageState(bool); + void ipv6EditFinished(const QString &address); }; #endif // IPV6PAGE_H diff --git a/src/frontend/netdetails/joinhiddenwifipage.cpp b/src/frontend/netdetails/joinhiddenwifipage.cpp new file mode 100644 index 00000000..313be9eb --- /dev/null +++ b/src/frontend/netdetails/joinhiddenwifipage.cpp @@ -0,0 +1,288 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#include "joinhiddenwifipage.h" + +#include + +#define THEME_SCHAME "org.ukui.style" +#define COLOR_THEME "styleName" +#define WINDOW_WIDTH 480 +#define MIN_WINDOW_HEIGHT 368 +#define PEAP_WINDOW_HEIGHT 524 +#define TLS_WINDOW_HEIGHT 580 +#define LAYOUT_MARGINS 0, 0, 0, 0 +#define TOP_LAYOUT_MARGINS 24, 12, 24, 16 +#define CENTER_LAYOUT_MARGINS 24, 0, 24, 8 +#define BOTTOM_LAYOUT_MARGINS 24, 24, 24, 24 +#define LAYOUT_SPACING 16 +#define LABEL_MIN_WIDTH 146 +#define LABEL_MAX_WIDTH 434 +#define MAX_NAME_LENGTH 32 +#define SCROAREA_WIDTH 480 +#define MEDIUM_WEIGHT_VALUE 57 + +JoinHiddenWiFiPage::JoinHiddenWiFiPage(QString devName, KDialog *parent) + :m_devName(devName), + KDialog(parent) +{ + m_wirelessConnOpration = new KyWirelessConnectOperation(this); + + initUI(); + initComponent(); + + setAttribute(Qt::WA_DeleteOnClose); + + setJoinBtnEnable(); +} + +JoinHiddenWiFiPage::~JoinHiddenWiFiPage() +{ + +} + +void JoinHiddenWiFiPage::closeEvent(QCloseEvent *event) +{ + Q_EMIT this->hiddenWiFiPageClose(m_devName); + return QWidget::closeEvent(event); +} + +void JoinHiddenWiFiPage::initUI() +{ + m_topWidget = new QWidget(this); + m_centerWidget = new QWidget(this); + m_bottomWidget = new QWidget(this); + m_secuWidget = new SecurityPage(false, this); + m_secuWidget->setSecurity(KySecuType::WPA_AND_WPA2_PERSONAL); + + m_descriptionLabel = new FixLabel(this); + m_descriptionLabel->setFixedWidth(LABEL_MAX_WIDTH); + m_nameLabel = new FixLabel(this); + m_nameLabel->setFixedWidth(LABEL_MIN_WIDTH); + m_nameEdit =new LineEdit(this); + + m_bottomDivider = new Divider(this); + m_showListBtn = new KBorderlessButton(this); + m_cancelBtn =new QPushButton(this); + m_joinBtn =new QPushButton(this); + + m_hiddenWifiScrollArea = new QScrollArea(this); + m_hiddenWifiScrollArea->setFrameShape(QFrame::NoFrame); + m_hiddenWifiScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + QPalette pa = m_hiddenWifiScrollArea->palette(); + pa.setBrush(QPalette::Window, Qt::transparent); + m_hiddenWifiScrollArea->setPalette(pa); + + m_pageLayout = new QVBoxLayout(this); + m_pageLayout->setContentsMargins(LAYOUT_MARGINS); + m_pageLayout->setSpacing(0); + m_pageLayout->addWidget(m_topWidget); + m_pageLayout->addWidget(m_hiddenWifiScrollArea); + m_pageLayout->addWidget(m_bottomDivider); + m_pageLayout->addWidget(m_bottomWidget); + this->mainWidget()->setLayout(m_pageLayout); + + m_topLayout = new QHBoxLayout(m_topWidget); + m_topLayout->setContentsMargins(TOP_LAYOUT_MARGINS); + m_topLayout->setSpacing(0); + m_topLayout->addWidget(m_descriptionLabel); + m_topLayout->addStretch(); + + QWidget *ssidWidget = new QWidget(this); + QHBoxLayout *ssidLayout = new QHBoxLayout(ssidWidget); + ssidLayout->setContentsMargins(LAYOUT_MARGINS); + ssidLayout->setSpacing(0); + m_nameLabel->setMinimumWidth(LABEL_MIN_WIDTH); + ssidLayout->addWidget(m_nameLabel); + ssidLayout->addWidget(m_nameEdit); + + m_centerVBoxLayout = new QVBoxLayout(m_centerWidget); + m_centerVBoxLayout->setContentsMargins(CENTER_LAYOUT_MARGINS); + m_centerVBoxLayout->setSpacing(0); + m_centerVBoxLayout->addWidget(ssidWidget); + m_centerVBoxLayout->addSpacing(LAYOUT_SPACING); + m_centerVBoxLayout->addWidget(m_secuWidget); + + m_centerWidget->setFixedWidth(SCROAREA_WIDTH); + m_hiddenWifiScrollArea->setFixedWidth(SCROAREA_WIDTH); + m_hiddenWifiScrollArea->setWidget(m_centerWidget); + m_hiddenWifiScrollArea->setWidgetResizable(true); + + //底部按钮 + m_bottomLayout = new QHBoxLayout(m_bottomWidget); + m_bottomLayout->setContentsMargins(BOTTOM_LAYOUT_MARGINS); + m_bottomLayout->setSpacing(LAYOUT_SPACING); + m_bottomLayout->addWidget(m_showListBtn); + m_bottomLayout->addStretch(); + m_bottomLayout->addWidget(m_cancelBtn); + m_bottomLayout->addWidget(m_joinBtn); + + //请输入您想要加入网络的名称和安全类型 + m_descriptionLabel->setLabelText(tr("Please enter the network name and security type")); + QFont font = m_descriptionLabel->font(); + font.setWeight(MEDIUM_WEIGHT_VALUE); + m_descriptionLabel->setFont(font); + + m_nameLabel->setLabelText(tr("Network name(SSID)")); //网络名(SSID) + m_showListBtn->setText(tr("Show Network List")); //显示网络列表 + m_cancelBtn->setText(tr("Cancel")); + m_joinBtn->setText(tr("Join")); + + m_nameEdit->setMaxLength(MAX_NAME_LENGTH); + m_nameEdit->setPlaceholderText(tr("Required")); //必填 + + this->setWindowTitle(tr("Find and Join Wi-Fi")); + this->setWindowIcon(QIcon::fromTheme("kylin-network")); + + this->setFixedHeight(MIN_WINDOW_HEIGHT); + this->setFixedWidth(WINDOW_WIDTH); + onPaletteChanged(); +} + +void JoinHiddenWiFiPage::initComponent() +{ + connect(m_cancelBtn, &QPushButton::clicked, this, [=] { + close(); + }); + + connect(m_joinBtn, SIGNAL(clicked()), this, SLOT(onBtnJoinClicked())); + connect(m_showListBtn, SIGNAL(clicked()), this, SLOT(onBtnShowListClicked())); + + connect(m_secuWidget, &SecurityPage::secuTypeChanged, this, &JoinHiddenWiFiPage::onSecuTypeChanged); + connect(m_secuWidget, &SecurityPage::eapTypeChanged, this, &JoinHiddenWiFiPage::onEapTypeChanged); + connect(m_secuWidget, &SecurityPage::setSecuPageState, this, [ = ](bool status) { + m_isSecuOk = status; + setJoinBtnEnable(); + }); + connect(m_nameEdit, &LineEdit::textChanged, this, &JoinHiddenWiFiPage::setJoinBtnEnable); + + connect(qApp, &QApplication::paletteChanged, this, &JoinHiddenWiFiPage::onPaletteChanged); + + const QByteArray id(THEME_SCHAME); + if(QGSettings::isSchemaInstalled(id)){ + QGSettings * fontSetting = new QGSettings(id, QByteArray(), this); + connect(fontSetting, &QGSettings::changed,[=](QString key) { + if ("themeColor" == key) { + onPaletteChanged(); + } + }); + } +} + +void JoinHiddenWiFiPage::setJoinBtnEnable() +{ + if (!m_nameEdit->text().isEmpty() && m_isSecuOk) { + m_isJoinBtnEnable = true; + } else { + m_isJoinBtnEnable = false; + } + m_joinBtn->setEnabled(m_isJoinBtnEnable); +} + +void JoinHiddenWiFiPage::onBtnJoinClicked() +{ + KyWirelessConnectSetting connSettingInfo; + //基本信息 + connSettingInfo.m_ssid = m_nameEdit->text(); + connSettingInfo.setConnectName(connSettingInfo.m_ssid); + connSettingInfo.setIfaceName(m_devName); + connSettingInfo.m_secretFlag = 0; + + KySecuType secuType; + KyEapMethodType eapType; + m_secuWidget->getSecuType(secuType, eapType); + + if (secuType == WPA_AND_WPA2_ENTERPRISE) { + if (eapType == TLS) { + m_info.tlsInfo.devIfaceName = m_devName; + m_secuWidget->updateTlsChange(m_info.tlsInfo); + m_wirelessConnOpration->addAndActiveWirelessEnterPriseTlsConnect(m_info.tlsInfo, connSettingInfo, m_devName, true); + } else if (eapType == PEAP) { + m_secuWidget->updatePeapChange(m_info.peapInfo); + m_wirelessConnOpration->addAndActiveWirelessEnterPrisePeapConnect(m_info.peapInfo, connSettingInfo, m_devName, true); + } else if (eapType = TTLS) { + m_secuWidget->updateTtlsChange(m_info.ttlsInfo); + m_wirelessConnOpration->addAndActiveWirelessEnterPriseTtlsConnect(m_info.ttlsInfo, connSettingInfo, m_devName, true); + } + } else { + m_secuWidget->updateSecurityChange(connSettingInfo); + m_wirelessConnOpration->addAndActiveWirelessConnect(m_devName, connSettingInfo, true); + } + + close(); +} + +void JoinHiddenWiFiPage::onBtnShowListClicked() +{ + Q_EMIT showWlanList(1); //WLAN_PAGE_INDEX +} + +void JoinHiddenWiFiPage::onSecuTypeChanged(const KySecuType &type) +{ + if (type != KySecuType::WPA_AND_WPA2_ENTERPRISE) { + this->setFixedHeight(MIN_WINDOW_HEIGHT); + } +} + +void JoinHiddenWiFiPage::onEapTypeChanged(const KyEapMethodType &type) +{ + if (type == KyEapMethodType::TLS) { + this->setFixedHeight(TLS_WINDOW_HEIGHT); + } else if (type == KyEapMethodType::PEAP || type == KyEapMethodType::TTLS) { + this->setFixedHeight(PEAP_WINDOW_HEIGHT); + } +} + +void JoinHiddenWiFiPage::onPaletteChanged() +{ + QPalette pal = qApp->palette(); + + QGSettings * styleGsettings = nullptr; + const QByteArray style_id(THEME_SCHAME); + if (QGSettings::isSchemaInstalled(style_id)) { + styleGsettings = new QGSettings(style_id); + QString currentTheme = styleGsettings->get(COLOR_THEME).toString(); + if(currentTheme == "ukui-default"){ + pal = lightPalette(this); + } + } + this->setPalette(pal); + setFramePalette(m_secuWidget, pal); + setFramePalette(m_hiddenWifiScrollArea, pal); + + if (styleGsettings != nullptr) { + delete styleGsettings; + styleGsettings = nullptr; + } +} + +void JoinHiddenWiFiPage::centerToScreen() +{ + QDesktopWidget* m = QApplication::desktop(); + QRect desk_rect = m->screenGeometry(m->screenNumber(QCursor::pos())); + int desk_x = desk_rect.width(); + int desk_y = desk_rect.height(); + int x = this->width(); + int y = this->height(); +// this->move(desk_x / 2 - x / 2 + desk_rect.left(), desk_y / 2 - y / 2 + desk_rect.top()); + kdk::WindowManager::setGeometry(this->windowHandle(), QRect(desk_x / 2 - x / 2 + desk_rect.left(), + desk_y / 2 - y / 2 + desk_rect.top(), + this->width(), + this->height())); +} diff --git a/src/frontend/netdetails/joinhiddenwifipage.h b/src/frontend/netdetails/joinhiddenwifipage.h new file mode 100644 index 00000000..5f97b56b --- /dev/null +++ b/src/frontend/netdetails/joinhiddenwifipage.h @@ -0,0 +1,98 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#ifndef JOINHIDDENWIFIPAGE_H +#define JOINHIDDENWIFIPAGE_H + +#include +#include +#include +#include +#include + +#include "windowmanager/windowmanager.h" +#include "coninfo.h" +#include "kywirelessconnectoperation.h" +#include "securitypage.h" +#include "divider.h" +#include "kwidget.h" +#include "kdialog.h" +#include "kborderlessbutton.h" + +using namespace kdk; + +class JoinHiddenWiFiPage : public KDialog +{ + Q_OBJECT + +public: + JoinHiddenWiFiPage(QString devName, KDialog *parent = nullptr); + ~JoinHiddenWiFiPage(); + + void centerToScreen(); +protected: + void closeEvent(QCloseEvent *event); + +private: + void initUI(); + void initComponent(); + + void setJoinBtnEnable(); + +private: + KyWirelessConnectOperation *m_wirelessConnOpration = nullptr; + QString m_devName; + + QWidget *m_topWidget; + QWidget *m_centerWidget; + QWidget *m_bottomWidget; + SecurityPage *m_secuWidget; + + FixLabel *m_descriptionLabel; + FixLabel *m_nameLabel; + LineEdit *m_nameEdit; + + Divider *m_bottomDivider = nullptr; + KBorderlessButton *m_showListBtn; + QPushButton *m_cancelBtn; + QPushButton *m_joinBtn; + + QScrollArea *m_hiddenWifiScrollArea; + QVBoxLayout *m_pageLayout; + QHBoxLayout *m_topLayout; + QVBoxLayout *m_centerVBoxLayout; + QHBoxLayout *m_bottomLayout; + + bool m_isJoinBtnEnable = false; + bool m_isSecuOk = false; + ConInfo m_info; + +private Q_SLOTS: + void onBtnJoinClicked(); + void onBtnShowListClicked(); + void onSecuTypeChanged(const KySecuType &type); + void onEapTypeChanged(const KyEapMethodType &type); + void onPaletteChanged(); + +Q_SIGNALS: + void hiddenWiFiPageClose(QString); + void showWlanList(int type); +}; + +#endif // JOINHIDDENWIFIPAGE_H diff --git a/src/frontend/netdetails/multiplednswidget.h b/src/frontend/netdetails/multiplednswidget.h index 92dc9c1a..5b32dd53 100644 --- a/src/frontend/netdetails/multiplednswidget.h +++ b/src/frontend/netdetails/multiplednswidget.h @@ -61,7 +61,6 @@ private Q_SLOTS: void setDnsListWidgetStyle(); void onAddBtnClicked(); void onRemoveBtnClicked(); - }; #endif // MULTIPLEDNSWIDGET_H diff --git a/src/frontend/netdetails/netdetail.cpp b/src/frontend/netdetails/netdetail.cpp index 3de2a2bb..16451952 100644 --- a/src/frontend/netdetails/netdetail.cpp +++ b/src/frontend/netdetails/netdetail.cpp @@ -1,34 +1,60 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "netdetail.h" #include "backend/kylinipv4arping.h" #include "backend/kylinipv6arping.h" //#include "xatom/xatom-helper.h" - #define THEME_SCHAME "org.ukui.style" #define COLOR_THEME "styleName" #include #include #include +#include #include "windowmanager/windowmanager.h" #define WINDOW_WIDTH 520 -#define WINDOW_HEIGHT 590 -#define BUTTON_SIZE 30 +#define WINDOW_HEIGHT 602 #define ICON_SIZE 22,22 #define TITLE_LAYOUT_MARGINS 9,9,0,0 -#define LAYOUT_MARGINS 24,0,24,0 +#define CENTER_LAYOUT_MARGINS 24,0,0,0 +#define BOTTOM_LAYOUT_MARGINS 24,0,24,0 #define BOTTOM_LAYOUT_SPACING 16 #define PAGE_LAYOUT_SPACING 1 #define DETAIL_PAGE_NUM 0 #define IPV4_PAGE_NUM 1 #define IPV6_PAGE_NUM 2 #define SECURITY_PAGE_NUM 3 -#define CREATE_NET_PAGE_NUM 4 +#define CONFIG_PAGE_NUM 4 +#define CREATE_NET_PAGE_NUM 5 #define PAGE_MIN_HEIGHT 40 -#define LAN_TAB_WIDTH 300 -#define WLAN_TAB_WIDTH 400 +#define PAGE_WIDTH 472 +#define LAN_TAB_WIDTH 180 +#define WLAN_TAB_WIDTH 240 +#define SCRO_WIDTH 496 +#define SCRO_HEIGHT 600 +#define PEAP_SCRO_HEIGHT 300 +#define TLS_SCRO_HEIGHT 480 +#define MAX_TAB_TEXT_LENGTH 44 //extern void qt_blurImage(QImage &blurImage, qreal radius, bool quality, int transposed); @@ -69,6 +95,37 @@ void NetDetail::setNetdetailSomeEnable(bool on) confimBtn->setEnabled(on); } +void NetDetail::startObjectThread() +{ + m_objectThread = new QThread(); + m_object = new ThreadObject(m_deviceName); + m_object->moveToThread(m_objectThread); + connect(m_objectThread, &QThread::finished, m_objectThread, &QObject::deleteLater); + connect(m_objectThread, &QThread::finished, m_object, &QObject::deleteLater); + connect(ipv4Page, &Ipv4Page::ipv4EditFinished, this, [=](){ + ipv4Page->startLoading(); + }); + connect(ipv6Page, &Ipv6Page::ipv6EditFinished, this, [=](){ + ipv6Page->startLoading(); + }); + + connect(ipv4Page, SIGNAL(ipv4EditFinished(const QString &)), m_object, SLOT(checkIpv4ConflictThread(const QString &))); + connect(ipv6Page, SIGNAL(ipv6EditFinished(const QString &)), m_object, SLOT(checkIpv6ConflictThread(const QString &))); + connect(this, SIGNAL(checkCurrentIpv4Conflict(const QString &)), m_object, SLOT(checkIpv4ConflictThread(const QString &))); + connect(this, SIGNAL(checkCurrentIpv6Conflict(const QString &)), m_object, SLOT(checkIpv6ConflictThread(const QString &))); + + connect(m_object, &ThreadObject::ipv4IsConflict, this, [=](bool ipv4IsConf) { + ipv4Page->stopLoading(); + ipv4Page->showIpv4AddressConflict(ipv4IsConf); + }); + connect(m_object, &ThreadObject::ipv6IsConflict, this, [=](bool ipv6IsConf) { + ipv6Page->stopLoading(); + ipv6Page->showIpv6AddressConflict(ipv6IsConf); + }); + + m_objectThread->start(); +} + NetDetail::NetDetail(QString interface, QString name, QString uuid, bool isActive, bool isWlan, bool isCreateNet, QWidget *parent) :m_deviceName(interface), m_name(name), @@ -110,8 +167,8 @@ NetDetail::NetDetail(QString interface, QString name, QString uuid, bool isActiv loadPage(); initComponent(); getConInfo(m_info); + startObjectThread(); pagePadding(name,isWlan); - connect(qApp, &QApplication::paletteChanged, this, &NetDetail::onPaletteChanged); isCreateOk = !(m_isCreateNet && !isWlan); @@ -130,7 +187,10 @@ NetDetail::NetDetail(QString interface, QString name, QString uuid, bool isActiv NetDetail::~NetDetail() { - + if (m_objectThread->isRunning()) { + m_objectThread->quit(); + m_objectThread->wait(); + } } void NetDetail::onPaletteChanged() @@ -146,7 +206,7 @@ void NetDetail::onPaletteChanged() pal = lightPalette(this); } } - + pal.setColor(QPalette::Background, pal.base().color()); this->setPalette(pal); setFramePalette(detailPage, pal); @@ -157,8 +217,8 @@ void NetDetail::onPaletteChanged() QToolTip::setPalette(pal); QPalette listwidget_pal(detailPage->m_listWidget->palette()); - listwidget_pal.setColor(QPalette::Base, this->palette().base().color()); - listwidget_pal.setColor(QPalette::AlternateBase, this->palette().alternateBase().color()); + listwidget_pal.setColor(QPalette::Base, pal.base().color()); + listwidget_pal.setColor(QPalette::AlternateBase, pal.alternateBase().color()); detailPage->m_listWidget->setAlternatingRowColors(true); detailPage->m_listWidget->setPalette(listwidget_pal); @@ -166,25 +226,39 @@ void NetDetail::onPaletteChanged() delete styleGsettings; styleGsettings = nullptr; } - - QColor colorTabBar = pal.color(QPalette::Disabled, QPalette::Highlight); - m_netTabBar->setBackgroundColor(colorTabBar); } void NetDetail::currentRowChangeSlot(int row) { - stackWidget->setCurrentIndex(row); + if (isActive) { + if (row < 3) { + stackWidget->setCurrentIndex(row); + } else { + if(isWlan) { + stackWidget->setCurrentIndex(row); + } else { + stackWidget->setCurrentIndex(CONFIG_PAGE_NUM); + } + } + } else { + stackWidget->setCurrentIndex(row); + } } void NetDetail::paintEvent(QPaintEvent *event) { +// QPalette pal = qApp->palette(); +// QPainter painter(this); +// painter.setBrush(pal.color(QPalette::Base)); +// painter.drawRect(this->rect()); +// painter.fillRect(rect(), QBrush(pal.color(QPalette::Base))); return QWidget::paintEvent(event); } void NetDetail::closeEvent(QCloseEvent *event) { - emit this->detailPageClose(false); - emit this->createPageClose(m_deviceName); + Q_EMIT this->detailPageClose(m_deviceName, m_name, m_uuid); + Q_EMIT this->createPageClose(m_deviceName); return QWidget::closeEvent(event); } @@ -196,65 +270,103 @@ void NetDetail::centerToScreen() int desk_y = desk_rect.height(); int x = this->width(); int y = this->height(); - this->move(desk_x / 2 - x / 2 + desk_rect.left(), desk_y / 2 - y / 2 + desk_rect.top()); -// kdk::WindowManager::setGeometry(this->windowHandle(), QRect(desk_x / 2 - x / 2 + desk_rect.left(), -// desk_y / 2 - y / 2 + desk_rect.top(), -// this->width(), -// this->height())); +// this->move(desk_x / 2 - x / 2 + desk_rect.left(), desk_y / 2 - y / 2 + desk_rect.top()); + kdk::WindowManager::setGeometry(this->windowHandle(), QRect(desk_x / 2 - x / 2 + desk_rect.left(), + desk_y / 2 - y / 2 + desk_rect.top(), + this->width(), + this->height())); } void NetDetail::initUI() { QVBoxLayout *mainLayout = new QVBoxLayout(this); - mainLayout->setContentsMargins(9,9,14,24); + mainLayout->setContentsMargins(0,9,0,24); + mainLayout->setSpacing(22); + + this->installEventFilter(this); + pageFrame = new QFrame(this); + centerWidget = new QWidget(this); + bottomWidget = new QWidget(this); detailPage = new DetailPage(isWlan, m_name.isEmpty(), this); - ipv4Page = new Ipv4Page(this); ipv6Page = new Ipv6Page(this); securityPage = new SecurityPage(this); createNetPage = new CreatNetPage(this); - this->installEventFilter(this); + configPage = new ConfigPage(this); + + detailPage->setFixedWidth(PAGE_WIDTH); + ipv4Page->setFixedWidth(PAGE_WIDTH); + ipv6Page->setFixedWidth(PAGE_WIDTH); + securityPage->setFixedWidth(PAGE_WIDTH); + createNetPage->setFixedWidth(PAGE_WIDTH); + configPage->setFixedWidth(PAGE_WIDTH); + + m_secuPageScrollArea = new QScrollArea(centerWidget); + m_secuPageScrollArea->setFixedWidth(SCRO_WIDTH); + m_secuPageScrollArea->setFrameShape(QFrame::NoFrame); + m_secuPageScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + m_secuPageScrollArea->setWidget(securityPage); + + m_secuPageScrollArea->setWidgetResizable(true); + + m_ipv4ScrollArea = new QScrollArea(centerWidget); + m_ipv4ScrollArea->setFixedWidth(SCRO_WIDTH); + m_ipv4ScrollArea->setFrameShape(QFrame::NoFrame); + m_ipv4ScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + m_ipv4ScrollArea->setWidget(ipv4Page); + m_ipv4ScrollArea->setWidgetResizable(true); + + m_ipv6ScrollArea = new QScrollArea(centerWidget); + m_ipv6ScrollArea->setFixedWidth(SCRO_WIDTH); + m_ipv6ScrollArea->setFrameShape(QFrame::NoFrame); + m_ipv6ScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + m_ipv6ScrollArea->setWidget(ipv6Page); + m_ipv6ScrollArea->setWidgetResizable(true); + + QPalette pal = m_secuPageScrollArea->palette(); + pal.setBrush(QPalette::Base, QColor(0,0,0,0)); + m_secuPageScrollArea->setPalette(pal); + m_ipv4ScrollArea->setPalette(pal); + m_ipv6ScrollArea->setPalette(pal); - centerWidget = new QWidget(this); - bottomWidget = new QWidget(this); stackWidget = new QStackedWidget(centerWidget); stackWidget->addWidget(detailPage); - stackWidget->addWidget(ipv4Page); - stackWidget->addWidget(ipv6Page); - stackWidget->addWidget(securityPage); + stackWidget->addWidget(m_ipv4ScrollArea); + stackWidget->addWidget(m_ipv6ScrollArea); + stackWidget->addWidget(m_secuPageScrollArea); + stackWidget->addWidget(configPage); stackWidget->addWidget(createNetPage); - mainLayout->addWidget(centerWidget); - mainLayout->addWidget(bottomWidget); - - bottomWidget->setMinimumHeight(PAGE_MIN_HEIGHT); - - pageFrame = new QFrame(this); - QHBoxLayout *pageLayout = new QHBoxLayout(pageFrame); - pageLayout->setSpacing(PAGE_LAYOUT_SPACING); - // TabBar - m_netTabBar = new KTabBar(KTabBarStyle::SegmentDark, this); + onPaletteChanged(); + m_networkMode = NetworkModeType(NetworkModeConfig::getInstance()->getNetworkModeConfig(m_uuid)); + m_netTabBar = new NetTabBar(this); m_netTabBar->addTab(tr("Detail")); //详情 - m_netTabBar->addTab(tr("Ipv4"));//Ipv4 - m_netTabBar->addTab(tr("Ipv6"));//Ipv6 + m_netTabBar->addTab(tr("IPv4"));//Ipv4 + m_netTabBar->addTab(tr("IPv6"));//Ipv6 if (isWlan) { m_netTabBar->addTab(tr("Security"));//安全 - m_netTabBar->setFixedWidth(WLAN_TAB_WIDTH); + if (isActive && m_networkMode != DBUS_INVAILD && m_networkMode != NO_CONFIG) { + m_netTabBar->addTab(tr("Config")); //配置 + m_netTabBar->setFixedWidth(WLAN_TAB_WIDTH + TAB_WIDTH); + } else { + m_netTabBar->setFixedWidth(WLAN_TAB_WIDTH); + } } else { - m_netTabBar->setFixedWidth(LAN_TAB_WIDTH); + if (isActive && m_networkMode != DBUS_INVAILD && m_networkMode != NO_CONFIG) { + m_netTabBar->addTab(tr("Config")); //配置 + m_netTabBar->setFixedWidth(LAN_TAB_WIDTH + TAB_WIDTH); + } else { + m_netTabBar->setFixedWidth(LAN_TAB_WIDTH); + } } - pageLayout->addStretch(); - pageLayout->addWidget(m_netTabBar); - pageLayout->addStretch(); - // TabBar关联选项卡页面 connect(m_netTabBar, SIGNAL(currentChanged(int)), this, SLOT(currentRowChangeSlot(int))); - + setNetTabToolTip(); confimBtn = new QPushButton(this); confimBtn->setText(tr("Confirm")); @@ -263,28 +375,29 @@ void NetDetail::initUI() cancelBtn->setText(tr("Cancel")); forgetBtn = new QPushButton(this); - forgetBtn->setText(tr("Forget this network")); - this->setWindowIcon(QIcon::fromTheme("kylin-network")); + QHBoxLayout *pageLayout = new QHBoxLayout(pageFrame); + pageLayout->setContentsMargins(0, 0, 0, 0); + pageLayout->addWidget(m_netTabBar, Qt::AlignCenter); QVBoxLayout *centerlayout = new QVBoxLayout(centerWidget); - centerlayout->setContentsMargins(LAYOUT_MARGINS); - centerlayout->addWidget(pageFrame); + centerlayout->setContentsMargins(CENTER_LAYOUT_MARGINS); // 右边距为0,为安全页滚动区域留出空间 centerlayout->addWidget(stackWidget); QHBoxLayout *bottomLayout = new QHBoxLayout(bottomWidget); - bottomLayout->setContentsMargins(LAYOUT_MARGINS); + bottomLayout->setContentsMargins(BOTTOM_LAYOUT_MARGINS); bottomLayout->setSpacing(BOTTOM_LAYOUT_SPACING); bottomLayout->addWidget(forgetBtn); bottomLayout->addStretch(); bottomLayout->addWidget(cancelBtn); bottomLayout->addWidget(confimBtn); + bottomWidget->setMinimumHeight(PAGE_MIN_HEIGHT); + + mainLayout->addWidget(pageFrame); + mainLayout->addWidget(centerWidget); + mainLayout->addWidget(bottomWidget); -// QPalette pal(this->palette()); -// pal.setColor(QPalette::Background, qApp->palette().base().color()); this->setAutoFillBackground(true); -// this->setPalette(pal); - onPaletteChanged(); } void NetDetail::loadPage() @@ -293,12 +406,12 @@ void NetDetail::loadPage() if (m_isCreateNet && !isWlan) { pageFrame->hide(); stackWidget->setCurrentIndex(CREATE_NET_PAGE_NUM); - this->setWindowTitle(tr("Add Lan Connect")); + this->setWindowTitle(tr("Add LAN Connect")); } else { stackWidget->setCurrentIndex(DETAIL_PAGE_NUM); this->setWindowTitle(m_name); if (isWlan && m_name.isEmpty()) { - this->setWindowTitle(tr("connect hiddin wlan")); + this->setWindowTitle(tr("Connect Hidden WLAN")); } } } @@ -310,7 +423,12 @@ void NetDetail::initComponent() }); connect(confimBtn, SIGNAL(clicked()), this, SLOT(on_btnConfirm_clicked())); - if (isWlan && !m_uuid.isEmpty()) { + if (!m_uuid.isEmpty()) { + if (isWlan) { + forgetBtn->setText(tr("Forget this network")); + } else { + forgetBtn->setText(tr("Delete this network")); + } forgetBtn->show(); connect(forgetBtn, SIGNAL(clicked()), this, SLOT(on_btnForget_clicked())); } else { @@ -341,6 +459,18 @@ void NetDetail::initComponent() isSecuOk = status; setConfirmEnable(); }); + + const QByteArray id(THEME_SCHAME); + if(QGSettings::isSchemaInstalled(id)){ + QGSettings * fontSetting = new QGSettings(id, QByteArray(), this); + connect(fontSetting, &QGSettings::changed,[=](QString key) { + if ("systemFont" == key || "systemFontSize" ==key) { + setNetTabToolTip(); + } else if ("themeColor" == key) { + onPaletteChanged(); + } + }); + } } void NetDetail::pagePadding(QString netName, bool isWlan) @@ -366,6 +496,7 @@ void NetDetail::pagePadding(QString netName, bool isWlan) ipv4Page->setIpv4Config(m_info.ipv4ConfigType); ipv4Page->setMulDns(m_info.ipv4DnsList); if (m_info.ipv4ConfigType == CONFIG_IP_MANUAL) { + Q_EMIT checkCurrentIpv4Conflict(m_info.strIPV4Address); ipv4Page->setIpv4(m_info.strIPV4Address); ipv4Page->setNetMask(m_info.strIPV4NetMask); ipv4Page->setGateWay(m_info.strIPV4GateWay); @@ -374,6 +505,7 @@ void NetDetail::pagePadding(QString netName, bool isWlan) ipv6Page->setIpv6Config(m_info.ipv6ConfigType); ipv6Page->setMulDns(m_info.ipv6DnsList); if (m_info.ipv6ConfigType == CONFIG_IP_MANUAL) { + Q_EMIT checkCurrentIpv6Conflict(m_info.strIPV6Address); ipv6Page->setIpv6(m_info.strIPV6Address); ipv6Page->setIpv6Perfix(m_info.iIPV6Prefix); ipv6Page->setGateWay(m_info.strIPV6GateWay); @@ -400,6 +532,10 @@ void NetDetail::pagePadding(QString netName, bool isWlan) } } + //配置页面 + if (isActive && m_networkMode != DBUS_INVAILD && m_networkMode != NO_CONFIG) { + configPage->setConfigState(m_networkMode); + } } //获取网路详情信息 @@ -523,6 +659,8 @@ void NetDetail::getStaticIpInfo(ConInfo &conInfo, bool bActived) // conInfo.ipv4ConfigType = connetSetting.m_ipv4ConfigIpType; conInfo.ipv6ConfigType = connetSetting.m_ipv6ConfigIpType; +// conInfo.ipv4DnsList = connetSetting.m_ipv4Dns; + conInfo.ipv6DnsList = connetSetting.m_ipv6Dns; conInfo.isAutoConnect = connetSetting.m_isAutoConnect; // if (connetSetting.m_ipv4ConfigIpType == CONFIG_IP_MANUAL) { @@ -539,7 +677,7 @@ void NetDetail::getStaticIpInfo(ConInfo &conInfo, bool bActived) // } // } //openkylin从第三方库读取有问题 改为ipv4信息直接通过dbus获取 - KyConnectItem* item = kyConnectResourse->getConnectionItemByUuid(m_uuid, false); + KyConnectItem* item = kyConnectResourse->getConnectionItemByUuidWithoutActivateChecking(m_uuid); if (item == nullptr) { conInfo.ipv4ConfigType = CONFIG_IP_DHCP; } else { @@ -554,8 +692,6 @@ void NetDetail::getStaticIpInfo(ConInfo &conInfo, bool bActived) } } - conInfo.ipv4DnsList = connetSetting.m_ipv4Dns; - conInfo.ipv6DnsList = connetSetting.m_ipv6Dns; QString dnsList; dnsList.clear(); if (!conInfo.ipv4DnsList.isEmpty()) { @@ -705,6 +841,7 @@ void NetDetail::setConfirmEnable() confimBtn->setEnabled(isConfirmBtnEnable); } +#if 0 bool NetDetail::checkIpv4Conflict(QString ipv4Address) { showDesktopNotify(tr("start check ipv4 address conflict"), "networkwrong"); @@ -738,6 +875,7 @@ bool NetDetail::checkIpv6Conflict(QString ipv6address) ipv46rping = nullptr; return isConflict; } +#endif void NetDetail::updateWirelessPersonalConnect() { @@ -776,13 +914,13 @@ bool NetDetail::createWiredConnect() KyWirelessConnectSetting connetSetting; connetSetting.setIfaceName(m_deviceName); createNetPage->constructIpv4Info(connetSetting); - if (connetSetting.m_ipv4ConfigIpType != CONFIG_IP_DHCP) { - if (checkIpv4Conflict(connetSetting.m_ipv4Address.at(0).ip().toString())) { - qDebug() << "ipv4 conflict"; - showDesktopNotify(tr("ipv4 address conflict!"), "networkwrong"); - return false; - } - } +// if (connetSetting.m_ipv4ConfigIpType != CONFIG_IP_DHCP) { +// if (checkIpv4Conflict(connetSetting.m_ipv4Address.at(0).ip().toString())) { +// qDebug() << "ipv4 conflict"; +// showDesktopNotify(tr("ipv4 address conflict!"), "networkwrong"); +// return false; +// } +// } m_wiredConnOperation->createWiredConnect(connetSetting); return true; } @@ -827,21 +965,21 @@ bool NetDetail::createWirelessConnect() connetSetting.dumpInfo(); qDebug() << "ipv4Changed" << ipv4Change << "ipv6Change" << ipv6Change; - if (ipv4Change && connetSetting.m_ipv4ConfigIpType == CONFIG_IP_MANUAL) { - if (checkIpv4Conflict(connetSetting.m_ipv4Address.at(0).ip().toString())) { - qDebug() << "ipv4 conflict"; - showDesktopNotify(tr("ipv4 address conflict!"), "networkwrong"); - return false; - } - } +// if (ipv4Change && connetSetting.m_ipv4ConfigIpType == CONFIG_IP_MANUAL) { +// if (checkIpv4Conflict(connetSetting.m_ipv4Address.at(0).ip().toString())) { +// qDebug() << "ipv4 conflict"; +// showDesktopNotify(tr("ipv4 address conflict!"), "networkwrong"); +// return false; +// } +// } - if (ipv6Change && connetSetting.m_ipv6ConfigIpType == CONFIG_IP_MANUAL) { - if (checkIpv6Conflict(connetSetting.m_ipv6Address.at(0).ip().toString())) { - qDebug() << "ipv6 conflict"; - showDesktopNotify(tr("ipv6 address conflict!"), "networkwrong"); - return false; - } - } +// if (ipv6Change && connetSetting.m_ipv6ConfigIpType == CONFIG_IP_MANUAL) { +// if (checkIpv6Conflict(connetSetting.m_ipv6Address.at(0).ip().toString())) { +// qDebug() << "ipv6 conflict"; +// showDesktopNotify(tr("ipv6 address conflict!"), "networkwrong"); +// return false; +// } +// } //wifi安全性 if (secuType == WPA_AND_WPA2_ENTERPRISE) { connetSetting.m_type = WpaEap; @@ -942,21 +1080,21 @@ bool NetDetail::updateConnect() qDebug() << "ipv4Changed" << ipv4Change << "ipv6Change" << ipv6Change; - if (ipv4Change && connetSetting.m_ipv4ConfigIpType == CONFIG_IP_MANUAL) { - if (checkIpv4Conflict(connetSetting.m_ipv4Address.at(0).ip().toString())) { - qDebug() << "ipv4 conflict"; - showDesktopNotify(tr("ipv4 address conflict!"), "networkwrong"); - return false; - } - } +// if (ipv4Change && connetSetting.m_ipv4ConfigIpType == CONFIG_IP_MANUAL) { +// if (checkIpv4Conflict(connetSetting.m_ipv4Address.at(0).ip().toString())) { +// qDebug() << "ipv4 conflict"; +// showDesktopNotify(tr("ipv4 address conflict!"), "networkwrong"); +// return false; +// } +// } - if (ipv6Change && connetSetting.m_ipv6ConfigIpType == CONFIG_IP_MANUAL) { - if (checkIpv6Conflict(connetSetting.m_ipv6Address.at(0).ip().toString())) { - qDebug() << "ipv6 conflict"; - showDesktopNotify(tr("ipv6 address conflict!"), "networkwrong"); - return false; - } - } +// if (ipv6Change && connetSetting.m_ipv6ConfigIpType == CONFIG_IP_MANUAL) { +// if (checkIpv6Conflict(connetSetting.m_ipv6Address.at(0).ip().toString())) { +// qDebug() << "ipv6 conflict"; +// showDesktopNotify(tr("ipv6 address conflict!"), "networkwrong"); +// return false; +// } +// } if (ipv4Change || ipv6Change) { connetSetting.dumpInfo(); @@ -982,6 +1120,18 @@ bool NetDetail::updateConnect() m_wirelessConnOpration->activateConnection(m_uuid, m_deviceName); } } + + if (m_networkMode != DBUS_INVAILD && m_networkMode != NO_CONFIG) { + int configType = NetworkModeConfig::getInstance()->getNetworkModeConfig(m_uuid); + bool configPageChange = configPage->checkIsChanged(configType); + int currentConfigType = configPage->getConfigState(); +// qDebug () << Q_FUNC_INFO << __LINE__<< configPageChange; + + if (configPageChange) { + NetworkModeConfig::getInstance()->setNetworkModeConfig(m_uuid, m_deviceName, m_name, currentConfigType); +// qDebug () <(event); if (mEvent->key() == Qt::Key_Enter || mEvent->key() == Qt::Key_Return) { if (confimBtn->isEnabled()) { - emit confimBtn->clicked(); + Q_EMIT confimBtn->clicked(); } return true; } else if (mEvent->key() == Qt::Key_Escape) { @@ -1027,6 +1177,145 @@ bool NetDetail::eventFilter(QObject *w, QEvent *event) return QWidget::eventFilter(w, event); } +void NetDetail::setNetTabToolTip() +{ + int tabCount = m_netTabBar->count(); + for (int i = 0; i< tabCount; ++i) { + QFontMetrics fontMetrics(m_netTabBar->font()); + int fontSize = fontMetrics.width(m_netTabBar->tabText(i)); + if (fontSize > MAX_TAB_TEXT_LENGTH) { + m_netTabBar->setTabToolTip(i, m_netTabBar->tabText(i)); + } else { + m_netTabBar->setTabToolTip(i, ""); + } + } +} + +NetTabBar::NetTabBar(QWidget *parent) + :KTabBar(KTabBarStyle::SegmentDark, parent) +{ + //模式切换 + QDBusConnection::sessionBus().connect(QString("com.kylin.statusmanager.interface"), + QString("/"), + QString("com.kylin.statusmanager.interface"), + QString("mode_change_signal"), this, SLOT(onModeChanged(bool))); + //模式获取 + QDBusInterface interface(QString("com.kylin.statusmanager.interface"), + QString("/"), + QString("com.kylin.statusmanager.interface"), + QDBusConnection::sessionBus()); + if(!interface.isValid()) { + this->setFixedHeight(TAB_HEIGHT); + return; + } + QDBusReply reply = interface.call("get_current_tabletmode"); + if (!reply.isValid()) { + this->setFixedHeight(TAB_HEIGHT); + return; + } + onModeChanged(reply.value()); +} + +NetTabBar::~NetTabBar() +{ + +} + +QSize NetTabBar::sizeHint() const +{ + QSize size = KTabBar::sizeHint(); + size.setWidth(TAB_WIDTH); + return size; +} + +QSize NetTabBar::minimumTabSizeHint(int index) const +{ + Q_UNUSED(index) + QSize size = KTabBar::minimumTabSizeHint(index); + size.setWidth(TAB_WIDTH); + return size; +} + +void NetTabBar::onModeChanged(bool mode) +{ + if (mode) { + this->setFixedHeight(TAB_HEIGHT_TABLET); // 平板模式 + } else { + this->setFixedHeight(TAB_HEIGHT); // PC模式 + } +} + + +ThreadObject::ThreadObject(QString deviceName, QObject *parent) + :m_devName(deviceName), QObject(parent) +{ + m_isStop = false; +} + +ThreadObject::~ThreadObject() +{ + +} + +void ThreadObject::stop() +{ + m_isStop = true; +} + +void ThreadObject::checkIpv4ConflictThread(const QString &ipv4Address) +{ + if (m_isStop) { + return; + } + bool isConflict = false; + KyIpv4Arping* ipv4Arping = new KyIpv4Arping(m_devName, ipv4Address); + if (ipv4Arping->ipv4ConflictCheck() >= 0) { + isConflict = ipv4Arping->ipv4IsConflict(); + if (isConflict) { + QString mac = ipv4Arping->getMacAddress(); + qDebug() << "conflict mac" << mac; + KyNetworkDeviceResourse resource; + QStringList devList,devList1,devList2; + resource.getNetworkDeviceList(NetworkManager::Device::Type::Ethernet, devList1); + resource.getNetworkDeviceList(NetworkManager::Device::Type::Wifi, devList2); + devList << devList1 << devList2; + for(int i = 0; i < devList.size(); ++i){ + QString hardAddress; + int band; + resource.getHardwareInfo(devList.at(i), hardAddress, band); + if (hardAddress == mac) { + qDebug() << "conflict local card" << devList.at(i); + isConflict = false; + } + } + } + } else { + qWarning() << "checkIpv4Conflict internal error"; + } + + delete ipv4Arping; + ipv4Arping = nullptr; + Q_EMIT ipv4IsConflict(isConflict); +} + +void ThreadObject::checkIpv6ConflictThread(const QString &ipv6Address) +{ + if (m_isStop) { + return; + } + bool isConflict = false; + KyIpv6Arping* ipv6rping = new KyIpv6Arping(m_devName, ipv6Address); + if (ipv6rping->ipv6ConflictCheck() >= 0) { + isConflict = ipv6rping->ipv6IsConflict(); + } else { + qWarning() << "checkIpv6Conflict internal error"; + } + + delete ipv6rping; + ipv6rping = nullptr; + Q_EMIT ipv6IsConflict(isConflict); +} + void NetDetail::getIpv4Info(QString objPath, ConInfo &conInfo) { QDBusInterface m_interface("org.freedesktop.NetworkManager", diff --git a/src/frontend/netdetails/netdetail.h b/src/frontend/netdetails/netdetail.h index c6dcb19e..61d81940 100644 --- a/src/frontend/netdetails/netdetail.h +++ b/src/frontend/netdetails/netdetail.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef NETDETAIL_H #define NETDETAIL_H @@ -13,6 +32,7 @@ #include #include #include +#include #include #include @@ -25,14 +45,54 @@ #include "ipv6page.h" #include "securitypage.h" #include "creatnetpage.h" +#include "configpage.h" #include "coninfo.h" #include "tab-pages/tabpage.h" #include "kwidget.h" #include "ktabbar.h" - +#include "networkmodeconfig.h" #include + using namespace kdk; +#define TAB_WIDTH 60 +#define TAB_HEIGHT 36 +#define TAB_HEIGHT_TABLET 48 + +class NetTabBar : public KTabBar +{ + Q_OBJECT +public: + explicit NetTabBar(QWidget *parent = nullptr); + ~NetTabBar(); +protected: + QSize sizeHint() const; + QSize minimumTabSizeHint(int index) const; + +private Q_SLOTS: + void onModeChanged(bool mode); + +}; +class ThreadObject : public QObject +{ + Q_OBJECT +public: + ThreadObject(QString deviceName, QObject *parent = nullptr); + ~ThreadObject(); + void stop(); +private: + QString m_devName; + volatile bool m_isStop; + +public Q_SLOTS: + void checkIpv4ConflictThread(const QString &ipv4Address); + void checkIpv6ConflictThread(const QString &ipv6Address); + +Q_SIGNALS: + bool ipv4IsConflict(bool isConflict); + bool ipv6IsConflict(bool isConflict); +}; + class NetDetail : public QWidget { Q_OBJECT @@ -40,14 +100,14 @@ class NetDetail : public QWidget public: NetDetail(QString interface, QString name, QString uuid, bool isActive, bool isWlan, bool isCreateNet, QWidget *parent = nullptr); ~NetDetail(); -protected: + void centerToScreen(); + void paintEvent(QPaintEvent *event); void closeEvent(QCloseEvent *event); bool eventFilter(QObject *w, QEvent *event); private: void initUI(); - void centerToScreen(); void initComponent(); void getConInfo(ConInfo &conInfo); void loadPage(); @@ -73,8 +133,8 @@ private: void setConfirmEnable(); - bool checkIpv4Conflict(QString ipv4Address); - bool checkIpv6Conflict(QString ipv6Address); +// bool checkIpv4Conflict(QString ipv4Address); +// bool checkIpv6Conflict(QString ipv6Address); bool createWiredConnect(); bool createWirelessConnect(); @@ -85,6 +145,8 @@ private: void showDesktopNotify(const QString &message, QString soundName); void setNetdetailSomeEnable(bool on); + void startObjectThread(); + void setNetTabToolTip(); void getIpv4Info(QString objPath, ConInfo &conInfo); private: @@ -101,16 +163,20 @@ private: Ipv6Page * ipv6Page; SecurityPage * securityPage; CreatNetPage * createNetPage; + ConfigPage * configPage; QWidget * centerWidget; QWidget * bottomWidget; + QScrollArea * m_secuPageScrollArea; + QScrollArea * m_ipv4ScrollArea; + QScrollArea * m_ipv6ScrollArea; QPushButton * cancelBtn; QPushButton * forgetBtn; QPushButton * confimBtn; QFrame * pageFrame; - KTabBar *m_netTabBar = nullptr; + NetTabBar *m_netTabBar = nullptr; QString m_name; QString m_uuid; @@ -130,20 +196,23 @@ private: ConInfo m_info; -private slots: + ThreadObject *m_object; + QThread *m_objectThread; + NetworkModeType m_networkMode = DBUS_INVAILD; + +private Q_SLOTS: void on_btnConfirm_clicked(); void on_btnForget_clicked(); void onPaletteChanged(); -protected slots: +protected Q_SLOTS: void currentRowChangeSlot(int row); -signals: - void detailPageClose(bool on); +Q_SIGNALS: + void detailPageClose(QString, QString, QString); void createPageClose(QString); void currentChanged(int); + void checkCurrentIpv4Conflict(const QString &address); + void checkCurrentIpv6Conflict(const QString &address); }; - - - #endif // NETDETAIL_H diff --git a/src/frontend/netdetails/netdetails.pri b/src/frontend/netdetails/netdetails.pri index f207a80f..f06fe245 100644 --- a/src/frontend/netdetails/netdetails.pri +++ b/src/frontend/netdetails/netdetails.pri @@ -1,6 +1,7 @@ INCLUDEPATH += $$PWD HEADERS += \ + $$PWD/configpage.h \ $$PWD/coninfo.h \ $$PWD/creatnetpage.h \ $$PWD/customtabstyle.h \ @@ -8,17 +9,20 @@ HEADERS += \ $$PWD/detailwidget.h \ $$PWD/ipv4page.h \ $$PWD/ipv6page.h \ + $$PWD/joinhiddenwifipage.h \ + $$PWD/multiplednswidget.h \ $$PWD/netdetail.h \ - $$PWD/securitypage.h \ - $$PWD/multiplednswidget.h + $$PWD/securitypage.h SOURCES += \ + $$PWD/configpage.cpp \ $$PWD/creatnetpage.cpp \ $$PWD/customtabstyle.cpp \ $$PWD/detailpage.cpp \ $$PWD/detailwidget.cpp \ $$PWD/ipv4page.cpp \ $$PWD/ipv6page.cpp \ + $$PWD/joinhiddenwifipage.cpp \ + $$PWD/multiplednswidget.cpp \ $$PWD/netdetail.cpp \ - $$PWD/securitypage.cpp \ - $$PWD/multiplednswidget.cpp + $$PWD/securitypage.cpp diff --git a/src/frontend/netdetails/securitypage.cpp b/src/frontend/netdetails/securitypage.cpp index daf95558..7a832cf6 100644 --- a/src/frontend/netdetails/securitypage.cpp +++ b/src/frontend/netdetails/securitypage.cpp @@ -1,9 +1,33 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "securitypage.h" #include "netdetail.h" #include -SecurityPage::SecurityPage(QWidget *parent) : QFrame(parent) +#define DETAIL_MIN_LABEL_WIDTH 80 +#define DETAIL_MIN_EDIT_WIDTH 390 +#define MIN_LABEL_WIDTH 146 +#define MIN_EDIT_WIDTH 286 + +SecurityPage::SecurityPage(bool isNetDetailPage, QWidget *parent) : isDetailPage(isNetDetailPage), QFrame(parent) { initUI(); initConnect(); @@ -11,8 +35,7 @@ SecurityPage::SecurityPage(QWidget *parent) : QFrame(parent) void SecurityPage::initUI() { - secuTypeLabel = new QLabel(this); - pwdLabel = new QLabel(this); + mainLayout = new QVBoxLayout(this); secuTypeLabel = new QLabel(this); pwdLabel = new QLabel(this); //企业wifi共有 @@ -22,18 +45,25 @@ void SecurityPage::initUI() domainLable = new QLabel(this); caCertPathLabel = new QLabel(this); caNeedFlagLabel = new QLabel(this); - clientCertPathLabel = new QLabel(this); - clientPrivateKeyLabel = new QLabel(this); - clientPrivateKeyPwdLabel = new QLabel(this); + clientCertPathLabel = new FixLabel(this); + clientCertPathLabel->setFixedWidth(MIN_LABEL_WIDTH); + clientPrivateKeyLabel = new FixLabel(this); + clientPrivateKeyLabel->setFixedWidth(MIN_LABEL_WIDTH); + clientPrivateKeyPwdLabel = new FixLabel(this); + clientPrivateKeyPwdLabel->setFixedWidth(MIN_LABEL_WIDTH); + pwdOptionLabel = new FixLabel(this); + pwdOptionLabel->setFixedWidth(MIN_LABEL_WIDTH); //PEAP TTLS共有 - eapMethodLabel = new QLabel(this); + eapMethodLabel = new FixLabel(this); + eapMethodLabel->setFixedWidth(MIN_LABEL_WIDTH); userNameLabel = new QLabel(this); userPwdLabel = new QLabel(this); userPwdFlagLabel = new QLabel(this); secuTypeCombox = new QComboBox(this); pwdEdit = new KPasswordEdit(this); + pwdEdit->setUseCustomPalette(true); eapTypeCombox = new QComboBox(this); //TLS identityEdit = new LineEdit(this); @@ -43,43 +73,150 @@ void SecurityPage::initUI() clientCertPathCombox = new QComboBox(this); clientPrivateKeyCombox = new QComboBox(this); clientPrivateKeyPwdEdit = new KPasswordEdit(this); + clientPrivateKeyPwdEdit->setUseCustomPalette(true); + pwdOptionCombox = new QComboBox(this); + tlsWidget = new QWidget(this); //PEAP && TTLS eapMethodCombox = new QComboBox(this); userNameEdit = new LineEdit(this); userPwdEdit = new KPasswordEdit(this); + userPwdEdit->setUseCustomPalette(true); userPwdFlagBox = new QCheckBox(this); + QWidget *queryWidget = new QWidget(this); + QHBoxLayout *queryLayout = new QHBoxLayout(queryWidget); + queryLayout->setContentsMargins(0, 0, 0, 0); + queryLayout->addWidget(userPwdFlagBox); + queryLayout->addWidget(userPwdFlagLabel); + queryLayout->addStretch(); + //FAST m_pacCheckBox = new QCheckBox(this); m_pacProvisionComboBox = new QComboBox(this); m_pacFilePathComboBox = new QComboBox(this); m_pacProvisionLabel = new FixLabel(this); + m_pacProvisionLabel->setFixedWidth(MIN_LABEL_WIDTH); m_pacFlagLabel = new FixLabel(this); m_pacFileLabel = new QLabel(this); - mSecuLayout = new QFormLayout(this); - mSecuLayout->addRow(secuTypeLabel, secuTypeCombox); - mSecuLayout->addRow(pwdLabel, pwdEdit); - mSecuLayout->addRow(eapTypeLabel, eapTypeCombox); - mSecuLayout->addRow(identityLable, identityEdit); - mSecuLayout->addRow(domainLable, domainEdit); - mSecuLayout->addRow(caCertPathLabel, caCertPathCombox); - mSecuLayout->addRow(caNeedBox, caNeedFlagLabel); - mSecuLayout->addRow(clientCertPathLabel, clientCertPathCombox); - mSecuLayout->addRow(clientPrivateKeyLabel, clientPrivateKeyCombox); - mSecuLayout->addRow(clientPrivateKeyPwdLabel,clientPrivateKeyPwdEdit); - mSecuLayout->addRow(m_pacProvisionLabel,m_pacProvisionComboBox); - mSecuLayout->addRow(m_pacCheckBox,m_pacFlagLabel); - mSecuLayout->addRow(m_pacFileLabel,m_pacFilePathComboBox); - mSecuLayout->addRow(eapMethodLabel, eapMethodCombox); - mSecuLayout->addRow(userNameLabel, userNameEdit); - mSecuLayout->addRow(userPwdLabel, userPwdEdit); - mSecuLayout->addRow(userPwdFlagBox, userPwdFlagLabel); + //记住该网络复选框 + m_emptyLabel = new QLabel(this); + m_emptyLabel->setMinimumWidth(MIN_LABEL_WIDTH - 8); + m_checkLabel = new QLabel(this); + m_checkLabel->setText(tr("Remember the Network")); //记住该网络 + m_rememberCheckBox = new QCheckBox(this); + m_rememberCheckBox->setChecked(true); + QWidget *checkWidget = new QWidget(this); + QHBoxLayout *rememberLayout = new QHBoxLayout(checkWidget); + rememberLayout->setContentsMargins(0, 0, 0, 0); + rememberLayout->addWidget(m_emptyLabel); + rememberLayout->addWidget(m_rememberCheckBox); + rememberLayout->addWidget(m_checkLabel); + rememberLayout->addStretch(); + //允许自动PAC配置复选框 + m_pacCheckWidget = new QWidget(this); + QGridLayout *pacCheckLayout = new QGridLayout(m_pacCheckWidget); + pacCheckLayout->setContentsMargins(0, 0, 0, 0); + pacCheckLayout->setVerticalSpacing(0); + pacCheckLayout->setColumnMinimumWidth(0, 16); + pacCheckLayout->addWidget(m_pacProvisionComboBox, 0, 0, 1, 2); + pacCheckLayout->addWidget(m_pacCheckBox, 1, 0); + pacCheckLayout->addWidget(m_pacFlagLabel, 1, 1); + + topLayout = new QGridLayout(); + topLayout->setContentsMargins(0, 0, 0, 0); + topLayout->setVerticalSpacing(16); + // 安全 Label和选项框 第0行,第0列,第1列 + topLayout->addWidget(secuTypeLabel, 0, 0); + topLayout->addWidget(secuTypeCombox, 0, 1); + //密码 Label和密码框 第1行,第0列,第1列 + topLayout->addWidget(pwdLabel, 1, 0); + topLayout->addWidget(pwdEdit, 1, 1); + // EAP认证 Label和选项框 第2行,第0列,第1列 + topLayout->addWidget(eapTypeLabel, 2, 0); + topLayout->addWidget(eapTypeCombox, 2, 1); + // 匿名身份 Label和输入框 第3行,第0列,第1列 + topLayout->addWidget(identityLable, 3, 0); + topLayout->addWidget(identityEdit, 3, 1); + //PAC配置 允许自动PAC配置 第4行,第0列;第4行,第1列,占2行1列 + topLayout->addWidget(m_pacProvisionLabel, 4, 0, Qt::AlignTop); + topLayout->addWidget(m_pacCheckWidget, 4, 1); + // PAC文件 + topLayout->addWidget(m_pacFileLabel, 6, 0); + topLayout->addWidget(m_pacFilePathComboBox, 6, 1); + //内部认证 Label和选项框 + topLayout->addWidget(eapMethodLabel, 7, 0); + topLayout->addWidget(eapMethodCombox, 7, 1); + //用户名 Label和输入框 + topLayout->addWidget(userNameLabel, 8, 0); + topLayout->addWidget(userNameEdit, 8, 1); + //密码 Label和密码框 + topLayout->addWidget(userPwdLabel, 9, 0); + topLayout->addWidget(userPwdEdit, 9, 1); + + + // CA证书选项框及CheckBox布局 + QWidget *caWidget = new QWidget(this); + QGridLayout *checkLayout = new QGridLayout(caWidget); + checkLayout->setContentsMargins(0, 0, 0, 0); + checkLayout->setVerticalSpacing(0); + checkLayout->setColumnMinimumWidth(0, 16); + checkLayout->addWidget(caCertPathCombox, 0, 0, 1, 2); + checkLayout->addWidget(caNeedBox, 1, 0); + checkLayout->addWidget(caNeedFlagLabel, 1, 1); + + bottomLayout = new QGridLayout(tlsWidget); + bottomLayout->setContentsMargins(0, 0, 0, 0); + bottomLayout->setVerticalSpacing(8); + bottomLayout->setHorizontalSpacing(0); + // 域 Label和输入框 第0行,第0列,第1列 + bottomLayout->addWidget(domainLable, 0, 0); + bottomLayout->addWidget(domainEdit, 0, 1); + + // CA证书 Label第1行,第0列 + bottomLayout->addWidget(caCertPathLabel, 1, 0); + // CA证书选项框 不需要CA证书复选框 从第1行,第1列开始,占2行1列 + bottomLayout->addWidget(caWidget, 1, 1, 2, 1); + // 用户证书 Label和选项框 第3行,第0列,第1列 + bottomLayout->addWidget(clientCertPathLabel, 3, 0); + bottomLayout->addWidget(clientCertPathCombox, 3, 1); + // 用户私钥 Label和选项框 第4行,第0列,第1列 + bottomLayout->addWidget(clientPrivateKeyLabel, 4, 0); + bottomLayout->addWidget(clientPrivateKeyCombox, 4, 1); + // 私钥密码 Label和密码框 第5行,第0列,第1列 + bottomLayout->addWidget(clientPrivateKeyPwdLabel, 5, 0); + bottomLayout->addWidget(clientPrivateKeyPwdEdit, 5, 1); + // 密码选项 Label和选项框 第6行,第0列,第1列 + bottomLayout->addWidget(pwdOptionLabel, 6, 0); + bottomLayout->addWidget(pwdOptionCombox, 6, 1); + + if (isDetailPage) { + checkWidget->hide(); + topLayout->addWidget(queryWidget, 10, 1); + changeColumnWidthWithSecuType(); + m_pacFlagLabel->setMinimumWidth(MIN_EDIT_WIDTH); + } else { + queryWidget->hide(); + topLayout->setColumnMinimumWidth(0, MIN_LABEL_WIDTH); + topLayout->setColumnMinimumWidth(1, MIN_EDIT_WIDTH); + bottomLayout->setColumnMinimumWidth(0, MIN_LABEL_WIDTH - 8); + m_pacFlagLabel->setMinimumWidth(MIN_EDIT_WIDTH - 36); + } + + topLayout->addWidget(tlsWidget, 10, 0, 6, 2); + + mainLayout->setContentsMargins(0, 0, 0, 0); + mainLayout->setSpacing(0); + mainLayout->addLayout(topLayout); + mainLayout->addWidget(checkWidget); + mainLayout->addStretch(); secuTypeLabel->setText(tr("Security")); pwdLabel->setText(tr("Password")); + pwdEdit->setPlaceholderText(hintRequired); + //企业wifi共有 eapTypeLabel->setText(tr("EAP type")); //TLS @@ -87,15 +224,20 @@ void SecurityPage::initUI() domainLable->setText(tr("Domain")); caCertPathLabel->setText(tr("CA certficate")); caNeedFlagLabel->setText(tr("no need for CA certificate")); - clientCertPathLabel->setText(tr("User certificate")); - clientPrivateKeyLabel->setText(tr("User private key")); - clientPrivateKeyPwdLabel->setText(tr("User key password")); + clientCertPathLabel->setLabelText(tr("User certificate")); + clientPrivateKeyLabel->setLabelText(tr("User private key")); + clientPrivateKeyPwdLabel->setLabelText(tr("User key password")); + pwdOptionLabel->setLabelText(tr("Password options")); + identityEdit->setPlaceholderText(tr("Required")); + clientPrivateKeyPwdEdit->setPlaceholderText(hintRequired); //PEAP TTLS共有 - eapMethodLabel->setText(tr("Ineer authentication")); - userNameLabel->setText(tr("Usename")); + eapMethodLabel->setLabelText(tr("Ineer authentication")); + userNameLabel->setText(tr("Username")); userPwdLabel->setText(tr("Password")); userPwdFlagLabel->setText(tr("Ask pwd each query")); + userNameEdit->setPlaceholderText(tr("Required")); + userPwdEdit->setPlaceholderText(hintRequired); secuTypeCombox->addItem(tr("None"),NONE); secuTypeCombox->addItem(tr("WPA&WPA2 Personal"),WPA_AND_WPA2_PERSONAL); @@ -119,10 +261,18 @@ void SecurityPage::initUI() clientPrivateKeyCombox->addItem(tr("None"), QString(tr("None"))); //无 clientPrivateKeyCombox->addItem(tr("Choose from file..."), QString(tr("Choose from file..."))); //从文件中选择... + //仅为该用户存储密码 + pwdOptionCombox->addItem(tr("Store passwords only for this user"), QString(tr("Store password only for this user"))); + //存储所有用户的密码 + pwdOptionCombox->addItem(tr("Store passwords for all users"), QString(tr("Store password for all users"))); + //每次询问这个密码 + pwdOptionCombox->addItem(tr("Ask this password every time"), QString(tr("Ask password every time"))); + pwdOptionCombox->setCurrentIndex(1); + //FAST m_pacCheckBox->setChecked(true); - m_pacProvisionLabel->setText(tr("PAC provisioning")); //PAC配置 - m_pacFlagLabel->setText(tr("Allow automatic PAC provisioning")); //允许自动PAC配置 + m_pacProvisionLabel->setLabelText(tr("PAC provisioning")); //PAC配置 + m_pacFlagLabel->setLabelText(tr("Allow automatic PAC provisioning")); //允许自动PAC配置 m_pacFileLabel->setText(tr("PAC file")); //PAC文件 m_pacProvisionComboBox->addItem(tr("Anonymous"), ANON); //匿名 m_pacProvisionComboBox->addItem(tr("Authenticated"), AUTHEN); //已认证 @@ -150,6 +300,8 @@ void SecurityPage::initConnect() //安全类型变化 // connect(secuTypeCombox, &QComboBox::currentTextChanged, this, &SecurityPage::onSecuTypeComboxIndexChanged); connect(secuTypeCombox, QOverload::of(&QComboBox::currentIndexChanged), this, &SecurityPage::onSecuTypeComboxIndexChanged); + + connect(secuTypeCombox, QOverload::of(&QComboBox::currentIndexChanged), this, &SecurityPage::changeColumnWidthWithSecuType); //EAP方式变化 // connect(eapTypeCombox, &QComboBox::currentTextChanged, this, &SecurityPage::onEapTypeComboxIndexChanged); connect(eapTypeCombox, QOverload::of(&QComboBox::currentIndexChanged), this, &SecurityPage::onEapTypeComboxIndexChanged); @@ -165,6 +317,9 @@ void SecurityPage::initConnect() connect(clientPrivateKeyCombox, static_cast(&QComboBox::currentIndexChanged), this, &SecurityPage::onClientPrivateKeyComboxIndexChanged); + connect(pwdOptionCombox, static_cast(&QComboBox::currentIndexChanged), + this, &SecurityPage::onPwdOptionComboxIndexChanged); + connect(secuTypeCombox, SIGNAL(currentIndexChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(pwdEdit, &LineEdit::textChanged, this, &SecurityPage::setEnableOfSaveBtn); connect(eapTypeCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(setEnableOfSaveBtn())); @@ -226,6 +381,13 @@ void SecurityPage::setTlsInfo(KyEapMethodTlsInfo &info) clientPrivateKeyPwdEdit->setText(info.clientPrivateKeyPWD); + if (info.m_privateKeyPWDFlag == NetworkManager::Setting::AgentOwned) { + pwdOptionCombox->setCurrentIndex(0); + } else if (info.m_privateKeyPWDFlag == NetworkManager::Setting::None) { + pwdOptionCombox->setCurrentIndex(1); + } else { + pwdOptionCombox->setCurrentIndex(2); + } } void SecurityPage::setPeapInfo(KyEapMethodPeapInfo &info) @@ -320,22 +482,28 @@ void SecurityPage::setFastInfo(KyEapMethodFastInfo &info) onEapTypeComboxIndexChanged(); identityEdit->setText(info.m_anonIdentity); - if (info.m_pacProvisioning == KyFastProvisioningAllowUnauthenticated) { + m_pacCheckBox->setChecked(false); + m_pacProvisionComboBox->setCurrentIndex(ANON); + if (info.m_pacProvisioning == KyFastProvisioningDisabled) { + m_pacCheckBox->setChecked(false); + m_pacProvisionComboBox->setCurrentIndex(ANON); + m_pacProvisionComboBox->setEnabled(false); + } else if (info.m_pacProvisioning == KyFastProvisioningAllowUnauthenticated) { m_pacProvisionComboBox->setCurrentIndex(ANON); } else if (info.m_pacProvisioning == KyFastProvisioningAllowAuthenticated) { m_pacProvisionComboBox->setCurrentIndex(AUTHEN); } else if (info.m_pacProvisioning == KyFastProvisioningAllowBoth) { m_pacProvisionComboBox->setCurrentIndex(BOTH); + } else { + qWarning() << "Unknown fastProvisioning type" << Q_FUNC_INFO << __LINE__; + m_pacCheckBox->setChecked(false); + m_pacProvisionComboBox->setEnabled(false); } if (info.m_pacFilePath.isEmpty()) { m_pacFilePathComboBox->setItemText(0, QString(tr("None"))); - m_pacCheckBox->setChecked(true); - m_pacFilePathComboBox->setEnabled(false); } else { m_pacFilePathComboBox->setItemText(0, info.m_pacFilePath); - m_pacCheckBox->setChecked(false); - m_pacFilePathComboBox->setEnabled(true); } if (info.m_authMethod == KyAuthMethodGtc) { @@ -427,6 +595,12 @@ void SecurityPage::getSecuType(KySecuType &secuType, KyEapMethodType &enterprise enterpriseType = (KyEapMethodType)eapTypeCombox->currentData().toInt(); } +bool SecurityPage::getAutoConnectState() +{ + bool state = m_rememberCheckBox->isChecked(); + return state; +} + bool SecurityPage::checkIsChanged(const ConInfo info) { if (info.secType != secuTypeCombox->currentData().toInt()) { @@ -460,272 +634,188 @@ bool SecurityPage::checkIsChanged(const ConInfo info) void SecurityPage::showNone() { - pwdEdit->hide(); - eapTypeCombox->hide(); - - identityEdit->hide(); - domainEdit->hide(); - caCertPathCombox->hide(); - caNeedBox->hide(); - clientCertPathCombox->hide(); - clientPrivateKeyCombox->hide(); - clientPrivateKeyPwdEdit->hide(); - - eapMethodCombox->hide(); - userNameEdit->hide(); - userPwdEdit->hide(); - userPwdFlagBox->hide(); - pwdLabel->hide(); + pwdEdit->hide(); //企业wifi共有 eapTypeLabel->hide(); + eapTypeCombox->hide(); + //TLS identityLable->hide(); - domainLable->hide(); - caCertPathLabel->hide(); - caNeedFlagLabel->hide(); - clientCertPathLabel->hide(); - clientPrivateKeyLabel->hide(); - clientPrivateKeyPwdLabel->hide(); + identityEdit->hide(); + tlsWidget->hide(); //PEAP TTLS共有 eapMethodLabel->hide(); userNameLabel->hide(); userPwdLabel->hide(); + userPwdFlagBox->hide(); + + eapMethodCombox->hide(); + userNameEdit->hide(); + userPwdEdit->hide(); userPwdFlagLabel->hide(); //FAST - m_pacCheckBox->hide(); - m_pacProvisionComboBox->hide(); - m_pacFilePathComboBox->hide(); m_pacProvisionLabel->hide(); - m_pacFlagLabel->hide(); + m_pacCheckWidget->hide(); m_pacFileLabel->hide(); + m_pacFilePathComboBox->hide(); } void SecurityPage::showPsk() { - pwdEdit->show(); - eapTypeCombox->hide(); - - identityEdit->hide(); - domainEdit->hide(); - caCertPathCombox->hide(); - caNeedBox->hide(); - clientCertPathCombox->hide(); - clientPrivateKeyCombox->hide(); - clientPrivateKeyPwdEdit->hide(); - - eapMethodCombox->hide(); - userNameEdit->hide(); - userPwdEdit->hide(); - userPwdFlagBox->hide(); - pwdLabel->show(); + pwdEdit->show(); //企业wifi共有 eapTypeLabel->hide(); + eapTypeCombox->hide(); + //TLS identityLable->hide(); - domainLable->hide(); - caCertPathLabel->hide(); - caNeedFlagLabel->hide(); - clientCertPathLabel->hide(); - clientPrivateKeyLabel->hide(); - clientPrivateKeyPwdLabel->hide(); + identityEdit->hide(); + tlsWidget->hide(); //PEAP TTLS共有 eapMethodLabel->hide(); userNameLabel->hide(); userPwdLabel->hide(); + userPwdFlagBox->hide(); + + eapMethodCombox->hide(); + userNameEdit->hide(); + userPwdEdit->hide(); userPwdFlagLabel->hide(); //FAST - m_pacCheckBox->hide(); - m_pacProvisionComboBox->hide(); - m_pacFilePathComboBox->hide(); m_pacProvisionLabel->hide(); - m_pacFlagLabel->hide(); + m_pacCheckWidget->hide(); m_pacFileLabel->hide(); + m_pacFilePathComboBox->hide(); } void SecurityPage::showTls() { + pwdLabel->hide(); pwdEdit->hide(); eapTypeCombox->show(); - - identityEdit->show(); - domainEdit->show(); - caCertPathCombox->show(); - caNeedBox->show(); - clientCertPathCombox->show(); - clientPrivateKeyCombox->show(); - clientPrivateKeyPwdEdit->show(); - - eapMethodCombox->hide(); - userNameEdit->hide(); - userPwdEdit->hide(); - userPwdFlagBox->hide(); - - pwdLabel->hide(); - //企业wifi共有 eapTypeLabel->show(); + //TLS identityLable->show(); - domainLable->show(); - caCertPathLabel->show(); - caNeedFlagLabel->show(); - clientCertPathLabel->show(); - clientPrivateKeyLabel->show(); - clientPrivateKeyPwdLabel->show(); + identityEdit->show(); + tlsWidget->show(); //PEAP TTLS共有 eapMethodLabel->hide(); userNameLabel->hide(); userPwdLabel->hide(); + userPwdFlagBox->hide(); + + eapMethodCombox->hide(); + userNameEdit->hide(); + userPwdEdit->hide(); userPwdFlagLabel->hide(); //FAST - m_pacCheckBox->hide(); - m_pacProvisionComboBox->hide(); - m_pacFilePathComboBox->hide(); m_pacProvisionLabel->hide(); - m_pacFlagLabel->hide(); + m_pacCheckWidget->hide(); m_pacFileLabel->hide(); + m_pacFilePathComboBox->hide(); } void SecurityPage::showPeapOrTtls() { - pwdEdit->hide(); - eapTypeCombox->show(); - - identityEdit->hide(); - domainEdit->hide(); - caCertPathCombox->hide(); - caNeedBox->hide(); - clientCertPathCombox->hide(); - clientPrivateKeyCombox->hide(); - clientPrivateKeyPwdEdit->hide(); - - eapMethodCombox->show(); - userNameEdit->show(); - userPwdEdit->show(); - userPwdFlagBox->show(); - pwdLabel->hide(); + pwdEdit->hide(); + //企业wifi共有 eapTypeLabel->show(); + eapTypeCombox->show(); + //TLS identityLable->hide(); - domainLable->hide(); - caCertPathLabel->hide(); - caNeedFlagLabel->hide(); - clientCertPathLabel->hide(); - clientPrivateKeyLabel->hide(); - clientPrivateKeyPwdLabel->hide(); + identityEdit->hide(); + tlsWidget->hide(); //PEAP TTLS共有 eapMethodLabel->show(); userNameLabel->show(); userPwdLabel->show(); + userPwdFlagBox->show(); + + eapMethodCombox->show(); + userNameEdit->show(); + userPwdEdit->show(); userPwdFlagLabel->show(); //FAST - m_pacCheckBox->hide(); - m_pacProvisionComboBox->hide(); - m_pacFilePathComboBox->hide(); m_pacProvisionLabel->hide(); - m_pacFlagLabel->hide(); + m_pacCheckWidget->hide(); m_pacFileLabel->hide(); + m_pacFilePathComboBox->hide(); } void SecurityPage::showLeapOrPwd() { - pwdEdit->hide(); - eapTypeCombox->show(); - - identityEdit->hide(); - domainEdit->hide(); - caCertPathCombox->hide(); - caNeedBox->hide(); - clientCertPathCombox->hide(); - clientPrivateKeyCombox->hide(); - clientPrivateKeyPwdEdit->hide(); - - eapMethodCombox->hide(); - userNameEdit->show(); - userPwdEdit->show(); - userPwdFlagBox->show(); - pwdLabel->hide(); + pwdEdit->hide(); + //企业wifi共有 eapTypeLabel->show(); + eapTypeCombox->show(); + //TLS identityLable->hide(); - domainLable->hide(); - caCertPathLabel->hide(); - caNeedFlagLabel->hide(); - clientCertPathLabel->hide(); - clientPrivateKeyLabel->hide(); - clientPrivateKeyPwdLabel->hide(); - - //PEAP TTLS共有 - eapMethodLabel->hide(); - userNameLabel->show(); - userPwdLabel->show(); - userPwdFlagLabel->show(); + identityEdit->hide(); + tlsWidget->hide(); //FAST - m_pacCheckBox->hide(); - m_pacProvisionComboBox->hide(); - m_pacFilePathComboBox->hide(); m_pacProvisionLabel->hide(); - m_pacFlagLabel->hide(); + m_pacCheckWidget->hide(); m_pacFileLabel->hide(); + m_pacFilePathComboBox->hide(); + + eapMethodLabel->hide(); + eapMethodCombox->hide(); + userPwdFlagBox->show(); + userPwdFlagLabel->show(); + + userNameLabel->show(); + userNameEdit->show(); + userPwdLabel->show(); + userPwdEdit->show(); } void SecurityPage::showFast() { - pwdEdit->hide(); - eapTypeCombox->show(); - - identityEdit->show(); - domainEdit->hide(); - caCertPathCombox->hide(); - caNeedBox->hide(); - clientCertPathCombox->hide(); - clientPrivateKeyCombox->hide(); - clientPrivateKeyPwdEdit->hide(); - - eapMethodCombox->show(); - userNameEdit->show(); - userPwdEdit->show(); - userPwdFlagBox->hide(); - pwdLabel->hide(); + pwdEdit->hide(); + //企业wifi共有 eapTypeLabel->show(); + eapTypeCombox->show(); + //TLS identityLable->show(); - domainLable->hide(); - caCertPathLabel->hide(); - caNeedFlagLabel->hide(); - clientCertPathLabel->hide(); - clientPrivateKeyLabel->hide(); - clientPrivateKeyPwdLabel->hide(); - - //PEAP TTLS共有 - eapMethodLabel->show(); - userNameLabel->show(); - userPwdLabel->show(); - userPwdFlagLabel->hide(); + identityEdit->show(); + tlsWidget->hide(); //FAST - m_pacCheckBox->show(); - m_pacProvisionComboBox->show(); - m_pacFilePathComboBox->show(); m_pacProvisionLabel->show(); - m_pacFlagLabel->show(); + m_pacCheckWidget->show(); m_pacFileLabel->show(); + m_pacFilePathComboBox->show(); + + eapMethodLabel->show(); + eapMethodCombox->show(); + userPwdFlagBox->show(); + userPwdFlagLabel->show(); + + userNameLabel->show(); + userNameEdit->show(); + userPwdLabel->show(); + userPwdEdit->show(); } KyEapMethodTlsInfo SecurityPage::assembleTlsInfo() @@ -738,8 +828,19 @@ KyEapMethodTlsInfo SecurityPage::assembleTlsInfo() info.clientCertPath = clientCertPathCombox->currentText(); info.clientPrivateKey = clientPrivateKeyCombox->currentText(); info.clientPrivateKeyPWD = clientPrivateKeyPwdEdit->text(); - info.m_privateKeyPWDFlag = NetworkManager::Setting::None; - + switch (pwdOptionCombox->currentIndex()) { + case 0: + info.m_privateKeyPWDFlag = NetworkManager::Setting::AgentOwned; + break; + case 1: + info.m_privateKeyPWDFlag = NetworkManager::Setting::None; + break; + case 2: + info.m_privateKeyPWDFlag = NetworkManager::Setting::NotSaved; + break; + default: + break; + } return info; } @@ -877,6 +978,7 @@ void SecurityPage::updateSecurityChange(KyWirelessConnectSetting &setting) } else if (secuTypeCombox->currentData().toInt() == WPA3_PERSONAL) { setting.m_type = SAE; } + setting.isAutoConnect = m_rememberCheckBox->isChecked(); } bool SecurityPage::checkConnectBtnIsEnabled() @@ -924,13 +1026,11 @@ bool SecurityPage::checkConnectBtnIsEnabled() return false; } } else if (type == FAST) { - if (identityEdit->text().isEmpty()) { - qDebug() << "fast anonymous identity is empty"; - return false; - } if(!m_pacCheckBox->isChecked()) { - qDebug() << "Not allow automatic PAC provisioning "; - return false; + if (m_pacFilePathComboBox->currentText() == QString(tr("None"))) { + qDebug() << "Not allow automatic PAC provisioning && pac file is empty"; + return false; + } } if(userNameEdit->text().isEmpty() || userPwdEdit->text().isEmpty()) { qDebug() << "user name or user password is empty"; @@ -943,18 +1043,25 @@ bool SecurityPage::checkConnectBtnIsEnabled() void SecurityPage::setEnableOfSaveBtn() { - emit setSecuPageState(checkConnectBtnIsEnabled()); + Q_EMIT setSecuPageState(checkConnectBtnIsEnabled()); } void SecurityPage::onSecuTypeComboxIndexChanged() { int index = secuTypeCombox->currentData().toInt(); - if (index == WPA_AND_WPA2_PERSONAL || index == WPA3_PERSONAL) { + if (index == WPA_AND_WPA2_PERSONAL) { showPsk(); + Q_EMIT this->secuTypeChanged(WPA_AND_WPA2_PERSONAL); + } + else if (index == WPA3_PERSONAL) { + showPsk(); + Q_EMIT this->secuTypeChanged(WPA3_PERSONAL); } else if (index == WPA_AND_WPA2_ENTERPRISE) { onEapTypeComboxIndexChanged(); + Q_EMIT this->secuTypeChanged(WPA_AND_WPA2_ENTERPRISE); } else if (index == NONE) { showNone(); + Q_EMIT this->secuTypeChanged(NONE); } } @@ -964,14 +1071,14 @@ void SecurityPage::onEapTypeComboxIndexChanged() int index = eapTypeCombox->currentData().toInt(); if (index == TLS) { showTls(); - emit this->eapTypeChanged(TLS); + Q_EMIT this->eapTypeChanged(TLS); } else if (index == PEAP) { showPeapOrTtls(); eapMethodCombox->clear(); eapMethodCombox->addItem("MSCHAPv2", MSCHAPV2_PEAP); eapMethodCombox->addItem("MD5", MD5_PEAP); eapMethodCombox->addItem("GTC", GTC_PEAP); - emit this->eapTypeChanged(PEAP); + Q_EMIT this->eapTypeChanged(PEAP); } else if (index == TTLS) { showPeapOrTtls(); eapMethodCombox->clear(); @@ -982,19 +1089,19 @@ void SecurityPage::onEapTypeComboxIndexChanged() eapMethodCombox->addItem("chap", CHAP); eapMethodCombox->addItem("md5(eap)", MD5_EAP); eapMethodCombox->addItem("gtc(eap)", GTC_EAP); - emit this->eapTypeChanged(TTLS); - } else if (index == LEAP) { + Q_EMIT this->eapTypeChanged(TTLS); + } else if (index == LEAP) { showLeapOrPwd(); - emit this->eapTypeChanged(LEAP); + Q_EMIT this->eapTypeChanged(LEAP); } else if (index == PWD) { showLeapOrPwd(); - emit this->eapTypeChanged(PWD); + Q_EMIT this->eapTypeChanged(PWD); } else if (index == FAST) { showFast(); eapMethodCombox->clear(); eapMethodCombox->addItem("GTC", GTC_FAST); eapMethodCombox->addItem("MSCHAPv2", MSCHAPV2_FAST); - emit this->eapTypeChanged(FAST); + Q_EMIT this->eapTypeChanged(FAST); } } @@ -1086,6 +1193,39 @@ void SecurityPage::onClientPrivateKeyComboxIndexChanged(QString str) } } +void SecurityPage::onPwdOptionComboxIndexChanged(QString str) +{ + KyEapMethodTlsInfo info; + if (str.contains("Store passwords only for this user") || str.contains("仅为该用户存储密码")) { + info.m_privateKeyPWDFlag = NetworkManager::Setting::AgentOwned; + clientPrivateKeyPwdEdit->setPlaceholderText(emptyhint); + } else if (str.contains("Store passwords for all users") || str.contains("存储所有用户的密码")) { + info.m_privateKeyPWDFlag = NetworkManager::Setting::None; + clientPrivateKeyPwdEdit->setPlaceholderText(hintRequired); + } else { + info.m_privateKeyPWDFlag = NetworkManager::Setting::NotSaved; + clientPrivateKeyPwdEdit->setPlaceholderText(emptyhint); + } +} + +void SecurityPage::changeColumnWidthWithSecuType() +{ + if (!isDetailPage) { + return; + } + if (secuTypeCombox->currentData().toInt() == WPA_AND_WPA2_ENTERPRISE) { + if (eapMethodCombox->currentData().toInt() == TLS || eapMethodCombox->currentData().toInt() == FAST) { + topLayout->setColumnMinimumWidth(0, MIN_LABEL_WIDTH); + topLayout->setColumnMinimumWidth(1, MIN_EDIT_WIDTH); + bottomLayout->setColumnMinimumWidth(0, MIN_LABEL_WIDTH - 8); + + } + }else { + topLayout->setColumnMinimumWidth(0, DETAIL_MIN_LABEL_WIDTH); + topLayout->setColumnMinimumWidth(1, DETAIL_MIN_EDIT_WIDTH); + } +} + void SecurityPage::onPacFilePathComboxIndexChanged(QString str) { if (str.contains("Choose from file...") || str.contains("从文件选择...")) diff --git a/src/frontend/netdetails/securitypage.h b/src/frontend/netdetails/securitypage.h index 8214d2af..81f16656 100644 --- a/src/frontend/netdetails/securitypage.h +++ b/src/frontend/netdetails/securitypage.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef SECURITYWIDGET_H #define SECURITYWIDGET_H @@ -9,6 +28,7 @@ #include #include "coninfo.h" +#include "kylable.h" #include "kwidget.h" #include "kpasswordedit.h" #include "detailwidget.h" @@ -19,7 +39,7 @@ class SecurityPage : public QFrame { Q_OBJECT public: - SecurityPage(QWidget *parent = nullptr); + SecurityPage(bool isNetDetailPage, QWidget *parent = nullptr); void setSecurity(KySecuType index); void setPsk(const QString &psk); @@ -41,11 +61,14 @@ public: void updateFastChange(KyEapMethodFastInfo &info); void getSecuType(KySecuType &secuType, KyEapMethodType &enterpriseType); + bool getAutoConnectState(); private: - QFormLayout *mSecuLayout; - -private: + bool isDetailPage; +// QFormLayout *mSecuLayout; + QGridLayout *topLayout; + QGridLayout *bottomLayout; + QVBoxLayout *mainLayout; QLabel *secuTypeLabel; QLabel *pwdLabel; @@ -56,12 +79,13 @@ private: QLabel *domainLable; QLabel *caCertPathLabel; QLabel *caNeedFlagLabel; - QLabel *clientCertPathLabel; - QLabel *clientPrivateKeyLabel; - QLabel *clientPrivateKeyPwdLabel; + FixLabel *clientCertPathLabel; + FixLabel *clientPrivateKeyLabel; + FixLabel *clientPrivateKeyPwdLabel; + FixLabel *pwdOptionLabel; //PEAP TTLS共有 - QLabel *eapMethodLabel; + FixLabel *eapMethodLabel; QLabel *userNameLabel; QLabel *userPwdLabel; QLabel *userPwdFlagLabel; @@ -77,6 +101,8 @@ private: QComboBox *clientCertPathCombox; QComboBox *clientPrivateKeyCombox; KPasswordEdit *clientPrivateKeyPwdEdit = nullptr; + QComboBox *pwdOptionCombox; + QWidget *tlsWidget; //PEAP && TTLS QComboBox *eapMethodCombox; @@ -93,6 +119,14 @@ private: QLabel *m_pacFileLabel; QWidget *m_pacCheckWidget; + QLabel *m_emptyLabel = nullptr; + QLabel *m_checkLabel = nullptr; + QCheckBox *m_rememberCheckBox = nullptr; + + QString hintRequired = tr("Required"); //必填 + QString emptyhint = tr(" "); + +private: void showNone(); void showPsk(); void showTls(); @@ -111,8 +145,7 @@ private: bool checkConnectBtnIsEnabled(); - -private slots: +private Q_SLOTS: void onSecuTypeComboxIndexChanged(); void onEapTypeComboxIndexChanged(); void setEnableOfSaveBtn(); @@ -123,10 +156,13 @@ private slots: void onCaCertPathComboxIndexChanged(QString str); void onClientCertPathComboxIndexChanged(QString str); void onClientPrivateKeyComboxIndexChanged(QString str); + void onPwdOptionComboxIndexChanged(QString str); + void changeColumnWidthWithSecuType(); void onPacFilePathComboxIndexChanged(QString str); -signals: +Q_SIGNALS: void setSecuPageState(bool); + void secuTypeChanged(const KySecuType &type); void eapTypeChanged(const KyEapMethodType &type); }; diff --git a/src/frontend/networkmode/firewalldialog.cpp b/src/frontend/networkmode/firewalldialog.cpp new file mode 100644 index 00000000..749d4efb --- /dev/null +++ b/src/frontend/networkmode/firewalldialog.cpp @@ -0,0 +1,130 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#include "firewalldialog.h" + +#include + +#define THEME_SCHAME "org.ukui.style" +#define COLOR_THEME "styleName" +#define ICON_SIZE 16,16 + +FirewallDialog::FirewallDialog(QWidget *parent): KDialog(parent) +{ + initUI(); + this->setWindowIcon(QIcon::fromTheme("kylin-network")); + this->setFixedSize(480, 204); + setAttribute(Qt::WA_DeleteOnClose); +// centerToScreen(); + connect(qApp, &QApplication::paletteChanged, this, &FirewallDialog::onPaletteChanged); +} + +FirewallDialog::~FirewallDialog() +{ + +} + +void FirewallDialog::initUI() +{ + m_iconLabel = new QLabel(this); + m_contentLabel = new FixLabel(this); + m_suggestLabel = new FixLabel(this); + m_PublicBtn = new QPushButton(this); + m_PrivateBtn = new QPushButton(this); + m_dialogLayout = new QVBoxLayout(this); + + m_contentLabel->setFixedWidth(405); + m_suggestLabel->setFixedWidth(405); + + QWidget *contentWidget = new QWidget(this); + QGridLayout *contentLayout = new QGridLayout(contentWidget); + contentLayout->setHorizontalSpacing(0); + contentLayout->setContentsMargins(0, 0, 0, 0); + contentLayout->addWidget(m_iconLabel, 0, 0); + contentLayout->addWidget(m_contentLabel, 0, 1); + contentLayout->addWidget(m_suggestLabel, 1, 1); + m_iconLabel->setFixedWidth(24); + + QWidget *btnWidget = new QWidget(this); + QHBoxLayout *btnLayout = new QHBoxLayout(btnWidget); + btnLayout->setContentsMargins(0, 0, 0, 0); + btnLayout->setSpacing(16); + btnLayout->addStretch(); + btnLayout->addWidget(m_PublicBtn); + btnLayout->addWidget(m_PrivateBtn); + + m_dialogLayout->setContentsMargins(22, 16, 22, 24); + m_dialogLayout->setSpacing(0); + m_dialogLayout->addWidget(contentWidget); + m_dialogLayout->addStretch(); + m_dialogLayout->addWidget(btnWidget); + + QIcon icon = QIcon::fromTheme("dialog-info"); + m_iconLabel->setPixmap(icon.pixmap(ICON_SIZE)); + + QFont font = m_contentLabel->font(); + font.setWeight(57); + m_contentLabel->setFont(font); + //是否允许此网络上的其他设备发现这台电脑? + m_contentLabel->setLabelText(tr("Allow other devices on this network to discover this computer?")); + //不建议在公共网络上开启此功能 + m_suggestLabel->setLabelText(tr("It is not recommended to enable this feature on public networks")); + + m_PublicBtn->setText(tr("Not allowed (recommended)")); + m_PrivateBtn->setText(tr("Allowed")); + + this->closeButton(); + this->mainWidget()->setLayout(m_dialogLayout); + onPaletteChanged(); + + connect(m_PublicBtn, &QPushButton::clicked, this, &FirewallDialog::setPublicNetMode); + connect(m_PrivateBtn, &QPushButton::clicked, this, &FirewallDialog::setPrivateNetMode); +} + +void FirewallDialog::centerToScreen() +{ + QDesktopWidget* m = QApplication::desktop(); + QRect desk_rect = m->screenGeometry(m->screenNumber(QCursor::pos())); + int desk_x = desk_rect.width(); + int desk_y = desk_rect.height(); + int x = this->width(); + int y = this->height(); + this->move(desk_x / 2 - x / 2 + desk_rect.left(), desk_y / 2 - y / 2 + desk_rect.top()); +} + +void FirewallDialog::onPaletteChanged() +{ + QPalette pal = qApp->palette(); + + QGSettings * styleGsettings = nullptr; + const QByteArray style_id(THEME_SCHAME); + if (QGSettings::isSchemaInstalled(style_id)) { + styleGsettings = new QGSettings(style_id); + QString currentTheme = styleGsettings->get(COLOR_THEME).toString(); + if(currentTheme == "ukui-default"){ + pal = lightPalette(this); + } + } + this->setPalette(pal); + + if (styleGsettings != nullptr) { + delete styleGsettings; + styleGsettings = nullptr; + } +} diff --git a/src/frontend/networkmode/firewalldialog.h b/src/frontend/networkmode/firewalldialog.h new file mode 100644 index 00000000..4a16d315 --- /dev/null +++ b/src/frontend/networkmode/firewalldialog.h @@ -0,0 +1,75 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#ifndef FIREWALLDIALOG_H +#define FIREWALLDIALOG_H + +#include +#include +#include +#include +#include +#include + +#include "coninfo.h" +#include "kwidget.h" +#include "kdialog.h" +#include "kylable.h" + +using namespace kdk; + +class FirewallDialog : public KDialog +{ + Q_OBJECT +public: + FirewallDialog(QWidget *parent = nullptr); + ~FirewallDialog(); + void setUuid(QString uuid) { + m_uuid = uuid; + } + + void centerToScreen(); + +private: + void initUI(); + + QString m_uuid; + QLabel * m_iconLabel = nullptr; + FixLabel * m_contentLabel = nullptr; + FixLabel * m_suggestLabel = nullptr; + QVBoxLayout *m_dialogLayout = nullptr; + QPushButton *m_PublicBtn = nullptr; + QPushButton *m_PrivateBtn = nullptr; + +Q_SIGNALS: + void setPublicNetMode(); + void setPrivateNetMode(); + +private Q_SLOTS: + void onPaletteChanged(); + + +public Q_SLOTS: + void closeMyself(QString uuid, int status) { + if (uuid == m_uuid && status == 4) { + this->close(); + } + } +}; +#endif // FIREWALLDIALOG_H diff --git a/src/frontend/networkmode/networkmode.pri b/src/frontend/networkmode/networkmode.pri new file mode 100644 index 00000000..6459b81c --- /dev/null +++ b/src/frontend/networkmode/networkmode.pri @@ -0,0 +1,10 @@ +INCLUDEPATH += $$PWD + +HEADERS += \ + $$PWD/firewalldialog.h \ + $$PWD/networkmodeconfig.h + +SOURCES += \ + $$PWD/firewalldialog.cpp \ + $$PWD/networkmodeconfig.cpp + diff --git a/src/frontend/networkmode/networkmodeconfig.cpp b/src/frontend/networkmode/networkmodeconfig.cpp new file mode 100644 index 00000000..d5ca8a57 --- /dev/null +++ b/src/frontend/networkmode/networkmodeconfig.cpp @@ -0,0 +1,253 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#include "networkmodeconfig.h" +#include "firewalldialog.h" +#include + +#define LOG_FLAG "[NetworkMode]" + +NetworkModeConfig *NetworkModeConfig::m_netModeInstance = nullptr; + +NetworkModeConfig *NetworkModeConfig::getInstance() +{ + if (m_netModeInstance == NULL) { + m_netModeInstance = new NetworkModeConfig(); + } + return m_netModeInstance; +} + + +NetworkModeConfig::NetworkModeConfig(QObject *parent) : QObject(parent) +{ + m_dbusInterface = new QDBusInterface("com.ksc.defender", + "/firewall", + "com.ksc.defender.firewall", + QDBusConnection::systemBus()); + if(!m_dbusInterface->isValid()) { + qWarning() << qPrintable(QDBusConnection::sessionBus().lastError().message()); + } +} + +int NetworkModeConfig::getNetworkModeConfig(QString uuid) +{ + if (uuid.isEmpty()) { + qWarning()<< /*LOG_FLAG <<*/ "uuid is empty, so can not get network mode config"; + return NO_CONFIG; + } + + if(m_dbusInterface == nullptr || !m_dbusInterface->isValid()) { + qWarning () << "com.ksc.defender dbus is invalid"; + return DBUS_INVAILD; + } + + QDBusReply reply = m_dbusInterface->call("get_networkModeConfig", uuid); + if (reply.isValid()) { + return reply.value(); + } else { + qWarning() << "call get_networkModeConfig failed" << reply.error().message(); + } + return NO_CONFIG; +} + +void NetworkModeConfig::setNetworkModeConfig(QString uuid, QString cardName, QString ssid, int mode) +{ + if(m_dbusInterface == nullptr || !m_dbusInterface->isValid()) { + qWarning () << "com.ksc.defender dbus is invalid"; + return; + } + + QDBusReply reply = m_dbusInterface->call("set_networkModeConfig", uuid, cardName, ssid, mode); + if (reply.isValid()) { + qDebug() << "set_networkModeConfig" << ssid << uuid << cardName << mode << ",result" << reply.value(); + } else { + qWarning() << "call set_networkModeConfig" << reply.error().message(); + } +} + +int NetworkModeConfig::breakNetworkConnect(QString uuid, QString cardName, QString ssid) +{ + if(m_dbusInterface == nullptr || !m_dbusInterface->isValid()) { + qWarning () << "com.ksc.defender dbus is invalid"; + return -1; + } + + QDBusReply reply = m_dbusInterface->call("break_networkConnect", uuid, cardName, ssid); + if (reply.isValid()) { + qDebug() << "break_networkConnect" << ssid << uuid << cardName << ",result" << reply.value(); + return reply.value(); + } else { + qWarning() << "call break_networkConnect failed" << reply.error().message(); + return -1; + } +} + +//安全中心-网络防火墙模式配置 +NetworkMode::NetworkMode(QObject *parent) + :QObject(parent) +{ + qRegisterMetaType("NetworkManager::Device::State"); + qRegisterMetaType("NetworkManager::Device::StateChangeReason"); + m_deviceResource = new KyNetworkDeviceResourse(this); + m_activatedConnectResource = new KyActiveConnectResourse(this); + m_connectResource = new KyConnectResourse(this); + m_wirelessNetResource = new KyWirelessNetResource(this); + connect(m_activatedConnectResource, &KyActiveConnectResourse::stateChangeReason, + this, &NetworkMode::onConnectionStateChanged); +} + +void NetworkMode::initWiredNetworkMode() +{ + qDebug()<< LOG_FLAG << "initWiredNetworkMode"; + QStringList wiredDevList; + m_deviceResource->getNetworkDeviceList(NetworkManager::Device::Type::Ethernet, wiredDevList); + if (wiredDevList.isEmpty()) { + return; + } + + for (auto devName : wiredDevList) { + QList activedList; + m_activatedConnectResource->getActiveConnectionList(devName, + NetworkManager::ConnectionSettings::Wired, + activedList); + if (activedList.isEmpty()) { + continue; + } + + int configType = NetworkModeConfig::getInstance()->getNetworkModeConfig(activedList.at(0)->m_connectUuid); + if (configType == DBUS_INVAILD) { + return; + } else if (configType == NO_CONFIG) { + //已连接网络无配置 默认公有配置 + NetworkModeConfig::getInstance()->setNetworkModeConfig(activedList.at(0)->m_connectUuid, devName, + activedList.at(0)->m_connectName, KSC_FIREWALL_PUBLIC); + } else { + NetworkModeConfig::getInstance()->setNetworkModeConfig(activedList.at(0)->m_connectUuid, devName, + activedList.at(0)->m_connectName, configType); + } + } +} + +void NetworkMode::initWirelessNetworkMode() +{ + qDebug()<< LOG_FLAG << "initWirelessNetworkMode"; + QStringList wirelessDevList; + m_deviceResource->getNetworkDeviceList(NetworkManager::Device::Type::Wifi, wirelessDevList); + if (wirelessDevList.isEmpty()) { + return; + } + + for (auto devName : wirelessDevList) { + KyWirelessNetItem wirelessNetItem; + bool ret = m_wirelessNetResource->getActiveWirelessNetItem(devName, wirelessNetItem); + + if (ret == true) { + int configType = NetworkModeConfig::getInstance()->getNetworkModeConfig(wirelessNetItem.m_connectUuid); + if (configType == DBUS_INVAILD) { + return; + } else if (configType == NO_CONFIG) { + //已连接网络无配置 默认公有配置 + NetworkModeConfig::getInstance()->setNetworkModeConfig(wirelessNetItem.m_connectUuid, devName, + wirelessNetItem.m_connName, KSC_FIREWALL_PUBLIC); + } else { + NetworkModeConfig::getInstance()->setNetworkModeConfig(wirelessNetItem.m_connectUuid, devName, + wirelessNetItem.m_connName, configType); + } + } + } +} + +void NetworkMode::setFirstConnectNetworkMode(QString uuid, QString deviceName, QString ssid) +{ + NetworkModeConfig::getInstance()->setNetworkModeConfig(uuid, deviceName, ssid, KSC_FIREWALL_PUBLIC); //默认公有配置 + FirewallDialog *fireWallDialog = new FirewallDialog(); + fireWallDialog->setUuid(uuid); + fireWallDialog->setWindowTitle(ssid); + + connect(fireWallDialog, &FirewallDialog::setPrivateNetMode, this, [=](){ + fireWallDialog->hide(); + NetworkModeConfig::getInstance()->setNetworkModeConfig(uuid, deviceName, ssid, KSC_FIREWALL_PRIVATE); + }); + + connect(fireWallDialog, &FirewallDialog::setPublicNetMode, this, [=](){ + fireWallDialog->hide(); + NetworkModeConfig::getInstance()->setNetworkModeConfig(uuid, deviceName, ssid, KSC_FIREWALL_PUBLIC); + }); + + connect(m_activatedConnectResource, &KyActiveConnectResourse::stateChangeReason, fireWallDialog, &FirewallDialog::closeMyself); + + fireWallDialog->show(); + fireWallDialog->centerToScreen(); +} + +void NetworkMode::onConnectionStateChanged(QString uuid, + NetworkManager::ActiveConnection::State state, + NetworkManager::ActiveConnection::Reason reason) +{ + if (state == NetworkManager::ActiveConnection::State::Activated) { + QString deviceName = ""; + QString ssid = ""; + + int configType = NetworkModeConfig::getInstance()->getNetworkModeConfig(uuid); + + //有线网络连接 + if (m_connectResource->isWiredConnection(uuid)) { + KyConnectItem *p_newItem = nullptr; + p_newItem = m_activatedConnectResource->getActiveConnectionByUuid(uuid); + if (nullptr == p_newItem) { + //删除此网络 + qDebug()<< LOG_FLAG << "delete wired connect:" << uuid << ", call break_networkConnect"; + NetworkModeConfig::getInstance()->breakNetworkConnect(uuid, "", ""); + return; + } + + deviceName = p_newItem->m_ifaceName; + ssid = p_newItem->m_connectName; + if (configType == NO_CONFIG) { + //首次连接的网络 + setFirstConnectNetworkMode(uuid, deviceName, ssid); + } else if (configType == KSC_FIREWALL_PUBLIC) { + NetworkModeConfig::getInstance()->setNetworkModeConfig(uuid, deviceName, ssid, KSC_FIREWALL_PUBLIC); + } else if (configType == KSC_FIREWALL_PRIVATE) { + NetworkModeConfig::getInstance()->setNetworkModeConfig(uuid, deviceName, ssid, KSC_FIREWALL_PRIVATE); + } + } + //无线网络连接 + if (m_connectResource->isWirelessConnection(uuid)) { + m_wirelessNetResource->getSsidByUuid(uuid, ssid); + m_wirelessNetResource->getDeviceByUuid(uuid, deviceName); + if (ssid.isEmpty()) { + //忘记此网络 + qDebug()<< LOG_FLAG << "forgrt wireless connect:" << uuid <<", call break_networkConnect"; + NetworkModeConfig::getInstance()->breakNetworkConnect(uuid, "", ""); + } + + if (configType == NO_CONFIG) { + setFirstConnectNetworkMode(uuid, deviceName, ssid); + } else if (configType == KSC_FIREWALL_PUBLIC) { + NetworkModeConfig::getInstance()->setNetworkModeConfig(uuid, deviceName, ssid, KSC_FIREWALL_PUBLIC); + } else if (configType == KSC_FIREWALL_PRIVATE) { + NetworkModeConfig::getInstance()->setNetworkModeConfig(uuid, deviceName, ssid, KSC_FIREWALL_PRIVATE); + } + } + + } else if (state == NetworkManager::ActiveConnection::State::Deactivated) { + NetworkModeConfig::getInstance()->breakNetworkConnect(uuid, "", ""); + } +} diff --git a/src/frontend/networkmode/networkmodeconfig.h b/src/frontend/networkmode/networkmodeconfig.h new file mode 100644 index 00000000..c4af58ee --- /dev/null +++ b/src/frontend/networkmode/networkmodeconfig.h @@ -0,0 +1,79 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#ifndef NETWORKMODECONFIG_H +#define NETWORKMODECONFIG_H + +#include +#include +#include +#include "kylinactiveconnectresource.h" +#include "kylinconnectresource.h" +#include "kywirelessnetresource.h" + +enum NetworkModeType { + DBUS_INVAILD = -2, + NO_CONFIG = -1, + KSC_FIREWALL_PUBLIC = 0, + KSC_FIREWALL_PRIVATE +}; + +class NetworkModeConfig : public QObject +{ + Q_OBJECT +public: + static NetworkModeConfig *getInstance(); + //安全中心-获取网络模式配置 + int getNetworkModeConfig(QString uuid); + //安全中心-设置网络模式配置 + void setNetworkModeConfig(QString uuid, QString cardName, QString ssid, int mode); + //安全中心-解除连接(用于防火墙处从正在使用的网络中删除) + int breakNetworkConnect(QString uuid, QString cardName, QString ssid); + + static NetworkModeConfig *m_netModeInstance; + +private: + explicit NetworkModeConfig(QObject *parent = nullptr); + QDBusInterface *m_dbusInterface = nullptr; +}; + + +class NetworkMode : public QObject +{ + Q_OBJECT +public: + NetworkMode(QObject *parent = 0); + ~NetworkMode() = default; + void initWiredNetworkMode(); + void initWirelessNetworkMode(); + +private: + KyNetworkDeviceResourse *m_deviceResource = nullptr; + KyActiveConnectResourse *m_activatedConnectResource = nullptr; + KyConnectResourse * m_connectResource = nullptr; + KyWirelessNetResource *m_wirelessNetResource = nullptr; + void setFirstConnectNetworkMode(QString uuid, QString deviceName, QString ssid); + +private Q_SLOTS: + void onConnectionStateChanged(QString uuid, + NetworkManager::ActiveConnection::State state, + NetworkManager::ActiveConnection::Reason reason); +}; + +#endif // NETWORKMODECONFIG_H diff --git a/src/frontend/tab-pages/lanpage.cpp b/src/frontend/tab-pages/lanpage.cpp index 564fd00d..2f6e04ae 100644 --- a/src/frontend/tab-pages/lanpage.cpp +++ b/src/frontend/tab-pages/lanpage.cpp @@ -1,4 +1,25 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "lanpage.h" +#include "kwindowsystem.h" +#include "kwindowsystem_export.h" #include #include @@ -48,10 +69,16 @@ LanPage::LanPage(QWidget *parent) : TabPage(parent) connect(m_deviceResource, &KyNetworkDeviceResourse::carrierChanage, this, &LanPage::onDeviceCarriered); connect(m_deviceResource, &KyNetworkDeviceResourse::deviceActiveChanage, this, &LanPage::onDeviceActiveChanage); + connect(m_deviceResource, &KyNetworkDeviceResourse::deviceManagedChange, this, &LanPage::onDeviceManagedChange); connect(m_wiredConnectOperation, &KyWiredConnectOperation::activateConnectionError, this, &LanPage::activateFailed); connect(m_wiredConnectOperation, &KyWiredConnectOperation::deactivateConnectionError, this, &LanPage::deactivateFailed); - + connect(m_wiredConnectOperation, &KyWiredConnectOperation::wiredEnabledChanged, this, &LanPage::onWiredEnabledChanged); + connect(m_netSwitch, &KSwitchButton::clicked, this, [=](bool checked) { + m_netSwitch->setChecked(!checked); + m_wiredConnectOperation->setWiredEnabled(checked); + }); + m_lanPagePtrMap.clear(); } LanPage::~LanPage() @@ -99,65 +126,55 @@ void LanPage::initLanDevice() void LanPage::initLanDeviceState() { - QMap deviceStateMap; - getDeviceEnableState(WIRED, deviceStateMap); - - QStringList disableDeviceList; - disableDeviceList.clear(); + m_disableDeviceList.clear(); m_enableDeviceList.clear(); for (int index = 0; index < m_devList.count(); ++index) { QString deviceName = m_devList.at(index); - if (deviceStateMap.contains(deviceName)) { - if (deviceStateMap[deviceName]) { - m_enableDeviceList<getDeviceManaged(deviceName)) { m_enableDeviceList<isChecked()) { - for (int index = 0; index < disableDeviceList.count(); ++index) { - wiredOperation.closeWiredNetworkWithDevice(disableDeviceList.at(index)); - } - } else { - for (int index = 0; index < m_devList.count(); ++index) { - wiredOperation.closeWiredNetworkWithDevice(m_devList.at(index)); - } - } - - return; } void LanPage::initNetSwitch() { - bool wiredSwitch = true; + bool wiredGsetting = true; + bool wiredEnable = m_wiredConnectOperation->getWiredEnabled(); if (QGSettings::isSchemaInstalled(GSETTINGS_SCHEMA)) { m_switchGsettings = new QGSettings(GSETTINGS_SCHEMA); if (m_switchGsettings->keys().contains(WIRED_SWITCH)) { - wiredSwitch = m_switchGsettings->get(WIRED_SWITCH).toBool(); + wiredGsetting = m_switchGsettings->get(WIRED_SWITCH).toBool(); connect(m_switchGsettings, &QGSettings::changed, this, &LanPage::onSwithGsettingsChanged); + if (wiredEnable != wiredGsetting) { + wiredEnable = wiredGsetting; + m_wiredConnectOperation->setWiredEnabled(wiredGsetting); + } } } else { qDebug()<<"[LanPage] org.ukui.kylin-nm.switch is not installed!"; } + //从3.0升级上来 先读取老的配置文件来保证和升级前状态一致 + bool oldVersionState = true; + if (getOldVersionWiredSwitchState(oldVersionState)) { + if (wiredEnable != oldVersionState) { + wiredEnable = oldVersionState; + m_wiredConnectOperation->setWiredEnabled(oldVersionState); + } + } + if (m_devList.count() == 0) { qDebug() << "[wiredSwitch]:init not enable when no device"; m_netSwitch->setChecked(false); m_netSwitch->setCheckable(false); } - qDebug() << "[wiredSwitch]:init state:" << wiredSwitch; + qDebug() << "[wiredSwitch]:init state:" << wiredEnable; - m_netSwitch->setChecked(wiredSwitch); - - return; + m_netSwitch->setChecked(wiredEnable); } void LanPage::onSwithGsettingsChanged(const QString &key) @@ -167,25 +184,14 @@ void LanPage::onSwithGsettingsChanged(const QString &key) bool wiredSwitch = m_switchGsettings->get(WIRED_SWITCH).toBool(); qDebug()<<"[LanPage] SwitchButton statue changed to:" << wiredSwitch << m_netSwitch->isChecked(); - if (wiredSwitch == m_netSwitch->isChecked()) { + if (wiredSwitch != m_wiredConnectOperation->getWiredEnabled()) { + m_wiredConnectOperation->setWiredEnabled(wiredSwitch); return; } - KyWiredConnectOperation wiredOperation; - if (wiredSwitch) { - for (int index = 0; index < m_enableDeviceList.size(); ++index) { - qDebug()<<"[LanPage] open wired device "<< m_enableDeviceList.at(index); - wiredOperation.openWiredNetworkWithDevice(m_enableDeviceList.at(index)); - } - } else { - for (int index = 0; index < m_enableDeviceList.size(); ++index) { - qDebug()<<"[LanPage] close wired device "<< m_enableDeviceList.at(index); - wiredOperation.closeWiredNetworkWithDevice(m_enableDeviceList.at(index)); - } - } - m_netSwitch->setChecked(wiredSwitch); + initLanDeviceState(); initDeviceCombox(); initLanArea(); } @@ -193,49 +199,30 @@ void LanPage::onSwithGsettingsChanged(const QString &key) void LanPage::getEnabledDevice(QStringList &enableDeviceList) { - int index = 0; - QMap deviceMap; - if (m_devList.isEmpty()) { qDebug()<<"[LanPage] there is not wired device."; return; } - getDeviceEnableState(WIRED, deviceMap); - for (index = 0; index < m_devList.size(); ++index) { - if (deviceMap.contains(m_devList.at(index))) { - if (deviceMap[m_devList.at(index)]) { - enableDeviceList << m_devList.at(index); - } - } else { - saveDeviceEnableState(m_devList.at(index), true); + for (int index = 0; index < m_devList.size(); ++index) { + if (m_deviceResource->getDeviceManaged(m_devList.at(index))) { enableDeviceList << m_devList.at(index); } } - - return; } void LanPage::getDisabledDevices(QStringList &disableDeviceList) { - int index = 0; - QMap deviceMap; - if (m_devList.isEmpty()) { qDebug()<<"[LanPage] there is not wired device."; return; } - getDeviceEnableState(WIRED, deviceMap); - for (index = 0; index < m_devList.size(); ++index) { - if (deviceMap.contains(m_devList.at(index))) { - if (!deviceMap[m_devList.at(index)]) { - disableDeviceList << m_devList.at(index); - } + for (int index = 0; index < m_devList.size(); ++index) { + if (!m_deviceResource->getDeviceManaged(m_devList.at(index))) { + disableDeviceList << m_devList.at(index); } } - - return; } void LanPage::initDeviceCombox() @@ -280,13 +267,11 @@ void LanPage::initDeviceCombox() } else { m_deviceFrame->hide(); m_currentDeviceName = ""; - } setDefaultDevice(WIRED, m_currentDeviceName); connect(m_deviceComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, &LanPage::onDeviceComboxIndexChanged); - return; } void LanPage::addEmptyConnectItem(QMap &connectMap, @@ -294,8 +279,6 @@ void LanPage::addEmptyConnectItem(QMap &connectMap, { QListWidgetItem *p_listWidgetItem = addNewItem(nullptr, lanListWidget); connectMap.insert(EMPTY_CONNECT_UUID, p_listWidgetItem); - - return; } @@ -364,6 +347,7 @@ void LanPage::constructActiveConnectionArea() delete p_activeConnectionItem; p_activeConnectionItem = nullptr; } + setNetSpeed->start(REFRESH_NETWORKSPEED_TIMER); } else { qDebug()<<"[LanPage] there is not active"; addEmptyConnectItem(m_activeConnectionMap, m_activatedLanListWidget); @@ -396,7 +380,7 @@ void LanPage::constructConnectionArea() } } - if (m_inactivatedLanListWidget->count() < MAX_ITEMS) { + if (m_inactivatedLanListWidget->count() <= MAX_ITEMS) { m_inactivatedLanListWidget->setFixedWidth(MIN_WIDTH); } else { m_inactivatedLanListWidget->setFixedWidth(MAX_WIDTH); @@ -442,7 +426,7 @@ bool LanPage::removeConnectionItem(QMap &connectMap, p_listWidgetItem = nullptr; iter = connectMap.erase(iter); - if (m_inactivatedLanListWidget->count() < MAX_ITEMS) { + if (m_inactivatedLanListWidget->count() <= MAX_ITEMS) { m_inactivatedLanListWidget->setFixedWidth(MIN_WIDTH); } return true; @@ -455,8 +439,15 @@ bool LanPage::removeConnectionItem(QMap &connectMap, void LanPage::onRemoveConnection(QString path) //删除时后端会自动断开激活,将其从未激活列表中删除 { //for dbus - qDebug() << "[LanPage] emit lanRemove because onRemoveConnection " << path; - emit lanRemove(path); + qDebug() << "[LanPage] Q_EMIT lanRemove because onRemoveConnection " << path; + Q_EMIT lanRemove(path); + + if (m_lanPagePtrMap.contains(path)) { + if (m_lanPagePtrMap[path] != nullptr) { + delete m_lanPagePtrMap[path]; + m_lanPagePtrMap[path] = nullptr; + } + } if (removeConnectionItem(m_inactiveConnectionMap, m_inactivatedLanListWidget, path)) { return; @@ -465,7 +456,7 @@ void LanPage::onRemoveConnection(QString path) //删除时后端会 if (m_activeConnectionMap.count() <= 0) { addEmptyConnectItem(m_activeConnectionMap, m_activatedLanListWidget); } - + setNetSpeed->stop(); return; } } @@ -495,10 +486,9 @@ void LanPage::onAddConnection(QString uuid) //新增一个有线 delete p_newItem; p_newItem = nullptr; - if (m_inactivatedLanListWidget->count() >= MAX_ITEMS) { + if (m_inactivatedLanListWidget->count() > MAX_ITEMS) { m_inactivatedLanListWidget->setFixedWidth(MAX_WIDTH); } - return; } void LanPage::addDeviceForCombox(QString deviceName) @@ -530,7 +520,6 @@ void LanPage::addDeviceForCombox(QString deviceName) connect(m_deviceComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, &LanPage::onDeviceComboxIndexChanged); - return; } void LanPage::onDeviceAdd(QString deviceName, NetworkManager::Device::Type deviceType) @@ -552,17 +541,17 @@ void LanPage::onDeviceAdd(QString deviceName, NetworkManager::Device::Type devic qDebug() << "[LanPage] Begin add device:" << deviceName; m_devList << deviceName; - saveDeviceEnableState(deviceName, true); - m_enableDeviceList<getDeviceManaged(deviceName)) { + m_enableDeviceList << deviceName; + addDeviceForCombox(deviceName); + if (m_currentDeviceName == deviceName) { + initLanArea(); + } + } else { + m_disableDeviceList << deviceName; } - emit deviceStatusChanged(); - - return; + Q_EMIT deviceStatusChanged(); } void LanPage::deleteDeviceFromCombox(QString deviceName) @@ -629,8 +618,8 @@ void LanPage::onDeviceRemove(QString deviceName) m_devList.removeOne(deviceName); if (m_devList.count() == 0) { - m_netSwitch->setCheckable(false); m_netSwitch->setChecked(false); + m_netSwitch->setCheckable(false); qDebug() << "[wiredSwitch]set not enable after device remove"; } @@ -644,11 +633,11 @@ void LanPage::onDeviceRemove(QString deviceName) if (m_enableDeviceList.contains(deviceName)) { m_enableDeviceList.removeOne(deviceName); } - deleteDeviceEnableState(deviceName); + if (m_disableDeviceList.contains(deviceName)) { + m_disableDeviceList.removeOne(deviceName); + } - emit deviceStatusChanged(); - - return; + Q_EMIT deviceStatusChanged(); } void LanPage::updateDeviceCombox(QString oldDeviceName, QString newDeviceName) @@ -675,15 +664,18 @@ void LanPage::onDeviceNameUpdate(QString oldName, QString newName) if (m_enableDeviceList.contains(oldName)) { m_enableDeviceList.removeOne(oldName); m_enableDeviceList.append(newName); + } else if (m_disableDeviceList.contains(oldName)) { + m_disableDeviceList.removeOne(oldName); + m_disableDeviceList.append(newName); } - qDebug() << "[LanPage] emit deviceNameUpdate " << oldName << newName; + qDebug() << "[LanPage] Q_EMIT deviceNameUpdate " << oldName << newName; updateDeviceCombox(oldName, newName); if (m_currentDeviceName == newName) { initLanArea(); } - emit deviceNameChanged(oldName, newName, WIRED); + Q_EMIT deviceNameChanged(oldName, newName, WIRED); } } @@ -693,26 +685,32 @@ void LanPage::onDeviceCarriered(QString deviceName, bool pluged) return; } if (m_enableDeviceList.contains(deviceName)) { - m_wiredConnectOperation->openWiredNetworkWithDevice(deviceName); updateCurrentDevice(deviceName); } - return; } void LanPage::onDeviceActiveChanage(QString deviceName, bool deviceActive) { - if (!m_devList.contains(deviceName)) { - return; - } +// if (!m_devList.contains(deviceName)) { +// return; +// } - if (deviceActive) { - if (!m_netSwitch->isChecked() || !m_enableDeviceList.contains(deviceName)) { - qDebug()<< LOG_FLAG << "close disabled device"; - m_wiredConnectOperation->closeWiredNetworkWithDevice(deviceName); - } - } +// if (deviceActive) { +// if (!m_netSwitch->isChecked() || !m_enableDeviceList.contains(deviceName)) { +// qDebug()<< LOG_FLAG << "close disabled device"; +// m_wiredConnectOperation->closeWiredNetworkWithDevice(deviceName); +// } +// } - return; +// return; +} + +void LanPage::onDeviceManagedChange(QString deviceName, bool managed) +{ + initLanDeviceState(); + initDeviceCombox(); + initLanArea(); + Q_EMIT deviceStatusChanged(); } @@ -741,6 +739,7 @@ void LanPage::initUI() m_activatedLanListWidget->setFixedHeight(ITEM_HEIGHT); //active区域固定高度,只显示一个条目 m_activatedLanListWidget->setFixedWidth(MIN_WIDTH); m_activatedLanListWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + m_activatedLanListWidget->setProperty("needTranslucent", true); m_activatedNetLayout->addWidget(m_activatedLanListWidget); m_inactivatedNetLabel->setText(tr("Inactivated LAN")); @@ -752,15 +751,27 @@ void LanPage::initUI() m_inactivatedLanListWidget->verticalScrollBar()->setProperty("drawScrollBarGroove",false); //去除滚动条的外侧黑框 m_inactivatedLanListWidget->verticalScrollBar()->setSingleStep(SCROLL_STEP); m_inactivatedLanListWidget->verticalScrollBar()->setContextMenuPolicy(Qt::NoContextMenu); + m_inactivatedLanListWidget->verticalScrollBar()->setProperty("needTranslucent", true); + m_inactivatedLanListWidget->setProperty("needTranslucent", true); m_inactivatedAreaLayout->addWidget(m_inactivatedLanListWidget); + connect(m_inactivatedLanListWidget, &QListWidget::currentItemChanged, this, [=]() { + if (m_inactivatedLanListWidget->currentItem() != nullptr) { + m_inactivatedLanListWidget->currentItem()->setSelected(false); + } + }); + QPalette pal = m_activatedLanListWidget->palette(); pal.setBrush(QPalette::Base, QColor(0,0,0,0)); //背景透明 m_activatedLanListWidget->setPalette(pal); m_inactivatedLanListWidget->setPalette(pal); - m_settingsBtn->installEventFilter(this); + m_settingsLabel->installEventFilter(this); m_netSwitch->installEventFilter(this); + m_activatedLanListWidget->installEventFilter(this); + m_inactivatedLanListWidget->installEventFilter(this); + + showRate(); } QListWidgetItem *LanPage::insertNewItem(KyConnectItem *itemData, QListWidget *listWidget) @@ -778,7 +789,7 @@ QListWidgetItem *LanPage::insertNewItem(KyConnectItem *itemData, QListWidget *li } QListWidgetItem *p_sortListWidgetItem = new QListWidgetItem(); - p_sortListWidgetItem->setFlags(p_sortListWidgetItem->flags() & (~Qt::ItemIsSelectable)); //设置不可被选中 +// p_sortListWidgetItem->setFlags(p_sortListWidgetItem->flags() & (~Qt::ItemIsSelectable)); //设置不可被选中 p_sortListWidgetItem->setSizeHint(QSize(listWidget->width(),ITEM_HEIGHT)); listWidget->insertItem(index, p_sortListWidgetItem); @@ -786,14 +797,14 @@ QListWidgetItem *LanPage::insertNewItem(KyConnectItem *itemData, QListWidget *li LanListItem *p_sortLanItem = nullptr; p_sortLanItem = new LanListItem(itemData, m_currentDeviceName); listWidget->setItemWidget(p_sortListWidgetItem, p_sortLanItem); - + connect(p_sortLanItem, &LanListItem::detailShow, this, &LanPage::showDetailPage); return p_sortListWidgetItem; } QListWidgetItem *LanPage::addNewItem(KyConnectItem *itemData, QListWidget *listWidget) { QListWidgetItem *p_listWidgetItem = new QListWidgetItem(); - p_listWidgetItem->setFlags(p_listWidgetItem->flags() & (~Qt::ItemIsSelectable)); +// p_listWidgetItem->setFlags(p_listWidgetItem->flags() & (~Qt::ItemIsSelectable)); p_listWidgetItem->setSizeHint(QSize(listWidget->width(), ITEM_HEIGHT)); listWidget->addItem(p_listWidgetItem); LanListItem *p_lanItem = nullptr; @@ -807,6 +818,7 @@ QListWidgetItem *LanPage::addNewItem(KyConnectItem *itemData, QListWidget *listW } listWidget->setItemWidget(p_listWidgetItem, p_lanItem); + connect(p_lanItem, &LanListItem::detailShow, this, &LanPage::showDetailPage); return p_listWidgetItem; } @@ -822,9 +834,9 @@ void LanPage::updateActivatedConnectionArea(KyConnectItem *p_newItem) deleteConnectionMapItem(m_activeConnectionMap, m_activatedLanListWidget, EMPTY_CONNECT_UUID); QListWidgetItem *p_listWidgetItem = addNewItem(p_newItem, m_activatedLanListWidget); m_activeConnectionMap.insert(p_newItem->m_connectUuid, p_listWidgetItem); - this->showDesktopNotify(tr("LAN Connected Successfully"), "networkconnected"); +// this->showDesktopNotify(tr("LAN Connected Successfully"), "networkconnected"); } - if (m_inactivatedLanListWidget->count() < MAX_ITEMS) { + if (m_inactivatedLanListWidget->count() <= MAX_ITEMS) { m_inactivatedLanListWidget->setFixedWidth(MIN_WIDTH); } @@ -846,9 +858,9 @@ void LanPage::updateConnectionArea(KyConnectItem *p_newItem) qDebug()<<"[LanPage] update connection item"<m_connectName; QListWidgetItem *p_listWidgetItem = insertNewItem(p_newItem, m_inactivatedLanListWidget); m_inactiveConnectionMap.insert(p_newItem->m_connectUuid, p_listWidgetItem); - this->showDesktopNotify(tr("LAN Disconnected Successfully"), "networkdisconnected"); +// this->showDesktopNotify(tr("LAN Disconnected Successfully"), "networkdisconnected"); } - if (m_inactivatedLanListWidget->count() < MAX_ITEMS) { + if (m_inactivatedLanListWidget->count() <= MAX_ITEMS) { m_inactivatedLanListWidget->setFixedWidth(MIN_WIDTH); } else { m_inactivatedLanListWidget->setFixedWidth(MAX_WIDTH); @@ -908,6 +920,10 @@ void LanPage::onConnectionStateChange(QString uuid, sendLanStateChangeSignal(uuid, (ConnectState)state); + if (m_activeConnectionMap.keys().contains(uuid) && state == NetworkManager::ActiveConnection::State::Activated) { + return; + } + qDebug()<<"[LanPage] connection uuid"<< uuid << "state change slot:"<< state; @@ -920,12 +936,12 @@ void LanPage::onConnectionStateChange(QString uuid, qWarning()<<"[LanPage] get active connection failed, connection uuid" << uuid; return; } - - deviceName = p_newItem->m_ifaceName; updateActivatedConnectionArea(p_newItem); updateConnectionState(m_activeConnectionMap, m_activatedLanListWidget, uuid, (ConnectState)state); + deviceName = p_newItem->m_ifaceName; + setNetSpeed->start(REFRESH_NETWORKSPEED_TIMER); } else if (state == NetworkManager::ActiveConnection::State::Deactivated) { - p_newItem = m_connectResourse->getConnectionItemByUuid(uuid); + p_newItem = m_connectResourse->getConnectionItemByUuidWithoutActivateChecking(uuid); qDebug() << "[LanPage] deactivated reason" << reason; if (nullptr == p_newItem) { qWarning()<<"[LanPage] get active connection failed, connection uuid" << uuid; @@ -935,6 +951,7 @@ void LanPage::onConnectionStateChange(QString uuid, deviceName = p_newItem->m_ifaceName; updateConnectionArea(p_newItem); updateConnectionState(m_inactiveConnectionMap, m_inactivatedLanListWidget, uuid, (ConnectState)state); + setNetSpeed->stop(); } else if (state == NetworkManager::ActiveConnection::State::Activating) { deviceName = getConnectionDevice(uuid); if (deviceName == m_currentDeviceName) { @@ -947,7 +964,7 @@ void LanPage::onConnectionStateChange(QString uuid, } } - emit lanActiveConnectionStateChanged(deviceName, uuid, state); + Q_EMIT lanActiveConnectionStateChanged(deviceName, uuid, state); if (p_newItem) { delete p_newItem; @@ -966,7 +983,7 @@ void LanPage::getWiredList(QMap > &map) return; } - foreach (auto deviceName, devlist) { + Q_FOREACH (auto deviceName, devlist) { QList activedList; QList deactivedList; QVector vector; @@ -992,7 +1009,7 @@ void LanPage::sendLanUpdateSignal(KyConnectItem *p_connectItem) { QStringList info; info << p_connectItem->m_connectName << p_connectItem->m_connectUuid << p_connectItem->m_connectPath; - emit lanUpdate(p_connectItem->m_ifaceName, info); + Q_EMIT lanUpdate(p_connectItem->m_ifaceName, info); return; } @@ -1001,8 +1018,8 @@ void LanPage::sendLanAddSignal(KyConnectItem *p_connectItem) { QStringList info; info << p_connectItem->m_connectName << p_connectItem->m_connectUuid << p_connectItem->m_connectPath; - qDebug() << "[LanPage] emit lanAdd because addConnection "; - emit lanAdd(p_connectItem->m_ifaceName, info); + qDebug() << "[LanPage] Q_EMIT lanAdd because addConnection "; + Q_EMIT lanAdd(p_connectItem->m_ifaceName, info); return; } @@ -1014,8 +1031,7 @@ void LanPage::sendLanStateChangeSignal(QString uuid, ConnectState state) return; } } - - emit this->lanConnectChanged(state); + Q_EMIT this->lanConnectChanged(state); return; } @@ -1141,33 +1157,7 @@ void LanPage::onUpdateConnection(QString uuid) void LanPage::setWiredDeviceEnable(const QString& devName, bool enable) { - saveDeviceEnableState(devName, enable); - - KyWiredConnectOperation wiredOperation; - if (enable) { - wiredOperation.openWiredNetworkWithDevice(devName); - - m_enableDeviceList<setDeviceManaged(devName, enable); } void LanPage::deleteWired(const QString &connUuid) @@ -1181,7 +1171,7 @@ void LanPage::deleteWired(const QString &connUuid) bool LanPage::eventFilter(QObject *watched, QEvent *event) { - if (watched == m_settingsBtn) { + if (watched == m_settingsLabel) { if (event->type() == QEvent::MouseButtonRelease) { onShowControlCenter(); } @@ -1192,24 +1182,44 @@ bool LanPage::eventFilter(QObject *watched, QEvent *event) if (m_devList.count() == 0) { this->showDesktopNotify(tr("No ethernet device avaliable"), "networkwrong"); - m_netSwitch->setCheckable(false); m_netSwitch->setChecked(false); - } else { - m_netSwitch->setCheckable(true); - if (m_netSwitch->isChecked()) { - m_switchGsettings->set(WIRED_SWITCH, false); - } else { - m_switchGsettings->set(WIRED_SWITCH,true); - } + m_netSwitch->setCheckable(false); } - return true; } + } else if (watched == m_activatedLanListWidget) { + //去掉无右键菜单显示时的选中效果 + if (event->type() == QEvent::FocusIn) { + if (m_activatedLanListWidget->currentItem() != nullptr) { + m_activatedLanListWidget->currentItem()->setSelected(false); + } + } + } else if (watched == m_inactivatedLanListWidget) { + //去掉无右键菜单显示时的选中效果 + if (event->type() == QEvent::FocusIn) { + if (m_inactivatedLanListWidget->currentItem() != nullptr) { + m_inactivatedLanListWidget->currentItem()->setSelected(false); + } + } } return QWidget::eventFilter(watched, event); } +void LanPage::onWiredEnabledChanged(bool enabled) +{ + if (m_devList.isEmpty()) { + qDebug() << "[LanPage] have no device to use " << Q_FUNC_INFO << __LINE__; + return; + } + + if (m_netSwitch->isChecked() == enabled) { + return; + } else { + m_switchGsettings->set(WIRED_SWITCH, enabled); + } +} + void LanPage::activateWired(const QString& devName, const QString& connUuid) { qDebug() << "[LanPage] activateWired" << devName << connUuid; @@ -1248,8 +1258,39 @@ void LanPage::showDetailPage(QString devName, QString uuid) return; } + if (m_lanPagePtrMap.contains(p_item->m_connectPath)) { + if (m_lanPagePtrMap[p_item->m_connectPath] != nullptr) { + qDebug() << "[LanPage] ShowLanDetailPage" << uuid << "already create,just raise"; + KWindowSystem::activateWindow(m_lanPagePtrMap[p_item->m_connectPath]->winId()); + KWindowSystem::raiseWindow(m_lanPagePtrMap[p_item->m_connectPath]->winId()); + return; + } + } + NetDetail *netDetail = new NetDetail(devName, p_item->m_connectName, uuid, isActive, false, false); + m_lanPagePtrMap.insert(p_item->m_connectPath, netDetail); netDetail->show(); + netDetail->centerToScreen(); + + connect(netDetail, &NetDetail::detailPageClose, [&](QString deviceName, QString lanName, QString lanUuid){ + if (lanUuid.isEmpty()) { + return; + } + KyConnectItem *currentItem = nullptr; + if (m_connectResourse->isActivatedConnection(lanUuid)) { + currentItem = m_activeResourse->getActiveConnectionByUuid(lanUuid); + } else { + currentItem = m_connectResourse->getConnectionItemByUuid(lanUuid); + } + if (currentItem == nullptr) { + return; + } + if (m_lanPagePtrMap.contains(currentItem->m_connectPath)) { + m_lanPagePtrMap[currentItem->m_connectPath] = nullptr; + } + delete currentItem; + currentItem = nullptr; + }); delete p_item; p_item = nullptr; @@ -1264,3 +1305,12 @@ bool LanPage::lanIsConnected() } } +void LanPage::showRate() +{ + //定时获取网速 + setNetSpeed = new QTimer(this); + setNetSpeed->setTimerType(Qt::PreciseTimer); + connect(setNetSpeed, &QTimer::timeout, [&]() { + onSetNetSpeed(m_activatedLanListWidget, m_activeConnectionMap.contains(EMPTY_SSID), m_currentDeviceName); + }); +} diff --git a/src/frontend/tab-pages/lanpage.h b/src/frontend/tab-pages/lanpage.h index 83155e2a..159ce530 100644 --- a/src/frontend/tab-pages/lanpage.h +++ b/src/frontend/tab-pages/lanpage.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef LANPAGE_H #define LANPAGE_H @@ -80,8 +99,9 @@ private: QListWidget *lanListWidget, QString uuid); void updateCurrentDevice(QString deviceName); + void showRate(); -signals: +Q_SIGNALS: void lanAdd(QString devName, QStringList info); void lanRemove(QString dbusPath); void lanUpdate(QString devName, QStringList info); @@ -89,7 +109,9 @@ signals: void lanActiveConnectionStateChanged(QString interface, QString uuid, int status); void lanConnectChanged(int state); -private slots: + void showLanRate(QListWidget *widget, QMap &map, QString dev, bool isLan); + +private Q_SLOTS: void onConnectionStateChange(QString uuid, NetworkManager::ActiveConnection::State state, NetworkManager::ActiveConnection::Reason reason); @@ -102,6 +124,7 @@ private slots: void onDeviceAdd(QString deviceName, NetworkManager::Device::Type deviceType); void onDeviceRemove(QString deviceName); void onDeviceNameUpdate(QString oldName, QString newName); + void onDeviceManagedChange(QString deviceName, bool managed); void onDeviceCarriered(QString deviceName, bool pluged); void onDeviceActiveChanage(QString deviceName, bool deviceActive); @@ -110,6 +133,7 @@ private slots: void onShowControlCenter(); + void onWiredEnabledChanged(bool); private: QListWidget * m_activatedLanListWidget = nullptr; QListWidget * m_inactivatedLanListWidget = nullptr; @@ -125,9 +149,10 @@ private: QString m_currentDeviceName; QStringList m_devList; QStringList m_enableDeviceList; + QStringList m_disableDeviceList; QGSettings *m_switchGsettings = nullptr; - + QMap m_lanPagePtrMap; }; #endif // LANPAGE_H diff --git a/src/frontend/tab-pages/tabpage.cpp b/src/frontend/tab-pages/tabpage.cpp index e32f3fb9..03d4f92c 100644 --- a/src/frontend/tab-pages/tabpage.cpp +++ b/src/frontend/tab-pages/tabpage.cpp @@ -1,8 +1,34 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "tabpage.h" #include #include #include #include +#include +#include +#include + +#include"listitem.h" + +#define LOG_FLAG "[tabPage]" TabPage::TabPage(QWidget *parent) : QWidget(parent) { @@ -30,6 +56,7 @@ void TabPage::initUI() m_titleLayout->setContentsMargins(TITLE_LAYOUT_MARGINS); m_titleLabel = new QLabel(m_titleFrame); m_netSwitch = new KSwitchButton(m_titleFrame); + m_netSwitch->setTranslucent(true); m_titleLayout->addWidget(m_titleLabel); m_titleLayout->addStretch(); m_titleLayout->addWidget(m_netSwitch); @@ -61,6 +88,7 @@ void TabPage::initUI() // m_activatedNetLayout->setSpacing(NET_LAYOUT_SPACING); m_activatedNetLabel = new QLabel(m_activatedNetFrame); m_activatedNetLabel->setContentsMargins(TEXT_MARGINS); + m_activatedNetLabel->setFixedHeight(TEXT_HEIGHT); m_activatedNetLayout->addWidget(m_activatedNetLabel); m_activatedNetDivider = new Divider(this); @@ -73,17 +101,19 @@ void TabPage::initUI() m_inactivatedNetLabel = new QLabel(m_inactivatedNetFrame); m_inactivatedNetLabel->setContentsMargins(TEXT_MARGINS); + m_inactivatedNetLabel->setFixedHeight(TEXT_HEIGHT); - m_inactivatedNetListArea = new QScrollArea(m_inactivatedNetFrame); - m_inactivatedNetListArea->setFrameShape(QFrame::Shape::NoFrame); - m_inactivatedNetListArea->setWidgetResizable(true); - m_inactivatedNetListArea->setBackgroundRole(QPalette::Base); - m_inactivatedNetListArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - m_inactivatedNetListArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); +// m_inactivatedNetListArea = new QScrollArea(m_inactivatedNetFrame); +// m_inactivatedNetListArea->setFrameShape(QFrame::Shape::NoFrame); +// m_inactivatedNetListArea->setWidgetResizable(true); +// m_inactivatedNetListArea->setBackgroundRole(QPalette::Base); +// m_inactivatedNetListArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); +// m_inactivatedNetListArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + m_inactivatedNetListArea = new QWidget(m_inactivatedNetFrame); m_inactivatedAreaLayout = new QVBoxLayout(m_inactivatedNetListArea); m_inactivatedAreaLayout->setSpacing(MAIN_LAYOUT_SPACING); m_inactivatedAreaLayout->setContentsMargins(MAIN_LAYOUT_MARGINS); - m_inactivatedNetListArea->setLayout(m_inactivatedAreaLayout); +// m_inactivatedNetListArea->setLayout(m_inactivatedAreaLayout); m_inactivatedNetLayout->addWidget(m_inactivatedNetLabel); m_inactivatedNetLayout->addWidget(m_inactivatedNetListArea); @@ -95,10 +125,16 @@ void TabPage::initUI() m_settingsLayout = new QHBoxLayout(m_settingsFrame); m_settingsLayout->setContentsMargins(SETTINGS_LAYOUT_MARGINS); - m_settingsBtn = new KBorderlessButton(m_settingsFrame); - m_settingsBtn->setText(tr("Settings")); +// m_settingsBtn = new KBorderlessButton(m_settingsFrame); +// m_settingsBtn->setText(tr("Settings")); +// m_settingsLayout->addWidget(m_settingsBtn); - m_settingsLayout->addWidget(m_settingsBtn); + m_settingsLabel = new KyLable(m_settingsFrame); + m_settingsLabel->setCursor(Qt::PointingHandCursor); + m_settingsLabel->setText(tr("Settings")); + m_settingsLabel->setScaledContents(true); + + m_settingsLayout->addWidget(m_settingsLabel); m_settingsLayout->addStretch(); m_settingsFrame->setLayout(m_settingsLayout); @@ -113,9 +149,9 @@ void TabPage::initUI() m_mainLayout->addWidget(m_inactivatedNetDivider); m_mainLayout->addWidget(m_settingsFrame); - QPalette pal = m_inactivatedNetListArea->palette(); - pal.setBrush(QPalette::Base, QColor(0,0,0,0)); //背景透明 - m_inactivatedNetListArea->setPalette(pal); +// QPalette pal = m_inactivatedNetListArea->palette(); +// pal.setBrush(QPalette::Base, QColor(0,0,0,0)); //背景透明 +// m_inactivatedNetListArea->setPalette(pal); onPaletteChanged(); } @@ -137,6 +173,141 @@ void TabPage::onPaletteChanged() } } +int TabPage::getCurrentLoadRate(QString dev, long *save_rate, long *tx_rate) +{ + FILE * net_dev_file; //文件指针 + char buffer[1024]; //文件中的内容暂存在字符缓冲区里 + //size_t bytes_read; //实际读取的内容大小 + char * match; //用以保存所匹配字符串及之后的内容 + char * device;//将QString转为Char * + QByteArray ba = dev.toLatin1(); // must + device = ba.data(); + int counter = 0; + //int i = 0; + char tmp_value[128]; + + if ((NULL == device) || (NULL == save_rate) || (NULL == tx_rate)) { + qDebug() << LOG_FLAG << "parameter pass error" ; + return -1; + } + + if ((net_dev_file = fopen("/proc/net/dev", "r")) == NULL) { + //打开文件/pro/net/dev/,从中读取流量数据 + qDebug() << LOG_FLAG << "error occurred when try to open file /proc/net/dev/"; + return -1; + } + memset(buffer, 0, sizeof(buffer)); + + while (fgets(buffer, sizeof(buffer), net_dev_file) != NULL) { + match = strstr(buffer, device); + + if (NULL == match) { + // qDebug()<<"No eth0 keyword to find!"; + continue; + } else { + match = match + strlen(device) + strlen(":"); //地址偏移到冒号 + sscanf(match, "%ld ", save_rate); + memset(tmp_value, 0, sizeof(tmp_value)); + sscanf(match, "%s ", tmp_value); + match = match + strlen(tmp_value); + for (size_t i=0; iitem(0); + ListItem *p_item = (ListItem *)m_activatedNetListWidget->itemWidget(activeitem); + if (isEmpty) { + p_item->m_lbLoadUp->hide(); + p_item->m_lbLoadDown->hide(); + p_item->m_lbLoadDownImg->hide(); + p_item->m_lbLoadUpImg->hide(); + return; + } + + if (this->isVisible()) { + + if (getCurrentLoadRate(dev, &start_rcv_rates, &start_tx_rates) == -1) { + start_rcv_rates = end_rcv_rates; + return; + } + + long int delta_rcv = (start_rcv_rates - end_rcv_rates) / 1024; + long int delta_tx = (start_tx_rates - end_tx_rates) / 1024; + + //简易滤波 + if (delta_rcv < 0 || delta_tx < 0) { + delta_rcv = 0; + delta_tx = 0; + } + else if (end_rcv_rates == 0 || end_tx_rates == 0){ + delta_rcv = 0; + delta_tx = 0; + } + + end_rcv_rates = start_rcv_rates; + end_tx_rates = start_tx_rates; + + int rcv_num = delta_rcv; + int tx_num = delta_tx; + + QString str_rcv = 0; + QString str_tx = 0; + + if (rcv_num < 1024) { + str_rcv = QString::number(rcv_num) + "KB/s"; + } else { + int remainder; + if (rcv_num % 1024 < 100) { + remainder = 0; + } else { + remainder = (rcv_num % 1024) / 100; + } + str_rcv = QString::number(rcv_num / 1024) + "." + QString::number(remainder) + "MB/s"; + } + + if (tx_num < 1024) { + str_tx = QString::number(tx_num) + "KB/s"; + } else { + int remainder; + if (tx_num % 1024 < 100) { + remainder = 0; + } else { + remainder = (tx_num % 1024)/100; + } + str_tx = QString::number(tx_num / 1024) + "." + QString::number(remainder) + "MB/s"; + } + p_item->m_lbLoadDown->setText(str_rcv); + p_item->m_lbLoadUp->setText(str_tx); + if (!p_item->m_hoverButton->isVisible()) { + p_item->m_lbLoadDown->show(); + p_item->m_lbLoadUp->show(); + p_item->m_lbLoadDownImg->show(); + p_item->m_lbLoadUpImg->show(); + } + } +} + void TabPage::showDesktopNotify(const QString &message, QString soundName) { QDBusInterface iface("org.freedesktop.Notifications", @@ -211,8 +382,6 @@ void setDefaultDevice(KyDeviceType deviceType, QString deviceName) delete m_settings; m_settings = nullptr; - - return; } bool checkDeviceExist(KyDeviceType deviceType, QString deviceName) @@ -239,37 +408,9 @@ bool checkDeviceExist(KyDeviceType deviceType, QString deviceName) return devList.contains(deviceName); } -void saveDeviceEnableState(QString deviceName, bool enable) -{ - QSettings * m_settings = new QSettings(CONFIG_FILE_PATH, QSettings::IniFormat); - m_settings->beginGroup("CARDEABLE"); - m_settings->setValue(deviceName, enable); - m_settings->endGroup(); - m_settings->sync(); - delete m_settings; - m_settings = nullptr; - return; -} - -void deleteDeviceEnableState(QString deviceName) -{ - QSettings * m_settings = new QSettings(CONFIG_FILE_PATH, QSettings::IniFormat); - m_settings->beginGroup("CARDEABLE"); - m_settings->remove(deviceName); - m_settings->endGroup(); - m_settings->sync(); - delete m_settings; - m_settings = nullptr; - return; -} - void getDeviceEnableState(int type, QMap &map) { map.clear(); - if (!QFile::exists(CONFIG_FILE_PATH)) { - qDebug() << "CONFIG_FILE_PATH not exist"; - return; - } if (type != WIRED && type != WIRELESS) { qDebug() << "getDeviceEnableState but wrong type"; return; @@ -280,34 +421,41 @@ void getDeviceEnableState(int type, QMap &map) wiredDevList.clear(); wirelessDevList.clear(); - QSettings * m_settings = new QSettings(CONFIG_FILE_PATH, QSettings::IniFormat); - m_settings->beginGroup("CARDEABLE"); - if (type == WIRED) { kdr->getNetworkDeviceList(NetworkManager::Device::Type::Ethernet, wiredDevList); if (!wiredDevList.isEmpty()) { for (int i = 0; i < wiredDevList.size(); ++i) { - if (!m_settings->contains(wiredDevList.at(i))) { - saveDeviceEnableState(wiredDevList.at(i),true); - } - bool enable = m_settings->value(wiredDevList.at(i), true).toBool(); - map.insert(wiredDevList.at(i), enable); + QString devName = wiredDevList.at(i); + map.insert(devName, kdr->getDeviceManaged(devName)); } } } else if (type == WIRELESS) { kdr->getNetworkDeviceList(NetworkManager::Device::Type::Wifi, wirelessDevList); if (!wirelessDevList.isEmpty()) { for (int i = 0; i < wirelessDevList.size(); ++i) { - bool enable = m_settings->value(wirelessDevList.at(i), true).toBool(); - map.insert(wirelessDevList.at(i), enable); + QString devName = wirelessDevList.at(i); + map.insert(devName, kdr->getDeviceManaged(devName)); } } } - m_settings->endGroup(); - delete m_settings; - m_settings = nullptr; delete kdr; kdr = nullptr; - return; +} + +bool getOldVersionWiredSwitchState(bool &state) +{ + QSettings * m_settings = new QSettings(CONFIG_FILE_PATH, QSettings::IniFormat); + QVariant value = m_settings->value("lan_switch_opened"); + + if (!value.isValid()) { + delete m_settings; + m_settings = nullptr; + return false; + } + state = value.toBool(); + m_settings->remove("lan_switch_opened"); + delete m_settings; + m_settings = nullptr; + return true; } diff --git a/src/frontend/tab-pages/tabpage.h b/src/frontend/tab-pages/tabpage.h index 60d6319f..1fc76eea 100644 --- a/src/frontend/tab-pages/tabpage.h +++ b/src/frontend/tab-pages/tabpage.h @@ -1,9 +1,30 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef TABPAGE_H #define TABPAGE_H #include "divider.h" +#include "kylable.h" #include #include +#include #include #include #include @@ -15,7 +36,11 @@ #include "kylinnetworkdeviceresource.h" #include "kwidget.h" #include "kswitchbutton.h" -#include "kborderlessbutton.h" +//#include "kborderlessbutton.h" + +#define EMPTY_SSID "emptyssid" + +#define REFRESH_NETWORKSPEED_TIMER 1000 using namespace kdk; @@ -26,19 +51,20 @@ using namespace kdk; #define DEVICE_LAYOUT_MARGINS 24,0,24,8 #define DEVICE_COMBOBOX_WIDTH 180 #define ACTIVE_NET_LAYOUT_MARGINS 8,8,8,8 -#define NET_LAYOUT_MARGINS 8,8,0,3 +#define NET_LAYOUT_MARGINS 8,8,0,1 #define NET_LAYOUT_SPACING 8 #define NET_LIST_SPACING 0 #define TEXT_MARGINS 16,0,0,0 +#define TEXT_HEIGHT 20 //#define SCROLL_AREA_HEIGHT 200 -#define SETTINGS_LAYOUT_MARGINS 24,0,24,0 +#define SETTINGS_LAYOUT_MARGINS 23,0,24,0 #define TRANSPARENT_COLOR QColor(0,0,0,0) #define INACTIVE_AREA_MIN_HEIGHT 170 #define ACTIVE_AREA_MAX_HEIGHT 92 #define MAX_ITEMS 4 -#define MAX_WIDTH 400 -#define MIN_WIDTH 383 +#define MAX_WIDTH 412 +#define MIN_WIDTH 404 #define SCROLL_STEP 4 @@ -52,9 +78,8 @@ const QString CONFIG_FILE_PATH = QDir::homePath() + "/.config/ukui/kylin-nm.c bool checkDeviceExist(KyDeviceType deviceType, QString deviceName); QString getDefaultDeviceName(KyDeviceType deviceType); void setDefaultDevice(KyDeviceType deviceType, QString deviceName); -void saveDeviceEnableState(QString deviceName, bool enable); -void deleteDeviceEnableState(QString deviceName); void getDeviceEnableState(int type, QMap &map); +bool getOldVersionWiredSwitchState(bool &state); class TabPage : public QWidget { @@ -82,7 +107,7 @@ public: } } -signals: +Q_SIGNALS: void deviceStatusChanged(); void deviceNameChanged(QString oldName, QString newName, int type); void activateFailed(QString errorMessage); @@ -90,8 +115,10 @@ signals: protected: void initUI(); + int getCurrentLoadRate(QString dev, long *save_rate, long *tx_rate); // virtual void initDevice() = 0;//初始化默认设备 virtual void initDeviceCombox() = 0;//初始化设备选择下拉框 + QTimer *setNetSpeed = nullptr; QVBoxLayout * m_mainLayout = nullptr; QFrame * m_titleFrame = nullptr; QHBoxLayout * m_titleLayout = nullptr; @@ -107,14 +134,16 @@ protected: QFrame * m_inactivatedNetFrame = nullptr; QVBoxLayout * m_inactivatedNetLayout = nullptr; QLabel * m_inactivatedNetLabel = nullptr; - QScrollArea * m_inactivatedNetListArea = nullptr; +// QScrollArea * m_inactivatedNetListArea = nullptr; + QWidget * m_inactivatedNetListArea = nullptr; QVBoxLayout * m_inactivatedAreaLayout = nullptr; Divider * m_inactivatedNetDivider = nullptr; QFrame * m_settingsFrame = nullptr; QHBoxLayout * m_settingsLayout = nullptr; - KBorderlessButton *m_settingsBtn = nullptr; + KyLable * m_settingsLabel = nullptr; +// KBorderlessButton *m_settingsBtn = nullptr; //临时增加的下拉框选择网卡区域 QFrame * m_deviceFrame = nullptr; @@ -123,10 +152,17 @@ protected: QComboBox * m_deviceComboBox = nullptr; QLabel * m_tipsLabel = nullptr; -public slots: + long int start_rcv_rates = 0; //保存开始时的流量计数 + long int end_rcv_rates = 0; //保存结束时的流量计数 + long int start_tx_rates = 0; //保存开始时的流量计数 + long int end_tx_rates = 0; //保存结束时的流量计数 + +public Q_SLOTS: virtual void onDeviceComboxIndexChanged(int currentIndex) = 0; void onPaletteChanged(); +protected Q_SLOTS: + void onSetNetSpeed(QListWidget* m_activatedNetListWidget, bool isActive, QString dev); }; #endif // TABPAGE_H diff --git a/src/frontend/tab-pages/wlanpage.cpp b/src/frontend/tab-pages/wlanpage.cpp index f968eaeb..3470113b 100644 --- a/src/frontend/tab-pages/wlanpage.cpp +++ b/src/frontend/tab-pages/wlanpage.cpp @@ -1,5 +1,26 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "wlanpage.h" #include "kywirelessnetitem.h" +#include "kwindowsystem.h" +#include "kwindowsystem_export.h" #include #include #include @@ -8,7 +29,7 @@ #define AP_SCAN_INTERVAL (20*1000) #define ICON_REFRESH_INTERVAL (5*1000) -#define EMPTY_SSID "emptyssid" + #define LOG_FLAG "[WlanPage]" #define LAN_PAGE_INDEX 0 @@ -17,6 +38,8 @@ const QString IsApConnection = "1"; WlanPage::WlanPage(QWidget *parent) : TabPage(parent) { + qRegisterMetaType("NetworkManager::Device::State"); + qRegisterMetaType("NetworkManager::Device::StateChangeReason"); m_wirelessNetResource = new KyWirelessNetResource(this); m_activatedConnectResource = new KyActiveConnectResourse(this); m_netDeviceResource=new KyNetworkDeviceResourse(this); @@ -47,6 +70,8 @@ WlanPage::WlanPage(QWidget *parent) : TabPage(parent) connect(m_netDeviceResource, &KyNetworkDeviceResourse::deviceRemove, this, &WlanPage::onDeviceRemove); connect(m_netDeviceResource, &KyNetworkDeviceResourse::deviceNameUpdate, this, &WlanPage::onDeviceNameUpdate); + connect(m_netDeviceResource, &KyNetworkDeviceResourse::stateChanged, this, &WlanPage::onWlanStateChanged); + connect(m_wirelessConnectOpreation, &KyWirelessConnectOperation::activateConnectionError, this, &WlanPage::activateFailed); connect(m_wirelessConnectOpreation, &KyWirelessConnectOperation::addAndActivateConnectionError, this, &WlanPage::activateFailed); connect(m_wirelessConnectOpreation, &KyWirelessConnectOperation::deactivateConnectionError, this, &WlanPage::deactivateFailed); @@ -54,11 +79,20 @@ WlanPage::WlanPage(QWidget *parent) : TabPage(parent) connect(m_wirelessConnectOpreation, &KyWirelessConnectOperation::wifiEnabledChanged, this, &WlanPage::onWifiEnabledChanged); connect(m_connectResource, &KyConnectResourse::connectivityChanged, this, &WlanPage::connectivityChanged); + connect(m_netSwitch, &KSwitchButton::clicked, this, [=](bool checked) { + //解决 switchBtn不支持点击的情况下,点击按钮,有无线网卡后不自动开启的问题 + if (getSwitchBtnEnable()) { + setSwitchBtnState(!checked); + setWirelessEnable(checked); + } + }); + m_wlanPagePtrMap.clear(); + m_joinHiddenWiFiPagePtrMap.clear(); } bool WlanPage::eventFilter(QObject *w, QEvent *e) { - if (w == m_settingsBtn) { + if (w == m_settingsLabel) { if (e->type() == QEvent::MouseButtonRelease) { //ZJP_TODO 打开控制面板 qDebug() << LOG_FLAG <<"recive event show control center"; @@ -66,18 +100,26 @@ bool WlanPage::eventFilter(QObject *w, QEvent *e) } } else if (w == m_netSwitch) { if (e->type() == QEvent::MouseButtonRelease) { - if (m_devList.isEmpty()) { + if (!getSwitchBtnEnable()) { showDesktopNotify(tr("No wireless network card detected"), "networkwrong"); //检测不到无线网卡不再触发click信号 - m_netSwitch->setCheckable(false); - m_netSwitch->setChecked(false); - } else { - m_wirelessConnectOpreation->setWirelessEnabled(!m_netSwitch->isChecked()); } - return true; + } + } else if (w == m_activatedNetListWidget) { + //去掉无右键菜单显示时的选中效果 + if (e->type() == QEvent::FocusIn) { + if (m_activatedNetListWidget->currentItem() != nullptr) { + m_activatedNetListWidget->currentItem()->setSelected(false); + } + } + } else if (w == m_inactivatedNetListWidget) { + //去掉无右键菜单显示时的选中效果 + if (e->type() == QEvent::FocusIn) { + if (m_inactivatedNetListWidget->currentItem() != nullptr) { + m_inactivatedNetListWidget->currentItem()->setSelected(false); + } } } - return QWidget::eventFilter(w,e); } @@ -93,6 +135,7 @@ void WlanPage::initWlanUI() m_activatedNetListWidget->setFixedHeight(NORMAL_HEIGHT); m_activatedNetListWidget->setFixedWidth(MIN_WIDTH); m_activatedNetListWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + m_activatedNetListWidget->setProperty("needTranslucent", true); m_activatedNetLayout->addWidget(m_activatedNetListWidget); m_inactivatedNetLabel->setText(tr("Other WLAN")); @@ -105,58 +148,62 @@ void WlanPage::initWlanUI() m_inactivatedNetListWidget->verticalScrollBar()->setProperty("drawScrollBarGroove",false); //去除滚动条的外侧黑框 m_inactivatedNetListWidget->verticalScrollBar()->setSingleStep(SCROLL_STEP); m_inactivatedNetListWidget->verticalScrollBar()->setContextMenuPolicy(Qt::NoContextMenu); + m_inactivatedNetListWidget->verticalScrollBar()->setProperty("needTranslucent", true); + m_inactivatedNetListWidget->setProperty("needTranslucent", true); addWlanMoreItem(); m_inactivatedAreaLayout->addWidget(m_inactivatedNetListWidget); + connect(m_inactivatedNetListWidget, &QListWidget::currentItemChanged, this, [=]() { + if (m_inactivatedNetListWidget->currentItem() != nullptr) { + m_inactivatedNetListWidget->currentItem()->setSelected(false); + } + }); + QPalette pal = m_activatedNetListWidget->palette(); pal.setBrush(QPalette::Base, QColor(0,0,0,0)); //背景透明 m_activatedNetListWidget->setPalette(pal); m_inactivatedNetListWidget->setPalette(pal); - m_settingsBtn->installEventFilter(this); + m_settingsLabel->installEventFilter(this); m_netSwitch->installEventFilter(this); + m_activatedNetListWidget->installEventFilter(this); + m_inactivatedNetListWidget->installEventFilter(this); + + showRate(); } - -void WlanPage::onWlanSwithGsettingsChanged(const QString &key) +bool WlanPage::getWirelessDevieceUseable() { - if (key == WIRELESS_SWITCH) { - m_wlanSwitchEnable = m_switchGsettings->get(WIRELESS_SWITCH).toBool(); - qDebug() << LOG_FLAG << "wlan switch state" << m_wlanSwitchEnable; - - m_netSwitch->setChecked(m_wlanSwitchEnable); - - initDeviceCombox(); - initWlanArea(); + for (auto devname : m_devList) { + if (m_netDeviceResource->getDeviceState(devname) >= NetworkManager::Device::Disconnected) { + return true; + } } + return false; +} +void WlanPage::setWirelessEnable(bool state) +{ + m_wirelessConnectOpreation->setWirelessEnabled(state); return; } +bool WlanPage::getWirelessEnable() +{ + return m_wirelessConnectOpreation->getWirelessEnabled(); +} + void WlanPage::initWlanSwitchState() { - bool wirelessGsetting = true; - bool wirelessEnabled = m_wirelessConnectOpreation->getWirelessEnabled(); - if (QGSettings::isSchemaInstalled(GSETTINGS_SCHEMA)) { - m_switchGsettings = new QGSettings(GSETTINGS_SCHEMA); - if (m_switchGsettings->keys().contains(WIRELESS_SWITCH)) { - if (m_devList.isEmpty()) { - m_netSwitch->setCheckable(false); - m_netSwitch->setChecked(false); - } else { - wirelessGsetting = m_switchGsettings->get(WIRELESS_SWITCH).toBool(); - if (wirelessEnabled - != wirelessGsetting) { - //以后端状态为准 - m_switchGsettings->set(WIRELESS_SWITCH, wirelessEnabled); - } - m_netSwitch->setChecked(wirelessEnabled); - } - connect(m_switchGsettings, &QGSettings::changed, this, &WlanPage::onWlanSwithGsettingsChanged); - } + if (m_devList.isEmpty()) { + setSwitchBtnState(false); + setSwitchBtnEnable(false); + return ; } - m_netSwitch->setChecked(wirelessEnabled); - m_wlanSwitchEnable = wirelessEnabled; + + setSwitchBtnEnable(true); + setSwitchBtnState(getWirelessDevieceUseable()); + return; } void WlanPage::initTimer() @@ -188,7 +235,7 @@ void WlanPage::initDeviceCombox() this, &WlanPage::onDeviceComboxIndexChanged); m_deviceComboBox->clear(); - if (m_netSwitch->isChecked()) { + if (getSwitchBtnState()) { if (0 == m_devList.count()) { m_deviceFrame->show(); m_tipsLabel->show(); @@ -218,8 +265,9 @@ void WlanPage::initDeviceCombox() } } else { m_deviceFrame->hide(); - m_currentDevice = ""; - setDefaultDevice(WIRELESS, m_currentDevice); + //解决因m_currentDevice被置空,安全中心网络显示BUG +// m_currentDevice = ""; +// setDefaultDevice(WIRELESS, m_currentDevice); } connect(m_deviceComboBox, QOverload::of(&QComboBox::currentIndexChanged), @@ -231,7 +279,7 @@ QListWidgetItem *WlanPage::addEmptyItem(QListWidget *wirelessListWidget) { WlanListItem *p_wlanItem = new WlanListItem(); QListWidgetItem *p_listWidgetItem = new QListWidgetItem(); - p_listWidgetItem->setFlags(p_listWidgetItem->flags() & (~Qt::ItemIsSelectable)); //设置不可被选中 +// p_listWidgetItem->setFlags(p_listWidgetItem->flags() & (~Qt::ItemIsSelectable)); //设置不可被选中 p_listWidgetItem->setSizeHint(QSize(wirelessListWidget->width(), p_wlanItem->height())); wirelessListWidget->addItem(p_listWidgetItem); wirelessListWidget->setItemWidget(p_listWidgetItem, p_wlanItem); @@ -247,9 +295,10 @@ QListWidgetItem *WlanPage::addNewItem(KyWirelessNetItem &wirelessNetItem, m_currentDevice, m_connectResource->isApConnection(wirelessNetItem.m_connectUuid)); connect(p_wlanItem, &WlanListItem::itemHeightChanged, this, &WlanPage::onItemHeightChanged); + connect(p_wlanItem, &WlanListItem::detailShow, this, &WlanPage::showDetailPage); QListWidgetItem *p_listWidgetItem = new QListWidgetItem(); - p_listWidgetItem->setFlags(p_listWidgetItem->flags() & (~Qt::ItemIsSelectable)); +// p_listWidgetItem->setFlags(p_listWidgetItem->flags() & (~Qt::ItemIsSelectable)); p_listWidgetItem->setSizeHint(QSize(wirelessListWidget->width(), p_wlanItem->height())); wirelessListWidget->addItem(p_listWidgetItem); wirelessListWidget->setItemWidget(p_listWidgetItem, p_wlanItem); @@ -263,9 +312,10 @@ QListWidgetItem *WlanPage::insertNewItem(KyWirelessNetItem &wirelessNetItem, { WlanListItem *p_wlanItem = new WlanListItem(wirelessNetItem, m_currentDevice); connect(p_wlanItem, &WlanListItem::itemHeightChanged, this, &WlanPage::onItemHeightChanged); + connect(p_wlanItem, &WlanListItem::detailShow, this, &WlanPage::showDetailPage); QListWidgetItem *p_listWidgetItem = new QListWidgetItem(); - p_listWidgetItem->setFlags(p_listWidgetItem->flags() & (~Qt::ItemIsSelectable)); +// p_listWidgetItem->setFlags(p_listWidgetItem->flags() & (~Qt::ItemIsSelectable)); p_listWidgetItem->setSizeHint(QSize(wirelessListWidget->width(), p_wlanItem->height())); wirelessListWidget->insertItem(row, p_listWidgetItem); wirelessListWidget->setItemWidget(p_listWidgetItem, p_wlanItem); @@ -283,9 +333,10 @@ QListWidgetItem *WlanPage::insertNewItemWithSort(KyWirelessNetItem &wirelessNetI // << "signal strength" << wirelessNetItem.m_signalStrength; WlanListItem *p_sortWlanItem = new WlanListItem(wirelessNetItem, m_currentDevice); connect(p_sortWlanItem, &WlanListItem::itemHeightChanged, this, &WlanPage::onItemHeightChanged); + connect(p_sortWlanItem, &WlanListItem::detailShow, this, &WlanPage::showDetailPage); QListWidgetItem *p_sortListWidgetItem = new QListWidgetItem(); - p_sortListWidgetItem->setFlags(p_sortListWidgetItem->flags() & (~Qt::ItemIsSelectable)); +// p_sortListWidgetItem->setFlags(p_sortListWidgetItem->flags() & (~Qt::ItemIsSelectable)); p_sortListWidgetItem->setSizeHint(QSize(p_ListWidget->width(), p_sortWlanItem->height())); // qDebug() << "insertNewItemWithSort, count" << p_ListWidget->count(); @@ -336,10 +387,8 @@ void WlanPage::clearWirelessNetItemMap(QMap &wireless wirelessListWidget->removeItemWidget(p_listWidgetItem); delete p_wlanItem; - p_wlanItem = nullptr; delete p_listWidgetItem; - p_listWidgetItem = nullptr; iter = wirelessNetItem.erase(iter); } @@ -367,12 +416,10 @@ void WlanPage::deleteWirelessItemFormMap(QMap &wirele wirelessListWidget->takeItem(wirelessListWidget->row(p_listWidgetItem)); delete p_wlanItem; - p_wlanItem = nullptr; delete p_listWidgetItem; - p_listWidgetItem = nullptr; - if (m_inactivatedNetListWidget->count() < MAX_ITEMS) { + if (m_inactivatedNetListWidget->count() <= MAX_ITEMS) { m_inactivatedNetListWidget->setFixedWidth(MIN_WIDTH); } return; @@ -405,6 +452,7 @@ void WlanPage::constructActivateConnectionArea() updateWlanItemState(m_activatedNetListWidget, p_listWidgetItem, Activated); height += p_listWidgetItem->sizeHint().height(); + setNetSpeed->start(REFRESH_NETWORKSPEED_TIMER); } } @@ -436,7 +484,7 @@ void WlanPage::constructWirelessNetArea() QString activateSsid = m_activateConnectionItemMap.firstKey(); - foreach (auto wirelessNetItem, wirelessNetItemList) { + Q_FOREACH (auto wirelessNetItem, wirelessNetItemList) { if (wirelessNetItem.m_NetSsid == activateSsid) { continue; } @@ -450,7 +498,7 @@ void WlanPage::constructWirelessNetArea() qDebug() << "[WlanPage] Stopped loading wireless net list! time=" << QDateTime::currentDateTime().toString("hh:mm:ss.zzzz"); - if (m_inactivatedNetListWidget->count() < MAX_ITEMS) { + if (m_inactivatedNetListWidget->count() <= MAX_ITEMS) { m_inactivatedNetListWidget->setFixedWidth(MIN_WIDTH); } else { m_inactivatedNetListWidget->setFixedWidth(MAX_WIDTH); @@ -460,7 +508,7 @@ void WlanPage::constructWirelessNetArea() void WlanPage::initWlanArea() { - if (m_netSwitch->isChecked()) { + if (getSwitchBtnState()) { m_activatedNetFrame->show(); m_activatedNetDivider->show(); constructActivateConnectionArea(); @@ -486,7 +534,7 @@ void WlanPage::onWlanAdded(QString interface, KyWirelessNetItem &item) << item.m_secuType << (m_connectResource->isApConnection(item.m_connectUuid) ? IsApConnection : NotApConnection) << QString::number(item.getCategory(item.m_uni)); - emit wlanAdd(interface, info); + Q_EMIT wlanAdd(interface, info); if (interface != m_currentDevice) { qDebug() << "[WlanPage] wlan add interface not equal defaultdevice"; @@ -505,7 +553,7 @@ void WlanPage::onWlanAdded(QString interface, KyWirelessNetItem &item) updateWlanItemState(m_inactivatedNetListWidget, p_listWidgetItem, Deactivated); addWlanMoreItem(); - if (m_inactivatedNetListWidget->count() >= MAX_ITEMS) { + if (m_inactivatedNetListWidget->count() > MAX_ITEMS) { m_inactivatedNetListWidget->setFixedWidth(MAX_WIDTH); } return; @@ -513,7 +561,13 @@ void WlanPage::onWlanAdded(QString interface, KyWirelessNetItem &item) void WlanPage::onWlanRemoved(QString interface, QString ssid) { - emit wlanRemove(interface, ssid); + Q_EMIT wlanRemove(interface, ssid); + + if (m_wlanPagePtrMap.contains(interface) && m_wlanPagePtrMap[interface].contains(ssid)) { + if (m_wlanPagePtrMap[interface][ssid] != nullptr) { + m_wlanPagePtrMap[interface][ssid]->close(); + } + } if (interface != m_currentDevice) { qDebug()<<"[WlanPage] the device is not current device," @@ -540,7 +594,7 @@ void WlanPage::onWlanRemoved(QString interface, QString ssid) } else { deleteWirelessItemFormMap(m_activateConnectionItemMap, m_activatedNetListWidget, ssid); - showDesktopNotify(tr("WLAN Disconnected Successfully"), "networkdisconnected"); +// showDesktopNotify(tr("WLAN Disconnected Successfully"), "networkdisconnected"); QListWidgetItem *p_listWidgetItem = addEmptyItem(m_activatedNetListWidget); m_activateConnectionItemMap.insert(EMPTY_SSID, p_listWidgetItem); @@ -562,7 +616,7 @@ void WlanPage::updateWlanListItem(QString ssid) WlanListItem *p_wlanItem = (WlanListItem *)m_inactivatedNetListWidget->itemWidget(p_listWidgetItem); p_wlanItem->updateWirelessNetItem(wirelessNetItem); p_wlanItem->updateConnectState(Deactivated); - emit this->wlanConnectChanged(Deactivated); + Q_EMIT this->wlanConnectChanged(Deactivated); } } @@ -580,12 +634,12 @@ void WlanPage::onConnectionAdd(QString deviceName, QString ssid) return; } -void WlanPage::onConnectionRemove(QString deviceName, QString ssid) +void WlanPage::onConnectionRemove(QString deviceName, QString ssid, QString path) { qDebug() << LOG_FLAG << "one connection is removed, it's ssid " << ssid << "device name"<< deviceName; if (deviceName == m_currentDevice) { if (m_activateConnectionItemMap.contains(ssid)) { - updateWirelessNetArea(nullptr, ssid, deviceName); + updateWirelessNetArea(nullptr, ssid, deviceName, path); } updateWlanListItem(ssid); } @@ -612,7 +666,7 @@ void WlanPage::onSecurityTypeChange(QString devName, QString ssid, QString secuT p_wlanItem->updateWirelessNetSecurity(ssid, secuType); } - emit secuTypeChange(devName, ssid, secuType); + Q_EMIT secuTypeChange(devName, ssid, secuType); return; } @@ -622,7 +676,7 @@ void WlanPage::addDeviceToCombox(QString deviceName) { disconnect(m_deviceComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, &WlanPage::onDeviceComboxIndexChanged); - if (m_netSwitch->isChecked()) { + if (getSwitchBtnState()) { if (m_currentDevice.isEmpty()){ m_deviceFrame->hide(); m_currentDevice = deviceName; @@ -654,19 +708,16 @@ void WlanPage::onDeviceAdd(QString deviceName, NetworkManager::Device::Type devi return; } - if (m_devList.isEmpty()) { - bool wlanSwitch = m_switchGsettings->get(WIRELESS_SWITCH).toBool(); - m_netSwitch->setCheckable(true); - m_netSwitch->setChecked(wlanSwitch); - } - m_devList << deviceName; + setSwitchBtnEnable(true); + setSwitchBtnState(getWirelessDevieceUseable()); + addDeviceToCombox(deviceName); if (m_currentDevice == deviceName) { initWlanArea(); } - emit deviceStatusChanged(); + Q_EMIT deviceStatusChanged(); return; } @@ -676,7 +727,7 @@ void WlanPage::deleteDeviceFromCombox(QString deviceName) disconnect(m_deviceComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, &WlanPage::onDeviceComboxIndexChanged); - if (m_netSwitch->isChecked()) { + if (getSwitchBtnState()) { if (0 == m_devList.count()) { m_deviceFrame->hide(); //m_tipsLabel->show(); @@ -713,19 +764,25 @@ void WlanPage::onDeviceRemove(QString deviceName) QString originalDeviceName = m_currentDevice; + if (m_joinHiddenWiFiPagePtrMap.contains(deviceName)) { + if (m_joinHiddenWiFiPagePtrMap[deviceName] != nullptr) { + m_joinHiddenWiFiPagePtrMap[deviceName]->close(); + } + } + m_devList.removeOne(deviceName); deleteDeviceFromCombox(deviceName); if (m_devList.isEmpty()) { - m_netSwitch->setCheckable(false); - m_netSwitch->setChecked(false); + setSwitchBtnState(false); + setSwitchBtnEnable(false); } if (originalDeviceName == deviceName) { initWlanArea(); } - emit deviceStatusChanged(); + Q_EMIT deviceStatusChanged(); } void WlanPage::updateDeviceForCombox(QString oldDeviceName, QString newDeviceName) @@ -762,7 +819,19 @@ void WlanPage::onDeviceNameUpdate(QString oldName, QString newName) initWlanArea(); } - emit deviceNameChanged(oldName, newName, WIRELESS); + Q_EMIT deviceNameChanged(oldName, newName, WIRELESS); +} + +void WlanPage::onWlanStateChanged(NetworkManager::Device::State newstate, NetworkManager::Device::State oldstate, NetworkManager::Device::StateChangeReason reason) +{ + if (getSwitchBtnState() == getWirelessDevieceUseable()) { + return ; + } + setSwitchBtnEnable(true); + setSwitchBtnState(getWirelessDevieceUseable()); + initDeviceCombox(); + initWlanArea(); + Q_EMIT wirelessSwitchBtnChanged(getSwitchBtnState()); } void WlanPage::sendApStateChangeSignal(QString uuid, @@ -778,15 +847,20 @@ void WlanPage::sendApStateChangeSignal(QString uuid, if (state == NetworkManager::ActiveConnection::State::Deactivated) { qDebug() << "[WlanPage] hotspot Deactivated"; - emit hotspotDeactivated(deviceName, ssid); + Q_EMIT hotspotDeactivated(deviceName, ssid); } else if (state == NetworkManager::ActiveConnection::State::Activated) { - qDebug() << "[WlanPage] hotspot activated"; - emit hotspotActivated(deviceName, ssid, uuid); + QString activePath; + QString settingPath; + activePath = m_activatedConnectResource->getAcitveConnectionPathByUuid(uuid); + settingPath = m_connectResource->getApConnectionPathByUuid(uuid); + qDebug() << "[WlanPage] hotspot activated"<setFixedHeight(p_listWidgetItem->sizeHint().height()); - if (m_inactivatedNetListWidget->count() < MAX_ITEMS) { + if (m_inactivatedNetListWidget->count() <= MAX_ITEMS) { m_inactivatedNetListWidget->setFixedWidth(MIN_WIDTH); } return; } -void WlanPage::updateWirelessNetArea(QString uuid, QString ssid, QString devName) +void WlanPage::updateWirelessNetArea(QString uuid, QString ssid, QString devName, QString path) { if(m_wirelessNetItemMap.contains(ssid)) { return; } if (m_activateConnectionItemMap.contains(ssid)) { - deleteWirelessItemFormMap(m_activateConnectionItemMap, m_activatedNetListWidget, ssid); - QListWidgetItem *p_activeListWidgetItem = addEmptyItem(m_activatedNetListWidget); - m_activateConnectionItemMap.insert(EMPTY_SSID, p_activeListWidgetItem); - m_activatedNetListWidget->setFixedHeight(p_activeListWidgetItem->sizeHint().height()); + QListWidgetItem *p_listWidgetItem = m_activateConnectionItemMap.value(ssid); + if (nullptr == p_listWidgetItem) { + qWarning()<< LOG_FLAG <<"wireless item is not exsit, it's ssid is " << ssid; + return; + } + WlanListItem *p_wlanItem = (WlanListItem *)m_activatedNetListWidget->itemWidget(p_listWidgetItem); + if (nullptr == p_wlanItem) { + qWarning() << LOG_FLAG << "p_wlanItem is null"; + return; + } + + if (p_wlanItem->getUuid() == uuid || uuid.isEmpty()) { + if (uuid.isEmpty() && p_wlanItem->getPath() != path) { + return; + } + + deleteWirelessItemFormMap(m_activateConnectionItemMap, m_activatedNetListWidget, ssid); + QListWidgetItem *p_activeListWidgetItem = addEmptyItem(m_activatedNetListWidget); + m_activateConnectionItemMap.insert(EMPTY_SSID, p_activeListWidgetItem); + m_activatedNetListWidget->setFixedHeight(p_activeListWidgetItem->sizeHint().height()); + } } else { qDebug() << LOG_FLAG << ssid << "is not in activeconnection map"; } @@ -858,7 +950,7 @@ void WlanPage::updateWirelessNetArea(QString uuid, QString ssid, QString devName // 更新‘更多’条目,以保证其处于listwidget的最底部 addWlanMoreItem(); - if (m_inactivatedNetListWidget->count() < MAX_ITEMS) { + if (m_inactivatedNetListWidget->count() <= MAX_ITEMS) { m_inactivatedNetListWidget->setFixedWidth(MIN_WIDTH); } else { m_inactivatedNetListWidget->setFixedWidth(MAX_WIDTH); @@ -874,34 +966,30 @@ void WlanPage::onConnectionStateChanged(QString uuid, m_wirelessNetResource->getSsidByUuid(uuid, ssid); m_wirelessNetResource->getDeviceByUuid(uuid, devName); - qDebug()<< LOG_FLAG << "emit wlanActiveConnectionStateChanged" << devName << ssid << state; - emit wlanActiveConnectionStateChanged(devName, ssid, uuid, state); - - if (ssid.isEmpty() || devName.isEmpty()) { - qDebug()<< LOG_FLAG << "ssid or devicename is empty" - << "devicename"<< devName <<"ssid"<isWirelessConnection(uuid)) { qDebug()<< LOG_FLAG << "it is not wireless connection" << uuid; return; } - emit this->wlanConnectChanged(state); + Q_EMIT this->wlanConnectChanged(state); - if (m_connectResource->isApConnection(uuid)) { + bool isApConnection = m_connectResource->isApConnection(uuid); + + if (isApConnection) { sendApStateChangeSignal(uuid, ssid, devName, state); } else { if (state == NetworkManager::ActiveConnection::State::Deactivated && !m_activateConnectionItemMap.contains(ssid)) { qDebug() << "wlan remove before deactivated"; } else { - wlanShowNotify(ssid, state, reason); +// wlanShowNotify(ssid, state, reason); } } - if (devName != m_currentDevice) { + if (!devName.isEmpty() && devName != m_currentDevice) { return; } @@ -910,13 +998,20 @@ void WlanPage::onConnectionStateChanged(QString uuid, if (state == NetworkManager::ActiveConnection::State::Activated) { m_updateStrength = true; updateActivatedArea(uuid, ssid, devName); + setNetSpeed->start(REFRESH_NETWORKSPEED_TIMER); if (m_activateConnectionItemMap.contains(ssid)) { QListWidgetItem *p_listWidgetItem = m_activateConnectionItemMap.value(ssid); updateWlanItemState(m_activatedNetListWidget, p_listWidgetItem, Activated); } } else if (state == NetworkManager::ActiveConnection::State::Deactivated) { m_updateStrength = true; - updateWirelessNetArea(uuid, ssid, devName); + if (devName.isEmpty()) { + devName = m_currentDevice; + } + + updateWirelessNetArea(uuid, ssid, devName,""); + setNetSpeed->stop(); + if (m_wirelessNetItemMap.contains(ssid)) { QListWidgetItem *p_listWidgetItem = m_wirelessNetItemMap.value(ssid); updateWlanItemState(m_inactivatedNetListWidget, p_listWidgetItem, Deactivated); @@ -1002,8 +1097,7 @@ void WlanPage::requestScan() void WlanPage::onHiddenWlanClicked() { qDebug() << "[wlanPage] AddHideWifi Clicked! " << Q_FUNC_INFO << __LINE__ ; - NetDetail *netDetail = new NetDetail(m_currentDevice, "", "", false, true, true); - netDetail->show(); + showHiddenWlanPage(m_currentDevice); } void WlanPage::showControlCenter() @@ -1020,22 +1114,6 @@ void WlanPage::onWifiEnabledChanged(bool isWifiOn) { //监听外部命令导致wifi状态变化,更新界面 qDebug() << "[WlanPage] onWifiEnabledChanged wifi state" << isWifiOn; - - //应该先检测是否有无线网卡可用,才改变开关状态 - if (m_devList.isEmpty()) { - qDebug() << "[WLanPage] have no device to use " << Q_FUNC_INFO << __LINE__; - return; - } - - if (m_wlanSwitchEnable == isWifiOn) { - return; - } else { - if (!m_netSwitch->isChecked()) { - m_netSwitch->setChecked(true); - } - m_switchGsettings->set(WIRELESS_SWITCH, isWifiOn); - } - return; } @@ -1057,7 +1135,7 @@ void WlanPage::onRefreshIconTimer() return; } - emit timeToUpdate(); + Q_EMIT timeToUpdate(); if(!this->isVisible()) { return; @@ -1074,7 +1152,10 @@ void WlanPage::onRefreshIconTimer() return; } - + //解决没有无线设备且m_currentDevice不清空的情况下,m_activateConnectionItemMap为空造成的段错误 + if (m_activateConnectionItemMap.isEmpty()) { + return ; + } QString activateSsid = m_activateConnectionItemMap.firstKey(); int sortRow = 0; for (int index = 0; index < wlanList.length(); index++) { @@ -1125,6 +1206,7 @@ void WlanPage::onRefreshIconTimer() WlanListItem *p_sortWlanItem = new WlanListItem(sortItem, m_currentDevice); connect(p_sortWlanItem, &WlanListItem::itemHeightChanged, this, &WlanPage::onItemHeightChanged); + connect(p_sortWlanItem, &WlanListItem::detailShow, this, &WlanPage::showDetailPage); m_inactivatedNetListWidget->insertItem(sortRow, p_sortListWidgetItem); m_inactivatedNetListWidget->setItemWidget(p_sortListWidgetItem, p_sortWlanItem); updateWlanItemState(m_inactivatedNetListWidget, p_sortListWidgetItem, Deactivated); @@ -1189,7 +1271,7 @@ void WlanPage::getWirelessList(QMap > &map) vector.append(QStringList("--")); } //未连接 - foreach (auto itemData, iter.value()) { + Q_FOREACH (auto itemData, iter.value()) { if (itemData.m_NetSsid == activeSsid) { continue; } @@ -1207,6 +1289,12 @@ void WlanPage::getWirelessList(QMap > &map) return; } +//for dbus +bool WlanPage::getWirelessSwitchBtnState() +{ + return getSwitchBtnState(); +} + //开启热点 void WlanPage::activeWirelessAp(const QString apName, const QString apPassword, const QString wirelessBand, const QString apDevice) { @@ -1243,6 +1331,18 @@ void WlanPage::getStoredApInfo(QStringList &list) } } +void WlanPage::getApConnectionPath(QString &path, QString uuid) +{ + path.clear(); + path = m_connectResource->getApConnectionPathByUuid(uuid); +} + +void WlanPage::getActiveConnectionPath(QString &path, QString uuid) +{ + path.clear(); + path = m_activatedConnectResource->getAcitveConnectionPathByUuid(uuid); +} + void WlanPage::getApInfoBySsid(QString devName, QString ssid, QStringList &list) { list.clear(); @@ -1289,7 +1389,7 @@ void WlanPage::activateWirelessConnection(const QString& devName, const QString& QMouseEvent *event = new QMouseEvent(QEvent::MouseButtonPress, QPoint(0,0), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); QApplication::postEvent(p_wlanItem, event); - emit showMainWindow(WLAN_PAGE_INDEX); + Q_EMIT showMainWindow(WLAN_PAGE_INDEX); } else { qDebug() << "[WlanPage]activateWirelessConnection no such " << ssid << "in" << devName; } @@ -1319,7 +1419,8 @@ void WlanPage::deactivateWirelessConnection(const QString& devName, const QStrin void WlanPage::onMainWindowVisibleChanged(const bool &visible) { qDebug() << "[WlanPage] Received signal of mainwindow visible changed. cur_state = " << visible << Q_FUNC_INFO << __LINE__; - if (visible) { + //开关关闭状态不刷新 + if (visible && getSwitchBtnState()) { //打开页面时先触发一次扫描,然后定时扫描wifi热点和刷新icon requestScan(); m_scanTimer->start(AP_SCAN_INTERVAL); @@ -1359,6 +1460,40 @@ void WlanPage::showNonePwd() return; } +void WlanPage::showRate() +{ + //定时获取网速 + setNetSpeed = new QTimer(this); + setNetSpeed->setTimerType(Qt::PreciseTimer); + connect(setNetSpeed, &QTimer::timeout, [&](){ + onSetNetSpeed(m_activatedNetListWidget, m_activateConnectionItemMap.contains(EMPTY_SSID), m_currentDevice); + }); +} + +void WlanPage::showHiddenWlanPage(QString devName) +{ + if (m_joinHiddenWiFiPagePtrMap.contains(devName)) { + if (m_joinHiddenWiFiPagePtrMap[devName] != nullptr) { + qDebug() << "[WlanPage] showAddOtherWlanWidget" << devName << "already create,just raise"; + KWindowSystem::activateWindow(m_joinHiddenWiFiPagePtrMap[devName]->winId()); + KWindowSystem::raiseWindow(m_joinHiddenWiFiPagePtrMap[devName]->winId()); + return; + } + } + + JoinHiddenWiFiPage *hiddenWiFi =new JoinHiddenWiFiPage(devName); + connect(hiddenWiFi, &JoinHiddenWiFiPage::hiddenWiFiPageClose, [&](QString interfaceName){ + if (m_joinHiddenWiFiPagePtrMap.contains(interfaceName)) { + m_joinHiddenWiFiPagePtrMap[interfaceName] = nullptr; + } + }); + connect(hiddenWiFi, &JoinHiddenWiFiPage::showWlanList, this, &WlanPage::showMainWindow); + + m_joinHiddenWiFiPagePtrMap.insert(devName, hiddenWiFi); + hiddenWiFi->show(); + hiddenWiFi->centerToScreen(); +} + void WlanPage::showDetailPage(QString devName, QString ssid) { KyWirelessNetItem wirelessNetItem; @@ -1369,12 +1504,33 @@ void WlanPage::showDetailPage(QString devName, QString ssid) bool isActive = m_connectResource->isActivatedConnection(wirelessNetItem.m_connectUuid); + if (m_wlanPagePtrMap.contains(devName) && m_wlanPagePtrMap[devName].contains(ssid)) { + if (m_wlanPagePtrMap[devName][ssid] != nullptr) { + qDebug() << "[WlanPage] ShowWlanDetailPage" << ssid << "already create,just raise"; + KWindowSystem::activateWindow(m_wlanPagePtrMap[devName][ssid]->winId()); + KWindowSystem::raiseWindow(m_wlanPagePtrMap[devName][ssid]->winId()); + return; + } + } + NetDetail *netDetail = new NetDetail(devName, ssid, wirelessNetItem.m_connectUuid, isActive, true, !wirelessNetItem.m_isConfigured); + m_wlanPagePtrMap[devName].insert(ssid, netDetail); + connect(netDetail, &NetDetail::detailPageClose, [&](QString deviceName, QString wlanSsid){ + if (m_wlanPagePtrMap.contains(deviceName) && m_wlanPagePtrMap[deviceName].contains(wlanSsid)) { + m_wlanPagePtrMap[deviceName][wlanSsid] = nullptr; + } + }); netDetail->show(); + netDetail->centerToScreen(); return; } +void WlanPage::showAddOtherPage(QString devName) +{ + showHiddenWlanPage(devName); +} + bool WlanPage::checkWlanStatus(NetworkManager::ActiveConnection::State state) { if (m_activatedConnectResource->checkWirelessStatus(state)) { @@ -1387,23 +1543,7 @@ bool WlanPage::checkWlanStatus(NetworkManager::ActiveConnection::State state) void WlanPage::setWirelessSwitchEnable(bool enable) { qDebug() << "dbus setWirelessSwitchEnable = " << enable << __LINE__; - //应该先检测是否有无线网卡可用,才改变开关状态 - if (m_devList.isEmpty()) { - qDebug() << "have no device to use " << Q_FUNC_INFO << __LINE__; - //检测不到无线网卡不再触发click信号 -// m_netSwitch->setSwitchStatus(false); - m_netSwitch->setEnabled(false); - }else{ - m_wirelessConnectOpreation->setWirelessEnabled(enable); - if (!enable) { -// m_netSwitch->setEnabled(false); - m_netSwitch->setChecked(false); - m_activatedNetFrame->hide(); - m_activatedNetDivider->hide(); - m_inactivatedNetFrame->hide(); - m_deviceFrame->hide(); - } - } + setWirelessEnable(enable); } void WlanPage::getWirelessDeviceCap(QMap &map) @@ -1447,5 +1587,11 @@ void WlanPage::addWlanMoreItem() m_hiddenItem->setSizeHint(QSize(m_inactivatedNetListWidget->width(), m_hiddenWlanWidget->height())); m_inactivatedNetListWidget->addItem(m_hiddenItem); m_inactivatedNetListWidget->setItemWidget(m_hiddenItem, m_hiddenWlanWidget); + m_hiddenWlanWidget->m_freq->hide(); return; } + +int WlanPage::getAcivateWifiSignal() +{ + return m_activatedConnectResource->getAcivateWifiSignal(); +} diff --git a/src/frontend/tab-pages/wlanpage.h b/src/frontend/tab-pages/wlanpage.h index b4cf4f88..d7453722 100644 --- a/src/frontend/tab-pages/wlanpage.h +++ b/src/frontend/tab-pages/wlanpage.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef WLANPAGE_H #define WLANPAGE_H @@ -14,6 +33,7 @@ #include #include "kylinactiveconnectresource.h" #include "kywirelessnetresource.h" +#include "netdetails/joinhiddenwifipage.h" //#define SCROLLAREA_HEIGHT 150 #define MORE_TEXT_MARGINS 16,0,0,0 @@ -39,11 +59,14 @@ public: void deactiveWirelessAp(const QString apName, const QString uuid); //获取热点 void getStoredApInfo(QStringList &list); + void getApConnectionPath(QString &path, QString uuid); + void getActiveConnectionPath(QString &path, QString uuid); void activateWirelessConnection(const QString& devName, const QString& ssid); void deactivateWirelessConnection(const QString& devName, const QString& ssid); void showDetailPage(QString devName, QString uuid); + void showAddOtherPage(QString devName); bool checkWlanStatus(NetworkManager::ActiveConnection::State state); @@ -54,13 +77,17 @@ public: void getConnectivity(NetworkManager::Connectivity &connectivity); -signals: + bool getWirelessSwitchBtnState(); + + int getAcivateWifiSignal(); + +Q_SIGNALS: void oneItemExpanded(const QString &ssid); void wlanAdd(QString devName, QStringList info); void wlanRemove(QString devName,QString ssid); void wlanActiveConnectionStateChanged(QString interface, QString ssid, QString uuid, int status); void hotspotDeactivated(QString devName, QString ssid); - void hotspotActivated(QString devName, QString ssid, QString uuid); + void hotspotActivated(QString devName, QString ssid, QString uuid, QString activePath, QString settingPath); void signalStrengthChange(QString devName, QString ssid, int strength); void secuTypeChange(QString devName, QString ssid, QString secuType); void hiddenWlanClicked(); @@ -71,18 +98,20 @@ signals: void connectivityChanged(NetworkManager::Connectivity connectivity); -public slots: + void wirelessSwitchBtnChanged(bool state); + +public Q_SLOTS: void onMainWindowVisibleChanged(const bool &visible); void onSecurityTypeChange(QString devName, QString ssid, QString secuType); void requestScan(); void onWlanPageVisibleChanged(int index); -private slots: +private Q_SLOTS: void onWlanAdded(QString interface, KyWirelessNetItem &item); void onWlanRemoved(QString interface, QString ssid); void onConnectionAdd(QString deviceName, QString ssid); - void onConnectionRemove(QString deviceName, QString ssid); + void onConnectionRemove(QString deviceName, QString ssid, QString path); void onDeviceAdd(QString deviceName, NetworkManager::Device::Type deviceType); void onDeviceRemove(QString deviceName); @@ -93,14 +122,14 @@ private slots: NetworkManager::ActiveConnection::Reason reason); void onItemHeightChanged(const bool isExpanded, const QString &ssid); - void onWlanSwithGsettingsChanged(const QString &key); - void onDeviceComboxIndexChanged(int currentIndex); void onHiddenWlanClicked(); void showControlCenter(); void onWifiEnabledChanged(bool isWifiOn); void onRefreshIconTimer(); + void onWlanStateChanged(NetworkManager::Device::State newstate, NetworkManager::Device::State oldstate, NetworkManager::Device::StateChangeReason reason); + protected: bool eventFilter(QObject *watched, QEvent *event); @@ -117,6 +146,10 @@ private: void showNonePwd(); + void showRate(); + + void showHiddenWlanPage(QString devName); + QListWidgetItem *addEmptyItem(QListWidget *wirelessListWidget); QListWidgetItem *addNewItem(KyWirelessNetItem &wirelessNetItem, QListWidget *wirelessListWidget); @@ -141,7 +174,7 @@ private: void constructActivateConnectionArea(); void updateActivatedArea(QString uuid, QString ssid, QString devName); - void updateWirelessNetArea(QString uuid, QString ssid, QString devName); + void updateWirelessNetArea(QString uuid, QString ssid, QString devName, QString path); void addDeviceToCombox(QString deviceName); void deleteDeviceFromCombox(QString deviceName); @@ -149,8 +182,33 @@ private: void sendApStateChangeSignal(QString uuid, QString ssid, QString deviceName, NetworkManager::ActiveConnection::State state); - void wlanShowNotify(QString ssid, NetworkManager::ActiveConnection::State state, - NetworkManager::ActiveConnection::Reason reason); +// void wlanShowNotify(QString ssid, NetworkManager::ActiveConnection::State state, +// NetworkManager::ActiveConnection::Reason reason); + + //是否存在可用的无线网卡 + bool getWirelessDevieceUseable(); + void setWirelessEnable(bool state); + bool getWirelessEnable(); + inline void setSwitchBtnState(bool state) { + if (m_netSwitch != nullptr) { + m_netSwitch->setChecked(state); + } + } + inline bool getSwitchBtnState() { + if (m_netSwitch != nullptr) { + return m_netSwitch->isChecked(); + } + } + inline void setSwitchBtnEnable(bool state) { + if (m_netSwitch != nullptr) { + m_netSwitch->setEnabled(state); + } + } + inline bool getSwitchBtnEnable() { + if (m_netSwitch != nullptr) { + return m_netSwitch->isEnabled(); + } + } private: QMap m_wirelessNetItemMap; @@ -173,13 +231,13 @@ private: KyWirelessConnectOperation * m_wirelessConnectOpreation = nullptr; KyConnectResourse * m_connectResource = nullptr; - QGSettings *m_switchGsettings = nullptr; - bool m_wlanSwitchEnable = true; - bool m_updateStrength = true; QTimer *m_scanTimer = nullptr; QTimer *m_refreshIconTimer = nullptr; + + QMap> m_wlanPagePtrMap; + QMap m_joinHiddenWiFiPagePtrMap; }; #endif // WLANPAGE_H diff --git a/src/frontend/tools/divider.cpp b/src/frontend/tools/divider.cpp index f82fba9a..1bb28182 100644 --- a/src/frontend/tools/divider.cpp +++ b/src/frontend/tools/divider.cpp @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "divider.h" #include #include diff --git a/src/frontend/tools/divider.h b/src/frontend/tools/divider.h index e22a6392..9d7b1729 100644 --- a/src/frontend/tools/divider.h +++ b/src/frontend/tools/divider.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef DIVIDER_H #define DIVIDER_H #include diff --git a/src/frontend/tools/infobutton.cpp b/src/frontend/tools/infobutton.cpp index 399ed4a8..8e462343 100644 --- a/src/frontend/tools/infobutton.cpp +++ b/src/frontend/tools/infobutton.cpp @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "infobutton.h" #include #include @@ -8,14 +27,18 @@ #define ICON_SIZE 16,16 #define BACKGROUND_COLOR QColor(0,0,0,0) #define FOREGROUND_COLOR_NORMAL qApp->palette().text().color() -#define FOREGROUND_COLOR_HOVER QColor(55,144,250,255) -#define FOREGROUND_COLOR_PRESS QColor(36,109,212,255) -#define OUTER_PATH 8,8,16,16 -#define INNER_PATH 9,9,14,14 -#define TEXT_POS 14,5,16,16,0 +//#define FOREGROUND_COLOR_HOVER QColor(55,144,250,255) +//#define FOREGROUND_COLOR_PRESS QColor(36,109,212,255) +#define FOREGROUND_COLOR_BRIGHTTEXT qApp->palette().brightText().color() +#define FOREGROUND_COLOR_HIGHLIGHT qApp->palette().highlight().color() +#define OUTER_PATH 8,10,16,16 +#define INNER_PATH 9,11,14,14 +#define TEXT_POS 14,7,16,16,0 #define BUTTON_SIZE 36,36 +QColor mixColor(const QColor &c1, const QColor &c2, qreal bias); + InfoButton::InfoButton(QWidget *parent) : QPushButton(parent) { this->setFixedSize(BUTTON_SIZE); @@ -69,7 +92,8 @@ void InfoButton::paintEvent(QPaintEvent *event) void InfoButton::enterEvent(QEvent *event) { - m_foregroundColor = FOREGROUND_COLOR_HOVER; +// m_foregroundColor = FOREGROUND_COLOR_HOVER; + m_foregroundColor = FOREGROUND_COLOR_HIGHLIGHT; this->update(); } @@ -81,14 +105,16 @@ void InfoButton::leaveEvent(QEvent *event) void InfoButton::mousePressEvent(QMouseEvent *event) { - m_foregroundColor = FOREGROUND_COLOR_PRESS; +// m_foregroundColor = FOREGROUND_COLOR_PRESS; + m_foregroundColor = mixColor(FOREGROUND_COLOR_HIGHLIGHT, FOREGROUND_COLOR_BRIGHTTEXT, 0.2); this->update(); return QPushButton::mousePressEvent(event); } void InfoButton::mouseReleaseEvent(QMouseEvent *event) { - m_foregroundColor = FOREGROUND_COLOR_HOVER; +// m_foregroundColor = FOREGROUND_COLOR_HOVER; + m_foregroundColor = mixColor(FOREGROUND_COLOR_HIGHLIGHT, FOREGROUND_COLOR_BRIGHTTEXT, 0.2); this->update(); return QPushButton::mouseReleaseEvent(event); } diff --git a/src/frontend/tools/infobutton.h b/src/frontend/tools/infobutton.h index 523825ab..34e57891 100644 --- a/src/frontend/tools/infobutton.h +++ b/src/frontend/tools/infobutton.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef INFOBUTTON_H #define INFOBUTTON_H #include @@ -24,7 +43,7 @@ private: QColor m_backgroundColor; QColor m_foregroundColor; -private slots: +private Q_SLOTS: void onPaletteChanged(); }; diff --git a/src/frontend/tools/kylable.cpp b/src/frontend/tools/kylable.cpp index 0c428a5d..0cb597e7 100644 --- a/src/frontend/tools/kylable.cpp +++ b/src/frontend/tools/kylable.cpp @@ -1,8 +1,30 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "kylable.h" #include #include #include +#include +#include + #define FOREGROUND_COLOR_NORMAL qApp->palette().text().color() static inline qreal mixQreal(qreal a, qreal b, qreal bias) @@ -31,6 +53,43 @@ QColor mixColor(const QColor &c1, const QColor &c2, qreal bias) return QColor::fromRgbF(r, g, b, a); } +FixLabel::FixLabel(QWidget *parent) : + QLabel(parent) +{ + const QByteArray id("org.ukui.style"); + QGSettings * fontSetting = new QGSettings(id, QByteArray(), this); + if(QGSettings::isSchemaInstalled(id)){ + connect(fontSetting, &QGSettings::changed,[=](QString key) { + if ("systemFont" == key || "systemFontSize" ==key) { + changedLabelSlot(); + } + }); + } +} + + +void FixLabel::setLabelText(QString text) { + + mStr = text; + changedLabelSlot(); +} + +QString FixLabel::getText(){ + return mStr; +} + +void FixLabel::changedLabelSlot() { + QFontMetrics fontMetrics(this->font()); + int fontSize = fontMetrics.width(mStr); + if (fontSize > this->width()) { + setText(fontMetrics.elidedText(mStr, Qt::ElideRight, this->width())); + setToolTip(mStr); + } else { + setText(mStr); + setToolTip(""); + } +} + KyLable::KyLable(QWidget *parent) : QLabel(parent) { connect(qApp, &QApplication::paletteChanged, this, &KyLable::onPaletteChanged); @@ -47,14 +106,15 @@ void KyLable::setPressColor() { QColor hightlight = this->palette().color(QPalette::Active,QPalette::Highlight); QColor mix = this->palette().color(QPalette::Active,QPalette::BrightText); - m_foregroundColor = mixColor(hightlight, mix, 0.05); + m_foregroundColor = mixColor(hightlight, mix, 0.2); } void KyLable::setHoverColor() { - QColor hightlight = this->palette().color(QPalette::Active,QPalette::Highlight); - QColor mix = this->palette().color(QPalette::Active,QPalette::BrightText); - m_foregroundColor = mixColor(hightlight, mix, 0.2); +// QColor hightlight = this->palette().color(QPalette::Active,QPalette::Highlight); +// QColor mix = this->palette().color(QPalette::Active,QPalette::BrightText); +// m_foregroundColor = mixColor(hightlight, mix, 0.2); + m_foregroundColor = this->palette().color(QPalette::Active,QPalette::Highlight); } void KyLable::setNormalColor() diff --git a/src/frontend/tools/kylable.h b/src/frontend/tools/kylable.h index 9b32dfe4..c45eb8bd 100644 --- a/src/frontend/tools/kylable.h +++ b/src/frontend/tools/kylable.h @@ -1,9 +1,45 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef KYLABLE_H #define KYLABLE_H #include #include +class FixLabel : public QLabel +{ + Q_OBJECT +public: + explicit FixLabel(QWidget *parent = 0); + +public: + void setLabelText(QString text); + QString getText(); + +private Q_SLOTS: + void changedLabelSlot(); +private: + QString mStr; + +}; + class KyLable : public QLabel { Q_OBJECT @@ -25,7 +61,7 @@ private: void setHoverColor(); void setNormalColor(); -private slots: +private Q_SLOTS: void onPaletteChanged(); }; diff --git a/src/frontend/tools/loadingdiv.cpp b/src/frontend/tools/loadingdiv.cpp index ddaeef31..9e3b1f87 100644 --- a/src/frontend/tools/loadingdiv.cpp +++ b/src/frontend/tools/loadingdiv.cpp @@ -57,7 +57,7 @@ void LoadingDiv::switchAnimStep() } this->countCurrentTime += FRAMESPEED; if (this->countCurrentTime >= ALLTIME) { - emit this->toStopLoading(); //发出信号停止主界面和托盘区的等待动画 + Q_EMIT this->toStopLoading(); //发出信号停止主界面和托盘区的等待动画 } } diff --git a/src/frontend/tools/loadingdiv.h b/src/frontend/tools/loadingdiv.h index 246e686e..f8ee9e30 100644 --- a/src/frontend/tools/loadingdiv.h +++ b/src/frontend/tools/loadingdiv.h @@ -32,10 +32,10 @@ class LoadingDiv : public QWidget public: explicit LoadingDiv(QWidget *parent = nullptr); -signals: +Q_SIGNALS: void toStopLoading(); -public slots: +public Q_SLOTS: void switchAnimStep(); void startLoading(); void stopLoading(); diff --git a/src/frontend/tools/radioitembutton.cpp b/src/frontend/tools/radioitembutton.cpp index fb408636..ece52cf3 100644 --- a/src/frontend/tools/radioitembutton.cpp +++ b/src/frontend/tools/radioitembutton.cpp @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "radioitembutton.h" #include #include @@ -16,6 +35,11 @@ #define FOREGROUND_COLOR_PRESS_INACTIVE_DARK QColor(70,70,70,255) #define FOREGROUND_COLOR_NORMAL_ACTIVE QColor(55,144,250,255) #define FOREGROUND_COLOR_PRESS_ACTIVE QColor(36,109,212,255) +#define COLOR_BRIGHT_TEXT qApp->palette().brightText().color() +#define COLOR_HIGH_LIGHT qApp->palette().highlight().color() +#define THEME_SCHAME "org.ukui.style" + +QColor mixColor(const QColor &c1, const QColor &c2, qreal bias); RadioItemButton::RadioItemButton(QWidget *parent) : QPushButton(parent) { @@ -27,6 +51,16 @@ RadioItemButton::RadioItemButton(QWidget *parent) : QPushButton(parent) m_iconLabel->setAlignment(Qt::AlignCenter); setActive(false); + + const QByteArray id(THEME_SCHAME); + if (QGSettings::isSchemaInstalled(id)) { + m_styleGSettings = new QGSettings(id); + connect(m_styleGSettings, &QGSettings::changed, this, [=](QString key){ + if ("themeColor" == key) { + onPaletteChanged(); + } + }); + } //JXJ_TODO loading动画 connect(this, &RadioItemButton::requestStartLoading, this, &RadioItemButton::onLoadingStarted); connect(this , &RadioItemButton::requestStopLoading, this, &RadioItemButton::onLoadingStopped); @@ -35,17 +69,20 @@ RadioItemButton::RadioItemButton(QWidget *parent) : QPushButton(parent) RadioItemButton::~RadioItemButton() { - + if (m_styleGSettings != nullptr) { + delete m_styleGSettings; + m_styleGSettings = nullptr; + } } void RadioItemButton::startLoading() { - emit this->requestStartLoading(); + Q_EMIT this->requestStartLoading(); } void RadioItemButton::stopLoading() { - emit this->requestStopLoading(); + Q_EMIT this->requestStopLoading(); } //设置图标 void RadioItemButton::setButtonIcon(const QIcon &icon) @@ -95,7 +132,7 @@ void RadioItemButton::onLoadingStopped() } else { m_iconLabel->setPixmap(m_pixmap); m_animation->stop(); - emit this->animationStoped(); + Q_EMIT this->animationStoped(); } } @@ -141,9 +178,10 @@ void RadioItemButton::paintEvent(QPaintEvent *event) void RadioItemButton::mousePressEvent(QMouseEvent *event) { if (m_isActivated) { - m_backgroundColor = qApp->palette().highlight().color(); +// m_backgroundColor = qApp->palette().highlight().color(); + m_backgroundColor = mixColor(COLOR_HIGH_LIGHT, COLOR_BRIGHT_TEXT, 0.2); } else { - m_backgroundColor = qApp->palette().brightText().color(); + m_backgroundColor = COLOR_BRIGHT_TEXT; m_backgroundColor.setAlphaF(0.21); } this->update(); @@ -153,10 +191,10 @@ void RadioItemButton::mousePressEvent(QMouseEvent *event) void RadioItemButton::mouseReleaseEvent(QMouseEvent *event) { if (m_isActivated) { - m_backgroundColor = qApp->palette().highlight().color(); + m_backgroundColor = COLOR_HIGH_LIGHT; } else { - m_backgroundColor = qApp->palette().brightText().color(); - m_backgroundColor.setAlphaF(0.18); + m_backgroundColor = COLOR_BRIGHT_TEXT; + m_backgroundColor.setAlphaF(0.12); } this->update(); return QPushButton::mouseReleaseEvent(event); @@ -165,10 +203,10 @@ void RadioItemButton::mouseReleaseEvent(QMouseEvent *event) void RadioItemButton::enterEvent(QEvent *event) { if (m_isActivated) { - m_backgroundColor = qApp->palette().highlight().color(); + m_backgroundColor = COLOR_HIGH_LIGHT; } else { - m_backgroundColor = qApp->palette().brightText().color(); - m_backgroundColor.setAlphaF(0.32); + m_backgroundColor = COLOR_BRIGHT_TEXT; + m_backgroundColor.setAlphaF(0.15); } this->update(); return QPushButton::enterEvent(event); @@ -177,10 +215,10 @@ void RadioItemButton::enterEvent(QEvent *event) void RadioItemButton::leaveEvent(QEvent *event) { if (m_isActivated) { - m_backgroundColor = qApp->palette().highlight().color(); + m_backgroundColor = COLOR_HIGH_LIGHT; } else { - m_backgroundColor = qApp->palette().brightText().color(); - m_backgroundColor.setAlphaF(0.18); + m_backgroundColor = COLOR_BRIGHT_TEXT; + m_backgroundColor.setAlphaF(0.12); } this->update(); return QPushButton::leaveEvent(event); @@ -189,11 +227,11 @@ void RadioItemButton::leaveEvent(QEvent *event) void RadioItemButton::refreshButtonIcon() { if (m_isActivated) { - m_backgroundColor = qApp->palette().highlight().color(); + m_backgroundColor = COLOR_HIGH_LIGHT; m_iconLabel->setPixmap(loadSvg(m_pixmap, PixmapColor::WHITE)); } else { - m_backgroundColor = qApp->palette().brightText().color(); - m_backgroundColor.setAlphaF(0.18); + m_backgroundColor = COLOR_BRIGHT_TEXT; + m_backgroundColor.setAlphaF(0.12); if (qApp->palette().base().color().red() > MIDDLE_COLOR) { m_iconLabel->setPixmap(m_pixmap); } else { diff --git a/src/frontend/tools/radioitembutton.h b/src/frontend/tools/radioitembutton.h index 89ba1a8d..478ea123 100644 --- a/src/frontend/tools/radioitembutton.h +++ b/src/frontend/tools/radioitembutton.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef NETBUTTON_H #define NETBUTTON_H #include @@ -5,6 +24,7 @@ #include #include #include +#include #define MIDDLE_COLOR 178 @@ -28,7 +48,7 @@ public: }; const QPixmap loadSvg(const QPixmap &source, const PixmapColor &color); -signals: +Q_SIGNALS: void requestStartLoading(); void requestStopLoading(); void animationStoped(); @@ -48,9 +68,11 @@ private: QPixmap m_pixmap; + QGSettings *m_styleGSettings = nullptr; + void refreshButtonIcon(); -private slots: +private Q_SLOTS: void onLoadingStarted(); void onLoadingStopped(); void onPaletteChanged(); diff --git a/src/frontend/tools/switchbutton.cpp b/src/frontend/tools/switchbutton.cpp index 806ca05e..e906f78f 100644 --- a/src/frontend/tools/switchbutton.cpp +++ b/src/frontend/tools/switchbutton.cpp @@ -56,7 +56,7 @@ void SwitchButton::setSwitchStatus(bool check) { } else { m_bIsOn = 0; } - emit this->switchStatusChanged(); + Q_EMIT this->switchStatusChanged(); m_cTimer->start(); //开始播放动画 } diff --git a/src/frontend/wificonfigdialog.cpp b/src/frontend/wificonfigdialog.cpp index 310d5019..f91a524b 100644 --- a/src/frontend/wificonfigdialog.cpp +++ b/src/frontend/wificonfigdialog.cpp @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #include "wificonfigdialog.h" #include "ui_wificonfigdialog.h" #include "utils.h" @@ -8,7 +27,6 @@ #include #include -#include #include WiFiConfigDialog::WiFiConfigDialog(QWidget *parent) : diff --git a/src/frontend/wificonfigdialog.h b/src/frontend/wificonfigdialog.h index 90588783..2031795f 100644 --- a/src/frontend/wificonfigdialog.h +++ b/src/frontend/wificonfigdialog.h @@ -1,3 +1,22 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2022 Tianjin KYLIN Information Technology Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ #ifndef WIFICONFIGDIALOG_H #define WIFICONFIGDIALOG_H @@ -26,7 +45,7 @@ public: protected: void paintEvent(QPaintEvent *event); -private slots: +private Q_SLOTS: void on_btnCancel_clicked(); void on_btnOk_clicked(); diff --git a/src/main.cpp b/src/main.cpp index ed357610..1eff8ac7 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -16,6 +16,7 @@ * */ +//#include "mainwindow.h" #include "mainwindow.h" #include "dbusadaptor.h" #include @@ -29,9 +30,6 @@ #include "xatom-helper.h" #endif -#include "vpnobject.h" -#include "vpndbusadaptor.h" - #define LOG_IDENT "ukui_kylin_nm" const QString QT_TRANSLATE_FILE = "/usr/share/qt5/translations/qt_zh_CN.qm"; @@ -129,7 +127,7 @@ int main(int argc, char *argv[]) QString locale = QLocale::system().name(); QTranslator trans_global; qDebug() << "QLocale " << QLocale(); - if (trans_global.load(QLocale(), "kylin-nm", "_", ":/translations/")) + if (trans_global.load(QLocale(), "kylin-nm", "_", "/usr/share/kylin-nm/kylin-nm/")) { a.installTranslator(&trans_global); qDebug()<<"Translations load success"; @@ -146,6 +144,15 @@ int main(int argc, char *argv[]) qWarning() << "QtBase Translations load fail"; } + QTranslator sdkTranslator; + if (sdkTranslator.load(QLocale(), "gui", "_", ":/translations/")) + { + a.installTranslator(&sdkTranslator); + qDebug()<<"SDK Translations load success"; + } else { + qWarning() << "SDK Translations load fail"; + } + while (!p_networkResource->NetworkManagerIsInited()) { ::usleep(1000); } @@ -153,22 +160,23 @@ int main(int argc, char *argv[]) MainWindow w; a.setActivationWindow(&w); w.setProperty("useStyleWindowManager", false); //禁用拖动 + a.setWindowIcon(QIcon::fromTheme("kylin-network")); + //设置窗口无边框,阴影 - vpnObject vnpobject; +// MotifWmHints window_hints; +// window_hints.flags = MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS; +// window_hints.functions = MWM_FUNC_ALL; +// window_hints.decorations = MWM_DECOR_BORDER; +// XAtomHelper::getInstance()->setWindowMotifHint(w.winId(), window_hints); - w.setWindowFlags(Qt::CustomizeWindowHint | Qt::FramelessWindowHint/* | Qt::X11BypassWindowManagerHint*/); + w.setWindowFlags(Qt::CustomizeWindowHint | Qt::FramelessWindowHint /*| Qt::X11BypassWindowManagerHint*/); DbusAdaptor adaptor(&w); Q_UNUSED(adaptor); - VpnDbusAdaptor vpnAdaptor(&vnpobject); - Q_UNUSED(vpnAdaptor); - auto connection = QDBusConnection::sessionBus(); - if (!connection.registerService("com.kylin.network") - || !connection.registerObject("/com/kylin/network", &w) - || !connection.registerObject("/com/kylin/vpnTool", &vnpobject)) { + if (!connection.registerService("com.kylin.network") || !connection.registerObject("/com/kylin/network", &w)) { qCritical() << "QDbus register service failed reason:" << connection.lastError(); } diff --git a/src/org.ukui.kylin-nm.switch.gschema.xml b/src/org.ukui.kylin-nm.switch.gschema.xml index f7fa75de..544f2cd0 100644 --- a/src/org.ukui.kylin-nm.switch.gschema.xml +++ b/src/org.ukui.kylin-nm.switch.gschema.xml @@ -11,11 +11,4 @@ Wired switch.true is open,false is close. - - - false - vpnicon visible - vpnicon visible.true is visible,false is invisible. - - diff --git a/src/src.pro b/src/src.pro index 8453443e..8a66099c 100644 --- a/src/src.pro +++ b/src/src.pro @@ -11,7 +11,7 @@ greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = kylin-nm TEMPLATE = app -CONFIG += c++14 qt warn_on link_pkgconfig +CONFIG += c++14 qt warn_on link_pkgconfig no_keywords #CONFIG += release PKGCONFIG +=gio-2.0 glib-2.0 gio-unix-2.0 libnm libnma libsecret-1 gtk+-3.0 gsettings-qt libcap kysdk-qtwidgets kysdk-waylandhelper diff --git a/translate_generation.sh b/translate_generation.sh new file mode 100755 index 00000000..72f748b9 --- /dev/null +++ b/translate_generation.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +ts_list=(`ls translations/*.ts`) +source /etc/os-release +version=(`echo $ID`) + +for ts in "${ts_list[@]}" +do + printf "\nprocess ${ts}\n" + if [ "$version" == "fedora" ] || [ "$version" == "opensuse-leap" ] || [ "$version" == "opensuse-tumbleweed" ];then + lrelease-qt5 "${ts}" + else + lrelease "${ts}" + fi +done diff --git a/translations/kylin-nm_bo.ts b/translations/kylin-nm_bo.ts index a8ee3040..a1a36aef 100644 --- a/translations/kylin-nm_bo.ts +++ b/translations/kylin-nm_bo.ts @@ -1,46 +1,79 @@ + + ConfigPage + + + Network profile type + + + + + Public(recommended) Devices on the network cannot discover this computer. Generally, it is suitable for networks in public places, such as airports or coffee shops, etc. + + + + + Private Devices on the network can discover this computer. Generally applicable to a network at home or work where you know and trust the individuals and devices on the network. + + + + + Config firewall and security settings + + + CreatNetPage - + Connection Name - - Ipv4Config + + IPv4Config - + Address - + Netmask - + Default Gateway - - + + Invalid address + + + + + Invalid subnet mask + + + + + Required - + Auto(DHCP) - + Manual @@ -48,82 +81,82 @@ DetailPage - + Auto Connection - - + + SSID: - + Copied successfully! - + Copy all - + Please input SSID: - - + + Protocol: - - + + Security Type: - - + + Hz: - - + + Chan: - - + + BandWidth: - - - IPV6: + + + IPv4: - - - IPV4: + + + IPv6: - - - IPV4 Dns: + + + IPv4 DNS: - - + + Mac: @@ -131,146 +164,263 @@ EnterpriseWlanDialog - - Connect Enterprise WLAN + + Wi-Fi network requires authentication - + + Access to Wi-Fi network " + + + + + " requires a password or encryption key. + + + + Cancel - + Connect + + FirewallDialog + + + Allow other devices on this network to discover this computer? + + + + + It is not recommended to enable this feature on public networks + + + + + Not allowed (recommended) + + + + + Allowed + + + Ipv4Page - - Ipv4Config - - - - + Address - + Netmask - + Default Gateway - + + IPv4Config + + + + Auto(DHCP) - + Manual + + + Invalid address + + + + + Invalid subnet mask + + + + + + Required + + + + + Address conflict + + Ipv6Page - - Ipv6Config - - - - + Address - + Subnet prefix Length - + Default Gateway - + + IPv6Config + + + + Auto(DHCP) - + Manual + + + + Required + + + + + Invalid address + + + + + Invalid gateway + + + + + Address conflict + + + + + JoinHiddenWiFiPage + + + Please enter the network name and security type + + + + + Network name(SSID) + + + + + Show Network List + + + + + Cancel + + + + + Join + + + + + Required + + + + + Find and Join Wi-Fi + + LanListItem - + Not connected - + Wired Device not carried - - + + + Disconnect - - + + + Connect + + + + Property + + + + + + Delete + + LanPage - + No ethernet device avaliable - + LAN - + Activated LAN - + Inactivated LAN - - LAN Connected Successfully - - - - - LAN Disconnected Successfully - - - - + Wired Device not carried @@ -278,12 +428,12 @@ ListItem - + Kylin NM - + kylin network applet desktop message @@ -291,28 +441,28 @@ MainWindow - - + + kylin-nm - + LAN - + WLAN - + Settings - + Show MainWindow @@ -328,114 +478,112 @@ NetDetail - + Kylin NM - + kylin network desktop message - + Detail - - Ipv4 - - - - - Ipv6 - - - - + Security - + + + Config + + + + Confirm - + Cancel - + Forget this network - - Add Lan Connect + + IPv4 - - connect hiddin wlan + + IPv6 - - - + + Add LAN Connect + + + + + Connect Hidden WLAN + + + + + Delete this network + + + + + + None - - - + + + Auto - + start check ipv4 address conflict - + start check ipv6 address conflict - - - - ipv4 address conflict! - - - - - - ipv6 address conflict! - - - - + this wifi no support enterprise type - + this wifi no support None type - + this wifi no support WPA2 type - + this wifi no support WPA3 type @@ -459,200 +607,245 @@ SecurityPage - + + Remember the Network + + + + Security - - + + Password - + EAP type - + Identity - + Domain - + CA certficate - + no need for CA certificate - + User certificate - + User private key - + User key password - + + Password options + + + + + + + Required + + + + Ineer authentication - - Usename + + Username - + Ask pwd each query - - - - - - - - - + + + + + + + + + + + + None - + WPA&WPA2 Personal - + WPA&WPA2 Enterprise - + WPA3 Personal - - - + + + + Choose from file... - - - + + PAC provisioning + + + + + Allow automatic PAC provisioning + + + + + PAC file + + + + + Anonymous + + + + + Authenticated + + + + + Both + + + + + Store passwords only for this user + + + + + Store password only for this user + + + + + Store passwords for all users + + + + + Store password for all users + + + + + Ask this password every time + + + + + Ask password every time + + + + + + Choose a CA certificate - - - + + + CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) - - - SinglePage - - Settings + + Choose a PAC file - - Kylin NM + + PAC Files (*.pac) - - kylin network applet desktop message + + TabPage - + Current Device - + Devices Closed! - + Settings - + Kylin NM - + kylin network applet desktop message - - VpnListItem - - - Not connected - - - - - - Disconnect - - - - - - Connect - - - - - VpnPage - - - VPN Connection - - - - - VPN Settings - - - WiFiConfigDialog @@ -661,37 +854,37 @@ - + WLAN Authentication - + Input WLAN Information Please - + WLAN ID: - + WLAN Name: - + Password: - + Cancl - + Ok @@ -699,31 +892,42 @@ WlanListItem - + Not connected - - + + + + + Disconnect - - - + + + + + Connect - - + + + Property + + + + + Forget - + Auto Connect @@ -731,7 +935,7 @@ WlanMoreItem - + Add Others... @@ -739,33 +943,32 @@ WlanPage - + WLAN - + Activated WLAN - + Other WLAN - + No wireless network card detected - + WLAN Connected Successfully - - + WLAN Disconnected Successfully @@ -788,17 +991,4 @@ - - vpnMainWindow - - - kylin-vpn - - - - - vpn tool - - - diff --git a/translations/kylin-nm_bo_CN.ts b/translations/kylin-nm_bo_CN.ts new file mode 100644 index 00000000..64e1f0ab --- /dev/null +++ b/translations/kylin-nm_bo_CN.ts @@ -0,0 +1,1506 @@ + + + + + ConfForm + + Manual + 手动 + + + Cancel + 取消 + + + kylin-nm + 网络工具 + + + kylin network applet desktop message + 网络提示消息 + + + Will check the IP address conflict + 正在检测ip地址冲突 + + + IPv4 address conflict, Please change IP + ip地址冲突,请更改ip + + + IPv6 address conflict, Please change IP + ip地址冲突,请更改ip {6 ?} + + + + ConfigPage + + + Network profile type + དྲ་རྒྱའི་བཀོད་སྒྲིག་ཡིག་ཆའི་རིགས། + + + + Public(recommended) Devices on the network cannot discover this computer. Generally, it is suitable for networks in public places, such as airports or coffee shops, etc. + སྤྱི་སྤྱོད།(འོས་སྦྱོར་བྱས་པ།)དྲ་རྒྱའི་སྒྲིག་ཆས་ཀྱིས་གློག་ཀླད་འདི་མཐོང་མི་ཐུབ། སྤྱིར་བཏང་གི་གནས་ཚུལ་འོག་ཏུ་མི་མང་འདུ་སའི་ནང་གི་དྲ་བ་ལ་འཚམ་པ་སྟེ།དཔེར་ན་གནམ་གྲུ་ཐང་དང་འཚིག་ཇའི་ཁང་སོགས་ལྟ་བུ།. + + + + Private Devices on the network can discover this computer. Generally applicable to a network at home or work where you know and trust the individuals and devices on the network. + ཆེད་སྤྱོད། དྲ་རྒྱའི་སྒྲིག་ཆས་ཀྱིས་གློག་ཀླད་འདི་མཐོང་ཐུབ། སྤྱིར་བཏང་གི་གནས་ཚུལ་འོག་ཁྱིམ་ཚང་ངམ་ལས་དོན་ཚན་པའི་དྲ་བ་དང་འཚམ་པས།ཁྱེད་ཀྱིས་དྲ་ཐོག་གི་མི་སྒེར་དང་སྒྲིག་ཆས་ལ་ངོས་འཛིན་དང་ཡིད་ཆེས་བྱེད་དགོས།. + + + + Config firewall and security settings + མེ་འགོག་གྱང་རྩིག་དང་བདེ་འཇགས་བཀོད་སྒྲིག་བྱ་དགོས། + + + + CopyButton + + Copied successfully + 复制成功 + + + Copied successfully! + 复制成功! + + + Copy all + 复制全部 + + + + CreatNetPage + + + Connection Name + འབྲེལ་མཐུད་ཀྱི་མིང་། + + + + IPv4Config + IPv4ཁུང་ཙི། + + + + Address + སྡོད་གནས། + + + + Netmask + དྲ་རྒྱའི་མ་ལག + + + + Default Gateway + ཁ་ཆད་བཞག་པའི་སྒོ་ཆེན། + + + Prefs DNS + སྔོན་གྲབས་DNS + + + Alternative DNS + ཚབ་བྱེད་རང་བཞིན་གྱི་DNS + + + + Auto(DHCP) + རང་འགུལ་(DHCP) + + + + Manual + ལག་དེབ། + + + + Invalid address + རྩིས་འགྲོ་མེད་པའི་ས་གནས། + + + + Invalid subnet mask + རྩིས་འགྲོ་མེད་པའི་དྲ་བ་འགེབས་སྲུང་བྱེད་པ། + + + + + Required + ངེས་པར་དུ་སྐོང་དགོས། + + + + DetailPage + + + Auto Connection + རང་འགུལ་གྱིས་འབྲེལ་མཐུད་བྱེད + + + + + SSID: + SSID: + + + + Copied successfully! + འདྲ་བཟོ་བྱས་ནས་གྲུབ་འབྲས་ཐོབ་! + + + + Copy all + ཚང་མ་འདྲ་བཤུས་བྱེད་ + + + + Please input SSID: + SSID:ནང་འཇུག་གནང་རོགས།: + + + + + Protocol: + གྲོས་ཆོད་ནང་དུ།: + + + + + Security Type: + བདེ་འཇགས་ཀྱི་རིགས་དབྱིབས་ནི།: + + + + + Hz: + དྲ་རྒྱའི་འཕྲིན་ལམ།: + + + + + Chan: + དྲ་བའི་བགྲོད་ལམ།: + + + + + BandWidth: + ཞེང་ཆེ་བ།: + + + + + IPv6: + IPv6: + + + + + IPv4: + IPv4: + + + + + IPv4 DNS: + IPv4 DNS: + + + + + Mac: + ཨའོ་མོན་ནི།: + + + + DlgHideWifi + + Cancel + 取消 + + + Connect + 连接 + + + None + + + + + DlgHideWifiEapFast + + Username + 用户名 + + + Password + 密钥 + + + Cancel + 取消 + + + Connect + 连接 + + + None + + + + + DlgHideWifiEapLeap + + Username + 用户名 + + + Password + 密钥 + + + Cancel + 取消 + + + Connect + 连接 + + + None + + + + + DlgHideWifiEapPeap + + Domain + + + + Username + 用户名 + + + Password + 密钥 + + + Cancel + 取消 + + + Connect + 连接 + + + None + + + + + DlgHideWifiEapPwd + + Username + 用户名 + + + Password + 密钥 + + + Cancel + 取消 + + + Connect + 连接 + + + None + + + + + DlgHideWifiEapTTLS + + Domain + + + + Username + 用户名 + + + Password + 密钥 + + + Cancel + 取消 + + + Connect + 连接 + + + None + + + + + DlgHideWifiEapTls + + Identity + 匿名身份 + + + Domain + + + + User certificate + 用户证书 + + + User private key + 用户私钥 + + + User key password + 用户密钥密码 + + + Cancel + 取消 + + + Connect + 连接 + + + None + + + + + DlgHideWifiLeap + + Username + 用户名 + + + Password + 密钥 + + + Cancel + 取消 + + + Connect + 连接 + + + None + + + + + DlgHideWifiWep + + Cancel + 取消 + + + Connect + 连接 + + + None + + + + + DlgHideWifiWpa + + Password + 密钥 + + + Cancel + 取消 + + + Connect + 连接 + + + None + + + + + EnterpriseWlanDialog + + Connect Enterprise WLAN + ཁེ་ལས་WLANས སྦྲེལ་མཐུད་བྱེད་པ། + + + Close + 关闭 + + + + Wi-Fi network requires authentication + Wi-Fiཡི་དྲ་རྒྱའི་བླང་བྱར་སྤྲོད་བྱ་རྒྱུའི་བླང་བྱ་བཏོན་ཡོད། + + + + Access to Wi-Fi network " + Wii-Fiབར་གྱི་དྲ་རྒྱར་འཚམས་འདྲི་གནང་བ་རེད། + + + + " requires a password or encryption key. + གསང་གྲངས་དང་གསང་བའི་ལྡེ་མིག་དགོས། + + + + Cancel + ཕྱིར་འཐེན། + + + + Connect + སྦྲེལ་མཐུད་བྱེད་པ + + + + FirewallDialog + + Allow your computer to be discovered by other computers and devices on this network? + ཁྱོད་ཀྱི་གློག་ཀླད་དེ་དྲ་རྒྱའི་སྟེང་གི་གློག་ཀླད་དང་སྒྲིག་ཆས་གཞན་དག་གིས་རྙེད་ཐུབ་བམ།? + + + It is recommended that you enable this feature on your home and work networks rather than public networks. + ཁྱེད་ཀྱིས་ཁྱིམ་ཚང་དང་བྱ་བའི་དྲ་རྒྱའི་སྟེང་ནས་སྤྱི་སྤྱོད་མིན་པའི་དྲ་རྒྱའི་སྟེང་ནས་བྱེད་ནུས་འདི་སྤྱོད་རྒྱུའི་གྲོས་འགོ་བཏོན།. + + + Yse + དེ་ནི་རེད། + + + No + དེ་ལྟར་མ་བྱས་ + + + + Allow other devices on this network to discover this computer? + དྲ་རྒྱའི་སྟེང་གི་སྒྲིག་ཆས་གཞན་པས་གློག་ཀླད་འདི་རྙེད་དུ་འཇུག་གམ།? + + + + It is not recommended to enable this feature on public networks + བསམ་འཆར་མེད་།སྤྱི་པའི་དྲ་རྒྱའི་སྟེང་ནས་ནུས་པ་འདི་མགོ་བརྩམས་། + + + + Not allowed (recommended) + མི་ཆོག་པ་(འོས་སྦྱོར།) + + + + Allowed + ཆོག་པ་ + + + + Ipv4Page + + + IPv4Config + IPv4ཁུང་ཙི། + + + + Address + སྡོད་གནས། + + + + Netmask + དྲ་རྒྱའི་མ་ལག + + + + Default Gateway + ཁ་ཆད་བཞག་པའི་སྒོ་ཆེན། + + + Prefs DNS + སྔོན་གྲབས་DNS + + + Alternative DNS + ཚབ་བྱེད་རང་བཞིན་གྱི་DNS + + + + Auto(DHCP) + རང་འགུལ་(DHCP) + + + + Manual + ལག་དེབ། + + + + Invalid address + རྩིས་འགྲོ་མེད་པའི་ས་གནས། + + + + Invalid subnet mask + རྩིས་འགྲོ་མེད་པའི་དྲ་བ་འགེབས་སྲུང་བྱེད་པ། + + + + + Required + ངེས་པར་དུ་སྐོང་དགོས། + + + + Address conflict + ཤག་གནས་གདོང་གཏུག་ + + + + Ipv6Page + + + IPv6Config + IPv6ཁུང་ཙི། + + + + Address + སྡོད་གནས། + + + + Subnet prefix Length + ཡན་ལག་དྲ་རྒྱའི་སྔོན་སྒྲིག་གི་རིང་ཚད། + + + + Default Gateway + ཁ་ཆད་བཞག་པའི་སྒོ་ཆེན། + + + Prefs DNS + སྔོན་གྲབས་DNS + + + Alternative DNS + ཚབ་བྱེད་རང་བཞིན་གྱི་DNS + + + + Auto(DHCP) + རང་འགུལ་(DHCP) + + + + Manual + ལག་དེབ། + + + + + Required + ངེས་པར་དུ་སྐོང་དགོས། + + + + Invalid address + རྩིས་འགྲོ་མེད་པའི་ས་གནས། + + + + Invalid gateway + རྩིས་འགྲོ་མེད་པའི་དྲ་བའི་འགག་སྒོ། + + + + Address conflict + ཤག་གནས་གདོང་གཏུག་ + + + + JoinHiddenWiFiPage + + + Please enter the network name and security type + ཁྱེད་རང་དྲ་རྒྱའི་ནང་དུ་ཞུགས་འདོད་པའི་མིང་དང་བདེ་འཇགས་རིགས་ནང་འཇུག་བྱེད་རོགས། + + + + Network name(SSID) + དྲ་རྒྱའི་མིང་། (SID) + + + Remember the Network + དྲ་རྒྱ་དེ་སེམས་ལ་འཛིན་དགོས། + + + + Show Network List + དྲ་རྒྱའི་རེའུ་མིག་གསལ་པོར་མངོན་པ། + + + + Cancel + མེད་པར་བཟོ་དགོས། + + + + Join + དེའི་ནང་དུ་ཞུགས་པ། + + + + Required + ངེས་པར་དུ་སྐོང་དགོས། + + + + Find and Join Wi-Fi + འཚོལ་ཞིབ་བྱས་པ་མ་ཟད་WI-FIལ་ཞུགས་པ་རེད། + + + + LanListItem + + + Not connected + འབྲེལ་མཐུད་མི་བྱེད་པ། + + + + Wired Device not carried + སྐུད་ཡོད་སྒྲིག་ཆས་འཁྱེར་མེད་པ། + + + + + + Disconnect + འབྲེལ་ཐག་ཆད་པ། + + + + + + Connect + སྦྲེལ་མཐུད་བྱེད་པ + + + + + Property + ངོ་བོ། + + + + + Delete + དྲ་རྒྱ་དེ་བསུབ་དགོས། + + + + LanPage + + + No ethernet device avaliable + ཨེ་ཙི་དྲ་རྒྱའི་སྒྲིག་ཆས་ལ་བཙན་འཛུལ་བྱས་མི་ཆོག། + + + + LAN + སྐུད་ཡོད་དྲ་བ། + + + + Activated LAN + ངའི་དྲ་རྒྱ། + + + + Inactivated LAN + དྲ་བ་གཞན་དག + + + LAN Disconnected Successfully + སྐུད་ཡོད་དྲ་བ་ཆད་སོང་། + + + + Wired Device not carried + སྐུད་ཡོད་སྒྲིག་ཆས་འཁྱེར་མེད་པ། + + + LAN Connected Successfully + སྐུད་ཡོད་དྲ་བ་སྦྲེལ་ཡོད། + + + + ListItem + + + Kylin NM + དྲ་རྒྱའི་ཡོ་བྱད། + + + + kylin network applet desktop message + དྲ་རྒྱའི་གསལ་འདེབས་གནས་ཚུལ། + + + + MainWindow + + + + kylin-nm + དྲ་རྒྱའི་ཡོ་བྱད། + + + + LAN + 有线网络 + སྐུད་ཡོད་དྲ་བ། + + + + WLAN + 无线局域网 + སྐུད་མེད་ཅུས་ཁོངས་ཀྱི་དྲ་བ། + + + + Show MainWindow + རླུང་གཙོ་བོ་མངོན་པར་བྱས་ཡོད། + + + + Settings + 设置网络项 + སྒྲིག་བཀོད། + + + Network tool + དྲ་རྒྱའི་ལག་ཆ་ + + + + MultipleDnsWidget + + + DNS server: + DNSཞབས་ཞུའི་ཡོ་བྱད།: + + + + NetDetail + + + Kylin NM + ཅིན་ལིན་NM + + + + kylin network desktop message + དྲ་རྒྱའི་གསལ་འདེབས་གནས་ཚུལ། + + + + Detail + ཞིབ་ཕྲའི་གནས་ཚུལ། + + + + IPv4 + IPv4 + + + + IPv6 + IPv6 + + + + Security + བདེ་འཇགས། + + + Close + 关闭 + + + + + Config + བཀོད་སྒྲིག་བཅས་བྱ་དགོས། + + + + Confirm + གཏན་འཁེལ་བྱ་དགོས། + + + + Cancel + ཕྱིར་འཐེན། + + + + Forget this network + དྲ་རྒྱ་འདི་བརྗེད་སོང་། + + + + Delete this network + དྲ་རྒྱ་དེ་བསུབ་དགོས། + + + + Add LAN Connect + སྐུད་ཡོད་དྲ་བ་ཁ་སྣོན་བྱ་དགོས། + + + + Connect Hidden WLAN + ཧའེ་ཏེན་ཝེ་ལན་དང་འབྲེལ་མཐུད་བྱེད་པ། + + + + + + None + གཅིག་ཀྱང་མེད། + + + + + + Auto + རང་འགུལ་གྱིས་རླངས་ + + + + start check ipv4 address conflict + ipv4ས་གནས་ཀྱི་འགལ་བ་ལ་ཞིབ་བཤེར་བྱེད་འགོ་ཚུགས། + + + + start check ipv6 address conflict + ipv6གནས་ཡུལ་དང་འགལ་བར་ཞིབ་བཤེར་བྱེད་འགོ་ཚུགས། + + + ipv4 address conflict! + ipv4ཐག་གཅོད་གདོང་གཏུག་བྱུང་བ་རེད།! + + + ipv6 address conflict! + ipv6ཐག་གཅོད་གདོང་གཏུག་བྱུང་བ་རེད།! + + + + this wifi no support enterprise type + wifiལ་རྒྱབ་སྐྱོར་མེད་པའི་ཁེ་ལས་ཀྱི་རིགས་དབྱིབས། + + + + this wifi no support None type + wifiལ་རྒྱབ་སྐྱོར་མི་བྱེད་པར་རིགས་དབྱིབས་གཅིག་ཀྱང་མེད། + + + + this wifi no support WPA2 type + wifiལ་རྒྱབ་སྐྱོར་མི་བྱེད་པའི་WPA2རིགས་དབྱིབས་ + + + + this wifi no support WPA3 type + wifiལ་རྒྱབ་སྐྱོར་མི་བྱེད་པའི་WPA3རིགས་དབྱིབས་ + + + SSID: + SSID: + + + Protocol: + 协议: + + + Hz: + 网络频带: + + + Chan: + 网络通道: + + + BandWidth: + 带宽: + + + IPv4: + IPv4地址: + + + IPv4 DNS: + IPv4 DNS服务器: + + + IPv6: + 本地链接IPv6地址: + + + Mac: + 物理地址: + + + + OldMainWindow + + kylin-nm + 网络工具 + + + Show MainWindow + 打开网络工具 + + + Not connected + 未连接 + + + + OneConnForm + + + Form + + + + Connect + 连接 + + + Disconnect + 断开 + + + Cancel + 取消 + + + Forget + 忘记此网络 + + + None + + + + + OneLancForm + + + Form + + + + Connect + 连接 + + + Disconnect + 断开 + + + Cancel + 取消 + + + Not connected + 未连接 + + + + SecurityPage + + + Remember the Network + དྲ་རྒྱ་དེ་སེམས་ལ་འཛིན་དགོས། + + + + Security + བདེ་འཇགས། + + + + + Password + གསང་གྲངས། + + + + EAP type + EAP རིགས་དབྱིབས། + + + + Identity + ཐོབ་ཐང་། + + + + Domain + ཁྱབ་ཁོངས། + + + + CA certficate + CA certficate + + + + no need for CA certificate + CAཡི་ལག་ཁྱེར་མི་དགོས། + + + + User certificate + སྤྱོད་མཁན་གྱི་ལག་ཁྱེར། + + + + User private key + སྤྱོད་མཁན་གྱི་སྒེར་གྱི་ལྡེ་མིག + + + + User key password + སྤྱོད་མཁན་གྱི་ལྡེ་མིག་གི་གསང་ + + + + Password options + གསང་བའི་ཐོག་ནས་རྣམ་གྲངས་བདམས་པ། + + + + + + Required + ངེས་པར་དུ་སྐོང་དགོས། + + + + Ineer authentication + དབྱིན་ཆས་ཀྱི་བདེན་དཔང་ར་སྤྲོད་ + + + + Username + བཀོལ་སྤྱོད་ཀྱི་མིང་། + + + + Ask pwd each query + འདྲི་རྩད་རེ་རེར་འདྲི་རྩད་བྱེད་པ། + + + + + + + + + + + + + + + None + གཅིག་ཀྱང་མེད། + + + + WPA&WPA2 Personal + WPA&WPA2མི་སྒེར་གྱི་ངོས་ནས་བཤད་ན། + + + + WPA&WPA2 Enterprise + WPA&WPA2 ཁེ་ལས། + + + + WPA3 Personal + WPA3མི་སྒེར་ + + + + + + + Choose from file... + ཡིག་ཆའི་ནང་ནས་གདམ་ག་རྒྱག་དགོས།... + + + + PAC provisioning + PACབཀོད་སྒྲིག་བྱས་པ། + + + + Allow automatic PAC provisioning + རང་འགུལ་PACབཀོད་སྒྲིག་བྱས་ཆོག + + + + PAC file + PACཡི་ཡིག་ཆ། + + + + Anonymous + མིང་མི་འགོད་པ། + + + + Authenticated + དཔང་དངོས་བདེན་པ་ཡིན་པའི་ར་ + + + + Both + དེ་གཉིས་ཀ་མཉམ་དུ་སྤྱོད་དགོས། + + + + Store passwords only for this user + སྤྱོད་མཁན་དེ་ཁོ་ནའི་ཆེད་དུ་གསང་གྲངས་ཉར་ཚགས་བྱས་ཡོད། + + + + Store password only for this user + སྤྱོད་མཁན་དེ་ཁོ་ནའི་ཆེད་དུ་གསང་གྲངས་ཉར་ཚགས་བྱས་ཡོད། + + + + Store passwords for all users + སྤྱོད་མཁན་ཚང་མའི་གསང་བ་གསོག་ཉར་བྱེད་དགོས། + + + + Store password for all users + སྤྱོད་མཁན་ཚང་མའི་གསང་བ་གསོག་ཉར་བྱེད་དགོས། + + + + Ask this password every time + ཐེངས་རེར་གསང་བ་འདི་འདྲི་རྩད་བྱེད་ཐེངས་རེ་ཡིན། + + + + Ask password every time + ཐེངས་རེར་གསང་བ་འདི་འདྲི་རྩད་བྱེད་ཐེངས་རེ་ཡིན། + + + + + + Choose a CA certificate + CAཡི་དཔང་ཡིག་འདེམས་པ། + + + + + + CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) + CA དཔང་ཡིག (*.pem *.der *.p12 *.crt *.cer *.pfx) + + + + Choose a PAC file + ཡིག་ཆ་PACབདམས་པ་རེད། + + + + PAC Files (*.pac) + PACཡི་ཡིག་ཆ། (*.pac) + + + + + + + + + TabPage + + + Current Device + མིག་སྔའི་སྒྲིག་ཆས། + + + + Devices Closed! + སྒྲིག་ཆས་སྒོ་རྒྱག་པ།! + + + + Settings + སྒྲིག་བཀོད། + + + + Kylin NM + ཅིན་ལིན་NM + + + + kylin network applet desktop message + kylinདྲ་རྒྱའི་ཀུ་ཤུའི་ཅོག་ཙེའི་ཆ་འཕྲིན། + + + + VpnPage + + Wired Device not carried + སྐུད་ཡོད་སྒྲིག་ཆས་འཁྱེར་མེད་པ། + + + + WiFiConfigDialog + + + Dialog + + + + + WLAN Authentication + སྐུད་མེད་བདེན་དཔང་ར་སྤྲོད། + + + + Input WLAN Information Please + སྐུད་མེད་ཆ་འཕྲིན་ནང་འཇུག་གནང་རོགས། + + + + WLAN ID: + WLAN ID: + + + + WLAN Name: + སྐུད་མེད་མིང་།: + + + + Password: + གསང་གྲངས་ནི།: + + + + Cancl + ཁན་ཁེ་ལན། + + + + Ok + འགྲིགས། + + + + WlanListItem + + + Not connected + འབྲེལ་མཐུད་མི་བྱེད་པ། + + + + + + + + Disconnect + འབྲེལ་ཐག་ཆད་པ། + + + + + + + + Connect + སྦྲེལ་མཐུད་བྱེད་པ + + + + + Forget + བརྗེད་པ། + + + + + Property + ངོ་བོ། + + + + Auto Connect + རང་འགུལ་གྱིས་སྦྲེལ་མཐུད་ + + + + WlanMoreItem + + More... + 更多... + + + + Add Others... + གཞན་པ་ཁ་སྣོན་བྱས་ནས་... + + + + WlanPage + + + WLAN + སྐུད་མེད་ཅུས་ཁོངས་ཀྱི་དྲ་བ། + + + + No wireless network card detected + སྐུད་མེད་དྲ་རྒྱའི་བྱང་བུ་མ་རྙེད་པ། + + + + Activated WLAN + ངའི་དྲ་རྒྱ། + + + + Other WLAN + དྲ་བ་གཞན་དག + + + More... + 更多... + + + + WLAN Connected Successfully + སྐུད་མེད་དྲ་བ་སྦྲེལ་ཡོད། + + + + WLAN Disconnected Successfully + སྐུད་མེད་དྲ་རྒྱ་ཆད་སོང་། + + + + WpaWifiDialog + + EAP type + EAP方法 + + + Username + 用户名 + + + Password + 密钥 + + + Ask pwd each query + 每次询问密码 + + + Cancel + 取消 + + + Connect + 连接 + + + None + + + + Choose from file... + 从文件选择... + + + Choose a CA certificate + 选择一个CA证书 + + + CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) + CA 证书 (*.pem *.der *.p12 *.crt *.cer *.pfx) + + + Identity + 匿名身份 + + + Domain + + + + no need for CA certificate + 不需要CA证书 + + + + main + + + kylinnm + + + + + show kylin-nm wifi page + སྐུད་མེད་དྲ་རྒྱའི་ངོས་མངོན་པར་བྱས་ཡོད། + + + + show kylin-nm lan page + སྐུད་ཡོད་དྲ་རྒྱའི་ཤོག་ངོས་མངོན་པར་བྱས་ཡོད། + + + diff --git a/translations/kylin-nm_tr.qm b/translations/kylin-nm_tr.qm deleted file mode 100644 index 07e2ca58..00000000 Binary files a/translations/kylin-nm_tr.qm and /dev/null differ diff --git a/translations/kylin-nm_tr.ts b/translations/kylin-nm_tr.ts index c87a65ca..7a973305 100644 --- a/translations/kylin-nm_tr.ts +++ b/translations/kylin-nm_tr.ts @@ -99,46 +99,79 @@ Yeni ayarlar zaten etkili + + ConfigPage + + + Network profile type + + + + + Public(recommended) Devices on the network cannot discover this computer. Generally, it is suitable for networks in public places, such as airports or coffee shops, etc. + + + + + Private Devices on the network can discover this computer. Generally applicable to a network at home or work where you know and trust the individuals and devices on the network. + + + + + Config firewall and security settings + + + CreatNetPage - + Connection Name - - Ipv4Config + + IPv4Config - + Address - + Netmask - + Default Gateway - - + + Invalid address + + + + + Invalid subnet mask + + + + + Required - + Auto(DHCP) Oto(DHCP) - + Manual Elle @@ -146,82 +179,82 @@ DetailPage - + Auto Connection - - + + SSID: - + Copied successfully! - + Copy all - + Please input SSID: - - + + Protocol: - - + + Security Type: - - + + Hz: - - + + Chan: - - + + BandWidth: - - - IPV6: + + + IPv4: + IPv6 adresi: {4:?} + + + + + IPv6: + IPv6 adresi: {6:?} + + + + + IPv4 DNS: - - - IPV4: - - - - - - IPV4 Dns: - - - - - + + Mac: @@ -1150,86 +1183,199 @@ EnterpriseWlanDialog - - Connect Enterprise WLAN + + Wi-Fi network requires authentication - + + Access to Wi-Fi network " + + + + + " requires a password or encryption key. + + + + Cancel - + Connect + + FirewallDialog + + + Allow other devices on this network to discover this computer? + + + + + It is not recommended to enable this feature on public networks + + + + + Not allowed (recommended) + + + + + Allowed + + + Ipv4Page - - Ipv4Config - - - - + Address - + Netmask - + Default Gateway - + + IPv4Config + + + + Auto(DHCP) Oto(DHCP) - + Manual Elle + + + Invalid address + + + + + Invalid subnet mask + + + + + + Required + + + + + Address conflict + + Ipv6Page - - Ipv6Config - - - - + Address - + Subnet prefix Length - + Default Gateway - + + IPv6Config + + + + Auto(DHCP) Oto(DHCP) - + Manual Elle + + + + Required + + + + + Invalid address + + + + + Invalid gateway + + + + + Address conflict + + + + + JoinHiddenWiFiPage + + + Please enter the network name and security type + + + + + Network name(SSID) + + + + + Show Network List + + + + + Cancel + + + + + Join + + + + + Required + + + + + Find and Join Wi-Fi + + KylinDBus @@ -1241,62 +1387,66 @@ LanListItem - + Not connected Bağlanamadı - + Wired Device not carried - - + + + Disconnect Bağlantıyı Kes - - + + + Connect + + + + Property + + + + + + Delete + + LanPage - + No ethernet device avaliable - + LAN - + Activated LAN - + Inactivated LAN - - LAN Connected Successfully - - - - - LAN Disconnected Successfully - - - - + Wired Device not carried @@ -1304,12 +1454,12 @@ ListItem - + Kylin NM - + kylin network applet desktop message Kylin ağ uygulaması masaüstü mesajı @@ -1317,8 +1467,8 @@ MainWindow - - + + kylin-nm @@ -1339,17 +1489,17 @@ Gizli Ağı Bağlan - + LAN - + WLAN WLAN - + Settings @@ -1366,7 +1516,7 @@ HotSpot - + Show MainWindow Ana Pencereyi Göster @@ -1470,114 +1620,112 @@ NetDetail - + Kylin NM - + kylin network desktop message - + Detail - - Ipv4 - - - - - Ipv6 - - - - + Security - + + + Config + Ayar + + + Confirm - + Cancel - + Forget this network - - Add Lan Connect + + IPv4 + IPv6 adresi: {4?} + + + + IPv6 + IPv6 adresi: {6?} + + + + Add LAN Connect - - connect hiddin wlan + + Connect Hidden WLAN - - - + + Delete this network + + + + + + None Yok - - - + + + Auto Oto - + start check ipv4 address conflict - + start check ipv6 address conflict - - - - ipv4 address conflict! - - - - - - ipv6 address conflict! - - - - + this wifi no support enterprise type - + this wifi no support None type - + this wifi no support WPA2 type - + this wifi no support WPA3 type @@ -1799,163 +1947,241 @@ SecurityPage - + + Remember the Network + + + + Security - - + + Password - + EAP type - + Identity Kimlik: - + Domain Domain: - + CA certficate - + no need for CA certificate - + User certificate Kullanıcı sertifikası: - + User private key Kullanıcı özel anahtarı: - + User key password Kullanıcı anahtarı şifresi: - + + Password options + + + + + + + Required + + + + Ineer authentication - - Usename + + Username - + Ask pwd each query - - - - - - - - - + + + + + + + + + + + + None Yok - + WPA&WPA2 Personal - + WPA&WPA2 Enterprise - + WPA3 Personal - - - + + + + Choose from file... - - - + + PAC provisioning + + + + + Allow automatic PAC provisioning + + + + + PAC file + PAC dosyası + + + + Anonymous + Anonim + + + + Authenticated + Doğrulanmış + + + + Both + Her ikisi de + + + + Store passwords only for this user + + + + + Store password only for this user + + + + + Store passwords for all users + + + + + Store password for all users + + + + + Ask this password every time + + + + + Ask password every time + + + + + + Choose a CA certificate - - - + + + CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) - - - SinglePage - - Settings + + Choose a PAC file - - Kylin NM + + PAC Files (*.pac) - - kylin network applet desktop message - Kylin ağ uygulaması masaüstü mesajı + + + TabPage - + Current Device - + Devices Closed! - + Settings - + Kylin NM - + kylin network applet desktop message Kylin ağ uygulaması masaüstü mesajı @@ -1967,39 +2193,6 @@ Kylin ağ uygulaması masaüstü mesajı - - VpnListItem - - - Not connected - Bağlanamadı - - - - - Disconnect - Bağlantıyı Kes - - - - - Connect - - - - - VpnPage - - - VPN Connection - - - - - VPN Settings - - - WiFiConfigDialog @@ -2008,37 +2201,37 @@ - + WLAN Authentication - + Input WLAN Information Please - + WLAN ID: - + WLAN Name: - + Password: - + Cancl - + Ok Tamam @@ -2046,31 +2239,42 @@ WlanListItem - + Not connected Bağlanamadı - - + + + + + Disconnect Bağlantıyı Kes - - - + + + + + Connect - - + + + Property + + + + + Forget - + Auto Connect @@ -2078,7 +2282,7 @@ WlanMoreItem - + Add Others... @@ -2086,33 +2290,32 @@ WlanPage - + WLAN WLAN - + Activated WLAN - + Other WLAN - + No wireless network card detected - + WLAN Connected Successfully - - + WLAN Disconnected Successfully @@ -2150,17 +2353,4 @@ - - vpnMainWindow - - - kylin-vpn - - - - - vpn tool - - - diff --git a/translations/kylin-nm_zh_CN.qm b/translations/kylin-nm_zh_CN.qm deleted file mode 100644 index 7f1110df..00000000 Binary files a/translations/kylin-nm_zh_CN.qm and /dev/null differ diff --git a/translations/kylin-nm_zh_CN.ts b/translations/kylin-nm_zh_CN.ts index 08cbf757..ed79480e 100644 --- a/translations/kylin-nm_zh_CN.ts +++ b/translations/kylin-nm_zh_CN.ts @@ -24,14 +24,37 @@ 正在检测ip地址冲突 - IPV4 address conflict, Please change IP + IPv4 address conflict, Please change IP ip地址冲突,请更改ip - IPV6 address conflict, Please change IP + IPv6 address conflict, Please change IP ip地址冲突,请更改ip {6 ?} + + ConfigPage + + + Network profile type + 网络配置文件类型 + + + + Public(recommended) Devices on the network cannot discover this computer. Generally, it is suitable for networks in public places, such as airports or coffee shops, etc. + 公用(推荐) 网络中的设备不可发现此电脑。一般情况下适用于公共场所中的网络,如机场或咖啡店等等。 + + + + Private Devices on the network can discover this computer. Generally applicable to a network at home or work where you know and trust the individuals and devices on the network. + 专用 网络中的设备可发现此电脑。一般情况下适用于家庭或工作单位的网络,您认识并信任网络上的个人和设备。 + + + + Config firewall and security settings + 配置防火墙和安全设置 + + CopyButton @@ -50,27 +73,27 @@ CreatNetPage - + Connection Name 网络名称 - - Ipv4Config - IPV4配置 + + IPv4Config + IPv4配置 - + Address - IPV4地址 + IPv4地址 - + Netmask 子网掩码 - + Default Gateway 默认网关 @@ -83,18 +106,28 @@ 备选DNS - + Auto(DHCP) 自动(DHCP) - + Manual 手动 - - + + Invalid address + 无效地址 + + + + Invalid subnet mask + 无效子网掩码 + + + + Required 必填 @@ -102,82 +135,82 @@ DetailPage - + Auto Connection 自动连接 - - + + SSID: SSID: - + Copied successfully! 复制成功! - + Copy all 复制全部 - + Please input SSID: 请输入SSID: - - + + Protocol: 协议: - - + + Security Type: 安全类型: - - + + Hz: 网络频带: - - + + Chan: 网络通道: - - + + BandWidth: 带宽: - - - IPV6: - 本地链接IPV6地址: + + + IPv6: + 本地链接IPv6地址: - - - IPV4: - IPV4地址: + + + IPv4: + IPv4地址: - - - IPV4 Dns: - IPV4 DNS服务器: + + + IPv4 DNS: + IPv4 DNS服务器: - - + + Mac: 物理地址: @@ -415,44 +448,97 @@ EnterpriseWlanDialog - Connect Enterprise WLAN - 连接企业网 + 连接企业网 Close 关闭 - + + Wi-Fi network requires authentication + Wi-Fi网络要求认证 + + + + Access to Wi-Fi network " + 访问Wi-Fi网络 + + + + " requires a password or encryption key. + 需要密码或加密密钥。 + + + Cancel 取消 - + Connect 连接 + + FirewallDialog + + Allow your computer to be discovered by other computers and devices on this network? + 是否允许你的电脑被此网络上的其他电脑和设备发现? + + + It is recommended that you enable this feature on your home and work networks rather than public networks. + 建议你在家庭和工作网络上而非公共网络上启用此功能。 + + + Yse + + + + No + + + + + Allow other devices on this network to discover this computer? + 是否允许此网络上的其他设备发现这台电脑? + + + + It is not recommended to enable this feature on public networks + 不建议在公共网络上开启此功能 + + + + Not allowed (recommended) + 不允许(推荐) + + + + Allowed + 允许 + + Ipv4Page - - Ipv4Config - Ipv4配置 + + IPv4Config + IPv4配置 - + Address 地址 - + Netmask 子网掩码 - + Default Gateway 默认网关 @@ -465,35 +551,56 @@ 备选DNS - + Auto(DHCP) 自动 - + Manual 手动 + + + Invalid address + 无效地址 + + + + Invalid subnet mask + 无效子网掩码 + + + + + Required + 必填 + + + + Address conflict + 地址冲突 + Ipv6Page - - Ipv6Config - Ipv6配置 + + IPv6Config + IPv6配置 - + Address 地址 - + Subnet prefix Length 子网前缀长度 - + Default Gateway 默认网关 @@ -506,88 +613,163 @@ 备选DNS - + Auto(DHCP) 自动 - + Manual 手动 + + + + Required + 必填 + + + + Invalid address + 无效地址 + + + + Invalid gateway + 无效网关 + + + + Address conflict + 地址冲突 + + + + JoinHiddenWiFiPage + + + Please enter the network name and security type + 请输入您想要加入网络的名称和安全类型 + + + + Network name(SSID) + 网络名(SSID) + + + Remember the Network + 记住该网络 + + + + Show Network List + 显示网络列表 + + + + Cancel + 取消 + + + + Join + 加入 + + + + Required + 必填 + + + + Find and Join Wi-Fi + 查找并加入Wi-Fi + LanListItem - + Not connected 未连接 - + Wired Device not carried 未插入网线 - - + + + Disconnect 断开 - - + + + Connect 连接 + + + + Property + 属性 + + + + + Delete + 删除此网络 + LanPage - + No ethernet device avaliable 未检测到有线设备 - + LAN 有线网络 - + Activated LAN 我的网络 - + Inactivated LAN 其他网络 - LAN Disconnected Successfully - 有线网络已断开 + 有线网络已断开 - + Wired Device not carried 未插入网线 - LAN Connected Successfully - 有线网络已连接 + 有线网络已连接 ListItem - + Kylin NM 麒麟网络设置工具 - + kylin network applet desktop message 网络提示消息 @@ -595,72 +777,76 @@ MainWindow - - + + kylin-nm 网络工具 - + LAN 有线网络 有线网络 - + WLAN 无线局域网 无线局域网 - + Show MainWindow 打开网络工具 - + Settings 设置网络项 设置网络项 + + Network tool + 网络工具 + MultipleDnsWidget DNS server: - DNS服务器: + DNS服务器: NetDetail - + Kylin NM 麒麟网络设置工具 - + kylin network desktop message 网络提示消息 - + Detail 详情 - - Ipv4 - Ipv4 + + IPv4 + IPv4 - - Ipv6 - Ipv6 + + IPv6 + IPv6 - + Security 安全 @@ -669,84 +855,90 @@ 关闭 - + + + Config + 配置 + + + Confirm 确定 - + Cancel 取消 - + Forget this network 忘记此网络 - - Add Lan Connect + + Delete this network + 删除此网络 + + + + Add LAN Connect 添加有线网络 - - connect hiddin wlan + + Connect Hidden WLAN 连接到隐藏WLAN - - - + + + None - - - + + + Auto 自动 - + start check ipv4 address conflict 开始检测ipv4地址冲突 - + start check ipv6 address conflict 开始检测ipv6地址冲突 - - - ipv4 address conflict! - ipv4地址冲突! + ipv4地址冲突! - - ipv6 address conflict! - ipv6地址冲突! + ipv6地址冲突! - + this wifi no support enterprise type 此wifi不支持企业网类型 - + this wifi no support None type 此wifi不支持空类型 - + this wifi no support WPA2 type 此wifi不支持WPA2类型 - + this wifi no support WPA3 type 此wifi不支持WPA3类型 @@ -771,16 +963,16 @@ 带宽: - IPV4: - IPV4地址: + IPv4: + IPv4地址: - IPV4 Dns: - IPV4 DNS服务器: + IPv4 DNS: + IPv4 DNS服务器: - IPV6: - 本地链接IPV6地址: + IPv6: + 本地链接IPv6地址: Mac: @@ -857,247 +1049,250 @@ SecurityPage - + + Remember the Network + 记住该网络 + + + Security 安全性 - - + + Password 密钥 - + EAP type EAP方法 - + Identity 匿名身份 - + Domain - + CA certficate CA 证书 - + no need for CA certificate 不需要CA证书 - + User certificate 用户证书 - + User private key 用户私钥 - + User key password 用户密钥密码 - + + Password options + 密码选项 + + + + + + Required + 必填 + + + Ineer authentication 内部认证 - - Usename + + Username 用户名 - Username - Usename - 用户名 - - - + Ask pwd each query 每次询问密码 - - - - - - - - - + + + + + + + + + + + + None - + WPA&WPA2 Personal WPA&WPA2 个人 - + WPA&WPA2 Enterprise WPA&WPA2 企业 - + WPA3 Personal WPA3 个人 - - - + + + + Choose from file... 从文件选择... - - - - Choose a CA certificate - 选择一个CA证书 - - - - - - CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) - CA 证书 (*.pem *.der *.p12 *.crt *.cer *.pfx) - - - + PAC provisioning - PAC 配置 + PAC配置 - + Allow automatic PAC provisioning 允许自动PAC配置 - + PAC file - PAC 文件 + PAC文件 - + Anonymous 匿名 - + Authenticated 已认证 - + Both 两者兼用 - + + Store passwords only for this user + 仅为该用户存储密码 + + + + Store password only for this user + 仅为该用户存储密码 + + + + Store passwords for all users + 存储所有用户的密码 + + + + Store password for all users + 存储所有用户的密码 + + + + Ask this password every time + 每次询问这个密码 + + + + Ask password every time + 每次询问这个密码 + + + + + + Choose a CA certificate + 选择一个CA证书 + + + + + + CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) + CA 证书 (*.pem *.der *.p12 *.crt *.cer *.pfx) + + + Choose a PAC file 选择一个PAC文件 - + PAC Files (*.pac) - PAC文件(*.pac) - - - - SinglePage - - - Settings - 设置 + PAC 文件 (*.pac) - - Kylin NM - 网络工具 - - - - kylin network applet desktop message - 网络提示消息 + + + TabPage - + Current Device 当前网卡 - + Devices Closed! 设备关闭! - + Settings 网络设置 - + Kylin NM 麒麟网络设置工具 - + kylin network applet desktop message 网络提示消息 - - VpnListItem - - - Not connected - 未连接 - - - - - Disconnect - 断开 - - - - - Connect - 连接 - - VpnPage - VPN Connection - VPN连接 - - - - VPN - - - - - VPN Settings - VPN设置 + Wired Device not carried + 未插入网线 @@ -1108,37 +1303,37 @@ - + WLAN Authentication - + Input WLAN Information Please - + WLAN ID: - + WLAN Name: - + Password: - + Cancl - + Ok @@ -1146,31 +1341,42 @@ WlanListItem - + Not connected 未连接 - - + + + + + Disconnect 断开 - - - + + + + + Connect 连接 - - + + Forget 忘记此网络 - + + + Property + 属性 + + + Auto Connect 自动加入该网络 @@ -1182,7 +1388,7 @@ 更多... - + Add Others... 加入其他网络... @@ -1190,22 +1396,22 @@ WlanPage - + WLAN 无线局域网 - + No wireless network card detected 未检测到无线网卡 - + Activated WLAN 我的网络 - + Other WLAN 其他网络 @@ -1214,13 +1420,12 @@ 更多... - + WLAN Connected Successfully 无线网络已连接 - - + WLAN Disconnected Successfully 无线网络已断开 @@ -1283,38 +1488,19 @@ main - + kylinnm - + show kylin-nm wifi page - + show kylin-nm lan page - - vpnMainWindow - - kylin-vpn - VPN工具 - - - vpn tool - VPN工具 - - - - vpnObject - - - vpn tool - VPN工具 - -