kylin-nm-plugin/0000775000175000017500000000000015170122723012532 5ustar fengfengkylin-nm-plugin/kylin-nm.pro0000664000175000017500000000060515160520531015011 0ustar fengfengTEMPLATE = subdirs CONFIG += ordered \ qt SUBDIRS = \ plugins/plugin.pro \ libnm-kylin # autotests/autotests.pro # kylin-nm-gui \ # kylin-nm-server \ #kylin-nm-gui.depends = libnm-kylin #kylin-nm-server.depends = libnm-kylin #TRANSLATIONS += \ # translations/kylin-nm_zh_CN.ts \ # translations/kylin-nm_tr.ts \ # translations/kylin-nm_bo.ts kylin-nm-plugin/README.md0000664000175000017500000000206615170130044014010 0ustar fengfeng# NAME kylin-nm-plugin - Plugin of kylin network monitor used in Ubuntu Kylin operation system # DESCRIPTION kylin-nm is a Qt based applet and uses some interface provided by NetworkManager. It provides a GUI for users to connect or disconnect wired or wireless network which managed by NetworkManager. Users can also create new wired network and configure a old network. By click button at left bottom in the main window, a network configure window of NetworkManager will show in the screen. Users can get some information about network directly by clicking one item in the network list, these information shown in extension area. kylin-nm-plugin provides a system tray applet for UKUI . It lets users view network status and configure wired, wireless, VPN, and related network connection settings in UKUI. # BUILD KYLIN-NM down the source sode install dependency packages(see cntrol files in the debian directory) execute debuild command in the root directory of project execute sudo dpkg -i packagename.deb to installkylin-nm-plugin/AUTHORS0000664000175000017500000000010015170122552013571 0ustar fengfengshine zhoubin kylin-nm-plugin/man/0000775000175000017500000000000015160520516013306 5ustar fengfengkylin-nm-plugin/man/kylin-nm-plugin.10000664000175000017500000000140215160520516016417 0ustar fengfeng.\" Man page for Kylin-nm .TH KYLIN-NM 1 "20 September 2019" "UKUI Desktop Environment" .\" Please adjust this date when revising the manpage. .\" .SH "NAME" kylin-nm \- The tool for the UKUI Desktop Environment .SH "SYNOPSIS" .B kylin-nm .SH "DESCRIPTION" The \fBkylin-nm\fR program is a part of the ukui-indicators, It provides network manager for the the UKUI Desktop Environment. Detect the system disk automatically, Can pop up and open the device. .PP This manual page documents the \fBkylin-nm\fR command. .P .SH "BUGS" .SS Should you encounter any bugs, they may be reported at: https://github.com/ukui/kylin-nm/issues .SH "AUTHORS" .SS This Man Page has been written for the UKUI Desktop Environment by: shine (2019) .SH "SEE ALSO"kylin-nm-plugin/autotests/0000775000175000017500000000000015167660365014604 5ustar fengfengkylin-nm-plugin/autotests/unit_test_libnm_icon_kylin/0000775000175000017500000000000015160520531022200 5ustar fengfengkylin-nm-plugin/autotests/unit_test_libnm_icon_kylin/unit_test_libnm_icon_kylin.pro0000664000175000017500000000550215160520531030341 0ustar fengfeng#------------------------------------------------- # # Project created by QtCreator 2019-08-22T11:12:59 # #------------------------------------------------- QT += core gui dbus network svg widgets QT -= gui TEMPLATE = app DEFINES += LIBNMICONKYLIN_LIBRARY CONFIG += c++14 qt link_pkgconfig no_keywords PKGCONFIG += gsettings-qt \ kysdk-qtwidgets \ kylin-nm-base TARGET = unit_test_libnm_icon_kylin target.source += $$TARGET target.path = ./ #代码覆盖率工具gcov QMAKE_LFLAGS +=-fprofile-arcs -ftest-coverage QMAKE_CXXFLAGS += --coverage -fno-inline -fno-access-control -fno-exceptions LIBS += -lgtest_main -lpthread LIBS += -L$$[QT_INSTALL_LIBS] -lgtest -lgcov LIBS += -L$$[QT_INSTALL_LIBS] -lkylin-nm-base #打桩工具 TEST_UTILS_PATH = $$PWD/../kt-test-utils # Include directories INCLUDEPATH += $$PROJECT_ROOTDIR \ $$TEST_UTILS_PATH/cpp-stub \ $$TEST_UTILS_PATH/cpp-stub-ext SOURCES += main.cpp \ ../../libnm-kylin/libnm-icon-kylin/kynetworkicon.cpp \ unit_test_libnm_icon_kylin.cpp \ ../../plugins/component/DeviceFrame/deviceframe.cpp \ unit_test_plugin_deviceframe.cpp \ ../../plugins/component/Divider/divider.cpp \ unit_test_plugin_divier.cpp \ ../../plugins/component/FixLabel/fixlabel.cpp \ unit_test_plugin_fixlabel.cpp \ ../../plugins/netconnect/itemframe.cpp \ unit_test_plugin_itemframe.cpp \ ../../plugins/component/RadioItemButton/radioitembutton.cpp \ unit_test_plugin_radioitembutton.cpp # ../../plugins/component/DrownLabel/drownlabel.cpp # unit_test_plugin_drownlabel.cpp # ../../plugins/netconnect/netconnect.cpp \ # unit_test_plugin_netconnect.cpp # ../../plugins/netconnect/lanitem.cpp \ # unit_test_plugin_lanitem.cpp # ../../plugins/component/InfoButton/infobutton.cpp \ # unit_test_plugin_infobutton.cpp \ HEADERS += ../../libnm-kylin/libnm-icon-kylin/kynetworkicon.h \ ../../plugins/component/DeviceFrame/deviceframe.h \ ../../plugins/component/Divider/divider.h \ ../../plugins/component/FixLabel/fixlabel.h \ ../../plugins/netconnect/itemframe.h \ ../../plugins/component/RadioItemButton/radioitembutton.h # ../../plugins/component/DrownLabel/drownlabel.h # ../../plugins/netconnect/netconnect.h # ../../plugins/netconnect/lanitem.h # ../../plugins/component/FixLabel/infobutton.h \ ## Default rules for deployment. #unix { # target.path = /usr/lib # manager.path = /usr/include/kylin-nm # manager.files = kynetworkicon.h # INSTALLS += manager #} #!isEmpty(target.path): INSTALLS += target kylin-nm-plugin/autotests/unit_test_libnm_icon_kylin/unit_test_plugin_divier.cpp0000664000175000017500000000272515160520531027650 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2024 KylinSoft 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 #include #include "../../plugins/component/Divider/divider.h" #include "stubext.h" using namespace stub_ext; class DividerTest : public testing::Test { protected: static void SetUpTestSuite() { m_pDividerTest = new Divider(); } static void TearDownTestSuite() { if (m_pDividerTest) { delete m_pDividerTest; m_pDividerTest = nullptr; } } static Divider *m_pDividerTest; }; Divider *DividerTest::m_pDividerTest = nullptr; TEST_F(DividerTest, testAllFunc) { QPaintEvent * e; m_pDividerTest->paintEvent(e); } kylin-nm-plugin/autotests/unit_test_libnm_icon_kylin/unit_test_plugin_radioitembutton.cpp0000664000175000017500000000434515160520531031577 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2024 KylinSoft 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 #include #include #include "../../plugins/component/RadioItemButton/radioitembutton.h" #include "stubext.h" using namespace stub_ext; class RadioItemButtonTest : public testing::Test { protected: static void SetUpTestSuite() { m_pRadioItemButtonTest = new RadioItemButton(); } static void TearDownTestSuite() { if (m_pRadioItemButtonTest) { delete m_pRadioItemButtonTest; m_pRadioItemButtonTest = nullptr; } } static RadioItemButton *m_pRadioItemButtonTest; }; RadioItemButton *RadioItemButtonTest::m_pRadioItemButtonTest = nullptr; TEST_F(RadioItemButtonTest, testAllFunc) { QIcon icon(""); m_pRadioItemButtonTest->setButtonIcon(icon); m_pRadioItemButtonTest->setDefaultPixmap(); m_pRadioItemButtonTest->setActive(true); m_pRadioItemButtonTest->setActive(false); // QPaintEvent *p_paintEvent; // m_pRadioItemButtonTest->paintEvent(p_paintEvent); // QMouseEvent *p_mouseEvent; // m_pRadioItemButtonTest->mousePressEvent(p_mouseEvent); // m_pRadioItemButtonTest->mouseReleaseEvent(p_mouseEvent); // QEvent *p_event; // m_pRadioItemButtonTest->enterEvent(p_event); // m_pRadioItemButtonTest->leaveEvent(p_event); m_pRadioItemButtonTest->refreshButtonIcon(); m_pRadioItemButtonTest->onPaletteChanged(); } kylin-nm-plugin/autotests/unit_test_libnm_icon_kylin/main.cpp0000664000175000017500000000206415160520531023632 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 #include int main(int argc, char **argv) { QApplication a(argc,argv); testing::InitGoogleTest(&argc, argv); // a.exec(); return RUN_ALL_TESTS(); } kylin-nm-plugin/autotests/unit_test_libnm_icon_kylin/unit_test_plugin_infobutton.cpp0000664000175000017500000000365215160520531030555 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2024 KylinSoft 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 #include #include #include "../../plugins/component/InfoButton/infobutton.h" #include "stubext.h" using namespace stub_ext; class InfoButtonTest : public testing::Test { protected: static void SetUpTestSuite() { m_pInfoButtonTest = new InfoButton(); } static void TearDownTestSuite() { if (m_pInfoButtonTest) { delete m_pInfoButtonTest; m_pInfoButtonTest = nullptr; } } static InfoButton *m_pInfoButtonTest; }; InfoButton *InfoButtonTest::m_pInfoButtonTest = nullptr; TEST_F(InfoButtonTest, testAllFunc) { // QPaintEvent *p_paintEvent; // m_pInfoButtonTest->paintEvent(p_paintEvent); // QEvent *p_event; // m_pInfoButtonTest->enterEvent(p_event); // m_pInfoButtonTest->leaveEvent(p_event); // QMouseEvent *p_mouseEvent; // m_pInfoButtonTest->mousePressEvent(p_mouseEvent); // m_pInfoButtonTest->mouseReleaseEvent(p_mouseEvent); m_pInfoButtonTest->initUI(); // m_pInfoButtonTest->onGSettingChaned("key"); } kylin-nm-plugin/autotests/unit_test_libnm_icon_kylin/unit_test_plugin_deviceframe.cpp0000664000175000017500000000276715160520531030646 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2024 KylinSoft 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 #include #include "../../plugins/component/DeviceFrame/deviceframe.h" #include "stubext.h" using namespace stub_ext; class DeviceFrameTest : public testing::Test { protected: static void SetUpTestSuite() { m_pDeviceFrameTest = new DeviceFrame("eth0"); } static void TearDownTestSuite() { if (m_pDeviceFrameTest) { delete m_pDeviceFrameTest; m_pDeviceFrameTest = nullptr; } } static DeviceFrame *m_pDeviceFrameTest; }; DeviceFrame *DeviceFrameTest::m_pDeviceFrameTest = nullptr; TEST_F(DeviceFrameTest, testAllFunc) { ASSERT_EQ(true, true); } kylin-nm-plugin/autotests/unit_test_libnm_icon_kylin/unit_test_plugin_lanitem.cpp0000664000175000017500000000513215160520531030012 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2024 KylinSoft 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 #include #include #include "../../plugins/netconnect/lanitem.h" #include "stubext.h" using namespace stub_ext; class LanItemTest : public testing::Test { protected: static void SetUpTestSuite() { m_pLanItemTest = new LanItem(false); } static void TearDownTestSuite() { if (m_pLanItemTest) { delete m_pLanItemTest; m_pLanItemTest = nullptr; } } static LanItem *m_pLanItemTest; }; LanItem *LanItemTest::m_pLanItemTest = nullptr; TEST_F(LanItemTest, testAllFunc) { m_pLanItemTest->setName("lan1"); QString strLan = m_pLanItemTest->getName(); qDebug() << Q_FUNC_INFO << __LINE__ << strLan; QIcon icon(""); m_pLanItemTest->setItemIcon(icon); m_pLanItemTest->setStatus(true); bool status = m_pLanItemTest->getStatus(); qDebug() << Q_FUNC_INFO << __LINE__ << status; bool loadStatus = m_pLanItemTest->getIsLoading(); qDebug() << Q_FUNC_INFO << __LINE__ << loadStatus; QString strUuid = m_pLanItemTest->getUuid(); qDebug() << Q_FUNC_INFO << __LINE__ << strUuid; m_pLanItemTest->setUuid(strUuid); QString strPath = m_pLanItemTest->getPath(); qDebug() << Q_FUNC_INFO << __LINE__ << strPath; m_pLanItemTest->setPath(strPath); m_pLanItemTest->startLoading(); m_pLanItemTest->stopLoading(); // QMouseEvent *p_mouseEvent; // m_pLanItemTest->mousePressEvent(p_mouseEvent); // m_pLanItemTest->mouseReleaseEvent(p_mouseEvent); // QEvent *p_event; // m_pLanItemTest->enterEvent(p_event); // m_pLanItemTest->leaveEvent(p_event); // QPaintEvent *p_paintEvent; // m_pLanItemTest->paintEvent(p_paintEvent); m_pLanItemTest->updateIcon(); } kylin-nm-plugin/autotests/unit_test_libnm_icon_kylin/unit_test_plugin_fixlabel.cpp0000664000175000017500000000314715160520531030153 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2024 KylinSoft 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 #include #include #include "../../plugins/component/FixLabel/fixlabel.h" #include "stubext.h" using namespace stub_ext; class FixLabelTest : public testing::Test { protected: static void SetUpTestSuite() { m_pFixLabelTest = new FixLabel(); } static void TearDownTestSuite() { if (m_pFixLabelTest) { delete m_pFixLabelTest; m_pFixLabelTest = nullptr; } } static FixLabel *m_pFixLabelTest; }; FixLabel *FixLabelTest::m_pFixLabelTest = nullptr; TEST_F(FixLabelTest, testAllFunc) { m_pFixLabelTest->setLabelText("test"); QString str = m_pFixLabelTest->getText(); //增加判断 qDebug() << str; m_pFixLabelTest->changedLabelSlot(); } kylin-nm-plugin/autotests/unit_test_libnm_icon_kylin/Makefile0000664000175000017500000007065315160520531023653 0ustar fengfeng############################################################################# # Makefile for building: unit_test_libnm_icon_kylin # Generated by qmake (3.1) (Qt 5.12.12) # Project: unit_test_libnm_icon_kylin.pro # Template: app # Command: /usr/lib/qt5/bin/qmake -o Makefile unit_test_libnm_icon_kylin.pro ############################################################################# MAKEFILE = Makefile EQ = = ####### Compiler, tools and options CC = gcc CXX = g++ DEFINES = -DLIBNMICONKYLIN_LIBRARY -DQT_NO_DEBUG -DQT_NO_KEYWORDS -DQT_DBUS_LIB -DQT_NETWORK_LIB -DQT_SVG_LIB -DQT_WIDGETS_LIB -DQT_GUI_LIB -DQT_CORE_LIB CFLAGS = -pipe -O2 -pthread -D_REENTRANT -Wall -W -fPIC $(DEFINES) CXXFLAGS = -pipe --coverage -fno-inline -fno-access-control -fno-exceptions -O2 -std=gnu++1y -pthread -D_REENTRANT -Wall -W -fPIC $(DEFINES) INCPATH = -I. -I../kt-test-utils/cpp-stub -I../kt-test-utils/cpp-stub-ext -isystem /usr/include/libnm -isystem /usr/include/libmount -isystem /usr/include/blkid -isystem /usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -isystem /usr/include/kylin-nm -isystem /usr/include/KF5/NetworkManagerQt -isystem /usr/include/x86_64-linux-gnu/qt5/QGSettings -isystem /usr/include/x86_64-linux-gnu/qt5 -isystem /usr/include/x86_64-linux-gnu/qt5/QtDBus -isystem /usr/include/x86_64-linux-gnu/qt5/QtNetwork -isystem /usr/include/x86_64-linux-gnu/qt5/QtSvg -isystem /usr/include/x86_64-linux-gnu/qt5/QtWidgets -isystem /usr/include/x86_64-linux-gnu/qt5/QtGui -isystem /usr/include/x86_64-linux-gnu/qt5/QtCore -I. -I/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++ QMAKE = /usr/lib/qt5/bin/qmake DEL_FILE = rm -f CHK_DIR_EXISTS= test -d MKDIR = mkdir -p COPY = cp -f COPY_FILE = cp -f COPY_DIR = cp -f -R INSTALL_FILE = install -m 644 -p INSTALL_PROGRAM = install -m 755 -p INSTALL_DIR = cp -f -R QINSTALL = /usr/lib/qt5/bin/qmake -install qinstall QINSTALL_PROGRAM = /usr/lib/qt5/bin/qmake -install qinstall -exe DEL_FILE = rm -f SYMLINK = ln -f -s DEL_DIR = rmdir MOVE = mv -f TAR = tar -cf COMPRESS = gzip -9f DISTNAME = unit_test_libnm_icon_kylin1.0.0 DISTDIR = /data/data/kylinos-src/单元测试/dd/kylin-nm-plugin-openkylin-nile-tests/kylin-nm-plugin-openkylin-nile-tests/kylin-nm-plugin-openkylin-nile-tests/autotests/unit_test_libnm_icon_kylin/.tmp/unit_test_libnm_icon_kylin1.0.0 LINK = g++ LFLAGS = -fprofile-arcs -ftest-coverage -Wl,-O1 LIBS = $(SUBLIBS) -lgtest_main -L/usr/lib/x86_64-linux-gnu -lgtest -lgcov -L/usr/lib/ -lkylin-nm-base -lnm -lgio-2.0 -lgobject-2.0 -lglib-2.0 -lgsettings-qt /usr/lib/x86_64-linux-gnu/libQt5DBus.so /usr/lib/x86_64-linux-gnu/libQt5Network.so /usr/lib/x86_64-linux-gnu/libQt5Svg.so /usr/lib/x86_64-linux-gnu/libQt5Widgets.so /usr/lib/x86_64-linux-gnu/libQt5Gui.so /usr/lib/x86_64-linux-gnu/libQt5Core.so /usr/lib/x86_64-linux-gnu/libGL.so -lpthread AR = ar cqs RANLIB = SED = sed STRIP = strip ####### Output directory OBJECTS_DIR = ./ ####### Files SOURCES = ../../libnm-kylin/libnm-icon-kylin/kynetworkicon.cpp \ unit_test_libnm_icon_kylin.cpp \ ../../plugins/component/DeviceFrame/deviceframe.cpp \ unit_test_plugin_deviceframe.cpp \ ../../plugins/component/Divider/divider.cpp \ unit_test_plugin_divier.cpp \ main.cpp moc_kynetworkicon.cpp OBJECTS = kynetworkicon.o \ unit_test_libnm_icon_kylin.o \ deviceframe.o \ unit_test_plugin_deviceframe.o \ divider.o \ unit_test_plugin_divier.o \ main.o \ moc_kynetworkicon.o DIST = /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/spec_pre.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/unix.conf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/linux.conf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/sanitize.conf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/gcc-base.conf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/gcc-base-unix.conf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/g++-base.conf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/g++-unix.conf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/qconfig.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_BluezQt.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_KWindowSystem.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_accessibility_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_bootstrap_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_concurrent.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_concurrent_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_core.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_core_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_dbus.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_dbus_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_devicediscovery_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_edid_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_egl_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eglfs_kms_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eglfsdeviceintegration_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eventdispatcher_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_fb_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_fontdatabase_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_glx_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_gui.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_gui_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_input_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_kms_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_linuxaccessibility_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_multimedia.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_multimediawidgets.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_network.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_network_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_opengl_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_openglextensions.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_openglextensions_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_platformcompositor_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_printsupport.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_printsupport_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_script.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_scripttools.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_service_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_sql.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_sql_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_svg.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_testlib.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_testlib_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_theme_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_vulkan_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_widgets.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_widgets_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_x11extras.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xcb_qpa_lib_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xml.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xml_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_phonon4qt5.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qt_functions.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qt_config.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++/qmake.conf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/spec_post.prf \ ../../.qmake.stash \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/exclusive_builds.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/toolchain.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/default_pre.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/resolve_config.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/default_post.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/link_pkgconfig.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qt.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/resources.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/moc.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/unix/opengl.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/uic.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/dbuscommon.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/dbusinterfaces.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/dbusadaptors.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/unix/thread.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/warn_on.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qmake_use.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/file_copies.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/testcase_targets.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/exceptions.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/yacc.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/lex.prf \ unit_test_libnm_icon_kylin.pro ../../libnm-kylin/libnm-icon-kylin/kynetworkicon.h \ ../../plugins/component/DeviceFrame/deviceframe.h \ ../../plugins/component/Divider/divider.h ../../libnm-kylin/libnm-icon-kylin/kynetworkicon.cpp \ unit_test_libnm_icon_kylin.cpp \ ../../plugins/component/DeviceFrame/deviceframe.cpp \ unit_test_plugin_deviceframe.cpp \ ../../plugins/component/Divider/divider.cpp \ unit_test_plugin_divier.cpp \ main.cpp QMAKE_TARGET = unit_test_libnm_icon_kylin DESTDIR = TARGET = unit_test_libnm_icon_kylin first: all ####### Build rules unit_test_libnm_icon_kylin: $(OBJECTS) $(LINK) $(LFLAGS) -o $(TARGET) $(OBJECTS) $(OBJCOMP) $(LIBS) Makefile: unit_test_libnm_icon_kylin.pro /usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++/qmake.conf /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/spec_pre.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/unix.conf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/linux.conf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/sanitize.conf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/gcc-base.conf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/gcc-base-unix.conf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/g++-base.conf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/g++-unix.conf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/qconfig.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_BluezQt.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_KWindowSystem.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_accessibility_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_bootstrap_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_concurrent.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_concurrent_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_core.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_core_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_dbus.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_dbus_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_devicediscovery_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_edid_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_egl_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eglfs_kms_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eglfsdeviceintegration_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eventdispatcher_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_fb_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_fontdatabase_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_glx_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_gui.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_gui_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_input_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_kms_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_linuxaccessibility_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_multimedia.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_multimediawidgets.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_network.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_network_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_opengl_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_openglextensions.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_openglextensions_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_platformcompositor_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_printsupport.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_printsupport_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_script.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_scripttools.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_service_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_sql.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_sql_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_svg.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_testlib.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_testlib_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_theme_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_vulkan_support_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_widgets.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_widgets_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_x11extras.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xcb_qpa_lib_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xml.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xml_private.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_phonon4qt5.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qt_functions.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qt_config.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++/qmake.conf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/spec_post.prf \ ../../.qmake.stash \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/exclusive_builds.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/toolchain.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/default_pre.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/resolve_config.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/default_post.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/link_pkgconfig.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qt.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/resources.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/moc.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/unix/opengl.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/uic.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/dbuscommon.pri \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/dbusinterfaces.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/dbusadaptors.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/unix/thread.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/warn_on.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qmake_use.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/file_copies.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/testcase_targets.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/exceptions.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/yacc.prf \ /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/lex.prf \ unit_test_libnm_icon_kylin.pro $(QMAKE) -o Makefile unit_test_libnm_icon_kylin.pro /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/spec_pre.prf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/unix.conf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/linux.conf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/sanitize.conf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/gcc-base.conf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/gcc-base-unix.conf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/g++-base.conf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/g++-unix.conf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/qconfig.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_BluezQt.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_KWindowSystem.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_accessibility_support_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_bootstrap_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_concurrent.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_concurrent_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_core.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_core_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_dbus.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_dbus_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_devicediscovery_support_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_edid_support_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_egl_support_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eglfs_kms_support_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eglfsdeviceintegration_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eventdispatcher_support_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_fb_support_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_fontdatabase_support_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_glx_support_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_gui.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_gui_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_input_support_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_kms_support_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_linuxaccessibility_support_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_multimedia.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_multimediawidgets.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_network.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_network_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_opengl_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_openglextensions.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_openglextensions_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_platformcompositor_support_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_printsupport.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_printsupport_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_script.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_scripttools.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_service_support_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_sql.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_sql_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_svg.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_testlib.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_testlib_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_theme_support_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_vulkan_support_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_widgets.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_widgets_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_x11extras.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xcb_qpa_lib_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xml.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xml_private.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_phonon4qt5.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qt_functions.prf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qt_config.prf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++/qmake.conf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/spec_post.prf: ../../.qmake.stash: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/exclusive_builds.prf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/toolchain.prf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/default_pre.prf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/resolve_config.prf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/default_post.prf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/link_pkgconfig.prf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qt.prf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/resources.prf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/moc.prf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/unix/opengl.prf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/uic.prf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/dbuscommon.pri: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/dbusinterfaces.prf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/dbusadaptors.prf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/unix/thread.prf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/warn_on.prf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qmake_use.prf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/file_copies.prf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/testcase_targets.prf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/exceptions.prf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/yacc.prf: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/lex.prf: unit_test_libnm_icon_kylin.pro: qmake: FORCE @$(QMAKE) -o Makefile unit_test_libnm_icon_kylin.pro qmake_all: FORCE all: Makefile unit_test_libnm_icon_kylin dist: distdir FORCE (cd `dirname $(DISTDIR)` && $(TAR) $(DISTNAME).tar $(DISTNAME) && $(COMPRESS) $(DISTNAME).tar) && $(MOVE) `dirname $(DISTDIR)`/$(DISTNAME).tar.gz . && $(DEL_FILE) -r $(DISTDIR) distdir: FORCE @test -d $(DISTDIR) || mkdir -p $(DISTDIR) $(COPY_FILE) --parents $(DIST) $(DISTDIR)/ $(COPY_FILE) --parents /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/data/dummy.cpp $(DISTDIR)/ $(COPY_FILE) --parents ../../libnm-kylin/libnm-icon-kylin/kynetworkicon.h ../../plugins/component/DeviceFrame/deviceframe.h ../../plugins/component/Divider/divider.h $(DISTDIR)/ $(COPY_FILE) --parents ../../libnm-kylin/libnm-icon-kylin/kynetworkicon.cpp unit_test_libnm_icon_kylin.cpp ../../plugins/component/DeviceFrame/deviceframe.cpp unit_test_plugin_deviceframe.cpp ../../plugins/component/Divider/divider.cpp unit_test_plugin_divier.cpp main.cpp $(DISTDIR)/ clean: compiler_clean -$(DEL_FILE) $(OBJECTS) -$(DEL_FILE) *~ core *.core distclean: clean -$(DEL_FILE) $(TARGET) -$(DEL_FILE) Makefile ####### Sub-libraries mocclean: compiler_moc_header_clean compiler_moc_objc_header_clean compiler_moc_source_clean mocables: compiler_moc_header_make_all compiler_moc_objc_header_make_all compiler_moc_source_make_all check: first benchmark: first compiler_rcc_make_all: compiler_rcc_clean: compiler_moc_predefs_make_all: moc_predefs.h compiler_moc_predefs_clean: -$(DEL_FILE) moc_predefs.h moc_predefs.h: /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/data/dummy.cpp g++ -pipe --coverage -fno-inline -fno-access-control -fno-exceptions -O2 -std=gnu++1y -pthread -dM -E -o moc_predefs.h /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/data/dummy.cpp compiler_moc_header_make_all: moc_kynetworkicon.cpp compiler_moc_header_clean: -$(DEL_FILE) moc_kynetworkicon.cpp moc_kynetworkicon.cpp: ../../libnm-kylin/libnm-icon-kylin/kynetworkicon.h \ moc_predefs.h \ /usr/lib/qt5/bin/moc /usr/lib/qt5/bin/moc $(DEFINES) --include /data/data/kylinos-src/单元测试/dd/kylin-nm-plugin-openkylin-nile-tests/kylin-nm-plugin-openkylin-nile-tests/kylin-nm-plugin-openkylin-nile-tests/autotests/unit_test_libnm_icon_kylin/moc_predefs.h -I/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++ -I/data/data/kylinos-src/单元测试/dd/kylin-nm-plugin-openkylin-nile-tests/kylin-nm-plugin-openkylin-nile-tests/kylin-nm-plugin-openkylin-nile-tests/autotests/unit_test_libnm_icon_kylin -I/data/data/kylinos-src/单元测试/dd/kylin-nm-plugin-openkylin-nile-tests/kylin-nm-plugin-openkylin-nile-tests/kylin-nm-plugin-openkylin-nile-tests/autotests/kt-test-utils/cpp-stub -I/data/data/kylinos-src/单元测试/dd/kylin-nm-plugin-openkylin-nile-tests/kylin-nm-plugin-openkylin-nile-tests/kylin-nm-plugin-openkylin-nile-tests/autotests/kt-test-utils/cpp-stub-ext -I/usr/include/libnm -I/usr/include/libmount -I/usr/include/blkid -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/kylin-nm -I/usr/include/KF5/NetworkManagerQt -I/usr/include/x86_64-linux-gnu/qt5/QGSettings -I/usr/include/x86_64-linux-gnu/qt5 -I/usr/include/x86_64-linux-gnu/qt5/QtDBus -I/usr/include/x86_64-linux-gnu/qt5/QtNetwork -I/usr/include/x86_64-linux-gnu/qt5/QtSvg -I/usr/include/x86_64-linux-gnu/qt5/QtWidgets -I/usr/include/x86_64-linux-gnu/qt5/QtGui -I/usr/include/x86_64-linux-gnu/qt5/QtCore -I/usr/include/c++/12 -I/usr/include/x86_64-linux-gnu/c++/12 -I/usr/include/c++/12/backward -I/usr/lib/gcc/x86_64-linux-gnu/12/include -I/usr/local/include -I/usr/include/x86_64-linux-gnu -I/usr/include ../../libnm-kylin/libnm-icon-kylin/kynetworkicon.h -o moc_kynetworkicon.cpp compiler_moc_objc_header_make_all: compiler_moc_objc_header_clean: compiler_moc_source_make_all: compiler_moc_source_clean: compiler_uic_make_all: compiler_uic_clean: compiler_yacc_decl_make_all: compiler_yacc_decl_clean: compiler_yacc_impl_make_all: compiler_yacc_impl_clean: compiler_lex_make_all: compiler_lex_clean: compiler_clean: compiler_moc_predefs_clean compiler_moc_header_clean ####### Compile kynetworkicon.o: ../../libnm-kylin/libnm-icon-kylin/kynetworkicon.cpp ../../libnm-kylin/libnm-icon-kylin/kynetworkicon.h \ ../../libnm-kylin/libnm-icon-kylin/imageutil.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o kynetworkicon.o ../../libnm-kylin/libnm-icon-kylin/kynetworkicon.cpp unit_test_libnm_icon_kylin.o: unit_test_libnm_icon_kylin.cpp ../../libnm-kylin/libnm-icon-kylin/kynetworkicon.h \ ../kt-test-utils/cpp-stub-ext/stubext.h \ ../kt-test-utils/cpp-stub/stub.h \ ../kt-test-utils/cpp-stub-ext/stub-shadow.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o unit_test_libnm_icon_kylin.o unit_test_libnm_icon_kylin.cpp deviceframe.o: ../../plugins/component/DeviceFrame/deviceframe.cpp ../../plugins/component/DeviceFrame/deviceframe.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o deviceframe.o ../../plugins/component/DeviceFrame/deviceframe.cpp unit_test_plugin_deviceframe.o: unit_test_plugin_deviceframe.cpp ../../plugins/component/DeviceFrame/deviceframe.h \ ../kt-test-utils/cpp-stub-ext/stubext.h \ ../kt-test-utils/cpp-stub/stub.h \ ../kt-test-utils/cpp-stub-ext/stub-shadow.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o unit_test_plugin_deviceframe.o unit_test_plugin_deviceframe.cpp divider.o: ../../plugins/component/Divider/divider.cpp ../../plugins/component/Divider/divider.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o divider.o ../../plugins/component/Divider/divider.cpp unit_test_plugin_divier.o: unit_test_plugin_divier.cpp ../../plugins/component/Divider/divider.h \ ../kt-test-utils/cpp-stub-ext/stubext.h \ ../kt-test-utils/cpp-stub/stub.h \ ../kt-test-utils/cpp-stub-ext/stub-shadow.h $(CXX) -c $(CXXFLAGS) $(INCPATH) -o unit_test_plugin_divier.o unit_test_plugin_divier.cpp main.o: main.cpp $(CXX) -c $(CXXFLAGS) $(INCPATH) -o main.o main.cpp moc_kynetworkicon.o: moc_kynetworkicon.cpp $(CXX) -c $(CXXFLAGS) $(INCPATH) -o moc_kynetworkicon.o moc_kynetworkicon.cpp ####### Install install: FORCE uninstall: FORCE FORCE: kylin-nm-plugin/autotests/unit_test_libnm_icon_kylin/unit_test_plugin_netconnect.cpp0000664000175000017500000001141115160520531030516 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2024 KylinSoft 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 #include #include "../../plugins/netconnect/netconnect.h" #include "stubext.h" using namespace stub_ext; class NetConnectTest : public testing::Test { protected: static void SetUpTestSuite() { PluginType type = PluginType::SIMPLE; m_pNetConnectTest = new NetConnect(); } static void TearDownTestSuite() { if (m_pNetConnectTest) { delete m_pNetConnectTest; m_pNetConnectTest = nullptr; } } static NetConnect *m_pNetConnectTest; }; NetConnect *NetConnectTest::m_pNetConnectTest = nullptr; TEST_F(NetConnectTest, testAllFunc) { // QWidget *m_widget = m_pNetConnectTest->pluginUi(); PluginType mtype = PluginType::SIMPLE; m_pNetConnectTest->setPluginType(mtype, true); // // m_pNetConnectTest->setParentWidget(nullptr); // m_pNetConnectTest->setWidgetVisable(true); // m_pNetConnectTest->initUi(); // m_pNetConnectTest->initComponent(); // m_pNetConnectTest->initConnect(); // m_pNetConnectTest->runExternalApp(); // // 开关相关 // m_pNetConnectTest->setSwitchStatus(); // QVBoxLayout *m_vboxLayoutTest = new QVBoxLayout(); // m_pNetConnectTest->hideLayout(m_vboxLayoutTest); // m_pNetConnectTest->showLayout(m_vboxLayoutTest); // QString m_connName = "test"; // m_pNetConnectTest->getInsertPos(m_connName, m_vboxLayoutTest); // QString m_uuid = "9999-0000-0000-1111-2222"; // QString m_deviceName = "Lan0"; // m_pNetConnectTest->activeConnect(m_uuid, m_deviceName); // // m_pNetConnectTest->deActiveConnect(m_uuid); // // 获取设备列表 // QMap m_map; // m_pNetConnectTest->getDeviceStatusMap(m_map); // m_pNetConnectTest->initNet(); // m_pNetConnectTest->initNetListFromDevice(m_deviceName); // // 处理列表增加 // ItemFrame *m_itemFrame = new ItemFrame(m_deviceName); // // KyWiredItem m_kyWiredItem; // // m_pNetConnectTest->addLanItem(m_itemFrame, m_deviceName, m_kyWiredItem); // // 增加设备 // m_pNetConnectTest->addDeviceFrame(m_deviceName, true); // // 减少设备 // m_pNetConnectTest->removeDeviceFrame(m_deviceName); // // 增加一项 // QStringList m_infoList; // m_pNetConnectTest->addOneLanFrame(m_itemFrame, m_deviceName, m_infoList); // // 减少一项 // m_pNetConnectTest->removeOneLanFrame(m_itemFrame, m_deviceName, m_uuid); // // 单个lan连接状态变化 // LanItem *m_lanItem = new LanItem(true); // KyConnectState m_kyConnectState = KyConnectState::CONNECT_STATE_ACTIVATING; // m_pNetConnectTest->itemActiveConnectionStatusChanged(m_lanItem, m_kyConnectState); // // QObject *m_wObject = new QObject(); // // QEvent *m_event; // // bool status = m_pNetConnectTest->eventFilter(m_wObject, m_event); // // qDebug() << Q_FUNC_INFO << __LINE__ << status; // QString m_connectUuid; // QString m_connectName; // QString m_connectPath; // m_pNetConnectTest->updateLanInfo(m_deviceName, m_connectUuid, m_connectName, m_connectPath); // m_pNetConnectTest->onLanAdd(m_deviceName, m_connectUuid, m_connectName, m_connectPath); // QString m_dbusPath; // m_pNetConnectTest->onLanRemove(m_dbusPath); // m_pNetConnectTest->onActiveConnectionChanged(m_deviceName, m_uuid, m_kyConnectState); // // void onDeviceStatusChanged(); // m_pNetConnectTest->onDeviceNameChanged(m_deviceName, m_deviceName); // m_pNetConnectTest->onDeviceCarrierChange(m_deviceName, true); // m_pNetConnectTest->onDeviceManagedChange(m_deviceName, true); // m_pNetConnectTest->onWiredEnabledChanged(true); // m_pNetConnectTest->onDeviceAdd(m_deviceName); // m_pNetConnectTest->onDeviceRemove(m_deviceName); } kylin-nm-plugin/autotests/unit_test_libnm_icon_kylin/unit_test_plugin_itemframe.cpp0000664000175000017500000000272215160520531030334 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2024 KylinSoft 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 #include #include "../../plugins/netconnect/itemframe.h" #include "stubext.h" using namespace stub_ext; class ItemFrameTest : public testing::Test { protected: static void SetUpTestSuite() { m_pItemFrameTest = new ItemFrame("eth0"); } static void TearDownTestSuite() { if (m_pItemFrameTest) { delete m_pItemFrameTest; m_pItemFrameTest = nullptr; } } static ItemFrame *m_pItemFrameTest; }; ItemFrame *ItemFrameTest::m_pItemFrameTest = nullptr; TEST_F(ItemFrameTest, testAllFunc) { ASSERT_EQ(true, true); } kylin-nm-plugin/autotests/unit_test_libnm_icon_kylin/unit_test_libnm_icon_kylin.cpp0000664000175000017500000000703615160520531030327 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2024 KylinSoft 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 #include #include "../../libnm-kylin/libnm-icon-kylin/kynetworkicon.h" #include "stubext.h" using namespace stub_ext; class KyNetworkIconTest : public testing::Test { protected: static void SetUpTestSuite() { m_pKyNetworkIconTest = new KyNetworkIcon(); } static void TearDownTestSuite() { if (m_pKyNetworkIconTest) { delete m_pKyNetworkIconTest; m_pKyNetworkIconTest = nullptr; } } static KyNetworkIcon *m_pKyNetworkIconTest; }; KyNetworkIcon *KyNetworkIconTest::m_pKyNetworkIconTest = nullptr; TEST_F(KyNetworkIconTest, checkIconIsHidden) { // get current value bool currentValue = m_pKyNetworkIconTest->checkIconIsHidden(); // test the current value and the value you have set ASSERT_EQ(currentValue, false); } TEST_F(KyNetworkIconTest, testAllFunc) { m_pKyNetworkIconTest->initConnect(); m_pKyNetworkIconTest->startLoading(); m_pKyNetworkIconTest->stopLoading(); // onSetTrayIconLoading() m_pKyNetworkIconTest->currentIconIndex = 0; m_pKyNetworkIconTest->onSetTrayIconLoading(); m_pKyNetworkIconTest->currentIconIndex = 12; m_pKyNetworkIconTest->onSetTrayIconLoading(); // updateIcon(); if (nullptr != m_pKyNetworkIconTest->loadingTimer) { m_pKyNetworkIconTest->loadingTimer->start(); m_pKyNetworkIconTest->updateIcon(); } m_pKyNetworkIconTest->iconStatus = KyConnectStatus::NOT_CONNECTED; m_pKyNetworkIconTest->updateIcon(); m_pKyNetworkIconTest->iconStatus = KyConnectStatus::LAN_CONNECTED; m_pKyNetworkIconTest->updateIcon(); m_pKyNetworkIconTest->iconStatus = KyConnectStatus::WLAN_CONNECTED; m_pKyNetworkIconTest->updateIcon(); m_pKyNetworkIconTest->iconStatus = KyConnectStatus::LAN_CONNECTED_LIMITED; m_pKyNetworkIconTest->updateIcon(); m_pKyNetworkIconTest->iconStatus = KyConnectStatus::WLAN_CONNECTED_LIMITED; m_pKyNetworkIconTest->updateIcon(); // onWiredStateChange() m_pKyNetworkIconTest->onWiredStateChange( "en0", "ed773242-de2c-4903-889b-22a2f14723e0", KyConnectState::CONNECT_STATE_ACTIVATING); m_pKyNetworkIconTest->onWiredStateChange( "en0", "ed773242-de2c-4903-889b-22a2f14723e0", KyConnectState::CONNECT_STATE_ACTIVATED); // onWirelessStateChange m_pKyNetworkIconTest->onWirelessStateChange( "wlan0", "kylin-wifi", "ed773242-de2c-4903-889b-22a2f14723e0", KyConnectState::CONNECT_STATE_ACTIVATING); m_pKyNetworkIconTest->onWirelessStateChange( "wlan0", "kylin-wifi", "ed773242-de2c-4903-889b-22a2f14723e0", KyConnectState::CONNECT_STATE_ACTIVATED); // QPaintEvent *event; // m_pKyNetworkIconTest->paintEvent(event); } kylin-nm-plugin/autotests/autotests.pro0000664000175000017500000000065715160520531017350 0ustar fengfengTEMPLATE = subdirs SUBDIRS = unit_test_libnm_icon_kylin # 打桩工具 # Define paths TEST_UTILS_PATH = $$PWD/kt-test-utils # Header files (if needed) HEADERS += $$files($$TEST_UTILS_PATH/cpp-stub/*.h $$TEST_UTILS_PATH/cpp-stub/*.hpp) \ $$files($$TEST_UTILS_PATH/cpp-stub-ext/*.h) # Gather source files SOURCES += $$files($$TEST_UTILS_PATH/cpp-stub/*.cpp) \ $$files($$TEST_UTILS_PATH/cpp-stub-ext/*.cpp) kylin-nm-plugin/autotests/readme0000664000175000017500000000051215160520531015741 0ustar fengfeng##单元测试上传计算覆盖了命令 ##src/path 需要同步修改 sonar-scanner -Dsonar.projectKey=desktop_kylin-nm-plugin -Dsonar.sources=. -Dsonar.host.url=https://codescan.kylinos.cn -Dsonar.cfamily.gcov.reportsPath=src/path -Dsonar.token=sqp_d362c6e4c39633cf9f4bff4b996f8936cd0bc017 -Dsonar.branch.name=yhkylin/v11-2503 kylin-nm-plugin/autotests/kt-test-utils/0000775000175000017500000000000015160520531017314 5ustar fengfengkylin-nm-plugin/autotests/kt-test-utils/cpp-stub/0000775000175000017500000000000015167660365021072 5ustar fengfengkylin-nm-plugin/autotests/kt-test-utils/cpp-stub/addr_pri.h0000664000175000017500000002653615167660365023043 0ustar fengfeng/* * MIT License * * Copyright (c) 2019 coolxv * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef __ADDR_PRI_H__ #define __ADDR_PRI_H__ #include #include //base on C++11 /********************************************************** access private function **********************************************************/ namespace std { template using enable_if_t = typename enable_if::type; template using remove_reference_t = typename remove_reference::type; } // std // Unnamed namespace is used to avoid duplicate symbols if the macros are used namespace { namespace private_access_detail { // @tparam TagType, used to declare different "get" funciton overloads for // different members/statics template struct private_access { // Normal lookup cannot find in-class defined (inline) friend functions. friend PtrType get(TagType) { return PtrValue; } }; } // namespace private_access_detail } // namespace // Used macro naming conventions: // The "namespace" of this macro library is PRIVATE_ACCESS, i.e. all // macro here has this prefix. // All implementation macro, which are not meant to be used directly have the // PRIVATE_ACCESS_DETAIL prefix. // Some macros have the ABCD_IMPL form, which means they contain the // implementation details for the specific ABCD macro. #define PRIVATE_ACCESS_DETAIL_CONCATENATE_IMPL(x, y) x##y #define PRIVATE_ACCESS_DETAIL_CONCATENATE(x, y) \ PRIVATE_ACCESS_DETAIL_CONCATENATE_IMPL(x, y) // @param PtrTypeKind E.g if we have "class A", then it can be "A::*" in case of // members, or it can be "*" in case of statics. #define PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE(Tag, Class, Type, Name, \ PtrTypeKind) \ namespace { \ namespace private_access_detail { \ /* Tag type, used to declare different get funcitons for different \ * members \ */ \ struct Tag {}; \ /* Explicit instantiation */ \ template struct private_access; \ /* We can build the PtrType only with two aliases */ \ /* E.g. using PtrType = int(int) *; would be illformed */ \ using PRIVATE_ACCESS_DETAIL_CONCATENATE(Alias_, Tag) = Type; \ using PRIVATE_ACCESS_DETAIL_CONCATENATE(PtrType_, Tag) = \ PRIVATE_ACCESS_DETAIL_CONCATENATE(Alias_, Tag) PtrTypeKind; \ /* Declare the friend function, now it is visible in namespace scope. \ * Note, \ * we could declare it inside the Tag type too, in that case ADL would \ * find \ * the declaration. By choosing to declare it here, the Tag type remains \ * a \ * simple tag type, it has no other responsibilities. */ \ PRIVATE_ACCESS_DETAIL_CONCATENATE(PtrType_, Tag) get(Tag); \ } \ } #define PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE_FIELD(Tag, Class, Type, Name) \ PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE(Tag, Class, Type, Name, Class::*) \ namespace { \ namespace access_private_field { \ Type &Class##Name(Class &&t) { return t.*get(private_access_detail::Tag{}); } \ Type &Class##Name(Class &t) { return t.*get(private_access_detail::Tag{}); } \ /* The following usings are here to avoid duplicate const qualifier \ * warnings \ */ \ using PRIVATE_ACCESS_DETAIL_CONCATENATE(X, Tag) = Type; \ using PRIVATE_ACCESS_DETAIL_CONCATENATE(Y, Tag) = \ const PRIVATE_ACCESS_DETAIL_CONCATENATE(X, Tag); \ PRIVATE_ACCESS_DETAIL_CONCATENATE(Y, Tag) & Class##Name(const Class &t) {\ return t.*get(private_access_detail::Tag{}); \ } \ } \ } #define PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE_FUN(Tag, Class, Type, Name) \ PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE(Tag, Class, Type, Name, Class::*) \ namespace { \ namespace call_private_fun { \ /* We do perfect forwarding, but we want to restrict the overload set \ * only for objects which have the type Class. */ \ template , \ Class>::value> * = nullptr, \ typename... Args> \ auto Class##Name(Obj &&o, Args &&... args) -> decltype( \ (std::forward(o).* \ get(private_access_detail::Tag{}))(std::forward(args)...)) { \ return (std::forward(o).*get(private_access_detail::Tag{}))( \ std::forward(args)...); \ } \ } \ namespace get_private_fun { \ auto Class##Name() -> decltype( \ get(private_access_detail::Tag{})) { \ return (get(private_access_detail::Tag{})); \ } \ } \ } #define PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE_STATIC_FIELD(Tag, Class, Type, \ Name) \ PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE(Tag, Class, Type, Name, *) \ namespace { \ namespace access_private_static_field { \ namespace Class { \ Type &Class##Name() { return *get(private_access_detail::Tag{}); } \ } \ } \ } #define PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE_STATIC_FUN(Tag, Class, Type, \ Name) \ PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE(Tag, Class, Type, Name, *) \ namespace { \ namespace call_private_static_fun { \ namespace Class { \ template \ auto Class##Name(Args &&... args) -> decltype( \ get(private_access_detail::Tag{})(std::forward(args)...)) { \ return get(private_access_detail::Tag{})( \ std::forward(args)...); \ } \ } \ } \ namespace get_private_static_fun { \ namespace Class { \ auto Class##Name() -> decltype(get(private_access_detail::Tag{})) { \ return get(private_access_detail::Tag{}); \ } \ } \ } \ } #define PRIVATE_ACCESS_DETAIL_UNIQUE_TAG \ PRIVATE_ACCESS_DETAIL_CONCATENATE(PrivateAccessTag, __COUNTER__) #define ACCESS_PRIVATE_FIELD(Class, Type, Name) \ PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE_FIELD(PRIVATE_ACCESS_DETAIL_UNIQUE_TAG, \ Class, Type, Name) #define ACCESS_PRIVATE_FUN(Class, Type, Name) \ PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE_FUN(PRIVATE_ACCESS_DETAIL_UNIQUE_TAG, \ Class, Type, Name) #define ACCESS_PRIVATE_STATIC_FIELD(Class, Type, Name) \ Type Class::Name; \ PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE_STATIC_FIELD( \ PRIVATE_ACCESS_DETAIL_UNIQUE_TAG, Class, Type, Name) #define ACCESS_PRIVATE_STATIC_FUN(Class, Type, Name) \ PRIVATE_ACCESS_DETAIL_ACCESS_PRIVATE_STATIC_FUN( \ PRIVATE_ACCESS_DETAIL_UNIQUE_TAG, Class, Type, Name) #endif kylin-nm-plugin/autotests/kt-test-utils/cpp-stub/addr_any.h0000664000175000017500000002330615167660365023030 0ustar fengfeng/* * MIT License * * Copyright (c) 2019 coolxv * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef __ADDR_ANY_H__ #define __ADDR_ANY_H__ //linux #include #include //c #include #include #include //c++ #include #include //project #include "elfio.hpp" class AddrAny { public: AddrAny() { m_init = get_exe_pathname(m_fullname); m_baseaddr = 0; } AddrAny(std::string libname) { m_init = get_lib_pathname_and_baseaddr(libname, m_fullname, m_baseaddr); } int get_local_func_addr_symtab(std::string func_name_regex_str, std::map& result) { return get_func_addr(SHT_SYMTAB, STB_LOCAL, func_name_regex_str, result); } int get_global_func_addr_symtab(std::string func_name_regex_str, std::map& result) { return get_func_addr(SHT_SYMTAB, STB_GLOBAL, func_name_regex_str, result); } int get_weak_func_addr_symtab(std::string func_name_regex_str, std::map& result) { return get_func_addr(SHT_SYMTAB, STB_WEAK, func_name_regex_str, result); } int get_global_func_addr_dynsym( std::string func_name_regex_str, std::map& result) { return get_func_addr(SHT_DYNSYM, STB_GLOBAL, func_name_regex_str, result); } int get_weak_func_addr_dynsym(std::string func_name_regex_str, std::map& result) { return get_func_addr(SHT_DYNSYM, STB_WEAK, func_name_regex_str, result); } private: bool demangle(std::string& s, std::string& name) { int status; char* pname = abi::__cxa_demangle(s.c_str(), 0, 0, &status); if (status != 0) { switch(status) { case -1: name = "memory allocation error"; break; case -2: name = "invalid name given"; break; case -3: name = "internal error: __cxa_demangle: invalid argument"; break; default: name = "unknown error occured"; break; } return false; } name = pname; free(pname); return true; } bool get_exe_pathname( std::string& name) { char line[512]; FILE *fp; uintptr_t base_addr; char perm[5]; unsigned long offset; int pathname_pos; char *pathname; size_t pathname_len; int match = 0; if(NULL == (fp = fopen("/proc/self/maps", "r"))) { return false; } while(fgets(line, sizeof(line), fp)) { if(sscanf(line, "%" PRIxPTR "-%*lx %4s %lx %*x:%*x %*d%n", &base_addr, perm, &offset, &pathname_pos) != 3) continue; if(0 != offset) continue; //get pathname while(isspace(line[pathname_pos]) && pathname_pos < (int)(sizeof(line) - 1)) pathname_pos += 1; if(pathname_pos >= (int)(sizeof(line) - 1)) continue; pathname = line + pathname_pos; pathname_len = strlen(pathname); if(0 == pathname_len) continue; if(pathname[pathname_len - 1] == '\n') { pathname[pathname_len - 1] = '\0'; pathname_len -= 1; } if(0 == pathname_len) continue; if('[' == pathname[0]) continue; name = pathname; match = 1; break; } fclose(fp); if(0 == match) { return false; } else { return true; } } bool get_lib_pathname_and_baseaddr(std::string pathname_regex_str, std::string& name, unsigned long& addr) { char line[512]; FILE *fp; uintptr_t base_addr; char perm[5]; unsigned long offset; int pathname_pos; char *pathname; size_t pathname_len; int match; regex_t pathname_regex; regcomp(&pathname_regex, pathname_regex_str.c_str(), 0); if(NULL == (fp = fopen("/proc/self/maps", "r"))) { return false; } while(fgets(line, sizeof(line), fp)) { if(sscanf(line, "%" PRIxPTR "-%*lx %4s %lx %*x:%*x %*d%n", &base_addr, perm, &offset, &pathname_pos) != 3) continue; //check permission if(perm[0] != 'r') continue; if(perm[3] != 'p') continue; //do not touch the shared memory //check offset // //We are trying to find ELF header in memory. //It can only be found at the beginning of a mapped memory regions //whose offset is 0. if(0 != offset) continue; //get pathname while(isspace(line[pathname_pos]) && pathname_pos < (int)(sizeof(line) - 1)) pathname_pos += 1; if(pathname_pos >= (int)(sizeof(line) - 1)) continue; pathname = line + pathname_pos; pathname_len = strlen(pathname); if(0 == pathname_len) continue; if(pathname[pathname_len - 1] == '\n') { pathname[pathname_len - 1] = '\0'; pathname_len -= 1; } if(0 == pathname_len) continue; if('[' == pathname[0]) continue; //check pathname //if we need to hook this elf? match = 0; if(0 == regexec(&pathname_regex, pathname, 0, NULL, 0)) { match = 1; name = pathname; addr = (unsigned long)base_addr; break; } if(0 == match) continue; } fclose(fp); if(0 == match) { return false; } else { return true; } } int get_func_addr(unsigned int ttype, unsigned int stype, std::string& func_name_regex_str, std::map& result) { // Create an elfio reader ELFIO::elfio reader; int count = 0; regex_t pathname_regex; if(!m_init) { return -1; } regcomp(&pathname_regex, func_name_regex_str.c_str(), 0); // Load ELF data if(!reader.load(m_fullname.c_str())) { return -1; } ELFIO::Elf_Half sec_num = reader.sections.size(); for(int i = 0; i < sec_num; ++i) { ELFIO::section* psec = reader.sections[i]; // Check section type if(psec->get_type() == ttype) { const ELFIO::symbol_section_accessor symbols( reader, psec ); for ( unsigned int j = 0; j < symbols.get_symbols_num(); ++j ) { std::string name; std::string name_mangle; ELFIO::Elf64_Addr value; ELFIO::Elf_Xword size; unsigned char bind; unsigned char type; ELFIO::Elf_Half section_index; unsigned char other; // Read symbol properties symbols.get_symbol( j, name, value, size, bind, type, section_index, other ); if(type == STT_FUNC && bind == stype) { bool ret = demangle(name,name_mangle); if(ret == true) { if (0 == regexec(&pathname_regex, name_mangle.c_str(), 0, NULL, 0)) { result.insert ( std::pair(name_mangle,(void*)(value + m_baseaddr))); count++; } } else { if (0 == regexec(&pathname_regex, name.c_str(), 0, NULL, 0)) { result.insert ( std::pair(name,(void*)(value + m_baseaddr))); count++; } } } } break; } } return count; } private: bool m_init; std::string m_name; std::string m_fullname; unsigned long m_baseaddr; }; #endif kylin-nm-plugin/autotests/kt-test-utils/cpp-stub/elfio.hpp0000664000175000017500000045517715167660365022724 0ustar fengfeng/* Copyright (C) 2001-present by Serge Lamikhov-Center Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*** Start of inlined file: elfio_dump.hpp ***/ #ifndef ELFIO_DUMP_HPP #define ELFIO_DUMP_HPP #include #include #include #include #include /*** Start of inlined file: elfio.hpp ***/ #ifndef ELFIO_HPP #define ELFIO_HPP #ifdef _MSC_VER #pragma warning( push ) #pragma warning( disable : 4996 ) #pragma warning( disable : 4355 ) #pragma warning( disable : 4244 ) #endif #include #include #include #include #include #include #include #include /*** Start of inlined file: elf_types.hpp ***/ #ifndef ELFTYPES_H #define ELFTYPES_H #ifndef ELFIO_NO_OWN_TYPES #if !defined( ELFIO_NO_CSTDINT ) && !defined( ELFIO_NO_INTTYPES ) #include #else typedef unsigned char uint8_t; typedef signed char int8_t; typedef unsigned short uint16_t; typedef signed short int16_t; #ifdef _MSC_VER typedef unsigned __int32 uint32_t; typedef signed __int32 int32_t; typedef unsigned __int64 uint64_t; typedef signed __int64 int64_t; #else typedef unsigned int uint32_t; typedef signed int int32_t; typedef unsigned long long uint64_t; typedef signed long long int64_t; #endif // _MSC_VER #endif // ELFIO_NO_CSTDINT #endif // ELFIO_NO_OWN_TYPES namespace ELFIO { // Attention! Platform depended definitions. typedef uint16_t Elf_Half; typedef uint32_t Elf_Word; typedef int32_t Elf_Sword; typedef uint64_t Elf_Xword; typedef int64_t Elf_Sxword; typedef uint32_t Elf32_Addr; typedef uint32_t Elf32_Off; typedef uint64_t Elf64_Addr; typedef uint64_t Elf64_Off; #define Elf32_Half Elf_Half #define Elf64_Half Elf_Half #define Elf32_Word Elf_Word #define Elf64_Word Elf_Word #define Elf32_Sword Elf_Sword #define Elf64_Sword Elf_Sword /////////////////////// // ELF Header Constants // File type #define ET_NONE 0 #define ET_REL 1 #define ET_EXEC 2 #define ET_DYN 3 #define ET_CORE 4 #define ET_LOOS 0xFE00 #define ET_HIOS 0xFEFF #define ET_LOPROC 0xFF00 #define ET_HIPROC 0xFFFF #define EM_NONE 0 // No machine #define EM_M32 1 // AT&T WE 32100 #define EM_SPARC 2 // SUN SPARC #define EM_386 3 // Intel 80386 #define EM_68K 4 // Motorola m68k family #define EM_88K 5 // Motorola m88k family #define EM_486 6 // Intel 80486// Reserved for future use #define EM_860 7 // Intel 80860 #define EM_MIPS 8 // MIPS R3000 (officially, big-endian only) #define EM_S370 9 // IBM System/370 #define EM_MIPS_RS3_LE \ 10 // MIPS R3000 little-endian (Oct 4 1999 Draft) Deprecated #define EM_res011 11 // Reserved #define EM_res012 12 // Reserved #define EM_res013 13 // Reserved #define EM_res014 14 // Reserved #define EM_PARISC 15 // HPPA #define EM_res016 16 // Reserved #define EM_VPP550 17 // Fujitsu VPP500 #define EM_SPARC32PLUS 18 // Sun's "v8plus" #define EM_960 19 // Intel 80960 #define EM_PPC 20 // PowerPC #define EM_PPC64 21 // 64-bit PowerPC #define EM_S390 22 // IBM S/390 #define EM_SPU 23 // Sony/Toshiba/IBM SPU #define EM_res024 24 // Reserved #define EM_res025 25 // Reserved #define EM_res026 26 // Reserved #define EM_res027 27 // Reserved #define EM_res028 28 // Reserved #define EM_res029 29 // Reserved #define EM_res030 30 // Reserved #define EM_res031 31 // Reserved #define EM_res032 32 // Reserved #define EM_res033 33 // Reserved #define EM_res034 34 // Reserved #define EM_res035 35 // Reserved #define EM_V800 36 // NEC V800 series #define EM_FR20 37 // Fujitsu FR20 #define EM_RH32 38 // TRW RH32 #define EM_MCORE 39 // Motorola M*Core // May also be taken by Fujitsu MMA #define EM_RCE 39 // Old name for MCore #define EM_ARM 40 // ARM #define EM_OLD_ALPHA 41 // Digital Alpha #define EM_SH 42 // Renesas (formerly Hitachi) / SuperH SH #define EM_SPARCV9 43 // SPARC v9 64-bit #define EM_TRICORE 44 // Siemens Tricore embedded processor #define EM_ARC 45 // ARC Cores #define EM_H8_300 46 // Renesas (formerly Hitachi) H8/300 #define EM_H8_300H 47 // Renesas (formerly Hitachi) H8/300H #define EM_H8S 48 // Renesas (formerly Hitachi) H8S #define EM_H8_500 49 // Renesas (formerly Hitachi) H8/500 #define EM_IA_64 50 // Intel IA-64 Processor #define EM_MIPS_X 51 // Stanford MIPS-X #define EM_COLDFIRE 52 // Motorola Coldfire #define EM_68HC12 53 // Motorola M68HC12 #define EM_MMA 54 // Fujitsu Multimedia Accelerator #define EM_PCP 55 // Siemens PCP #define EM_NCPU 56 // Sony nCPU embedded RISC processor #define EM_NDR1 57 // Denso NDR1 microprocesspr #define EM_STARCORE 58 // Motorola Star*Core processor #define EM_ME16 59 // Toyota ME16 processor #define EM_ST100 60 // STMicroelectronics ST100 processor #define EM_TINYJ 61 // Advanced Logic Corp. TinyJ embedded processor #define EM_X86_64 62 // Advanced Micro Devices X86-64 processor #define EM_PDSP 63 // Sony DSP Processor #define EM_PDP10 64 // Digital Equipment Corp. PDP-10 #define EM_PDP11 65 // Digital Equipment Corp. PDP-11 #define EM_FX66 66 // Siemens FX66 microcontroller #define EM_ST9PLUS 67 // STMicroelectronics ST9+ 8/16 bit microcontroller #define EM_ST7 68 // STMicroelectronics ST7 8-bit microcontroller #define EM_68HC16 69 // Motorola MC68HC16 Microcontroller #define EM_68HC11 70 // Motorola MC68HC11 Microcontroller #define EM_68HC08 71 // Motorola MC68HC08 Microcontroller #define EM_68HC05 72 // Motorola MC68HC05 Microcontroller #define EM_SVX 73 // Silicon Graphics SVx #define EM_ST19 74 // STMicroelectronics ST19 8-bit cpu #define EM_VAX 75 // Digital VAX #define EM_CRIS 76 // Axis Communications 32-bit embedded processor #define EM_JAVELIN 77 // Infineon Technologies 32-bit embedded cpu #define EM_FIREPATH 78 // Element 14 64-bit DSP processor #define EM_ZSP 79 // LSI Logic's 16-bit DSP processor #define EM_MMIX 80 // Donald Knuth's educational 64-bit processor #define EM_HUANY 81 // Harvard's machine-independent format #define EM_PRISM 82 // SiTera Prism #define EM_AVR 83 // Atmel AVR 8-bit microcontroller #define EM_FR30 84 // Fujitsu FR30 #define EM_D10V 85 // Mitsubishi D10V #define EM_D30V 86 // Mitsubishi D30V #define EM_V850 87 // NEC v850 #define EM_M32R 88 // Renesas M32R (formerly Mitsubishi M32R) #define EM_MN10300 89 // Matsushita MN10300 #define EM_MN10200 90 // Matsushita MN10200 #define EM_PJ 91 // picoJava #define EM_OPENRISC 92 // OpenRISC 32-bit embedded processor #define EM_ARC_A5 93 // ARC Cores Tangent-A5 #define EM_XTENSA 94 // Tensilica Xtensa Architecture #define EM_VIDEOCORE 95 // Alphamosaic VideoCore processor #define EM_TMM_GPP 96 // Thompson Multimedia General Purpose Processor #define EM_NS32K 97 // National Semiconductor 32000 series #define EM_TPC 98 // Tenor Network TPC processor #define EM_SNP1K 99 // Trebia SNP 1000 processor #define EM_ST200 100 // STMicroelectronics ST200 microcontroller #define EM_IP2K 101 // Ubicom IP2022 micro controller #define EM_MAX 102 // MAX Processor #define EM_CR 103 // National Semiconductor CompactRISC #define EM_F2MC16 104 // Fujitsu F2MC16 #define EM_MSP430 105 // TI msp430 micro controller #define EM_BLACKFIN 106 // ADI Blackfin #define EM_SE_C33 107 // S1C33 Family of Seiko Epson processors #define EM_SEP 108 // Sharp embedded microprocessor #define EM_ARCA 109 // Arca RISC Microprocessor #define EM_UNICORE \ 110 // Microprocessor series from PKU-Unity Ltd. and MPRC of Peking University #define EM_EXCESS 111 // eXcess: 16/32/64-bit configurable embedded CPU #define EM_DXP 112 // Icera Semiconductor Inc. Deep Execution Processor #define EM_ALTERA_NIOS2 113 // Altera Nios II soft-core processor #define EM_CRX 114 // National Semiconductor CRX #define EM_XGATE 115 // Motorola XGATE embedded processor #define EM_C166 116 // Infineon C16x/XC16x processor #define EM_M16C 117 // Renesas M16C series microprocessors #define EM_DSPIC30F \ 118 // Microchip Technology dsPIC30F Digital Signal Controller #define EM_CE 119 // Freescale Communication Engine RISC core #define EM_M32C 120 // Renesas M32C series microprocessors #define EM_res121 121 // Reserved #define EM_res122 122 // Reserved #define EM_res123 123 // Reserved #define EM_res124 124 // Reserved #define EM_res125 125 // Reserved #define EM_res126 126 // Reserved #define EM_res127 127 // Reserved #define EM_res128 128 // Reserved #define EM_res129 129 // Reserved #define EM_res130 130 // Reserved #define EM_TSK3000 131 // Altium TSK3000 core #define EM_RS08 132 // Freescale RS08 embedded processor #define EM_res133 133 // Reserved #define EM_ECOG2 134 // Cyan Technology eCOG2 microprocessor #define EM_SCORE 135 // Sunplus Score #define EM_SCORE7 135 // Sunplus S+core7 RISC processor #define EM_DSP24 136 // New Japan Radio (NJR) 24-bit DSP Processor #define EM_VIDEOCORE3 137 // Broadcom VideoCore III processor #define EM_LATTICEMICO32 138 // RISC processor for Lattice FPGA architecture #define EM_SE_C17 139 // Seiko Epson C17 family #define EM_TI_C6000 140 // Texas Instruments TMS320C6000 DSP family #define EM_TI_C2000 141 // Texas Instruments TMS320C2000 DSP family #define EM_TI_C5500 142 // Texas Instruments TMS320C55x DSP family #define EM_res143 143 // Reserved #define EM_res144 144 // Reserved #define EM_res145 145 // Reserved #define EM_res146 146 // Reserved #define EM_res147 147 // Reserved #define EM_res148 148 // Reserved #define EM_res149 149 // Reserved #define EM_res150 150 // Reserved #define EM_res151 151 // Reserved #define EM_res152 152 // Reserved #define EM_res153 153 // Reserved #define EM_res154 154 // Reserved #define EM_res155 155 // Reserved #define EM_res156 156 // Reserved #define EM_res157 157 // Reserved #define EM_res158 158 // Reserved #define EM_res159 159 // Reserved #define EM_MMDSP_PLUS 160 // STMicroelectronics 64bit VLIW Data Signal Processor #define EM_CYPRESS_M8C 161 // Cypress M8C microprocessor #define EM_R32C 162 // Renesas R32C series microprocessors #define EM_TRIMEDIA 163 // NXP Semiconductors TriMedia architecture family #define EM_QDSP6 164 // QUALCOMM DSP6 Processor #define EM_8051 165 // Intel 8051 and variants #define EM_STXP7X 166 // STMicroelectronics STxP7x family #define EM_NDS32 \ 167 // Andes Technology compact code size embedded RISC processor family #define EM_ECOG1 168 // Cyan Technology eCOG1X family #define EM_ECOG1X 168 // Cyan Technology eCOG1X family #define EM_MAXQ30 169 // Dallas Semiconductor MAXQ30 Core Micro-controllers #define EM_XIMO16 170 // New Japan Radio (NJR) 16-bit DSP Processor #define EM_MANIK 171 // M2000 Reconfigurable RISC Microprocessor #define EM_CRAYNV2 172 // Cray Inc. NV2 vector architecture #define EM_RX 173 // Renesas RX family #define EM_METAG 174 // Imagination Technologies META processor architecture #define EM_MCST_ELBRUS 175 // MCST Elbrus general purpose hardware architecture #define EM_ECOG16 176 // Cyan Technology eCOG16 family #define EM_CR16 177 // National Semiconductor CompactRISC 16-bit processor #define EM_ETPU 178 // Freescale Extended Time Processing Unit #define EM_SLE9X 179 // Infineon Technologies SLE9X core #define EM_L1OM 180 // Intel L1OM #define EM_INTEL181 181 // Reserved by Intel #define EM_INTEL182 182 // Reserved by Intel #define EM_res183 183 // Reserved by ARM #define EM_res184 184 // Reserved by ARM #define EM_AVR32 185 // Atmel Corporation 32-bit microprocessor family #define EM_STM8 186 // STMicroeletronics STM8 8-bit microcontroller #define EM_TILE64 187 // Tilera TILE64 multicore architecture family #define EM_TILEPRO 188 // Tilera TILEPro multicore architecture family #define EM_MICROBLAZE 189 // Xilinx MicroBlaze 32-bit RISC soft processor core #define EM_CUDA 190 // NVIDIA CUDA architecture #define EM_TILEGX 191 // Tilera TILE-Gx multicore architecture family #define EM_CLOUDSHIELD 192 // CloudShield architecture family #define EM_COREA_1ST 193 // KIPO-KAIST Core-A 1st generation processor family #define EM_COREA_2ND 194 // KIPO-KAIST Core-A 2nd generation processor family #define EM_ARC_COMPACT2 195 // Synopsys ARCompact V2 #define EM_OPEN8 196 // Open8 8-bit RISC soft processor core #define EM_RL78 197 // Renesas RL78 family #define EM_VIDEOCORE5 198 // Broadcom VideoCore V processor #define EM_78KOR 199 // Renesas 78KOR family #define EM_56800EX 200 // Freescale 56800EX Digital Signal Controller (DSC) #define EM_BA1 201 // Beyond BA1 CPU architecture #define EM_BA2 202 // Beyond BA2 CPU architecture #define EM_XCORE 203 // XMOS xCORE processor family #define EM_MCHP_PIC 204 // Microchip 8-bit PIC(r) family #define EM_INTEL205 205 // Reserved by Intel #define EM_INTEL206 206 // Reserved by Intel #define EM_INTEL207 207 // Reserved by Intel #define EM_INTEL208 208 // Reserved by Intel #define EM_INTEL209 209 // Reserved by Intel #define EM_KM32 210 // KM211 KM32 32-bit processor #define EM_KMX32 211 // KM211 KMX32 32-bit processor #define EM_KMX16 212 // KM211 KMX16 16-bit processor #define EM_KMX8 213 // KM211 KMX8 8-bit processor #define EM_KVARC 214 // KM211 KVARC processor #define EM_CDP 215 // Paneve CDP architecture family #define EM_COGE 216 // Cognitive Smart Memory Processor #define EM_COOL 217 // iCelero CoolEngine #define EM_NORC 218 // Nanoradio Optimized RISC #define EM_CSR_KALIMBA 219 // CSR Kalimba architecture family #define EM_Z80 220 // Zilog Z80 #define EM_VISIUM 221 // Controls and Data Services VISIUMcore processor #define EM_FT32 222 // FTDI Chip FT32 high performance 32-bit RISC architecture #define EM_MOXIE 223 // Moxie processor family #define EM_AMDGPU 224 // AMD GPU architecture #define EM_RISCV 243 // RISC-V #define EM_LANAI 244 // Lanai processor #define EM_CEVA 245 // CEVA Processor Architecture Family #define EM_CEVA_X2 246 // CEVA X2 Processor Family #define EM_BPF 247 // Linux BPF – in-kernel virtual machine #define EM_GRAPHCORE_IPU 248 // Graphcore Intelligent Processing Unit #define EM_IMG1 249 // Imagination Technologies #define EM_NFP 250 // Netronome Flow Processor (P) #define EM_CSKY 252 // C-SKY processor family // File version #define EV_NONE 0 #define EV_CURRENT 1 // Identification index #define EI_MAG0 0 #define EI_MAG1 1 #define EI_MAG2 2 #define EI_MAG3 3 #define EI_CLASS 4 #define EI_DATA 5 #define EI_VERSION 6 #define EI_OSABI 7 #define EI_ABIVERSION 8 #define EI_PAD 9 #define EI_NIDENT 16 // Magic number #define ELFMAG0 0x7F #define ELFMAG1 'E' #define ELFMAG2 'L' #define ELFMAG3 'F' // File class #define ELFCLASSNONE 0 #define ELFCLASS32 1 #define ELFCLASS64 2 // Encoding #define ELFDATANONE 0 #define ELFDATA2LSB 1 #define ELFDATA2MSB 2 // OS extensions #define ELFOSABI_NONE 0 // No extensions or unspecified #define ELFOSABI_HPUX 1 // Hewlett-Packard HP-UX #define ELFOSABI_NETBSD 2 // NetBSD #define ELFOSABI_LINUX 3 // Linux #define ELFOSABI_SOLARIS 6 // Sun Solaris #define ELFOSABI_AIX 7 // AIX #define ELFOSABI_IRIX 8 // IRIX #define ELFOSABI_FREEBSD 9 // FreeBSD #define ELFOSABI_TRU64 10 // Compaq TRU64 UNIX #define ELFOSABI_MODESTO 11 // Novell Modesto #define ELFOSABI_OPENBSD 12 // Open BSD #define ELFOSABI_OPENVMS 13 // Open VMS #define ELFOSABI_NSK 14 // Hewlett-Packard Non-Stop Kernel #define ELFOSABI_AROS 15 // Amiga Research OS #define ELFOSABI_FENIXOS 16 // The FenixOS highly scalable multi-core OS // 64-255 Architecture-specific value range #define ELFOSABI_AMDGPU_HSA \ 64 // AMDGPU OS for HSA compatible compute // kernels. #define ELFOSABI_AMDGPU_PAL \ 65 // AMDGPU OS for AMD PAL compatible graphics // shaders and compute kernels. #define ELFOSABI_AMDGPU_MESA3D \ 66 // AMDGPU OS for Mesa3D compatible graphics // shaders and compute kernels. // AMDGPU specific e_flags #define EF_AMDGPU_MACH 0x0ff // AMDGPU processor selection mask. #define EF_AMDGPU_XNACK \ 0x100 // Indicates if the XNACK target feature is // enabled for all code contained in the ELF. // AMDGPU processors #define EF_AMDGPU_MACH_NONE 0x000 // Unspecified processor. #define EF_AMDGPU_MACH_R600_R600 0x001 #define EF_AMDGPU_MACH_R600_R630 0x002 #define EF_AMDGPU_MACH_R600_RS880 0x003 #define EF_AMDGPU_MACH_R600_RV670 0x004 #define EF_AMDGPU_MACH_R600_RV710 0x005 #define EF_AMDGPU_MACH_R600_RV730 0x006 #define EF_AMDGPU_MACH_R600_RV770 0x007 #define EF_AMDGPU_MACH_R600_CEDAR 0x008 #define EF_AMDGPU_MACH_R600_CYPRESS 0x009 #define EF_AMDGPU_MACH_R600_JUNIPER 0x00a #define EF_AMDGPU_MACH_R600_REDWOOD 0x00b #define EF_AMDGPU_MACH_R600_SUMO 0x00c #define EF_AMDGPU_MACH_R600_BARTS 0x00d #define EF_AMDGPU_MACH_R600_CAICOS 0x00e #define EF_AMDGPU_MACH_R600_CAYMAN 0x00f #define EF_AMDGPU_MACH_R600_TURKS 0x010 #define EF_AMDGPU_MACH_R600_RESERVED_FIRST 0x011 #define EF_AMDGPU_MACH_R600_RESERVED_LAST 0x01f #define EF_AMDGPU_MACH_R600_FIRST EF_AMDGPU_MACH_R600_R600 #define EF_AMDGPU_MACH_R600_LAST EF_AMDGPU_MACH_R600_TURKS #define EF_AMDGPU_MACH_AMDGCN_GFX600 0x020 #define EF_AMDGPU_MACH_AMDGCN_GFX601 0x021 #define EF_AMDGPU_MACH_AMDGCN_GFX700 0x022 #define EF_AMDGPU_MACH_AMDGCN_GFX701 0x023 #define EF_AMDGPU_MACH_AMDGCN_GFX702 0x024 #define EF_AMDGPU_MACH_AMDGCN_GFX703 0x025 #define EF_AMDGPU_MACH_AMDGCN_GFX704 0x026 #define EF_AMDGPU_MACH_AMDGCN_GFX801 0x028 #define EF_AMDGPU_MACH_AMDGCN_GFX802 0x029 #define EF_AMDGPU_MACH_AMDGCN_GFX803 0x02a #define EF_AMDGPU_MACH_AMDGCN_GFX810 0x02b #define EF_AMDGPU_MACH_AMDGCN_GFX900 0x02c #define EF_AMDGPU_MACH_AMDGCN_GFX902 0x02d #define EF_AMDGPU_MACH_AMDGCN_GFX904 0x02e #define EF_AMDGPU_MACH_AMDGCN_GFX906 0x02f #define EF_AMDGPU_MACH_AMDGCN_RESERVED0 0x027 #define EF_AMDGPU_MACH_AMDGCN_RESERVED1 0x030 #define EF_AMDGPU_MACH_AMDGCN_FIRST EF_AMDGPU_MACH_AMDGCN_GFX600 #define EF_AMDGPU_MACH_AMDGCN_LAST EF_AMDGPU_MACH_AMDGCN_GFX906 ///////////////////// // Sections constants // Section indexes #define SHN_UNDEF 0 #define SHN_LORESERVE 0xFF00 #define SHN_LOPROC 0xFF00 #define SHN_HIPROC 0xFF1F #define SHN_LOOS 0xFF20 #define SHN_HIOS 0xFF3F #define SHN_ABS 0xFFF1 #define SHN_COMMON 0xFFF2 #define SHN_XINDEX 0xFFFF #define SHN_HIRESERVE 0xFFFF // Section types #define SHT_NULL 0 #define SHT_PROGBITS 1 #define SHT_SYMTAB 2 #define SHT_STRTAB 3 #define SHT_RELA 4 #define SHT_HASH 5 #define SHT_DYNAMIC 6 #define SHT_NOTE 7 #define SHT_NOBITS 8 #define SHT_REL 9 #define SHT_SHLIB 10 #define SHT_DYNSYM 11 #define SHT_INIT_ARRAY 14 #define SHT_FINI_ARRAY 15 #define SHT_PREINIT_ARRAY 16 #define SHT_GROUP 17 #define SHT_SYMTAB_SHNDX 18 #define SHT_LOOS 0x60000000 #define SHT_HIOS 0x6fffffff #define SHT_LOPROC 0x70000000 #define SHT_HIPROC 0x7FFFFFFF #define SHT_LOUSER 0x80000000 #define SHT_HIUSER 0xFFFFFFFF // Section attribute flags #define SHF_WRITE 0x1 #define SHF_ALLOC 0x2 #define SHF_EXECINSTR 0x4 #define SHF_MERGE 0x10 #define SHF_STRINGS 0x20 #define SHF_INFO_LINK 0x40 #define SHF_LINK_ORDER 0x80 #define SHF_OS_NONCONFORMING 0x100 #define SHF_GROUP 0x200 #define SHF_TLS 0x400 #define SHF_MASKOS 0x0ff00000 #define SHF_MASKPROC 0xF0000000 // Section group flags #define GRP_COMDAT 0x1 #define GRP_MASKOS 0x0ff00000 #define GRP_MASKPROC 0xf0000000 // Symbol binding #define STB_LOCAL 0 #define STB_GLOBAL 1 #define STB_WEAK 2 #define STB_LOOS 10 #define STB_HIOS 12 #define STB_MULTIDEF 13 #define STB_LOPROC 13 #define STB_HIPROC 15 // Note types #define NT_AMDGPU_METADATA 1 #define NT_AMD_AMDGPU_HSA_METADATA 10 #define NT_AMD_AMDGPU_ISA 11 #define NT_AMD_AMDGPU_PAL_METADATA 12 // Symbol types #define STT_NOTYPE 0 #define STT_OBJECT 1 #define STT_FUNC 2 #define STT_SECTION 3 #define STT_FILE 4 #define STT_COMMON 5 #define STT_TLS 6 #define STT_LOOS 10 #define STT_AMDGPU_HSA_KERNEL 10 #define STT_HIOS 12 #define STT_LOPROC 13 #define STT_HIPROC 15 // Symbol visibility #define STV_DEFAULT 0 #define STV_INTERNAL 1 #define STV_HIDDEN 2 #define STV_PROTECTED 3 // Undefined name #define STN_UNDEF 0 // Relocation types #define R_386_NONE 0 #define R_X86_64_NONE 0 #define R_AMDGPU_NONE 0 #define R_386_32 1 #define R_X86_64_64 1 #define R_AMDGPU_ABS32_LO 1 #define R_386_PC32 2 #define R_X86_64_PC32 2 #define R_AMDGPU_ABS32_HI 2 #define R_386_GOT32 3 #define R_X86_64_GOT32 3 #define R_AMDGPU_ABS64 3 #define R_386_PLT32 4 #define R_X86_64_PLT32 4 #define R_AMDGPU_REL32 4 #define R_386_COPY 5 #define R_X86_64_COPY 5 #define R_AMDGPU_REL64 5 #define R_386_GLOB_DAT 6 #define R_X86_64_GLOB_DAT 6 #define R_AMDGPU_ABS32 6 #define R_386_JMP_SLOT 7 #define R_X86_64_JUMP_SLOT 7 #define R_AMDGPU_GOTPCREL 7 #define R_386_RELATIVE 8 #define R_X86_64_RELATIVE 8 #define R_AMDGPU_GOTPCREL32_LO 8 #define R_386_GOTOFF 9 #define R_X86_64_GOTPCREL 9 #define R_AMDGPU_GOTPCREL32_HI 9 #define R_386_GOTPC 10 #define R_X86_64_32 10 #define R_AMDGPU_REL32_LO 10 #define R_386_32PLT 11 #define R_X86_64_32S 11 #define R_AMDGPU_REL32_HI 11 #define R_X86_64_16 12 #define R_X86_64_PC16 13 #define R_AMDGPU_RELATIVE64 13 #define R_386_TLS_TPOFF 14 #define R_X86_64_8 14 #define R_386_TLS_IE 15 #define R_X86_64_PC8 15 #define R_386_TLS_GOTIE 16 #define R_X86_64_DTPMOD64 16 #define R_386_TLS_LE 17 #define R_X86_64_DTPOFF64 17 #define R_386_TLS_GD 18 #define R_X86_64_TPOFF64 18 #define R_386_TLS_LDM 19 #define R_X86_64_TLSGD 19 #define R_386_16 20 #define R_X86_64_TLSLD 20 #define R_386_PC16 21 #define R_X86_64_DTPOFF32 21 #define R_386_8 22 #define R_X86_64_GOTTPOFF 22 #define R_386_PC8 23 #define R_X86_64_TPOFF32 23 #define R_386_TLS_GD_32 24 #define R_X86_64_PC64 24 #define R_386_TLS_GD_PUSH 25 #define R_X86_64_GOTOFF64 25 #define R_386_TLS_GD_CALL 26 #define R_X86_64_GOTPC32 26 #define R_386_TLS_GD_POP 27 #define R_X86_64_GOT64 27 #define R_386_TLS_LDM_32 28 #define R_X86_64_GOTPCREL64 28 #define R_386_TLS_LDM_PUSH 29 #define R_X86_64_GOTPC64 29 #define R_386_TLS_LDM_CALL 30 #define R_X86_64_GOTPLT64 30 #define R_386_TLS_LDM_POP 31 #define R_X86_64_PLTOFF64 31 #define R_386_TLS_LDO_32 32 #define R_386_TLS_IE_32 33 #define R_386_TLS_LE_32 34 #define R_X86_64_GOTPC32_TLSDESC 34 #define R_386_TLS_DTPMOD32 35 #define R_X86_64_TLSDESC_CALL 35 #define R_386_TLS_DTPOFF32 36 #define R_X86_64_TLSDESC 36 #define R_386_TLS_TPOFF32 37 #define R_X86_64_IRELATIVE 37 #define R_386_SIZE32 38 #define R_386_TLS_GOTDESC 39 #define R_386_TLS_DESC_CALL 40 #define R_386_TLS_DESC 41 #define R_386_IRELATIVE 42 #define R_386_GOT32X 43 #define R_X86_64_GNU_VTINHERIT 250 #define R_X86_64_GNU_VTENTRY 251 // Segment types #define PT_NULL 0 #define PT_LOAD 1 #define PT_DYNAMIC 2 #define PT_INTERP 3 #define PT_NOTE 4 #define PT_SHLIB 5 #define PT_PHDR 6 #define PT_TLS 7 #define PT_LOOS 0x60000000 #define PT_HIOS 0x6fffffff #define PT_LOPROC 0x70000000 #define PT_HIPROC 0x7FFFFFFF // Segment flags #define PF_X 1 // Execute #define PF_W 2 // Write #define PF_R 4 // Read #define PF_MASKOS 0x0ff00000 // Unspecified #define PF_MASKPROC 0xf0000000 // Unspecified // Dynamic Array Tags #define DT_NULL 0 #define DT_NEEDED 1 #define DT_PLTRELSZ 2 #define DT_PLTGOT 3 #define DT_HASH 4 #define DT_STRTAB 5 #define DT_SYMTAB 6 #define DT_RELA 7 #define DT_RELASZ 8 #define DT_RELAENT 9 #define DT_STRSZ 10 #define DT_SYMENT 11 #define DT_INIT 12 #define DT_FINI 13 #define DT_SONAME 14 #define DT_RPATH 15 #define DT_SYMBOLIC 16 #define DT_REL 17 #define DT_RELSZ 18 #define DT_RELENT 19 #define DT_PLTREL 20 #define DT_DEBUG 21 #define DT_TEXTREL 22 #define DT_JMPREL 23 #define DT_BIND_NOW 24 #define DT_INIT_ARRAY 25 #define DT_FINI_ARRAY 26 #define DT_INIT_ARRAYSZ 27 #define DT_FINI_ARRAYSZ 28 #define DT_RUNPATH 29 #define DT_FLAGS 30 #define DT_ENCODING 32 #define DT_PREINIT_ARRAY 32 #define DT_PREINIT_ARRAYSZ 33 #define DT_MAXPOSTAGS 34 #define DT_LOOS 0x6000000D #define DT_HIOS 0x6ffff000 #define DT_LOPROC 0x70000000 #define DT_HIPROC 0x7FFFFFFF // DT_FLAGS values #define DF_ORIGIN 0x1 #define DF_SYMBOLIC 0x2 #define DF_TEXTREL 0x4 #define DF_BIND_NOW 0x8 #define DF_STATIC_TLS 0x10 // ELF file header struct Elf32_Ehdr { unsigned char e_ident[EI_NIDENT]; Elf_Half e_type; Elf_Half e_machine; Elf_Word e_version; Elf32_Addr e_entry; Elf32_Off e_phoff; Elf32_Off e_shoff; Elf_Word e_flags; Elf_Half e_ehsize; Elf_Half e_phentsize; Elf_Half e_phnum; Elf_Half e_shentsize; Elf_Half e_shnum; Elf_Half e_shstrndx; }; struct Elf64_Ehdr { unsigned char e_ident[EI_NIDENT]; Elf_Half e_type; Elf_Half e_machine; Elf_Word e_version; Elf64_Addr e_entry; Elf64_Off e_phoff; Elf64_Off e_shoff; Elf_Word e_flags; Elf_Half e_ehsize; Elf_Half e_phentsize; Elf_Half e_phnum; Elf_Half e_shentsize; Elf_Half e_shnum; Elf_Half e_shstrndx; }; // Section header struct Elf32_Shdr { Elf_Word sh_name; Elf_Word sh_type; Elf_Word sh_flags; Elf32_Addr sh_addr; Elf32_Off sh_offset; Elf_Word sh_size; Elf_Word sh_link; Elf_Word sh_info; Elf_Word sh_addralign; Elf_Word sh_entsize; }; struct Elf64_Shdr { Elf_Word sh_name; Elf_Word sh_type; Elf_Xword sh_flags; Elf64_Addr sh_addr; Elf64_Off sh_offset; Elf_Xword sh_size; Elf_Word sh_link; Elf_Word sh_info; Elf_Xword sh_addralign; Elf_Xword sh_entsize; }; // Segment header struct Elf32_Phdr { Elf_Word p_type; Elf32_Off p_offset; Elf32_Addr p_vaddr; Elf32_Addr p_paddr; Elf_Word p_filesz; Elf_Word p_memsz; Elf_Word p_flags; Elf_Word p_align; }; struct Elf64_Phdr { Elf_Word p_type; Elf_Word p_flags; Elf64_Off p_offset; Elf64_Addr p_vaddr; Elf64_Addr p_paddr; Elf_Xword p_filesz; Elf_Xword p_memsz; Elf_Xword p_align; }; // Symbol table entry struct Elf32_Sym { Elf_Word st_name; Elf32_Addr st_value; Elf_Word st_size; unsigned char st_info; unsigned char st_other; Elf_Half st_shndx; }; struct Elf64_Sym { Elf_Word st_name; unsigned char st_info; unsigned char st_other; Elf_Half st_shndx; Elf64_Addr st_value; Elf_Xword st_size; }; #define ELF_ST_BIND( i ) ( ( i ) >> 4 ) #define ELF_ST_TYPE( i ) ( (i)&0xf ) #define ELF_ST_INFO( b, t ) ( ( ( b ) << 4 ) + ( (t)&0xf ) ) #define ELF_ST_VISIBILITY( o ) ( (o)&0x3 ) // Relocation entries struct Elf32_Rel { Elf32_Addr r_offset; Elf_Word r_info; }; struct Elf32_Rela { Elf32_Addr r_offset; Elf_Word r_info; Elf_Sword r_addend; }; struct Elf64_Rel { Elf64_Addr r_offset; Elf_Xword r_info; }; struct Elf64_Rela { Elf64_Addr r_offset; Elf_Xword r_info; Elf_Sxword r_addend; }; #define ELF32_R_SYM( i ) ( ( i ) >> 8 ) #define ELF32_R_TYPE( i ) ( (unsigned char)( i ) ) #define ELF32_R_INFO( s, t ) ( ( ( s ) << 8 ) + (unsigned char)( t ) ) #define ELF64_R_SYM( i ) ( ( i ) >> 32 ) #define ELF64_R_TYPE( i ) ( (i)&0xffffffffL ) #define ELF64_R_INFO( s, t ) \ ( ( ( ( int64_t )( s ) ) << 32 ) + ( (t)&0xffffffffL ) ) // Dynamic structure struct Elf32_Dyn { Elf_Sword d_tag; union { Elf_Word d_val; Elf32_Addr d_ptr; } d_un; }; struct Elf64_Dyn { Elf_Sxword d_tag; union { Elf_Xword d_val; Elf64_Addr d_ptr; } d_un; }; } // namespace ELFIO #endif // ELFTYPES_H /*** End of inlined file: elf_types.hpp ***/ /*** Start of inlined file: elfio_version.hpp ***/ #define ELFIO_VERSION "3.8" /*** End of inlined file: elfio_version.hpp ***/ /*** Start of inlined file: elfio_utils.hpp ***/ #ifndef ELFIO_UTILS_HPP #define ELFIO_UTILS_HPP #define ELFIO_GET_ACCESS( TYPE, NAME, FIELD ) \ TYPE get_##NAME() const { return ( *convertor )( FIELD ); } #define ELFIO_SET_ACCESS( TYPE, NAME, FIELD ) \ void set_##NAME( TYPE value ) \ { \ FIELD = value; \ FIELD = ( *convertor )( FIELD ); \ } #define ELFIO_GET_SET_ACCESS( TYPE, NAME, FIELD ) \ TYPE get_##NAME() const { return ( *convertor )( FIELD ); } \ void set_##NAME( TYPE value ) \ { \ FIELD = value; \ FIELD = ( *convertor )( FIELD ); \ } #define ELFIO_GET_ACCESS_DECL( TYPE, NAME ) virtual TYPE get_##NAME() const = 0 #define ELFIO_SET_ACCESS_DECL( TYPE, NAME ) \ virtual void set_##NAME( TYPE value ) = 0 #define ELFIO_GET_SET_ACCESS_DECL( TYPE, NAME ) \ virtual TYPE get_##NAME() const = 0; \ virtual void set_##NAME( TYPE value ) = 0 namespace ELFIO { //------------------------------------------------------------------------------ class endianess_convertor { public: //------------------------------------------------------------------------------ endianess_convertor() { need_conversion = false; } //------------------------------------------------------------------------------ void setup( unsigned char elf_file_encoding ) { need_conversion = ( elf_file_encoding != get_host_encoding() ); } //------------------------------------------------------------------------------ uint64_t operator()( uint64_t value ) const { if ( !need_conversion ) { return value; } value = ( ( value & 0x00000000000000FFull ) << 56 ) | ( ( value & 0x000000000000FF00ull ) << 40 ) | ( ( value & 0x0000000000FF0000ull ) << 24 ) | ( ( value & 0x00000000FF000000ull ) << 8 ) | ( ( value & 0x000000FF00000000ull ) >> 8 ) | ( ( value & 0x0000FF0000000000ull ) >> 24 ) | ( ( value & 0x00FF000000000000ull ) >> 40 ) | ( ( value & 0xFF00000000000000ull ) >> 56 ); return value; } //------------------------------------------------------------------------------ int64_t operator()( int64_t value ) const { if ( !need_conversion ) { return value; } return ( int64_t )( *this )( (uint64_t)value ); } //------------------------------------------------------------------------------ uint32_t operator()( uint32_t value ) const { if ( !need_conversion ) { return value; } value = ( ( value & 0x000000FF ) << 24 ) | ( ( value & 0x0000FF00 ) << 8 ) | ( ( value & 0x00FF0000 ) >> 8 ) | ( ( value & 0xFF000000 ) >> 24 ); return value; } //------------------------------------------------------------------------------ int32_t operator()( int32_t value ) const { if ( !need_conversion ) { return value; } return ( int32_t )( *this )( (uint32_t)value ); } //------------------------------------------------------------------------------ uint16_t operator()( uint16_t value ) const { if ( !need_conversion ) { return value; } value = ( ( value & 0x00FF ) << 8 ) | ( ( value & 0xFF00 ) >> 8 ); return value; } //------------------------------------------------------------------------------ int16_t operator()( int16_t value ) const { if ( !need_conversion ) { return value; } return ( int16_t )( *this )( (uint16_t)value ); } //------------------------------------------------------------------------------ int8_t operator()( int8_t value ) const { return value; } //------------------------------------------------------------------------------ uint8_t operator()( uint8_t value ) const { return value; } //------------------------------------------------------------------------------ private: //------------------------------------------------------------------------------ unsigned char get_host_encoding() const { static const int tmp = 1; if ( 1 == *(const char*)&tmp ) { return ELFDATA2LSB; } else { return ELFDATA2MSB; } } //------------------------------------------------------------------------------ private: bool need_conversion; }; //------------------------------------------------------------------------------ inline uint32_t elf_hash( const unsigned char* name ) { uint32_t h = 0, g; while ( *name ) { h = ( h << 4 ) + *name++; g = h & 0xf0000000; if ( g != 0 ) h ^= g >> 24; h &= ~g; } return h; } } // namespace ELFIO #endif // ELFIO_UTILS_HPP /*** End of inlined file: elfio_utils.hpp ***/ /*** Start of inlined file: elfio_header.hpp ***/ #ifndef ELF_HEADER_HPP #define ELF_HEADER_HPP #include namespace ELFIO { class elf_header { public: virtual ~elf_header(){}; virtual bool load( std::istream& stream ) = 0; virtual bool save( std::ostream& stream ) const = 0; // ELF header functions ELFIO_GET_ACCESS_DECL( unsigned char, class ); ELFIO_GET_ACCESS_DECL( unsigned char, elf_version ); ELFIO_GET_ACCESS_DECL( unsigned char, encoding ); ELFIO_GET_ACCESS_DECL( Elf_Half, header_size ); ELFIO_GET_ACCESS_DECL( Elf_Half, section_entry_size ); ELFIO_GET_ACCESS_DECL( Elf_Half, segment_entry_size ); ELFIO_GET_SET_ACCESS_DECL( Elf_Word, version ); ELFIO_GET_SET_ACCESS_DECL( unsigned char, os_abi ); ELFIO_GET_SET_ACCESS_DECL( unsigned char, abi_version ); ELFIO_GET_SET_ACCESS_DECL( Elf_Half, type ); ELFIO_GET_SET_ACCESS_DECL( Elf_Half, machine ); ELFIO_GET_SET_ACCESS_DECL( Elf_Word, flags ); ELFIO_GET_SET_ACCESS_DECL( Elf64_Addr, entry ); ELFIO_GET_SET_ACCESS_DECL( Elf_Half, sections_num ); ELFIO_GET_SET_ACCESS_DECL( Elf64_Off, sections_offset ); ELFIO_GET_SET_ACCESS_DECL( Elf_Half, segments_num ); ELFIO_GET_SET_ACCESS_DECL( Elf64_Off, segments_offset ); ELFIO_GET_SET_ACCESS_DECL( Elf_Half, section_name_str_index ); }; template struct elf_header_impl_types; template <> struct elf_header_impl_types { typedef Elf32_Phdr Phdr_type; typedef Elf32_Shdr Shdr_type; static const unsigned char file_class = ELFCLASS32; }; template <> struct elf_header_impl_types { typedef Elf64_Phdr Phdr_type; typedef Elf64_Shdr Shdr_type; static const unsigned char file_class = ELFCLASS64; }; template class elf_header_impl : public elf_header { public: //------------------------------------------------------------------------------ elf_header_impl( endianess_convertor* convertor_, unsigned char encoding ) { convertor = convertor_; std::fill_n( reinterpret_cast( &header ), sizeof( header ), '\0' ); header.e_ident[EI_MAG0] = ELFMAG0; header.e_ident[EI_MAG1] = ELFMAG1; header.e_ident[EI_MAG2] = ELFMAG2; header.e_ident[EI_MAG3] = ELFMAG3; header.e_ident[EI_CLASS] = elf_header_impl_types::file_class; header.e_ident[EI_DATA] = encoding; header.e_ident[EI_VERSION] = EV_CURRENT; header.e_version = ( *convertor )( (Elf_Word)EV_CURRENT ); header.e_ehsize = ( sizeof( header ) ); header.e_ehsize = ( *convertor )( header.e_ehsize ); header.e_shstrndx = ( *convertor )( (Elf_Half)1 ); header.e_phentsize = sizeof( typename elf_header_impl_types::Phdr_type ); header.e_shentsize = sizeof( typename elf_header_impl_types::Shdr_type ); header.e_phentsize = ( *convertor )( header.e_phentsize ); header.e_shentsize = ( *convertor )( header.e_shentsize ); } //------------------------------------------------------------------------------ bool load( std::istream& stream ) { stream.seekg( 0 ); stream.read( reinterpret_cast( &header ), sizeof( header ) ); return ( stream.gcount() == sizeof( header ) ); } //------------------------------------------------------------------------------ bool save( std::ostream& stream ) const { stream.seekp( 0 ); stream.write( reinterpret_cast( &header ), sizeof( header ) ); return stream.good(); } //------------------------------------------------------------------------------ // ELF header functions ELFIO_GET_ACCESS( unsigned char, class, header.e_ident[EI_CLASS] ); ELFIO_GET_ACCESS( unsigned char, elf_version, header.e_ident[EI_VERSION] ); ELFIO_GET_ACCESS( unsigned char, encoding, header.e_ident[EI_DATA] ); ELFIO_GET_ACCESS( Elf_Half, header_size, header.e_ehsize ); ELFIO_GET_ACCESS( Elf_Half, section_entry_size, header.e_shentsize ); ELFIO_GET_ACCESS( Elf_Half, segment_entry_size, header.e_phentsize ); ELFIO_GET_SET_ACCESS( Elf_Word, version, header.e_version ); ELFIO_GET_SET_ACCESS( unsigned char, os_abi, header.e_ident[EI_OSABI] ); ELFIO_GET_SET_ACCESS( unsigned char, abi_version, header.e_ident[EI_ABIVERSION] ); ELFIO_GET_SET_ACCESS( Elf_Half, type, header.e_type ); ELFIO_GET_SET_ACCESS( Elf_Half, machine, header.e_machine ); ELFIO_GET_SET_ACCESS( Elf_Word, flags, header.e_flags ); ELFIO_GET_SET_ACCESS( Elf_Half, section_name_str_index, header.e_shstrndx ); ELFIO_GET_SET_ACCESS( Elf64_Addr, entry, header.e_entry ); ELFIO_GET_SET_ACCESS( Elf_Half, sections_num, header.e_shnum ); ELFIO_GET_SET_ACCESS( Elf64_Off, sections_offset, header.e_shoff ); ELFIO_GET_SET_ACCESS( Elf_Half, segments_num, header.e_phnum ); ELFIO_GET_SET_ACCESS( Elf64_Off, segments_offset, header.e_phoff ); private: T header; endianess_convertor* convertor; }; } // namespace ELFIO #endif // ELF_HEADER_HPP /*** End of inlined file: elfio_header.hpp ***/ /*** Start of inlined file: elfio_section.hpp ***/ #ifndef ELFIO_SECTION_HPP #define ELFIO_SECTION_HPP #include #include #include namespace ELFIO { class section { friend class elfio; public: virtual ~section(){}; ELFIO_GET_ACCESS_DECL( Elf_Half, index ); ELFIO_GET_SET_ACCESS_DECL( std::string, name ); ELFIO_GET_SET_ACCESS_DECL( Elf_Word, type ); ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, flags ); ELFIO_GET_SET_ACCESS_DECL( Elf_Word, info ); ELFIO_GET_SET_ACCESS_DECL( Elf_Word, link ); ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, addr_align ); ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, entry_size ); ELFIO_GET_SET_ACCESS_DECL( Elf64_Addr, address ); ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, size ); ELFIO_GET_SET_ACCESS_DECL( Elf_Word, name_string_offset ); ELFIO_GET_ACCESS_DECL( Elf64_Off, offset ); virtual const char* get_data() const = 0; virtual void set_data( const char* pData, Elf_Word size ) = 0; virtual void set_data( const std::string& data ) = 0; virtual void append_data( const char* pData, Elf_Word size ) = 0; virtual void append_data( const std::string& data ) = 0; virtual size_t get_stream_size() const = 0; virtual void set_stream_size( size_t value ) = 0; protected: ELFIO_SET_ACCESS_DECL( Elf64_Off, offset ); ELFIO_SET_ACCESS_DECL( Elf_Half, index ); virtual void load( std::istream& stream, std::streampos header_offset ) = 0; virtual void save( std::ostream& stream, std::streampos header_offset, std::streampos data_offset ) = 0; virtual bool is_address_initialized() const = 0; }; template class section_impl : public section { public: //------------------------------------------------------------------------------ section_impl( const endianess_convertor* convertor_ ) : convertor( convertor_ ) { std::fill_n( reinterpret_cast( &header ), sizeof( header ), '\0' ); is_address_set = false; data = 0; data_size = 0; index = 0; stream_size = 0; } //------------------------------------------------------------------------------ ~section_impl() { delete[] data; } //------------------------------------------------------------------------------ // Section info functions ELFIO_GET_SET_ACCESS( Elf_Word, type, header.sh_type ); ELFIO_GET_SET_ACCESS( Elf_Xword, flags, header.sh_flags ); ELFIO_GET_SET_ACCESS( Elf_Xword, size, header.sh_size ); ELFIO_GET_SET_ACCESS( Elf_Word, link, header.sh_link ); ELFIO_GET_SET_ACCESS( Elf_Word, info, header.sh_info ); ELFIO_GET_SET_ACCESS( Elf_Xword, addr_align, header.sh_addralign ); ELFIO_GET_SET_ACCESS( Elf_Xword, entry_size, header.sh_entsize ); ELFIO_GET_SET_ACCESS( Elf_Word, name_string_offset, header.sh_name ); ELFIO_GET_ACCESS( Elf64_Addr, address, header.sh_addr ); //------------------------------------------------------------------------------ Elf_Half get_index() const { return index; } //------------------------------------------------------------------------------ std::string get_name() const { return name; } //------------------------------------------------------------------------------ void set_name( std::string name_ ) { name = name_; } //------------------------------------------------------------------------------ void set_address( Elf64_Addr value ) { header.sh_addr = value; header.sh_addr = ( *convertor )( header.sh_addr ); is_address_set = true; } //------------------------------------------------------------------------------ bool is_address_initialized() const { return is_address_set; } //------------------------------------------------------------------------------ const char* get_data() const { return data; } //------------------------------------------------------------------------------ void set_data( const char* raw_data, Elf_Word size ) { if ( get_type() != SHT_NOBITS ) { delete[] data; data = new ( std::nothrow ) char[size]; if ( 0 != data && 0 != raw_data ) { data_size = size; std::copy( raw_data, raw_data + size, data ); } else { data_size = 0; } } set_size( data_size ); } //------------------------------------------------------------------------------ void set_data( const std::string& str_data ) { return set_data( str_data.c_str(), (Elf_Word)str_data.size() ); } //------------------------------------------------------------------------------ void append_data( const char* raw_data, Elf_Word size ) { if ( get_type() != SHT_NOBITS ) { if ( get_size() + size < data_size ) { std::copy( raw_data, raw_data + size, data + get_size() ); } else { data_size = 2 * ( data_size + size ); char* new_data = new ( std::nothrow ) char[data_size]; if ( 0 != new_data ) { std::copy( data, data + get_size(), new_data ); std::copy( raw_data, raw_data + size, new_data + get_size() ); delete[] data; data = new_data; } else { size = 0; } } set_size( get_size() + size ); } } //------------------------------------------------------------------------------ void append_data( const std::string& str_data ) { return append_data( str_data.c_str(), (Elf_Word)str_data.size() ); } //------------------------------------------------------------------------------ protected: //------------------------------------------------------------------------------ ELFIO_GET_SET_ACCESS( Elf64_Off, offset, header.sh_offset ); //------------------------------------------------------------------------------ void set_index( Elf_Half value ) { index = value; } //------------------------------------------------------------------------------ void load( std::istream& stream, std::streampos header_offset ) { std::fill_n( reinterpret_cast( &header ), sizeof( header ), '\0' ); stream.seekg( 0, stream.end ); set_stream_size( stream.tellg() ); stream.seekg( header_offset ); stream.read( reinterpret_cast( &header ), sizeof( header ) ); Elf_Xword size = get_size(); if ( 0 == data && SHT_NULL != get_type() && SHT_NOBITS != get_type() && size < get_stream_size() ) { data = new ( std::nothrow ) char[size + 1]; if ( ( 0 != size ) && ( 0 != data ) ) { stream.seekg( ( *convertor )( header.sh_offset ) ); stream.read( data, size ); data[size] = 0; // Ensure data is ended with 0 to avoid oob read data_size = size; } else { data_size = 0; } } } //------------------------------------------------------------------------------ void save( std::ostream& stream, std::streampos header_offset, std::streampos data_offset ) { if ( 0 != get_index() ) { header.sh_offset = data_offset; header.sh_offset = ( *convertor )( header.sh_offset ); } save_header( stream, header_offset ); if ( get_type() != SHT_NOBITS && get_type() != SHT_NULL && get_size() != 0 && data != 0 ) { save_data( stream, data_offset ); } } //------------------------------------------------------------------------------ private: //------------------------------------------------------------------------------ void save_header( std::ostream& stream, std::streampos header_offset ) const { stream.seekp( header_offset ); stream.write( reinterpret_cast( &header ), sizeof( header ) ); } //------------------------------------------------------------------------------ void save_data( std::ostream& stream, std::streampos data_offset ) const { stream.seekp( data_offset ); stream.write( get_data(), get_size() ); } //------------------------------------------------------------------------------ size_t get_stream_size() const { return stream_size; } //------------------------------------------------------------------------------ void set_stream_size( size_t value ) { stream_size = value; } //------------------------------------------------------------------------------ private: T header; Elf_Half index; std::string name; char* data; Elf_Word data_size; const endianess_convertor* convertor; bool is_address_set; size_t stream_size; }; } // namespace ELFIO #endif // ELFIO_SECTION_HPP /*** End of inlined file: elfio_section.hpp ***/ /*** Start of inlined file: elfio_segment.hpp ***/ #ifndef ELFIO_SEGMENT_HPP #define ELFIO_SEGMENT_HPP #include #include #include namespace ELFIO { class segment { friend class elfio; public: virtual ~segment(){}; ELFIO_GET_ACCESS_DECL( Elf_Half, index ); ELFIO_GET_SET_ACCESS_DECL( Elf_Word, type ); ELFIO_GET_SET_ACCESS_DECL( Elf_Word, flags ); ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, align ); ELFIO_GET_SET_ACCESS_DECL( Elf64_Addr, virtual_address ); ELFIO_GET_SET_ACCESS_DECL( Elf64_Addr, physical_address ); ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, file_size ); ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, memory_size ); ELFIO_GET_ACCESS_DECL( Elf64_Off, offset ); virtual const char* get_data() const = 0; virtual Elf_Half add_section_index( Elf_Half index, Elf_Xword addr_align ) = 0; virtual Elf_Half get_sections_num() const = 0; virtual Elf_Half get_section_index_at( Elf_Half num ) const = 0; virtual bool is_offset_initialized() const = 0; protected: ELFIO_SET_ACCESS_DECL( Elf64_Off, offset ); ELFIO_SET_ACCESS_DECL( Elf_Half, index ); virtual const std::vector& get_sections() const = 0; virtual void load( std::istream& stream, std::streampos header_offset ) = 0; virtual void save( std::ostream& stream, std::streampos header_offset, std::streampos data_offset ) = 0; }; //------------------------------------------------------------------------------ template class segment_impl : public segment { public: //------------------------------------------------------------------------------ segment_impl( endianess_convertor* convertor_ ) : stream_size( 0 ), index( 0 ), data( 0 ), convertor( convertor_ ) { is_offset_set = false; std::fill_n( reinterpret_cast( &ph ), sizeof( ph ), '\0' ); } //------------------------------------------------------------------------------ virtual ~segment_impl() { delete[] data; } //------------------------------------------------------------------------------ // Section info functions ELFIO_GET_SET_ACCESS( Elf_Word, type, ph.p_type ); ELFIO_GET_SET_ACCESS( Elf_Word, flags, ph.p_flags ); ELFIO_GET_SET_ACCESS( Elf_Xword, align, ph.p_align ); ELFIO_GET_SET_ACCESS( Elf64_Addr, virtual_address, ph.p_vaddr ); ELFIO_GET_SET_ACCESS( Elf64_Addr, physical_address, ph.p_paddr ); ELFIO_GET_SET_ACCESS( Elf_Xword, file_size, ph.p_filesz ); ELFIO_GET_SET_ACCESS( Elf_Xword, memory_size, ph.p_memsz ); ELFIO_GET_ACCESS( Elf64_Off, offset, ph.p_offset ); size_t stream_size; //------------------------------------------------------------------------------ size_t get_stream_size() const { return stream_size; } //------------------------------------------------------------------------------ void set_stream_size( size_t value ) { stream_size = value; } //------------------------------------------------------------------------------ Elf_Half get_index() const { return index; } //------------------------------------------------------------------------------ const char* get_data() const { return data; } //------------------------------------------------------------------------------ Elf_Half add_section_index( Elf_Half sec_index, Elf_Xword addr_align ) { sections.push_back( sec_index ); if ( addr_align > get_align() ) { set_align( addr_align ); } return (Elf_Half)sections.size(); } //------------------------------------------------------------------------------ Elf_Half get_sections_num() const { return (Elf_Half)sections.size(); } //------------------------------------------------------------------------------ Elf_Half get_section_index_at( Elf_Half num ) const { if ( num < sections.size() ) { return sections[num]; } return Elf_Half( -1 ); } //------------------------------------------------------------------------------ protected: //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void set_offset( Elf64_Off value ) { ph.p_offset = value; ph.p_offset = ( *convertor )( ph.p_offset ); is_offset_set = true; } //------------------------------------------------------------------------------ bool is_offset_initialized() const { return is_offset_set; } //------------------------------------------------------------------------------ const std::vector& get_sections() const { return sections; } //------------------------------------------------------------------------------ void set_index( Elf_Half value ) { index = value; } //------------------------------------------------------------------------------ void load( std::istream& stream, std::streampos header_offset ) { stream.seekg( 0, stream.end ); set_stream_size( stream.tellg() ); stream.seekg( header_offset ); stream.read( reinterpret_cast( &ph ), sizeof( ph ) ); is_offset_set = true; if ( PT_NULL != get_type() && 0 != get_file_size() ) { stream.seekg( ( *convertor )( ph.p_offset ) ); Elf_Xword size = get_file_size(); if ( size > get_stream_size() ) { data = 0; } else { data = new (std::nothrow) char[size + 1]; if ( 0 != data ) { stream.read( data, size ); data[size] = 0; } } } } //------------------------------------------------------------------------------ void save( std::ostream& stream, std::streampos header_offset, std::streampos data_offset ) { ph.p_offset = data_offset; ph.p_offset = ( *convertor )( ph.p_offset ); stream.seekp( header_offset ); stream.write( reinterpret_cast( &ph ), sizeof( ph ) ); } //------------------------------------------------------------------------------ private: T ph; Elf_Half index; char* data; std::vector sections; endianess_convertor* convertor; bool is_offset_set; }; } // namespace ELFIO #endif // ELFIO_SEGMENT_HPP /*** End of inlined file: elfio_segment.hpp ***/ /*** Start of inlined file: elfio_strings.hpp ***/ #ifndef ELFIO_STRINGS_HPP #define ELFIO_STRINGS_HPP #include #include #include namespace ELFIO { //------------------------------------------------------------------------------ template class string_section_accessor_template { public: //------------------------------------------------------------------------------ string_section_accessor_template( S* section_ ) : string_section( section_ ) { } //------------------------------------------------------------------------------ const char* get_string( Elf_Word index ) const { if ( string_section ) { if ( index < string_section->get_size() ) { const char* data = string_section->get_data(); if ( 0 != data ) { return data + index; } } } return 0; } //------------------------------------------------------------------------------ Elf_Word add_string( const char* str ) { Elf_Word current_position = 0; if ( string_section ) { // Strings are addeded to the end of the current section data current_position = (Elf_Word)string_section->get_size(); if ( current_position == 0 ) { char empty_string = '\0'; string_section->append_data( &empty_string, 1 ); current_position++; } string_section->append_data( str, (Elf_Word)std::strlen( str ) + 1 ); } return current_position; } //------------------------------------------------------------------------------ Elf_Word add_string( const std::string& str ) { return add_string( str.c_str() ); } //------------------------------------------------------------------------------ private: S* string_section; }; using string_section_accessor = string_section_accessor_template
; using const_string_section_accessor = string_section_accessor_template; } // namespace ELFIO #endif // ELFIO_STRINGS_HPP /*** End of inlined file: elfio_strings.hpp ***/ #define ELFIO_HEADER_ACCESS_GET( TYPE, FNAME ) \ TYPE get_##FNAME() const { return header ? ( header->get_##FNAME() ) : 0; } #define ELFIO_HEADER_ACCESS_GET_SET( TYPE, FNAME ) \ TYPE get_##FNAME() const \ { \ return header ? ( header->get_##FNAME() ) : 0; \ } \ void set_##FNAME( TYPE val ) \ { \ if ( header ) { \ header->set_##FNAME( val ); \ } \ } namespace ELFIO { //------------------------------------------------------------------------------ class elfio { public: //------------------------------------------------------------------------------ elfio() : sections( this ), segments( this ) { header = 0; current_file_pos = 0; create( ELFCLASS32, ELFDATA2LSB ); } //------------------------------------------------------------------------------ ~elfio() { clean(); } //------------------------------------------------------------------------------ void create( unsigned char file_class, unsigned char encoding ) { clean(); convertor.setup( encoding ); header = create_header( file_class, encoding ); create_mandatory_sections(); } //------------------------------------------------------------------------------ bool load( const std::string& file_name ) { std::ifstream stream; stream.open( file_name.c_str(), std::ios::in | std::ios::binary ); if ( !stream ) { return false; } return load( stream ); } //------------------------------------------------------------------------------ bool load( std::istream& stream ) { clean(); unsigned char e_ident[EI_NIDENT]; // Read ELF file signature stream.read( reinterpret_cast( &e_ident ), sizeof( e_ident ) ); // Is it ELF file? if ( stream.gcount() != sizeof( e_ident ) || e_ident[EI_MAG0] != ELFMAG0 || e_ident[EI_MAG1] != ELFMAG1 || e_ident[EI_MAG2] != ELFMAG2 || e_ident[EI_MAG3] != ELFMAG3 ) { return false; } if ( ( e_ident[EI_CLASS] != ELFCLASS64 ) && ( e_ident[EI_CLASS] != ELFCLASS32 ) ) { return false; } convertor.setup( e_ident[EI_DATA] ); header = create_header( e_ident[EI_CLASS], e_ident[EI_DATA] ); if ( 0 == header ) { return false; } if ( !header->load( stream ) ) { return false; } load_sections( stream ); bool is_still_good = load_segments( stream ); return is_still_good; } //------------------------------------------------------------------------------ bool save( const std::string& file_name ) { std::ofstream stream; stream.open( file_name.c_str(), std::ios::out | std::ios::binary ); if ( !stream ) { return false; } return save( stream ); } //------------------------------------------------------------------------------ bool save( std::ostream& stream ) { if ( !stream || !header ) { return false; } bool is_still_good = true; // Define layout specific header fields // The position of the segment table is fixed after the header. // The position of the section table is variable and needs to be fixed // before saving. header->set_segments_num( segments.size() ); header->set_segments_offset( segments.size() ? header->get_header_size() : 0 ); header->set_sections_num( sections.size() ); header->set_sections_offset( 0 ); // Layout the first section right after the segment table current_file_pos = header->get_header_size() + header->get_segment_entry_size() * (Elf_Xword)header->get_segments_num(); calc_segment_alignment(); is_still_good = layout_segments_and_their_sections(); is_still_good = is_still_good && layout_sections_without_segments(); is_still_good = is_still_good && layout_section_table(); is_still_good = is_still_good && save_header( stream ); is_still_good = is_still_good && save_sections( stream ); is_still_good = is_still_good && save_segments( stream ); return is_still_good; } //------------------------------------------------------------------------------ // ELF header access functions ELFIO_HEADER_ACCESS_GET( unsigned char, class ); ELFIO_HEADER_ACCESS_GET( unsigned char, elf_version ); ELFIO_HEADER_ACCESS_GET( unsigned char, encoding ); ELFIO_HEADER_ACCESS_GET( Elf_Word, version ); ELFIO_HEADER_ACCESS_GET( Elf_Half, header_size ); ELFIO_HEADER_ACCESS_GET( Elf_Half, section_entry_size ); ELFIO_HEADER_ACCESS_GET( Elf_Half, segment_entry_size ); ELFIO_HEADER_ACCESS_GET_SET( unsigned char, os_abi ); ELFIO_HEADER_ACCESS_GET_SET( unsigned char, abi_version ); ELFIO_HEADER_ACCESS_GET_SET( Elf_Half, type ); ELFIO_HEADER_ACCESS_GET_SET( Elf_Half, machine ); ELFIO_HEADER_ACCESS_GET_SET( Elf_Word, flags ); ELFIO_HEADER_ACCESS_GET_SET( Elf64_Addr, entry ); ELFIO_HEADER_ACCESS_GET_SET( Elf64_Off, sections_offset ); ELFIO_HEADER_ACCESS_GET_SET( Elf64_Off, segments_offset ); ELFIO_HEADER_ACCESS_GET_SET( Elf_Half, section_name_str_index ); //------------------------------------------------------------------------------ const endianess_convertor& get_convertor() const { return convertor; } //------------------------------------------------------------------------------ Elf_Xword get_default_entry_size( Elf_Word section_type ) const { switch ( section_type ) { case SHT_RELA: if ( header->get_class() == ELFCLASS64 ) { return sizeof( Elf64_Rela ); } else { return sizeof( Elf32_Rela ); } case SHT_REL: if ( header->get_class() == ELFCLASS64 ) { return sizeof( Elf64_Rel ); } else { return sizeof( Elf32_Rel ); } case SHT_SYMTAB: if ( header->get_class() == ELFCLASS64 ) { return sizeof( Elf64_Sym ); } else { return sizeof( Elf32_Sym ); } case SHT_DYNAMIC: if ( header->get_class() == ELFCLASS64 ) { return sizeof( Elf64_Dyn ); } else { return sizeof( Elf32_Dyn ); } default: return 0; } } //------------------------------------------------------------------------------ private: bool is_offset_in_section( Elf64_Off offset, const section* sec ) const { return ( offset >= sec->get_offset() ) && ( offset < ( sec->get_offset() + sec->get_size() ) ); } //------------------------------------------------------------------------------ public: //! returns an empty string if no problems are detected, //! or a string containing an error message if problems are found std::string validate() const { // check for overlapping sections in the file for ( int i = 0; i < sections.size(); ++i ) { for ( int j = i + 1; j < sections.size(); ++j ) { const section* a = sections[i]; const section* b = sections[j]; if ( !( a->get_type() & SHT_NOBITS ) && !( b->get_type() & SHT_NOBITS ) && ( a->get_size() > 0 ) && ( b->get_size() > 0 ) && ( a->get_offset() > 0 ) && ( b->get_offset() > 0 ) ) { if ( is_offset_in_section( a->get_offset(), b ) || is_offset_in_section( a->get_offset() + a->get_size() - 1, b ) || is_offset_in_section( b->get_offset(), a ) || is_offset_in_section( b->get_offset() + b->get_size() - 1, a ) ) { return "Sections " + a->get_name() + " and " + b->get_name() + " overlap in file"; } } } } // more checks to be added here... return ""; } //------------------------------------------------------------------------------ private: //------------------------------------------------------------------------------ void clean() { delete header; header = 0; std::vector::const_iterator it; for ( it = sections_.begin(); it != sections_.end(); ++it ) { delete *it; } sections_.clear(); std::vector::const_iterator it1; for ( it1 = segments_.begin(); it1 != segments_.end(); ++it1 ) { delete *it1; } segments_.clear(); } //------------------------------------------------------------------------------ elf_header* create_header( unsigned char file_class, unsigned char encoding ) { elf_header* new_header = 0; if ( file_class == ELFCLASS64 ) { new_header = new elf_header_impl( &convertor, encoding ); } else if ( file_class == ELFCLASS32 ) { new_header = new elf_header_impl( &convertor, encoding ); } else { return 0; } return new_header; } //------------------------------------------------------------------------------ section* create_section() { section* new_section; unsigned char file_class = get_class(); if ( file_class == ELFCLASS64 ) { new_section = new section_impl( &convertor ); } else if ( file_class == ELFCLASS32 ) { new_section = new section_impl( &convertor ); } else { return 0; } new_section->set_index( (Elf_Half)sections_.size() ); sections_.push_back( new_section ); return new_section; } //------------------------------------------------------------------------------ segment* create_segment() { segment* new_segment; unsigned char file_class = header->get_class(); if ( file_class == ELFCLASS64 ) { new_segment = new segment_impl( &convertor ); } else if ( file_class == ELFCLASS32 ) { new_segment = new segment_impl( &convertor ); } else { return 0; } new_segment->set_index( (Elf_Half)segments_.size() ); segments_.push_back( new_segment ); return new_segment; } //------------------------------------------------------------------------------ void create_mandatory_sections() { // Create null section without calling to 'add_section' as no string // section containing section names exists yet section* sec0 = create_section(); sec0->set_index( 0 ); sec0->set_name( "" ); sec0->set_name_string_offset( 0 ); set_section_name_str_index( 1 ); section* shstrtab = sections.add( ".shstrtab" ); shstrtab->set_type( SHT_STRTAB ); shstrtab->set_addr_align( 1 ); } //------------------------------------------------------------------------------ Elf_Half load_sections( std::istream& stream ) { Elf_Half entry_size = header->get_section_entry_size(); Elf_Half num = header->get_sections_num(); Elf64_Off offset = header->get_sections_offset(); for ( Elf_Half i = 0; i < num; ++i ) { section* sec = create_section(); sec->load( stream, (std::streamoff)offset + (std::streampos)i * entry_size ); sec->set_index( i ); // To mark that the section is not permitted to reassign address // during layout calculation sec->set_address( sec->get_address() ); } Elf_Half shstrndx = get_section_name_str_index(); if ( SHN_UNDEF != shstrndx ) { string_section_accessor str_reader( sections[shstrndx] ); for ( Elf_Half i = 0; i < num; ++i ) { Elf_Word section_offset = sections[i]->get_name_string_offset(); const char* p = str_reader.get_string( section_offset ); if ( p != 0 ) { sections[i]->set_name( p ); } } } return num; } //------------------------------------------------------------------------------ //! Checks whether the addresses of the section entirely fall within the given segment. //! It doesn't matter if the addresses are memory addresses, or file offsets, //! they just need to be in the same address space bool is_sect_in_seg( Elf64_Off sect_begin, Elf_Xword sect_size, Elf64_Off seg_begin, Elf64_Off seg_end ) { return ( seg_begin <= sect_begin ) && ( sect_begin + sect_size <= seg_end ) && ( sect_begin < seg_end ); // this is important criteria when sect_size == 0 // Example: seg_begin=10, seg_end=12 (-> covering the bytes 10 and 11) // sect_begin=12, sect_size=0 -> shall return false! } //------------------------------------------------------------------------------ bool load_segments( std::istream& stream ) { Elf_Half entry_size = header->get_segment_entry_size(); Elf_Half num = header->get_segments_num(); Elf64_Off offset = header->get_segments_offset(); for ( Elf_Half i = 0; i < num; ++i ) { segment* seg; unsigned char file_class = header->get_class(); if ( file_class == ELFCLASS64 ) { seg = new segment_impl( &convertor ); } else if ( file_class == ELFCLASS32 ) { seg = new segment_impl( &convertor ); } else { return false; } seg->load( stream, (std::streamoff)offset + (std::streampos)i * entry_size ); seg->set_index( i ); // Add sections to the segments (similar to readelfs algorithm) Elf64_Off segBaseOffset = seg->get_offset(); Elf64_Off segEndOffset = segBaseOffset + seg->get_file_size(); Elf64_Off segVBaseAddr = seg->get_virtual_address(); Elf64_Off segVEndAddr = segVBaseAddr + seg->get_memory_size(); for ( Elf_Half j = 0; j < sections.size(); ++j ) { const section* psec = sections[j]; // SHF_ALLOC sections are matched based on the virtual address // otherwise the file offset is matched if ( ( psec->get_flags() & SHF_ALLOC ) ? is_sect_in_seg( psec->get_address(), psec->get_size(), segVBaseAddr, segVEndAddr ) : is_sect_in_seg( psec->get_offset(), psec->get_size(), segBaseOffset, segEndOffset ) ) { // Alignment of segment shall not be updated, to preserve original value // It will be re-calculated on saving. seg->add_section_index( psec->get_index(), 0 ); } } // Add section into the segments' container segments_.push_back( seg ); } return true; } //------------------------------------------------------------------------------ bool save_header( std::ostream& stream ) { return header->save( stream ); } //------------------------------------------------------------------------------ bool save_sections( std::ostream& stream ) { for ( unsigned int i = 0; i < sections_.size(); ++i ) { section* sec = sections_.at( i ); std::streampos headerPosition = (std::streamoff)header->get_sections_offset() + (std::streampos)header->get_section_entry_size() * sec->get_index(); sec->save( stream, headerPosition, sec->get_offset() ); } return true; } //------------------------------------------------------------------------------ bool save_segments( std::ostream& stream ) { for ( unsigned int i = 0; i < segments_.size(); ++i ) { segment* seg = segments_.at( i ); std::streampos headerPosition = header->get_segments_offset() + (std::streampos)header->get_segment_entry_size() * seg->get_index(); seg->save( stream, headerPosition, seg->get_offset() ); } return true; } //------------------------------------------------------------------------------ bool is_section_without_segment( unsigned int section_index ) { bool found = false; for ( unsigned int j = 0; !found && ( j < segments.size() ); ++j ) { for ( unsigned int k = 0; !found && ( k < segments[j]->get_sections_num() ); ++k ) { found = segments[j]->get_section_index_at( k ) == section_index; } } return !found; } //------------------------------------------------------------------------------ bool is_subsequence_of( segment* seg1, segment* seg2 ) { // Return 'true' if sections of seg1 are a subset of sections in seg2 const std::vector& sections1 = seg1->get_sections(); const std::vector& sections2 = seg2->get_sections(); bool found = false; if ( sections1.size() < sections2.size() ) { found = std::includes( sections2.begin(), sections2.end(), sections1.begin(), sections1.end() ); } return found; } //------------------------------------------------------------------------------ std::vector get_ordered_segments() { std::vector res; std::deque worklist; res.reserve( segments.size() ); std::copy( segments_.begin(), segments_.end(), std::back_inserter( worklist ) ); // Bring the segments which start at address 0 to the front size_t nextSlot = 0; for ( size_t i = 0; i < worklist.size(); ++i ) { if ( i != nextSlot && worklist[i]->is_offset_initialized() && worklist[i]->get_offset() == 0 ) { if ( worklist[nextSlot]->get_offset() == 0 ) { ++nextSlot; } std::swap( worklist[i], worklist[nextSlot] ); ++nextSlot; } } while ( !worklist.empty() ) { segment* seg = worklist.front(); worklist.pop_front(); size_t i = 0; for ( ; i < worklist.size(); ++i ) { if ( is_subsequence_of( seg, worklist[i] ) ) { break; } } if ( i < worklist.size() ) worklist.push_back( seg ); else res.push_back( seg ); } return res; } //------------------------------------------------------------------------------ bool layout_sections_without_segments() { for ( unsigned int i = 0; i < sections_.size(); ++i ) { if ( is_section_without_segment( i ) ) { section* sec = sections_[i]; Elf_Xword section_align = sec->get_addr_align(); if ( section_align > 1 && current_file_pos % section_align != 0 ) { current_file_pos += section_align - current_file_pos % section_align; } if ( 0 != sec->get_index() ) sec->set_offset( current_file_pos ); if ( SHT_NOBITS != sec->get_type() && SHT_NULL != sec->get_type() ) { current_file_pos += sec->get_size(); } } } return true; } //------------------------------------------------------------------------------ void calc_segment_alignment() { for ( std::vector::iterator s = segments_.begin(); s != segments_.end(); ++s ) { segment* seg = *s; for ( int i = 0; i < seg->get_sections_num(); ++i ) { section* sect = sections_[seg->get_section_index_at( i )]; if ( sect->get_addr_align() > seg->get_align() ) { seg->set_align( sect->get_addr_align() ); } } } } //------------------------------------------------------------------------------ bool layout_segments_and_their_sections() { std::vector worklist; std::vector section_generated( sections.size(), false ); // Get segments in a order in where segments which contain a // sub sequence of other segments are located at the end worklist = get_ordered_segments(); for ( unsigned int i = 0; i < worklist.size(); ++i ) { Elf_Xword segment_memory = 0; Elf_Xword segment_filesize = 0; Elf_Xword seg_start_pos = current_file_pos; segment* seg = worklist[i]; // Special case: PHDR segment // This segment contains the program headers but no sections if ( seg->get_type() == PT_PHDR && seg->get_sections_num() == 0 ) { seg_start_pos = header->get_segments_offset(); segment_memory = segment_filesize = header->get_segment_entry_size() * (Elf_Xword)header->get_segments_num(); } // Special case: else if ( seg->is_offset_initialized() && seg->get_offset() == 0 ) { seg_start_pos = 0; if ( seg->get_sections_num() ) { segment_memory = segment_filesize = current_file_pos; } } // New segments with not generated sections // have to be aligned else if ( seg->get_sections_num() && !section_generated[seg->get_section_index_at( 0 )] ) { Elf_Xword align = seg->get_align() > 0 ? seg->get_align() : 1; Elf64_Off cur_page_alignment = current_file_pos % align; Elf64_Off req_page_alignment = seg->get_virtual_address() % align; Elf64_Off error = req_page_alignment - cur_page_alignment; current_file_pos += ( seg->get_align() + error ) % align; seg_start_pos = current_file_pos; } else if ( seg->get_sections_num() ) { seg_start_pos = sections[seg->get_section_index_at( 0 )]->get_offset(); } // Write segment's data for ( unsigned int j = 0; j < seg->get_sections_num(); ++j ) { Elf_Half index = seg->get_section_index_at( j ); section* sec = sections[index]; // The NULL section is always generated if ( SHT_NULL == sec->get_type() ) { section_generated[index] = true; continue; } Elf_Xword secAlign = 0; // Fix up the alignment if ( !section_generated[index] && sec->is_address_initialized() && SHT_NOBITS != sec->get_type() && SHT_NULL != sec->get_type() && 0 != sec->get_size() ) { // Align the sections based on the virtual addresses // when possible (this is what matters for execution) Elf64_Off req_offset = sec->get_address() - seg->get_virtual_address(); Elf64_Off cur_offset = current_file_pos - seg_start_pos; if ( req_offset < cur_offset ) { // something has gone awfully wrong, abort! // secAlign would turn out negative, seeking backwards and overwriting previous data return false; } secAlign = req_offset - cur_offset; } else if ( !section_generated[index] && !sec->is_address_initialized() ) { // If no address has been specified then only the section // alignment constraint has to be matched Elf_Xword align = sec->get_addr_align(); if ( align == 0 ) { align = 1; } Elf64_Off error = current_file_pos % align; secAlign = ( align - error ) % align; } else if ( section_generated[index] ) { // Alignment for already generated sections secAlign = sec->get_offset() - seg_start_pos - segment_filesize; } // Determine the segment file and memory sizes // Special case .tbss section (NOBITS) in non TLS segment if ( ( sec->get_flags() & SHF_ALLOC ) && !( ( sec->get_flags() & SHF_TLS ) && ( seg->get_type() != PT_TLS ) && ( SHT_NOBITS == sec->get_type() ) ) ) segment_memory += sec->get_size() + secAlign; if ( SHT_NOBITS != sec->get_type() ) segment_filesize += sec->get_size() + secAlign; // Nothing to be done when generating nested segments if ( section_generated[index] ) { continue; } current_file_pos += secAlign; // Set the section addresses when missing if ( !sec->is_address_initialized() ) sec->set_address( seg->get_virtual_address() + current_file_pos - seg_start_pos ); if ( 0 != sec->get_index() ) sec->set_offset( current_file_pos ); if ( SHT_NOBITS != sec->get_type() ) current_file_pos += sec->get_size(); section_generated[index] = true; } seg->set_file_size( segment_filesize ); // If we already have a memory size from loading an elf file (value > 0), // it must not shrink! // Memory size may be bigger than file size and it is the loader's job to do something // with the surplus bytes in memory, like initializing them with a defined value. if ( seg->get_memory_size() < segment_memory ) { seg->set_memory_size( segment_memory ); } seg->set_offset( seg_start_pos ); } return true; } //------------------------------------------------------------------------------ bool layout_section_table() { // Simply place the section table at the end for now Elf64_Off alignmentError = current_file_pos % 4; current_file_pos += ( 4 - alignmentError ) % 4; header->set_sections_offset( current_file_pos ); return true; } //------------------------------------------------------------------------------ public: friend class Sections; class Sections { public: //------------------------------------------------------------------------------ Sections( elfio* parent_ ) : parent( parent_ ) {} //------------------------------------------------------------------------------ Elf_Half size() const { return (Elf_Half)parent->sections_.size(); } //------------------------------------------------------------------------------ section* operator[]( unsigned int index ) const { section* sec = 0; if ( index < parent->sections_.size() ) { sec = parent->sections_[index]; } return sec; } //------------------------------------------------------------------------------ section* operator[]( const std::string& name ) const { section* sec = 0; std::vector::const_iterator it; for ( it = parent->sections_.begin(); it != parent->sections_.end(); ++it ) { if ( ( *it )->get_name() == name ) { sec = *it; break; } } return sec; } //------------------------------------------------------------------------------ section* add( const std::string& name ) { section* new_section = parent->create_section(); new_section->set_name( name ); Elf_Half str_index = parent->get_section_name_str_index(); section* string_table( parent->sections_[str_index] ); string_section_accessor str_writer( string_table ); Elf_Word pos = str_writer.add_string( name ); new_section->set_name_string_offset( pos ); return new_section; } //------------------------------------------------------------------------------ std::vector::iterator begin() { return parent->sections_.begin(); } //------------------------------------------------------------------------------ std::vector::iterator end() { return parent->sections_.end(); } //------------------------------------------------------------------------------ std::vector::const_iterator begin() const { return parent->sections_.cbegin(); } //------------------------------------------------------------------------------ std::vector::const_iterator end() const { return parent->sections_.cend(); } //------------------------------------------------------------------------------ private: elfio* parent; } sections; //------------------------------------------------------------------------------ public: friend class Segments; class Segments { public: //------------------------------------------------------------------------------ Segments( elfio* parent_ ) : parent( parent_ ) {} //------------------------------------------------------------------------------ Elf_Half size() const { return (Elf_Half)parent->segments_.size(); } //------------------------------------------------------------------------------ segment* operator[]( unsigned int index ) const { return parent->segments_[index]; } //------------------------------------------------------------------------------ segment* add() { return parent->create_segment(); } //------------------------------------------------------------------------------ std::vector::iterator begin() { return parent->segments_.begin(); } //------------------------------------------------------------------------------ std::vector::iterator end() { return parent->segments_.end(); } //------------------------------------------------------------------------------ std::vector::const_iterator begin() const { return parent->segments_.cbegin(); } //------------------------------------------------------------------------------ std::vector::const_iterator end() const { return parent->segments_.cend(); } //------------------------------------------------------------------------------ private: elfio* parent; } segments; //------------------------------------------------------------------------------ private: elf_header* header; std::vector sections_; std::vector segments_; endianess_convertor convertor; Elf_Xword current_file_pos; }; } // namespace ELFIO /*** Start of inlined file: elfio_symbols.hpp ***/ #ifndef ELFIO_SYMBOLS_HPP #define ELFIO_SYMBOLS_HPP namespace ELFIO { //------------------------------------------------------------------------------ template class symbol_section_accessor_template { public: //------------------------------------------------------------------------------ symbol_section_accessor_template( const elfio& elf_file_, S* symbol_section_ ) : elf_file( elf_file_ ), symbol_section( symbol_section_ ) { find_hash_section(); } //------------------------------------------------------------------------------ Elf_Xword get_symbols_num() const { Elf_Xword nRet = 0; if ( 0 != symbol_section->get_entry_size() ) { nRet = symbol_section->get_size() / symbol_section->get_entry_size(); } return nRet; } //------------------------------------------------------------------------------ bool get_symbol( Elf_Xword index, std::string& name, Elf64_Addr& value, Elf_Xword& size, unsigned char& bind, unsigned char& type, Elf_Half& section_index, unsigned char& other ) const { bool ret = false; if ( elf_file.get_class() == ELFCLASS32 ) { ret = generic_get_symbol( index, name, value, size, bind, type, section_index, other ); } else { ret = generic_get_symbol( index, name, value, size, bind, type, section_index, other ); } return ret; } //------------------------------------------------------------------------------ bool get_symbol( const std::string& name, Elf64_Addr& value, Elf_Xword& size, unsigned char& bind, unsigned char& type, Elf_Half& section_index, unsigned char& other ) const { bool ret = false; if ( 0 != get_hash_table_index() ) { Elf_Word nbucket = *(const Elf_Word*)hash_section->get_data(); Elf_Word nchain = *(const Elf_Word*)( hash_section->get_data() + sizeof( Elf_Word ) ); Elf_Word val = elf_hash( (const unsigned char*)name.c_str() ); Elf_Word y = *(const Elf_Word*)( hash_section->get_data() + ( 2 + val % nbucket ) * sizeof( Elf_Word ) ); std::string str; get_symbol( y, str, value, size, bind, type, section_index, other ); while ( str != name && STN_UNDEF != y && y < nchain ) { y = *(const Elf_Word*)( hash_section->get_data() + ( 2 + nbucket + y ) * sizeof( Elf_Word ) ); get_symbol( y, str, value, size, bind, type, section_index, other ); } if ( str == name ) { ret = true; } } else { for ( Elf_Xword i = 0; i < get_symbols_num() && !ret; i++ ) { std::string symbol_name; if ( get_symbol( i, symbol_name, value, size, bind, type, section_index, other ) ) { if ( symbol_name == name ) { ret = true; } } } } return ret; } //------------------------------------------------------------------------------ bool get_symbol( const Elf64_Addr& value, std::string& name, Elf_Xword& size, unsigned char& bind, unsigned char& type, Elf_Half& section_index, unsigned char& other ) const { const endianess_convertor& convertor = elf_file.get_convertor(); Elf_Xword idx = 0; bool match = false; Elf64_Addr v = 0; if ( elf_file.get_class() == ELFCLASS32 ) { match = generic_search_symbols( [&]( const Elf32_Sym* sym ) { return convertor( sym->st_value ) == value; }, idx ); } else { match = generic_search_symbols( [&]( const Elf64_Sym* sym ) { return convertor( sym->st_value ) == value; }, idx ); } if ( match ) { return get_symbol( idx, name, v, size, bind, type, section_index, other ); } return false; } //------------------------------------------------------------------------------ Elf_Word add_symbol( Elf_Word name, Elf64_Addr value, Elf_Xword size, unsigned char info, unsigned char other, Elf_Half shndx ) { Elf_Word nRet; if ( symbol_section->get_size() == 0 ) { if ( elf_file.get_class() == ELFCLASS32 ) { nRet = generic_add_symbol( 0, 0, 0, 0, 0, 0 ); } else { nRet = generic_add_symbol( 0, 0, 0, 0, 0, 0 ); } } if ( elf_file.get_class() == ELFCLASS32 ) { nRet = generic_add_symbol( name, value, size, info, other, shndx ); } else { nRet = generic_add_symbol( name, value, size, info, other, shndx ); } return nRet; } //------------------------------------------------------------------------------ Elf_Word add_symbol( Elf_Word name, Elf64_Addr value, Elf_Xword size, unsigned char bind, unsigned char type, unsigned char other, Elf_Half shndx ) { return add_symbol( name, value, size, ELF_ST_INFO( bind, type ), other, shndx ); } //------------------------------------------------------------------------------ Elf_Word add_symbol( string_section_accessor& pStrWriter, const char* str, Elf64_Addr value, Elf_Xword size, unsigned char info, unsigned char other, Elf_Half shndx ) { Elf_Word index = pStrWriter.add_string( str ); return add_symbol( index, value, size, info, other, shndx ); } //------------------------------------------------------------------------------ Elf_Word add_symbol( string_section_accessor& pStrWriter, const char* str, Elf64_Addr value, Elf_Xword size, unsigned char bind, unsigned char type, unsigned char other, Elf_Half shndx ) { return add_symbol( pStrWriter, str, value, size, ELF_ST_INFO( bind, type ), other, shndx ); } //------------------------------------------------------------------------------ Elf_Xword arrange_local_symbols( std::function func = nullptr ) { int nRet = 0; if ( elf_file.get_class() == ELFCLASS32 ) { nRet = generic_arrange_local_symbols( func ); } else { nRet = generic_arrange_local_symbols( func ); } return nRet; } //------------------------------------------------------------------------------ private: //------------------------------------------------------------------------------ void find_hash_section() { hash_section = 0; hash_section_index = 0; Elf_Half nSecNo = elf_file.sections.size(); for ( Elf_Half i = 0; i < nSecNo && 0 == hash_section_index; ++i ) { const section* sec = elf_file.sections[i]; if ( sec->get_link() == symbol_section->get_index() ) { hash_section = sec; hash_section_index = i; } } } //------------------------------------------------------------------------------ Elf_Half get_string_table_index() const { return (Elf_Half)symbol_section->get_link(); } //------------------------------------------------------------------------------ Elf_Half get_hash_table_index() const { return hash_section_index; } //------------------------------------------------------------------------------ template const T* generic_get_symbol_ptr( Elf_Xword index ) const { if ( 0 != symbol_section->get_data() && index < get_symbols_num() ) { const T* pSym = reinterpret_cast( symbol_section->get_data() + index * symbol_section->get_entry_size() ); return pSym; } return nullptr; } //------------------------------------------------------------------------------ template bool generic_search_symbols( std::function match, Elf_Xword& idx ) const { for ( Elf_Xword i = 0; i < get_symbols_num(); i++ ) { const T* symPtr = generic_get_symbol_ptr( i ); if ( symPtr == nullptr ) return false; if ( match( symPtr ) ) { idx = i; return true; } } return false; } //------------------------------------------------------------------------------ template bool generic_get_symbol( Elf_Xword index, std::string& name, Elf64_Addr& value, Elf_Xword& size, unsigned char& bind, unsigned char& type, Elf_Half& section_index, unsigned char& other ) const { bool ret = false; if ( 0 != symbol_section->get_data() && index < get_symbols_num() ) { const T* pSym = reinterpret_cast( symbol_section->get_data() + index * symbol_section->get_entry_size() ); const endianess_convertor& convertor = elf_file.get_convertor(); section* string_section = elf_file.sections[get_string_table_index()]; string_section_accessor str_reader( string_section ); const char* pStr = str_reader.get_string( convertor( pSym->st_name ) ); if ( 0 != pStr ) { name = pStr; } value = convertor( pSym->st_value ); size = convertor( pSym->st_size ); bind = ELF_ST_BIND( pSym->st_info ); type = ELF_ST_TYPE( pSym->st_info ); section_index = convertor( pSym->st_shndx ); other = pSym->st_other; ret = true; } return ret; } //------------------------------------------------------------------------------ template Elf_Word generic_add_symbol( Elf_Word name, Elf64_Addr value, Elf_Xword size, unsigned char info, unsigned char other, Elf_Half shndx ) { const endianess_convertor& convertor = elf_file.get_convertor(); T entry; entry.st_name = convertor( name ); entry.st_value = value; entry.st_value = convertor( entry.st_value ); entry.st_size = size; entry.st_size = convertor( entry.st_size ); entry.st_info = convertor( info ); entry.st_other = convertor( other ); entry.st_shndx = convertor( shndx ); symbol_section->append_data( reinterpret_cast( &entry ), sizeof( entry ) ); Elf_Word nRet = symbol_section->get_size() / sizeof( entry ) - 1; return nRet; } //------------------------------------------------------------------------------ template Elf_Xword generic_arrange_local_symbols( std::function func ) { const endianess_convertor& convertor = elf_file.get_convertor(); const Elf_Xword size = symbol_section->get_entry_size(); Elf_Xword first_not_local = 1; // Skip the first entry. It is always NOTYPE Elf_Xword current = 0; Elf_Xword count = get_symbols_num(); while ( true ) { T* p1 = nullptr; T* p2 = nullptr; while ( first_not_local < count ) { p1 = const_cast( generic_get_symbol_ptr( first_not_local ) ); if ( ELF_ST_BIND( convertor( p1->st_info ) ) != STB_LOCAL ) break; ++first_not_local; } current = first_not_local + 1; while ( current < count ) { p2 = const_cast( generic_get_symbol_ptr( current ) ); if ( ELF_ST_BIND( convertor( p2->st_info ) ) == STB_LOCAL ) break; ++current; } if ( first_not_local < count && current < count ) { if ( func ) func( first_not_local, current ); // Swap the symbols T tmp; std::copy( p1, p1 + 1, &tmp ); std::copy( p2, p2 + 1, p1 ); std::copy( &tmp, &tmp + 1, p2 ); } else { // Update 'info' field of the section symbol_section->set_info( first_not_local ); break; } } // Elf_Word nRet = symbol_section->get_size() / sizeof(entry) - 1; return first_not_local; } //------------------------------------------------------------------------------ private: const elfio& elf_file; S* symbol_section; Elf_Half hash_section_index; const section* hash_section; }; using symbol_section_accessor = symbol_section_accessor_template
; using const_symbol_section_accessor = symbol_section_accessor_template; } // namespace ELFIO #endif // ELFIO_SYMBOLS_HPP /*** End of inlined file: elfio_symbols.hpp ***/ /*** Start of inlined file: elfio_note.hpp ***/ #ifndef ELFIO_NOTE_HPP #define ELFIO_NOTE_HPP namespace ELFIO { //------------------------------------------------------------------------------ // There are discrepancies in documentations. SCO documentation // (http://www.sco.com/developers/gabi/latest/ch5.pheader.html#note_section) // requires 8 byte entries alignment for 64-bit ELF file, // but Oracle's definition uses the same structure // for 32-bit and 64-bit formats. // (https://docs.oracle.com/cd/E23824_01/html/819-0690/chapter6-18048.html) // // It looks like EM_X86_64 Linux implementation is similar to Oracle's // definition. Therefore, the same alignment works for both formats //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ template class note_section_accessor_template { public: //------------------------------------------------------------------------------ note_section_accessor_template( const elfio& elf_file_, S* section_ ) : elf_file( elf_file_ ), note_section( section_ ) { process_section(); } //------------------------------------------------------------------------------ Elf_Word get_notes_num() const { return (Elf_Word)note_start_positions.size(); } //------------------------------------------------------------------------------ bool get_note( Elf_Word index, Elf_Word& type, std::string& name, void*& desc, Elf_Word& descSize ) const { if ( index >= note_section->get_size() ) { return false; } const char* pData = note_section->get_data() + note_start_positions[index]; int align = sizeof( Elf_Word ); const endianess_convertor& convertor = elf_file.get_convertor(); type = convertor( *(const Elf_Word*)( pData + 2 * align ) ); Elf_Word namesz = convertor( *(const Elf_Word*)( pData ) ); descSize = convertor( *(const Elf_Word*)( pData + sizeof( namesz ) ) ); Elf_Xword max_name_size = note_section->get_size() - note_start_positions[index]; if ( namesz < 1 || namesz > max_name_size || (Elf_Xword)namesz + descSize > max_name_size ) { return false; } name.assign( pData + 3 * align, namesz - 1 ); if ( 0 == descSize ) { desc = 0; } else { desc = const_cast( pData + 3 * align + ( ( namesz + align - 1 ) / align ) * align ); } return true; } //------------------------------------------------------------------------------ void add_note( Elf_Word type, const std::string& name, const void* desc, Elf_Word descSize ) { const endianess_convertor& convertor = elf_file.get_convertor(); int align = sizeof( Elf_Word ); Elf_Word nameLen = (Elf_Word)name.size() + 1; Elf_Word nameLenConv = convertor( nameLen ); std::string buffer( reinterpret_cast( &nameLenConv ), align ); Elf_Word descSizeConv = convertor( descSize ); buffer.append( reinterpret_cast( &descSizeConv ), align ); type = convertor( type ); buffer.append( reinterpret_cast( &type ), align ); buffer.append( name ); buffer.append( 1, '\x00' ); const char pad[] = { '\0', '\0', '\0', '\0' }; if ( nameLen % align != 0 ) { buffer.append( pad, align - nameLen % align ); } if ( desc != 0 && descSize != 0 ) { buffer.append( reinterpret_cast( desc ), descSize ); if ( descSize % align != 0 ) { buffer.append( pad, align - descSize % align ); } } note_start_positions.push_back( note_section->get_size() ); note_section->append_data( buffer ); } private: //------------------------------------------------------------------------------ void process_section() { const endianess_convertor& convertor = elf_file.get_convertor(); const char* data = note_section->get_data(); Elf_Xword size = note_section->get_size(); Elf_Xword current = 0; note_start_positions.clear(); // Is it empty? if ( 0 == data || 0 == size ) { return; } Elf_Word align = sizeof( Elf_Word ); while ( current + (Elf_Xword)3 * align <= size ) { note_start_positions.push_back( current ); Elf_Word namesz = convertor( *(const Elf_Word*)( data + current ) ); Elf_Word descsz = convertor( *(const Elf_Word*)( data + current + sizeof( namesz ) ) ); current += (Elf_Xword)3 * sizeof( Elf_Word ) + ( ( namesz + align - 1 ) / align ) * (Elf_Xword)align + ( ( descsz + align - 1 ) / align ) * (Elf_Xword)align; } } //------------------------------------------------------------------------------ private: const elfio& elf_file; S* note_section; std::vector note_start_positions; }; using note_section_accessor = note_section_accessor_template
; using const_note_section_accessor = note_section_accessor_template; } // namespace ELFIO #endif // ELFIO_NOTE_HPP /*** End of inlined file: elfio_note.hpp ***/ /*** Start of inlined file: elfio_relocation.hpp ***/ #ifndef ELFIO_RELOCATION_HPP #define ELFIO_RELOCATION_HPP namespace ELFIO { template struct get_sym_and_type; template <> struct get_sym_and_type { static int get_r_sym( Elf_Xword info ) { return ELF32_R_SYM( (Elf_Word)info ); } static int get_r_type( Elf_Xword info ) { return ELF32_R_TYPE( (Elf_Word)info ); } }; template <> struct get_sym_and_type { static int get_r_sym( Elf_Xword info ) { return ELF32_R_SYM( (Elf_Word)info ); } static int get_r_type( Elf_Xword info ) { return ELF32_R_TYPE( (Elf_Word)info ); } }; template <> struct get_sym_and_type { static int get_r_sym( Elf_Xword info ) { return ELF64_R_SYM( info ); } static int get_r_type( Elf_Xword info ) { return ELF64_R_TYPE( info ); } }; template <> struct get_sym_and_type { static int get_r_sym( Elf_Xword info ) { return ELF64_R_SYM( info ); } static int get_r_type( Elf_Xword info ) { return ELF64_R_TYPE( info ); } }; //------------------------------------------------------------------------------ template class relocation_section_accessor_template { public: //------------------------------------------------------------------------------ relocation_section_accessor_template( const elfio& elf_file_, S* section_ ) : elf_file( elf_file_ ), relocation_section( section_ ) { } //------------------------------------------------------------------------------ Elf_Xword get_entries_num() const { Elf_Xword nRet = 0; if ( 0 != relocation_section->get_entry_size() ) { nRet = relocation_section->get_size() / relocation_section->get_entry_size(); } return nRet; } //------------------------------------------------------------------------------ bool get_entry( Elf_Xword index, Elf64_Addr& offset, Elf_Word& symbol, Elf_Word& type, Elf_Sxword& addend ) const { if ( index >= get_entries_num() ) { // Is index valid return false; } if ( elf_file.get_class() == ELFCLASS32 ) { if ( SHT_REL == relocation_section->get_type() ) { generic_get_entry_rel( index, offset, symbol, type, addend ); } else if ( SHT_RELA == relocation_section->get_type() ) { generic_get_entry_rela( index, offset, symbol, type, addend ); } } else { if ( SHT_REL == relocation_section->get_type() ) { generic_get_entry_rel( index, offset, symbol, type, addend ); } else if ( SHT_RELA == relocation_section->get_type() ) { generic_get_entry_rela( index, offset, symbol, type, addend ); } } return true; } //------------------------------------------------------------------------------ bool get_entry( Elf_Xword index, Elf64_Addr& offset, Elf64_Addr& symbolValue, std::string& symbolName, Elf_Word& type, Elf_Sxword& addend, Elf_Sxword& calcValue ) const { // Do regular job Elf_Word symbol; bool ret = get_entry( index, offset, symbol, type, addend ); // Find the symbol Elf_Xword size; unsigned char bind; unsigned char symbolType; Elf_Half section; unsigned char other; symbol_section_accessor symbols( elf_file, elf_file.sections[get_symbol_table_index()] ); ret = ret && symbols.get_symbol( symbol, symbolName, symbolValue, size, bind, symbolType, section, other ); if ( ret ) { // Was it successful? switch ( type ) { case R_386_NONE: // none calcValue = 0; break; case R_386_32: // S + A calcValue = symbolValue + addend; break; case R_386_PC32: // S + A - P calcValue = symbolValue + addend - offset; break; case R_386_GOT32: // G + A - P calcValue = 0; break; case R_386_PLT32: // L + A - P calcValue = 0; break; case R_386_COPY: // none calcValue = 0; break; case R_386_GLOB_DAT: // S case R_386_JMP_SLOT: // S calcValue = symbolValue; break; case R_386_RELATIVE: // B + A calcValue = addend; break; case R_386_GOTOFF: // S + A - GOT calcValue = 0; break; case R_386_GOTPC: // GOT + A - P calcValue = 0; break; default: // Not recognized symbol! calcValue = 0; break; } } return ret; } //------------------------------------------------------------------------------ bool set_entry( Elf_Xword index, Elf64_Addr offset, Elf_Word symbol, Elf_Word type, Elf_Sxword addend ) { if ( index >= get_entries_num() ) { // Is index valid return false; } if ( elf_file.get_class() == ELFCLASS32 ) { if ( SHT_REL == relocation_section->get_type() ) { generic_set_entry_rel( index, offset, symbol, type, addend ); } else if ( SHT_RELA == relocation_section->get_type() ) { generic_set_entry_rela( index, offset, symbol, type, addend ); } } else { if ( SHT_REL == relocation_section->get_type() ) { generic_set_entry_rel( index, offset, symbol, type, addend ); } else if ( SHT_RELA == relocation_section->get_type() ) { generic_set_entry_rela( index, offset, symbol, type, addend ); } } return true; } //------------------------------------------------------------------------------ void add_entry( Elf64_Addr offset, Elf_Xword info ) { if ( elf_file.get_class() == ELFCLASS32 ) { generic_add_entry( offset, info ); } else { generic_add_entry( offset, info ); } } //------------------------------------------------------------------------------ void add_entry( Elf64_Addr offset, Elf_Word symbol, unsigned char type ) { Elf_Xword info; if ( elf_file.get_class() == ELFCLASS32 ) { info = ELF32_R_INFO( (Elf_Xword)symbol, type ); } else { info = ELF64_R_INFO( (Elf_Xword)symbol, type ); } add_entry( offset, info ); } //------------------------------------------------------------------------------ void add_entry( Elf64_Addr offset, Elf_Xword info, Elf_Sxword addend ) { if ( elf_file.get_class() == ELFCLASS32 ) { generic_add_entry( offset, info, addend ); } else { generic_add_entry( offset, info, addend ); } } //------------------------------------------------------------------------------ void add_entry( Elf64_Addr offset, Elf_Word symbol, unsigned char type, Elf_Sxword addend ) { Elf_Xword info; if ( elf_file.get_class() == ELFCLASS32 ) { info = ELF32_R_INFO( (Elf_Xword)symbol, type ); } else { info = ELF64_R_INFO( (Elf_Xword)symbol, type ); } add_entry( offset, info, addend ); } //------------------------------------------------------------------------------ void add_entry( string_section_accessor str_writer, const char* str, symbol_section_accessor sym_writer, Elf64_Addr value, Elf_Word size, unsigned char sym_info, unsigned char other, Elf_Half shndx, Elf64_Addr offset, unsigned char type ) { Elf_Word str_index = str_writer.add_string( str ); Elf_Word sym_index = sym_writer.add_symbol( str_index, value, size, sym_info, other, shndx ); add_entry( offset, sym_index, type ); } //------------------------------------------------------------------------------ void swap_symbols( Elf_Xword first, Elf_Xword second ) { Elf64_Addr offset; Elf_Word symbol; Elf_Word rtype; Elf_Sxword addend; for ( Elf_Word i = 0; i < get_entries_num(); i++ ) { get_entry( i, offset, symbol, rtype, addend ); if ( symbol == first ) { set_entry( i, offset, (Elf_Word)second, rtype, addend ); } if ( symbol == second ) { set_entry( i, offset, (Elf_Word)first, rtype, addend ); } } } //------------------------------------------------------------------------------ private: //------------------------------------------------------------------------------ Elf_Half get_symbol_table_index() const { return (Elf_Half)relocation_section->get_link(); } //------------------------------------------------------------------------------ template void generic_get_entry_rel( Elf_Xword index, Elf64_Addr& offset, Elf_Word& symbol, Elf_Word& type, Elf_Sxword& addend ) const { const endianess_convertor& convertor = elf_file.get_convertor(); const T* pEntry = reinterpret_cast( relocation_section->get_data() + index * relocation_section->get_entry_size() ); offset = convertor( pEntry->r_offset ); Elf_Xword tmp = convertor( pEntry->r_info ); symbol = get_sym_and_type::get_r_sym( tmp ); type = get_sym_and_type::get_r_type( tmp ); addend = 0; } //------------------------------------------------------------------------------ template void generic_get_entry_rela( Elf_Xword index, Elf64_Addr& offset, Elf_Word& symbol, Elf_Word& type, Elf_Sxword& addend ) const { const endianess_convertor& convertor = elf_file.get_convertor(); const T* pEntry = reinterpret_cast( relocation_section->get_data() + index * relocation_section->get_entry_size() ); offset = convertor( pEntry->r_offset ); Elf_Xword tmp = convertor( pEntry->r_info ); symbol = get_sym_and_type::get_r_sym( tmp ); type = get_sym_and_type::get_r_type( tmp ); addend = convertor( pEntry->r_addend ); } //------------------------------------------------------------------------------ template void generic_set_entry_rel( Elf_Xword index, Elf64_Addr offset, Elf_Word symbol, Elf_Word type, Elf_Sxword ) { const endianess_convertor& convertor = elf_file.get_convertor(); T* pEntry = const_cast( reinterpret_cast( relocation_section->get_data() + index * relocation_section->get_entry_size() ) ); if ( elf_file.get_class() == ELFCLASS32 ) { pEntry->r_info = ELF32_R_INFO( (Elf_Xword)symbol, type ); } else { pEntry->r_info = ELF64_R_INFO( (Elf_Xword)symbol, type ); } pEntry->r_offset = offset; pEntry->r_offset = convertor( pEntry->r_offset ); pEntry->r_info = convertor( pEntry->r_info ); } //------------------------------------------------------------------------------ template void generic_set_entry_rela( Elf_Xword index, Elf64_Addr offset, Elf_Word symbol, Elf_Word type, Elf_Sxword addend ) { const endianess_convertor& convertor = elf_file.get_convertor(); T* pEntry = const_cast( reinterpret_cast( relocation_section->get_data() + index * relocation_section->get_entry_size() ) ); if ( elf_file.get_class() == ELFCLASS32 ) { pEntry->r_info = ELF32_R_INFO( (Elf_Xword)symbol, type ); } else { pEntry->r_info = ELF64_R_INFO( (Elf_Xword)symbol, type ); } pEntry->r_offset = offset; pEntry->r_addend = addend; pEntry->r_offset = convertor( pEntry->r_offset ); pEntry->r_info = convertor( pEntry->r_info ); pEntry->r_addend = convertor( pEntry->r_addend ); } //------------------------------------------------------------------------------ template void generic_add_entry( Elf64_Addr offset, Elf_Xword info ) { const endianess_convertor& convertor = elf_file.get_convertor(); T entry; entry.r_offset = offset; entry.r_info = info; entry.r_offset = convertor( entry.r_offset ); entry.r_info = convertor( entry.r_info ); relocation_section->append_data( reinterpret_cast( &entry ), sizeof( entry ) ); } //------------------------------------------------------------------------------ template void generic_add_entry( Elf64_Addr offset, Elf_Xword info, Elf_Sxword addend ) { const endianess_convertor& convertor = elf_file.get_convertor(); T entry; entry.r_offset = offset; entry.r_info = info; entry.r_addend = addend; entry.r_offset = convertor( entry.r_offset ); entry.r_info = convertor( entry.r_info ); entry.r_addend = convertor( entry.r_addend ); relocation_section->append_data( reinterpret_cast( &entry ), sizeof( entry ) ); } //------------------------------------------------------------------------------ private: const elfio& elf_file; S* relocation_section; }; using relocation_section_accessor = relocation_section_accessor_template
; using const_relocation_section_accessor = relocation_section_accessor_template; } // namespace ELFIO #endif // ELFIO_RELOCATION_HPP /*** End of inlined file: elfio_relocation.hpp ***/ /*** Start of inlined file: elfio_dynamic.hpp ***/ #ifndef ELFIO_DYNAMIC_HPP #define ELFIO_DYNAMIC_HPP namespace ELFIO { //------------------------------------------------------------------------------ template class dynamic_section_accessor_template { public: //------------------------------------------------------------------------------ dynamic_section_accessor_template( const elfio& elf_file_, S* section_ ) : elf_file( elf_file_ ), dynamic_section( section_ ) { } //------------------------------------------------------------------------------ Elf_Xword get_entries_num() const { Elf_Xword nRet = 0; if ( 0 != dynamic_section->get_entry_size() ) { nRet = dynamic_section->get_size() / dynamic_section->get_entry_size(); } return nRet; } //------------------------------------------------------------------------------ bool get_entry( Elf_Xword index, Elf_Xword& tag, Elf_Xword& value, std::string& str ) const { if ( index >= get_entries_num() ) { // Is index valid return false; } if ( elf_file.get_class() == ELFCLASS32 ) { generic_get_entry_dyn( index, tag, value ); } else { generic_get_entry_dyn( index, tag, value ); } // If the tag may have a string table reference, prepare the string if ( tag == DT_NEEDED || tag == DT_SONAME || tag == DT_RPATH || tag == DT_RUNPATH ) { string_section_accessor strsec = elf_file.sections[get_string_table_index()]; const char* result = strsec.get_string( value ); if ( 0 == result ) { str.clear(); return false; } str = result; } else { str.clear(); } return true; } //------------------------------------------------------------------------------ void add_entry( Elf_Xword tag, Elf_Xword value ) { if ( elf_file.get_class() == ELFCLASS32 ) { generic_add_entry( tag, value ); } else { generic_add_entry( tag, value ); } } //------------------------------------------------------------------------------ void add_entry( Elf_Xword tag, const std::string& str ) { string_section_accessor strsec = elf_file.sections[get_string_table_index()]; Elf_Xword value = strsec.add_string( str ); add_entry( tag, value ); } //------------------------------------------------------------------------------ private: //------------------------------------------------------------------------------ Elf_Half get_string_table_index() const { return (Elf_Half)dynamic_section->get_link(); } //------------------------------------------------------------------------------ template void generic_get_entry_dyn( Elf_Xword index, Elf_Xword& tag, Elf_Xword& value ) const { const endianess_convertor& convertor = elf_file.get_convertor(); // Check unusual case when dynamic section has no data if ( dynamic_section->get_data() == 0 || ( index + 1 ) * dynamic_section->get_entry_size() > dynamic_section->get_size() ) { tag = DT_NULL; value = 0; return; } const T* pEntry = reinterpret_cast( dynamic_section->get_data() + index * dynamic_section->get_entry_size() ); tag = convertor( pEntry->d_tag ); switch ( tag ) { case DT_NULL: case DT_SYMBOLIC: case DT_TEXTREL: case DT_BIND_NOW: value = 0; break; case DT_NEEDED: case DT_PLTRELSZ: case DT_RELASZ: case DT_RELAENT: case DT_STRSZ: case DT_SYMENT: case DT_SONAME: case DT_RPATH: case DT_RELSZ: case DT_RELENT: case DT_PLTREL: case DT_INIT_ARRAYSZ: case DT_FINI_ARRAYSZ: case DT_RUNPATH: case DT_FLAGS: case DT_PREINIT_ARRAYSZ: value = convertor( pEntry->d_un.d_val ); break; case DT_PLTGOT: case DT_HASH: case DT_STRTAB: case DT_SYMTAB: case DT_RELA: case DT_INIT: case DT_FINI: case DT_REL: case DT_DEBUG: case DT_JMPREL: case DT_INIT_ARRAY: case DT_FINI_ARRAY: case DT_PREINIT_ARRAY: default: value = convertor( pEntry->d_un.d_ptr ); break; } } //------------------------------------------------------------------------------ template void generic_add_entry( Elf_Xword tag, Elf_Xword value ) { const endianess_convertor& convertor = elf_file.get_convertor(); T entry; switch ( tag ) { case DT_NULL: case DT_SYMBOLIC: case DT_TEXTREL: case DT_BIND_NOW: value = 0; case DT_NEEDED: case DT_PLTRELSZ: case DT_RELASZ: case DT_RELAENT: case DT_STRSZ: case DT_SYMENT: case DT_SONAME: case DT_RPATH: case DT_RELSZ: case DT_RELENT: case DT_PLTREL: case DT_INIT_ARRAYSZ: case DT_FINI_ARRAYSZ: case DT_RUNPATH: case DT_FLAGS: case DT_PREINIT_ARRAYSZ: entry.d_un.d_val = convertor( value ); break; case DT_PLTGOT: case DT_HASH: case DT_STRTAB: case DT_SYMTAB: case DT_RELA: case DT_INIT: case DT_FINI: case DT_REL: case DT_DEBUG: case DT_JMPREL: case DT_INIT_ARRAY: case DT_FINI_ARRAY: case DT_PREINIT_ARRAY: default: entry.d_un.d_ptr = convertor( value ); break; } entry.d_tag = convertor( tag ); dynamic_section->append_data( reinterpret_cast( &entry ), sizeof( entry ) ); } //------------------------------------------------------------------------------ private: const elfio& elf_file; S* dynamic_section; }; using dynamic_section_accessor = dynamic_section_accessor_template
; using const_dynamic_section_accessor = dynamic_section_accessor_template; } // namespace ELFIO #endif // ELFIO_DYNAMIC_HPP /*** End of inlined file: elfio_dynamic.hpp ***/ /*** Start of inlined file: elfio_modinfo.hpp ***/ #ifndef ELFIO_MODINFO_HPP #define ELFIO_MODINFO_HPP #include #include namespace ELFIO { //------------------------------------------------------------------------------ template class modinfo_section_accessor_template { public: //------------------------------------------------------------------------------ modinfo_section_accessor_template( S* section_ ) : modinfo_section( section_ ) { process_section(); } //------------------------------------------------------------------------------ Elf_Word get_attribute_num() const { return (Elf_Word)content.size(); } //------------------------------------------------------------------------------ bool get_attribute( Elf_Word no, std::string& field, std::string& value ) const { if ( no < content.size() ) { field = content[no].first; value = content[no].second; return true; } return false; } //------------------------------------------------------------------------------ bool get_attribute( std::string field_name, std::string& value ) const { for ( auto i = content.begin(); i != content.end(); i++ ) { if ( field_name == i->first ) { value = i->second; return true; } } return false; } //------------------------------------------------------------------------------ Elf_Word add_attribute( std::string field, std::string value ) { Elf_Word current_position = 0; if ( modinfo_section ) { // Strings are addeded to the end of the current section data current_position = (Elf_Word)modinfo_section->get_size(); std::string attribute = field + "=" + value; modinfo_section->append_data( attribute + '\0' ); content.push_back( std::pair( field, value ) ); } return current_position; } //------------------------------------------------------------------------------ private: void process_section() { const char* pdata = modinfo_section->get_data(); if ( pdata ) { ELFIO::Elf_Xword i = 0; while ( i < modinfo_section->get_size() ) { while ( i < modinfo_section->get_size() && !pdata[i] ) i++; if ( i < modinfo_section->get_size() ) { std::string info = pdata + i; size_t loc = info.find( '=' ); std::pair attribute( info.substr( 0, loc ), info.substr( loc + 1 ) ); content.push_back( attribute ); i += info.length(); } } } } //------------------------------------------------------------------------------ private: S* modinfo_section; std::vector> content; }; using modinfo_section_accessor = modinfo_section_accessor_template
; using const_modinfo_section_accessor = modinfo_section_accessor_template; } // namespace ELFIO #endif // ELFIO_MODINFO_HPP /*** End of inlined file: elfio_modinfo.hpp ***/ #ifdef _MSC_VER #pragma warning( pop ) #endif #endif // ELFIO_HPP /*** End of inlined file: elfio.hpp ***/ namespace ELFIO { static struct class_table_t { const char key; const char* str; } class_table[] = { { ELFCLASS32, "ELF32" }, { ELFCLASS64, "ELF64" }, }; static struct endian_table_t { const char key; const char* str; } endian_table[] = { { ELFDATANONE, "None" }, { ELFDATA2LSB, "Little endian" }, { ELFDATA2MSB, "Big endian" }, }; static struct version_table_t { const Elf64_Word key; const char* str; } version_table[] = { { EV_NONE, "None" }, { EV_CURRENT, "Current" }, }; static struct type_table_t { const Elf32_Half key; const char* str; } type_table[] = { { ET_NONE, "No file type" }, { ET_REL, "Relocatable file" }, { ET_EXEC, "Executable file" }, { ET_DYN, "Shared object file" }, { ET_CORE, "Core file" }, }; static struct machine_table_t { const Elf64_Half key; const char* str; } machine_table[] = { { EM_NONE, "No machine" }, { EM_M32, "AT&T WE 32100" }, { EM_SPARC, "SUN SPARC" }, { EM_386, "Intel 80386" }, { EM_68K, "Motorola m68k family" }, { EM_88K, "Motorola m88k family" }, { EM_486, "Intel 80486// Reserved for future use" }, { EM_860, "Intel 80860" }, { EM_MIPS, "MIPS R3000 (officially, big-endian only)" }, { EM_S370, "IBM System/370" }, { EM_MIPS_RS3_LE, "MIPS R3000 little-endian (Oct 4 1999 Draft) Deprecated" }, { EM_res011, "Reserved" }, { EM_res012, "Reserved" }, { EM_res013, "Reserved" }, { EM_res014, "Reserved" }, { EM_PARISC, "HPPA" }, { EM_res016, "Reserved" }, { EM_VPP550, "Fujitsu VPP500" }, { EM_SPARC32PLUS, "Sun's v8plus" }, { EM_960, "Intel 80960" }, { EM_PPC, "PowerPC" }, { EM_PPC64, "64-bit PowerPC" }, { EM_S390, "IBM S/390" }, { EM_SPU, "Sony/Toshiba/IBM SPU" }, { EM_res024, "Reserved" }, { EM_res025, "Reserved" }, { EM_res026, "Reserved" }, { EM_res027, "Reserved" }, { EM_res028, "Reserved" }, { EM_res029, "Reserved" }, { EM_res030, "Reserved" }, { EM_res031, "Reserved" }, { EM_res032, "Reserved" }, { EM_res033, "Reserved" }, { EM_res034, "Reserved" }, { EM_res035, "Reserved" }, { EM_V800, "NEC V800 series" }, { EM_FR20, "Fujitsu FR20" }, { EM_RH32, "TRW RH32" }, { EM_MCORE, "Motorola M*Core // May also be taken by Fujitsu MMA" }, { EM_RCE, "Old name for MCore" }, { EM_ARM, "ARM" }, { EM_OLD_ALPHA, "Digital Alpha" }, { EM_SH, "Renesas (formerly Hitachi) / SuperH SH" }, { EM_SPARCV9, "SPARC v9 64-bit" }, { EM_TRICORE, "Siemens Tricore embedded processor" }, { EM_ARC, "ARC Cores" }, { EM_H8_300, "Renesas (formerly Hitachi) H8/300" }, { EM_H8_300H, "Renesas (formerly Hitachi) H8/300H" }, { EM_H8S, "Renesas (formerly Hitachi) H8S" }, { EM_H8_500, "Renesas (formerly Hitachi) H8/500" }, { EM_IA_64, "Intel IA-64 Processor" }, { EM_MIPS_X, "Stanford MIPS-X" }, { EM_COLDFIRE, "Motorola Coldfire" }, { EM_68HC12, "Motorola M68HC12" }, { EM_MMA, "Fujitsu Multimedia Accelerator" }, { EM_PCP, "Siemens PCP" }, { EM_NCPU, "Sony nCPU embedded RISC processor" }, { EM_NDR1, "Denso NDR1 microprocesspr" }, { EM_STARCORE, "Motorola Star*Core processor" }, { EM_ME16, "Toyota ME16 processor" }, { EM_ST100, "STMicroelectronics ST100 processor" }, { EM_TINYJ, "Advanced Logic Corp. TinyJ embedded processor" }, { EM_X86_64, "Advanced Micro Devices X86-64 processor" }, { EM_PDSP, "Sony DSP Processor" }, { EM_PDP10, "Digital Equipment Corp. PDP-10" }, { EM_PDP11, "Digital Equipment Corp. PDP-11" }, { EM_FX66, "Siemens FX66 microcontroller" }, { EM_ST9PLUS, "STMicroelectronics ST9+ 8/16 bit microcontroller" }, { EM_ST7, "STMicroelectronics ST7 8-bit microcontroller" }, { EM_68HC16, "Motorola MC68HC16 Microcontroller" }, { EM_68HC11, "Motorola MC68HC11 Microcontroller" }, { EM_68HC08, "Motorola MC68HC08 Microcontroller" }, { EM_68HC05, "Motorola MC68HC05 Microcontroller" }, { EM_SVX, "Silicon Graphics SVx" }, { EM_ST19, "STMicroelectronics ST19 8-bit cpu" }, { EM_VAX, "Digital VAX" }, { EM_CRIS, "Axis Communications 32-bit embedded processor" }, { EM_JAVELIN, "Infineon Technologies 32-bit embedded cpu" }, { EM_FIREPATH, "Element 14 64-bit DSP processor" }, { EM_ZSP, "LSI Logic's 16-bit DSP processor" }, { EM_MMIX, "Donald Knuth's educational 64-bit processor" }, { EM_HUANY, "Harvard's machine-independent format" }, { EM_PRISM, "SiTera Prism" }, { EM_AVR, "Atmel AVR 8-bit microcontroller" }, { EM_FR30, "Fujitsu FR30" }, { EM_D10V, "Mitsubishi D10V" }, { EM_D30V, "Mitsubishi D30V" }, { EM_V850, "NEC v850" }, { EM_M32R, "Renesas M32R (formerly Mitsubishi M32R)" }, { EM_MN10300, "Matsushita MN10300" }, { EM_MN10200, "Matsushita MN10200" }, { EM_PJ, "picoJava" }, { EM_OPENRISC, "OpenRISC 32-bit embedded processor" }, { EM_ARC_A5, "ARC Cores Tangent-A5" }, { EM_XTENSA, "Tensilica Xtensa Architecture" }, { EM_VIDEOCORE, "Alphamosaic VideoCore processor" }, { EM_TMM_GPP, "Thompson Multimedia General Purpose Processor" }, { EM_NS32K, "National Semiconductor 32000 series" }, { EM_TPC, "Tenor Network TPC processor" }, { EM_SNP1K, "Trebia SNP 1000 processor" }, { EM_ST200, "STMicroelectronics ST200 microcontroller" }, { EM_IP2K, "Ubicom IP2022 micro controller" }, { EM_MAX, "MAX Processor" }, { EM_CR, "National Semiconductor CompactRISC" }, { EM_F2MC16, "Fujitsu F2MC16" }, { EM_MSP430, "TI msp430 micro controller" }, { EM_BLACKFIN, "ADI Blackfin" }, { EM_SE_C33, "S1C33 Family of Seiko Epson processors" }, { EM_SEP, "Sharp embedded microprocessor" }, { EM_ARCA, "Arca RISC Microprocessor" }, { EM_UNICORE, "Microprocessor series from PKU-Unity Ltd. and MPRC of " "Peking University" }, { EM_EXCESS, "eXcess: 16/32/64-bit configurable embedded CPU" }, { EM_DXP, "Icera Semiconductor Inc. Deep Execution Processor" }, { EM_ALTERA_NIOS2, "Altera Nios II soft-core processor" }, { EM_CRX, "National Semiconductor CRX" }, { EM_XGATE, "Motorola XGATE embedded processor" }, { EM_C166, "Infineon C16x/XC16x processor" }, { EM_M16C, "Renesas M16C series microprocessors" }, { EM_DSPIC30F, "Microchip Technology dsPIC30F Digital Signal Controller" }, { EM_CE, "Freescale Communication Engine RISC core" }, { EM_M32C, "Renesas M32C series microprocessors" }, { EM_res121, "Reserved" }, { EM_res122, "Reserved" }, { EM_res123, "Reserved" }, { EM_res124, "Reserved" }, { EM_res125, "Reserved" }, { EM_res126, "Reserved" }, { EM_res127, "Reserved" }, { EM_res128, "Reserved" }, { EM_res129, "Reserved" }, { EM_res130, "Reserved" }, { EM_TSK3000, "Altium TSK3000 core" }, { EM_RS08, "Freescale RS08 embedded processor" }, { EM_res133, "Reserved" }, { EM_ECOG2, "Cyan Technology eCOG2 microprocessor" }, { EM_SCORE, "Sunplus Score" }, { EM_SCORE7, "Sunplus S+core7 RISC processor" }, { EM_DSP24, "New Japan Radio (NJR) 24-bit DSP Processor" }, { EM_VIDEOCORE3, "Broadcom VideoCore III processor" }, { EM_LATTICEMICO32, "RISC processor for Lattice FPGA architecture" }, { EM_SE_C17, "Seiko Epson C17 family" }, { EM_TI_C6000, "Texas Instruments TMS320C6000 DSP family" }, { EM_TI_C2000, "Texas Instruments TMS320C2000 DSP family" }, { EM_TI_C5500, "Texas Instruments TMS320C55x DSP family" }, { EM_res143, "Reserved" }, { EM_res144, "Reserved" }, { EM_res145, "Reserved" }, { EM_res146, "Reserved" }, { EM_res147, "Reserved" }, { EM_res148, "Reserved" }, { EM_res149, "Reserved" }, { EM_res150, "Reserved" }, { EM_res151, "Reserved" }, { EM_res152, "Reserved" }, { EM_res153, "Reserved" }, { EM_res154, "Reserved" }, { EM_res155, "Reserved" }, { EM_res156, "Reserved" }, { EM_res157, "Reserved" }, { EM_res158, "Reserved" }, { EM_res159, "Reserved" }, { EM_MMDSP_PLUS, "STMicroelectronics 64bit VLIW Data Signal Processor" }, { EM_CYPRESS_M8C, "Cypress M8C microprocessor" }, { EM_R32C, "Renesas R32C series microprocessors" }, { EM_TRIMEDIA, "NXP Semiconductors TriMedia architecture family" }, { EM_QDSP6, "QUALCOMM DSP6 Processor" }, { EM_8051, "Intel 8051 and variants" }, { EM_STXP7X, "STMicroelectronics STxP7x family" }, { EM_NDS32, "Andes Technology compact code size embedded RISC processor family" }, { EM_ECOG1, "Cyan Technology eCOG1X family" }, { EM_ECOG1X, "Cyan Technology eCOG1X family" }, { EM_MAXQ30, "Dallas Semiconductor MAXQ30 Core Micro-controllers" }, { EM_XIMO16, "New Japan Radio (NJR) 16-bit DSP Processor" }, { EM_MANIK, "M2000 Reconfigurable RISC Microprocessor" }, { EM_CRAYNV2, "Cray Inc. NV2 vector architecture" }, { EM_RX, "Renesas RX family" }, { EM_METAG, "Imagination Technologies META processor architecture" }, { EM_MCST_ELBRUS, "MCST Elbrus general purpose hardware architecture" }, { EM_ECOG16, "Cyan Technology eCOG16 family" }, { EM_CR16, "National Semiconductor CompactRISC 16-bit processor" }, { EM_ETPU, "Freescale Extended Time Processing Unit" }, { EM_SLE9X, "Infineon Technologies SLE9X core" }, { EM_L1OM, "Intel L1OM" }, { EM_INTEL181, "Reserved by Intel" }, { EM_INTEL182, "Reserved by Intel" }, { EM_res183, "Reserved by ARM" }, { EM_res184, "Reserved by ARM" }, { EM_AVR32, "Atmel Corporation 32-bit microprocessor family" }, { EM_STM8, "STMicroeletronics STM8 8-bit microcontroller" }, { EM_TILE64, "Tilera TILE64 multicore architecture family" }, { EM_TILEPRO, "Tilera TILEPro multicore architecture family" }, { EM_MICROBLAZE, "Xilinx MicroBlaze 32-bit RISC soft processor core" }, { EM_CUDA, "NVIDIA CUDA architecture " }, }; static struct section_type_table_t { const Elf64_Half key; const char* str; } section_type_table[] = { { SHT_NULL, "NULL" }, { SHT_PROGBITS, "PROGBITS" }, { SHT_SYMTAB, "SYMTAB" }, { SHT_STRTAB, "STRTAB" }, { SHT_RELA, "RELA" }, { SHT_HASH, "HASH" }, { SHT_DYNAMIC, "DYNAMIC" }, { SHT_NOTE, "NOTE" }, { SHT_NOBITS, "NOBITS" }, { SHT_REL, "REL" }, { SHT_SHLIB, "SHLIB" }, { SHT_DYNSYM, "DYNSYM" }, { SHT_INIT_ARRAY, "INIT_ARRAY" }, { SHT_FINI_ARRAY, "FINI_ARRAY" }, { SHT_PREINIT_ARRAY, "PREINIT_ARRAY" }, { SHT_GROUP, "GROUP" }, { SHT_SYMTAB_SHNDX, "SYMTAB_SHNDX " }, }; static struct segment_type_table_t { const Elf_Word key; const char* str; } segment_type_table[] = { { PT_NULL, "NULL" }, { PT_LOAD, "LOAD" }, { PT_DYNAMIC, "DYNAMIC" }, { PT_INTERP, "INTERP" }, { PT_NOTE, "NOTE" }, { PT_SHLIB, "SHLIB" }, { PT_PHDR, "PHDR" }, { PT_TLS, "TLS" }, }; static struct segment_flag_table_t { const Elf_Word key; const char* str; } segment_flag_table[] = { { 0, "" }, { 1, "X" }, { 2, "W" }, { 3, "WX" }, { 4, "R" }, { 5, "RX" }, { 6, "RW" }, { 7, "RWX" }, }; static struct symbol_bind_t { const Elf_Word key; const char* str; } symbol_bind_table[] = { { STB_LOCAL, "LOCAL" }, { STB_GLOBAL, "GLOBAL" }, { STB_WEAK, "WEAK" }, { STB_LOOS, "LOOS" }, { STB_HIOS, "HIOS" }, { STB_MULTIDEF, "MULTIDEF" }, { STB_LOPROC, "LOPROC" }, { STB_HIPROC, "HIPROC" }, }; static struct symbol_type_t { const Elf_Word key; const char* str; } symbol_type_table[] = { { STT_NOTYPE, "NOTYPE" }, { STT_OBJECT, "OBJECT" }, { STT_FUNC, "FUNC" }, { STT_SECTION, "SECTION" }, { STT_FILE, "FILE" }, { STT_COMMON, "COMMON" }, { STT_TLS, "TLS" }, { STT_LOOS, "LOOS" }, { STT_HIOS, "HIOS" }, { STT_LOPROC, "LOPROC" }, { STT_HIPROC, "HIPROC" }, }; static struct dynamic_tag_t { const Elf_Word key; const char* str; } dynamic_tag_table[] = { { DT_NULL, "NULL" }, { DT_NEEDED, "NEEDED" }, { DT_PLTRELSZ, "PLTRELSZ" }, { DT_PLTGOT, "PLTGOT" }, { DT_HASH, "HASH" }, { DT_STRTAB, "STRTAB" }, { DT_SYMTAB, "SYMTAB" }, { DT_RELA, "RELA" }, { DT_RELASZ, "RELASZ" }, { DT_RELAENT, "RELAENT" }, { DT_STRSZ, "STRSZ" }, { DT_SYMENT, "SYMENT" }, { DT_INIT, "INIT" }, { DT_FINI, "FINI" }, { DT_SONAME, "SONAME" }, { DT_RPATH, "RPATH" }, { DT_SYMBOLIC, "SYMBOLIC" }, { DT_REL, "REL" }, { DT_RELSZ, "RELSZ" }, { DT_RELENT, "RELENT" }, { DT_PLTREL, "PLTREL" }, { DT_DEBUG, "DEBUG" }, { DT_TEXTREL, "TEXTREL" }, { DT_JMPREL, "JMPREL" }, { DT_BIND_NOW, "BIND_NOW" }, { DT_INIT_ARRAY, "INIT_ARRAY" }, { DT_FINI_ARRAY, "FINI_ARRAY" }, { DT_INIT_ARRAYSZ, "INIT_ARRAYSZ" }, { DT_FINI_ARRAYSZ, "FINI_ARRAYSZ" }, { DT_RUNPATH, "RUNPATH" }, { DT_FLAGS, "FLAGS" }, { DT_ENCODING, "ENCODING" }, { DT_PREINIT_ARRAY, "PREINIT_ARRAY" }, { DT_PREINIT_ARRAYSZ, "PREINIT_ARRAYSZ" }, { DT_MAXPOSTAGS, "MAXPOSTAGS" }, }; static const ELFIO::Elf_Xword MAX_DATA_ENTRIES = 64; //------------------------------------------------------------------------------ class dump { #define DUMP_DEC_FORMAT( width ) \ std::setw( width ) << std::setfill( ' ' ) << std::dec << std::right #define DUMP_HEX_FORMAT( width ) \ std::setw( width ) << std::setfill( '0' ) << std::hex << std::right #define DUMP_STR_FORMAT( width ) \ std::setw( width ) << std::setfill( ' ' ) << std::hex << std::left public: //------------------------------------------------------------------------------ static void header( std::ostream& out, const elfio& reader ) { if ( !reader.get_header_size() ) { return; } out << "ELF Header" << std::endl << std::endl << " Class: " << str_class( reader.get_class() ) << std::endl << " Encoding: " << str_endian( reader.get_encoding() ) << std::endl << " ELFVersion: " << str_version( reader.get_elf_version() ) << std::endl << " Type: " << str_type( reader.get_type() ) << std::endl << " Machine: " << str_machine( reader.get_machine() ) << std::endl << " Version: " << str_version( reader.get_version() ) << std::endl << " Entry: " << "0x" << std::hex << reader.get_entry() << std::endl << " Flags: " << "0x" << std::hex << reader.get_flags() << std::endl << std::endl; } //------------------------------------------------------------------------------ static void section_headers( std::ostream& out, const elfio& reader ) { Elf_Half n = reader.sections.size(); if ( n == 0 ) { return; } out << "Section Headers:" << std::endl; if ( reader.get_class() == ELFCLASS32 ) { // Output for 32-bit out << "[ Nr ] Type Addr Size ES Flg Lk Inf " "Al Name" << std::endl; } else { // Output for 64-bit out << "[ Nr ] Type Addr Size " " ES Flg" << std::endl << " Lk Inf Al Name" << std::endl; } for ( Elf_Half i = 0; i < n; ++i ) { // For all sections section* sec = reader.sections[i]; section_header( out, i, sec, reader.get_class() ); } out << "Key to Flags: W (write), A (alloc), X (execute)\n\n" << std::endl; } //------------------------------------------------------------------------------ static void section_header( std::ostream& out, Elf_Half no, const section* sec, unsigned char elf_class ) { std::ios_base::fmtflags original_flags = out.flags(); if ( elf_class == ELFCLASS32 ) { // Output for 32-bit out << "[" << DUMP_DEC_FORMAT( 5 ) << no << "] " << DUMP_STR_FORMAT( 17 ) << str_section_type( sec->get_type() ) << " " << DUMP_HEX_FORMAT( 8 ) << sec->get_address() << " " << DUMP_HEX_FORMAT( 8 ) << sec->get_size() << " " << DUMP_HEX_FORMAT( 2 ) << sec->get_entry_size() << " " << DUMP_STR_FORMAT( 3 ) << section_flags( sec->get_flags() ) << " " << DUMP_HEX_FORMAT( 2 ) << sec->get_link() << " " << DUMP_HEX_FORMAT( 3 ) << sec->get_info() << " " << DUMP_HEX_FORMAT( 2 ) << sec->get_addr_align() << " " << DUMP_STR_FORMAT( 17 ) << sec->get_name() << " " << std::endl; } else { // Output for 64-bit out << "[" << DUMP_DEC_FORMAT( 5 ) << no << "] " << DUMP_STR_FORMAT( 17 ) << str_section_type( sec->get_type() ) << " " << DUMP_HEX_FORMAT( 16 ) << sec->get_address() << " " << DUMP_HEX_FORMAT( 16 ) << sec->get_size() << " " << DUMP_HEX_FORMAT( 4 ) << sec->get_entry_size() << " " << DUMP_STR_FORMAT( 3 ) << section_flags( sec->get_flags() ) << " " << std::endl << " " << DUMP_HEX_FORMAT( 4 ) << sec->get_link() << " " << DUMP_HEX_FORMAT( 4 ) << sec->get_info() << " " << DUMP_HEX_FORMAT( 4 ) << sec->get_addr_align() << " " << DUMP_STR_FORMAT( 17 ) << sec->get_name() << " " << std::endl; } out.flags( original_flags ); return; } //------------------------------------------------------------------------------ static void segment_headers( std::ostream& out, const elfio& reader ) { Elf_Half n = reader.segments.size(); if ( n == 0 ) { return; } out << "Segment headers:" << std::endl; if ( reader.get_class() == ELFCLASS32 ) { // Output for 32-bit out << "[ Nr ] Type VirtAddr PhysAddr FileSize Mem.Size " "Flags Align" << std::endl; } else { // Output for 64-bit out << "[ Nr ] Type VirtAddr PhysAddr " "Flags" << std::endl << " FileSize Mem.Size " "Align" << std::endl; } for ( Elf_Half i = 0; i < n; ++i ) { segment* seg = reader.segments[i]; segment_header( out, i, seg, reader.get_class() ); } out << std::endl; } //------------------------------------------------------------------------------ static void segment_header( std::ostream& out, Elf_Half no, const segment* seg, unsigned int elf_class ) { std::ios_base::fmtflags original_flags = out.flags(); if ( elf_class == ELFCLASS32 ) { // Output for 32-bit out << "[" << DUMP_DEC_FORMAT( 5 ) << no << "] " << DUMP_STR_FORMAT( 14 ) << str_segment_type( seg->get_type() ) << " " << DUMP_HEX_FORMAT( 8 ) << seg->get_virtual_address() << " " << DUMP_HEX_FORMAT( 8 ) << seg->get_physical_address() << " " << DUMP_HEX_FORMAT( 8 ) << seg->get_file_size() << " " << DUMP_HEX_FORMAT( 8 ) << seg->get_memory_size() << " " << DUMP_STR_FORMAT( 8 ) << str_segment_flag( seg->get_flags() ) << " " << DUMP_HEX_FORMAT( 8 ) << seg->get_align() << " " << std::endl; } else { // Output for 64-bit out << "[" << DUMP_DEC_FORMAT( 5 ) << no << "] " << DUMP_STR_FORMAT( 14 ) << str_segment_type( seg->get_type() ) << " " << DUMP_HEX_FORMAT( 16 ) << seg->get_virtual_address() << " " << DUMP_HEX_FORMAT( 16 ) << seg->get_physical_address() << " " << DUMP_STR_FORMAT( 16 ) << str_segment_flag( seg->get_flags() ) << " " << std::endl << " " << DUMP_HEX_FORMAT( 16 ) << seg->get_file_size() << " " << DUMP_HEX_FORMAT( 16 ) << seg->get_memory_size() << " " << DUMP_HEX_FORMAT( 16 ) << seg->get_align() << " " << std::endl; } out.flags( original_flags ); } //------------------------------------------------------------------------------ static void symbol_tables( std::ostream& out, const elfio& reader ) { Elf_Half n = reader.sections.size(); for ( Elf_Half i = 0; i < n; ++i ) { // For all sections section* sec = reader.sections[i]; if ( SHT_SYMTAB == sec->get_type() || SHT_DYNSYM == sec->get_type() ) { symbol_section_accessor symbols( reader, sec ); Elf_Xword sym_no = symbols.get_symbols_num(); if ( sym_no > 0 ) { out << "Symbol table (" << sec->get_name() << ")" << std::endl; if ( reader.get_class() == ELFCLASS32 ) { // Output for 32-bit out << "[ Nr ] Value Size Type Bind " "Sect Name" << std::endl; } else { // Output for 64-bit out << "[ Nr ] Value Size Type " " Bind Sect" << std::endl << " Name" << std::endl; } for ( Elf_Xword i = 0; i < sym_no; ++i ) { std::string name; Elf64_Addr value = 0; Elf_Xword size = 0; unsigned char bind = 0; unsigned char type = 0; Elf_Half section = 0; unsigned char other = 0; symbols.get_symbol( i, name, value, size, bind, type, section, other ); symbol_table( out, i, name, value, size, bind, type, section, reader.get_class() ); } out << std::endl; } } } } //------------------------------------------------------------------------------ static void symbol_table( std::ostream& out, Elf_Xword no, std::string& name, Elf64_Addr value, Elf_Xword size, unsigned char bind, unsigned char type, Elf_Half section, unsigned int elf_class ) { std::ios_base::fmtflags original_flags = out.flags(); if ( elf_class == ELFCLASS32 ) { // Output for 32-bit out << "[" << DUMP_DEC_FORMAT( 5 ) << no << "] " << DUMP_HEX_FORMAT( 8 ) << value << " " << DUMP_HEX_FORMAT( 8 ) << size << " " << DUMP_STR_FORMAT( 7 ) << str_symbol_type( type ) << " " << DUMP_STR_FORMAT( 8 ) << str_symbol_bind( bind ) << " " << DUMP_DEC_FORMAT( 5 ) << section << " " << DUMP_STR_FORMAT( 1 ) << name << " " << std::endl; } else { // Output for 64-bit out << "[" << DUMP_DEC_FORMAT( 5 ) << no << "] " << DUMP_HEX_FORMAT( 16 ) << value << " " << DUMP_HEX_FORMAT( 16 ) << size << " " << DUMP_STR_FORMAT( 7 ) << str_symbol_type( type ) << " " << DUMP_STR_FORMAT( 8 ) << str_symbol_bind( bind ) << " " << DUMP_DEC_FORMAT( 5 ) << section << " " << std::endl << " " << DUMP_STR_FORMAT( 1 ) << name << " " << std::endl; } out.flags( original_flags ); } //------------------------------------------------------------------------------ static void notes( std::ostream& out, const elfio& reader ) { Elf_Half no = reader.sections.size(); for ( Elf_Half i = 0; i < no; ++i ) { // For all sections section* sec = reader.sections[i]; if ( SHT_NOTE == sec->get_type() ) { // Look at notes note_section_accessor notes( reader, sec ); Elf_Word no_notes = notes.get_notes_num(); if ( no > 0 ) { out << "Note section (" << sec->get_name() << ")" << std::endl << " No Type Name" << std::endl; for ( Elf_Word j = 0; j < no_notes; ++j ) { // For all notes Elf_Word type; std::string name; void* desc; Elf_Word descsz; if ( notes.get_note( j, type, name, desc, descsz ) ) { // 'name' usually contains \0 at the end. Try to fix it name = name.c_str(); note( out, j, type, name ); } } out << std::endl; } } } } //------------------------------------------------------------------------------ static void modinfo( std::ostream& out, const elfio& reader ) { Elf_Half no = reader.sections.size(); for ( Elf_Half i = 0; i < no; ++i ) { // For all sections section* sec = reader.sections[i]; if ( ".modinfo" == sec->get_name() ) { // Look for the section out << "Section .modinfo" << std::endl; const_modinfo_section_accessor modinfo( sec ); for ( Elf_Word i = 0; i < modinfo.get_attribute_num(); i++ ) { std::string field; std::string value; if ( modinfo.get_attribute( i, field, value ) ) { out << " " << std::setw( 20 ) << field << std::setw( 0 ) << " = " << value << std::endl; } } out << std::endl; break; } } } //------------------------------------------------------------------------------ static void note( std::ostream& out, int no, Elf_Word type, const std::string& name ) { out << " [" << DUMP_DEC_FORMAT( 2 ) << no << "] " << DUMP_HEX_FORMAT( 8 ) << type << " " << DUMP_STR_FORMAT( 1 ) << name << std::endl; } //------------------------------------------------------------------------------ static void dynamic_tags( std::ostream& out, const elfio& reader ) { Elf_Half n = reader.sections.size(); for ( Elf_Half i = 0; i < n; ++i ) { // For all sections section* sec = reader.sections[i]; if ( SHT_DYNAMIC == sec->get_type() ) { dynamic_section_accessor dynamic( reader, sec ); Elf_Xword dyn_no = dynamic.get_entries_num(); if ( dyn_no > 0 ) { out << "Dynamic section (" << sec->get_name() << ")" << std::endl; out << "[ Nr ] Tag Name/Value" << std::endl; for ( Elf_Xword i = 0; i < dyn_no; ++i ) { Elf_Xword tag = 0; Elf_Xword value = 0; std::string str; dynamic.get_entry( i, tag, value, str ); dynamic_tag( out, i, tag, value, str, reader.get_class() ); if ( DT_NULL == tag ) { break; } } out << std::endl; } } } } //------------------------------------------------------------------------------ static void dynamic_tag( std::ostream& out, Elf_Xword no, Elf_Xword tag, Elf_Xword value, std::string str, unsigned int /*elf_class*/ ) { out << "[" << DUMP_DEC_FORMAT( 5 ) << no << "] " << DUMP_STR_FORMAT( 16 ) << str_dynamic_tag( tag ) << " "; if ( str.empty() ) { out << DUMP_HEX_FORMAT( 16 ) << value << " "; } else { out << DUMP_STR_FORMAT( 32 ) << str << " "; } out << std::endl; } //------------------------------------------------------------------------------ static void section_data( std::ostream& out, const section* sec ) { std::ios_base::fmtflags original_flags = out.flags(); out << sec->get_name() << std::endl; const char* pdata = sec->get_data(); if ( pdata ) { ELFIO::Elf_Xword i; for ( i = 0; i < std::min( sec->get_size(), MAX_DATA_ENTRIES ); ++i ) { if ( i % 16 == 0 ) { out << "[" << DUMP_HEX_FORMAT( 8 ) << i << "]"; } out << " " << DUMP_HEX_FORMAT( 2 ) << ( pdata[i] & 0x000000FF ); if ( i % 16 == 15 ) { out << std::endl; } } if ( i % 16 != 0 ) { out << std::endl; } out.flags( original_flags ); } return; } //------------------------------------------------------------------------------ static void section_datas( std::ostream& out, const elfio& reader ) { Elf_Half n = reader.sections.size(); if ( n == 0 ) { return; } out << "Section Data:" << std::endl; for ( Elf_Half i = 1; i < n; ++i ) { // For all sections section* sec = reader.sections[i]; if ( sec->get_type() == SHT_NOBITS ) { continue; } section_data( out, sec ); } out << std::endl; } //------------------------------------------------------------------------------ static void segment_data( std::ostream& out, Elf_Half no, const segment* seg ) { std::ios_base::fmtflags original_flags = out.flags(); out << "Segment # " << no << std::endl; const char* pdata = seg->get_data(); if ( pdata ) { ELFIO::Elf_Xword i; for ( i = 0; i < std::min( seg->get_file_size(), MAX_DATA_ENTRIES ); ++i ) { if ( i % 16 == 0 ) { out << "[" << DUMP_HEX_FORMAT( 8 ) << i << "]"; } out << " " << DUMP_HEX_FORMAT( 2 ) << ( pdata[i] & 0x000000FF ); if ( i % 16 == 15 ) { out << std::endl; } } if ( i % 16 != 0 ) { out << std::endl; } out.flags( original_flags ); } return; } //------------------------------------------------------------------------------ static void segment_datas( std::ostream& out, const elfio& reader ) { Elf_Half n = reader.segments.size(); if ( n == 0 ) { return; } out << "Segment Data:" << std::endl; for ( Elf_Half i = 0; i < n; ++i ) { // For all sections segment* seg = reader.segments[i]; segment_data( out, i, seg ); } out << std::endl; } private: //------------------------------------------------------------------------------ template std::string static find_value_in_table( const T& table, const K& key ) { std::string res = "?"; for ( unsigned int i = 0; i < sizeof( table ) / sizeof( table[0] ); ++i ) { if ( table[i].key == key ) { res = table[i].str; break; } } return res; } //------------------------------------------------------------------------------ template static std::string format_assoc( const T& table, const K& key ) { std::string str = find_value_in_table( table, key ); if ( str == "?" ) { std::ostringstream oss; oss << str << " (0x" << std::hex << key << ")"; str = oss.str(); } return str; } //------------------------------------------------------------------------------ template static std::string format_assoc( const T& table, const char key ) { return format_assoc( table, (const int)key ); } //------------------------------------------------------------------------------ static std::string section_flags( Elf_Xword flags ) { std::string ret = ""; if ( flags & SHF_WRITE ) { ret += "W"; } if ( flags & SHF_ALLOC ) { ret += "A"; } if ( flags & SHF_EXECINSTR ) { ret += "X"; } return ret; } //------------------------------------------------------------------------------ #define STR_FUNC_TABLE( name ) \ template static std::string str_##name( const T key ) \ { \ return format_assoc( name##_table, key ); \ } STR_FUNC_TABLE( class ) STR_FUNC_TABLE( endian ) STR_FUNC_TABLE( version ) STR_FUNC_TABLE( type ) STR_FUNC_TABLE( machine ) STR_FUNC_TABLE( section_type ) STR_FUNC_TABLE( segment_type ) STR_FUNC_TABLE( segment_flag ) STR_FUNC_TABLE( symbol_bind ) STR_FUNC_TABLE( symbol_type ) STR_FUNC_TABLE( dynamic_tag ) #undef STR_FUNC_TABLE #undef DUMP_DEC_FORMAT #undef DUMP_HEX_FORMAT #undef DUMP_STR_FORMAT }; // class dump }; // namespace ELFIO #endif // ELFIO_DUMP_HPP /*** End of inlined file: elfio_dump.hpp ***/ kylin-nm-plugin/autotests/kt-test-utils/cpp-stub/stub.h0000664000175000017500000002556215167660365022232 0ustar fengfeng/* * MIT License * * Copyright (c) 2019 coolxv * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef __STUB_H__ #define __STUB_H__ #ifdef _WIN32 //windows #include #include #else //linux #include #include #include #endif //c #include #include //c++ #include #define ADDR(CLASS_NAME,MEMBER_NAME) (&CLASS_NAME::MEMBER_NAME) /********************************************************** replace function **********************************************************/ #ifdef _WIN32 #define CACHEFLUSH(addr, size) FlushInstructionCache(GetCurrentProcess(), addr, size) #else #define CACHEFLUSH(addr, size) __builtin___clear_cache(addr, addr + size) #endif #if defined(__aarch64__) || defined(_M_ARM64) #define CODESIZE 16U #define CODESIZE_MIN 16U #define CODESIZE_MAX CODESIZE // ldr x9, +8 // br x9 // addr #define REPLACE_FAR(t, fn, fn_stub)\ ((uint32_t*)fn)[0] = 0x58000040 | 9;\ ((uint32_t*)fn)[1] = 0xd61f0120 | (9 << 5);\ *(long long *)(fn + 8) = (long long )fn_stub;\ CACHEFLUSH((char *)fn, CODESIZE); #define REPLACE_NEAR(t, fn, fn_stub) REPLACE_FAR(t, fn, fn_stub) #elif defined(__arm__) || defined(_M_ARM) #define CODESIZE 8U #define CODESIZE_MIN 8U #define CODESIZE_MAX CODESIZE // ldr pc, [pc, #-4] #define REPLACE_FAR(t, fn, fn_stub)\ ((uint32_t*)fn)[0] = 0xe51ff004;\ ((uint32_t*)fn)[1] = (uint32_t)fn_stub;\ CACHEFLUSH((char *)fn, CODESIZE); #define REPLACE_NEAR(t, fn, fn_stub) REPLACE_FAR(t, fn, fn_stub) #elif defined(__mips64) #define CACHEFLUSH(addr, size) __builtin___clear_cache(addr, addr + size) #define CODESIZE 80U #define CODESIZE_MIN 80U #define CODESIZE_MAX CODESIZE //mips没有PC指针,所以需要手动入栈出栈 //120000ce0: 67bdffe0 daddiu sp, sp, -32 //入栈 //120000ce4: ffbf0018 sd ra, 24(sp) //120000ce8: ffbe0010 sd s8, 16(sp) //120000cec: ffbc0008 sd gp, 8(sp) //120000cf0: 03a0f025 move s8, sp //120000d2c: 03c0e825 move sp, s8 //出栈 //120000d30: dfbf0018 ld ra, 24(sp) //120000d34: dfbe0010 ld s8, 16(sp) //120000d38: dfbc0008 ld gp, 8(sp) //120000d3c: 67bd0020 daddiu sp, sp, 32 //120000d40: 03e00008 jr ra #define REPLACE_FAR(t, fn, fn_stub)\ ((uint32_t *)fn)[0] = 0x67bdffe0;\ ((uint32_t *)fn)[1] = 0xffbf0018;\ ((uint32_t *)fn)[2] = 0xffbe0010;\ ((uint32_t *)fn)[3] = 0xffbc0008;\ ((uint32_t *)fn)[4] = 0x03a0f025;\ *(uint16_t *)(fn + 20) = (long long)fn_stub >> 32;\ *(fn + 22) = 0x19;\ *(fn + 23) = 0x24;\ ((uint32_t *)fn)[6] = 0x0019cc38;\ *(uint16_t *)(fn + 28) = (long long)fn_stub >> 16;\ *(fn + 30) = 0x39;\ *(fn + 31) = 0x37;\ ((uint32_t *)fn)[8] = 0x0019cc38;\ *(uint16_t *)(fn + 36) = (long long)fn_stub;\ *(fn + 38) = 0x39;\ *(fn + 39) = 0x37;\ ((uint32_t *)fn)[10] = 0x0320f809;\ ((uint32_t *)fn)[11] = 0x00000000;\ ((uint32_t *)fn)[12] = 0x00000000;\ ((uint32_t *)fn)[13] = 0x03c0e825;\ ((uint32_t *)fn)[14] = 0xdfbf0018;\ ((uint32_t *)fn)[15] = 0xdfbe0010;\ ((uint32_t *)fn)[16] = 0xdfbc0008;\ ((uint32_t *)fn)[17] = 0x67bd0020;\ ((uint32_t *)fn)[18] = 0x03e00008;\ ((uint32_t *)fn)[19] = 0x00000000;\ CACHEFLUSH((char *)fn, CODESIZE); #define REPLACE_NEAR(t, fn, fn_stub) REPLACE_FAR(t, fn, fn_stub) #elif defined(__thumb__) || defined(_M_THUMB) #error "Thumb is not supported" #else //__i386__ _x86_64__ #define CODESIZE 13U #define CODESIZE_MIN 5U #define CODESIZE_MAX CODESIZE //13 byte(jmp m16:64) //movabs $0x102030405060708,%r11 //jmpq *%r11 static void REPLACE_FAR(void *t, char *fn, char *fn_stub) { *fn = 0x49; *(fn + 1) = 0xbb; *(long long *)(fn + 2) = (long long)fn_stub; *(fn + 10) = 0x41; *(fn + 11) = 0xff; *(fn + 12) = 0xe3; CACHEFLUSH((char *)fn, CODESIZE); } //5 byte(jmp rel32) #define REPLACE_NEAR(t, fn, fn_stub)\ *fn = 0xE9;\ *(int *)(fn + 1) = (int)(fn_stub - fn - CODESIZE_MIN);\ CACHEFLUSH((char *)fn, CODESIZE); #endif struct func_stub { char *fn; unsigned char code_buf[CODESIZE]; bool far_jmp; }; class Stub { public: Stub() { #ifdef _WIN32 SYSTEM_INFO sys_info; GetSystemInfo(&sys_info); m_pagesize = sys_info.dwPageSize; #else m_pagesize = sysconf(_SC_PAGE_SIZE); #endif if (m_pagesize < 0) { m_pagesize = 4096; } } ~Stub() { clear(); } virtual void clear() { std::map::iterator iter; struct func_stub *pstub; for(iter=m_result.begin(); iter != m_result.end(); iter++) { pstub = iter->second; #ifdef _WIN32 DWORD lpflOldProtect; if(0 != VirtualProtect(pageof(pstub->fn), m_pagesize * 2, PAGE_EXECUTE_READWRITE, &lpflOldProtect)) #else if (0 == mprotect(pageof(pstub->fn), m_pagesize * 2, PROT_READ | PROT_WRITE | PROT_EXEC)) #endif { if(pstub->far_jmp) { std::memcpy(pstub->fn, pstub->code_buf, CODESIZE_MAX); } else { std::memcpy(pstub->fn, pstub->code_buf, CODESIZE_MIN); } #ifdef _WIN32 VirtualProtect(pageof(pstub->fn), m_pagesize * 2, PAGE_EXECUTE_READ, &lpflOldProtect); #else CACHEFLUSH(pstub->fn,CODESIZE); mprotect(pageof(pstub->fn), m_pagesize * 2, PROT_READ | PROT_EXEC); #endif } iter->second = NULL; delete pstub; } m_result.clear(); return; } template bool set(T addr, S addr_stub) { char * fn; char * fn_stub; fn = addrof(addr); fn_stub = addrof(addr_stub); struct func_stub *pstub; std::map::iterator iter = m_result.find(fn); if (iter == m_result.end()) { pstub = new func_stub; //start pstub->fn = fn; if(distanceof(fn, fn_stub)) { pstub->far_jmp = true; std::memcpy(pstub->code_buf, fn, CODESIZE_MAX); } else { pstub->far_jmp = false; std::memcpy(pstub->code_buf, fn, CODESIZE_MIN); } } else { pstub = iter->second; pstub->far_jmp = distanceof(fn, fn_stub); } #ifdef _WIN32 DWORD lpflOldProtect; if(0 == VirtualProtect(pageof(pstub->fn), m_pagesize * 2, PAGE_EXECUTE_READWRITE, &lpflOldProtect)) #else if (-1 == mprotect(pageof(pstub->fn), static_cast(m_pagesize * 2), PROT_READ | PROT_WRITE | PROT_EXEC)) #endif { throw("stub set memory protect to w+r+x faild"); return false; } if(pstub->far_jmp) { REPLACE_FAR(this, fn, fn_stub); } else { REPLACE_NEAR(this, fn, fn_stub); } #ifdef _WIN32 if(0 == VirtualProtect(pageof(pstub->fn), m_pagesize * 2, PAGE_EXECUTE_READ, &lpflOldProtect)) #else if (-1 == mprotect(pageof(pstub->fn), m_pagesize * 2, PROT_READ | PROT_EXEC)) #endif { throw("stub set memory protect to r+x failed"); return false; } m_result.insert(std::pair(fn,pstub)); return true; } template bool reset(T addr) { char * fn; fn = addrof(addr); std::map::iterator iter = m_result.find(fn); if (iter == m_result.end()) { return true; } struct func_stub *pstub; pstub = iter->second; #ifdef _WIN32 DWORD lpflOldProtect; if(0 == VirtualProtect(pageof(pstub->fn), m_pagesize * 2, PAGE_EXECUTE_READWRITE, &lpflOldProtect)) #else if (-1 == mprotect(pageof(pstub->fn), m_pagesize * 2, PROT_READ | PROT_WRITE | PROT_EXEC)) #endif { throw("stub reset memory protect to w+r+x faild"); return false; } if(pstub->far_jmp) { std::memcpy(pstub->fn, pstub->code_buf, CODESIZE_MAX); } else { std::memcpy(pstub->fn, pstub->code_buf, CODESIZE_MIN); } #ifdef _WIN32 if(0 == VirtualProtect(pageof(pstub->fn), m_pagesize * 2, PAGE_EXECUTE_READ, &lpflOldProtect)) #else CACHEFLUSH(pstub->fn,CODESIZE); if (-1 == mprotect(pageof(pstub->fn), m_pagesize * 2, PROT_READ | PROT_EXEC)) #endif { throw("stub reset memory protect to r+x failed"); return false; } m_result.erase(iter); delete pstub; return true; } protected: char *pageof(char* addr) { #ifdef _WIN32 return (char *)((unsigned long long)addr & ~(m_pagesize - 1)); #else return (char *)((unsigned long)addr & ~(m_pagesize - 1)); #endif } template char* addrof(T addr) { union { T _s; char* _d; }ut; ut._s = addr; return ut._d; } bool distanceof(char* addr, char* addr_stub) { std::ptrdiff_t diff = addr_stub >= addr ? addr_stub - addr : addr - addr_stub; if((sizeof(addr) > 4) && (((diff >> 31) - 1) > 0)) { return true; } return false; } protected: #ifdef _WIN32 //LLP64 long long m_pagesize; #else //LP64 long m_pagesize; #endif std::map m_result; }; #endif kylin-nm-plugin/autotests/kt-test-utils/cpp-stub-ext/0000775000175000017500000000000015160520531021647 5ustar fengfengkylin-nm-plugin/autotests/kt-test-utils/cpp-stub-ext/stubext.h0000664000175000017500000000734115160520531023523 0ustar fengfeng #ifndef STUBEXT_H #define STUBEXT_H /* * Author: Zhang Yu * Maintainer: Zhang Yu * * MIT License * * Copyright (c) 2020 Zhang Yu * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ //需修改Stub的私用成员函数和成员变量为保护类型 #include "stub.h" #include "stub-shadow.h" #ifdef DEBUG_STUB_INVOKE // use to make sure the stub function is invoked. # define __DBG_STUB_INVOKE__ printf("stub at %s:%d is invoked.\n", __FILE__, __LINE__); #else # define __DBG_STUB_INVOKE__ #endif #define VADDR(CLASS_NAME, MEMBER_NAME) (typename stub_ext::VFLocator::Func)(&CLASS_NAME::MEMBER_NAME) namespace stub_ext { class StubExt : public Stub { public: StubExt() : Stub() { } template bool set_lamda(T addr, Lamda lamda) { char *fn = addrof(addr); if (m_result.find(fn) != m_result.end()) reset(addr); Wrapper *wrapper = nullptr; auto addr_stub = depictShadow(&wrapper, addr, lamda); if (set(addr, addr_stub)) { m_wrappers.insert(std::make_pair(fn, wrapper)); return true; } else { freeWrapper(wrapper); } return false; } template void reset(T addr) { Stub::reset(addr); char *fn = addrof(addr); auto iter = m_wrappers.find(fn); if (iter != m_wrappers.end()) { freeWrapper(iter->second); m_wrappers.erase(iter); } } ~StubExt() { clear(); } void clear() override { Stub::clear(); for (auto iter = m_wrappers.begin(); iter != m_wrappers.end(); ++iter) { freeWrapper(iter->second); } m_wrappers.clear(); } template static void *get_ctor_addr(bool start = true) { // the start vairable must be true, or the compiler will optimize out. if (start) goto Start; Call_Constructor: // This line of code will not be executed. // The purpose of the code is to allow the compiler to generate the assembly code that calls the constructor. T(); Start: // The address of the line of code T() obtained by assembly char *p = (char *)&&Call_Constructor; // https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html // CALL rel32 void *ret = 0; char pos; char call = 0xe8; do { pos = *p; if (pos == call) { ret = p + 5 + (*(int *)(p + 1)); } } while (!ret && (++p)); return ret; } protected: std::map m_wrappers; }; } #endif // STUBEXT_H kylin-nm-plugin/autotests/kt-test-utils/cpp-stub-ext/stub-shadow.cpp0000664000175000017500000000314715160520531024620 0ustar fengfeng/* * Author: Zhang Yu * Maintainer: Zhang Yu * * MIT License * * Copyright (c) 2020 Zhang Yu * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "stub-shadow.h" namespace stub_ext { WrapperMap stub_wrappers; Wrapper::Wrapper() { } Wrapper::~Wrapper() { } void freeWrapper(Wrapper *wrapper) { if (!wrapper) return; for (auto iter = stub_wrappers.begin(); iter != stub_wrappers.end();) { if (iter->second == wrapper) iter = stub_wrappers.erase(iter); else ++iter; } delete wrapper; } } kylin-nm-plugin/autotests/kt-test-utils/cpp-stub-ext/stub-shadow.h0000664000175000017500000001143415160520531024263 0ustar fengfeng #ifndef STUBSHADOW_H #define STUBSHADOW_H /* * Author: Zhang Yu * Maintainer: Zhang Yu * * MIT License * * Copyright (c) 2020 Zhang Yu * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include #include namespace stub_ext { #define LAMDA_FUNCTION_TYPE decltype(&Lamda::operator()) class Wrapper { public: Wrapper(); virtual ~Wrapper(); }; typedef std::unordered_map WrapperMap; extern WrapperMap stub_wrappers; template class LamdaWrapper : public Wrapper { public: LamdaWrapper(Lamda func): Wrapper(),_func(func){} ~LamdaWrapper(){} Lamda _func; }; template struct VFLocator { }; template struct VFLocator { typedef Ret (*Func)(Obj*, Args...); }; template struct VFLocator { typedef Ret (*Func)(Obj*, Args...); }; template struct LamdaCaller { }; template struct LamdaCaller { template static Ret call(LamdaWrapper *wrapper, OrgArgs&&... args) { return wrapper->_func(std::forward(args)...); } }; template struct LamdaCaller { template static Ret call(LamdaWrapper *wrapper, OrgArgs&&... args) { return wrapper->_func(); } }; template struct FuncShadow { }; template struct FuncShadow { typedef Ret (*Shadow)(Args...); typedef Ret RetType; static Ret call(Args ...args) { Shadow shadow = &call; long id = (long)shadow; auto iter = stub_wrappers.find(id); assert(stub_wrappers.find(id) != stub_wrappers.end()); LamdaWrapper *wrapper = dynamic_cast *>(iter->second); return LamdaCaller::call(wrapper, args...); } }; template struct FuncShadow { typedef Ret (*Shadow)(Obj *,Args...); typedef Ret RetType; static Ret call(Obj *obj, Args ...args) { Shadow shadow = &call; long id = (long)shadow; auto iter = stub_wrappers.find(id); assert(stub_wrappers.find(id) != stub_wrappers.end()); LamdaWrapper *wrapper = dynamic_cast *>(iter->second); return LamdaCaller::call(wrapper, obj, args...); } }; template struct FuncShadow { typedef Ret (*Shadow)(Obj *,Args...); typedef Ret RetType; static Ret call(Obj *obj, Args ...args) { Shadow shadow = &call; long id = (long)shadow; auto iter = stub_wrappers.find(id); assert(stub_wrappers.find(id) != stub_wrappers.end()); LamdaWrapper *wrapper = dynamic_cast *>(iter->second); return LamdaCaller::call(wrapper, obj, args...); } }; template typename FuncShadow::Shadow depictShadow(Wrapper **wrapper, Func func, Lamda lamda) { *wrapper = new LamdaWrapper(lamda); typename FuncShadow::Shadow shadow = &FuncShadow::call; long id = (long)shadow; assert(stub_wrappers.find(id) == stub_wrappers.end()); stub_wrappers.insert(std::make_pair(id,*wrapper)); return shadow; } void freeWrapper(Wrapper *wrapper); } #endif // STUBSHADOW_H kylin-nm-plugin/autotests/auto_test.sh0000664000175000017500000000457215167660365017157 0ustar fengfeng#!/bin/bash # -*- Mode: Shell-script; tab-width: 4; indent-tabs-mode: nil; sh-basic-offset: 4 -*- # # Copyright (C) 2019 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. # # 设置退出脚本当命令失败时 (非零退出状态) #set -e # 函数:运行单元测试 run_unit_tests() { local pattern="unit_test_*" # 遍历所有匹配模式的目录 for dir in $pattern; do if [ -d "$dir" ] && [ -x "$dir/$(basename "$dir")" ]; then echo "Running tests in $dir..." # 执行单元测试 (cd "$dir" && "./$(basename "$dir")") # 收集代码覆盖率数据 echo "Collecting coverage data..." (cd "$dir" && (find ./ -name '*.o' | xargs gcov --preserve-paths)) else echo "Skipping non-existent or non-executable directory: $dir, $dir/$(basename "$dir")" fi done } # 上传 result.zip 到平台 URL=$1 upload_result() { echo "current pwd : $(pwd)" # 收集覆盖率信息 lcov -d . -c -o r.info # 删除不需要的文件或路径 lcov -r r.info "$(pwd)/unit_test_*" "$(pwd)/../registeredSession/universalinterface.cpp" "/usr/include/*" "/opt/*" -o coverage.info # 生成html覆盖率报告 genhtml "$(pwd)/coverage.info" -o result # 打包 zip -r result.zip result # 上传平台 curl --insecure -X POST -F "file=@/$(pwd)/result.zip" -F "package=ukui-control-center" -F "username=hesisheng" $URL echo "all parameter : $@" } # 编译项目 echo "Compiling the project..." qmake . && make # 运行各个单元测试 echo "Running unit tests..." run_unit_tests # 上传到平台 #upload_result echo "All tests have been run successfully, and coverage data has been collected." kylin-nm-plugin/COPYING0000664000175000017500000004310015167633456013603 0ustar fengfeng GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 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, see . Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Moe Ghoul, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. kylin-nm-plugin/libnm-kylin/0000775000175000017500000000000015167664423014775 5ustar fengfengkylin-nm-plugin/libnm-kylin/libnm-icon-kylin/0000775000175000017500000000000015170115272020133 5ustar fengfengkylin-nm-plugin/libnm-kylin/libnm-icon-kylin/translations/0000775000175000017500000000000015167664423022671 5ustar fengfengkylin-nm-plugin/libnm-kylin/libnm-icon-kylin/translations/icon_tr.ts0000664000175000017500000000273315160520531024663 0ustar fengfeng KyNetworkIcon Network tool Network Card Not connected to the network Connected: (Limited) Not Connected kylin-nm-plugin/libnm-kylin/libnm-icon-kylin/translations/icon_zh_CN.ts0000664000175000017500000000270315160520531025234 0ustar fengfeng KyNetworkIcon Network tool 网络工具 Network Card 网卡 Not connected to the network 未连接网络 Connected: 已连接: (Limited) (网络受限) Not Connected 未连接 kylin-nm-plugin/libnm-kylin/libnm-icon-kylin/translations/icon_bo_CN.ts0000664000175000017500000000334015160520531025211 0ustar fengfeng KyNetworkIcon Network tool དྲ་རྒྱའི་ལག་ཆ་ Network Card དྲ་བྱང་། Not connected to the network དྲ་རྒྱ་དང་སྦྲེལ་མཐུད་མ་བྱས་པ། Connected: འབྲེལ་མཐུད་བྱུང་ཡོད།: (Limited) (དྲ་བར་ཚོད་འཛིན་ཐེབས་པ་རེད།) Not Connected འབྲེལ་མཐུད་མ་བྱས་པ། kylin-nm-plugin/libnm-kylin/libnm-icon-kylin/translations/icon_zh_HK.ts0000664000175000017500000000270715160520531025242 0ustar fengfeng KyNetworkIcon Not connected to the network 未連接網路 Network tool 網路工具 Network Card 網卡 Connected: 已連線: (Limited) (網路受限) Not Connected 未連接 kylin-nm-plugin/libnm-kylin/libnm-icon-kylin/translations/icon_bo.ts0000664000175000017500000000273315160520531024636 0ustar fengfeng KyNetworkIcon Network tool Network Card Not connected to the network Connected: (Limited) Not Connected kylin-nm-plugin/libnm-kylin/libnm-icon-kylin/translations/icon_mn.ts0000664000175000017500000000330315160520531024642 0ustar fengfeng KyNetworkIcon Not connected to the network ᠲᠣᠤᠷ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠶᠢ ᠬᠣᠯᠪᠣᠭᠰᠠᠨ ᠦᠭᠡᠶ ᠃ Network tool ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠪᠠᠭᠠᠵᠢ Network Card ᠰᠦᠯᠵᠢᠶᠡᠨ ᠺᠠᠯᠼ ᠃ Connected: ᠴᠥᠷᠬᠡᠯᠡᠪᠡ: (Limited) ( ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠬᠢᠵᠠᠭᠠᠷᠯᠠᠭᠳᠠᠪᠠ) Not Connected ᠵᠠᠯᠭᠠᠭᠰᠠᠨ ᠦᠭᠡᠢ ᠃ kylin-nm-plugin/libnm-kylin/libnm-icon-kylin/imageutil.cpp0000664000175000017500000000537515160520516022631 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 "imageutil.h" #include #include const QPixmap ImageUtil::loadSvg(const QString &path, const QString color, int size) { int origSize = size; const auto ratio = qApp->devicePixelRatio(); if ( 2 == ratio) { size += origSize; } else if (3 == ratio) { size += origSize; } QPixmap pixmap(size, size); QSvgRenderer renderer(path); pixmap.fill(Qt::transparent); QPainter painter; painter.begin(&pixmap); renderer.render(&painter); painter.end(); pixmap.setDevicePixelRatio(ratio); return drawSymbolicColoredPixmap(pixmap, color); } QPixmap ImageUtil::drawSymbolicColoredPixmap(const QPixmap &source, QString cgColor) { QImage img = source.toImage(); for (int x = 0; x < img.width(); x++) { for (int y = 0; y < img.height(); y++) { auto color = img.pixelColor(x, y); if (color.alpha() > 0) { if ( "white" == cgColor) { color.setRed(255); color.setGreen(255); color.setBlue(255); img.setPixelColor(x, y, color); } else if( "black" == cgColor) { color.setRed(0); color.setGreen(0); color.setBlue(0); img.setPixelColor(x, y, color); } else if ("gray"== cgColor) { color.setRed(152); color.setGreen(163); color.setBlue(164); img.setPixelColor(x, y, color); } else if ("blue" == cgColor){ color.setRed(61); color.setGreen(107); color.setBlue(229); img.setPixelColor(x, y, color); } else { return source; } } } } return QPixmap::fromImage(img); } kylin-nm-plugin/libnm-kylin/libnm-icon-kylin/translate_generation.sh0000775000175000017500000000232515167660365024722 0ustar fengfeng#!/bin/bash # -*- Mode: Shell-script; tab-width: 4; indent-tabs-mode: nil; sh-basic-offset: 4 -*- # # Copyright (C) 2019 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. # export PATH="/usr/lib/qt6/bin:$PATH" 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 kylin-nm-plugin/libnm-kylin/libnm-icon-kylin/kynetworkicon.cpp0000664000175000017500000005203515160520531023547 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 "kynetworkicon.h" #include "imageutil.h" #define EXCELLENT_SIGNAL 80 #define GOOD_SIGNAL 55 #define OK_SIGNAL 30 #define LOW_SIGNAL 5 #define 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" static QPalette getPalette(bool isDark) { QPalette palette = qApp->palette(); //ukui-light palette UKUI3.1 亮主题色板 QColor windowText_at(38, 38, 38), 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), light_at(255, 255, 255), light_iat(255, 255, 255), light_dis(242, 242, 242), midlight_at(218, 218, 218), midlight_iat(218, 218, 218), midlight_dis(230, 230, 230), dark_at(77, 77, 77), dark_iat(77, 77, 77), dark_dis(64, 64, 64), mid_at(115, 115, 115), mid_iat(115, 115, 115), mid_dis(102, 102, 102), text_at(38, 38, 38), text_iat(38, 38, 38), 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), base_at(255, 255, 255), base_iat(245, 245, 245), base_dis(237, 237, 237), window_at(245, 245, 245), window_iat(237, 237, 237), window_dis(230, 230, 230), 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), alternateBase_at(245, 245, 245), alternateBase_iat(245, 245, 245), alternateBase_dis(245, 245, 245), noRale_at(240, 240, 240), noRole_iat(240, 240, 240), noRole_dis(217, 217, 217), toolTipBase_at(255, 255, 255), toolTipBase_iat(255, 255, 255), toolTipBase_dis(255, 255, 255), toolTipText_at(38, 38, 38), toolTipText_iat(38, 38, 38), toolTipText_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); //ukui-dark 暗主题色板 if (isDark) { windowText_at.setRgb(217, 217, 217); windowText_iat.setRgb(255, 255, 255, 255 * 0.55); windowText_dis.setRgb(255, 255, 255, 255 * 0.3); button_at.setRgb(55, 55, 59); button_iat.setRgb(55, 55, 59); button_dis.setRgb(46, 46, 46); light_at.setRgb(255, 255, 255); light_iat.setRgb(255, 255, 255); light_dis.setRgb(242, 242, 242); midlight_at.setRgb(95, 95, 98); midlight_iat.setRgb(95, 95, 98); midlight_dis.setRgb(79, 79, 82); dark_at.setRgb(38, 38, 38); dark_iat.setRgb(38, 38, 38); dark_dis.setRgb(26, 26, 26); mid_at.setRgb(115, 115, 115); mid_iat.setRgb(115, 115, 115); mid_dis.setRgb(102, 102, 102); text_at.setRgb(217, 217, 217); text_iat.setRgb(217, 217, 217); text_dis.setRgb(255, 255, 255, 255 * 0.3); brightText_at.setRgb(255, 255, 255); brightText_iat.setRgb(255, 255, 255); brightText_dis.setRgb(255, 255, 255); buttonText_at.setRgb(217, 217, 217); buttonText_iat.setRgb(217, 217, 217); buttonText_dis.setRgb(76, 76, 79); base_at.setRgb(29, 29, 29); base_iat.setRgb(28, 28, 28); base_dis.setRgb(36, 36, 36); window_at.setRgb(35, 36, 38); window_iat.setRgb(26, 26, 26); window_dis.setRgb(18, 18, 18); shadow_at.setRgb(0, 0, 0, 255 * 0.16); shadow_iat.setRgb(0, 0, 0, 255 * 0.16); shadow_dis.setRgb(0, 0, 0, 255 * 0.21); highLightText_at.setRgb(255, 255, 255); highLightText_iat.setRgb(255, 255, 255); highLightText_dis.setRgb(77, 77, 77); alternateBase_at.setRgb(38, 38, 38); alternateBase_iat.setRgb(38, 38, 38); alternateBase_dis.setRgb(38, 38, 38); noRale_at.setRgb(51, 51, 51); noRole_iat.setRgb(51, 51, 51); noRole_dis.setRgb(60, 60, 60); toolTipBase_at.setRgb(38, 38, 38); toolTipBase_iat.setRgb(38, 38, 38); toolTipBase_dis.setRgb(38, 38, 38); toolTipText_at.setRgb(217, 217, 217); toolTipText_iat.setRgb(217, 217, 217); toolTipText_dis.setRgb(217, 217, 217); placeholderText_at.setRgb(255, 255, 255, 255 * 0.35); placeholderText_iat.setRgb(255, 255, 255, 255 * 0.35); placeholderText_dis.setRgb(255, 255, 255, 255 * 0.3); } palette.setColor(QPalette::Active, QPalette::WindowText, windowText_at); palette.setColor(QPalette::Inactive, QPalette::WindowText, windowText_iat); palette.setColor(QPalette::Disabled, QPalette::WindowText, windowText_dis); palette.setColor(QPalette::Active, QPalette::Button, button_at); palette.setColor(QPalette::Inactive, QPalette::Button, button_iat); palette.setColor(QPalette::Disabled, QPalette::Button, button_dis); palette.setColor(QPalette::Active, QPalette::Light, light_at); palette.setColor(QPalette::Inactive, QPalette::Light, light_iat); palette.setColor(QPalette::Disabled, QPalette::Light, light_dis); palette.setColor(QPalette::Active, QPalette::Midlight, midlight_at); palette.setColor(QPalette::Inactive, QPalette::Midlight, midlight_iat); palette.setColor(QPalette::Disabled, QPalette::Midlight, midlight_dis); palette.setColor(QPalette::Active, QPalette::Dark, dark_at); palette.setColor(QPalette::Inactive, QPalette::Dark, dark_iat); palette.setColor(QPalette::Disabled, QPalette::Dark, dark_dis); palette.setColor(QPalette::Active, QPalette::Mid, mid_at); palette.setColor(QPalette::Inactive, QPalette::Mid, mid_iat); palette.setColor(QPalette::Disabled, QPalette::Mid, mid_dis); palette.setColor(QPalette::Active, QPalette::Text, text_at); palette.setColor(QPalette::Inactive, QPalette::Text, text_iat); palette.setColor(QPalette::Disabled, QPalette::Text, text_dis); palette.setColor(QPalette::Active, QPalette::BrightText, brightText_at); palette.setColor(QPalette::Inactive, QPalette::BrightText, brightText_iat); palette.setColor(QPalette::Disabled, QPalette::BrightText, brightText_dis); palette.setColor(QPalette::Active, QPalette::ButtonText, buttonText_at); palette.setColor(QPalette::Inactive, QPalette::ButtonText, buttonText_iat); palette.setColor(QPalette::Disabled, QPalette::ButtonText, buttonText_dis); palette.setColor(QPalette::Active, QPalette::Base, base_at); palette.setColor(QPalette::Inactive, QPalette::Base, base_iat); palette.setColor(QPalette::Disabled, QPalette::Base, base_dis); palette.setColor(QPalette::Active, QPalette::Window, window_at); palette.setColor(QPalette::Inactive, QPalette::Window, window_iat); palette.setColor(QPalette::Disabled, QPalette::Window, window_dis); palette.setColor(QPalette::Active, QPalette::Shadow, shadow_at); palette.setColor(QPalette::Inactive, QPalette::Shadow, shadow_iat); palette.setColor(QPalette::Disabled, QPalette::Shadow, shadow_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::AlternateBase, alternateBase_at); palette.setColor(QPalette::Inactive, QPalette::AlternateBase, alternateBase_iat); palette.setColor(QPalette::Disabled, QPalette::AlternateBase, alternateBase_dis); palette.setColor(QPalette::Active, QPalette::NoRole, noRale_at); palette.setColor(QPalette::Inactive, QPalette::NoRole, noRole_iat); palette.setColor(QPalette::Disabled, QPalette::NoRole, noRole_dis); palette.setColor(QPalette::Active, QPalette::ToolTipBase, toolTipBase_at); palette.setColor(QPalette::Inactive, QPalette::ToolTipBase, toolTipBase_iat); palette.setColor(QPalette::Disabled, QPalette::ToolTipBase, toolTipBase_dis); palette.setColor(QPalette::Active, QPalette::ToolTipText, toolTipText_at); palette.setColor(QPalette::Inactive, QPalette::ToolTipText, toolTipText_iat); palette.setColor(QPalette::Disabled, QPalette::ToolTipText, toolTipText_dis); #if (QT_VERSION >= QT_VERSION_CHECK(5,12,0)) palette.setColor(QPalette::Active, QPalette::PlaceholderText, placeholderText_at); palette.setColor(QPalette::Inactive, QPalette::PlaceholderText, placeholderText_iat); palette.setColor(QPalette::Disabled, QPalette::PlaceholderText, placeholderText_dis); #endif return palette; } KyNetworkIcon::KyNetworkIcon(QWidget *parent): QPushButton(parent) { QTranslator *m_translator = new QTranslator(this); QLocale local; QString locale = local.name(); if (m_translator->load("/usr/share/kylin-nm-plugin/icon/icon_" + locale)) { QApplication::installTranslator(m_translator); } else { qWarning() << "Translations load fail"; } qRegisterMetaType("KyConnectState"); qRegisterMetaType("KyConnectStatus"); qRegisterMetaType("KyConnectionType"); qRegisterMetaType("KyDeviceState"); qRegisterMetaType("NetworkManager::Device::StateChangeReason"); this->setProperty("useIconHighlightEffect", 0x10); this->setProperty("needTranslucent", true); this->setFlat(true); this->setProperty("useButtonPalette", true); thread = new QThread; manager = new KyNetworkManager(); manager->moveToThread(thread); connect(thread, &QThread::started, manager, &KyNetworkManager::kylinNetworkManagerInit); connect(thread, &QThread::finished, manager, &KyNetworkManager::deleteLater); connect(thread, &QThread::finished, [=](){ qDebug() << "icon thread quit"; }); thread->start(); while (!manager->isInitFinished()) { ::usleep(1000); } 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")); loadingTimer = new QTimer(this); connect(loadingTimer, &QTimer::timeout, this, &KyNetworkIcon::onSetTrayIconLoading); manager->getConnectStatus(iconStatus); updateIcon(); initConnect(); updateIconTooltip(); refreshTimer = new QTimer(this); connect(loadingTimer, &QTimer::timeout, this, &KyNetworkIcon::updateIcon); refreshTimer->start(10 * 1000); QPalette pal = qApp->palette(); pal = getPalette(true); this->setPalette(pal); this->setCheckable(true); } KyNetworkIcon::~KyNetworkIcon() { qDebug() << "~KyNetworkIcon 1"; thread->quit(); thread->wait(); if (thread != nullptr) { delete thread; thread = nullptr; } qDebug() << "~KyNetworkIcon 2"; } void KyNetworkIcon::paintEvent(QPaintEvent *event) { QPalette pal = qApp->palette(); pal = getPalette(true); QColor checkedColor = this->palette().brightText().color(); checkedColor.setAlphaF(0.21); pal.setColor(QPalette::Active, QPalette::Highlight, checkedColor); this->setPalette(pal); return QPushButton::paintEvent(event); } void KyNetworkIcon::initConnect() { connect(manager, &KyNetworkManager::wiredStateChange, this, &KyNetworkIcon::onWiredStateChange); connect(manager, &KyNetworkManager::wirelessStateChange, this, &KyNetworkIcon::onWirelessStateChange); connect(manager, &KyNetworkManager::connectStatusChanged ,this, [=](KyConnectStatus status){ iconStatus = status; updateIcon(); updateIconTooltip(); }); connect(manager, &KyNetworkManager::deviceStateChange, this, [=]() { updateIconTooltip(); }); } void KyNetworkIcon::updateIcon() { if (loadingTimer->isActive()) { return; } int signalStrength = 0; QIcon icon; if (iconStatus == LAN_CONNECTED) { this->setIcon(QIcon::fromTheme("network-wired-symbolic")); return; } else if (iconStatus == WLAN_CONNECTED || iconStatus == WLAN_CONNECTED_LIMITED) { signalStrength = manager->getAcivateWifiSignal(); } else if (iconStatus == NOT_CONNECTED) { this->setIcon(QIcon::fromTheme("network-wired-disconnected-symbolic")); return; } else if (iconStatus == LAN_CONNECTED_LIMITED) { icon = QIcon::fromTheme("network-error-symbolic"); } if (iconStatus == WLAN_CONNECTED || iconStatus == WLAN_CONNECTED_LIMITED) { if (signalStrength > EXCELLENT_SIGNAL){ icon = QIcon::fromTheme(EXCELLENT_SIGNAL_ICON); } else if (signalStrength > GOOD_SIGNAL) { icon = QIcon::fromTheme(GOOD_SIGNAL_ICON); } else if (signalStrength > OK_SIGNAL) { icon = QIcon::fromTheme(OK_SIGNAL_ICON); } else if (signalStrength > LOW_SIGNAL) { icon = QIcon::fromTheme(LOW_SIGNAL_ICON); } else { icon = QIcon::fromTheme(NONE_SIGNAL_ICON); } } else if (iconStatus == WLAN_CONNECTED_LIMITED) { if (signalStrength > EXCELLENT_SIGNAL){ icon = QIcon::fromTheme(EXCELLENT_SIGNAL_LIMIT_ICON); } else if (signalStrength > GOOD_SIGNAL) { icon = QIcon::fromTheme(GOOD_SIGNAL_LIMIT_ICON); } else if (signalStrength > OK_SIGNAL) { icon = QIcon::fromTheme(OK_SIGNAL_LIMIT_ICON); } else if (signalStrength > LOW_SIGNAL) { icon = QIcon::fromTheme(LOW_SIGNAL_LIMIT_ICON); } else { icon = QIcon::fromTheme(NONE_SIGNAL_LIMIT_ICON); } } this->setIcon(icon); } void KyNetworkIcon::startLoading() { if (!loadingTimer->isActive()) { loadingTimer->start(60); } } void KyNetworkIcon::stopLoading() { if (loadingTimer->isActive()) { loadingTimer->stop(); } } void KyNetworkIcon::assembleTrayIconTooltip(QMap &map, QString &tip) { if (map.isEmpty()) { tip = QString(tr("Network tool")); return; } QMap::iterator iter = map.begin(); if (map.size() == 1) { tip = map.value(iter.key()); if (tip.indexOf(":")) { tip = tip.mid(tip.indexOf(":") + 2); //单网卡显示时去掉“已连接: ”字样 } } else if (map.size() > 1) { tip = ""; int count = 0; while (iter != map.end()) { count += 1; tip += QString(tr("Network Card")) + QString("%1").arg(count) + "\n" + map.value(iter.key()); ++iter; if (iter != map.end()) { tip += "\n"; } } } } void KyNetworkIcon::onSetTrayIconLoading() { if (currentIconIndex > 11) { currentIconIndex = 0; } this->setIcon(loadIcons.at(currentIconIndex)); currentIconIndex ++; } void KyNetworkIcon::onWiredStateChange(QString deviceName, QString uuid, KyConnectState state) { Q_UNUSED(deviceName) Q_UNUSED(uuid) if (state == CONNECT_STATE_ACTIVATING || state == CONNECT_STATE_DEACTIVATING) { startLoading(); } else { manager->getConnectStatus(iconStatus); stopLoading(); updateIcon(); updateIconTooltip(); } } void KyNetworkIcon::onWirelessStateChange(QString deviceName, QString ssid, QString uuid, KyConnectState state) { Q_UNUSED(deviceName) Q_UNUSED(ssid) Q_UNUSED(uuid) if (state == CONNECT_STATE_ACTIVATING || state == CONNECT_STATE_DEACTIVATING) { startLoading(); } else { manager->getConnectStatus(iconStatus); stopLoading(); updateIcon(); updateIconTooltip(); } } void KyNetworkIcon::updateIconTooltip() { QString trayIconToolTip = ""; switch(iconStatus) { case NOT_CONNECTED: trayIconToolTip = QString(tr("Not connected to the network")); break; case LAN_CONNECTED: case LAN_CONNECTED_LIMITED: getLanConnectedTooltip(trayIconToolTip); break; case WLAN_CONNECTED: case WLAN_CONNECTED_LIMITED: getWlanConnectedTooltip(trayIconToolTip); break; default: trayIconToolTip = QString(tr("Network tool")); break; } QMetaObject::invokeMethod(qApp, [this, trayIconToolTip]() { this->setToolTip(trayIconToolTip); }, Qt::QueuedConnection); } void KyNetworkIcon::getLanConnectedTooltip(QString &strTooltip) { strTooltip = ""; QStringList wiredDevList; manager->getNetworkDeviceList(DEVICE_TYPE_ETHERNET, wiredDevList); if (wiredDevList.isEmpty()) { return; } QMap wiredDevConnectedList; for (const QString devName : wiredDevList) { if (manager->getDeviceManaged(devName)) { QList activateList; manager->getActiveConnectionList(devName, CONNECT_TYPE_WIRED, activateList); KyConnectivity devConnectivity; manager->getDeviceConnectivity(devName, devConnectivity); if (!activateList.isEmpty() && activateList.at(0).m_connStatus == CONNECT_STATE_ACTIVATED) { if (devConnectivity == CONNECTIVITY_FULL) { wiredDevConnectedList.insert(devName, QString(tr("Connected: ")) + activateList.at(0).m_connName); } else { wiredDevConnectedList.insert(devName, QString(tr("Connected: ")) + activateList.at(0).m_connName + " " + QString(tr("(Limited)"))); } } else { wiredDevConnectedList.insert(devName, tr("Not Connected")); } } } assembleTrayIconTooltip(wiredDevConnectedList, strTooltip); } void KyNetworkIcon::getWlanConnectedTooltip(QString &strTooltip) { strTooltip = ""; QStringList wirelessDevList; manager->getNetworkDeviceList(DEVICE_TYPE_WIFI, wirelessDevList); if (wirelessDevList.isEmpty()) { return; } QMap wirelessDevConnectedList; for (const QString devName : wirelessDevList) { if (manager->getDeviceManaged(devName)) { QList activateList; manager->getActiveConnectionList(devName, CONNECT_TYPE_WIRELESS, activateList); KyConnectivity devConnectivity; manager->getDeviceConnectivity(devName, devConnectivity); if (!activateList.isEmpty() && activateList.at(0).m_connStatus == CONNECT_STATE_ACTIVATED) { wirelessDevConnectedList.insert(devName, QString(tr("Connected: ")) + activateList.at(0).m_ssid); } else { wirelessDevConnectedList.insert(devName, tr("Not Connected")); } } } assembleTrayIconTooltip(wirelessDevConnectedList, strTooltip); } bool KyNetworkIcon::checkIconIsHidden() { return false; } kylin-nm-plugin/libnm-kylin/libnm-icon-kylin/kynetworkicon.h0000664000175000017500000000417015160520531023211 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 KYNETWORKICON_H #define KYNETWORKICON_H #include "libnm-base-kylin_global.h" #include #include #include #include #include #include class LIBNMBASEKYLIN_EXPORT KyNetworkIcon : public QPushButton { Q_OBJECT public: KyNetworkIcon(QWidget *parent = nullptr); ~KyNetworkIcon(); bool checkIconIsHidden(); private: KyNetworkManager* manager = nullptr; QThread* thread = nullptr; QTimer *loadingTimer; QTimer *refreshTimer; int currentIconIndex=0; QList loadIcons; KyConnectStatus iconStatus = NOT_CONNECTED; void initConnect(); void startLoading(); void stopLoading(); void assembleTrayIconTooltip(QMap &map, QString &tip); protected: void paintEvent(QPaintEvent *); private Q_SLOTS: void onSetTrayIconLoading(); void updateIcon(); void onWiredStateChange(QString deviceName, QString uuid, KyConnectState state); void onWirelessStateChange(QString deviceName, QString ssid, QString uuid, KyConnectState state); void updateIconTooltip(); void getLanConnectedTooltip(QString &strTooltip); void getWlanConnectedTooltip(QString &strTooltip); }; #endif // KYNETWORKICON_H kylin-nm-plugin/libnm-kylin/libnm-icon-kylin/kylin-nm-plugin.pc.in0000664000175000017500000000034715170115272024122 0ustar fengfengprefix=/usr exec_prefix=/usr libdir=/usr/lib/ includedir=/usr/include Name: $${NAME} Description: $${DESCRIPTION} Version: $${VERSION} Libs: -L/usr/lib/ -llibnm-icon-kylin Cflags: -I/usr/include/kylin-nm Requires: libkylin-nm-basekylin-nm-plugin/libnm-kylin/libnm-icon-kylin/libnm-icon-kylin.pro0000664000175000017500000000417115170115272024033 0ustar fengfengQT += core gui widgets dbus network svg TEMPLATE = lib DEFINES += LIBNMICONKYLIN_LIBRARY CONFIG += c++14 qt link_pkgconfig no_keywords # The following define makes your compiler emit warnings if you use # any Qt feature that has been marked deprecated (the exact warnings # depend on your compiler). Please consult the documentation of the # deprecated API in order to know how to port your code away from it. DEFINES += QT_DEPRECATED_WARNINGS PKGCONFIG += kylin-nm-base #INCLUDEPATH += $$PWD/../libnm-base-kylin/ #INCLUDEPATH += /usr/include/KF5/NetworkManagerQt #LIBS += -L$$PWD/../libnm-base-kylin/ -l kylin-nm-base # You can also make your code fail to compile if it uses 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 CONFIG(release, debug|release) { !system($$PWD/translate_generation.sh): error("Failed to generate translation") } SOURCES += \ kynetworkicon.cpp \ imageutil.cpp HEADERS += \ kynetworkicon.h \ imageutil.h TRANSLATIONS += \ translations/icon_zh_CN.ts \ translations/icon_tr.ts \ translations/icon_bo.ts \ translations/icon_bo_CN.ts \ translations/icon_mn.ts \ translations/icon_zh_HK.ts \ translations/icon_mn.ts # Default rules for deployment. unix { target.path = /usr/lib manager.path = /usr/include/kylin-nm manager.files = kynetworkicon.h qm_files.path = /usr/share/kylin-nm-plugin/icon/ qm_files.files = translations/*.qm NAME = kylin-nm-plugin DESCRIPTION = kylin-nm-plugin library VERSION = $$VERSION # 自动生成 .pc 文件 pcfile.input = kylin-nm-plugin.pc.in pcfile.output = $${NAME}.pc pcfile.CONFIG += no_link_no_clean QMAKE_SUBSTITUTES += pcfile # 安装 pc 文件到系统目录 pcfile.path = /usr/share/pkgconfig pcfile.files = $${NAME}.pc INSTALLS += manager \ qm_files \ pcfile } !isEmpty(target.path): INSTALLS += target kylin-nm-plugin/libnm-kylin/libnm-icon-kylin/imageutil.h0000664000175000017500000000227215160520516022267 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 IMAGEUTIL_H #define IMAGEUTIL_H #include #include #include class ImageUtil { public: static const QPixmap loadSvg(const QString &path, const QString color, int size = 16); static QPixmap drawSymbolicColoredPixmap(const QPixmap &source, QString cgColor); }; #endif // IMAGEUTIL_H kylin-nm-plugin/libnm-kylin/libnm-kylin.pro0000664000175000017500000000031115160520516017722 0ustar fengfengTEMPLATE = subdirs SUBDIRS += \ # libnm-base-kylin \ # libnm-external-kylin \ libnm-icon-kylin #libnm-external-kylin.depends = libnm-base-kylin #libnm-icon-kylin.depends = libnm-base-kylin kylin-nm-plugin/plugins/0000775000175000017500000000000015167664423014231 5ustar fengfengkylin-nm-plugin/plugins/plugin.pro0000664000175000017500000000012515160520516016232 0ustar fengfengTEMPLATE = subdirs SUBDIRS = \ netconnect \ wlanconnect \ # mobilehotspot kylin-nm-plugin/plugins/res/0000775000175000017500000000000015160520531015002 5ustar fengfengkylin-nm-plugin/plugins/res/icon/0000775000175000017500000000000015160520531015732 5ustar fengfengkylin-nm-plugin/plugins/res/icon/load-up.png0000775000175000017500000000030215160520531017777 0ustar fengfengPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<dIDATxb`WB|Ƨ  P6VC:&lȶ`5 @,&| X43@K#63ĂQ`~F0>IENDB`kylin-nm-plugin/plugins/res/icon/load-down.png0000775000175000017500000000030015160520531020320 0ustar fengfengPNG  IHDRatEXtSoftwareAdobe ImageReadyqe<bIDATxb`hK"BdBX2QQ`#; pNCB.X?@{hl AbP9aTxH" BH &q_1DIENDB`kylin-nm-plugin/plugins/wlanconnect/0000775000175000017500000000000015167664423016544 5ustar fengfengkylin-nm-plugin/plugins/wlanconnect/translations/0000775000175000017500000000000015167664423021265 5ustar fengfengkylin-nm-plugin/plugins/wlanconnect/translations/wlan_zh_CN.ts0000775000175000017500000003340315160520531023645 0ustar fengfeng AddNetItem Add Others... 加入其他网络... EntSecurityWidget 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 内部认证 Username 用户名 Usename 用户名 Password 密码 None Choose from file... 从文件选择... Please log in to the system first. 请先登录系统 Store passwords only for this user 仅为该用户存储密码 Store passwords for all users 存储所有用户的密码 Ask this password every time 每次询问这个密码 PAC provisioning PAC 配置 Allow automatic PAC provisioning 允许自动 PAC 配置 PAC file PAC 文件 Anonymous 匿名 Authenticated 已认证 Both 两者兼用 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) EnterpriseWlanPage Network name(SSID) 网络名(SSID) Cancel 取消 Connect 连接 Connect Enterprise WLAN 连接到企业网 HiddenWiFiPage None WPA&WPA2 Personal WPA&WPA2个人 WPA&WPA2 Enterprise WPA&WPA2企业 WPA3 Personal WPA3个人 Please enter the network information 请输入您想要加入的网络信息 Find and Join WLAN 查找并加入无线局域网络 Please enter the network name and security type 请输入您想要加入的网络名称和安全类型 Network name(SSID) 网络名(SSID) Security type 安全性 Password 密码 Remember the Network 记住该网络 Show Network List 显示网络列表 Cancel 取消 Join 加入 Required 必填 Find and Join Wi-Fi 查找并加入Wi-Fi LogHintDialog Please log in to the system first. 请先登录系统 Confirm 确定 WlanConnect Kylin NM 网络设置工具 kylin network applet desktop message 网络提示消息 WLAN 无线局域网 Settings 网络设置 No wireless device avaliable 没有可用的无线网卡 WlanItem Connect 连接 Auto Connect 自动加入该网络 Disconnect 断开 kylin-nm-plugin/plugins/wlanconnect/translations/wlan_zh_Hant.ts0000775000175000017500000003342015160520531024236 0ustar fengfeng AddNetItem Add Others... 加入其他網路... EntSecurityWidget 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 內部認證 Username 使用者名 Usename 使用者名 Password 密碼 None Choose from file... 從檔案選擇... Please log in to the system first. 請先登錄系統 Store passwords only for this user 僅為該使用者存儲密碼 Store passwords for all users 存儲所有用戶的密碼 Ask this password every time 每次詢問這個密碼 PAC provisioning PAC 配置 Allow automatic PAC provisioning 允許自動 PAC 配置 PAC file PAC 檔 Anonymous 匿名 Authenticated 已認證 Both 兩者兼用 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) EnterpriseWlanPage Network name(SSID) 網路名稱(SSID) Cancel 取消 Connect 連接 Connect Enterprise WLAN 連接到企業網 HiddenWiFiPage None WPA&WPA2 Personal WPA&WPA2個人 WPA&WPA2 Enterprise WPA&WPA2企業 WPA3 Personal WPA3個人 Please enter the network information 請輸入您想要加入的網路資訊 Find and Join WLAN 查找並加入無線局域網路 Please enter the network name and security type 请输入您想要加入的网络名称和安全类型 Network name(SSID) 網路名稱(SSID) Security type 安全性 Password 密碼 Remember the Network 記住該網路 Show Network List 显示网络列表 Cancel 取消 Join 加入 Required 必填 Find and Join Wi-Fi 查找并加入Wi-Fi LogHintDialog Please log in to the system first. 請先登錄系統 Confirm 確定 WlanConnect Kylin NM kylin network applet desktop message WLAN 無線局域網 Settings 網路設置 No wireless device avaliable WlanItem Connect 連接 Auto Connect 自動加入該網路 Disconnect 斷開 kylin-nm-plugin/plugins/wlanconnect/translations/wlan_zh_HK.ts0000775000175000017500000003342515160520531023653 0ustar fengfeng AddNetItem Add Others... 加入其他網絡... EntSecurityWidget 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 內部認證 Username 使用者名 Usename 用戶名 Password 密碼 None Choose from file... 從文件選擇... Please log in to the system first. 請先登錄系統 Store passwords only for this user 僅為該用戶存儲密碼 Store passwords for all users 存儲所有用戶的密碼 Ask this password every time 每次詢問這個密碼 PAC provisioning PAC 預配 Allow automatic PAC provisioning 允許自動 PAC 預配 PAC file PAC 檔 Anonymous 匿名 Authenticated 認證 Both Choose a CA certificate 選擇壹個CA證書 CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) CA 證書 (*.pem *.der *.p12 *.crt *.cer *.pfx) Choose a PAC file 選擇一個CA證書 PAC Files (*.pac) CA 憑證 (*.pem *.der *.p12 *.crt *.cer *.pfx) EnterpriseWlanPage Network name(SSID) 網絡名(SSID) Cancel 取消 Connect 連接 Connect Enterprise WLAN 連接到企業網 HiddenWiFiPage None WPA&WPA2 Personal WPA&WPA2個人 WPA&WPA2 Enterprise WPA&WPA2企業 WPA3 Personal WPA3個人 Please enter the network information 請輸入您想要加入的網路資訊 Find and Join WLAN 查找並加入無線局域網路 Please enter the network name and security type 請輸入您想要加入的網絡名稱和安全類型 Network name(SSID) 網絡名(SSID) Security type 安全性 Password 密碼 Remember the Network 記住該網絡 Show Network List 顯示網絡列表 Cancel 取消 Join 加入 Required 必填 Find and Join Wi-Fi 查找並加入Wi-Fi LogHintDialog Please log in to the system first. 請先登錄系統 Confirm 確定 WlanConnect Kylin NM 網路設置工具 kylin network applet desktop message 網路提示消息 WLAN 無線局域網 Settings 網絡設置 No wireless device avaliable 沒有可用的無線設備 WlanItem Connect 連接 Auto Connect 自動加入該網絡 Disconnect 斷開 kylin-nm-plugin/plugins/wlanconnect/translations/wlan_tr.ts0000775000175000017500000003251315160520531023272 0ustar fengfeng AddNetItem Add Others... EntSecurityWidget EAP type Identity Domain CA certficate no need for CA certificate User certificate User private key User key password Password options Required Ineer authentication Username Password None Choose from file... Please log in to the system first. Store passwords only for this user Store passwords for all users Ask this password every time PAC provisioning Allow automatic PAC provisioning PAC file Anonymous Authenticated Both Choose a CA certificate CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) Choose a PAC file PAC Files (*.pac) EnterpriseWlanPage Network name(SSID) Cancel Connect Connect Enterprise WLAN HiddenWiFiPage None WPA&WPA2 Personal WPA&WPA2 Enterprise WPA3 Personal Please enter the network information Network name(SSID) Security type Password Remember the Network Cancel Join Required Find and Join WLAN LogHintDialog Please log in to the system first. Confirm WlanConnect Kylin NM kylin network applet desktop message WLAN Settings No wireless device avaliable WlanItem Connect Auto Connect Disconnect kylin-nm-plugin/plugins/wlanconnect/translations/wlan_bo.ts0000775000175000017500000003251315160520531023245 0ustar fengfeng AddNetItem Add Others... EntSecurityWidget EAP type Identity Domain CA certficate no need for CA certificate User certificate User private key User key password Password options Required Ineer authentication Username Password None Choose from file... Please log in to the system first. Store passwords only for this user Store passwords for all users Ask this password every time PAC provisioning Allow automatic PAC provisioning PAC file Anonymous Authenticated Both Choose a CA certificate CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx) Choose a PAC file PAC Files (*.pac) EnterpriseWlanPage Network name(SSID) Cancel Connect Connect Enterprise WLAN HiddenWiFiPage None WPA&WPA2 Personal WPA&WPA2 Enterprise WPA3 Personal Please enter the network information Network name(SSID) Security type Password Remember the Network Cancel Join Required Find and Join WLAN LogHintDialog Please log in to the system first. Confirm WlanConnect Kylin NM kylin network applet desktop message WLAN Settings No wireless device avaliable WlanItem Connect Auto Connect Disconnect kylin-nm-plugin/plugins/wlanconnect/translations/wlan_kk.ts0000775000175000017500000003404015160520531023247 0ustar fengfeng AddNetItem Add Others... باسقا تورعا قوسىلۋ... EntSecurityWidget 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 ٸشكٸ قىسىمى دالەلدەۋ Username پايدالانۋشٸ مى Usename ٸستەتۋ مى Password قۇپيا نۇمىردى وزگەرتۋ None جوق Choose from file... حۇجاتىن تالداۋ... Please log in to the system first. الدىندا سەستاماعا كىرىڭىز. Store passwords only for this user تەك نۇ ٸستەتۋشٸنٸڭ قۇپيا نۇمىردى ساقتايدى Store passwords for all users بارلٸق ٸستەتۋشٸنٸڭ قۇپيا نۇمىردى ساقتاۋ Ask this password every time ٵر رەت نۇ قۇپيا نۇمىردى سۇراۋ PAC provisioning PAC مەنەن قامداعٸش Allow automatic PAC provisioning PAC نى اۆتوماتتى تەڭشەۋگە جول قويادى PAC file PAC حۇجاتى Anonymous اتسىز Authenticated راستلىق دالەلدەۋ Both ەكەۋى 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) EnterpriseWlanPage Network name(SSID) تور مى (SSID) Cancel كۇشىنەن قالدىرۋ Connect جالعانۋ Connect Enterprise WLAN كاسپورىن WLAN نى بايلاۋ HiddenWiFiPage None جوق WPA&WPA2 Personal WPA&WPA2 جەكە WPA&WPA2 Enterprise WPA&WPA2 كاسپورىن WPA3 Personal WPA3 جەكە Please enter the network information تور حاباردٸ كىرگىزىڭىز Find and Join WLAN WLAN نى تابۋ ۋا قوسۋ Please enter the network name and security type 请输入您想要加入的网络名称和安全类型 Network name(SSID) تور مى (SSID) Security type حاۋىپسىزدىك تيپى Password قۇپيا نۇمىردى وزگەرتۋ Remember the Network وسى توردى ەستە ساقتاۋ Show Network List 显示网络列表 Cancel كۇشىنەن قالدىرۋ Join قوسىلۋ Required ٴسوزسىز Find and Join Wi-Fi 查找并加入Wi-Fi LogHintDialog Please log in to the system first. الدىندا سەستاماعا كىرىڭىز. Confirm تۇراقتاندىرۋ WlanConnect WLAN سىمسىز تور Settings ورنالاسترعان ەتۋ WlanItem Connect جالعانۋ Auto Connect نۇ تورعا اۆتوماتتى اۋلاۋ Disconnect ۇزارتىۋ kylin-nm-plugin/plugins/wlanconnect/translations/wlan_bo_CN.ts0000775000175000017500000004135215160520531023626 0ustar fengfeng AddNetItem Add Others... གཞན་པ་ཁ་སྣོན་བྱས་ནས་... EntSecurityWidget 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 དབྱིན་ཆས་ཀྱི་བདེན་དཔང་ར་སྤྲོད་ Username སྤྱོད་མཁན་མིང་།: Usename སྤྱོད་མཁན་གྱི་མིང་། Password ཕར་འགྲོ་ཚུར་འོང་བྱེད་མཁན། None གཅིག་ཀྱང་མེད། Choose from file... ཡིག་ཆའི་ནང་ནས་གདམ་ག་རྒྱག་དགོས།... Please log in to the system first. ཕུའུ་ལི་སི་ལོ་ཀེ་ནི་ཐུའོ་ཐི་ཞི་སི་ཐེ་མུའུ་ཧྥུ་སི་ཐེ་ཡིན། Store passwords only for this user སྤྱོད་མཁན་དེ་ཁོ་ནའི་ཆེད་དུ་གསང་གྲངས་ཉར་ཚགས་བྱས་ཡོད། Store passwords for all users སྤྱོད་མཁན་ཚང་མའི་གསང་བ་གསོག་ཉར་བྱེད་དགོས། Ask this password every time ཐེངས་རེར་གསང་བ་འདི་འདྲི་རྩད་བྱེད་ཐེངས་རེ་ཡིན། PAC provisioning PAC གཏན་འབེབས་བྱས་པ། Allow automatic PAC provisioning རང་འགུལ་གྱིས་PACམཚོ་འདོན་བྱས་ཆོག། PAC file PACཡིག་ཆ། Anonymous མིང་མ་བཀོད་པའི་ Authenticated བདེན་དཔང་ར་སྤྲོད་བྱས། Both དེ་གཉིས་ཀ 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) EnterpriseWlanPage Network name(SSID) དྲ་རྒྱའི་མིང་། (SSID) Cancel དོར་བ། Connect སྦྲེལ་མཐུད་བྱེད་པ། Connect Enterprise WLAN ཁེ་ལས་ས སྦྲེལ་མཐུད་བྱེད་པ། HiddenWiFiPage None གཅིག་ཀྱང་མེད། WPA&WPA2 Personal WPA&WPA2མི་སྒེར་གྱི་ངོས་ནས་བཤད་ན། WPA&WPA2 Enterprise WPA&WPA2 ཁེ་ལས། WPA3 Personal WPA3མི་སྒེར་ Please enter the network information ཁྱེད་རང་ཞུགས་འདོད་པའི་དྲ་རྒྱའི་ཆ་འཕྲིན་ནང་འཇུག་བྱེད་རོགས། Find and Join WLAN འཚོལ་ཞིབ་བྱས་པ་མ་ཟད་ལ་ཞུགས་པ་རེད། Please enter the network name and security type 请输入您想要加入的网络名称和安全类型 Network name(SSID) དྲ་རྒྱའི་མིང་། (SSID) Security type སའེ་ཁི་ལི་ཏི་ཐའེ་ཕེ། Password ཕར་འགྲོ་ཚུར་འོང་བྱེད་མཁན། Remember the Network དྲ་རྒྱ་དེ་སེམས་ལ་འཛིན་དགོས། Show Network List 显示网络列表 Cancel དོར་བ། Join དེའི་ནང་དུ་ཞུགས་པ། Required བླང་བྱ་བཏོན་པ། Find and Join Wi-Fi འཚོལ་ཞིབ་བྱས་པ་མ་ཟད་WI-FIལ་ཞུགས་པ་རེད། LogHintDialog Please log in to the system first. ཕུའུ་ལི་སི་ལོ་ཀེ་ནི་ཐུའོ་ཐི་ཞི་སི་ཐེ་མུའུ་ཧྥུ་སི་ཐེ་ཡིན། Confirm ཐག་ཆོད། WlanConnect Kylin NM དྲ་རྒྱའི་ཡོ་བྱད། kylin network applet desktop message དྲ་རྒྱའི་ཀུ་ཤུའི་ཅོག་ཙེའི་ཆ་འཕྲིན། WLAN སྐུད་མེད་ཅུས་ཁོངས་ཀྱི་དྲ་བ། Settings སྒྲིག་བཀོད། No wireless device avaliable དྲ་རྒྱ་མེད་པའི་ཨང་ཀི་མེད། WlanItem Connect སྦྲེལ་མཐུད་བྱེད་པ། Auto Connect རང་འགུལ་གྱིས་སྦྲེལ་མཐུད་ Disconnect ཆད་པ། kylin-nm-plugin/plugins/wlanconnect/translations/wlan_ug_CN.ts0000775000175000017500000003516515160520531023646 0ustar fengfeng AddNetItem Add Others... باشقا تورغا قوشۇلۇش... EntSecurityWidget 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 ئىچكى قىسىمنى دەلىللەش Username Usename ئىشلىتىش نامى Password مەخپىي نومۇرنى ئۆزگەرتىش None يوق Choose from file... ھۆججەتتىن تاللاش... Please log in to the system first. ئاۋال سېستىمىغا كىرىڭ. Store passwords only for this user پەقەت بۇ ئىشلەتكۈچىنىڭ مەخپىي نومۇرىنى ساقلايدۇ. Store passwords for all users بارلىق ئىشلەتكۈچىنىڭ مەخپىي نومۇرىنى ساقلاش Ask this password every time ھەر قېتىم بۇ مەخپىي نومۇرنى سوراش PAC provisioning Allow automatic PAC provisioning PAC file Anonymous Authenticated Both 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 Files (*.pac) EnterpriseWlanPage Network name(SSID) تور نامى (SSID) Cancel ئەمەلدىن قالدۇرۇش Connect ئۇلىنىش Connect Enterprise WLAN كارخانا WLAN نى باغلاش HiddenWiFiPage None يوق WPA&WPA2 Personal WPA&WPA2 شەخسى WPA&WPA2 Enterprise WPA&WPA2 كارخانا WPA3 Personal WPA3 شەخسى Please enter the network information Find and Join WLAN Please enter the network name and security type تور نامى ۋە بىخەتەرلىك تىپىغا كىرىڭ Network name(SSID) تور نامى (SSID) Security type بىخەتەرلىك تىپى Password مەخپىي نومۇرنى ئۆزگەرتىش Remember the Network مۇشۇ تورنى ئەستە ساقلاش Show Network List 显示网络列表 Cancel ئەمەلدىن قالدۇرۇش Join قوشۇلۇش Required زۆرۈر Find and Join Wi-Fi Wi-Fi نى تېپىش ۋە قوشۇۋېلىش LogHintDialog Please log in to the system first. ئاۋال سېستىمىغا كىرىڭ. Confirm جەزملەشتۈرۈش WlanConnect Kylin NM kylin network applet desktop message WLAN تار دائىرىلىك سىمسىز تور Settings تەسىس قىلىش No wireless device avaliable WlanItem Connect ئۇلىنىش Auto Connect بۇ تورغا ئاپتوماتىك ئۇلاش Disconnect ئۈزۈۋېتىش kylin-nm-plugin/plugins/wlanconnect/translations/wlan_mn.ts0000664000175000017500000004105015160520531023250 0ustar fengfeng AddNetItem Add Others... ᠪᠤᠰᠤᠳ ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳ᠋ᠤ᠌ ᠵᠠᠯᠭᠠᠬᠤ··· EntSecurityWidget 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 ᠳᠤᠳᠤᠭᠠᠳᠤ ᠬᠡᠷᠡᠴᠢᠯᠡᠯ Username ᠬᠡᠷᠡᠭᠯᠡᠭᠴᠢ ᠵᠢᠨ ᠨᠡᠷ᠎ᠡ Usename ᠬᠡᠷᠡᠭᠯᠡᠭᠴᠢ ᠶᠢᠨ ᠨᠡᠷ᠎ᠡ ᠃ Password ᠨᠢᠭᠤᠴᠠ ᠺᠤᠳ᠋ None ᠦᠬᠡᠢ Choose from file... ᠹᠠᠢᠯ ᠡᠴᠡ ᠰᠤᠩᠭᠤᠬᠤ··· Please log in to the system first. ᠤᠷᠢᠳᠠᠪᠠᠷ ᠰᠢᠰᠲ᠋ᠧᠮ ᠳᠦ ᠭᠠᠷᠤᠭᠠᠷᠠᠢ ᠃ Store passwords only for this user ᠵᠥᠪᠬᠡᠨ ᠲᠤᠰ ᠬᠡᠷᠡᠭᠯᠡᠭᠴᠢ ᠵᠢᠨ ᠨᠢᠭᠤᠴᠠ ᠺᠣᠳ᠋ ᠢ᠋ ᠬᠠᠳᠠᠭᠠᠯᠠᠬᠤ Store passwords for all users ᠪᠦᠬᠦᠢᠯᠡ ᠬᠡᠷᠡᠭᠯᠡᠭᠴᠢ ᠵᠢᠨ ᠨᠢᠭᠤᠴᠠ ᠺᠤᠳ᠋ ᠢ᠋ ᠬᠠᠳᠠᠭᠠᠯᠠᠬᠤ Ask this password every time ᠤᠳᠠᠭ᠎ᠠ ᠪᠦᠷᠢ ᠲᠤᠰ ᠨᠢᠭᠤᠴᠠ ᠺᠣᠳ᠋ ᠢ᠋ ᠠᠰᠠᠭᠤᠨ ᠯᠠᠪᠯᠠᠬᠤ PAC provisioning PAC ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠭ᠎ᠠ Allow automatic PAC provisioning ᠠᠦ᠋ᠲ᠋ᠣ᠋ PAC ᠳᠤᠬᠢᠷᠠᠭᠤᠯᠭ᠎ᠠ ᠵᠢ ᠵᠥᠪᠰᠢᠶᠡᠷᠡᠬᠦ PAC file PAC ᠹᠠᠢᠯ Anonymous ᠨᠡᠷ᠎ᠡ ᠪᠤᠷᠤᠭᠤᠯᠠᠵᠤ ᠨᠡᠪᠳᠡᠷᠡᠬᠦ Authenticated ᠭᠡᠷᠡᠴᠢᠯᠡᠬᠦ Both ᠬᠣᠶᠠᠭᠤᠯᠠ ᠵᠢ ᠠᠭᠤᠰᠤᠯᠴᠠᠭᠤᠯᠵᠤ ᠬᠡᠷᠡᠭᠯᠡᠬᠦ 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) EnterpriseWlanPage Network name(SSID) ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠨᠡᠷ᠎ᠡ (SSID) Cancel ᠪᠣᠯᠢᠬᠤ Connect ᠴᠦᠷᠬᠡᠯᠡᠬᠡ Connect Enterprise WLAN ᠠᠵᠤ ᠠᠬᠤᠢᠯᠠᠯ ᠤ᠋ᠨ ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳ᠋ᠤ᠌ ᠴᠦᠷᠬᠡᠯᠡᠬᠦ HiddenWiFiPage None ᠦᠬᠡᠢ WPA&WPA2 Personal WPA&WPA2 ᠬᠤᠪᠢ ᠬᠦᠮᠦᠨ WPA&WPA2 Enterprise WPA&WPA2 ᠠᠵᠤ ᠠᠬᠤᠢᠯᠠᠯ WPA3 Personal WPA3 ᠬᠥᠮᠥᠨ ᠃ Please enter the network information ᠲᠠᠨ ᠤ᠋ ᠣᠷᠣᠬᠤ ᠬᠡᠵᠤ ᠪᠠᠢᠭ᠎ᠠ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠰᠤᠷᠠᠭ ᠵᠠᠩᠬᠢ ᠵᠢ ᠣᠷᠣᠭᠤᠯᠤᠭᠠᠷᠠᠢ Find and Join WLAN ᠤᠳᠠᠰᠤ ᠥᠬᠡᠢ ᠬᠡᠰᠡᠭ ᠤ᠋ᠨ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠵᠢ ᠡᠷᠢᠵᠤ ᠣᠷᠣᠬᠤ Please enter the network name and security type Нэгдэх хүсэлтэй сүлжээний нэр болон хамгаалалтын төрлийг оруулна уу Network name(SSID) ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠨᠡᠷ᠎ᠡ (SSID) Security type ᠠᠶᠤᠯᠭᠦᠢ ᠴᠢᠨᠠᠷ ᠃ Password ᠨᠢᠭᠤᠴᠠ ᠺᠤᠳ᠋ Remember the Network ᠲᠤᠰ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠵᠢ ᠴᠡᠬᠡᠵᠢᠯᠡᠬᠦ Show Network List Сүлжээний жагсаалтыг харуулах Cancel ᠪᠣᠯᠢᠬᠤ Join ᠣᠷᠣᠬᠤ Required ᠡᠷᠬᠡᠪᠰᠢ ᠳᠠᠭᠯᠠᠬᠤ Find and Join Wi-Fi 查找并加入Wi-Fi LogHintDialog Please log in to the system first. ᠤᠷᠢᠳᠠᠪᠠᠷ ᠰᠢᠰᠲ᠋ᠧᠮ ᠳᠦ ᠭᠠᠷᠤᠭᠠᠷᠠᠢ ᠃ Confirm ᠲᠣᠭᠲᠠᠭᠠᠬᠤ WlanConnect Kylin NM ᠲᠣᠤᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳᠡᠭᠡᠷ᠎ᠡ ᠪᠠᠭᠠᠵᠢ ᠲᠣᠬᠢᠷᠠᠭᠤᠯᠤᠨ᠎ᠠ ᠃ kylin network applet desktop message ᠰᠦᠯᠵᠢᠶᠡᠨ ᠦ ᠰᠠᠨᠠᠭᠤᠯᠤᠮᠵᠢ ᠶᠢᠨ ᠮᠡᠳᠡᠭᠡ ᠃ WLAN ᠤᠲᠠᠰᠤᠭᠤᠢ ᠬᠡᠰᠡᠭ ᠬᠡᠪᠴᠢᠶᠡᠨ᠎ᠦ᠌ ᠲᠣᠣᠷ Settings ᠲᠤᠬᠢᠷᠠᠭᠤᠯᠬᠤ No wireless device avaliable Утасгүй төхөөрөмж олдсонгү WlanItem Connect ᠴᠦᠷᠬᠡᠯᠡᠬᠡ Auto Connect ᠲᠤᠰ ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳ᠋ᠤ᠌ ᠠᠦ᠋ᠲ᠋ᠤ᠋ ᠪᠡᠷ ᠵᠠᠯᠭᠠᠬᠤ Disconnect ᠴᠦᠷᠬᠡᠯᠡᠬᠡ ᠵᠢ ᠳᠠᠰᠤᠯᠬᠤ kylin-nm-plugin/plugins/wlanconnect/translations/wlan_ug.ts0000775000175000017500000003523415160520531023263 0ustar fengfeng AddNetItem Add Others... باشقا تورغا قوشۇلۇش... EntSecurityWidget 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 ئىچكى قىسىمنى دەلىللەش Username ئىشلەتكۈچى نامى Usename ئابونت نامى Password ئىم None يوق Choose from file... ھۆججەتتىن تاللاش... Please log in to the system first. ئاۋۋال سىستېمىغا كىرىڭ Store passwords only for this user پەقەت بۇ ئىشلەتكۈچىنىڭ مەخپىي نومۇرىنى ساقلايدۇ Store passwords for all users بارلىق ئىشلەتكۈچىنىڭ مەخپىي نومۇرىنى ساقلاش Ask this password every time ھەر قېتىم بۇ مەخپىي نومۇرنى سوراش PAC provisioning PAC بىلەن تەمىنلەش Allow automatic PAC provisioning PAC نى ئاپتوماتىك تەڭشەشكە يول قويىدۇ PAC file PAC ھۆججىتى Anonymous نامسىز Authenticated راستلىق دەلىللەش Both ئىككىلىسى 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) EnterpriseWlanPage Network name(SSID) تور نامى (SSID) Cancel ئەمەلدىن قالدۇرۇش Connect ئۇلىنىش Connect Enterprise WLAN كارخانا تورىغا ئۇلاش HiddenWiFiPage None يوق WPA&WPA2 Personal WPA&WPA2 شەخسى WPA&WPA2 Enterprise WPA&WPA2 كارخانا WPA3 Personal WPA3 شەخسى Please enter the network information تور ئۇچۇرىنى كىرگۈزۈڭ Find and Join WLAN WLAN نى تېپىش ۋە قوشۇش Please enter the network name and security type 请输入您想要加入的网络名称和安全类型 Network name(SSID) تور نامى (SSID) Security type بىخەتەرلىك Password ئىم Remember the Network مۇشۇ تورنى ئەستە ساقلاش Show Network List 显示网络列表 Cancel ئەمەلدىن قالدۇرۇش Join قوشۇلۇش Required مۇقەررەر تولدۇرۇش Find and Join Wi-Fi 查找并加入Wi-Fi LogHintDialog Please log in to the system first. ئاۋۋال سىستېمىغا كىرىڭ Confirm جەزملەش WlanConnect Kylin NM kylin network applet desktop message WLAN سىمسىز دائىرلىك تور Settings تەڭشەك No wireless device avaliable WlanItem Connect ئۇلىنىش Auto Connect بۇ تورغا ئاپتوماتىك ئۇلاش Disconnect ئۇلىنىش ئۈزۈلدى kylin-nm-plugin/plugins/wlanconnect/translations/wlan_ky.ts0000775000175000017500000003446515160520531023300 0ustar fengfeng AddNetItem Add Others... Башка тармактарга кошулуңуз... EntSecurityWidget EAP type EAP күбөлөндүрүлгөн Identity Анонимдүү маалымат Domain облустук CA certficate СА күбөлүгү no need for CA certificate Эч кандай СА күбөлүгү талап кылынбайт User certificate Колдонуучунун күбөлүктөрү User private key Колдонуучунун жеке ачкычы User key password Жабык ачкычтын сыр сөзү Password options Сырсөздүн параметрлери Required Талап кылынат Ineer authentication Ички күбөлөндүрүү Username Колдонуучу аты Usename Колдонуучу аты Password сыр сөз None эмес Choose from file... Файлдан тандаңыз... Please log in to the system first. Алгач системага кириңиз Store passwords only for this user Сырсөздү ошол колдонуучунун гана сактагычы Store passwords for all users Бардык колдонуучулар үчүн сыр сөздү сактоо Ask this password every time Бул сырсөздү ар дайым сураңыз PAC provisioning PAC конфигурациясы Allow automatic PAC provisioning PAC автоматтык ырастоого мүмкүндүк берет PAC file PAC файл Anonymous Анонимдүүлүк Authenticated Күбөлөндүрүлгөн Both Экөөнү тең колдонуу Choose a CA certificate ЦСнын сертификатын тандоо 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) EnterpriseWlanPage Network name(SSID) Тармак аты (SSID) Cancel Жокко чыгаруу Connect Туташуу Connect Enterprise WLAN Ишкана тармагына туташуу HiddenWiFiPage None эмес WPA&WPA2 Personal WPA & WPA2 жекече WPA&WPA2 Enterprise WPA & WPA2 ишканасы WPA3 Personal WPA3 жеке адамдар Please enter the network information Сиз кошулгуңуз келген тармак маалыматтарын киргизиңиз Find and Join WLAN Зымсыз LAN табуу жана кошулуу Please enter the network name and security type 请输入您想要加入的网络名称和安全类型 Network name(SSID) Тармак аты (SSID) Security type Коопсуздук Password сыр сөз Remember the Network Тармакты эстеп калуу Show Network List 显示网络列表 Cancel Жокко чыгаруу Join Кошулуу Required Талап кылынат Find and Join Wi-Fi 查找并加入Wi-Fi LogHintDialog Please log in to the system first. Алгач системага кириңиз Confirm Чын элеби WlanConnect WLAN Зымсыз LAN Settings Тармактын ырастоолору WlanItem Connect Туташуу Auto Connect Тармакка автоматтык түрдө кошулуу Disconnect Байланышты үзүү kylin-nm-plugin/plugins/wlanconnect/wlanconnect.pro0000775000175000017500000000330515160520531021565 0ustar fengfengQT += widgets network dbus gui core TEMPLATE = lib CONFIG += plugin include(../component/infobutton.pri) include(../component/divider.pri) include(../component/deviceframe.pri) include(../component/RadioItemButton.pri) include(../component/fixlabel.pri) include(../component/fixpushbutton.pri) include(hiddenwifi/hiddenwifi.pri) TARGET = $$qtLibraryTarget(wlanconnect) DESTDIR = ../.. CONFIG(release, debug|release) { !system($$PWD/translate_generation.sh): error("Failed to generate translation") } INCLUDEPATH += \ $$PROJECT_COMPONENTSOURCE \ $$PROJECT_ROOTDIR \ LIBS += -L$$[QT_INSTALL_LIBS] -lkylin-nm-base -lkylin-keyring CONFIG += c++11 \ link_pkgconfig \ no_keywords PKGCONFIG += gsettings-qt6 \ kysdk-applications \ kylin-nm-base \ libsecret-1 #DEFINES += QT_DEPRECATED_WARNINGS SOURCES += \ itemframe.cpp \ wlanconnect.cpp \ wlanitem.cpp HEADERS += \ itemframe.h \ wlanconnect.h \ wlanitem.h TRANSLATIONS += \ translations/wlan_zh_CN.ts \ translations/wlan_zh_Hant.ts \ translations/wlan_zh_HK.ts \ translations/wlan_tr.ts \ translations/wlan_bo.ts \ translations/wlan_bo_CN.ts \ translations/wlan_ug_CN.ts \ translations/wlan_ug.ts \ translations/wlan_mn.ts target.path = /usr/lib/kylin-nm qm_files.path = /usr/share/kylin-nm-plugin/wlanconnect/ qm_files.files = translations/*.qm ts_files.path = /usr/share/kylin-nm-plugin/wlanconnect/ ts_files.files = translations/*.ts INSTALLS += target \ qm_files RESOURCES += \ resource.qrc DISTFILES += \ translations/wlan_bo_CN.ts kylin-nm-plugin/plugins/wlanconnect/itemframe.cpp0000775000175000017500000001362215160520531021210 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 #include #define LAYOUT_MARGINS 2,0,12,0 #define MAIN_LAYOUT_MARGINS 0,0,0,0 #define RADIUS 6.0 AddNetItem::AddNetItem(QWidget *parent) : QFrame(parent) { this->setFixedSize(404, 48); QHBoxLayout *m_mainLayout = new QHBoxLayout(this); m_mainLayout->setContentsMargins(0,0,0,0); titleLabel = new QLabel(this); titleLabel->setText(tr("Add Others...")); m_mainLayout->addSpacing(16); m_mainLayout->addWidget(titleLabel); m_mainLayout->addStretch(); this->setLayout(m_mainLayout); } void AddNetItem::mouseReleaseEvent(QMouseEvent *event) { Q_EMIT itemClick(); return QFrame::mouseReleaseEvent(event); } void AddNetItem::enterEvent(QEnterEvent *event) { m_isIn = true; update(); return QFrame::enterEvent(event); } void AddNetItem::leaveEvent(QEvent *event) { m_isIn = false; update(); return QFrame::leaveEvent(event); } void AddNetItem::paintEvent(QPaintEvent *event) { QPalette pal = this->palette(); QPainter painter(this); painter.setRenderHint(QPainter:: Antialiasing, true); //设置渲染,启动反锯齿 painter.setPen(Qt::NoPen); if (m_isIn) { QColor color(240, 240, 240); color.setAlphaF(0.39); painter.setBrush(color); } else painter.setBrush(pal.color(QPalette::Base)); QRect rect = this->rect(); QPainterPath path; path.addRoundedRect(rect, RADIUS, RADIUS); painter.drawPath(path); return QFrame::paintEvent(event); } ItemFrame::ItemFrame(QString devName, QWidget *parent) : m_deviceName(devName), QFrame(parent) { deviceLanLayout = new QVBoxLayout(this); deviceLanLayout->setContentsMargins(MAIN_LAYOUT_MARGINS); lanItemFrame = new QFrame(this); lanItemFrame->setFrameShape(QFrame::Shape::NoFrame); lanItemFrame->setContentsMargins(LAYOUT_MARGINS); lanItemLayout = new QVBoxLayout(this); lanItemLayout->setContentsMargins(LAYOUT_MARGINS); lanItemLayout->setSpacing(0); deviceLanLayout->setSpacing(0); setLayout(deviceLanLayout); lanItemFrame->setLayout(lanItemLayout); deviceFrame = new DeviceFrame(devName, this); m_divider = new Divider(this); addNetItem = new AddNetItem(this); deviceLanLayout->addWidget(m_divider); deviceLanLayout->addWidget(deviceFrame); deviceLanLayout->addWidget(lanItemFrame); deviceLanLayout->addWidget(addNetItem); connect(addNetItem, &AddNetItem::itemClick, this, &ItemFrame::addNetItemClick); m_updateNetSpeedThread = new KyNetLoadRateThread(devName); } ItemFrame::~ItemFrame() { if (m_updateNetSpeedThread) { m_updateNetSpeedThread->quit(); m_updateNetSpeedThread->wait(); delete m_updateNetSpeedThread; m_updateNetSpeedThread = nullptr; } } void ItemFrame::showJoinPage(QWidget *widget) { if (nullptr != joinPage) { joinPage->show(); } else { joinPage = new HiddenWiFiPage(deviceFrame->deviceLabel->text(), true, widget); connect(joinPage, &HiddenWiFiPage::destroyed, [=](){ joinPage->disconnect(this); joinPage = nullptr; }); connect(joinPage, &HiddenWiFiPage::connectHideNormalConnect, this, &ItemFrame::connectHideNormalConnect); connect(joinPage, &HiddenWiFiPage::connectHideTtlsConnect, this, &ItemFrame::connectHideTtlsConnect); connect(joinPage, &HiddenWiFiPage::connectHidePeapConnect, this, &ItemFrame::connectHidePeapConnect); joinPage->show(); } } void ItemFrame::startNetSpeedThread() { m_updateNetSpeedThread->start(); } void ItemFrame::stopNetSpeedThread() { if (m_updateNetSpeedThread->isRunning()) { m_updateNetSpeedThread->quit(); } } void ItemFrame::updateNetSpeed() { if (!m_updateNetSpeedThread->isRunning() || lanItemLayout->count() <= 0) { return; } long int rcvRate; long int txRate; WlanItem *wlanItem = nullptr; wlanItem = (WlanItem *)lanItemLayout->itemAt(0)->widget(); if (wlanItem->getStatus()) { m_updateNetSpeedThread->getNetSpeed(rcvRate, txRate); setNetSpeed(rcvRate, txRate, wlanItem); } } void ItemFrame::setNetSpeed(long rcvRate, long txRate, WlanItem *wlanItem) { if (!wlanItem->getStatus()) { return; } int rcvNum = rcvRate; int txNum = txRate; QString strRcv = "0"; QString strTx = "0"; if (rcvNum < 1024) { strRcv = QString::number(rcvNum) + "KB/s"; } else { int remainder; if (rcvNum % 1024 < 100) { remainder = 0; } else { remainder = (rcvNum % 1024) / 100; } strRcv = QString::number(rcvNum / 1024) + "." + QString::number(remainder) + "MB/s"; } if (txNum < 1024) { strTx = QString::number(txNum) + "KB/s"; } else { int remainder; if (txNum % 1024 < 100) { remainder = 0; } else { remainder = (txNum % 1024)/100; } strTx = QString::number(txNum / 1024) + "." + QString::number(remainder) + "MB/s"; } wlanItem->setNetSpeed(strRcv, strTx); } kylin-nm-plugin/plugins/wlanconnect/deviceframe.cpp0000664000175000017500000000423215160520531021503 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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,8,0 #define FRAME_HEIGHT 58 #define LAYOUT_SPACING 16 #define RADIUS 6.0 DeviceFrame::DeviceFrame(QString devName, QWidget *parent) : QFrame(parent) { this->setFrameShape(QFrame::Box); this->setFixedHeight(FRAME_HEIGHT); QHBoxLayout *deviceLayout = new QHBoxLayout(this); deviceLayout->setContentsMargins(LAYOUT_MARGINS); setLayout(deviceLayout); deviceLayout->setSpacing(LAYOUT_SPACING); deviceLabel = new QLabel(this); dropDownLabel = new DrownLabel(devName, this); deviceLayout->addWidget(deviceLabel); deviceLayout->addStretch(); deviceLayout->addWidget(dropDownLabel); } DeviceFrame::~DeviceFrame() { } void DeviceFrame::paintEvent(QPaintEvent *event) { QPalette pal = this->palette(); QPainter painter(this); painter.setRenderHint(QPainter:: Antialiasing, true); //设置渲染,启动反锯齿 painter.setPen(Qt::NoPen); painter.setBrush(pal.color(QPalette::Base)); QRect rect = this->rect(); QPainterPath path; path.addRoundedRect (rect, RADIUS, RADIUS); QRect temp_rect(rect.left(), rect.top() + rect.height()/2, rect.width(), rect.height()/2); path.addRect(temp_rect); painter.drawPath(path); QFrame::paintEvent(event); } kylin-nm-plugin/plugins/wlanconnect/resource.qrc0000664000175000017500000000022515160520531021061 0ustar fengfeng ../res/icon/load-down.png ../res/icon/load-up.png kylin-nm-plugin/plugins/wlanconnect/translate_generation.sh0000775000175000017500000000232415167660365023315 0ustar fengfeng#!/bin/bash # -*- Mode: Shell-script; tab-width: 4; indent-tabs-mode: nil; sh-basic-offset: 4 -*- # # Copyright (C) 2019 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. # export PATH="/usr/lib/qt6/bin:$PATH" 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 kylin-nm-plugin/plugins/wlanconnect/hiddenwifi/0000775000175000017500000000000015167660365020657 5ustar fengfengkylin-nm-plugin/plugins/wlanconnect/hiddenwifi/hiddenwifipage.cpp0000664000175000017500000003303415160520531024314 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 "hiddenwifipage.h" #include #define WINDOW_WIDTH 480 #define MIN_WINDOW_HEIGHT 328 #define PEAP_WINDOW_HEIGHT 494 #define MAX_WINDOW_HEIGHT 540 #define PAGE_LAYOUT_MARGINS 0,0,0,0 #define TOP_LAYOUT_MARGINS 24,14,24,24 #define BOTTOM_LAYOUT_MARGINS 24,24,24,24 #define LAYOUT_SPACING 16 #define LABEL_MIN_WIDTH 150 #define MAX_NAME_LENGTH 32 #define EDIT_MIN_WIDTH 274 HiddenWiFiPage::HiddenWiFiPage(QString interface, bool isLockScreen, QWidget *parent) : m_deviceName(interface), QWidget(parent) { initUI(); initComponent(); setFixedWidth(WINDOW_WIDTH); setAttribute(Qt::WA_DeleteOnClose); if (isLockScreen) { setAttribute(Qt::WA_TranslucentBackground);//设置窗口背景透明 setWindowFlags(Qt::FramelessWindowHint); //设置无边框窗口 setWindowFlags(Qt::Popup); } setJoinBtnEnable(); centerToScreen(); } HiddenWiFiPage::~HiddenWiFiPage() { delete m_bottomDivider; } void HiddenWiFiPage::getSecuType(KySecuType &secuType) { secuType = (KySecuType)m_secuTypeCombox->currentData().toInt(); } void HiddenWiFiPage::paintEvent(QPaintEvent *event) { QPalette pal = qApp->palette(); QColor colorPal = pal.color(QPalette::Window); //设置窗体为圆角 QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); // 反锯齿; painter.setBrush(colorPal); painter.setPen(Qt::transparent); auto rect = this->rect(); painter.drawRoundedRect(rect, 12, 12); //窗口圆角 return QWidget::paintEvent(event); } bool HiddenWiFiPage::eventFilter(QObject *w, QEvent *event) { return QWidget::eventFilter(w, event); } void HiddenWiFiPage::setBtnEnable(bool on) { m_cancelBtn->setEnabled(on); m_joinBtn->setEnabled(on); } void HiddenWiFiPage::initUI() { m_topWidget = new QWidget(this); m_centerWidget = new QWidget(this); m_bottomWidget = new QWidget(this); m_secuWidget = new EntSecurityWidget(true, this); m_descriptionLabel = new QLabel(this); m_nameLabel = new FixLabel(this); m_secuTypeLabel = new FixLabel(this); m_pwdLabel = new QLabel(this); m_emptyLabel = new QLabel(this); m_checkLabel = new QLabel(this); m_nameEdit =new LineEdit(this); m_secuTypeCombox = new QComboBox(this); m_pwdEdit = new KPasswordEdit(this); m_rememberCheckBox = new QCheckBox(this); m_bottomDivider = new Divider(this); // m_showListBtn = new KBorderlessButton(this); m_cancelBtn =new QPushButton(this); m_joinBtn =new QPushButton(this); m_centerWidget->setFixedWidth(WINDOW_WIDTH); m_nameLabel->setFixedWidth(LABEL_MIN_WIDTH); m_secuTypeLabel->setFixedWidth(LABEL_MIN_WIDTH); m_pwdLabel->setFixedWidth(LABEL_MIN_WIDTH); m_scrollArea = new QScrollArea(this); m_scrollArea->setFrameShape(QFrame::NoFrame); m_scrollArea->setWidget(m_centerWidget); m_scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_scrollArea->setFixedWidth(WINDOW_WIDTH); m_scrollArea->setWidgetResizable(true); m_pageLayout = new QVBoxLayout(this); m_pageLayout->setContentsMargins(PAGE_LAYOUT_MARGINS); m_pageLayout->setSpacing(0); m_pageLayout->addWidget(m_topWidget); m_pageLayout->addWidget(m_scrollArea); m_pageLayout->addWidget(m_bottomDivider); m_pageLayout->addWidget(m_bottomWidget); m_topLayout = new QHBoxLayout(m_topWidget); m_topLayout->setContentsMargins(TOP_LAYOUT_MARGINS); m_topLayout->setSpacing(0); m_topLayout->addWidget(m_descriptionLabel); m_topLayout->addStretch(); m_centerVBoxLayout = new QVBoxLayout(m_centerWidget); m_centerVBoxLayout->setContentsMargins(24, 0, 24, 8); m_centerVBoxLayout->setSpacing(0); QWidget *centerWidget = new QWidget(this); QGridLayout *centerLayout = new QGridLayout(centerWidget); centerLayout->setContentsMargins(PAGE_LAYOUT_MARGINS); centerLayout->setVerticalSpacing(LAYOUT_SPACING); //SSID Label和输入框 第0行,第0列,第1列 centerLayout->addWidget(m_nameLabel, 0, 0); centerLayout->addWidget(m_nameEdit, 0, 1); //安全性 Label和选项框 第1行,第0列,第1列 centerLayout->addWidget(m_secuTypeLabel, 1, 0); centerLayout->addWidget(m_secuTypeCombox, 1, 1); //密码 Label和密码框 第2行,第0列,第1列 centerLayout->addWidget(m_pwdLabel, 2, 0); centerLayout->addWidget(m_pwdEdit, 2, 1); //记住该网络复选框 QWidget *checkWidget = new QWidget(this); QHBoxLayout *checkLayout = new QHBoxLayout(checkWidget); checkLayout->setContentsMargins(PAGE_LAYOUT_MARGINS); m_emptyLabel->setMinimumWidth(LABEL_MIN_WIDTH); m_rememberCheckBox->setChecked(true); checkLayout->addWidget(m_emptyLabel); checkLayout->addWidget(m_rememberCheckBox); checkLayout->addWidget(m_checkLabel); checkLayout->addStretch(); m_centerVBoxLayout->addWidget(centerWidget); m_centerVBoxLayout->addWidget(m_secuWidget); m_centerVBoxLayout->addWidget(checkWidget); m_centerVBoxLayout->addStretch(); //底部按钮 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_secuTypeCombox->addItem(tr("None"),NONE); m_secuTypeCombox->addItem(tr("WPA&WPA2 Personal"),WPA_AND_WPA2_PERSONAL); m_secuTypeCombox->addItem(tr("WPA&WPA2 Enterprise"), WPA_AND_WPA2_ENTERPRISE); m_secuTypeCombox->addItem(tr("WPA3 Personal"), WPA3_PERSONAL); //请输入您想要加入的网络信息 m_descriptionLabel->setText(tr("Please enter the network information")); QFont font = m_descriptionLabel->font(); font.setWeight(QFont::Medium); //medium weight m_descriptionLabel->setFont(font); m_nameLabel->setLabelText(tr("Network name(SSID)")); //网络名(SSID) m_secuTypeLabel->setLabelText(tr("Security type")); //安全性 m_pwdLabel->setText(tr("Password")); //密码 m_checkLabel->setText(tr("Remember the Network")); //记住该网络 // 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")); //必填 QString hint = tr("Required"); m_pwdEdit->setPlaceholderText(hint); QRegularExpression rx("^[A-Za-z0-9`~!@#$%^&*()_-+=<>,.\\\/]+$"); QRegularExpressionValidator *latitude = new QRegularExpressionValidator(rx, this); m_pwdEdit->setValidator(latitude); m_pwdEdit->setClearButtonEnabled(false); //禁用ClearBtn按钮 this->setWindowTitle(tr("Find and Join WLAN")); this->setWindowIcon(QIcon::fromTheme("kylin-network")); QPalette pa = m_scrollArea->palette(); pa.setBrush(QPalette::Window, Qt::transparent); m_scrollArea->setPalette(pa); showNone(); } void HiddenWiFiPage::centerToScreen() { QRect desk_rect; QScreen *currentScreen = QGuiApplication::screenAt(QCursor::pos()); if (currentScreen) { desk_rect = currentScreen->geometry(); } else { desk_rect=QGuiApplication::primaryScreen()->geometry(); } int desk_x = desk_rect.width(); int desk_y = desk_rect.height(); int x = this->width(); int y = this->height(); this->move((desk_x - x)/ 2 , (desk_y - y)/ 2); } void HiddenWiFiPage::initComponent() { connect(m_cancelBtn, &QPushButton::clicked, this, [=] { close(); }); connect(m_joinBtn, SIGNAL(clicked()), this, SLOT(on_btnJoin_clicked())); //安全类型变化 connect(m_secuTypeCombox, QOverload::of(&QComboBox::currentIndexChanged), this, &HiddenWiFiPage::onSecuTypeComboxIndexChanged); //按钮状态变化 connect(m_nameEdit, &LineEdit::textChanged, this, &HiddenWiFiPage::setJoinBtnEnable); connect(m_pwdEdit, &LineEdit::textChanged, this, &HiddenWiFiPage::setJoinBtnEnable); connect(m_secuTypeCombox, QOverload::of(&QComboBox::currentIndexChanged), this, &HiddenWiFiPage::setJoinBtnEnable); connect(m_secuWidget, &EntSecurityWidget::setSecuPageState, this, [=](bool status) { m_isSecuOk = status; setJoinBtnEnable(); }); connect(m_secuWidget, &EntSecurityWidget::eapTypeChanged, this, [=](KyEapMethodType type) { setWindowWidth(type); }); } void HiddenWiFiPage::showNone() { this->setFixedHeight(MIN_WINDOW_HEIGHT); m_secuWidget->hide(); m_pwdLabel->hide(); m_pwdEdit->hide(); m_rememberCheckBox->hide(); m_checkLabel->hide(); } void HiddenWiFiPage::showPsk() { this->setFixedHeight(MIN_WINDOW_HEIGHT); m_pwdLabel->show(); m_pwdEdit->show(); m_rememberCheckBox->show(); m_checkLabel->show(); m_secuWidget->hide(); } void HiddenWiFiPage::showEnt() { KyEapMethodType eapType; m_secuWidget->getEnterpriseType(eapType); setWindowWidth(eapType); m_secuWidget->show(); m_rememberCheckBox->show(); m_checkLabel->show(); m_pwdLabel->hide(); m_pwdEdit->hide(); } void HiddenWiFiPage::setJoinBtnEnable() { if (m_nameEdit->text().isEmpty()) { qDebug() << "network name is empty"; m_isJoinBtnEnable = false; } else { int index = m_secuTypeCombox->currentData().toInt(); if (index == NONE) { if (!m_nameEdit->text().isEmpty()) { m_isJoinBtnEnable = true; } } else if (index == WPA_AND_WPA2_PERSONAL || index == WPA3_PERSONAL) { if (m_pwdEdit->text().isEmpty() || m_pwdEdit->text().length() < 8 ) { qDebug() << "password is empty or length < 8"; m_isJoinBtnEnable = false; } else { m_isJoinBtnEnable = true; } } else if (index == WPA_AND_WPA2_ENTERPRISE) { m_isJoinBtnEnable = m_isSecuOk; } } qDebug() << "setJoinBtnEnable "<< m_isJoinBtnEnable; m_joinBtn->setEnabled(m_isJoinBtnEnable); } void HiddenWiFiPage::setWindowWidth(KyEapMethodType eapType) { int type = eapType; if (type == TLS || type == FAST) { this->setFixedHeight(MAX_WINDOW_HEIGHT); } else if (type == PEAP || type == TTLS || type == LEAP || type == PWD) { this->setFixedHeight(PEAP_WINDOW_HEIGHT); } } void HiddenWiFiPage::on_btnJoin_clicked() { qDebug() << "on_btnJoin_clicked"; KyWirelessConnectSetting connSettingInfo; //基本信息 connSettingInfo.m_ssid = m_nameEdit->text(); connSettingInfo.setConnectName(connSettingInfo.m_ssid); connSettingInfo.setIfaceName(m_deviceName); connSettingInfo.isHidden = true; connSettingInfo.m_isAutoConnect = m_rememberCheckBox->isChecked(); connSettingInfo.m_secretFlag = NetworkManager::Setting::SecretFlagType::None; //ipv4 ipv6 connSettingInfo.setIpConfigType(IPADDRESS_V4, CONFIG_IP_DHCP); connSettingInfo.setIpConfigType(IPADDRESS_V6, CONFIG_IP_DHCP); int index = m_secuTypeCombox->currentData().toInt(); if (index == NONE) { Q_EMIT connectHideNormalConnect(connSettingInfo, NONE); } else if (index == WPA_AND_WPA2_PERSONAL || index == WPA3_PERSONAL) { connSettingInfo.m_psk = m_pwdEdit->text(); Q_EMIT connectHideNormalConnect(connSettingInfo, (KySecuType)index); } else if (index == WPA_AND_WPA2_ENTERPRISE) { KyEapMethodType eapType; m_secuWidget->getEnterpriseType(eapType); if (eapType == PEAP) { KyEapMethodPeapInfo info = m_secuWidget->assemblePeapInfo(); Q_EMIT connectHidePeapConnect(info, connSettingInfo); } else if (eapType == TTLS) { KyEapMethodTtlsInfo info = m_secuWidget->assembleTtlsInfo(); Q_EMIT connectHideTtlsConnect(info, connSettingInfo); } else if (eapType == LEAP) { KyEapMethodLeapInfo info = m_secuWidget->assembleLeapInfo(); Q_EMIT connectHideLeapConnect(info, connSettingInfo); } else if (eapType == PWD) { KyEapMethodPwdInfo info = m_secuWidget->assemblePwdInfo(); Q_EMIT connectHidePwdConnect(info, connSettingInfo); } else if (eapType == FAST) { KyEapMethodFastInfo info = m_secuWidget->assembleFastInfo(); Q_EMIT connectHideFastConnect(info, connSettingInfo); } else { qWarning() << "unsupport now!!!"; } } close(); } void HiddenWiFiPage::onSecuTypeComboxIndexChanged() { int index = m_secuTypeCombox->currentData().toInt(); if (index == WPA_AND_WPA2_PERSONAL || index == WPA3_PERSONAL) { showPsk(); } else if (index == WPA_AND_WPA2_ENTERPRISE) { showEnt(); } else if (index == NONE) { showNone(); } centerToScreen(); } kylin-nm-plugin/plugins/wlanconnect/hiddenwifi/entsecuritywidget.cpp0000664000175000017500000007541015160520531025133 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 "entsecuritywidget.h" #include #define LAYOUT_SPACING 16 #define LABEL_MIN_WIDTH 150 #define EDIT_MIN_WIDTH 274 #define HORIZON_SPACING 8 #define ROW_MIN_HEIGHT 36 EntSecurityWidget::EntSecurityWidget(bool isLockScreen, QWidget *parent) : m_isLockScreen(isLockScreen), QWidget(parent) { initUI(); initConnect(); } EntSecurityWidget::~EntSecurityWidget() { // if (m_loginHintDialog != nullptr) { // delete m_loginHintDialog; // } } void EntSecurityWidget::getEnterpriseType(KyEapMethodType &enterpriseType) { enterpriseType = (KyEapMethodType)m_eapTypeCombox->currentData().toInt(); } void EntSecurityWidget::initUI() { //企业wifi共有 m_eapTypeLabel = new QLabel(this); m_eapTypeCombox = new QComboBox(this); //TLS m_identityLable = new QLabel(this); m_domainLable = new QLabel(this); m_caCertPathLabel = new QLabel(this); m_caNeedFlagLabel = new QLabel(this); m_clientCertPathLabel = new FixLabel(this); m_clientPrivateKeyLabel = new FixLabel(this); m_clientPrivateKeyPwdLabel = new FixLabel(this); m_pwdOptionLabel = new FixLabel(this); //TLS m_identityEdit = new LineEdit(this); m_domainEdit = new LineEdit(this); m_caCertPathCombox = new QComboBox(this); m_caNeedBox = new QCheckBox(this); m_clientCertPathCombox = new QComboBox(this); m_clientPrivateKeyCombox = new QComboBox(this); m_clientPrivateKeyPwdEdit = new KPasswordEdit(this); m_pwdOptionCombox = new QComboBox(this); // m_loginHintDialog = new LogHintDialog(this->parentWidget()); //PEAP TTLS共有 m_eapMethodLabel = new FixLabel(this); m_userNameLabel = new QLabel(this); m_userPwdLabel = new QLabel(this); m_eapMethodCombox = new QComboBox(this); m_userNameEdit = new LineEdit(this); m_userPwdEdit = new KPasswordEdit(this); //FAST m_pacProvisionComboBox = new QComboBox(this); m_pacFilePathComboBox = new QComboBox(this); m_pacProvisionLabel = new FixLabel(this); m_pacCheckBox = new QCheckBox(this); m_pacFileLabel = new QLabel(this); m_pacProvisionLabel->setFixedWidth(LABEL_MIN_WIDTH); //允许自动PAC配置复选框 m_pacCheckWidget = new QWidget(this); m_pacCheckWidget->setMinimumHeight(72); QVBoxLayout *pacCheckLayout = new QVBoxLayout(m_pacCheckWidget); pacCheckLayout->setContentsMargins(0, 0, 0, 0); pacCheckLayout->setSpacing(0); pacCheckLayout->addWidget(m_pacProvisionComboBox); pacCheckLayout->addWidget(m_pacCheckBox); //main layout QGridLayout *mainLayout = new QGridLayout(this); mainLayout->setContentsMargins(0, 16, 0, 0); mainLayout->setColumnMinimumWidth(0, LABEL_MIN_WIDTH); mainLayout->setColumnMinimumWidth(1, EDIT_MIN_WIDTH); mainLayout->setVerticalSpacing(LAYOUT_SPACING); // EAP认证 Label和选项框 第0行,第0列,第1列 mainLayout->addWidget(m_eapTypeLabel, 0, 0); mainLayout->addWidget(m_eapTypeCombox, 0, 1); // 匿名身份 Label和输入框 第1行,第0列,第1列 mainLayout->addWidget(m_identityLable, 1, 0); mainLayout->addWidget(m_identityEdit, 1, 1); //PAC配置 允许自动PAC配置 第2行,第0列;第2行,第1列,占2行1列 mainLayout->addWidget(m_pacProvisionLabel, 2, 0, Qt::AlignTop); mainLayout->addWidget(m_pacCheckWidget, 2, 1); // PAC文件 mainLayout->addWidget(m_pacFileLabel, 4, 0); mainLayout->addWidget(m_pacFilePathComboBox, 4, 1); //内部认证 Label和选项框 第5行,第0列,第1列 mainLayout->addWidget(m_eapMethodLabel, 5, 0); mainLayout->addWidget(m_eapMethodCombox, 5, 1); //用户名 Label和输入框 第6行,第0列,第1列 mainLayout->addWidget(m_userNameLabel, 6, 0); mainLayout->addWidget(m_userNameEdit, 6, 1); //密码 Label和密码框 第7行,第0列,第1列 mainLayout->addWidget(m_userPwdLabel, 7, 0); mainLayout->addWidget(m_userPwdEdit, 7, 1); m_tlsWidget = new QWidget(this); QGridLayout *bottomLayout = new QGridLayout(m_tlsWidget); bottomLayout->setContentsMargins(0, 0, 0, 0); bottomLayout->setColumnMinimumWidth(0, LABEL_MIN_WIDTH); bottomLayout->setVerticalSpacing(8); // 域 Label和输入框 第0行,第0列,第1列 bottomLayout->addWidget(m_domainLable, 0, 0); bottomLayout->addWidget(m_domainEdit, 0, 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(m_caCertPathCombox, 0, 0, 1, 2); checkLayout->addWidget(m_caNeedBox, 1, 0); checkLayout->addWidget(m_caNeedFlagLabel, 1, 1); // CA证书 Label第1行,第0列 bottomLayout->addWidget(m_caCertPathLabel, 1, 0); // CA证书选项框 不需要CA证书复选框 从第1行,第1列开始,占2行1列 bottomLayout->addWidget(CaWidget, 1, 1, 2, 1); // 用户证书 Label和选项框 第3行,第0列,第1列 bottomLayout->addWidget(m_clientCertPathLabel, 3, 0); bottomLayout->addWidget(m_clientCertPathCombox, 3, 1); // 用户私钥 Label和选项框 第4行,第0列,第1列 bottomLayout->addWidget(m_clientPrivateKeyLabel, 4, 0); bottomLayout->addWidget(m_clientPrivateKeyCombox, 4, 1); // 私钥密码 Label和密码框 第5行,第0列,第1列 bottomLayout->addWidget(m_clientPrivateKeyPwdLabel, 5, 0); bottomLayout->addWidget(m_clientPrivateKeyPwdEdit, 5, 1); // 密码选项 Label和选项框 第6行,第0列,第1列 bottomLayout->addWidget(m_pwdOptionLabel, 6, 0); bottomLayout->addWidget(m_pwdOptionCombox, 6, 1); mainLayout->addWidget(m_tlsWidget, 8, 0, 6,2); m_eapMethodLabel->setFixedWidth(LABEL_MIN_WIDTH); m_clientCertPathLabel->setFixedWidth(LABEL_MIN_WIDTH); m_clientPrivateKeyLabel->setFixedWidth(LABEL_MIN_WIDTH); m_clientPrivateKeyPwdLabel->setFixedWidth(LABEL_MIN_WIDTH); m_pwdOptionLabel->setFixedWidth(LABEL_MIN_WIDTH); //企业wifi共有 m_eapTypeLabel->setText(tr("EAP type")); //TLS m_identityLable->setText(tr("Identity")); m_domainLable->setText(tr("Domain")); m_caCertPathLabel->setText(tr("CA certficate")); m_caNeedFlagLabel->setText(tr("no need for CA certificate")); m_clientCertPathLabel->setLabelText(tr("User certificate")); m_clientPrivateKeyLabel->setLabelText(tr("User private key")); m_clientPrivateKeyPwdLabel->setLabelText(tr("User key password")); m_pwdOptionLabel->setLabelText(tr("Password options")); QString hint = tr("Required"); m_identityEdit->setPlaceholderText(tr("Required")); //必填 m_clientPrivateKeyPwdEdit->setPlaceholderText(hint); m_clientPrivateKeyPwdEdit->setUseCustomPalette(true);//一定要设置这个不然点击就变回主题颜色了 m_userPwdEdit->setUseCustomPalette(true); QPalette pal = this->palette(); pal.setColor(QPalette::ButtonText, Qt::black); m_clientPrivateKeyPwdEdit->setPalette(pal); m_userPwdEdit->setPalette(pal); m_clientPrivateKeyPwdEdit->setEnabled(true); m_userPwdEdit->setEnabled(true); //PEAP TTLS共有 m_eapMethodLabel->setLabelText(tr("Ineer authentication")); m_userNameLabel->setText(tr("Username")); m_userPwdLabel->setText(tr("Password")); m_userNameEdit->setPlaceholderText(tr("Required")); m_userPwdEdit->setPlaceholderText(hint); m_eapTypeCombox->addItem("TLS", TLS); m_eapTypeCombox->addItem("PEAP", PEAP); m_eapTypeCombox->addItem("TTLS", TTLS); m_eapTypeCombox->addItem("LEAP", LEAP); m_eapTypeCombox->addItem("PWD", PWD); m_eapTypeCombox->addItem("FAST", FAST); m_eapTypeCombox->setCurrentIndex(TLS); //TLS m_caCertPathCombox->addItem(tr("None"), QString(tr("None"))); //无 if (!m_isLockScreen) m_caCertPathCombox->addItem(tr("Choose from file..."), QString(tr("Choose from file..."))); //从文件中选择... else m_caCertPathCombox->addItem(tr("Please log in to the system first."), QString(tr("Please log in to the system first."))); m_clientCertPathCombox->addItem(tr("None"), QString(tr("None"))); //无 if (!m_isLockScreen) m_clientCertPathCombox->addItem(tr("Choose from file..."), QString(tr("Choose from file..."))); //从文件中选择... else m_clientCertPathCombox->addItem(tr("Please log in to the system first."), QString(tr("Please log in to the system first."))); m_clientPrivateKeyCombox->addItem(tr("None"), QString(tr("None"))); //无 if (!m_isLockScreen) m_clientPrivateKeyCombox->addItem(tr("Choose from file..."), QString(tr("Choose from file..."))); //从文件中选择... else m_clientPrivateKeyCombox->addItem(tr("Please log in to the system first."), QString(tr("Please log in to the system first."))); m_pwdOptionCombox->addItem(tr("Store passwords only for this user"), QString(tr("Store passwords only for this user"))); //仅为该用户存储密码 m_pwdOptionCombox->addItem(tr("Store passwords for all users"), QString(tr("Store passwords for all users"))); //存储所有用户的密码 m_pwdOptionCombox->addItem(tr("Ask this password every time"), QString(tr("Ask this password every time"))); //每次询问这个密码 //FAST m_pacProvisionLabel->setLabelText(tr("PAC provisioning")); //PAC配置 m_pacCheckBox->setChecked(true); QString pacFlagText = tr("Allow automatic PAC provisioning"); //允许自动PAC配置 QFontMetrics fontMetrics(this->font()); int fontSize = fontMetrics.horizontalAdvance(pacFlagText); if (fontSize > 240) { //最大宽度240像素 QString elideNote = fontMetrics.elidedText(pacFlagText, Qt::ElideRight, 240); m_pacCheckBox->setText(elideNote); m_pacCheckBox->setToolTip(tr("Allow automatic PAC provisioning")); } else { m_pacCheckBox->setText(pacFlagText); } m_pacFileLabel->setText(tr("PAC file")); //PAC文件 m_pacProvisionComboBox->addItem(tr("Anonymous"), ANON); //匿名 m_pacProvisionComboBox->addItem(tr("Authenticated"), AUTHEN); //已认证 m_pacProvisionComboBox->addItem(tr("Both"), BOTH); //两者兼用 m_pacProvisionComboBox->setCurrentIndex(0); m_pacFilePathComboBox->addItem(tr("None"), QString(tr("None"))); //无 if (!m_isLockScreen) m_pacFilePathComboBox->addItem(tr("Choose from file..."), QString(tr("Choose from file..."))); //从文件中选择... else m_pacFilePathComboBox->addItem(tr("Please log in to the system first."), QString(tr("Please log in to the system first."))); QRegularExpression rx("^[A-Za-z0-9`~!@#$%^&*()_-+=<>,.\\\/]+$"); QRegularExpressionValidator *latitude = new QRegularExpressionValidator(rx, this); m_clientPrivateKeyPwdEdit->setValidator(latitude); m_userPwdEdit->setValidator(latitude); //禁用ClearBtn按钮 m_clientPrivateKeyPwdEdit->setClearButtonEnabled(false); m_userPwdEdit->setClearButtonEnabled(false); showTls(); } void EntSecurityWidget::initConnect() { //EAP方式变化 connect(m_eapTypeCombox, QOverload::of(&QComboBox::currentIndexChanged), this, &EntSecurityWidget::onEapTypeComboxIndexChanged); connect(m_caNeedBox, &QCheckBox::clicked, this, &EntSecurityWidget::onCaNeedBoxClicked); connect(m_caCertPathCombox, &QComboBox::currentTextChanged, this, &EntSecurityWidget::onCaCertPathComboxIndexChanged); connect(m_clientCertPathCombox, &QComboBox::currentTextChanged, this, &EntSecurityWidget::onClientCertPathComboxIndexChanged); connect(m_clientPrivateKeyCombox, &QComboBox::currentTextChanged, this, &EntSecurityWidget::onClientPrivateKeyComboxIndexChanged); connect(m_eapTypeCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(setEnableOfSaveBtn())); connect(m_identityEdit, &LineEdit::textChanged, this, &EntSecurityWidget::setEnableOfSaveBtn); connect(m_caCertPathCombox, SIGNAL(currentTextChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(m_caNeedBox, &QCheckBox::stateChanged, this, &EntSecurityWidget::setEnableOfSaveBtn); connect(m_clientCertPathCombox, SIGNAL(currentTextChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(m_clientPrivateKeyCombox, SIGNAL(currentTextChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(m_clientPrivateKeyPwdEdit, &LineEdit::textChanged, this, &EntSecurityWidget::setEnableOfSaveBtn); connect(m_eapMethodCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(setEnableOfSaveBtn())); connect(m_userNameEdit, &LineEdit::textChanged, this, &EntSecurityWidget::setEnableOfSaveBtn); connect(m_userPwdEdit, &LineEdit::textChanged, this, &EntSecurityWidget::setEnableOfSaveBtn); // connect(m_loginHintDialog, &LogHintDialog::LogHintDialogClosed, this, &EntSecurityWidget::setComboxIndex); connect(m_pacCheckBox, &QCheckBox::stateChanged, this, &EntSecurityWidget::setEnableOfSaveBtn); connect(m_pacProvisionComboBox, SIGNAL(currentTextChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(m_pacFilePathComboBox, SIGNAL(currentTextChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(m_pacCheckBox, &QCheckBox::clicked, this, &EntSecurityWidget::onPacBoxClicked); connect(m_pacFilePathComboBox, &QComboBox::currentTextChanged, this, &EntSecurityWidget::onPacFilePathComboxIndexChanged); } void EntSecurityWidget::showTls() { //TLS m_identityLable->show(); m_identityEdit->show(); m_tlsWidget->show(); //PEAP TTLS共有 m_eapMethodLabel->hide(); m_userNameLabel->hide(); m_userPwdLabel->hide(); m_eapMethodCombox->hide(); m_userNameEdit->hide(); m_userPwdEdit->hide(); //FAST m_pacProvisionLabel->hide(); m_pacCheckWidget->hide(); m_pacFileLabel->hide(); m_pacFilePathComboBox->hide(); } void EntSecurityWidget::showPeapOrTtls() { //TLS m_identityLable->hide(); m_identityEdit->hide(); m_tlsWidget->hide(); //PEAP TTLS共有 m_eapMethodLabel->show(); m_userNameLabel->show(); m_userPwdLabel->show(); m_eapMethodCombox->show(); m_userNameEdit->show(); m_userPwdEdit->show(); //FAST m_pacProvisionLabel->hide(); m_pacCheckWidget->hide(); m_pacFileLabel->hide(); m_pacFilePathComboBox->hide(); } void EntSecurityWidget::showLeapOrPwd() { //TLS m_identityLable->hide(); m_identityEdit->hide(); m_tlsWidget->hide(); //PEAP TTLS共有 m_eapMethodLabel->hide(); m_userNameLabel->show(); m_userPwdLabel->show(); m_eapMethodCombox->hide(); m_userNameEdit->show(); m_userPwdEdit->show(); //FAST m_pacProvisionLabel->hide(); m_pacCheckWidget->hide(); m_pacFileLabel->hide(); m_pacFilePathComboBox->hide(); } void EntSecurityWidget::showFast() { //TLS m_identityLable->show(); m_identityEdit->show(); m_tlsWidget->hide(); //PEAP TTLS共有 m_eapMethodLabel->show(); m_userNameLabel->show(); m_userPwdLabel->show(); m_eapMethodCombox->show(); m_userNameEdit->show(); m_userPwdEdit->show(); //FAST m_pacProvisionLabel->show(); m_pacCheckWidget->show(); m_pacFileLabel->show(); m_pacFilePathComboBox->show(); } bool EntSecurityWidget::checkConnectBtnIsEnabled() { int type = m_eapTypeCombox->currentData().toInt(); if (type == TLS) { return false; if (m_identityEdit->text().isEmpty()) { qDebug() << "tls identity is empty"; return false; } QFile cafile(m_caCertPathCombox->currentText()); if(!m_caNeedBox->isChecked() && !cafile.exists()) { qDebug() << "ca cert filepath " << m_caCertPathCombox->currentText() << " is invalid"; return false; } QFile cliCafile(m_clientCertPathCombox->currentText()); if(!cliCafile.exists()) { qDebug() << "client cert filepath " << m_clientCertPathCombox->currentText() << " is invalid"; return false; } QFile cliKeyfile(m_clientPrivateKeyCombox->currentText()); if(!cliKeyfile.exists()) { qDebug() << "client private key filepath " << m_clientPrivateKeyCombox->currentText() << " is invalid"; return false; } if(m_clientPrivateKeyPwdEdit->text().isEmpty()) { qDebug() << "client Private Key password is empty"; return false; } } else if (type == PEAP || type == TTLS || type == LEAP || type == PWD) { if(m_userNameEdit->text().isEmpty() || m_userPwdEdit->text().isEmpty()) { qDebug() << "user name or user password is empty"; return false; } } else if (type == FAST) { if (m_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_userNameEdit->text().isEmpty() || m_userPwdEdit->text().isEmpty()) { qDebug() << "user name or user password is empty"; return false; } } return true; } void EntSecurityWidget::onEapTypeComboxIndexChanged() { qDebug() << "onEapTypeComboxIndexChanged"; int index = m_eapTypeCombox->currentData().toInt(); if (index == TLS) { showTls(); Q_EMIT this->eapTypeChanged(TLS); } else if (index == PEAP) { showPeapOrTtls(); m_eapMethodCombox->clear(); m_eapMethodCombox->addItem("MSCHAPv2", MSCHAPV2_PEAP); m_eapMethodCombox->addItem("MD5", MD5_PEAP); m_eapMethodCombox->addItem("GTC", GTC_PEAP); Q_EMIT this->eapTypeChanged(PEAP); } else if (index == TTLS) { showPeapOrTtls(); m_eapMethodCombox->clear(); m_eapMethodCombox->addItem("pap", PAP); m_eapMethodCombox->addItem("mschap", MSCHAP); m_eapMethodCombox->addItem("mschapv2(eap)", MSCHAPV2_EAP); m_eapMethodCombox->addItem("mschapv2", MSCHAPV2); m_eapMethodCombox->addItem("chap", CHAP); m_eapMethodCombox->addItem("md5(eap)", MD5_EAP); m_eapMethodCombox->addItem("gtc(eap)", GTC_EAP); Q_EMIT this->eapTypeChanged(TTLS); } else if (index == LEAP) { showLeapOrPwd(); Q_EMIT this->eapTypeChanged(LEAP); } else if (index == PWD) { showLeapOrPwd(); Q_EMIT this->eapTypeChanged(PWD); } else if (index == FAST) { showFast(); m_eapMethodCombox->clear(); m_eapMethodCombox->addItem("GTC", GTC_FAST); m_eapMethodCombox->addItem("MSCHAPv2", MSCHAPV2_FAST); Q_EMIT this->eapTypeChanged(FAST); } } void EntSecurityWidget::setEnableOfSaveBtn() { Q_EMIT setSecuPageState(checkConnectBtnIsEnabled()); } void EntSecurityWidget::onCaNeedBoxClicked() { if (m_caNeedBox->isChecked()) { m_caCertPathCombox->setItemText(0, tr("None")); m_caCertPathCombox->setEnabled(false); } else { m_caCertPathCombox->setEnabled(true); } } void EntSecurityWidget::onPacBoxClicked() { if (!m_pacCheckBox->isChecked()) { m_pacProvisionComboBox->setCurrentIndex(ANON); m_pacProvisionComboBox->setEnabled(false); } else { m_pacProvisionComboBox->setEnabled(true); } } void EntSecurityWidget::onCaCertPathComboxIndexChanged(QString str) { if (m_isLockScreen) { if (m_caCertPathCombox->isEnabled()) { // m_loginHintDialog->show(); } } else { if (str.contains("Choose from file...") || str.contains("从文件选择...")) { QString fileName = QFileDialog::getOpenFileName(this, tr("Choose a CA certificate"), "recent:///", tr("CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx)")); if (!fileName.isNull()) { QStringList nameList = fileName.split("/"); m_caCertPathCombox->blockSignals(true); m_caCertPathCombox->setItemText(0, fileName); m_caCertPathCombox->setCurrentIndex(0); m_caCertPathCombox->blockSignals(false); } else { m_caCertPathCombox->blockSignals(true); m_caCertPathCombox->setItemText(0, tr("None")); m_caCertPathCombox->setCurrentIndex(0); m_caCertPathCombox->blockSignals(false); } } else { qWarning() << "Choose file is null or unvalible"; } } } void EntSecurityWidget::onClientCertPathComboxIndexChanged(QString str) { if (m_isLockScreen) { if (m_clientCertPathCombox->isEnabled()) { // m_loginHintDialog->show(); } } else { if (str.contains("Choose from file...") || str.contains("从文件选择...")) { QString fileName = QFileDialog::getOpenFileName(this, tr("Choose a CA certificate"), "recent:///", tr("CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx)")); if (!fileName.isNull()) { m_clientCertPathCombox->blockSignals(true); m_clientCertPathCombox->setItemText(0, fileName); m_clientCertPathCombox->setCurrentIndex(0); m_clientCertPathCombox->blockSignals(false); } else { m_clientCertPathCombox->blockSignals(true); m_clientCertPathCombox->setItemText(0, tr("None")); m_clientCertPathCombox->setCurrentIndex(0); m_clientCertPathCombox->blockSignals(false); } } else { qWarning() << "Choose file is null or unvalible"; } } } void EntSecurityWidget::onClientPrivateKeyComboxIndexChanged(QString str) { if (m_isLockScreen) { if (m_clientPrivateKeyCombox->isEnabled()) { // m_loginHintDialog->show(); } } else { if (str.contains("Choose from file...") || str.contains("从文件选择...")) { QString fileName = QFileDialog::getOpenFileName(this, tr("Choose a CA certificate"), "recent:///", tr("CA Files (*.pem *.der *.p12 *.crt *.cer *.pfx)")); if (!fileName.isNull()) { QStringList nameList = fileName.split("/"); m_clientPrivateKeyCombox->blockSignals(true); m_clientPrivateKeyCombox->setItemText(0, fileName); m_clientPrivateKeyCombox->setCurrentIndex(0); m_clientPrivateKeyCombox->blockSignals(false); } else { m_clientPrivateKeyCombox->blockSignals(true); m_clientPrivateKeyCombox->setItemText(0, tr("None")); m_clientPrivateKeyCombox->setCurrentIndex(0); m_clientPrivateKeyCombox->blockSignals(false); } } else { qWarning() << "Choose file is null or unvalible"; } } } void EntSecurityWidget::onPacFilePathComboxIndexChanged(QString str) { if (m_isLockScreen) { return; } else { if (str.contains("Choose from file...") || str.contains("从文件选择...")) { QString fileName = QFileDialog::getOpenFileName(this, tr("Choose a PAC file"), "recent:///", tr("PAC Files (*.pac)")); if (!fileName.isNull()) { QStringList nameList = fileName.split("/"); m_pacFilePathComboBox->blockSignals(true); m_pacFilePathComboBox->setItemText(0, fileName); m_pacFilePathComboBox->setCurrentIndex(0); m_pacFilePathComboBox->blockSignals(false); } else { m_pacFilePathComboBox->blockSignals(true); m_pacFilePathComboBox->setItemText(0, tr("None")); m_pacFilePathComboBox->setCurrentIndex(0); m_pacFilePathComboBox->blockSignals(false); } } else { qWarning() << "Choose file is null or unvalible"; } } } void EntSecurityWidget::setComboxIndex() { if (m_caCertPathCombox->isEnabled()) { m_caCertPathCombox->setCurrentIndex(0); } if (m_clientCertPathCombox->isEnabled()) { m_clientCertPathCombox->setCurrentIndex(0); } if (m_clientPrivateKeyCombox->isEnabled()) { m_clientPrivateKeyCombox->setCurrentIndex(0); } } KyEapMethodPeapInfo EntSecurityWidget::assemblePeapInfo() { KyEapMethodPeapInfo info; switch (m_eapMethodCombox->currentIndex()) { case 0: info.phase2AuthMethod = KyAuthMethodMschapv2; break; case 1: info.phase2AuthMethod = KyAuthMethodMd5; break; case 2: info.phase2AuthMethod = KyAuthMethodGtc; break; default: break; } info.userName = m_userNameEdit->text(); info.userPWD = m_userPwdEdit->text(); info.m_passwdFlag = NetworkManager::Setting::None; // switch (m_pwdOptionCombox->currentIndex()) { // case 0: // info.m_passwdFlag = NetworkManager::Setting::AgentOwned; // info.userPWD = m_userPwdEdit->text(); // break; // case 1: // info.m_passwdFlag = NetworkManager::Setting::None; // info.userPWD = m_userPwdEdit->text(); // break; // case 2: // info.m_passwdFlag = NetworkManager::Setting::NotSaved; // break; // default: // break; // } return info; } KyEapMethodTtlsInfo EntSecurityWidget::assembleTtlsInfo() { KyEapMethodTtlsInfo info; switch (m_eapMethodCombox->currentIndex()) { case PAP: info.authType = AUTH_NO_EAP; info.authNoEapMethod = KyAuthMethodPap; break; case MSCHAP: info.authType = AUTH_NO_EAP; info.authNoEapMethod = KyAuthMethodChap; break; case MSCHAPV2_EAP: info.authType = AUTH_EAP; info.authEapMethod = KyAuthEapMethodMschapv2; break; case MSCHAPV2: info.authType = AUTH_NO_EAP; info.authNoEapMethod = KyAuthMethodMschapv2; break; case CHAP: info.authType = AUTH_NO_EAP; info.authNoEapMethod = KyAuthMethodChap; break; case MD5_EAP: info.authType = AUTH_EAP; info.authEapMethod = KyAuthEapMethodMd5; break; case GTC_EAP: info.authType = AUTH_EAP; info.authEapMethod = KyAuthEapMethodGtc; break; default: break; } info.userName = m_userNameEdit->text(); info.m_passwdFlag = NetworkManager::Setting::None; info.userPWD = m_userPwdEdit->text(); // switch (m_pwdOptionCombox->currentIndex()) { // case 0: // info.m_passwdFlag = NetworkManager::Setting::AgentOwned; // info.userPWD = m_userPwdEdit->text(); // break; // case 1: // info.m_passwdFlag = NetworkManager::Setting::None; // info.userPWD = m_userPwdEdit->text(); // break; // case 2: // info.m_passwdFlag = NetworkManager::Setting::NotSaved; // break; // default: // break; // } return info; } KyEapMethodLeapInfo EntSecurityWidget::assembleLeapInfo() { KyEapMethodLeapInfo info; info.m_userName = m_userNameEdit->text(); info.m_userPwd = m_userPwdEdit->text(); info.m_passwdFlag = NetworkManager::Setting::None; return info; } KyEapMethodPwdInfo EntSecurityWidget::assemblePwdInfo() { KyEapMethodPwdInfo info; info.m_userName = m_userNameEdit->text(); info.m_userPwd = m_userPwdEdit->text(); info.m_passwdFlag = NetworkManager::Setting::None; return info; } KyEapMethodFastInfo EntSecurityWidget::assembleFastInfo() { KyEapMethodFastInfo info; info.m_anonIdentity = m_identityEdit->text(); switch (m_pacProvisionComboBox->currentIndex()) { case ANON: info.m_pacProvisioning = KyFastProvisioningAllowUnauthenticated; break; case AUTHEN: info.m_pacProvisioning = KyFastProvisioningAllowAuthenticated; break; case BOTH: info.m_pacProvisioning = KyFastProvisioningAllowBoth; break; default: break; } info.m_allowAutoPacFlag = m_pacCheckBox->isChecked(); info.m_pacFilePath = m_pacFilePathComboBox->currentText(); switch (m_eapMethodCombox->currentIndex()) { case GTC_FAST: info.m_authMethod = KyAuthMethodGtc; break; case MSCHAPV2_FAST: info.m_authMethod = KyAuthMethodMschapv2; break; default: break; } info.m_userName = m_userNameEdit->text(); info.m_userPwd = m_userPwdEdit->text(); info.m_passwdFlag = NetworkManager::Setting::None; return info; } #define ICON_SIZE 16,16 LogHintDialog::LogHintDialog(QWidget *parent) : KDialog(parent) { //弹窗 TLS添加本地文件 登录系统提示 m_iconLabel = new QLabel(this); m_contentLabel = new QLabel(this); m_confirmBtn = new QPushButton(this); m_dialogLayout = new QVBoxLayout(this); m_dialogLayout->setContentsMargins(20, 0, 24, 23); m_dialogLayout->setSpacing(0); this->setFixedSize(420, 168); this->closeButton(); QIcon m_icon = QIcon::fromTheme("dialog-warning"); m_iconLabel->setPixmap(m_icon.pixmap(ICON_SIZE)); m_contentLabel->setText(tr("Please log in to the system first.")); m_confirmBtn->setText(tr("Confirm")); QWidget *tipWidget = new QWidget(this); QHBoxLayout *tipLayout = new QHBoxLayout(tipWidget); tipLayout->addWidget(m_iconLabel); tipLayout->addWidget(m_contentLabel); tipLayout->addStretch(); QWidget *btnWidget = new QWidget(this); QHBoxLayout *btnLayout = new QHBoxLayout(btnWidget); btnLayout->addStretch(); btnLayout->addWidget(m_confirmBtn); m_dialogLayout->addWidget(tipWidget); m_dialogLayout->addStretch(); m_dialogLayout->addWidget(btnWidget); this->mainWidget()->setLayout(m_dialogLayout); connect(m_confirmBtn, &QPushButton::clicked, this, [=] { Q_EMIT LogHintDialogClosed(); close(); }); connect(this->closeButton(), &QPushButton::clicked, this, [=] { Q_EMIT LogHintDialogClosed(); close(); }); } kylin-nm-plugin/plugins/wlanconnect/hiddenwifi/hiddenwifi.pri0000664000175000017500000000044715160520516023474 0ustar fengfeng #LIBINTERFACE_NAME = $$qtLibraryTarget(divider) SOURCES += \ $$PWD/enterprisewlanpage.cpp \ $$PWD/entsecuritywidget.cpp \ $$PWD/hiddenwifipage.cpp \ HEADERS += \ $$PWD/enterprisewlanpage.h \ $$PWD/entsecuritywidget.h \ $$PWD/hiddenwifipage.h \ kylin-nm-plugin/plugins/wlanconnect/hiddenwifi/enterprisewlanpage.h0000664000175000017500000000447715167660365024743 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 ENTERPRISEWLANPAGE_H #define ENTERPRISEWLANPAGE_H #include #include #include #include #include #include #include "entsecuritywidget.h" class EnterpriseWlanPage : public QWidget { Q_OBJECT public: EnterpriseWlanPage(QString ssid, QString device, bool isLockScreen, QWidget *parent = nullptr); protected: void paintEvent(QPaintEvent *event); private: void initUI(); void initConnections(); void centerToScreen(); private: QString m_deviceName; QString m_ssid; QLabel *m_ssidTitleLabel; QLabel *m_ssidLabel; EntSecurityWidget *m_entSecurityWidget = nullptr; QPushButton *m_cancelBtn; QPushButton *m_connectBtn; QWidget *m_ssidWidget; QWidget *m_btnWidget; QVBoxLayout *m_mainLayout; private Q_SLOTS: void onBtnConnectClicked(); void onEapTypeChanged(const KyEapMethodType &type); Q_SIGNALS: void connectPeapConnect(KyEapMethodPeapInfo info, KyWirelessConnectSetting connSettingInfo); void connectTtlsConnect(KyEapMethodTtlsInfo info, KyWirelessConnectSetting connSettingInfo); void connectLeapConnect(KyEapMethodLeapInfo info, KyWirelessConnectSetting connSettingInfo); void connectPwdConnect(KyEapMethodPwdInfo info, KyWirelessConnectSetting connSettingInfo); void connectFastConnect(KyEapMethodFastInfo info, KyWirelessConnectSetting connSettingInfo); }; #endif // ENTERPRISEWLANPAGE_H kylin-nm-plugin/plugins/wlanconnect/hiddenwifi/enterprisewlanpage.cpp0000664000175000017500000001513515160520531025246 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 "enterprisewlanpage.h" #include #define MAIN_SIZE_EXPAND 480,550 #define MAIN_SIZE_NARROW 480,340 #define PAGE_LAYOUT_MARGINS 24,0,24,0 #define TOP_LAYOUT_MARGINS 0,14,0,0 #define BOTTOM_LAYOUT_MARGINS 0,8,0,24 #define LABEL_MIN_WIDTH 150 EnterpriseWlanPage::EnterpriseWlanPage(QString ssid, QString device, bool isLockScreen, QWidget *parent) : m_ssid(ssid), m_deviceName(device), QWidget(parent) { initUI(); initConnections(); setAttribute(Qt::WA_DeleteOnClose); if (isLockScreen) { setAttribute(Qt::WA_TranslucentBackground);//设置窗口背景透明 setWindowFlags(Qt::FramelessWindowHint); //设置无边框窗口 setWindowFlags(Qt::Popup); } centerToScreen(); } void EnterpriseWlanPage::paintEvent(QPaintEvent *event) { QPalette pal = qApp->palette(); QColor colorPal = pal.color(QPalette::Window); //设置窗体为圆角 QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); // 反锯齿; painter.setBrush(colorPal); painter.setPen(Qt::transparent); auto rect = this->rect(); painter.drawRoundedRect(rect, 12, 12); //窗口圆角 return QWidget::paintEvent(event); } void EnterpriseWlanPage::initUI() { m_ssidTitleLabel = new QLabel(this); m_ssidTitleLabel->setMinimumWidth(LABEL_MIN_WIDTH); m_ssidLabel = new QLabel(this); m_entSecurityWidget = new EntSecurityWidget(this); m_cancelBtn = new QPushButton(this); m_connectBtn = new QPushButton(this); m_connectBtn->setEnabled(false); m_ssidWidget = new QWidget(this); m_btnWidget = new QWidget(this); m_mainLayout = new QVBoxLayout(this); this->setLayout(m_mainLayout); m_mainLayout->setContentsMargins(PAGE_LAYOUT_MARGINS); m_mainLayout->setSpacing(0); m_mainLayout->addWidget(m_ssidWidget); m_mainLayout->addWidget(m_entSecurityWidget); m_mainLayout->addStretch(); m_mainLayout->addWidget(m_btnWidget); QHBoxLayout *ssidLayout = new QHBoxLayout(m_ssidWidget); m_ssidWidget->setMaximumHeight(40); ssidLayout->setContentsMargins(TOP_LAYOUT_MARGINS); ssidLayout->addWidget(m_ssidTitleLabel); ssidLayout->addWidget(m_ssidLabel); ssidLayout->addStretch(); QHBoxLayout *btnLayout = new QHBoxLayout(m_btnWidget); btnLayout->setContentsMargins(BOTTOM_LAYOUT_MARGINS); btnLayout->setSpacing(16); btnLayout->addStretch(); btnLayout->addWidget(m_cancelBtn); btnLayout->addWidget(m_connectBtn); m_ssidTitleLabel->setText(tr("Network name(SSID)")); //网络名(SSID) m_ssidLabel->setText(m_ssid); m_cancelBtn->setText(tr("Cancel")); m_connectBtn->setText(tr("Connect")); this->setWindowTitle(tr("Connect Enterprise WLAN")); this->setWindowIcon(QIcon::fromTheme("kylin-network")); this->setFixedSize(MAIN_SIZE_EXPAND); } void EnterpriseWlanPage::initConnections() { connect(m_cancelBtn, &QPushButton::clicked, this, &EnterpriseWlanPage::close); connect(m_connectBtn, &QPushButton::clicked, this, &EnterpriseWlanPage::onBtnConnectClicked); connect(m_entSecurityWidget, &EntSecurityWidget::eapTypeChanged, this, &EnterpriseWlanPage::onEapTypeChanged); connect(m_entSecurityWidget, &EntSecurityWidget::setSecuPageState, this, [ = ](bool status) { m_connectBtn->setEnabled(status); }); connect(m_entSecurityWidget, &EntSecurityWidget::setSecuPageState, this, [=](bool status) { m_connectBtn->setEnabled(status); }); } void EnterpriseWlanPage::centerToScreen() { QRect desk_rect; QScreen *currentScreen = QGuiApplication::screenAt(QCursor::pos()); if (currentScreen) { desk_rect = currentScreen->geometry(); } else { desk_rect=QGuiApplication::primaryScreen()->geometry(); } int desk_x = desk_rect.width(); int desk_y = desk_rect.height(); int x = this->width(); int y = this->height(); this->move((desk_x - x)/ 2 , (desk_y - y)/ 2); } void EnterpriseWlanPage::onBtnConnectClicked() { KyWirelessConnectSetting connSettingInfo; //基本信息 connSettingInfo.m_ssid = m_ssid; connSettingInfo.setConnectName(m_ssid); connSettingInfo.setIfaceName(m_deviceName); connSettingInfo.m_isAutoConnect = true; //ipv4 ipv6 connSettingInfo.setIpConfigType(IPADDRESS_V4, CONFIG_IP_DHCP); connSettingInfo.setIpConfigType(IPADDRESS_V6, CONFIG_IP_DHCP); KyEapMethodType eapType; m_entSecurityWidget->getEnterpriseType(eapType); if (eapType == PEAP) { KyEapMethodPeapInfo info = m_entSecurityWidget->assemblePeapInfo(); Q_EMIT connectPeapConnect(info, connSettingInfo); } else if (eapType == TTLS) { KyEapMethodTtlsInfo info = m_entSecurityWidget->assembleTtlsInfo(); Q_EMIT connectTtlsConnect(info, connSettingInfo); } else if (eapType == LEAP) { KyEapMethodLeapInfo info = m_entSecurityWidget->assembleLeapInfo(); Q_EMIT connectLeapConnect(info, connSettingInfo); } else if (eapType == PWD) { KyEapMethodPwdInfo info = m_entSecurityWidget->assemblePwdInfo(); Q_EMIT connectPwdConnect(info, connSettingInfo); } else if (eapType == FAST) { KyEapMethodFastInfo info = m_entSecurityWidget->assembleFastInfo(); Q_EMIT connectFastConnect(info, connSettingInfo); } else { qWarning() << "unsupport now!!!"; } close(); } void EnterpriseWlanPage::onEapTypeChanged(const KyEapMethodType &type) { switch (type) { case KyEapMethodType::TLS: case KyEapMethodType::FAST: this->setFixedSize(MAIN_SIZE_EXPAND); break; case KyEapMethodType::PEAP: case KyEapMethodType::TTLS: case KyEapMethodType::LEAP: case KyEapMethodType::PWD: this->setFixedSize(MAIN_SIZE_NARROW); break; default: break; } centerToScreen(); } kylin-nm-plugin/plugins/wlanconnect/hiddenwifi/hiddenwifipage.h0000664000175000017500000000674615167660365024014 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 HIDDENWIFIPAGE_H #define HIDDENWIFIPAGE_H #include #include #include #include #include #include #include #include #include #include #include //#include "coninfo.h" #include "../component/Divider/divider.h" #include "kwidget.h" #include "kpasswordedit.h" #include "kborderlessbutton.h" #include "entsecuritywidget.h" #include "kylin-nm/depend/kywirelessconnectoperation.h" using namespace kdk; class HiddenWiFiPage : public QWidget { Q_OBJECT public: HiddenWiFiPage(QString interface, bool isLockScreen, QWidget *parent = nullptr); ~HiddenWiFiPage(); void getSecuType(KySecuType &secuType); protected: void paintEvent(QPaintEvent *event); bool eventFilter(QObject *w, QEvent *event); private: void initUI(); void centerToScreen(); void initComponent(); void showNone(); void showPsk(); void showEnt(); void setBtnEnable(bool on); void setJoinBtnEnable(); void setWindowWidth(KyEapMethodType eapType); private: QWidget *m_topWidget; QWidget *m_centerWidget; QWidget *m_bottomWidget; EntSecurityWidget *m_secuWidget; QLabel *m_descriptionLabel; FixLabel *m_nameLabel; FixLabel *m_secuTypeLabel; QLabel *m_pwdLabel; QLabel *m_emptyLabel; QLabel *m_checkLabel; LineEdit *m_nameEdit; QComboBox *m_secuTypeCombox; KPasswordEdit *m_pwdEdit = nullptr; QCheckBox *m_rememberCheckBox = nullptr; Divider *m_bottomDivider = nullptr; // KBorderlessButton *m_showListBtn; QPushButton *m_cancelBtn; QPushButton *m_joinBtn; QScrollArea *m_scrollArea; QVBoxLayout *m_pageLayout; QHBoxLayout *m_topLayout; QVBoxLayout *m_centerVBoxLayout; QHBoxLayout *m_bottomLayout; bool m_isJoinBtnEnable; bool m_isSecuOk = false; QString m_deviceName; private Q_SLOTS: void on_btnJoin_clicked(); void onSecuTypeComboxIndexChanged(); Q_SIGNALS: void connectHidePeapConnect(KyEapMethodPeapInfo info, KyWirelessConnectSetting connSettingInfo); void connectHideTtlsConnect(KyEapMethodTtlsInfo info, KyWirelessConnectSetting connSettingInfo); void connectHideNormalConnect(KyWirelessConnectSetting connSettingInfo, KySecuType type); void connectHideLeapConnect(KyEapMethodLeapInfo info, KyWirelessConnectSetting connSettingInfo); void connectHidePwdConnect(KyEapMethodPwdInfo info, KyWirelessConnectSetting connSettingInfo); void connectHideFastConnect(KyEapMethodFastInfo info, KyWirelessConnectSetting connSettingInfo); }; #endif // HIDDENWIFIPAGE_H kylin-nm-plugin/plugins/wlanconnect/hiddenwifi/entsecuritywidget.h0000664000175000017500000001174415167660365024621 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 ENTSECURITYWIDGET_H #define ENTSECURITYWIDGET_H #include #include #include #include #include #include #include #include //#include "coninfo.h" #include "kwidget.h" #include "kpasswordedit.h" #include "kdialog.h" #include "kballontip.h" #include "kylin-nm/depend/kyenterpricesettinginfo.h" #include "../component/FixLabel/fixlabel.h" using namespace kdk; // ------------------------"coninfo.h"------------------------------ enum PeapInnerType { MSCHAPV2_PEAP = 0, MD5_PEAP, GTC_PEAP, }; enum TtlsInnerType { PAP = 0, MSCHAP, MSCHAPV2_EAP, MSCHAPV2, CHAP, MD5_EAP, GTC_EAP }; enum FastInnerType { GTC_FAST = 0, MSCHAPV2_FAST, }; enum PacProvisioningInnerType { ANON = 0, AUTHEN, BOTH, }; class LineEdit : public QLineEdit { Q_OBJECT public: explicit LineEdit(QWidget *parent = nullptr) : QLineEdit(parent) {} ~LineEdit() {} protected: void contextMenuEvent(QContextMenuEvent *event) { QMenu *menu = createStandardContextMenu();//默认的标准右键菜单,如果不需要刻意完全自己实现 menu->setPalette(this->palette()); menu->exec(event->globalPos()); delete menu; } }; // ------------------------------------------------------ class LogHintDialog : public KDialog { Q_OBJECT public: LogHintDialog(QWidget *parent = nullptr); private: QLabel * m_iconLabel = nullptr; QLabel * m_contentLabel = nullptr; QPushButton *m_confirmBtn; QVBoxLayout *m_dialogLayout; Q_SIGNALS: void LogHintDialogClosed(); }; class EntSecurityWidget : public QWidget { Q_OBJECT public: EntSecurityWidget(bool isLockScreen, QWidget *parent = nullptr); ~EntSecurityWidget(); // void setTlsInfo(KyEapMethodTlsInfo &info); // void setPeapInfo(KyEapMethodPeapInfo &info); // void setTtlsInfo(KyEapMethodTtlsInfo &info); KyEapMethodPeapInfo assemblePeapInfo(); KyEapMethodTtlsInfo assembleTtlsInfo(); KyEapMethodLeapInfo assembleLeapInfo(); KyEapMethodPwdInfo assemblePwdInfo(); KyEapMethodFastInfo assembleFastInfo(); void getEnterpriseType(KyEapMethodType &enterpriseType); private: void initUI(); void initConnect(); void showTls(); void showPeapOrTtls(); void showLeapOrPwd(); void showFast(); public: bool checkConnectBtnIsEnabled(); private: //企业wifi共有 QLabel *m_eapTypeLabel; QComboBox *m_eapTypeCombox; //TLS QLabel *m_identityLable; QLabel *m_domainLable; QLabel *m_caCertPathLabel; QLabel *m_caNeedFlagLabel; FixLabel *m_clientCertPathLabel; FixLabel *m_clientPrivateKeyLabel; FixLabel *m_clientPrivateKeyPwdLabel; FixLabel *m_pwdOptionLabel; //PEAP TTLS共有 FixLabel *m_eapMethodLabel; QLabel *m_userNameLabel; QLabel *m_userPwdLabel; //TLS LineEdit *m_identityEdit; LineEdit *m_domainEdit; QComboBox *m_caCertPathCombox; QCheckBox *m_caNeedBox; QComboBox *m_clientCertPathCombox; QComboBox *m_clientPrivateKeyCombox; KPasswordEdit *m_clientPrivateKeyPwdEdit = nullptr; QComboBox *m_pwdOptionCombox; QWidget *m_tlsWidget; // LogHintDialog *m_loginHintDialog = nullptr; bool m_isLockScreen; //PEAP && TTLS QComboBox *m_eapMethodCombox; LineEdit *m_userNameEdit; KPasswordEdit *m_userPwdEdit = nullptr; //FAST QCheckBox *m_pacCheckBox; QComboBox *m_pacProvisionComboBox; QComboBox *m_pacFilePathComboBox; FixLabel *m_pacProvisionLabel; QLabel *m_pacFileLabel; QWidget *m_pacCheckWidget; private Q_SLOTS: void onEapTypeComboxIndexChanged(); void setEnableOfSaveBtn(); void onCaNeedBoxClicked(); void onPacBoxClicked(); void onCaCertPathComboxIndexChanged(QString str); void onClientCertPathComboxIndexChanged(QString str); void onClientPrivateKeyComboxIndexChanged(QString str); void onPacFilePathComboxIndexChanged(QString str); void setComboxIndex(); Q_SIGNALS: void setSecuPageState(bool); void eapTypeChanged(const KyEapMethodType &type); }; #endif // ENTSECURITYWIDGET_H kylin-nm-plugin/plugins/wlanconnect/wlanitem.cpp0000775000175000017500000002775615160520531021074 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 #define RADIUS 6.0 #define LOADIMG_SIZE 16,16 #define UNEXPEND_HEIGHT 48 #define EXPEND_HEIGHT 120 #define ENABLE_BUTTON_COLOR qApp->palette().highlight().color() #define UNABLE_BUTTON_COLOR qApp->palette().button().color() WlanItem::WlanItem(PluginType type, QWidget *parent) : type(type), QFrame(parent) { this->setFixedSize(404, UNEXPEND_HEIGHT); QVBoxLayout *m_mainLayout = new QVBoxLayout(this); m_mainLayout->setContentsMargins(16,0,0,0); m_mainLayout->setSpacing(0); //icon + name m_nameFrame = new QFrame(this); QHBoxLayout *lanLyt = new QHBoxLayout(m_nameFrame); lanLyt->setContentsMargins(0,8,16,4); lanLyt->setSpacing(0); radioBtn = new RadioItemButton(this); titileLabel = new FixLabel(this); titileLabel->setMaximumWidth(MAX_WIDTH_DEACTIVATED); // m_freq = new FreqLabel(m_nameFrame); // m_freq->setEnabled(false); m_lbLoadUp = new QLabel(m_nameFrame); m_lbLoadDown = new QLabel(m_nameFrame); m_lbLoadDownImg = new QLabel(m_nameFrame); m_lbLoadUpImg = new QLabel(m_nameFrame); m_lbLoadUp->hide(); m_lbLoadDown->hide(); m_lbLoadDownImg->hide(); m_lbLoadUpImg->hide(); 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/icon/load-down.png"))); m_lbLoadUpImg->setPixmap(QPixmap(QLatin1String("://res/icon/load-up.png"))); m_lbLoadDownImg->setFixedSize(LOADIMG_SIZE); m_lbLoadUpImg->setFixedSize(LOADIMG_SIZE); lanLyt->setAlignment(Qt::AlignVCenter); lanLyt->addWidget(radioBtn); lanLyt->addSpacing(10); lanLyt->addWidget(titileLabel,Qt::AlignLeft); lanLyt->addSpacing(6); // lanLyt->addWidget(m_freq); lanLyt->addStretch(); lanLyt->addSpacing(8); lanLyt->addWidget(m_lbLoadUpImg); lanLyt->addWidget(m_lbLoadUp); lanLyt->addSpacing(2); lanLyt->addWidget(m_lbLoadDownImg); lanLyt->addWidget(m_lbLoadDown); if (type != SIMPLE) { infoLabel = new InfoButton(this); lanLyt->addSpacing(8); lanLyt->addWidget(infoLabel); connect(infoLabel, &InfoButton::released, this, &WlanItem::infoButtonClick); infoLabel->hide(); } m_expendFrame = new QFrame(this); QVBoxLayout *expendnLyt = new QVBoxLayout(m_expendFrame); expendnLyt->setContentsMargins(40, 0, 16, 0); expendnLyt->setSpacing(0); //pwdline + connect Button m_pwdFrame = new QFrame(m_expendFrame); m_pwdFrameLyt = new QHBoxLayout(m_pwdFrame); m_pwdFrameLyt->setContentsMargins(0,0,0,0); m_pwdFrameLyt->setSpacing(0); m_pwdFrame->setLayout(m_pwdFrameLyt); m_pwdLineEdit = new KPasswordEdit(m_pwdFrame); m_pwdLineEdit->setState(Ordinary); // m_pwdLineEdit->setEchoModeBtnVisible(true); m_pwdLineEdit->setContextMenuPolicy(Qt::NoContextMenu); m_pwdLineEdit->setUseCustomPalette(true); QPalette pal = this->palette(); m_pwdLineEdit->setPalette(pal); if (type == OOBE) { m_pwdLineEdit->setStyleSheet("background-color: black;"); } QRegularExpression rx("^[A-Za-z0-9`~!@#$%^&*()_-+=<>,.\\\/]+$"); QRegularExpressionValidator *latitude = new QRegularExpressionValidator(rx, this); m_pwdLineEdit->setValidator(latitude); m_pwdLineEdit->installEventFilter(this); connect(m_pwdLineEdit, &KPasswordEdit::textChanged, this, &WlanItem::onPwdEditorTextChanged); m_pwdLineEdit->setFixedSize(228, 36); m_pwdLineEdit->setEchoMode(QLineEdit::EchoMode::Password); m_pwdFrameLyt->addWidget(m_pwdLineEdit); m_pwdFrameLyt->addSpacing(8); m_connectButton = new QPushButton(m_pwdFrame); m_connectButton->setFixedSize(96, 36); m_connectButton->setText(tr("Connect")); m_connectButton->setEnabled(false); if (type == OOBE) { m_connectButton->setStyleSheet("background-color: gray;"); } connect(m_connectButton, &QPushButton::clicked, this, &WlanItem::onConnectButtonClicked); m_pwdFrameLyt->addWidget(m_connectButton); //自动连接选择区域UI m_autoConnectFrame = new QFrame(m_expendFrame); m_autoConnectFrameLyt = new QHBoxLayout(m_autoConnectFrame); m_autoConnectFrameLyt->setContentsMargins(0,8,150,8); m_autoConnectFrameLyt->setSpacing(0); m_autoConnectFrame->setLayout(m_autoConnectFrameLyt); m_autoConnectCheckBox = new QCheckBox(m_autoConnectFrame); m_autoConnectCheckBox->setText(tr("Auto Connect")); m_autoConnectCheckBox->setChecked(true); m_autoConnectCheckBox->setFixedSize(16, 16); m_autoConnectFrameLyt->addWidget(m_autoConnectCheckBox); m_autoConnectFrameLyt->addSpacing(8); m_autoConnectLabel = new QLabel(m_autoConnectFrame); m_autoConnectLabel->setText(tr("Auto Connect")); m_autoConnectFrameLyt->addWidget(m_autoConnectLabel); expendnLyt->addWidget(m_pwdFrame); expendnLyt->addWidget(m_autoConnectFrame); m_mainLayout->addWidget(m_nameFrame); m_mainLayout->addWidget(m_expendFrame); m_expendFrame->hide(); 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")); waitTimer = new QTimer(this); connect(waitTimer, &QTimer::timeout, this, &WlanItem::updateIcon); m_menu = new QMenu(this);//右键菜单 m_menu->setWindowFlag(Qt::X11BypassWindowManagerHint); connect(m_menu, &QMenu::triggered, this, &WlanItem::itemClick); m_pwdLineEdit->installEventFilter(this); m_autoConnectCheckBox->installEventFilter(this); } void WlanItem::updateIcon() { if (currentIconIndex > 6) { currentIconIndex = 0; } radioBtn->setButtonIcon(loadIcons.at(currentIconIndex)); currentIconIndex ++; } void WlanItem::showEnterPricePage(QString devName, QWidget *widget) { if (nullptr != m_enterPirsePage) { m_enterPirsePage->show(); } else { QString ssid = getName(); m_enterPirsePage = new EnterpriseWlanPage(ssid, devName, true, widget); connect(m_enterPirsePage, &EnterpriseWlanPage::destroyed, [=](){ m_enterPirsePage->disconnect(this); m_enterPirsePage = nullptr; }); connect(m_enterPirsePage, &EnterpriseWlanPage::connectPeapConnect, this, &WlanItem::connectPeapConnect); connect(m_enterPirsePage, &EnterpriseWlanPage::connectTtlsConnect, this, &WlanItem::connectTtlsConnect); connect(m_enterPirsePage, &EnterpriseWlanPage::connectLeapConnect, this, &WlanItem::connectLeapConnect); connect(m_enterPirsePage, &EnterpriseWlanPage::connectPwdConnect, this, &WlanItem::connectPwdConnect); connect(m_enterPirsePage, &EnterpriseWlanPage::connectFastConnect, this, &WlanItem::connectFastConnect); m_enterPirsePage->show(); } } void WlanItem::startLoading() { waitTimer->start(FRAME_SPEED); m_loading = true; } void WlanItem::stopLoading(){ waitTimer->stop(); m_loading = false; } void WlanItem::mousePressEvent(QMouseEvent *event) { return QFrame::mousePressEvent(event); } void WlanItem::mouseReleaseEvent(QMouseEvent *event) { if(event->button() == Qt::RightButton) { if (!m_menu || type == OOBE) { return QFrame::mouseReleaseEvent(event); } m_menu->clear(); if (m_isAcitve || m_loading) { m_menu->addAction(new QAction(tr("Disconnect"), this)); } else if (!m_isAcitve && !m_loading) { m_menu->addAction(new QAction(tr("Connect"), this)); } m_menu->move(cursor().pos()); m_menu->show(); } else { if (!m_isAcitve && !m_loading) { Q_EMIT itemClick(); } } return QFrame::mouseReleaseEvent(event); } void WlanItem::enterEvent(QEnterEvent *event) { m_isIn = true; update(); return QFrame::enterEvent(event); } void WlanItem::leaveEvent(QEvent *event) { m_isIn = false; update(); return QFrame::leaveEvent(event); } void WlanItem::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) { if (m_expendFrame && m_expendFrame->isVisible() && m_pwdLineEdit->text().length() >= 8) { onConnectButtonClicked(); } } return QFrame::keyPressEvent(event); } void WlanItem::paintEvent(QPaintEvent *event) { QPalette pal = this->palette(); QPainter painter(this); painter.setRenderHint(QPainter:: Antialiasing, true); //设置渲染,启动反锯齿 painter.setPen(Qt::NoPen); QColor color(240, 240, 240); if (m_isFocusIn) { color.setAlphaF(1); painter.setBrush(color); } else { if (m_isIn) { color.setAlphaF(0.39); painter.setBrush(color); } else { painter.setBrush(pal.color(QPalette::Base)); } } if (type == OOBE) { painter.setBrush(Qt::transparent); // 设置背景为透明 } QRect rect = this->rect(); QPainterPath path; path.addRoundedRect(rect, RADIUS, RADIUS); painter.drawPath(path); return QFrame::paintEvent(event); } bool WlanItem::eventFilter(QObject *watched, QEvent *event) { if (watched == m_pwdLineEdit && event->type() == QEvent::FocusIn) { Q_EMIT passwordFocusIn(); } if (watched == m_pwdLineEdit) { if (event->type() == QEvent::FocusIn) { m_isFocusIn = true; } else if (event->type() == QEvent::FocusOut) { m_isFocusIn = false; } } return QFrame::eventFilter(watched,event); } void WlanItem::setExpend(bool enable) { if (enable) { this->setFixedHeight(EXPEND_HEIGHT); m_expendFrame->show(); m_pwdLineEdit->setFocus(); } else { m_expendFrame->hide(); this->setFixedHeight(UNEXPEND_HEIGHT); m_pwdLineEdit->clear(); m_pwdLineEdit->setState(Ordinary); } } bool WlanItem::getExpend() { return !m_expendFrame->isHidden(); } void WlanItem::onPwdEditorTextChanged() { QPalette btnPal; if (m_pwdLineEdit->text().length() < 8) { m_connectButton->setEnabled(false); // 后续记得还原,应该是主题色板 btnPal.setColor(QPalette::Button, UNABLE_BUTTON_COLOR); m_connectButton->setPalette(btnPal); if(type == OOBE){ m_connectButton->setStyleSheet("background-color: gray;"); } } else { m_connectButton->setEnabled(true); btnPal.setColor(QPalette::Button, ENABLE_BUTTON_COLOR); m_connectButton->setPalette(btnPal); if(type == OOBE){ m_connectButton->setStyleSheet("background-color: #3790FA;"); } } } void WlanItem::onConnectButtonClicked() { connectButtonClick(m_pwdLineEdit->text(), m_autoConnectCheckBox->isChecked()); } kylin-nm-plugin/plugins/wlanconnect/wlanconnect.h0000775000175000017500000001664415160520531021226 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 WLANCONNECT_H #define WLANCONNECT_H #include "kswitchbutton.h" #include "kborderlessbutton.h" using namespace kdk; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "../component/DeviceFrame/deviceframe.h" #include "itemframe.h" #include "wlanitem.h" #include "hiddenwifi/enterprisewlanpage.h" class WlanConnect : public Interface { Q_OBJECT Q_PLUGIN_METADATA(IID "org.kylin.network") Q_INTERFACES(Interface) public: WlanConnect(); ~WlanConnect(); QWidget * pluginUi() Q_DECL_OVERRIDE; // 插件主界面---setPluginType后调用 void setPluginType(PluginType type, bool useSwitch = true) Q_DECL_OVERRIDE; // 设置插件类型 void setParentWidget(QWidget*); void setWidgetVisable(bool); bool checkInputStauts(); void setInputStauts(); bool checkPluginIsHidden(); void hideTitle(); private: bool m_isSimpleMode = true; KylinAgent* m_agent=nullptr; void initUi(); void initComponent(); void initConnect(); void runExternalApp(); void initSearchText(); void showDesktopNotify(const QString &message, QString soundName); void updateIcon(WlanItem *item, int signalStrength, QString security, bool isApConnection); void resortWifiList(ItemFrame *frame, QList connectItemList, QList list); //单wifi图标 int setSignal(int lv); QString wifiIcon(bool isLock, int strength); //开关相关 void setSwitchStatus(bool status); void hideLayout(QVBoxLayout * layout); void showLayout(QVBoxLayout * layout); //获取设备列表 void getDeviceList(QStringList &list); //初始化设备wifi列表 void initNet(); void initNetListFromDevice(QString deviceName); //增加设备 void addDeviceFrame(QString devName); //减少设备 void removeDeviceFrame(QString devName); //无序增加ap void addOneWlanFrame(ItemFrame *frame, QString deviceName, KyWirelessNetItem &wlanInfo); //减少ap void removeOneWlanFrame(ItemFrame *frame, QString deviceName, QString ssid); //有序增加ap void insertOneWlanFrame(ItemFrame *frame, QString devName, KyWirelessNetItem &wlanInfo); //单个wifi连接状态变化 void itemActiveConnectionStatusChanged(WlanItem *item, int status); void setOtherItemExpandedFalse(QString devName, QString ssid); WlanItem* getExpandedItem(); void kylinAgentInit(); protected: bool eventFilter(QObject *w,QEvent *e); private: KyNetworkManager* manager; QThread* thread; QWidget* parentWidget = nullptr; QWidget* pluginWidget = nullptr; //设备列表 QStringList deviceList; //设备名 + 单设备frame QMap deviceFrameMap; QTimer * m_scanTimer = nullptr; QTimer * m_updateTimer = nullptr; QTimer * m_setNetSpeedTimer = nullptr; bool m_firstLoad = true; bool msettingLoad = false; //插件启用类型 PluginType m_pluginType; QVBoxLayout* m_mainLayout = nullptr; QFrame* m_titleFrame = nullptr; QHBoxLayout* m_titleLayout = nullptr; QLabel* m_titleLabel = nullptr; KSwitchButton* m_wirelessSwitch = nullptr; Divider* m_titleDivider = nullptr; QFrame* m_scrollFrame = nullptr; QVBoxLayout* m_scrollLayout = nullptr; QScrollArea* m_scrollArea = nullptr; QWidget* m_listWidget = nullptr; QVBoxLayout* m_scrollAreaLayout = nullptr; Divider* m_settingsDivider = nullptr; QFrame* m_settingsFrame = nullptr; QHBoxLayout* m_settingsLayout = nullptr; KBorderlessButton* m_settingsLabel = nullptr; WlanItem* findItem(QString devName, QString ssid); bool getWirelessDeviceUseable(); bool getWirelessDeviceAvailable(); //显示网速 void showRate(); Q_SIGNALS: void updatePluginHidden(bool); void requestWirelessScan(); void setWirelessNetworkEnabled(bool enabled); //=======================连接/断开操作==================== void activateConnection(const QString connectUuid, const QString deviceName); void deactivateConnection(const QString &activeConnectUuid); //连接无本地配置的非企业网热点 void addAndActivateNormalWifi(KyWirelessConnectSetting connSettingInfo, KySecuType type); // //连接无本地配置的企业网热点 // void addAndActiveWirelessEnterPriseTlsConnect(KyEapMethodTlsInfo &info, // KyWirelessConnectSetting &connSettingInfo); // void addAndActiveWirelessEnterPrisePeapConnect(KyEapMethodPeapInfo &info, // KyWirelessConnectSetting &connSettingInfo); // void addAndActiveWirelessEnterPriseTtlsConnect(KyEapMethodTtlsInfo &info, // KyWirelessConnectSetting &connSettingInfo); void deleteConnect(QString uuid); private Q_SLOTS: void onNetworkAdd(QString deviceName, KyWirelessNetItem wlanInfo); void onNetworkRemove(QString deviceName, QString wlannName); void onNetworkUpdate(QString deviceName, QString wlannName, KyWirelessNetItem secuType); void onActiveConnectionChanged(QString deviceName, QString ssid, QString uuid, KyConnectState status); void updateList(QString devName, QList connectItemList, QList list); void onDeviceStatusChanged(); void onDeviceNameChanged(QString, QString); void reScan(); void onNetworkSecuTypeChange(QString deviceName, QString ssid, QString securityType); void onWifiEnabledChanged(bool); void onDeviceManagedChange(QString, bool); void onWirelessConnectionRemove(QString deviceName, QString ssid); void onWirelessConnectionAdd(QString deviceName, QString ssid, QString uuid, QString dbusPath); void onWirelessConnectionUpdate(QString deviceName, QString ssid, QString uuid, QString dbusPath, KySecuType connectSecuType); void onWirelessDeviceAdd(QString deviceName); void onWirelessDeviceRemove(QString deviceName); void onSetNetSpeed(); void keyAgentRegister(); void keyAgentUnregister(); }; #endif // WLANCONNECT_H kylin-nm-plugin/plugins/wlanconnect/itemframe.h0000775000175000017500000000555615167660365020705 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 #include #include "wlanitem.h" #include "../component/DeviceFrame/deviceframe.h" #include "../component/Divider/divider.h" #include "hiddenwifi/hiddenwifipage.h" #include class AddNetItem : public QFrame { Q_OBJECT public: AddNetItem(QWidget *parent = nullptr); protected: void enterEvent(QEnterEvent *event); void leaveEvent(QEvent *event); void paintEvent(QPaintEvent *event); void mouseReleaseEvent(QMouseEvent *event); private: QLabel* titleLabel = nullptr; bool m_isIn = false; Q_SIGNALS: void itemClick(); }; class ItemFrame : public QFrame { Q_OBJECT public: ItemFrame(QString devName, QWidget *parent = nullptr); ~ItemFrame(); //单设备整体layout QVBoxLayout * deviceLanLayout = nullptr; //单设备名称+下拉按钮Frame Divider * m_divider; DeviceFrame * deviceFrame = nullptr; //单设备列表Frame QFrame * lanItemFrame = nullptr; //单设备列表layout QVBoxLayout * lanItemLayout = nullptr; //单设备item列表 QMap itemMap; //加入其他网络 AddNetItem * addNetItem = nullptr; //已激活uuid QString uuid = ""; //获取当前网速子线程 KyNetLoadRateThread *m_updateNetSpeedThread; QString m_deviceName; //更新网速显示 void startNetSpeedThread(); void stopNetSpeedThread(); void updateNetSpeed(); public Q_SLOTS: void showJoinPage(QWidget *); private: HiddenWiFiPage* joinPage = nullptr; void setNetSpeed(long int rcvRate, long int txRate, WlanItem* wlanItem); Q_SIGNALS: void addNetItemClick(); void connectHidePeapConnect(KyEapMethodPeapInfo info, KyWirelessConnectSetting connSettingInfo); void connectHideTtlsConnect(KyEapMethodTtlsInfo info, KyWirelessConnectSetting connSettingInfo); void connectHideNormalConnect(KyWirelessConnectSetting connSettingInfo, KySecuType type); }; #endif // ITEMFRAME_H kylin-nm-plugin/plugins/wlanconnect/deviceframe.h0000664000175000017500000000264115167660365021173 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 #include #include #include #include #include #include "../component/DrownLabel/drownlabel.h" class DeviceFrame : public QFrame { public: DeviceFrame(QString devName, QWidget *parent = nullptr); ~DeviceFrame(); public: //仅设备名称+下拉label QLabel * deviceLabel = nullptr; DrownLabel *dropDownLabel = nullptr; protected: void paintEvent(QPaintEvent *event); private: int frameSize; }; #endif // DEVICEFRAME_H kylin-nm-plugin/plugins/wlanconnect/wlanitem.h0000775000175000017500000001421215167660365020541 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 #include #include #include #include #include #include #include #include #include #include "../component/InfoButton/infobutton.h" #include "../component/RadioItemButton/radioitembutton.h" #include "../component/FixLabel/fixlabel.h" #include "../component/FixLabel/freqlabel.h" #include "../component/FixPushButton/fixpushbutton.h" #include "kpasswordedit.h" #include "hiddenwifi/enterprisewlanpage.h" using namespace kdk; #define FREQ_5GHZ 5000 #define MAX_WIDTH_ACTIVATED 142 #define MAX_WIDTH_DEACTIVATED 270 class WlanItem : public QFrame { Q_OBJECT public: WlanItem(PluginType type, QWidget *parent = nullptr); public: void setName(QString name) { titileLabel->setLabelText(name); } QString getName() { return titileLabel->getText(); } void setItemIcon(const QIcon &icon) { radioBtn->setButtonIcon(icon); } inline void updateNameLabel() { if (m_isAcitve) { titileLabel->setMaximumWidth(MAX_WIDTH_ACTIVATED); } else { titileLabel->setMaximumWidth(MAX_WIDTH_DEACTIVATED); } setName(titileLabel->getText()); } inline void setNetSpeedUiVisible(bool visible) { m_lbLoadUp->setVisible(visible); m_lbLoadDown->setVisible(visible); m_lbLoadDownImg->setVisible(visible); m_lbLoadUpImg->setVisible(visible); } void setStatus(bool isAcitve){ m_isAcitve = isAcitve; radioBtn->setActive(isAcitve); updateNameLabel(); setNetSpeedUiVisible(isAcitve); } bool getStatus(){ return m_isAcitve; } bool getIsLoading() { return m_loading; } QString getUuid(){ return m_uuid; } void setUuid(QString uuid){ m_uuid = uuid; } QString getPath(){ return m_dbusPath; } void setPath(QString dbusPath){ m_dbusPath = dbusPath; } QString getSecuType(){ return m_secutype; } void setSecuType(QString &secuType){ m_secutype = secuType; } QString getInterface(){ return m_interface; } void setInterface(QString &interface){ m_interface = interface; } void setPasswordError(QString pwd) { m_pwdLineEdit->setState(LoginFailed); m_pwdLineEdit->setText(pwd); } void setFrequency(uint freq, bool isMix) { if (isMix) { m_freq->setText("2.4/5G"); return; } if (freq < FREQ_5GHZ) { m_freq->setText("2.4G"); } else { m_freq->setText("5G"); } return; } void setNetSpeed(QString strRcv, QString strTx) { m_lbLoadDown->setText(strRcv); m_lbLoadUp->setText(strTx); } void showEnterPricePage(QString devName, QWidget *widget); void startLoading(); void stopLoading(); void setExpend(bool); bool getExpend(); Q_SIGNALS: void itemClick(); void infoButtonClick(); void connectButtonClick(QString , bool); void passwordFocusIn(); protected: void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); void keyPressEvent(QKeyEvent *event); void enterEvent(QEnterEvent *event); void leaveEvent(QEvent *event); void paintEvent(QPaintEvent *event); bool eventFilter(QObject *watched, QEvent *event); private: QTimer *waitTimer = nullptr; QList loadIcons; int currentIconIndex=0; QMenu *m_menu = nullptr; RadioItemButton* radioBtn = nullptr; InfoButton * infoLabel = nullptr; FixLabel * titileLabel = nullptr; QLabel *m_lbLoadDown = nullptr; QLabel *m_lbLoadUp = nullptr; QLabel *m_lbLoadDownImg = nullptr; QLabel *m_lbLoadUpImg = nullptr; QLabel *m_freq = nullptr; PluginType type; bool m_isAcitve = false; bool m_loading = false; bool m_isExpand = false; QString m_uuid = ""; QString m_dbusPath =""; //ap类型 QString m_secutype = ""; QString m_interface = ""; QFrame* m_nameFrame = nullptr; QFrame* m_expendFrame = nullptr; QFrame* m_pwdFrame = nullptr; QFrame* m_autoConnectFrame = nullptr; KPasswordEdit* m_pwdLineEdit = nullptr; QPushButton* m_connectButton = nullptr; QCheckBox* m_autoConnectCheckBox = nullptr; QLabel* m_autoConnectLabel = nullptr; QHBoxLayout* m_autoConnectFrameLyt = nullptr; QHBoxLayout* m_pwdFrameLyt = nullptr; EnterpriseWlanPage* m_enterPirsePage = nullptr; bool m_isIn = false; bool m_isFocusIn = false; private Q_SLOTS: void updateIcon(); // void onMenuTriggered(QAction *action); void onPwdEditorTextChanged(); void onConnectButtonClicked(); Q_SIGNALS: void connectPeapConnect(KyEapMethodPeapInfo info, KyWirelessConnectSetting connSettingInfo); void connectTtlsConnect(KyEapMethodTtlsInfo info, KyWirelessConnectSetting connSettingInfo); void connectLeapConnect(KyEapMethodLeapInfo info, KyWirelessConnectSetting connSettingInfo); void connectPwdConnect(KyEapMethodPwdInfo info, KyWirelessConnectSetting connSettingInfo); void connectFastConnect(KyEapMethodFastInfo info, KyWirelessConnectSetting connSettingInfo); }; #endif // WLANITEM_H kylin-nm-plugin/plugins/wlanconnect/wlanconnect.cpp0000775000175000017500000011756415160520531021564 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 "wlanconnect.h" #include #include #include #include #include #include #include #define SCANTIMER 20 * 1000 #define UPDATETIMER 10 * 1000 #define REFRESH_NETWORKSPEED_TIMER 1000 #define SPACING 8 const QString KWifiSymbolic = "network-wireless-signal-excellent"; const QString KWifiLockSymbolic = "network-wireless-secure-signal-excellent"; const QString KWifiGood = "network-wireless-signal-good"; const QString KWifiLockGood = "network-wireless-secure-signal-good"; const QString KWifiOK = "network-wireless-signal-ok"; const QString KWifiLockOK = "network-wireless-secure-signal-ok"; const QString KWifiLow = "network-wireless-signal-low"; const QString KWifiLockLow = "network-wireless-secure-signal-low"; const QString KWifiNone = "network-wireless-signal-none"; const QString KWifiLockNone = "network-wireless-secure-signal-none"; const QString KApSymbolic = "network-wireless-hotspot-symbolic"; const QString IsApConnection = "1"; #define NO_MARGINS 0,0,0,0 #define TOP_MARGINS 0,8,0,0 #define MAIN_LAYOUT_MARGINS 0,0,0,0 #define MAIN_LAYOUT_SPACING 0 #define TITLE_FRAME_HEIGHT 53 //TabWidget的tab和widget有间隙,和设计稿看起来一致就不能设为设计稿里的高度 #define TITLE_LAYOUT_MARGINS 24,0,24,0 bool intThan(int sign1, int sign2) { return sign1 < sign2; } void WlanConnect::showDesktopNotify(const QString &message, QString soundName) { QDBusInterface iface("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "org.freedesktop.Notifications", QDBusConnection::sessionBus()); QStringList actions; //跳转动作 actions.append("default"); actions.append("kylin-nm"); //默认动作:点击消息体时打开麒麟录音 QMap hints; if (!soundName.isEmpty()) { hints.insert("sound-name",soundName); //添加声音 } QList args; args<<(tr("Kylin NM")) <<((unsigned int) 0) <("KyWirelessConnectSetting"); qRegisterMetaType("KySecuType"); qRegisterMetaType>("QList"); qRegisterMetaType>("QList"); qRegisterMetaType("KyEapMethodPeapInfo"); qRegisterMetaType("KyEapMethodTtlsInfo"); qRegisterMetaType("KyEapMethodLeapInfo"); qRegisterMetaType("KyEapMethodPwdInfo"); qRegisterMetaType("KyEapMethodFastInfo"); qRegisterMetaType("KyDeviceState"); qRegisterMetaType("NetworkManager::Device::StateChangeReason"); QLocale local; QString locale = local.name(); QTranslator* translator = new QTranslator(this); if (translator->load("/usr/share/kylin-nm-plugin/wlanconnect/wlan_" + locale)) { QApplication::installTranslator(translator); } else { qWarning() << "Translations load fail"; } } WlanConnect::~WlanConnect() { qDebug() << "~WlanConnect 1"; thread->quit(); thread->wait(); delete thread; if (pluginWidget != nullptr) { delete pluginWidget; } keyAgentUnregister(); qDebug() << "~WlanConnect 2"; } QWidget *WlanConnect::pluginUi() { if (m_firstLoad) { m_firstLoad = false; kylinAgentInit(); pluginWidget = new QWidget; pluginWidget->setAttribute(Qt::WA_DeleteOnClose); initUi(); initConnect(); initComponent(); if(msettingLoad){ hideTitle(); } } return pluginWidget; } void WlanConnect::setParentWidget(QWidget* widget){ if (parentWidget != nullptr) { return; } parentWidget = widget; } void WlanConnect::setWidgetVisable(bool visable) { if (pluginWidget == nullptr) { return; } if (deviceFrameMap.isEmpty()) { return; } if (visable) { return; } QMap::iterator iter; for (iter = deviceFrameMap.begin(); iter != deviceFrameMap.end(); iter++) { QMap::iterator itemIter; for (itemIter = iter.value()->itemMap.begin(); itemIter != iter.value()->itemMap.end(); itemIter++) { itemIter.value()->setExpend(false); } } } bool WlanConnect::checkInputStauts() { return (getExpandedItem() != nullptr); } void WlanConnect::setInputStauts() { WlanItem* item = getExpandedItem(); if (item != nullptr) { item->setExpend(true); } } void WlanConnect::setPluginType(PluginType type, bool useSwitch) { m_pluginType = type; Q_UNUSED(useSwitch) if (type == SIMPLE) { m_isSimpleMode = true; } else { m_isSimpleMode = false; } if (type == OOBE){ msettingLoad = true; m_isSimpleMode = true; } } bool WlanConnect::checkPluginIsHidden() { return true; //to show this plugin #if 0 if (nullptr != m_wirelessSwitch) { return m_wirelessSwitch->isEnabled(); } return false; #endif } void WlanConnect::initUi() { thread = new QThread; manager = new KyNetworkManager(); manager->moveToThread(thread); connect(thread, &QThread::started, manager, &KyNetworkManager::kylinNetworkManagerInit); connect(thread, &QThread::finished, manager, &KyNetworkManager::deleteLater); connect(thread, &QThread::finished, [=](){ qDebug() << "WlanConnect thread quit"; }); thread->start(); while (!manager->isInitFinished()) { ::usleep(1000); } m_mainLayout = new QVBoxLayout(pluginWidget); m_mainLayout->setContentsMargins(MAIN_LAYOUT_MARGINS); m_mainLayout->setSpacing(MAIN_LAYOUT_SPACING); pluginWidget->setLayout(m_mainLayout); m_titleFrame = new QFrame(pluginWidget); m_titleFrame->setFixedHeight(TITLE_FRAME_HEIGHT); m_titleLayout = new QHBoxLayout(m_titleFrame); m_titleLayout->setContentsMargins(TITLE_LAYOUT_MARGINS); m_titleLabel = new QLabel(m_titleFrame); m_titleLabel->setText(tr("WLAN")); m_wirelessSwitch = new KSwitchButton(pluginWidget); m_wirelessSwitch->installEventFilter(this); m_titleLayout->addWidget(m_titleLabel); m_titleLayout->addStretch(); m_titleLayout->addWidget(m_wirelessSwitch); m_titleDivider = new Divider(pluginWidget); m_titleDivider->hide(); m_scrollFrame = new QFrame(pluginWidget); if (m_isSimpleMode) { m_scrollFrame->setMinimumHeight(383); } else { m_scrollFrame->setMinimumHeight(330); } if (msettingLoad){ m_scrollFrame->setFixedHeight(700); } m_scrollLayout = new QVBoxLayout(m_scrollFrame); m_scrollLayout->setContentsMargins(0,0,0,0); m_scrollLayout->setSpacing(0); m_scrollFrame->setLayout(m_scrollLayout); m_scrollArea = new QScrollArea(m_scrollFrame); m_scrollArea->setFrameShape(QFrame::Shape::NoFrame); m_scrollArea->setWidgetResizable(true); m_scrollArea->setBackgroundRole(QPalette::Base); m_scrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); m_scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_scrollLayout->addWidget(m_scrollArea); m_listWidget = new QWidget(pluginWidget); m_listWidget->setFixedWidth(420); m_scrollAreaLayout = new QVBoxLayout(m_listWidget); m_scrollAreaLayout->setSpacing(MAIN_LAYOUT_SPACING); m_scrollAreaLayout->setContentsMargins(MAIN_LAYOUT_MARGINS); m_scrollAreaLayout->setAlignment(Qt::AlignTop); m_listWidget->setLayout(m_scrollAreaLayout); m_scrollArea->setWidget(m_listWidget); m_settingsDivider = new Divider(pluginWidget); m_settingsFrame = new QFrame(pluginWidget); m_settingsFrame->setFixedHeight(TITLE_FRAME_HEIGHT); m_settingsLayout = new QHBoxLayout(m_settingsFrame); m_settingsLayout->setContentsMargins(TITLE_LAYOUT_MARGINS); m_settingsLabel = new KBorderlessButton(m_settingsFrame); m_settingsLabel->setCursor(Qt::PointingHandCursor); m_settingsLabel->setText(tr("Settings")); m_settingsLayout->addWidget(m_settingsLabel); m_settingsLayout->addStretch(); m_settingsFrame->setLayout(m_settingsLayout); m_mainLayout->addWidget(m_titleFrame); m_mainLayout->addWidget(m_titleDivider); m_mainLayout->addWidget(m_scrollFrame); if (!m_isSimpleMode) { m_mainLayout->addStretch(); m_mainLayout->addWidget(m_settingsDivider); m_mainLayout->addWidget(m_settingsFrame); } else { m_settingsDivider->hide(); m_settingsFrame->hide(); } QPalette pal = m_scrollArea->palette(); pal.setBrush(QPalette::Base, QColor(0,0,0,0)); //背景透明 m_scrollArea->setPalette(pal); showRate(); } bool WlanConnect::eventFilter(QObject *w, QEvent *e) { if (w == m_wirelessSwitch && e->type() == QEvent::MouseButtonRelease) { if (!m_wirelessSwitch->isCheckable()) { showDesktopNotify(tr("No wireless device avaliable"), "networkwrong"); } else { Q_EMIT setWirelessNetworkEnabled(!m_wirelessSwitch->isChecked()); } return true; } return QObject::eventFilter(w,e); } void WlanConnect::initComponent() { m_wirelessSwitch->blockSignals(true); m_wirelessSwitch->setChecked(manager->getWirelessEnabled()); m_wirelessSwitch->blockSignals(false); getDeviceList(deviceList); if (deviceList.isEmpty()) { qDebug() << "[WlanConnect]no device exist when init, set switch disable"; m_wirelessSwitch->setChecked(false); m_wirelessSwitch->setCheckable(false); qDebug() << "m_wirelessSwitch setCheckable setChecked" << false; } initNet(); if (!m_wirelessSwitch->isChecked() || deviceList.isEmpty()) { hideLayout(m_scrollAreaLayout); m_titleDivider->show(); } connect(m_settingsLabel, &KBorderlessButton::clicked, this, [=]() { runExternalApp(); }); } void WlanConnect::initConnect() { connect(manager, &KyNetworkManager::wirelessStateChange, this, &WlanConnect::onActiveConnectionChanged); connect(manager, &KyNetworkManager::deviceStateChange, this, &WlanConnect::onDeviceStatusChanged); connect(manager, &KyNetworkManager::wifiEnabledChanged, this, &WlanConnect::onWifiEnabledChanged); connect(manager, &KyNetworkManager::secuTypeChange, this, &WlanConnect::onNetworkSecuTypeChange); connect(manager, &KyNetworkManager::wirelessConnectionRemove, this, &WlanConnect::onWirelessConnectionRemove); connect(manager, &KyNetworkManager::wirelessConnectionAdd, this, &WlanConnect::onWirelessConnectionAdd); connect(manager, &KyNetworkManager::wirelessConnectionUpdate, this, &WlanConnect::onWirelessConnectionUpdate); connect(manager, &KyNetworkManager::wirelessDeviceAdd, this, &WlanConnect::onWirelessDeviceAdd); connect(manager, &KyNetworkManager::deviceRemove, this, &WlanConnect::onWirelessDeviceRemove); connect(manager, &KyNetworkManager::wirelessDeviceNameUpdate, this, &WlanConnect::onDeviceNameChanged); connect(manager, &KyNetworkManager::wifiNetworkAdd, this, &WlanConnect::onNetworkAdd); connect(manager, &KyNetworkManager::wifiNetworkRemove, this, &WlanConnect::onNetworkRemove); connect(manager, &KyNetworkManager::wifiNetworkUpdate, this, &WlanConnect::onNetworkUpdate); connect(manager, &KyNetworkManager::updateWifiList, this, &WlanConnect::updateList); connect(manager, &KyNetworkManager::deviceManagedChange, this, &WlanConnect::onDeviceManagedChange); connect(this, &WlanConnect::requestWirelessScan, manager, &KyNetworkManager::onRequestWirelessScan); connect(this, &WlanConnect::activateConnection, manager, &KyNetworkManager::onActivateConnection); connect(this, &WlanConnect::deactivateConnection, manager, &KyNetworkManager::onDeactivateConnection); connect(this,&WlanConnect::addAndActivateNormalWifi, manager, &KyNetworkManager::onAddAndActivateNormalWifi); connect(this, &WlanConnect::setWirelessNetworkEnabled, manager, &KyNetworkManager::onSetWirelessNetworkEnabled); connect(this, &WlanConnect::deleteConnect, manager, &KyNetworkManager::onDeleteConnect); //定时20s扫描 m_scanTimer = new QTimer(this); m_scanTimer->start(SCANTIMER); connect(m_scanTimer, &QTimer::timeout, this, &WlanConnect::reScan); //10s重新排序 // m_updateTimer = new QTimer(this); // m_updateTimer->start(UPDATETIMER); // connect(m_updateTimer, &QTimer::timeout, this, &WlanConnect::updateList); reScan(); } void WlanConnect::reScan() { Q_EMIT requestWirelessScan(); } //更新列表顺序 ->从so中重新拿 然后插+更新icon void WlanConnect::updateList(QString devName, QList connectItemList, QList list) { if (!m_wirelessSwitch->isChecked()) { return; } if (!deviceFrameMap.keys().contains(devName)) { return; } resortWifiList(deviceFrameMap[devName], connectItemList, list); } void WlanConnect::resortWifiList(ItemFrame *frame, QList connectItemList, QList list) { qDebug() << "resortWifiList" << frame->deviceFrame->deviceLabel->text(); if(nullptr == frame || frame->lanItemLayout->count() <= 0) { return; } int frameIndex = 0; QString activateSsid = ""; for (int i = 0; i < connectItemList.size(); ++i) { if (connectItemList.at(i).m_connStatus == CONNECT_STATE_ACTIVATED) { activateSsid = connectItemList.at(i).m_ssid; for (int i = 0; i < list.size(); ++i) { if (list.at(i).m_NetSsid == activateSsid) { updateIcon(frame->itemMap[list.at(i).m_NetSsid], list.at(i).m_signalStrength, list.at(i).m_secuType, list.at(i).m_isApConnection); break; } } frameIndex++; qDebug() << "resortWifiList no" << frameIndex << activateSsid << list.at(i).m_signalStrength; break; } } for (int listIndex = 0; listIndex < list.size(); ++listIndex) { if (frameIndex > frame->lanItemLayout->count() - 1) { return; } if (frame->itemMap.contains(list.at(listIndex).m_NetSsid) && list.at(listIndex).m_NetSsid != activateSsid) { frame->lanItemLayout->removeWidget(frame->itemMap[list.at(listIndex).m_NetSsid]); frame->lanItemLayout->insertWidget(frameIndex, frame->itemMap[list.at(listIndex).m_NetSsid]); if (!frame->itemMap[list.at(listIndex).m_NetSsid]->getIsLoading()) { updateIcon(frame->itemMap[list.at(listIndex).m_NetSsid], list.at(listIndex).m_signalStrength, list.at(listIndex).m_secuType, list.at(listIndex).m_isApConnection); } frameIndex++; qDebug() << "resortWifiList no" << frameIndex << list.at(listIndex).m_NetSsid << list.at(listIndex).m_signalStrength; } else { qDebug() << "not find " << list.at(listIndex).m_NetSsid << " in current list, ignore"; } } qDebug() << "resort finish"; } void WlanConnect::updateIcon(WlanItem *item, int signalStrength, QString security, bool isApConnection) { qDebug() << "updateIcon" << item->getName(); int sign = setSignal(signalStrength); bool isLock = true; if (security.isEmpty()) { isLock = false; } else { isLock = true; } QString iconamePath; if (isApConnection) { iconamePath = KApSymbolic; } else { iconamePath = wifiIcon(isLock, sign); } QIcon searchIcon = QIcon::fromTheme(iconamePath); item->setItemIcon(searchIcon); qDebug() << "updateIcon" << item->getName() << " finish"; } //device status change void WlanConnect::onDeviceStatusChanged() { } void WlanConnect::onDeviceNameChanged(QString oldName, QString newName) { qDebug() << "============onDeviceNameChanged" << oldName << newName; if (!deviceFrameMap.contains(oldName) || !deviceList.contains(oldName)) { qWarning() << "[WlanConnect]onDeviceNameChanged no such device " << oldName; return; } if (deviceFrameMap.contains(newName) && deviceList.contains(newName)) { qWarning() << "[WlanConnect]onDeviceNameChanged already has device " << newName; return; } removeDeviceFrame(oldName); getDeviceList(deviceList); if (deviceList.contains(newName)) { addDeviceFrame(newName); initNetListFromDevice(newName); setSwitchStatus(manager->getWirelessEnabled()); } } //activeconnect status change void WlanConnect::onActiveConnectionChanged(QString deviceName, QString ssid, QString uuid, KyConnectState status) { qDebug() << "onActiveConnectionChanged" << ssid << status; if (!m_wirelessSwitch->isChecked()) { return; } if (uuid.isEmpty()) { return; } WlanItem * item= nullptr; //device ssid 有可能均为空 if (deviceName.isEmpty() || ssid.isEmpty()) { if (status == CONNECT_STATE_ACTIVATING || status == CONNECT_STATE_ACTIVATED) { return; } QMap::iterator iter; for (iter = deviceFrameMap.begin(); iter != deviceFrameMap.end(); iter++) { if (uuid == iter.value()->uuid) { QMap::iterator itemIter; for (itemIter = iter.value()->itemMap.begin(); itemIter != iter.value()->itemMap.end(); itemIter++) { if (itemIter.value()->getUuid() == uuid ) { item = itemIter.value(); break; } } break; } } } else { if (!deviceFrameMap.contains(deviceName)) { return; } for (int i = 0; i < deviceFrameMap[deviceName]->itemMap.size(); ++i) { if (deviceFrameMap[deviceName]->itemMap.contains(ssid)) { item = deviceFrameMap[deviceName]->itemMap[ssid]; if (status == CONNECT_STATE_ACTIVATED || status == CONNECT_STATE_ACTIVATING) { deviceFrameMap[deviceName]->itemMap[ssid]->setUuid(uuid); deviceFrameMap[deviceName]->uuid = uuid; if (status == CONNECT_STATE_ACTIVATED) { deviceFrameMap[deviceName]->lanItemLayout->removeWidget(item); deviceFrameMap[deviceName]->lanItemLayout->insertWidget(0,item); } } else if (status == CONNECT_STATE_DEACTIVATED) { deviceFrameMap[deviceName]->uuid.clear(); } break; } } } if (nullptr != item) { itemActiveConnectionStatusChanged(item, status); if (status == CONNECT_STATE_ACTIVATED || status == CONNECT_STATE_DEACTIVATED) { QList list; manager->getWifiNetworkList(deviceName, list); for (int i = 0; i < list.size(); ++i) { if (list.at(i).m_NetSsid == ssid) { updateIcon(item,list.at(i).m_signalStrength,list.at(i).m_secuType,list.at(i).m_isApConnection); break; } } } } } //wifi add============================================================== void WlanConnect::onNetworkAdd(QString deviceName, KyWirelessNetItem wlanInfo) { qDebug()<<"[WlanConnect]onNetworkAdd "<< deviceName << " " << wlanInfo.m_NetSsid; if(!m_wirelessSwitch->isChecked() || deviceName.isEmpty()) { return; } if (!deviceList.contains(deviceName)) { qDebug() << "[WlanConnect]onNetworkAdd not contain " << deviceName << "then add"; deviceList.append(deviceName); addDeviceFrame(deviceName); onNetworkAdd(deviceName, wlanInfo); return; } insertOneWlanFrame(deviceFrameMap[deviceName], deviceName, wlanInfo); } //wifi remove ============================================================= void WlanConnect::onNetworkRemove(QString deviceName, QString wlannName) { //当前无此设备 忽略 if (deviceName.isEmpty() || !deviceFrameMap.contains(deviceName)) { qWarning() << "[WlanConnect]recieve network remove,but no such device:" << deviceName; return; } qDebug()<<"[WlanConnect]Wifi remove device:" << deviceName << ",wlan name:" << wlannName; removeOneWlanFrame(deviceFrameMap[deviceName], deviceName, wlannName); } //wifi secu Update ============================================================= void WlanConnect::onNetworkUpdate(QString deviceName, QString wlannName, KyWirelessNetItem item) { //当前无此设备 忽略 if (deviceName.isEmpty() || !deviceFrameMap.contains(deviceName)) { qWarning() << "[WlanConnect]recieve network update,but no such device:" << deviceName; return; } qDebug()<<"[WlanConnect]Wifi update device:" << deviceName << ",wlan name:" << wlannName; bool isFind = false; QMap::iterator itemIter; for (itemIter = deviceFrameMap[deviceName]->itemMap.begin(); itemIter != deviceFrameMap[deviceName]->itemMap.end(); ++itemIter) { if (itemIter.value()->getName() == wlannName) { itemIter.value()->setSecuType(item.m_secuType); isFind = true; break; } } if (!isFind) { insertOneWlanFrame(deviceFrameMap[deviceName], deviceName, item); } } //获取设备列表======================================================= void WlanConnect::getDeviceList(QStringList &list) { manager->getNetworkDeviceList(DEVICE_TYPE_WIFI, list); } //设置开关 void WlanConnect::setSwitchStatus(bool status) { m_wirelessSwitch->setCheckable(true); m_wirelessSwitch->blockSignals(true); m_wirelessSwitch->setChecked(status); m_wirelessSwitch->blockSignals(false); if (!status) { hideLayout(m_scrollAreaLayout); m_titleDivider->show(); } else { showLayout(m_scrollAreaLayout); m_titleDivider->hide(); } } //初始化整体列表和单设备列表 void WlanConnect::initNet() { //先构建每个设备的列表头 qDebug() << deviceList <start(REFRESH_NETWORKSPEED_TIMER); } //初始化设备列表 void WlanConnect::initNetListFromDevice(QString deviceName) { qDebug() << "[WlanConnect]initNetListFromDevice " << deviceName; if (!m_wirelessSwitch->isChecked()) { qWarning() << "[WlanConnect]initNetListFromDevice " << deviceName << " switch off"; return; } if (!deviceFrameMap.contains(deviceName)) { qWarning() << "[WlanConnect]initNetListFromDevice " << deviceName << " not exist"; return; } QList list; manager->getWifiNetworkList(deviceName, list); for (int i = 0; i < list.size(); ++i) { KyWirelessNetItem item = list.at(i); addOneWlanFrame(deviceFrameMap[deviceName], deviceName, item); } QList activateList; manager->getActiveConnectionList(deviceName, CONNECT_TYPE_WIRELESS, activateList); if (activateList.size() != 0) { onActiveConnectionChanged(deviceName,activateList.at(0).m_ssid, activateList.at(0).m_uuid, activateList.at(0).m_connStatus); } } //高级设置 void WlanConnect::runExternalApp() { QProcess process; process.startDetached("ukui-control-center -m wlanconnect"); } //根据信号强度分级+安全性分图标 QString WlanConnect::wifiIcon(bool isLock, int strength) { switch (strength) { case 1: return isLock ? KWifiLockSymbolic : KWifiSymbolic; case 2: return isLock ? KWifiLockGood : KWifiGood; case 3: return isLock ? KWifiLockOK : KWifiOK; case 4: return isLock ? KWifiLockLow : KWifiLow; case 5: return isLock ? KWifiLockNone : KWifiNone; default: return ""; } } //根据信号强度分级 int WlanConnect::setSignal(int signal) { int signalLv = 0; if (signal > 75) { signalLv = 1; } else if (signal > 55 && signal <= 75) { signalLv = 2; } else if (signal > 35 && signal <= 55) { signalLv = 3; } else if (signal > 15 && signal <= 35) { signalLv = 4; } else if (signal <= 15) { signalLv = 5; } return signalLv; } //隐藏 void WlanConnect::hideLayout(QVBoxLayout * layout) { for (int i = layout->layout()->count()-1; i >= 0; --i) { QLayoutItem *it = layout->layout()->itemAt(i); ItemFrame *itemFrame = qobject_cast(it->widget()); itemFrame->hide(); } } //显示 void WlanConnect::showLayout(QVBoxLayout * layout) { for (int i = layout->layout()->count()-1; i >= 0; --i) { QLayoutItem *it = layout->layout()->itemAt(i); ItemFrame *itemFrame = qobject_cast(it->widget()); itemFrame->show(); } } //增加设备 void WlanConnect::addDeviceFrame(QString devName) { qDebug() << "[WlanConnect]addDeviceFrame " << devName; ItemFrame *itemFrame = new ItemFrame(devName, pluginWidget); m_scrollAreaLayout->addWidget(itemFrame); itemFrame->deviceFrame->deviceLabel->setText(devName); deviceFrameMap.insert(devName, itemFrame); if (deviceList.indexOf(devName) < 0) { deviceList << devName; } connect(itemFrame, &ItemFrame::addNetItemClick , [=](){ //加入网络 itemFrame->showJoinPage(parentWidget); }); connect(itemFrame, &ItemFrame::connectHideNormalConnect, manager, &KyNetworkManager::onAddAndActivateNormalWifi); connect(itemFrame, &ItemFrame::connectHideTtlsConnect, manager, &KyNetworkManager::onAddAndActiveWirelessEnterPriseTtlsConnect); connect(itemFrame, &ItemFrame::connectHidePeapConnect, manager, &KyNetworkManager::onAddAndActiveWirelessEnterPrisePeapConnect); } //减少设备 void WlanConnect::removeDeviceFrame(QString devName) { qDebug() << "[WlanConnect]removeDeviceFrame " << devName; if (deviceFrameMap.contains(devName)) { ItemFrame *item = deviceFrameMap[devName]; if (item->lanItemFrame->layout() != NULL) { QLayoutItem* layoutItem; while ((layoutItem = item->lanItemFrame->layout()->takeAt(0)) != NULL) { delete layoutItem->widget(); delete layoutItem; } item->itemMap.clear(); } delete item; item = nullptr; item->disconnect(this); deviceFrameMap.remove(devName); } // getDeviceList(deviceList); deviceList.removeOne(devName); } //增加ap void WlanConnect::addOneWlanFrame(ItemFrame *frame, QString deviceName, KyWirelessNetItem &wlanInfo) { if (nullptr == frame) { return; } if (frame->itemMap.contains(wlanInfo.m_NetSsid)) { qDebug() << "[WlanConnect]Already exist a wifi " << wlanInfo.m_NetSsid << " in " << deviceName; return; } //设置单项的信息 int sign = setSignal(wlanInfo.m_signalStrength); WlanItem * wlanItem = new WlanItem(m_pluginType, pluginWidget); QString iconamePath; if (wlanInfo.m_isApConnection) { iconamePath = KApSymbolic; } else { iconamePath = wifiIcon(!wlanInfo.m_secuType.isEmpty(), sign); } QIcon searchIcon = QIcon::fromTheme(iconamePath); wlanItem->setItemIcon(searchIcon); wlanItem->setName(wlanInfo.m_NetSsid); wlanItem->setSecuType(wlanInfo.m_secuType); wlanItem->setUuid(wlanInfo.m_connectUuid); wlanItem->setPath(wlanInfo.m_dbusPath); wlanItem->setInterface(deviceName); connect(wlanItem, &WlanItem::infoButtonClick, this, [=]{ //todo 详情页 }); connect(wlanItem, &WlanItem::itemClick, this, [=] { if (wlanItem->getStatus() || wlanItem->getIsLoading()) { Q_EMIT deactivateConnection(wlanItem->getUuid()); } else { if (wlanItem->getExpend()) { wlanItem->setExpend(false); } else { //先看加密类型 再看是否已有配置 if (!wlanItem->getUuid().isEmpty()) { activateConnection(wlanItem->getUuid(), wlanItem->getInterface()); } else { if (wlanItem->getSecuType().isEmpty()) { KyWirelessConnectSetting sett; KySecuType secuType = KySecuType::NONE; sett.m_ssid = wlanItem->getName(); sett.m_ifaceName = wlanItem->getInterface(); Q_EMIT addAndActivateNormalWifi(sett, secuType); } else { if (wlanItem->getSecuType().indexOf("802.1X") != -1) { //todo 企业网页面 wlanItem->showEnterPricePage(deviceName, parentWidget); } else { wlanItem->setExpend(true); setOtherItemExpandedFalse(deviceName, wlanInfo.m_NetSsid); } } } } } }); connect(wlanItem, &WlanItem::connectButtonClick, this, [=](QString password, bool isAutoConnect) { KySecuType secuType; if (wlanItem->getSecuType().indexOf("WPA3")) { secuType = KySecuType::WPA3_PERSONAL; } else { secuType = KySecuType::WPA_AND_WPA2_PERSONAL; } KyWirelessConnectSetting sett; sett.m_ssid = wlanItem->getName(); sett.m_psk = password; sett.m_isAutoConnect = isAutoConnect; sett.m_ifaceName = wlanItem->getInterface(); Q_EMIT addAndActivateNormalWifi(sett, secuType); wlanItem->setExpend(false); }); connect(wlanItem, &WlanItem::connectPeapConnect, manager, &KyNetworkManager::onAddAndActiveWirelessEnterPrisePeapConnect); connect(wlanItem, &WlanItem::connectTtlsConnect, manager, &KyNetworkManager::onAddAndActiveWirelessEnterPriseTtlsConnect); connect(wlanItem, &WlanItem::passwordFocusIn, this, &WlanConnect::needShowVirtualKeyboard); connect(wlanItem, &WlanItem::connectLeapConnect, manager, &KyNetworkManager::onAddAndActiveWirelessEnterPriseLeapConnect); connect(wlanItem, &WlanItem::connectPwdConnect, manager, &KyNetworkManager::onAddAndActiveWirelessEnterPrisePwdConnect); connect(wlanItem, &WlanItem::connectFastConnect, manager, &KyNetworkManager::onAddAndActiveWirelessEnterPriseFastConnect); //记录到deviceFrame的itemMap中 deviceFrameMap[deviceName]->itemMap.insert(wlanInfo.m_NetSsid, wlanItem); qDebug()<<"add " << wlanInfo.m_NetSsid << " to " << deviceName << " list"; frame->lanItemLayout->addWidget(wlanItem); } //减少ap void WlanConnect::removeOneWlanFrame(ItemFrame *frame, QString deviceName, QString ssid) { if (nullptr == frame) { return; } if (frame->itemMap.contains(ssid)) { qDebug() << "[WlanConnect]removeOneWlanFrame " << deviceName << ssid; frame->lanItemLayout->removeWidget(frame->itemMap[ssid]); delete frame->itemMap[ssid]; frame->itemMap.remove(ssid); } } void WlanConnect::insertOneWlanFrame(ItemFrame *frame, QString devName, KyWirelessNetItem &wlanInfo) { addOneWlanFrame(frame, devName, wlanInfo); } void WlanConnect::itemActiveConnectionStatusChanged(WlanItem *item, int status) { if (status == CONNECT_STATE_ACTIVATING) { item->startLoading(); } else if (status == CONNECT_STATE_ACTIVATED) { item->stopLoading(); item->setStatus(true); } else if (status == CONNECT_STATE_DEACTIVATING) { item->startLoading(); } else if (status == CONNECT_STATE_DEACTIVATED) { item->stopLoading(); item->setStatus(false); } } void WlanConnect::onNetworkSecuTypeChange(QString deviceName, QString ssid, QString securityType) { Q_UNUSED(deviceName) Q_UNUSED(ssid) Q_UNUSED(securityType) } void WlanConnect::onWifiEnabledChanged(bool status) { // if (m_wirelessSwitch->isCheckable()) { setSwitchStatus(status); // } } void WlanConnect::onDeviceManagedChange(QString, bool status) { setSwitchStatus(status); } void WlanConnect::onWirelessConnectionRemove(QString deviceName, QString ssid) { qDebug() << "onWirelessConnectionRemove" << deviceName << ssid; WlanItem *item = findItem(deviceName,ssid); if (nullptr == item) { return; } if (item->getStatus()) { onActiveConnectionChanged(deviceName, ssid, item->getUuid(), CONNECT_STATE_DEACTIVATED); } item->setUuid(""); item->setPath(""); } void WlanConnect::onWirelessConnectionAdd(QString deviceName, QString ssid, QString uuid, QString dbusPath) { qDebug() << "onWirelessConnectionAdd" << deviceName << ssid; WlanItem *item = findItem(deviceName,ssid); if (nullptr == item) { return; } if (!item->getUuid().isEmpty() && !item->getPath().isEmpty()) item->setUuid(uuid); item->setPath(dbusPath); } void WlanConnect::onWirelessConnectionUpdate(QString deviceName, QString ssid, QString uuid, QString dbusPath, KySecuType connectSecuType) { } void WlanConnect::onWirelessDeviceAdd(QString deviceName) { addDeviceFrame(deviceName); setSwitchStatus(manager->getWirelessEnabled()); } void WlanConnect::onWirelessDeviceRemove(QString deviceName) { if (!deviceFrameMap.contains(deviceName) || deviceList.indexOf(deviceName) < 0) { return; } removeDeviceFrame(deviceName); if (deviceList.isEmpty()) { setSwitchStatus(false); m_wirelessSwitch->setCheckable(false); } } void WlanConnect::onSetNetSpeed() { if (deviceFrameMap.isEmpty()) { return; } QMap::iterator iter; for (iter = deviceFrameMap.begin(); iter != deviceFrameMap.end(); iter++) { if(nullptr == iter.value() || iter.value()->lanItemLayout->count() <= 0) { continue; } iter.value()->updateNetSpeed(); } } WlanItem* WlanConnect::findItem(QString devName, QString ssid) { if (!deviceFrameMap.contains(devName)) { return nullptr; } if (!deviceFrameMap[devName]->itemMap.contains(ssid)) { return nullptr; } return deviceFrameMap[devName]->itemMap[ssid]; } void WlanConnect::setOtherItemExpandedFalse(QString devName, QString ssid) { QMap::iterator iter; for (iter = deviceFrameMap.begin(); iter != deviceFrameMap.end(); iter++) { if (iter.key() != devName) { QMap::iterator itemIter; for (itemIter = iter.value()->itemMap.begin(); itemIter != iter.value()->itemMap.end(); itemIter++) { itemIter.value()->setExpend(false); } } else { QMap::iterator itemIter; for (itemIter = iter.value()->itemMap.begin(); itemIter != iter.value()->itemMap.end(); itemIter++) { if (itemIter.value()->getName() != ssid) { itemIter.value()->setExpend(false); } } } } } WlanItem* WlanConnect::getExpandedItem() { QMap::iterator iter; for (iter = deviceFrameMap.begin(); iter != deviceFrameMap.end(); iter++) { QMap::iterator itemIter; for (itemIter = iter.value()->itemMap.begin(); itemIter != iter.value()->itemMap.end(); itemIter++) { if (itemIter.value()->getExpend()) { return itemIter.value(); } } } return nullptr; } bool WlanConnect::getWirelessDeviceUseable() { for (auto devname : deviceList) { qDebug() << devname << (KyDeviceState)manager->getDeviceState(devname); if (manager->getDeviceState(devname) >= DEVICE_STATE_DISCONNECTED) { return true; } } return false; } void WlanConnect::showRate() { m_setNetSpeedTimer = new QTimer(this); m_setNetSpeedTimer->setTimerType(Qt::PreciseTimer); connect(m_setNetSpeedTimer, &QTimer::timeout, [&]() { onSetNetSpeed(); }); } bool WlanConnect::getWirelessDeviceAvailable() { for (auto devname : deviceList) { qDebug() << devname << (KyDeviceState)manager->getDeviceState(devname); if (manager->getDeviceState(devname) >= DEVICE_STATE_UNAVAILABLE) { return true; } } return false; } void WlanConnect::hideTitle() { m_wirelessSwitch->hide(); m_titleLabel->hide(); m_settingsLabel->hide(); } void WlanConnect::keyAgentRegister() { m_agent = new KylinAgent(this); if(m_agent) { m_agent->setParentWidget(parentWidget); m_agent->startKylinAgent(); qDebug() << "keyAgentRegister startKylinAgent"; } } void WlanConnect::keyAgentUnregister() { qDebug() << "keyAgentUnregister"; if(m_agent) { delete m_agent; } } /*弹窗时机应该自洽,原方案两个包之间会通过dbus交互,登录锁屏前端容易崩,直接使用后端锁屏与否的信号来决定是否在桌面注册弹窗*/ void WlanConnect::kylinAgentInit() { bool lockState = true; QDBusInterface dbusInterface("org.ukui.ScreenSaver", "/", "org.ukui.ScreenSaver", QDBusConnection::sessionBus()); if (!dbusInterface.isValid()) { qWarning()< #include #include #include #include #include #include const QString KLanSymbolic = "network-wired-connected-symbolic"; const QString NoNetSymbolic = "network-wired-disconnected-symbolic"; #define NO_MARGINS 0,0,0,0 #define TOP_MARGINS 0,8,0,0 #define MAIN_LAYOUT_MARGINS 0,0,0,0 #define MAIN_LAYOUT_SPACING 0 #define TITLE_FRAME_HEIGHT 50 //TabWidget的tab和widget有间隙,和设计稿看起来一致就不能设为设计稿里的高度 #define TITLE_LAYOUT_MARGINS 24,0,24,0 #define SPACING 8 #define REFRESH_NETWORKSPEED_TIMER 1000 #define SYSTEM_DBUS_SERVICE "com.kylin.network.qt.systemdbus" #define SYSTEM_DBUS_PATH "/" #define SYSTEM_DBUS_INTERFACE "com.kylin.network.interface" bool checkMapValveContainsTrue(QMap map) { if (map.isEmpty()) { return false; } QMap::iterator iter; for (iter = map.begin(); iter != map.end(); iter++) { if (iter.value()) { return true; } } return false; } NetConnect::NetConnect() : mFirstLoad(true) { qRegisterMetaType("KyDeviceState"); qRegisterMetaType("KyConnectSetting"); QLocale local; QString locale = local.name(); QTranslator* translator = new QTranslator(this); if (translator->load("/usr/share/kylin-nm-plugin/netconnect/"+ locale + ".qm")) { QApplication::installTranslator(translator); } else { qWarning() << "Translations load fail"; } } NetConnect::~NetConnect() { qDebug() << Q_FUNC_INFO << __LINE__; if (nullptr != thread) { thread->quit(); thread->wait(); delete thread; } if (nullptr != pluginWidget ) { delete pluginWidget; } qDebug() << Q_FUNC_INFO << __LINE__; } QWidget *NetConnect::pluginUi() { if (mFirstLoad) { mFirstLoad = false; pluginWidget = new QWidget; pluginWidget->setAttribute(Qt::WA_DeleteOnClose); initSystemDbus(); initUi(); initComponent(); initConnect(); if(OOBE == m_pluginType){ hideTitle(); } } return pluginWidget; } void NetConnect::setPluginType(PluginType type, bool useSwitch) { m_pluginType = type; if (type == SIMPLE) { m_isSimpleMode = true; } else { m_isSimpleMode = false; } m_useSwitch = useSwitch; } bool NetConnect::checkPluginIsHidden() { return true; //to show this plugin #if 0 if (nullptr != m_wiredSwitch) { return m_wiredSwitch->isEnabled(); } return false; #endif } void NetConnect::initSystemDbus() { //add netconnect swtich signal m_pSysBusIntfs = new QDBusInterface(SYSTEM_DBUS_SERVICE, SYSTEM_DBUS_PATH, SYSTEM_DBUS_INTERFACE, QDBusConnection::systemBus()); if (m_pSysBusIntfs->isValid()) { //bind manager swtich signal QDBusConnection::systemBus().connect(SYSTEM_DBUS_SERVICE, SYSTEM_DBUS_PATH, SYSTEM_DBUS_INTERFACE, "sysWiredMainSwitchChanged", this, SLOT(onWiredMainSwitchChanged(bool))); } } void NetConnect::initUi() { thread = new QThread; manager = new KyNetworkManager(); manager->moveToThread(thread); connect(thread, &QThread::started, manager, &KyNetworkManager::kylinNetworkManagerInit); connect(thread, &QThread::finished, manager, &KyNetworkManager::deleteLater); connect(thread, &QThread::finished, [=](){ qDebug() << "NetConnect thread quit"; }); thread->start(); while (!manager->isInitFinished()) { ::usleep(1000); } m_mainLayout = new QVBoxLayout(pluginWidget); m_mainLayout->setContentsMargins(MAIN_LAYOUT_MARGINS); m_mainLayout->setSpacing(MAIN_LAYOUT_SPACING); pluginWidget->setLayout(m_mainLayout); m_titleFrame = new QFrame(pluginWidget); m_titleFrame->setFixedHeight(53); m_titleLayout = new QHBoxLayout(m_titleFrame); m_titleLayout->setContentsMargins(TITLE_LAYOUT_MARGINS); m_titleLabel = new QLabel(m_titleFrame); m_titleLabel->setText(tr("LAN")); m_wiredSwitch = new KSwitchButton(pluginWidget); m_wiredSwitch->installEventFilter(this); m_titleLayout->addWidget(m_titleLabel); m_titleLayout->addStretch(); m_titleLayout->addWidget(m_wiredSwitch); m_titleDivider = new Divider(pluginWidget); m_titleDivider->hide(); m_scrollFrame = new QFrame(pluginWidget); if (!m_isSimpleMode) { m_scrollFrame->setMinimumHeight(330); } else { m_scrollFrame->setMinimumHeight(383); } if (OOBE == m_pluginType){ m_scrollFrame->setFixedHeight(700); } m_scrollLayout = new QVBoxLayout(m_scrollFrame); m_scrollLayout->setContentsMargins(0,0,0,0); m_scrollLayout->setSpacing(0); m_scrollFrame->setLayout(m_scrollLayout); m_scrollArea = new QScrollArea(m_scrollFrame); m_scrollArea->setFrameShape(QFrame::Shape::NoFrame); m_scrollArea->setWidgetResizable(true); m_scrollArea->setBackgroundRole(QPalette::Base); m_scrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); m_scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_scrollLayout->addWidget(m_scrollArea); m_listWidget = new QWidget(pluginWidget); m_listWidget->setFixedWidth(420); m_scrollAreaLayout = new QVBoxLayout(m_listWidget); m_scrollAreaLayout->setSpacing(MAIN_LAYOUT_SPACING); m_scrollAreaLayout->setContentsMargins(MAIN_LAYOUT_MARGINS); m_scrollAreaLayout->setAlignment(Qt::AlignTop); m_listWidget->setLayout(m_scrollAreaLayout); m_scrollArea->setWidget(m_listWidget); m_settingsDivider = new Divider(pluginWidget); m_settingsFrame = new QFrame(pluginWidget); m_settingsFrame->setFixedHeight(TITLE_FRAME_HEIGHT); m_settingsLayout = new QHBoxLayout(m_settingsFrame); m_settingsLayout->setContentsMargins(TITLE_LAYOUT_MARGINS); m_settingsLabel = new KBorderlessButton(m_settingsFrame); m_settingsLabel->setCursor(Qt::PointingHandCursor); m_settingsLabel->setText(tr("Settings")); m_settingsLayout->addWidget(m_settingsLabel); m_settingsLayout->addStretch(); m_settingsFrame->setLayout(m_settingsLayout); m_mainLayout->addWidget(m_titleFrame); m_mainLayout->addWidget(m_titleDivider); m_mainLayout->addWidget(m_scrollFrame); if (!m_isSimpleMode) { m_mainLayout->addStretch(); m_mainLayout->addWidget(m_settingsDivider); m_mainLayout->addWidget(m_settingsFrame); } else { m_settingsDivider->hide(); m_settingsFrame->hide(); } QPalette pal = m_scrollArea->palette(); pal.setBrush(QPalette::Base, QColor(0,0,0,0)); //背景透明 m_scrollArea->setPalette(pal); showRate(); } void NetConnect::showDesktopNotify(const QString &message, QString soundName) { QDBusInterface iface("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "org.freedesktop.Notifications", QDBusConnection::sessionBus()); QStringList actions; //跳转动作 actions.append("default"); actions.append("kylin-nm"); //默认动作:点击消息体时打开麒麟录音 QMap hints; if (!soundName.isEmpty()) { hints.insert("sound-name",soundName); //添加声音 } QList args; args<<(tr("Kylin NM")) <<((unsigned int) 0) <type() == QEvent::MouseButtonRelease) { // // if (!m_wiredSwitch->isEnabled()) { // // // showDesktopNotify(tr("No ethernet device avaliable")); // // qDebug() << "No ethernet device avaliable"; // // } else { // // Q_EMIT setWiredEnabled(!m_wiredSwitch->isChecked()); // // } // // return true; // // } // return QObject::eventFilter(w,e); // } void NetConnect::initComponent() { getDeviceStatusMap(deviceStatusMap); initNet(); setSwitchStatus(); connect(m_settingsLabel, &KBorderlessButton::clicked, this, [=](bool checked) { Q_UNUSED(checked) runExternalApp(); }); } void NetConnect::initConnect() { connect(manager, &KyNetworkManager::wiredStateChange, this, &NetConnect::onActiveConnectionChanged); //connect(manager, &KyNetworkManager::deviceStateChange, this, &NetConnect::onDeviceStatusChanged); connect(manager, &KyNetworkManager::carrierChange, this, &NetConnect::onDeviceCarrierChange); connect(manager, &KyNetworkManager::wiredConnectionAdd, this, &NetConnect::onLanAdd); connect(manager, &KyNetworkManager::wiredConnectionUpdate, this, &NetConnect::updateLanInfo); connect(manager, &KyNetworkManager::connectionRemove, this, &NetConnect::onLanRemove); connect(manager, &KyNetworkManager::wiredDeviceAdd, this, &NetConnect::onDeviceAdd); connect(manager, &KyNetworkManager::deviceRemove, this, &NetConnect::onDeviceRemove); connect(manager, &KyNetworkManager::wiredDeviceUpdate, this, &NetConnect::onDeviceNameChanged); connect(manager, &KyNetworkManager::deviceManagedChange, this, &NetConnect::onDeviceManagedChange); connect(manager, &KyNetworkManager::wiredEnabledChanged, this, &NetConnect::onWiredEnabledChanged); connect(this, &NetConnect::setWiredDeviceEnable, manager, &KyNetworkManager::onSetWiredDeviceEnable); connect(this, &NetConnect::setWiredEnabled, manager, &KyNetworkManager::onSetWiredEnabled); connect(this, &NetConnect::activateConnection, manager, &KyNetworkManager::onActivateConnection); connect(this, &NetConnect::deactivateConnection, manager, &KyNetworkManager::onDeactivateConnection); connect(this, &NetConnect::deleteConnect, manager, &KyNetworkManager::onDeleteConnect); connect(this, &NetConnect::updateIpv4AndIpv6SettingInfo, manager, &KyNetworkManager::onUpdateIpv4AndIpv6SettingInfo); connect(this, &NetConnect::createWiredConnect, manager, &KyNetworkManager::onCreateWiredConnect); //btn connect(m_wiredSwitch, &KSwitchButton::clicked, this, &NetConnect::onWiredEnabledChanged); } //获取网卡列表 void NetConnect::getDeviceStatusMap(QMap &map) { map.clear(); QStringList wiredDevList; wiredDevList.clear(); manager->getNetworkDeviceList(DEVICE_TYPE_ETHERNET, wiredDevList); qDebug() << wiredDevList; if (!wiredDevList.isEmpty()) { for (int i = 0; i < wiredDevList.size(); ++i) { QString devName = wiredDevList.at(i);qDebug() << devName; map.insert(devName, manager->getDeviceManaged(devName)); } } } //lanUpdate void NetConnect::updateLanInfo(QString deviceName, QString connectUuid, QString connectName, QString connectPath) { QMap::iterator devIter; QMap::iterator itemIter; for (devIter = deviceFrameMap.begin(); devIter != deviceFrameMap.end(); devIter++) { // 全部show出来 for (itemIter = devIter.value()->itemMap.begin(); itemIter != devIter.value()->itemMap.end(); itemIter++) { if(itemIter.value()->getName() != connectName){ itemIter.value()->show(); } } } //设备归属变化 || 有线名称变化 QMap::iterator iter; for (iter = deviceFrameMap.begin(); iter != deviceFrameMap.end(); iter++) { if (deviceName.isEmpty()) { //变为无指定网卡,所有列表都要添加 if (!iter.value()->itemMap.contains(connectUuid)) { QStringList lanInfo; lanInfo << connectName << connectUuid << connectPath; addOneLanFrame(iter.value(), iter.key(), lanInfo); } else { if (iter.value()->itemMap[connectUuid]->getName() != connectName) { qDebug() << "[NetConnect]" << iter.key() << iter.value()->itemMap[connectUuid]->getName() << "change to" << connectName; iter.value()->itemMap[connectUuid]->setName(connectName); deviceFrameMap[iter.key()]->lanItemLayout->removeWidget(iter.value()->itemMap[connectUuid]); int index = getInsertPos(connectName, deviceFrameMap[iter.key()]->lanItemLayout); deviceFrameMap[iter.key()]->lanItemLayout->insertWidget(index,iter.value()->itemMap[connectUuid]); } } } else { if (iter.key() != deviceName) { qDebug() << "[NetConnect]" << connectUuid << " not belongs to " << iter.key(); removeOneLanFrame(iter.value(), deviceName, connectUuid); } else { if (!iter.value()->itemMap.contains(connectUuid)) { qDebug() << "[NetConnect]" << connectUuid << " now belongs to " << deviceName; QStringList lanInfo; lanInfo << connectName << connectUuid << connectPath; addOneLanFrame(iter.value(), deviceName, lanInfo); } else { qDebug() << "[NetConnect]" << deviceName << iter.value()->itemMap[connectUuid]->getName() << "change to" << connectName; if (iter.value()->itemMap[connectUuid]->getName() != connectName) { iter.value()->itemMap[connectUuid]->setName(connectName); deviceFrameMap[iter.key()]->lanItemLayout->removeWidget(iter.value()->itemMap[connectUuid]); int index = getInsertPos(connectName, deviceFrameMap[iter.key()]->lanItemLayout); deviceFrameMap[iter.key()]->lanItemLayout->insertWidget(index,iter.value()->itemMap[connectUuid]); } } } } } } //总开关 void NetConnect::setSwitchStatus() { getDeviceStatusMap(deviceStatusMap); if (deviceStatusMap.isEmpty()) { m_wiredSwitch->setChecked(false); m_wiredSwitch->setEnabled(false); #if 0 Q_EMIT updatePluginHidden(false); #endif } else { m_wiredSwitch->setEnabled(true); bool status = getWiredMainSwitch(); m_wiredSwitch->setChecked(status); if (!status) { hideLayout(m_scrollAreaLayout); m_titleDivider->show(); } else { showLayout(m_scrollAreaLayout); m_titleDivider->hide(); } #if 0 Q_EMIT updatePluginHidden(true); #endif } } //总体隐藏 void NetConnect::hideLayout(QVBoxLayout * layout) { for (int i = layout->layout()->count()-1; i >= 0; --i) { QLayoutItem *it = layout->layout()->itemAt(i); ItemFrame *itemFrame = qobject_cast(it->widget()); itemFrame->hide(); } } //总体显示 void NetConnect::showLayout(QVBoxLayout * layout) { for (int i = layout->layout()->count()-1; i >= 0; --i) { QLayoutItem *it = layout->layout()->itemAt(i); ItemFrame *itemFrame = qobject_cast(it->widget()); if (deviceStatusMap[itemFrame->m_deviceName]) { itemFrame->show(); } else { itemFrame->hide(); } } } //初始化 void NetConnect::initNet() { //先构建每个设备的列表头 QStringList deviceList = deviceStatusMap.keys(); for (int i = 0; i < deviceList.size(); ++i) { addDeviceFrame(deviceList.at(i), deviceStatusMap[deviceList.at(i)]); } //再填充每个设备的列表 for (int i = 0; i < deviceList.size(); ++i) { initNetListFromDevice(deviceList.at(i)); } m_setNetSpeedTimer->start(REFRESH_NETWORKSPEED_TIMER); } void NetConnect::runExternalApp() { QProcess process; process.startDetached("ukui-control-center -m netconnect"); } //激活 void NetConnect::activeConnect(QString uuid, QString deviceName) { if (manager) { bool isCarriered = manager->getWiredDeviceIsCarriered(deviceName); if (!isCarriered){ showDesktopNotify(tr("Wired Device not carried"), "networkwrong"); } } Q_EMIT activateConnection(uuid, deviceName); } //断开 void NetConnect::deActiveConnect(QString uuid) { Q_EMIT deactivateConnection(uuid); } //初始化设备列表 void NetConnect::initNetListFromDevice(QString deviceName) { qDebug() << "[NetConnect]initNetListFromDevice " << deviceName; if (!deviceFrameMap.contains(deviceName)) { qDebug() << "[NetConnect]initNetListFromDevice " << deviceName << " not exist"; return; } QMap> wiredMap; manager->getWiredList(wiredMap); QList activateUuidList; QList activateDeviceList; for (auto it = wiredMap.begin(); it != wiredMap.end(); ++it) { // 获取wiredMap里面的设备名称,将getActiveConnectionList里面所有的连接名称保存 QList activeConnections; manager->getActiveConnectionList(it.key(), CONNECT_TYPE_WIRED, activeConnections); for (const auto& connection : activeConnections) { qDebug() << "Active connection name: " << connection.m_uuid; activateUuidList.append(connection.m_uuid); activateDeviceList.append(it.key()); } } if (wiredMap.size() == 0) { qDebug() << "[NetConnect]initNetListFromDevice " << deviceName << " list empty"; return; } QMap>::iterator iter; for (iter = wiredMap.begin(); iter != wiredMap.end(); iter++) { if (deviceName == iter.key()) { QList lanListInfo = iter.value(); //处理列表 for (int i = 0; i < lanListInfo.length(); i++) { // 判断lanListInfo.at(i).m_connectUuid是否在activeConnections addLanItem(deviceFrameMap[deviceName], deviceName, lanListInfo.at(i)); // 如果判断网卡是否连接,未连接的同名连接进行移除,在初始化的时候 if(activateUuidList.contains(lanListInfo.at(i).m_connectUuid)&&!activateDeviceList.contains(deviceName)){ // 隐藏item deviceFrameMap[deviceName]->itemMap[lanListInfo.at(i).m_connectUuid]->hide(); } } } } QList activateList; manager->getActiveConnectionList(deviceName, CONNECT_TYPE_WIRED, activateList); if (activateList.size() != 0) { onActiveConnectionChanged(deviceName, activateList.at(0).m_uuid, activateList.at(0).m_connStatus); } } //初始化时添加一个项 void NetConnect::addLanItem(ItemFrame *frame, QString devName, KyWiredItem item) { if (frame == nullptr) { return; } LanItem * lanItem = new LanItem(m_isSimpleMode, pluginWidget); QIcon searchIcon = QIcon::fromTheme(NoNetSymbolic); lanItem->setItemIcon(searchIcon); lanItem->setName(item.m_connectName); lanItem->setUuid(item.m_connectUuid); lanItem->setPath(item.m_connectPath); //todo show detail page connect(lanItem, &LanItem::infoButtonClick, this, [=](QString uuid) { onShowDetailPage(devName, uuid); }); lanItem->setStatus(false); connect(lanItem, &LanItem::itemClick, this, [=] { if (lanItem->getStatus() || lanItem->getIsLoading()) { deActiveConnect(lanItem->getUuid()); } else { activeConnect(lanItem->getUuid(), devName); } }); //记录到deviceFrame的itemMap中 deviceFrameMap[devName]->itemMap.insert(item.m_connectUuid, lanItem); frame->lanItemLayout->addWidget(lanItem); } //增加设备 void NetConnect::addDeviceFrame(QString devName, bool isEnable) { ItemFrame *itemFrame = new ItemFrame(devName, pluginWidget); m_scrollAreaLayout->addWidget(itemFrame); itemFrame->deviceFrame->deviceLabel->setText(devName); if (isEnable) { itemFrame->show(); } else { itemFrame->hide(); } deviceFrameMap.insert(devName, itemFrame); deviceStatusMap.insert(devName, true); } //减少设备 void NetConnect::removeDeviceFrame(QString devName) { if (deviceFrameMap.contains(devName)) { ItemFrame *item = deviceFrameMap[devName]; if (item->lanItemFrame->layout() != NULL) { QLayoutItem* layoutItem; while ((layoutItem = item->lanItemFrame->layout()->takeAt(0)) != NULL) { delete layoutItem->widget(); delete layoutItem; layoutItem = nullptr; } item->itemMap.clear(); } delete item; item = nullptr; deviceFrameMap.remove(devName); } } //device add or remove================================= #if 0 void NetConnect::onDeviceStatusChanged() { qDebug()<<"[NetConnect]onDeviceStatusChanged"; QEventLoop eventloop; QTimer::singleShot(300, &eventloop, SLOT(quit())); eventloop.exec(); QStringList list; QMap map; getDeviceStatusMap(map); list = map.keys(); QStringList removeList; QMap addMap; //remove的设备 for (int i = 0; i< deviceStatusMap.keys().size(); ++i) { if (!list.contains(deviceStatusMap.keys().at(i))) { qDebug() << "[NetConnect]onDeviceStatusChanged " << deviceStatusMap.keys().at(i) << "was removed"; removeList << deviceStatusMap.keys().at(i); } } //add的设备 for (int i = 0; i< list.size(); ++i) { if (!deviceStatusMap.keys().contains(list.at(i))) { qDebug() << "[NetConnect]onDeviceStatusChanged " << list.at(i) << "was add, init status" << map[list.at(i)]; addMap.insert(list.at(i),map[list.at(i)]); } } for (int i = 0; i < removeList.size(); ++i) { removeDeviceFrame(removeList.at(i)); } QStringList addList = addMap.keys(); for (int i = 0; i < addList.size(); ++i) { qDebug() << "add a device " << addList.at(i) << "status" << map[addList.at(i)]; addDeviceFrame(addList.at(i)); initNetListFromDevice(addList.at(i)); } deviceStatusMap = map; if (deviceStatusMap.isEmpty()) { wiredSwitch->setDisabledFlag(true); wiredSwitch->setChecked(false); } else { wiredSwitch->setDisabledFlag(false); setSwitchStatus(); } } #endif void NetConnect::onDeviceNameChanged(QString oldName, QString newName) { if (!deviceFrameMap.contains(oldName) || !deviceStatusMap.contains(oldName)) { qDebug() << "[NetConnect]onDeviceNameChanged no such device " << oldName; return; } if (deviceFrameMap.contains(newName) && deviceStatusMap.contains(newName)) { qDebug() << "[NetConnect]onDeviceNameChanged already has device " << newName; return; } qDebug() << "[NetConnect]onDeviceNameChanged " << oldName << "change to" << newName; //shan chu chong jian removeDeviceFrame(oldName); removeDeviceFrame(newName); getDeviceStatusMap(deviceStatusMap); addDeviceFrame(newName, manager->getDeviceManaged(newName)); initNetListFromDevice(newName); } //lan add=============================================================== void NetConnect::onLanAdd(QString devName, QString connectUuid, QString connectName, QString connectPath) { qDebug() << "onLanAdd"; if (!devName.isEmpty() && !deviceStatusMap.contains(devName)) { return; } QStringList lanInfo; lanInfo << connectName << connectUuid << connectPath; QMap::iterator iter; for (iter = deviceFrameMap.begin(); iter != deviceFrameMap.end(); iter++) { if (devName.isEmpty()) { addOneLanFrame(iter.value(), iter.key(), lanInfo); } else if (devName == iter.key()) { addOneLanFrame(iter.value(), devName, lanInfo); break; } } } //wifi remove ============================================================= void NetConnect::onLanRemove(QString lanPath) { qDebug() << "onLanRemove"; QMap::iterator iter; for (iter = deviceFrameMap.begin(); iter != deviceFrameMap.end(); iter++) { QMap::iterator itemIter; for (itemIter = iter.value()->itemMap.begin(); itemIter != iter.value()->itemMap.end(); itemIter++) { if (itemIter.value()->getPath() == lanPath) { qDebug()<<"[NetConnect]lan remove " << lanPath << " find in " << itemIter.value()->getName(); QString key = itemIter.key(); iter.value()->lanItemLayout->removeWidget(itemIter.value()); delete itemIter.value(); iter.value()->itemMap.remove(key); break; } } } } //增加一项 void NetConnect::addOneLanFrame(ItemFrame *frame, QString deviceName, QStringList infoList) { if (nullptr == frame) { return; } if (frame->itemMap.contains(infoList.at(1))) { qDebug() << "[NetConnect]Already exist a lan " << infoList.at(1) << " in " << deviceName; return; } qDebug() << "[NetConnect]addOneLanFrame" << deviceName << infoList.at(0); QString connName = infoList.at(0); QString connUuid = infoList.at(1); QString connDbusPath = infoList.at(2); LanItem * lanItem = new LanItem(m_isSimpleMode, pluginWidget); QIcon searchIcon = QIcon::fromTheme(NoNetSymbolic); lanItem->setItemIcon(searchIcon); lanItem->setName(connName); lanItem->setUuid(connUuid); lanItem->setPath(connDbusPath); // todo open landetail page if (!m_isSimpleMode) { connect(lanItem, &LanItem::infoButtonClick, this, [=](QString uuid) { onShowDetailPage(deviceName, uuid); }); } lanItem->setStatus(false); connect(lanItem, &LanItem::itemClick, this, [=] { if (lanItem->getStatus() || lanItem->getIsLoading()) { deActiveConnect(lanItem->getUuid()); } else { activeConnect(lanItem->getUuid(), deviceName); } }); //记录到deviceFrame的itemMap中 deviceFrameMap[deviceName]->itemMap.insert(connUuid, lanItem); int index = getInsertPos(connName, deviceFrameMap[deviceName]->lanItemLayout); qDebug()<<"[NetConnect]addOneLanFrame " << connName << " to " << deviceName << " list at pos:" << index; frame->lanItemLayout->insertWidget(index, lanItem); } void NetConnect::removeOneLanFrame(ItemFrame *frame, QString deviceName, QString uuid) { if (nullptr == frame) { return; } if (!frame->itemMap.contains(uuid)) { qDebug() << "[NetConnect]not exist a lan " << uuid << " in " << deviceName; return; } qDebug()<<"[NetConnect]removeOneLanFrame " << uuid << " find in " << deviceName; frame->lanItemLayout->removeWidget(frame->itemMap[uuid]); delete frame->itemMap[uuid]; frame->itemMap.remove(uuid); } //activeconnect status change void NetConnect::onActiveConnectionChanged(QString deviceName, QString uuid, KyConnectState status) { if (uuid.isEmpty()) { qDebug() << "[NetConnect]onActiveConnectionChanged but uuid is empty"; return; } qDebug() << "[NetConnect]onActiveConnectionChanged " << deviceName << uuid << status; LanItem * item= nullptr; if (deviceName.isEmpty()) { if (status != CONNECT_STATE_DEACTIVATED) { return; } //断开时 设备为空 说明此有线未指定设备 添加到所有列表中 QStringList infoList; QMap::iterator iters; for (iters = deviceFrameMap.begin(); iters != deviceFrameMap.end(); iters++) { if (iters.value()->itemMap.contains(uuid)) { item = iters.value()->itemMap[uuid]; //为断开则重新插入 deviceFrameMap[iters.key()]->lanItemLayout->removeWidget(item); int index = getInsertPos(item->getName(), deviceFrameMap[iters.key()]->lanItemLayout); qDebug() << "[NetConnect]reinsert" << item->getName() << "pos" << index << "in" << iters.key() << "because status changes to deactive"; deviceFrameMap[iters.key()]->lanItemLayout->insertWidget(index,item); itemActiveConnectionStatusChanged(item, status); } } //添加到所有列表中 if (!infoList.isEmpty()) { QMap::iterator iter; for (iter = deviceFrameMap.begin(); iter != deviceFrameMap.end(); iter++) { if (!iter.value()->itemMap.contains(uuid)) { addOneLanFrame(iter.value(), iter.key(), infoList); } } } } else { if (deviceFrameMap.contains(deviceName)) { if (deviceFrameMap[deviceName]->itemMap.contains(uuid)) { item = deviceFrameMap[deviceName]->itemMap[uuid]; if (status == CONNECT_STATE_ACTIVATED) { //为已连接则放到第一个 QMap> wiredMap; manager->getWiredList(wiredMap); QList activateUuidList; for (auto it = wiredMap.begin(); it != wiredMap.end(); ++it) { // 获取wiredMap里面的设备名称,将getActiveConnectionList里面所有的连接名称保存 QList activeConnections; manager->getActiveConnectionList(it.key(), CONNECT_TYPE_WIRED, activeConnections); for (const auto& connection : activeConnections) { qDebug() << "Active connection name: " << connection.m_uuid; activateUuidList.append(connection.m_uuid); } } // 根据当前连接的名称隐藏所有网卡下同名的连接 QMap::iterator biter; for (biter = deviceFrameMap.begin(); biter != deviceFrameMap.end(); biter++) { if (biter.value()->itemMap.contains(uuid)) { QString key = biter.key(); LanItem *itemTmp = deviceFrameMap[key]->itemMap[uuid]; // 如果同名连接为当前网卡则移除,其余网卡下则隐藏 if(deviceName !=key){ itemTmp->hide(); }else{ deviceFrameMap[key]->lanItemLayout->removeWidget(itemTmp); } } } deviceFrameMap[deviceName]->lanItemLayout->insertWidget(0,item); deviceFrameMap[deviceName]->startNetSpeedThread(); } else if (status == CONNECT_STATE_DEACTIVATED) { //为断开则重新插入 deviceFrameMap[deviceName]->lanItemLayout->removeWidget(item); int index = getInsertPos(item->getName(), deviceFrameMap[deviceName]->lanItemLayout); qDebug() << "[NetConnect]reinsert" << item->getName() << "pos" << index << "in" << deviceName << "because status changes to deactive"; deviceFrameMap[deviceName]->lanItemLayout->insertWidget(index,item); deviceFrameMap[deviceName]->stopNetSpeedThread(); } itemActiveConnectionStatusChanged(item, status); } } else { if (status == CONNECT_STATE_ACTIVATED || status == CONNECT_STATE_DEACTIVATED) { //虚拟网卡处理 QMap::iterator iters; for (iters = deviceFrameMap.begin(); iters != deviceFrameMap.end(); iters++) { if (iters.value()->itemMap.contains(uuid)) { removeOneLanFrame(iters.value(), iters.key(), uuid); } } } } } } void NetConnect::itemActiveConnectionStatusChanged(LanItem *item, KyConnectState status) { if (status == CONNECT_STATE_ACTIVATING) { item->startLoading(); } else if (status == CONNECT_STATE_ACTIVATED) { item->stopLoading(); QIcon searchIcon = QIcon::fromTheme(KLanSymbolic); item->setItemIcon(searchIcon); item->setStatus(true); } else if (status == CONNECT_STATE_DEACTIVATING) { item->startLoading(); } else { item->stopLoading(); QIcon searchIcon = QIcon::fromTheme(NoNetSymbolic); item->setItemIcon(searchIcon); item->setStatus(false); } } void NetConnect::showRate() { m_setNetSpeedTimer = new QTimer(this); m_setNetSpeedTimer->setTimerType(Qt::PreciseTimer); connect(m_setNetSpeedTimer, &QTimer::timeout, [&]() { onSetNetSpeed(); }); } int NetConnect::getInsertPos(QString connName, QVBoxLayout* layout) { // qDebug() << "[NetConnect]getInsertPos" << connName << deviceName; // int index = 0; // QMap> wiredMap; // manager->getWiredList(wiredMap); // if (!wiredMap.contains(deviceName)) { // return 0; // } // QList activateList; // QString name; // manager->getActiveConnectionList(deviceName, CONNECT_TYPE_WIRED, activateList); // if (activateList.size() != 0) { // name = activateList.at(0).m_connName; // } // bool isFind = false; // for (;index < wiredMap[deviceName].size(); ++index) { // if (wiredMap[deviceName].at(index).m_connectName == connName) { // break; // } else if (wiredMap[deviceName].at(index).m_connectName == name) { // isFind = true; // } // } // if (!isFind) { // index++; // } // return index; int index = 0; for (; index < layout->count(); ++index) { QLayoutItem *it = layout->layout()->itemAt(index); LanItem *item = qobject_cast(it->widget()); if (QString::compare(connName, item->getName(), Qt::CaseInsensitive) > 0) { qDebug() << "compare" << connName << item->getName() << index; continue; } else { if (item->getStatus()) { continue; } break; } } return index; } void NetConnect::onDeviceCarrierChange(QString deviceName, bool pluged) { } void NetConnect::onDeviceManagedChange(QString deviceName, bool managed) { getDeviceStatusMap(deviceStatusMap); if (deviceFrameMap.contains(deviceName)) { if (managed) { deviceFrameMap[deviceName]->show(); } else { deviceFrameMap[deviceName]->hide(); } } setSwitchStatus(); } void NetConnect::onWiredEnabledChanged(bool enabled) { qDebug() << Q_FUNC_INFO << __LINE__ << enabled; // if (m_wiredSwitch->isChecked() == enabled) { // qDebug() << Q_FUNC_INFO << __LINE__ << "return"; // return; // } qWarning() << Q_FUNC_INFO << __LINE__ << deviceFrameMap.keys(); if (0 == deviceFrameMap.keys().count()) { showDesktopNotify(tr("No ethernet device avaliable"), "networkwrong"); } if (m_pSysBusIntfs == nullptr || !m_pSysBusIntfs->isValid()) { qWarning() << Q_FUNC_INFO << __LINE__ << "m_pSysBusIntfs is error"; return; } m_pSysBusIntfs->call(QStringLiteral("setWiredMainSwitch"), enabled); setSwitchStatus(); // Q_EMIT setWiredEnabled(enabled); if (!enabled) { QMap::iterator iter1; for (iter1 = deviceFrameMap.begin(); iter1 != deviceFrameMap.end(); iter1++) { QMap::iterator iter2; for (iter2 = iter1.value()->itemMap.begin(); iter2 != iter1.value()->itemMap.end(); iter2++) { if (iter2.value()->getStatus()) { deActiveConnect(iter2.value()->getUuid()); } } } } } void NetConnect::onDeviceAdd(QString deviceName) { addDeviceFrame(deviceName, manager->getDeviceManaged(deviceName)); initNetListFromDevice(deviceName); setSwitchStatus(); } void NetConnect::onDeviceRemove(QString deviceName) { if (!deviceFrameMap.contains(deviceName) || !deviceStatusMap.contains(deviceName)) { return; } removeDeviceFrame(deviceName); setSwitchStatus(); } void NetConnect::onSetNetSpeed() { if (deviceFrameMap.isEmpty()) { return; } QMap::iterator iter; for (iter = deviceFrameMap.begin(); iter != deviceFrameMap.end(); iter++) { if(nullptr == iter.value() || iter.value()->lanItemLayout->count() <= 0) { continue; } iter.value()->updateNetSpeed(); } } int getPerfixLength(QString text) { int length = 0; QStringList list= text.split(":"); for (int i = 0; i < list.size(); ++i) { QString temp = list.at(i); if (temp.isEmpty()) { continue; } bool ok; unsigned int val = temp.toUInt(&ok, 16); temp = temp.setNum(val,2); for(int j = 0; j < temp.length(); ++j) { if (temp.at(j) == "1") { length++; } } } return length; } void NetConnect::getDetailConfInfo(QString devName, QString uuid, ConInfo &conInfo) { KyDetailInfo detailInfo; manager->getWiredConnectDetail(devName, uuid, detailInfo); conInfo.strMac = detailInfo.strMac; conInfo.strBandWidth = detailInfo.strBandWidth; conInfo.strDynamicIpv4 = detailInfo.strDynamicIpv4; conInfo.strDynamicIpv6 = detailInfo.strDynamicIpv6; conInfo.strDynamicIpv4Dns = detailInfo.strDynamicIpv4Dns; conInfo.isAutoConnect = detailInfo.isAutoConnect; KyConnectSetting connectSetting; manager->getConnectIpInfo(uuid, connectSetting); conInfo.strConName = connectSetting.m_connectName; conInfo.ipv4ConfigType = connectSetting.m_ipv4ConfigIpType; conInfo.ipv6ConfigType = connectSetting.m_ipv6ConfigIpType; if (connectSetting.m_ipv4ConfigIpType == CONFIG_IP_MANUAL) { if (connectSetting.m_ipv4Address.size() > 0) { conInfo.strIPV4Address = connectSetting.m_ipv4Address.at(0).ip().toString(); conInfo.strIPV4NetMask = connectSetting.m_ipv4Address.at(0).netmask().toString(); conInfo.strIPV4GateWay = connectSetting.m_ipv4Address.at(0).gateway().toString(); } if (connectSetting.m_ipv4Dns.size() == 1) { conInfo.strIPV4FirDns = connectSetting.m_ipv4Dns.at(0).toString(); } else if (connectSetting.m_ipv4Dns.size() > 1) { conInfo.strIPV4FirDns = connectSetting.m_ipv4Dns.at(0).toString(); conInfo.strIPV4SecDns = connectSetting.m_ipv4Dns.at(1).toString(); } } if (connectSetting.m_ipv6ConfigIpType == CONFIG_IP_MANUAL) { if (connectSetting.m_ipv6Address.size() > 0) { conInfo.strIPV6Address = connectSetting.m_ipv6Address.at(0).ip().toString(); conInfo.iIPV6Prefix = getPerfixLength(connectSetting.m_ipv6Address.at(0).netmask().toString()); conInfo.strIPV6GateWay = connectSetting.m_ipv6Address.at(0).gateway().toString(); } if (connectSetting.m_ipv6Dns.size() == 1) { conInfo.strIPV6FirDns = connectSetting.m_ipv6Dns.at(0).toString(); } else if (connectSetting.m_ipv6Dns.size() > 1) { conInfo.strIPV6FirDns = connectSetting.m_ipv6Dns.at(0).toString(); conInfo.strIPV6SecDns = connectSetting.m_ipv6Dns.at(1).toString(); } } if (conInfo.strDynamicIpv4.isEmpty() && conInfo.strDynamicIpv6.isEmpty() && conInfo.strDynamicIpv4Dns.isEmpty()) { conInfo.strDynamicIpv4 = conInfo.strIPV4Address.isEmpty() ? tr("Auto") : conInfo.strIPV4Address; conInfo.strDynamicIpv6 = conInfo.strIPV6Address.isEmpty() ? tr("Auto") : conInfo.strIPV6Address; conInfo.strDynamicIpv4Dns = conInfo.strIPV4FirDns.isEmpty() ? tr("Auto") : conInfo.strIPV4FirDns; } } void NetConnect::onUpdateSettings(QString devName, QString uuid) { NetDetail * netDetail = qobject_cast(sender()); KyConnectSetting connectSetting; manager->getConnectIpInfo(uuid, connectSetting); netDetail->updateConnect(connectSetting); Q_EMIT updateIpv4AndIpv6SettingInfo(uuid, connectSetting); QList connectItemList; manager->getActiveConnectionList(devName,CONNECT_TYPE_WIRED, connectItemList); bool isActived = false; for (int i = 0; i < connectItemList.size(); ++i) { if (connectItemList.at(i).m_uuid == uuid) { isActived = true; break; } } if (isActived) { usleep(10000); activeConnect(uuid, devName); } netDetail->close(); } void NetConnect::onShowDetailPage(QString devName, QString uuid) { if (m_netdtail != nullptr) { disconnect(m_netdtail); m_netdtail->close(); delete m_netdtail; m_netdtail = nullptr; } ConInfo info; getDetailConfInfo(devName, uuid, info); m_netdtail = new NetDetail(m_pluginType, devName, info.strConName, uuid, false, info, parentWidget); m_netdtail->show(); m_netdtail->raise(); connect(m_netdtail, &NetDetail::deleteConnect, this, &NetConnect::deleteConnect); connect(m_netdtail, &NetDetail::needUpdate, this, &NetConnect::onUpdateSettings); connect(m_netdtail, &NetDetail::detailPageClose, this, [&](QString devName, QString uuid) { disconnect(m_netdtail); delete m_netdtail; m_netdtail = nullptr; }); } void NetConnect::hideTitle() { // m_wiredSwitch->hide(); m_titleLabel->hide(); m_settingsLabel->hide(); } //===================== wired network swtich (neet systemdbus) bool NetConnect::getWiredMainSwitch() { qDebug() << Q_FUNC_INFO << __LINE__ ; if (m_pSysBusIntfs && m_pSysBusIntfs->isValid()) { qDebug() << Q_FUNC_INFO << __LINE__ ; QDBusReply reply = m_pSysBusIntfs->call("getWiredMainSwitch"); if (reply.isValid()) { bool status = reply.value(); qDebug() << Q_FUNC_INFO << status << __LINE__ ; return status; } else { qWarning () << "switch init dbus reply invalid"; return false; } } return false; } void NetConnect::onWiredMainSwitchSLot(bool checked) { if (!m_wiredSwitch->isCheckable()) { return; } if (m_pSysBusIntfs == nullptr || !m_pSysBusIntfs->isValid()) return; m_pSysBusIntfs->call(QStringLiteral("setWiredMainSwitch"), checked); } void NetConnect::onWiredMainSwitchChanged(bool state) { qDebug() << Q_FUNC_INFO << __LINE__ << state; setSwitchStatus(); } kylin-nm-plugin/plugins/netconnect/translations/0000775000175000017500000000000015167664423021112 5ustar fengfengkylin-nm-plugin/plugins/netconnect/translations/ug_CN.ts0000775000175000017500000001663415160520531022452 0ustar fengfeng DetailPage SSID: Protocol: BandWidth: IPV4: IPV4 Dns: IPV6: Mac: Ipv4Page Ipv4Config Address Netmask Default Gateway Prefs DNS Alternative DNS Auto(DHCP) Manual Ipv6Page Ipv6Config Address Subnet prefix Length Default Gateway Prefs DNS Alternative DNS Auto(DHCP) Manual LanItem Disconnect ئۈزۈۋېتىش Connect ئۇلىنىش NetConnect LAN سىملىق تور Settings تەسىس قىلىش Kylin NM kylin network applet desktop message Wired Device not carried No ethernet device avaliable Auto NetDetail Detail Ipv4 Ipv6 Confirm Cancel Forget this network kylin-nm-plugin/plugins/netconnect/translations/ky.ts0000775000175000017500000001721415160520531022075 0ustar fengfeng DetailPage SSID: Protocol: گەلىشىم : BandWidth: كەڭ قۇر: IPV4: IPV4 Dns: IPV6: Mac: فىزىكالىق ادىرەس: Ipv4Page Ipv4Config Address دايىن وردۇ Netmask بۅلۉمچۅ تور جاشىرىن نومۇرۇ Default Gateway العاچىنداعى تور ۅتكۅلۉ Prefs DNS Alternative DNS Auto(DHCP) اپتوماتتىك(DHCP) Manual قولدونمو Ipv6Page Ipv6Config Address دايىن وردۇ Subnet prefix Length بۅلۉمچۅ تور الدى قوشۇمچا ۇزۇندۇق Default Gateway العاچىنداعى تور ۅتكۅلۉ Prefs DNS Alternative DNS Auto(DHCP) اپتوماتتىك(DHCP) Manual قولدونمو LanItem Disconnect ۇلانۇۇسۇن ۉزۉپ اتۇۇ Connect ۇلانۇۇ NetConnect LAN Settings تور تەڭشەگى Kylin NM kylin network applet desktop message Wired Device not carried No ethernet device avaliable Auto اپتوماتتىك NetDetail Detail ىچكەلەي ، قۇنت قويۇپ مازمۇنۇ Ipv4 Ipv6 Confirm البەتتە. Cancel ارعادان قالتىرىش Forget this network بۇل توردۇ ۇنتۇپ ۇياتسىز. kylin-nm-plugin/plugins/netconnect/translations/zh_CN.ts0000775000175000017500000001617215160520531022455 0ustar fengfeng DetailPage SSID: SSID: Protocol: 协议: BandWidth: 带宽: IPV4: IPV4地址: IPV4 Dns: IPV4 DNS服务器: IPV6: IPV6地址: Mac: 物理地址: Ipv4Page Ipv4Config IPv4配置 Address 地址 Netmask 子网掩码 Default Gateway 默认网关 Prefs DNS 首选DNS Alternative DNS 备选DNS Auto(DHCP) 自动 Manual 手动 Ipv6Page Ipv6Config IPv6配置 Address 地址 Subnet prefix Length 子网前缀长度 Default Gateway 默认网关 Prefs DNS 首选DNS Alternative DNS 备选DNS Auto(DHCP) 自动 Manual 手动 LanItem Disconnect 断开连接 Connect 连接 NetConnect LAN 有线网络 Settings 网络设置 Kylin NM 网络设置工具 kylin network applet desktop message 网络提示消息 Wired Device not carried 未插入网线 No ethernet device avaliable 未检测到有线网卡 Auto 自动 NetDetail Detail 详情 Ipv4 IPv4 Ipv6 IPv6 Confirm 确认 Cancel 取消 Forget this network 忘记此网络 kylin-nm-plugin/plugins/netconnect/translations/kk.ts0000775000175000017500000001547415160520531022065 0ustar fengfeng DetailPage SSID: Protocol: كەلىسىم: BandWidth: كەڭ بەلدىك: IPV4: IPV4 Dns: IPV6: Mac: فيزيكالىق ٵدىرىس: Ipv4Page Ipv4Config Address ٵدىرىس Netmask تارماق تور جاسىرىن نومەرى Default Gateway وز قالپٸ تور وتكەلى Prefs DNS Alternative DNS Auto(DHCP) اۆتوماتتى(DHCP) Manual قولدانبا Ipv6Page Ipv6Config Address ٵدىرىس Subnet prefix Length تارماق تور الدى قوسىمشا ۇزىندىق Default Gateway وز قالپٸ تور وتكەلى Prefs DNS Alternative DNS Auto(DHCP) اۆتوماتتى(DHCP) Manual قولدانبا LanItem Disconnect ۇزارتىۋ Connect جالعانۋ NetConnect LAN Settings ورنالاسترعان ەتۋ Auto ماشينا NetDetail Detail ناقتىلاپ مازمۇنى Ipv4 Ipv6 Confirm تۇراقتاندىرۋ Cancel كۇشىنەن قالدىرۋ Forget this network نۇ توردى ۇمٸتٸلپ ۇياتسىز kylin-nm-plugin/plugins/netconnect/translations/tr.ts0000775000175000017500000001661315160520531022101 0ustar fengfeng DetailPage SSID: Protocol: BandWidth: IPV4: IPV4 Dns: IPV6: Mac: Ipv4Page Ipv4Config Address Netmask Default Gateway Prefs DNS Alternative DNS Auto(DHCP) Manual Ipv6Page Ipv6Config Address Subnet prefix Length Default Gateway Prefs DNS Alternative DNS Auto(DHCP) Manual LanItem Disconnect Connect NetConnect LAN Settings Kylin NM kylin network applet desktop message Wired Device not carried No ethernet device avaliable Auto NetDetail Detail Ipv4 Ipv6 Confirm Cancel Forget this network kylin-nm-plugin/plugins/netconnect/translations/bo.ts0000775000175000017500000001661315160520531022054 0ustar fengfeng DetailPage SSID: Protocol: BandWidth: IPV4: IPV4 Dns: IPV6: Mac: Ipv4Page Ipv4Config Address Netmask Default Gateway Prefs DNS Alternative DNS Auto(DHCP) Manual Ipv6Page Ipv6Config Address Subnet prefix Length Default Gateway Prefs DNS Alternative DNS Auto(DHCP) Manual LanItem Disconnect Connect NetConnect LAN Settings Kylin NM kylin network applet desktop message Wired Device not carried No ethernet device avaliable Auto NetDetail Detail Ipv4 Ipv6 Confirm Cancel Forget this network kylin-nm-plugin/plugins/netconnect/translations/ug.ts0000775000175000017500000001712515160520531022066 0ustar fengfeng DetailPage SSID: SSID: Protocol: كېلىشىم: BandWidth: كەڭ بەلۋاغ: IPV4: IPV4 ئادرېس IPV4 Dns: IPV4 DNS مۇلازىمېتىرى IPV6: IPV6 ئادرېس Mac: فىزىكىلىق ئادرېىس: Ipv4Page Ipv4Config IPv4 سەپلىمىسى Address ئادرىس Netmask تارماق تور يوشۇرۇن نومۇرى Default Gateway ئەسلىدىكى تور ئۆتكىلى Prefs DNS ئالدىن تاللاش DNS Alternative DNS زاپاس تاللاش DNS Auto(DHCP) ئاپتوماتىك(DHCP) Manual قوللانما Ipv6Page Ipv6Config IPv6 سەپلىمىسى Address ئادرىس Subnet prefix Length تارماق تور ئالدى قوشۇمچە ئۇزۇنلۇق Default Gateway ئەسلىدىكى تور ئۆتكىلى Prefs DNS ئالدىن تاللاش DNS Alternative DNS زاپاس تاللاش DNS Auto(DHCP) ئاپتوماتىك(DHCP) Manual قوللانما LanItem Disconnect ئۇلىنىش ئۈزۈلدى Connect ئۇلىنىش NetConnect LAN سىملىق تور Settings تەڭشەك Kylin NM kylin network applet desktop message Wired Device not carried No ethernet device avaliable Auto ماشىنا NetDetail Detail تەپسىلاتلار Ipv4 IPv4 Ipv6 IPv6 Confirm جەزملەش Cancel ئەمەلدىن قالدۇرۇش Forget this network بۇ تورنى ئۇنتۇپ قاپسىز kylin-nm-plugin/plugins/netconnect/translations/bo_CN.ts0000775000175000017500000002110015160520531022417 0ustar fengfeng DetailPage SSID: SSID: Protocol: གྲོས་མཐུན་འདི་ལྟ་ BandWidth: ཞེང་ཆེན་པོ་ཡོད་པ་ IPV4: IPV4ཡི་སྡོད་གནས། IPV4 Dns: IPV4DNSཞབས་ཞུའི་ཡོ་བྱད། IPV6: IPV6གི་སྡོད་གནས། Mac: དངོས་ལུགས་ཀྱི་ས་གནས་ནི། Ipv4Page Ipv4Config IPv4བཀོ་སྒྲིག་བྱེད་པ། Address ས་གནས། Netmask དྲ་བ་འགེབས་པ། Default Gateway དྲ་རྒྱའི་འགག་སྒོ་ཁས་ལེན་བྱེད་དགོས། Prefs DNS ཐོག་མར་DNSའདེམས་དགོས། Alternative DNS DNSའདེམས་བསྐོ་གྲ་སྒྲིག་བྱས་ཡོད། Auto(DHCP) རང་འགུལ་ཡིན་དགོས། Manual ལག་པ་འགུལ་དགོས། Ipv6Page Ipv6Config IPv6བཀོ་སྒྲིག་བྱས་ཡོད། Address ས་གནས། Subnet prefix Length དྲ་བའི་མདུན་缀་རིང་ཚད་ལ་སླེབས་ཡོད། Default Gateway དྲ་རྒྱའི་འགག་སྒོ་ཁས་ལེན་བྱེད་དགོས། Prefs DNS ཐོག་མར་DNSའདེམས་དགོས། Alternative DNS DNSའདེམས་བསྐོ་གྲ་སྒྲིག་བྱས་ཡོད། Auto(DHCP) རང་འགུལ་ཡིན་དགོས། Manual ལག་པ་འགུལ་དགོས། LanItem Disconnect འབྲེལ་མཐུད་བྱེད་མཚམས་ཆད་པ། Connect འབྲེལ་མཐུད་བཅས་བྱ་དགོས། NetConnect LAN སྐུད་ཡོད་དྲ་བ། Settings དྲ་རྒྱའི་སྒྲིག་བཀོད། Kylin NM kylin network applet desktop message Wired Device not carried No ethernet device avaliable Auto རང་འགུལ་ཡིན་དགོས། NetDetail Detail གནས་ཚུལ་ཞིབ་ཕྲ། Ipv4 IPv4 Ipv6 IPv6 Confirm དངོས་སུ་ཁས་ལེན་པ། Cancel མེད་པར་བཟོ་དགོས། Forget this network དྲ་རྒྱ་དེ་བརྗེད་པ་རེད། kylin-nm-plugin/plugins/netconnect/translations/mn.ts0000664000175000017500000002063615160520531022063 0ustar fengfeng DetailPage SSID: SSID: Protocol: ᠭᠡᠷ᠎ᠡ: BandWidth: ᠪᠦᠰᠡ ᠵᠢᠨ ᠦᠷᠭᠡᠨ: IPV4: IPV4 ᠬᠠᠶᠢᠭ IPV4 Dns: IPV4 DNS ᠦᠢᠯᠡᠴᠢᠯᠡᠭᠦᠷ ᠄ IPV6: IPV6 ᠬᠠᠶᠢᠭ Mac: ᠹᠢᠽᠢᠺ ᠤ᠋ᠨ ᠬᠠᠶᠢᠭ: Ipv4Page Ipv4Config IPv4 ᠲᠣᠬᠢᠷᠠᠭᠤᠯᠤᠯᠲᠠ ᠃ Address ᠬᠠᠶᠢᠭ Netmask ᠬᠤᠪᠢᠶᠠᠷᠢ ᠨᠧᠲ᠎ᠤᠨ ᠳᠠᠯᠳᠠᠯᠠᠯ ᠺᠤᠳ᠋ Default Gateway ᠠᠶᠠᠳᠠᠯ ᠨᠸᠲ ᠪᠤᠭᠤᠮᠳᠠ Prefs DNS ᠳᠡᠷᠢᠬᠦᠨ ᠰᠤᠩᠭᠤᠯᠳᠠ DNS Alternative DNS ᠪᠡᠯᠡᠳᠬᠡᠯ ᠰᠤᠩᠭᠤᠯᠳᠠ DNS Auto(DHCP) ᠠᠦ᠋ᠲ᠋ᠣ᠋ (DHCP) Manual ᠭᠠᠷ ᠵᠢᠡᠷ Ipv6Page Ipv6Config IPv6 ᠲᠣᠬᠢᠷᠠᠭᠤᠯᠤᠯᠲᠠ ᠃ Address ᠬᠠᠶᠢᠭ Subnet prefix Length ᠬᠤᠪᠢᠶᠠᠷᠢ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠤᠭᠳᠤᠪᠤᠷᠢ ᠵᠢᠨ ᠤᠷᠳᠤ Default Gateway ᠠᠶᠠᠳᠠᠯ ᠨᠸᠲ ᠪᠤᠭᠤᠮᠳᠠ Prefs DNS ᠳᠡᠷᠢᠬᠦᠨ ᠰᠤᠩᠭᠤᠯᠳᠠ DNS Alternative DNS ᠪᠡᠯᠡᠳᠬᠡᠯ ᠰᠤᠩᠭᠤᠯᠳᠠ DNS Auto(DHCP) ᠠᠦ᠋ᠲ᠋ᠣ᠋ (DHCP) Manual ᠭᠠᠷ ᠵᠢᠡᠷ LanItem Disconnect ᠴᠦᠷᠬᠡᠯᠡᠬᠡ ᠵᠢ ᠳᠠᠰᠤᠯᠬᠤ Connect ᠴᠦᠷᠬᠡᠯᠡᠬᠡ NetConnect LAN ᠤᠲᠠᠰᠤᠲᠤ ᠲᠣᠣᠷ ᠰᠦᠯᠵᠢᠶ᠎ᠡ Settings ᠲᠤᠬᠢᠷᠠᠭᠤᠯᠬᠤ Kylin NM ᠲᠣᠤᠷ ᠰᠦᠯᠵᠢᠶᠡᠨ ᠳᠡᠭᠡᠷ᠎ᠡ ᠪᠠᠭᠠᠵᠢ ᠲᠣᠬᠢᠷᠠᠭᠤᠯᠤᠨ᠎ᠠ ᠃ kylin network applet desktop message ᠰᠦᠯᠵᠢᠶᠡᠨ ᠦ ᠰᠠᠨᠠᠭᠤᠯᠤᠮᠵᠢ ᠶᠢᠨ ᠮᠡᠳᠡᠭᠡ ᠃ Wired Device not carried ᠰᠦᠯᠵᠢᠶᠡᠨ ᠤ᠋ ᠤᠳᠠᠰᠤ ᠵᠠᠯᠭᠠᠭ᠎ᠠ ᠦᠬᠡᠢ No ethernet device avaliable ᠤᠳᠠᠰᠤᠳᠤ ᠳᠦᠬᠦᠬᠡᠷᠦᠮᠵᠢ ᠵᠢ ᠪᠠᠢᠴᠠᠭᠠᠵᠤ ᠤᠯᠤᠭᠰᠠᠨ ᠦᠬᠡᠢ Auto ᠳᠠᠭᠠᠯᠲᠠ ᠰᠢᠰᠲ᠋ᠧᠮ NetDetail Detail ᠨᠠᠷᠢᠨ ᠪᠠᠢᠳᠠᠯ Ipv4 IPv4 Ipv6 IPv6 Confirm ᠲᠣᠭᠲᠠᠭᠠᠬᠤ Cancel ᠪᠣᠯᠢᠬᠤ Forget this network ᠲᠤᠰ ᠲᠤᠤᠷ ᠰᠦᠯᠵᠢᠶ᠎ᠡ ᠵᠢ ᠮᠠᠷᠳᠠᠬᠤ kylin-nm-plugin/plugins/netconnect/translations/zh_Hant.ts0000775000175000017500000001617115160520531023046 0ustar fengfeng DetailPage SSID: SSID: Protocol: 協定: BandWidth: 頻寬: IPV4: IPV4位址: IPV4 Dns: IPV4 DNS伺服器: IPV6: IPV6位址: Mac: 物理位址: Ipv4Page Ipv4Config IPv4配置 Address 位址 Netmask 子網掩碼 Default Gateway 默認閘道 Prefs DNS 首選DNS Alternative DNS 備選DNS Auto(DHCP) 自動 Manual 手動 Ipv6Page Ipv6Config IPv6配置 Address 位址 Subnet prefix Length 子網前綴長度 Default Gateway 默認閘道 Prefs DNS 首選DNS Alternative DNS 備選DNS Auto(DHCP) 自動 Manual 手動 LanItem Disconnect 斷開連接 Connect 連接 NetConnect LAN 有線網路 Settings 網路設置 Kylin NM kylin network applet desktop message Wired Device not carried No ethernet device avaliable Auto 自動 NetDetail Detail 詳情 Ipv4 IPv4 Ipv6 IPv6 Confirm 確認 Cancel 取消 Forget this network 忘記此網路 kylin-nm-plugin/plugins/netconnect/translations/zh_HK.ts0000775000175000017500000001617215160520531022457 0ustar fengfeng DetailPage SSID: SSID: Protocol: 協議: BandWidth: 帶寬: IPV4: IPV4地址: IPV4 Dns: IPV4 DNS服務器: IPV6: IPV6地址: Mac: 物理地址: Ipv4Page Ipv4Config IPv4配置 Address 地址 Netmask 子網掩碼 Default Gateway 默認網關 Prefs DNS 首選DNS Alternative DNS 備選DNS Auto(DHCP) 自動 Manual 手動 Ipv6Page Ipv6Config IPv6配置 Address 地址 Subnet prefix Length 子網前綴長度 Default Gateway 默認網關 Prefs DNS 首選DNS Alternative DNS 備選DNS Auto(DHCP) 自動 Manual 手動 LanItem Disconnect 斷開連接 Connect 連接 NetConnect LAN 有線網絡 Settings 網絡設置 Kylin NM 網路設置工具 kylin network applet desktop message 網路提示消息 Wired Device not carried 未插入網線 No ethernet device avaliable 未檢測到有線設備 Auto 自動 NetDetail Detail 詳情 Ipv4 IPv4 Ipv6 IPv6 Confirm 確認 Cancel 取消 Forget this network 忘記此網絡 kylin-nm-plugin/plugins/netconnect/itemframe.cpp0000664000175000017500000000706015160520531021031 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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" #define LAYOUT_MARGINS 4,0,12,0 #define MAIN_LAYOUT_MARGINS 0,0,0,0 ItemFrame::ItemFrame(QString devName, QWidget *parent) : m_deviceName(devName), QFrame(parent) { deviceLanLayout = new QVBoxLayout(this); deviceLanLayout->setContentsMargins(MAIN_LAYOUT_MARGINS); lanItemFrame = new QFrame(this); lanItemFrame->setFrameShape(QFrame::Shape::NoFrame); lanItemLayout = new QVBoxLayout(this); lanItemLayout->setContentsMargins(LAYOUT_MARGINS); lanItemLayout->setSpacing(0); deviceLanLayout->setSpacing(0); setLayout(deviceLanLayout); lanItemFrame->setLayout(lanItemLayout); deviceFrame = new DeviceFrame(devName, this); m_divider = new Divider(this); deviceLanLayout->addWidget(m_divider); deviceLanLayout->addWidget(deviceFrame); deviceLanLayout->addWidget(lanItemFrame); m_updateNetSpeedThread = new KyNetLoadRateThread(devName); } ItemFrame::~ItemFrame() { if (m_updateNetSpeedThread) { m_updateNetSpeedThread->quit(); m_updateNetSpeedThread->wait(); delete m_updateNetSpeedThread; m_updateNetSpeedThread = nullptr; } } void ItemFrame::startNetSpeedThread() { m_updateNetSpeedThread->start(); } void ItemFrame::stopNetSpeedThread() { if (m_updateNetSpeedThread->isRunning()) { m_updateNetSpeedThread->quit(); } } void ItemFrame::updateNetSpeed() { if (!m_updateNetSpeedThread->isRunning() || lanItemLayout->count() <= 0) { return; } long int rcvRate; long int txRate; LanItem *lanItem = nullptr; lanItem = (LanItem *)lanItemLayout->itemAt(0)->widget(); if (lanItem->getStatus()) { m_updateNetSpeedThread->getNetSpeed(rcvRate, txRate); setNetSpeed(rcvRate, txRate, lanItem); } } void ItemFrame::setNetSpeed(long rcvRate, long txRate, LanItem *lanItem) { if (!lanItem->getStatus()) { return; } int rcvNum = rcvRate; int txNum = txRate; QString strRcv = "0"; QString strTx = "0"; if (rcvNum < 1024) { strRcv = QString::number(rcvNum) + "KB/s"; } else { int remainder; if (rcvNum % 1024 < 100) { remainder = 0; } else { remainder = (rcvNum % 1024) / 100; } strRcv = QString::number(rcvNum / 1024) + "." + QString::number(remainder) + "MB/s"; } if (txNum < 1024) { strTx = QString::number(txNum) + "KB/s"; } else { int remainder; if (txNum % 1024 < 100) { remainder = 0; } else { remainder = (txNum % 1024)/100; } strTx = QString::number(txNum / 1024) + "." + QString::number(remainder) + "MB/s"; } lanItem->setNetSpeed(strRcv, strTx); } kylin-nm-plugin/plugins/netconnect/lanitem.h0000775000175000017500000000733115167660365020203 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 #include #include #include #include #include #include #include #include "../component/InfoButton/infobutton.h" #include "../component/RadioItemButton/radioitembutton.h" #include "../component/FixLabel/fixlabel.h" #include "../component/FixLabel/freqlabel.h" #define MAX_WIDTH_ACTIVATED 190 #define MAX_WIDTH_DEACTIVATED 326 class LanItem : public QFrame { Q_OBJECT public: LanItem(bool isSimple, QWidget *parent = nullptr); void setName(QString name) { titileLabel->setLabelText(name); } QString getName() { return titileLabel->getText(); } void setItemIcon(const QIcon &icon) { radioBtn->setButtonIcon(icon); } inline void updateNameLabel() { if (m_isAcitve) { titileLabel->setMaximumWidth(MAX_WIDTH_ACTIVATED); } else { titileLabel->setMaximumWidth(MAX_WIDTH_DEACTIVATED); } setName(titileLabel->getText()); } inline void setNetSpeedUiVisible(bool visible) { m_lbLoadUp->setVisible(visible); m_lbLoadDown->setVisible(visible); m_lbLoadDownImg->setVisible(visible); m_lbLoadUpImg->setVisible(visible); } void setStatus(bool isAcitve){ m_isAcitve = isAcitve; radioBtn->setActive(isAcitve); updateNameLabel(); setNetSpeedUiVisible(isAcitve); } bool getStatus(){ return m_isAcitve; } bool getIsLoading() { return m_loading; } QString getUuid(){ return m_uuid; } void setUuid(QString uuid){ m_uuid = uuid; } QString getPath(){ return m_dbusPath; } void setPath(QString dbusPath){ m_dbusPath = dbusPath; } void setNetSpeed(QString strRcv, QString strTx) { m_lbLoadDown->setText(strRcv); m_lbLoadUp->setText(strTx); } void startLoading(); void stopLoading(); Q_SIGNALS: void itemClick(); void infoButtonClick(QString); protected: void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); void enterEvent(QEnterEvent *event); void leaveEvent(QEvent *event); void paintEvent(QPaintEvent *event); private: QTimer *waitTimer = nullptr; QList loadIcons; int currentIconIndex=0; QMenu *m_menu = nullptr; RadioItemButton* radioBtn = nullptr; InfoButton * infoLabel = nullptr; FixLabel * titileLabel = nullptr; QLabel *m_lbLoadDown = nullptr; QLabel *m_lbLoadUp = nullptr; QLabel *m_lbLoadDownImg = nullptr; QLabel *m_lbLoadUpImg = nullptr; bool m_loading = false; bool m_isAcitve = false; bool isSimple; QString m_uuid; QString m_dbusPath; bool m_isIn = false; private Q_SLOTS: void updateIcon(); }; #endif // LANITEM_H kylin-nm-plugin/plugins/netconnect/resource.qrc0000664000175000017500000000022515160520531020706 0ustar fengfeng ../res/icon/load-down.png ../res/icon/load-up.png kylin-nm-plugin/plugins/netconnect/netdetails/0000775000175000017500000000000015167660365020526 5ustar fengfengkylin-nm-plugin/plugins/netconnect/netdetails/coninfo.h0000664000175000017500000002450315167660365022336 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 #include #include #include #include "depend/kylinconnectsetting.h" #define AUTO_CONFIG 0 #define MANUAL_CONFIG 1 enum PeapInnerType { MSCHAPV2_PEAP = 0, MD5_PEAP, GTC_PEAP, }; enum TtlsInnerType { PAP = 0, MSCHAP, MSCHAPV2_EAP, MSCHAPV2, CHAP, MD5_EAP, GTC_EAP }; class LineEdit : public QLineEdit { Q_OBJECT public: explicit LineEdit(QWidget *parent = nullptr) : QLineEdit(parent) {} ~LineEdit() {} protected: void contextMenuEvent(QContextMenuEvent *event) { QMenu *menu = createStandardContextMenu();//默认的标准右键菜单,如果不需要刻意完全自己实现 menu->setPalette(this->palette()); menu->exec(event->globalPos()); delete menu; } }; class ConInfo { public: QString strConName; QString strConType = "802-3-ethernet"; QString strMac; QString strBandWidth; QString strDynamicIpv4; QString strDynamicIpv6; QString strDynamicIpv4Dns; bool isAutoConnect = false; KyIpConfigType ipv4ConfigType = CONFIG_IP_DHCP; QString strIPV4Address; QString strIPV4NetMask; QString strIPV4FirDns; QString strIPV4SecDns; QString strIPV4GateWay; KyIpConfigType ipv6ConfigType = CONFIG_IP_DHCP; QString strIPV6Address; int iIPV6Prefix; QString strIPV6FirDns; QString strIPV6SecDns; QString strIPV6GateWay; }; static void setFramePalette(QFrame *widget, QPalette &pal) { QList lineEditList = widget->findChildren(); for (int i = 0; i < lineEditList.count(); ++i) { lineEditList.at(i)->setPalette(pal); lineEditList.at(i)->setContextMenuPolicy(Qt::DefaultContextMenu); } QList comboBoxList = widget->findChildren(); for (int i = 0; i < comboBoxList.count(); ++i) { comboBoxList.at(i)->setPalette(pal); if (comboBoxList.at(i)->view()) { comboBoxList.at(i)->view()->setPalette(pal); } } } static QPalette lightPalette(QWidget *widget) { auto palette = widget->palette(); //ukui-light palette UKUI3.1 QColor windowText_at(38, 38, 38), windowText_iat(38, 38, 38), windowText_dis(166, 166, 166), button_at(230, 230, 230), button_iat(230, 230, 230), button_dis(233, 233, 233), light_at(255, 255, 255), light_iat(255, 255, 255), light_dis(242, 242, 242), midlight_at(218, 218, 218), midlight_iat(218, 218, 218), midlight_dis(230, 230, 230), dark_at(77, 77, 77), dark_iat(77, 77, 77), dark_dis(64, 64, 64), mid_at(115, 115, 115), mid_iat(115, 115, 115), 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), buttonText_at(38, 38, 38), buttonText_iat(38, 38, 38), buttonText_dis(179, 179, 179), base_at(255, 255, 255), base_iat(245, 245, 245), base_dis(237, 237, 237), 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), 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), noRale_at(240, 240, 240), noRole_iat(240, 240, 240), noRole_dis(217, 217, 217), toolTipBase_at(255, 255, 255), toolTipBase_iat(255, 255, 255), toolTipBase_dis(255, 255, 255), 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); palette.setColor(QPalette::Active, QPalette::WindowText, windowText_at); palette.setColor(QPalette::Inactive, QPalette::WindowText, windowText_iat); palette.setColor(QPalette::Disabled, QPalette::WindowText, windowText_dis); palette.setColor(QPalette::Active, QPalette::Button, button_at); palette.setColor(QPalette::Inactive, QPalette::Button, button_iat); palette.setColor(QPalette::Disabled, QPalette::Button, button_dis); palette.setColor(QPalette::Active, QPalette::Light, light_at); palette.setColor(QPalette::Inactive, QPalette::Light, light_iat); palette.setColor(QPalette::Disabled, QPalette::Light, light_dis); palette.setColor(QPalette::Active, QPalette::Midlight, midlight_at); palette.setColor(QPalette::Inactive, QPalette::Midlight, midlight_iat); palette.setColor(QPalette::Disabled, QPalette::Midlight, midlight_dis); palette.setColor(QPalette::Active, QPalette::Dark, dark_at); palette.setColor(QPalette::Inactive, QPalette::Dark, dark_iat); palette.setColor(QPalette::Disabled, QPalette::Dark, dark_dis); palette.setColor(QPalette::Active, QPalette::Mid, mid_at); palette.setColor(QPalette::Inactive, QPalette::Mid, mid_iat); palette.setColor(QPalette::Disabled, QPalette::Mid, mid_dis); palette.setColor(QPalette::Active, QPalette::Text, text_at); palette.setColor(QPalette::Inactive, QPalette::Text, text_iat); palette.setColor(QPalette::Disabled, QPalette::Text, text_dis); palette.setColor(QPalette::Active, QPalette::BrightText, brightText_at); palette.setColor(QPalette::Inactive, QPalette::BrightText, brightText_iat); palette.setColor(QPalette::Disabled, QPalette::BrightText, brightText_dis); palette.setColor(QPalette::Active, QPalette::ButtonText, buttonText_at); palette.setColor(QPalette::Inactive, QPalette::ButtonText, buttonText_iat); palette.setColor(QPalette::Disabled, QPalette::ButtonText, buttonText_dis); palette.setColor(QPalette::Active, QPalette::Base, base_at); palette.setColor(QPalette::Inactive, QPalette::Base, base_iat); palette.setColor(QPalette::Disabled, QPalette::Base, base_dis); palette.setColor(QPalette::Active, QPalette::Window, window_at); palette.setColor(QPalette::Inactive, QPalette::Window, window_iat); palette.setColor(QPalette::Disabled, QPalette::Window, window_dis); palette.setColor(QPalette::Active, QPalette::Shadow, shadow_at); 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); palette.setColor(QPalette::Active, QPalette::NoRole, noRale_at); palette.setColor(QPalette::Inactive, QPalette::NoRole, noRole_iat); palette.setColor(QPalette::Disabled, QPalette::NoRole, noRole_dis); palette.setColor(QPalette::Active, QPalette::ToolTipBase, toolTipBase_at); palette.setColor(QPalette::Inactive, QPalette::ToolTipBase, toolTipBase_iat); palette.setColor(QPalette::Disabled, QPalette::ToolTipBase, toolTipBase_dis); palette.setColor(QPalette::Active, QPalette::ToolTipText, toolTipText_at); palette.setColor(QPalette::Inactive, QPalette::ToolTipText, toolTipText_iat); palette.setColor(QPalette::Disabled, QPalette::ToolTipText, toolTipText_dis); #if (QT_VERSION >= QT_VERSION_CHECK(5,12,0)) palette.setColor(QPalette::Active, QPalette::PlaceholderText, placeholderText_at); palette.setColor(QPalette::Inactive, QPalette::PlaceholderText, placeholderText_iat); palette.setColor(QPalette::Disabled, QPalette::PlaceholderText, placeholderText_dis); #endif return palette; } #endif // CONINFO_H kylin-nm-plugin/plugins/netconnect/netdetails/ipv4page.cpp0000775000175000017500000002252715167660365022764 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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" Ipv4Page::Ipv4Page(QWidget *parent):QFrame(parent) { initUI(); initComponent(); } void Ipv4Page::initUI() { ipv4ConfigCombox = new QComboBox(this); 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_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_detailLayout = new QFormLayout(this); m_detailLayout->addRow(m_configLabel,ipv4ConfigCombox); m_detailLayout->addRow(m_addressLabel,ipv4addressEdit); m_detailLayout->addRow(m_maskLabel,netMaskEdit); m_detailLayout->addRow(m_gateWayLabel,gateWayEdit); m_detailLayout->addRow(m_dnsLabel,firstDnsEdit); m_detailLayout->addRow(m_secDnsLabel,secondDnsEdit); ipv4ConfigCombox->addItem(tr("Auto(DHCP)")); //"自动(DHCP)" ipv4ConfigCombox->addItem(tr("Manual")); //"手动" // IP的正则格式限制 QRegularExpression 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"); ipv4addressEdit->setValidator(new QRegularExpressionValidator(rx, this)); gateWayEdit->setValidator(new QRegularExpressionValidator(rx, this)); netMaskEdit->setValidator(new QRegularExpressionValidator(rx, this)); firstDnsEdit->setValidator(new QRegularExpressionValidator(rx, this)); secondDnsEdit->setValidator(new QRegularExpressionValidator(rx, this)); } void Ipv4Page::initComponent() { if (ipv4ConfigCombox->currentIndex() == AUTO_CONFIG) { setLineEnabled(false); } else if (ipv4ConfigCombox->currentIndex() == MANUAL_CONFIG) { setLineEnabled(true); } connect(ipv4ConfigCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(configChanged(int))); connect(ipv4ConfigCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(setEnableOfSaveBtn())); connect(ipv4addressEdit, SIGNAL(textChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(netMaskEdit, SIGNAL(textChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(gateWayEdit, SIGNAL(textChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(firstDnsEdit, SIGNAL(textChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(secondDnsEdit, SIGNAL(textChanged(QString)), this, SLOT(setEnableOfSaveBtn())); } void Ipv4Page::setIpv4Config(KyIpConfigType ipv4Config) { if (ipv4Config == CONFIG_IP_MANUAL) { ipv4ConfigCombox->setCurrentIndex(MANUAL_CONFIG); } else { ipv4ConfigCombox->setCurrentIndex(AUTO_CONFIG); } } void Ipv4Page::setIpv4(const QString &ipv4) { ipv4addressEdit->setText(ipv4); } void Ipv4Page::setNetMask(const QString &netMask) { netMaskEdit->setText(netMask); } void Ipv4Page::setIpv4FirDns(const QString &ipv4FirDns) { firstDnsEdit->setText(ipv4FirDns); } void Ipv4Page::setIpv4SecDns(const QString &ipv4SecDns) { secondDnsEdit->setText(ipv4SecDns); } void Ipv4Page::setGateWay(const QString &gateWay) { gateWayEdit->setText(gateWay); } bool Ipv4Page::checkIsChanged(const ConInfo info) { bool isChanged = false; if (ipv4ConfigCombox->currentIndex() == AUTO_CONFIG) { if (info.ipv4ConfigType != CONFIG_IP_DHCP) { isChanged = true; } } else { if (info.ipv4ConfigType != CONFIG_IP_MANUAL) { isChanged = true; } if(info.strIPV4Address != ipv4addressEdit->text() || info.strIPV4NetMask != /*netMaskEdit->text()*/getNetMaskText(netMaskEdit->text()) || info.strIPV4GateWay != gateWayEdit->text() || info.strIPV4FirDns != firstDnsEdit->text() || info.strIPV4SecDns != secondDnsEdit->text()) { isChanged = true; } } return isChanged; } void Ipv4Page::updateSetting(KyConnectSetting &setting) { if (ipv4ConfigCombox->currentIndex() == AUTO_CONFIG) { setting.setIpConfigType(IPADDRESS_V4, CONFIG_IP_DHCP); QString ipv4address(""); QString netMask(""); QString gateWay(""); QStringList dnsList; dnsList.empty(); qDebug() << ipv4address << netMask << gateWay; setting.ipv4AddressConstruct(ipv4address, netMask, gateWay, dnsList); }else { setting.setIpConfigType(IPADDRESS_V4, CONFIG_IP_MANUAL); QStringList dnsList; dnsList.empty(); if (!firstDnsEdit->text().isEmpty()) { dnsList << firstDnsEdit->text(); if (!secondDnsEdit->text().isEmpty()) { dnsList << secondDnsEdit->text(); } } QString ipv4address =ipv4addressEdit->text(); QString netMask = getNetMaskText(netMaskEdit->text()); QString gateWay = gateWayEdit->text(); qDebug() << ipv4address << netMask << gateWay; setting.ipv4AddressConstruct(ipv4address, netMask, gateWay, dnsList); setting.dumpInfo(); } } bool Ipv4Page::checkConnectBtnIsEnabled() { qDebug() << "checkConnectBtnIsEnabled currentIndex" << ipv4ConfigCombox->currentIndex(); if (ipv4ConfigCombox->currentIndex() == AUTO_CONFIG) { return true; } else { if (ipv4addressEdit->text().isEmpty() || !getTextEditState(ipv4addressEdit->text())) { qDebug() << "ipv4address empty or invalid"; return false; } if (netMaskEdit->text().isEmpty() || !netMaskIsValide(netMaskEdit->text())) { qDebug() << "ipv4 netMask empty or invalid"; return false; } // if (gateWayEdit->text().isEmpty() || !getTextEditState(gateWayEdit->text())) { // qDebug() << "ipv4 gateway empty or invalid"; // return false; // } 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; } } return true; } void Ipv4Page::configChanged(int index) { if (index == AUTO_CONFIG) { setLineEnabled(false); } if (index == MANUAL_CONFIG) { setLineEnabled(true); } } void Ipv4Page::setLineEnabled(bool check) { ipv4addressEdit->setEnabled(check); netMaskEdit->setEnabled(check); gateWayEdit->setEnabled(check); firstDnsEdit->setEnabled(check); secondDnsEdit->setEnabled(check); if (!check) { ipv4addressEdit->clear(); netMaskEdit->clear(); gateWayEdit->clear(); firstDnsEdit->clear(); secondDnsEdit->clear(); } } void Ipv4Page::setEnableOfSaveBtn() { Q_EMIT setIpv4PageState(checkConnectBtnIsEnabled()); } bool Ipv4Page::getTextEditState(QString text) { if (text.isEmpty()) { return true; } // IP地址正则表达式,包含开始和结束锚点确保完全匹配 QRegularExpression rx("^(?:(?: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]?)$"); // 进行匹配并返回结果 QRegularExpressionMatch match = rx.match(text); return match.hasMatch(); } bool Ipv4Page::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 Ipv4Page::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]); } kylin-nm-plugin/plugins/netconnect/netdetails/ipv6page.h0000664000175000017500000000454715167660365022432 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 #include #include #include #include #include #include #include #include #include #include //#include "kylinconnectsetting.h" #include "coninfo.h" class Ipv6Page : public QFrame { Q_OBJECT public: Ipv6Page(QWidget *parent = nullptr); 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 setGateWay(const QString &gateWay); bool checkIsChanged(const ConInfo info); void updateSetting(KyConnectSetting &setting); int getPerfixLength(QString text); 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; private: void initUI(); void initComponent(); void setControlEnabled(bool check); bool getIpv6EditState(QString text); bool checkConnectBtnIsEnabled(); private Q_SLOTS: void configChanged(int index); void setEnableOfSaveBtn(); Q_SIGNALS: void setIpv6PageState(bool); }; #endif // IPV6PAGE_H kylin-nm-plugin/plugins/netconnect/netdetails/ipv6page.cpp0000775000175000017500000002566615167660365022775 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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" Ipv6Page::Ipv6Page(QWidget *parent):QFrame(parent) { initUI(); initComponent(); } void Ipv6Page::setIpv6Config(KyIpConfigType ipv6Config) { if (ipv6Config == CONFIG_IP_MANUAL) { ipv6ConfigCombox->setCurrentIndex(MANUAL_CONFIG); } else { ipv6ConfigCombox->setCurrentIndex(AUTO_CONFIG); } } void Ipv6Page::setIpv6(const QString &ipv6) { ipv6AddressEdit->setText(ipv6); } void Ipv6Page::setIpv6Perfix(const int &ipv6Perfix) { lengthEdit->setText(QString::number(ipv6Perfix)); } void Ipv6Page::setIpv6FirDns(const QString &ipv6FirDns) { firstDnsEdit->setText(ipv6FirDns); } void Ipv6Page::setIpv6SecDns(const QString &ipv6SecDns) { secondDnsEdit->setText(ipv6SecDns); } void Ipv6Page::setGateWay(const QString &gateWay) { gateWayEdit->setText(gateWay); } bool Ipv6Page::checkIsChanged(const ConInfo info) { bool isChanged = false; if (ipv6ConfigCombox->currentIndex() == AUTO_CONFIG) { if (info.ipv6ConfigType != CONFIG_IP_DHCP) { isChanged = true; } } else { if (info.ipv6ConfigType != CONFIG_IP_MANUAL) { isChanged = true; } if(info.strIPV6Address != ipv6AddressEdit->text() || info.iIPV6Prefix != lengthEdit->text().toInt() || info.strIPV6GateWay != gateWayEdit->text() || info.strIPV6FirDns != firstDnsEdit->text() || info.strIPV6SecDns != secondDnsEdit->text()) { isChanged = true; } } return isChanged; } void Ipv6Page::updateSetting(KyConnectSetting &setting) { if (ipv6ConfigCombox->currentIndex() == AUTO_CONFIG) { setting.setIpConfigType(IPADDRESS_V6, CONFIG_IP_DHCP); QString ipv6address(""); QString prefix(""); QString gateWay(""); QStringList dnsList; dnsList.empty(); setting.ipv6AddressConstruct(ipv6address, prefix, gateWay, dnsList); }else { setting.setIpConfigType(IPADDRESS_V6, CONFIG_IP_MANUAL); QStringList dnsList; dnsList.empty(); if (!firstDnsEdit->text().isEmpty()) { dnsList << firstDnsEdit->text(); if (!secondDnsEdit->text().isEmpty()) { dnsList << secondDnsEdit->text(); } } QString ipv6address =ipv6AddressEdit->text(); QString prefix = lengthEdit->text(); QString gateWay = gateWayEdit->text(); setting.ipv6AddressConstruct(ipv6address, prefix, gateWay, dnsList); setting.dumpInfo(); } } void Ipv6Page::initUI() { ipv6ConfigCombox = new QComboBox(this); 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_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_detailLayout = new QFormLayout(this); m_detailLayout->addRow(m_configLabel,ipv6ConfigCombox); m_detailLayout->addRow(m_addressLabel,ipv6AddressEdit); m_detailLayout->addRow(m_subnetLabel,lengthEdit); m_detailLayout->addRow(m_gateWayLabel,gateWayEdit); m_detailLayout->addRow(m_dnsLabel,firstDnsEdit); m_detailLayout->addRow(m_secDnsLabel,secondDnsEdit); ipv6ConfigCombox->addItem(tr("Auto(DHCP)")); //"自动(DHCP)" ipv6ConfigCombox->addItem(tr("Manual")); //"手动" QRegularExpression 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*$"); ipv6AddressEdit->setValidator(new QRegularExpressionValidator(ipv6_rx, this)); gateWayEdit->setValidator(new QRegularExpressionValidator(ipv6_rx, this)); firstDnsEdit->setValidator(new QRegularExpressionValidator(ipv6_rx, this)); secondDnsEdit->setValidator(new QRegularExpressionValidator(ipv6_rx, this)); QRegularExpression 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 QRegularExpressionValidator(prefix_rx,this)); } void Ipv6Page::initComponent() { if (ipv6ConfigCombox->currentIndex() == AUTO_CONFIG) { setControlEnabled(false); } else if (ipv6ConfigCombox->currentIndex() == MANUAL_CONFIG) { setControlEnabled(true); } connect(ipv6ConfigCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(configChanged(int))); connect(ipv6ConfigCombox, SIGNAL(currentIndexChanged(int)), this, SLOT(setEnableOfSaveBtn())); connect(ipv6AddressEdit, SIGNAL(textChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(lengthEdit, SIGNAL(textChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(gateWayEdit, SIGNAL(textChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(firstDnsEdit, SIGNAL(textChanged(QString)), this, SLOT(setEnableOfSaveBtn())); connect(secondDnsEdit, SIGNAL(textChanged(QString)), this, SLOT(setEnableOfSaveBtn())); } void Ipv6Page::configChanged(int index) { if (index == AUTO_CONFIG) { setControlEnabled(false); } if (index == MANUAL_CONFIG) { setControlEnabled(true); } } void Ipv6Page::setControlEnabled(bool check) { ipv6AddressEdit->setEnabled(check); lengthEdit->setEnabled(check); gateWayEdit->setEnabled(check); firstDnsEdit->setEnabled(check); secondDnsEdit->setEnabled(check); if (!check) { ipv6AddressEdit->clear(); lengthEdit->clear(); gateWayEdit->clear(); firstDnsEdit->clear(); secondDnsEdit->clear(); } } void Ipv6Page::setEnableOfSaveBtn() { Q_EMIT setIpv6PageState(checkConnectBtnIsEnabled()); } bool Ipv6Page::checkConnectBtnIsEnabled() { if (ipv6ConfigCombox->currentIndex() == AUTO_CONFIG) { return true; } else { if (ipv6AddressEdit->text().isEmpty() || !getIpv6EditState(ipv6AddressEdit->text())) { qDebug() << "ipv6address empty or invalid"; return false; } if (lengthEdit->text().isEmpty()) { qDebug() << "ipv6 prefix length empty"; return false; } if (gateWayEdit->text().isEmpty() || !getIpv6EditState(gateWayEdit->text())) { qDebug() << "ipv6 gateway empty or invalid"; return false; } 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; } } return true; } bool Ipv6Page::getIpv6EditState(QString text) { if (text.isEmpty()) { return true; } QRegularExpression 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*$"); // 进行匹配并返回结果 QRegularExpressionMatch match = rx.match(text); return match.hasMatch(); } int Ipv6Page::getPerfixLength(QString text) { qDebug() << "getPerfixLength" << text; int length = 0; QStringList list= text.split(":"); for (int i = 0; i < list.size(); ++i) { QString temp = list.at(i); if (temp.isEmpty()) { continue; } bool ok; unsigned int val = temp.toUInt(&ok, 16); temp = temp.setNum(val,2); for(int j = 0; j < temp.length(); ++j) { if (temp.at(j) == "1") { length++; } } } qDebug() << "getPerfixLength" << length; return length; } kylin-nm-plugin/plugins/netconnect/netdetails/detailwidget.h0000664000175000017500000000260315167660365023346 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 #include "../component/FixLabel/fixlabel.h" class DetailWidget : public QWidget { Q_OBJECT public: explicit DetailWidget(QWidget *valueWidget = nullptr, QWidget *parent = nullptr); ~DetailWidget(); void setKey(const QString &keyLabel); private: QHBoxLayout * m_mainLayout = nullptr; FixLabel * m_keyLabel = nullptr; QWidget * m_valueWidget = nullptr; void initUI(); }; #endif // DetailWidget_H kylin-nm-plugin/plugins/netconnect/netdetails/customtabstyle.cpp0000664000175000017500000001016215167660365024314 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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" CustomTabStyle::CustomTabStyle() { } QSize CustomTabStyle::sizeFromContents(QStyle::ContentsType type, const QStyleOption *option, const QSize &size, const QWidget *widget) const { QSize s = QProxyStyle::sizeFromContents(type, option, size, widget); if (type == QStyle::CT_TabBarTab) { s.transpose(); s.rwidth() = 60; // 设置每个tabBar中item的大小 s.rheight() = 36; } return s; } void CustomTabStyle::drawControl(QStyle::ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const { if (element == CE_TabBarTab) { if (const QStyleOptionTab *tab = qstyleoption_cast(option)) { QRect allRect = tab->rect; if (tab->state & QStyle::State_Selected) { //选中状态:tab的Qlabel为矩形,底色为白色,边框淡灰色,文字为淡蓝色且加粗居中(具体颜色值由拾色器提取) painter->save(); painter->setPen(0x3790FA); //设置画笔颜色为淡灰色 painter->setBrush(QBrush(0x3790FA)); //设置画刷为白色 painter->drawRoundedRect(allRect.adjusted(0,0,0,0),6,6); //重绘tab的矩形边框 painter->restore(); //还原为默认 painter->save(); painter->setPen(0xffffff); //重新设置画笔颜色为淡蓝色 QTextOption option; option.setAlignment(Qt::AlignCenter); //设置文字居中 painter->drawText(allRect, tab->text, option); //重绘文字 painter->restore(); } else if(tab->state & QStyle::State_MouseOver) { //hover状态:tab的Qlabel为矩形,底色为灰色,边框仍未淡灰色,文字加粗居中 painter->save(); painter->setPen(tab->palette.color(QPalette::Window)); //设置画笔颜色为淡灰色 painter->setBrush(tab->palette.color(QPalette::Window)); //设置画刷为灰色 painter->drawRoundedRect(allRect.adjusted(0,0,0,0),6,6); //重绘tab的矩形边框 painter->restore(); //还原 painter->save(); QTextOption option; option.setAlignment(Qt::AlignCenter); //设置文字居中 painter->drawText(allRect, tab->text, option); //重绘文字 painter->restore(); } else //其它的:tab的Qlabel为矩形,底色为灰色,边框为淡灰色不变,文字不加粗但居中 { painter->save(); painter->setPen(tab->palette.color(QPalette::Button)); painter->setBrush(tab->palette.color(QPalette::Button)); painter->drawRoundedRect(allRect.adjusted(0,0,0,0),6,6); //重绘tab的矩形边框 painter->restore(); painter->save(); QTextOption option; option.setAlignment(Qt::AlignCenter); painter->drawText(allRect, tab->text, option); painter->restore(); } return; } } if (element == CE_TabBarTab) { QProxyStyle::drawControl(element, option, painter, widget); } } kylin-nm-plugin/plugins/netconnect/netdetails/detailpage.h0000664000175000017500000000475415167660365023010 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 #include #include #include #include #include #include #include #include #include "detailwidget.h" #include "coninfo.h" class DetailPage : public QFrame { Q_OBJECT public: DetailPage(bool isPppoe, QWidget *parent = nullptr); void setSSID(const QString &ssid); void setProtocol(const QString &protocol); void setSecType(const QString &secType); void setHz(const QString &hz); void setChan(const QString &chan); void setBandWidth(const QString &brandWidth); void setIpv4(const QString &ipv4); void setIpv4Dns(const QString &ipv4Dns); void setIpv6(const QString &ipv6); void setMac(const QString &mac); private: void initUI(); void addDetailItem(QListWidget *listWidget, DetailWidget *detailWidget); public: QListWidget * m_listWidget = nullptr; DetailWidget * m_ssidWidget = nullptr; DetailWidget * m_protocolWidget = nullptr; DetailWidget * m_bandwidthWidget = nullptr; DetailWidget * m_ipv4Widget = nullptr; DetailWidget * m_ipv4DnsWidget = nullptr; DetailWidget * m_ipv6Widget = nullptr; DetailWidget * m_macWidget = nullptr; LineEdit *mSSIDEdit; FixLabel *mSSIDLabel; QLabel *mProtocol; QLabel *mBandWidth; QLabel *mIPV4; QLabel *mIPV4Dns; FixLabel *mIPV6; QLabel *mMac; private: QVBoxLayout *layout; QVBoxLayout *mDetailLayout; bool m_isPppoe; private Q_SLOTS: void setEnableOfSaveBtn(); Q_SIGNALS: void setDetailPageState(bool); }; #endif // DETAILPAGE_H kylin-nm-plugin/plugins/netconnect/netdetails/detailwidget.cpp0000664000175000017500000000342115167660365023700 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 DetailWidget::DetailWidget(QWidget *valueWidget, QWidget *parent) : m_valueWidget(valueWidget) , QWidget(parent) { // m_valueWidget = valueWidget; initUI(); } DetailWidget::~DetailWidget() { } void DetailWidget::initUI() { this->setFixedHeight(ITEM_HEIGHT); m_mainLayout = new QHBoxLayout(this); m_mainLayout->setContentsMargins(ITEM_MARGINS); m_keyLabel = new FixLabel(this); m_keyLabel->setMaximumWidth(MAX_LABEL_WIDTH); m_keyLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); m_mainLayout->addWidget(m_keyLabel); m_mainLayout->addStretch(); m_mainLayout->addWidget(m_valueWidget); // m_valueWidget->setMaximumWidth(100000000000); } void DetailWidget::setKey(const QString &keyLabel) { m_keyLabel->setText(keyLabel); } kylin-nm-plugin/plugins/netconnect/netdetails/netdetail.cpp0000775000175000017500000002572615167660365023222 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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" #define THEME_SCHAME "org.ukui.style" #define COLOR_THEME "styleName" #include #include #define WINDOW_WIDTH 520 #define WINDOW_HEIGHT 590 #define BUTTON_SIZE 30 #define ICON_SIZE 22,22 #define TITLE_LAYOUT_MARGINS 9,9,0,0 #define 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 PAGE_MIN_HEIGHT 40 #define LAN_TAB_WIDTH 300 #define WLAN_TAB_WIDTH 400 void NetDetail::setNetdetailSomeEnable(bool on) { detailPage->setEnabled(on); ipv4Page->setEnabled(on); if (!m_isPppoe) { ipv6Page->setEnabled(on); } cancelBtn->setEnabled(on); forgetBtn->setEnabled(on); confimBtn->setEnabled(on); } NetDetail::NetDetail(PluginType type, QString interface, QString name, QString uuid, bool isPppoe, ConInfo info, QWidget *parent) :m_pluginType(type), m_deviceName(interface), m_name(name), m_uuid(uuid), m_isPppoe(isPppoe), m_info(info), QWidget(parent) { // setAttribute(Qt::WA_DeleteOnClose); setFixedSize(WINDOW_WIDTH,WINDOW_HEIGHT); centerToScreen(); initUI(); loadPage(); initComponent(); pagePadding(); connect(qApp, &QApplication::paletteChanged, this, &NetDetail::onPaletteChanged); isIpv4Ok = true; isIpv6Ok = true; qDebug() << interface << name << uuid; setConfirmEnable(); } void NetDetail::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(detailPage, pal); setFramePalette(ipv4Page, pal); if (!m_isPppoe) { setFramePalette(ipv6Page, 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()); detailPage->m_listWidget->setAlternatingRowColors(true); detailPage->m_listWidget->setPalette(listwidget_pal); if (styleGsettings != nullptr) { delete styleGsettings; styleGsettings = nullptr; } } void NetDetail::currentRowChangeSlot(int row) { stackWidget->setCurrentIndex(row); } void NetDetail::paintEvent(QPaintEvent *event) { QPalette pal = qApp->palette(); QColor colorPal = pal.color(QPalette::Window); //设置窗体为圆角 QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); // 反锯齿; painter.setBrush(colorPal); painter.setPen(Qt::transparent); auto rect = this->rect(); painter.drawRoundedRect(rect, 12, 12); //窗口圆角 return QWidget::paintEvent(event); } void NetDetail::closeEvent(QCloseEvent *event) { Q_EMIT this->detailPageClose(m_deviceName, m_uuid); return QWidget::closeEvent(event); } void NetDetail::centerToScreen() { QRect desk_rect; QScreen *currentScreen = QGuiApplication::screenAt(QCursor::pos()); if (currentScreen) { desk_rect = currentScreen->geometry(); } else { desk_rect=QGuiApplication::primaryScreen()->geometry(); } int desk_x = desk_rect.width(); int desk_y = desk_rect.height(); int x = this->width(); int y = this->height(); if (m_pluginType == OOBE){ //减去插件的宽度 this->move(desk_x / 2 - x / 2 + desk_rect.left() - 225, desk_y / 2 - y / 2 + desk_rect.top()); }else{ this->move(desk_x / 2 - x / 2 + desk_rect.left(), desk_y / 2 - y / 2 + desk_rect.top()); } } void NetDetail::initUI() { QVBoxLayout *mainLayout = new QVBoxLayout(this); mainLayout->setContentsMargins(9,9,14,24); detailPage = new DetailPage(m_isPppoe, this); ipv4Page = new Ipv4Page(this); if (!m_isPppoe) { ipv6Page = new Ipv6Page(this); } this->installEventFilter(this); centerWidget = new QWidget(this); bottomWidget = new QWidget(this); stackWidget = new QStackedWidget(centerWidget); stackWidget->addWidget(detailPage); stackWidget->addWidget(ipv4Page); if (!m_isPppoe) { stackWidget->addWidget(ipv6Page); } 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); onPaletteChanged(); // TabBar m_netTabBar = new KTabBar(KTabBarStyle::SegmentDark, this); m_netTabBar->addTab(tr("Detail")); //详情 m_netTabBar->addTab(tr("Ipv4"));//Ipv4 if (!m_isPppoe) { m_netTabBar->addTab(tr("Ipv6"));//Ipv6 } 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))); confimBtn = new QPushButton(this); confimBtn->setText(tr("Confirm")); cancelBtn = new QPushButton(this); cancelBtn->setText(tr("Cancel")); forgetBtn = new QPushButton(this); forgetBtn->setText(tr("Forget this network")); if (m_pluginType == OOBE){ forgetBtn->setStyleSheet("background-color: #3790FA;"); cancelBtn->setStyleSheet("background-color: #3790FA;"); confimBtn->setStyleSheet("background-color: #3790FA;"); } this->setWindowIcon(QIcon::fromTheme("kylin-network")); QVBoxLayout *centerlayout = new QVBoxLayout(centerWidget); centerlayout->setContentsMargins(LAYOUT_MARGINS); centerlayout->addWidget(pageFrame); centerlayout->addWidget(stackWidget); QHBoxLayout *bottomLayout = new QHBoxLayout(bottomWidget); bottomLayout->setContentsMargins(LAYOUT_MARGINS); bottomLayout->setSpacing(BOTTOM_LAYOUT_SPACING); bottomLayout->addWidget(forgetBtn); bottomLayout->addStretch(); bottomLayout->addWidget(cancelBtn); bottomLayout->addWidget(confimBtn); this->setAutoFillBackground(true); onPaletteChanged(); } void NetDetail::loadPage() { stackWidget->setCurrentIndex(DETAIL_PAGE_NUM); this->setWindowTitle(m_name); } void NetDetail::initComponent() { connect(cancelBtn, &QPushButton::clicked, this, [=] { close(); }); connect(confimBtn, SIGNAL(clicked()), this, SLOT(on_btnConfirm_clicked())); connect(forgetBtn, SIGNAL(clicked()), this, SLOT(on_btnForget_clicked())); connect(ipv4Page, &Ipv4Page::setIpv4PageState, this, [=](bool status) { isIpv4Ok = status; setConfirmEnable(); }); if (!m_isPppoe) { connect(ipv6Page, &Ipv6Page::setIpv6PageState, this, [=](bool status) { isIpv6Ok = status; setConfirmEnable(); }); } } void NetDetail::pagePadding() { //网络详情页填充 detailPage->setSSID(m_name); detailPage->setProtocol(m_info.strConType); detailPage->setIpv4(m_info.strDynamicIpv4); detailPage->setIpv4Dns(m_info.strDynamicIpv4Dns); if (!m_isPppoe) { detailPage->setIpv6(m_info.strDynamicIpv6); } detailPage->setMac(m_info.strMac); detailPage->setBandWidth(m_info.strBandWidth); //ipv4页面填充 if (m_info.ipv4ConfigType == CONFIG_IP_MANUAL) { ipv4Page->setIpv4Config(m_info.ipv4ConfigType); ipv4Page->setIpv4(m_info.strIPV4Address); ipv4Page->setNetMask(m_info.strIPV4NetMask); ipv4Page->setIpv4FirDns(m_info.strIPV4FirDns); ipv4Page->setIpv4SecDns(m_info.strIPV4SecDns); ipv4Page->setGateWay(m_info.strIPV4GateWay); } else { ipv4Page->setIpv4Config(m_info.ipv4ConfigType); } if (!m_isPppoe) { //ipv6页面填充 if (m_info.ipv6ConfigType == CONFIG_IP_MANUAL) { ipv6Page->setIpv6Config(m_info.ipv6ConfigType); ipv6Page->setIpv6(m_info.strIPV6Address); ipv6Page->setIpv6Perfix(m_info.iIPV6Prefix); ipv6Page->setIpv6FirDns(m_info.strIPV6FirDns); ipv6Page->setIpv6SecDns(m_info.strIPV6SecDns); ipv6Page->setGateWay(m_info.strIPV6GateWay); } else { ipv6Page->setIpv6Config(m_info.ipv6ConfigType); } } } //点击了保存更改网络设置的按钮 void NetDetail::on_btnConfirm_clicked() { setNetdetailSomeEnable(false); checkNeedUpdate(); } //点击忘记网络 void NetDetail::on_btnForget_clicked() { qDebug() << "user choose forget connection uuid = " << m_uuid; Q_EMIT deleteConnect(m_uuid); close(); } void NetDetail::setConfirmEnable() { if (isIpv4Ok && isIpv6Ok) { isConfirmBtnEnable = true; } else { isConfirmBtnEnable = false; } qDebug() << "setConfirmEnable "<< isConfirmBtnEnable; confimBtn->setEnabled(isConfirmBtnEnable); } void NetDetail::checkNeedUpdate() { bool ipv4Change = ipv4Page->checkIsChanged(m_info); bool ipv6Change = false; if (!m_isPppoe) { ipv6Change = ipv6Page->checkIsChanged(m_info); } if (ipv4Change || ipv6Change) { Q_EMIT needUpdate(m_deviceName, m_uuid); } else { close(); } } void NetDetail::updateConnect(KyConnectSetting &connetSetting) { ipv4Page->updateSetting(connetSetting); ipv6Page->updateSetting(connetSetting); } bool NetDetail::eventFilter(QObject *w, QEvent *event) { // 回车键触发确定按钮点击事件 if (event->type() == QEvent::KeyPress) { QKeyEvent *mEvent = static_cast(event); if (mEvent->key() == Qt::Key_Enter || mEvent->key() == Qt::Key_Return) { if (confimBtn->isEnabled()) { Q_EMIT confimBtn->clicked(); } return true; } else if (mEvent->key() == Qt::Key_Escape) { close(); return true; } } return QWidget::eventFilter(w, event); } kylin-nm-plugin/plugins/netconnect/netdetails/customtabstyle.h0000664000175000017500000000256515167660365023771 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 #include #include #include #include #include class CustomTabStyle : public QProxyStyle { public: CustomTabStyle(); QSize sizeFromContents(ContentsType type, const QStyleOption *option, const QSize &size, const QWidget *widget) const; void drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const; }; #endif // CUSTOMTABSTYLE_H kylin-nm-plugin/plugins/netconnect/netdetails/detailpage.cpp0000664000175000017500000001221415167660365023331 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 extern void qt_blurImage(QImage &blurImage, qreal radius, bool quality, int transposed); DetailPage::DetailPage(bool isPppoee, QWidget *parent) : m_isPppoe(isPppoee), QFrame(parent) { this->setFrameShape(QFrame::Shape::StyledPanel); this->setMaximumWidth(960); initUI(); } void DetailPage::setSSID(const QString &ssid) { this->mSSIDLabel->setText(ssid); } void DetailPage::setProtocol(const QString &protocol) { this->mProtocol->setText(protocol); } void DetailPage::setBandWidth(const QString &brandWidth) { this->mBandWidth->setText(brandWidth); } void DetailPage::setIpv4(const QString &ipv4) { this->mIPV4->setText(ipv4); } void DetailPage::setIpv4Dns(const QString &ipv4Dns) { this->mIPV4Dns->setText(ipv4Dns); } void DetailPage::setIpv6(const QString &ipv6) { this->mIPV6->setText(ipv6); } void DetailPage::setMac(const QString &mac) { this->mMac->setText(mac); } void DetailPage::addDetailItem(QListWidget *listWidget, DetailWidget *detailWidget) { QListWidgetItem *listWidgetItem = new QListWidgetItem(listWidget); listWidgetItem->setSizeHint(QSize(listWidget->width(),36)); listWidgetItem->setFlags(Qt::NoItemFlags); listWidget->addItem(listWidgetItem); listWidget->setItemWidget(listWidgetItem, detailWidget); } void DetailPage::initUI() { layout = new QVBoxLayout(this); layout->setContentsMargins(0,0,0,0); QWidget *mDetailFrame = new QFrame(this); mDetailLayout = new QVBoxLayout(mDetailFrame); mDetailLayout->setContentsMargins(0,0,0,0); m_listWidget = new QListWidget(mDetailFrame); m_listWidget->setFrameShape(QFrame::Shape::NoFrame); m_listWidget->setBackgroundRole(QPalette::Base); m_listWidget->setFocusPolicy(Qt::FocusPolicy::NoFocus); mDetailLayout->addWidget(m_listWidget); mSSIDLabel = new FixLabel(this); mSSIDLabel->setFixedWidth(MAX_LABEL_WIDTH); mSSIDLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); m_ssidWidget = new DetailWidget(qobject_cast(mSSIDLabel), m_listWidget); // mSSID->setStyleSheet("background:transparent;border-width:0px;border-style:none"); // mSSID->setFocusPolicy(Qt::NoFocus); m_ssidWidget->setKey(tr("SSID:")); mProtocol = new QLabel(this); m_protocolWidget = new DetailWidget(qobject_cast(mProtocol), m_listWidget); m_protocolWidget->setKey(tr("Protocol:")); mBandWidth = new QLabel(this); m_bandwidthWidget = new DetailWidget(qobject_cast(mBandWidth), m_listWidget); m_bandwidthWidget->setKey(tr("BandWidth:")); mIPV4 = new QLabel(this); m_ipv4Widget = new DetailWidget(qobject_cast(mIPV4), m_listWidget); m_ipv4Widget->setKey(tr("IPV4:")); mIPV4Dns = new QLabel(this); m_ipv4DnsWidget = new DetailWidget(qobject_cast(mIPV4Dns), m_listWidget); m_ipv4DnsWidget->setKey(tr("IPV4 Dns:")); if (!m_isPppoe) { mIPV6 = new FixLabel(this); mIPV6->setFixedWidth(MAX_LABEL_WIDTH); mIPV6->setAlignment(Qt::AlignRight | Qt::AlignVCenter); m_ipv6Widget = new DetailWidget(qobject_cast(mIPV6), m_listWidget); m_ipv6Widget->setKey(tr("IPV6:")); } mMac = new QLabel(this); m_macWidget = new DetailWidget(qobject_cast(mMac), m_listWidget); m_macWidget->setKey(tr("Mac:")); this->addDetailItem(m_listWidget, m_ssidWidget); this->addDetailItem(m_listWidget, m_protocolWidget); this->addDetailItem(m_listWidget, m_bandwidthWidget); if (!m_isPppoe) { this->addDetailItem(m_listWidget, m_ipv6Widget); } this->addDetailItem(m_listWidget, m_ipv4Widget); this->addDetailItem(m_listWidget, m_ipv4DnsWidget); this->addDetailItem(m_listWidget, m_macWidget); QPalette mpal(m_listWidget->palette()); mpal.setColor(QPalette::Base, qApp->palette().base().color()); mpal.setColor(QPalette::AlternateBase, qApp->palette().alternateBase().color()); m_listWidget->setAlternatingRowColors(true); // m_listWidget->setAutoFillBackground(true); m_listWidget->setPalette(mpal); layout->addWidget(mDetailFrame); } void DetailPage::setEnableOfSaveBtn() { bool saveEnable = true; Q_EMIT setDetailPageState(saveEnable); } kylin-nm-plugin/plugins/netconnect/netdetails/netdetails.pri0000664000175000017500000000060115160520531023352 0ustar fengfengINCLUDEPATH += $$PWD HEADERS += \ $$PWD/coninfo.h \ $$PWD/customtabstyle.h \ $$PWD/detailpage.h \ $$PWD/detailwidget.h \ $$PWD/ipv4page.h \ $$PWD/ipv6page.h \ $$PWD/netdetail.h \ SOURCES += \ $$PWD/customtabstyle.cpp \ $$PWD/detailpage.cpp \ $$PWD/detailwidget.cpp \ $$PWD/ipv4page.cpp \ $$PWD/ipv6page.cpp \ $$PWD/netdetail.cpp \ kylin-nm-plugin/plugins/netconnect/netdetails/ipv4page.h0000664000175000017500000000467515167660365022432 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 #include #include #include #include #include #include #include #include #include #include //#include "kylinconnectsetting.h" #include "coninfo.h" class Ipv4Page : public QFrame { Q_OBJECT public: Ipv4Page(QWidget *parent = nullptr); 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 setGateWay(const QString &gateWay); bool checkIsChanged(const ConInfo info); void updateSetting(KyConnectSetting &setting); 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; private: void initUI(); void initComponent(); void setLineEnabled(bool check); void configSave(); bool getTextEditState(QString text); bool netMaskIsValide(QString text); QString getNetMaskText(QString text); bool checkConnectBtnIsEnabled(); private Q_SLOTS: void setEnableOfSaveBtn(); void configChanged(int index); Q_SIGNALS: void setIpv4PageState(bool); }; #endif // IPV4PAGE_H kylin-nm-plugin/plugins/netconnect/netdetails/netdetail.h0000775000175000017500000000615615167660365022663 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "detailpage.h" #include "ipv4page.h" #include "ipv6page.h" #include "coninfo.h" #include "kwidget.h" #include "ktabbar.h" using namespace kdk; class NetDetail : public QWidget { Q_OBJECT public: NetDetail(PluginType type, QString interface, QString name, QString uuid, bool isPppoe, ConInfo info, QWidget *parent = nullptr); void updateConnect(KyConnectSetting &connetSetting); QString getInterface() { return m_deviceName; } protected: void paintEvent(QPaintEvent *event); void closeEvent(QCloseEvent *event); bool eventFilter(QObject *w, QEvent *event); private: void initUI(); void centerToScreen(); void initComponent(); void loadPage(); void pagePadding(); void setConfirmEnable(); void setNetdetailSomeEnable(bool on); void checkNeedUpdate(); private: QStackedWidget * stackWidget; DetailPage * detailPage; Ipv4Page * ipv4Page; Ipv6Page * ipv6Page; QWidget * centerWidget; QWidget * bottomWidget; QPushButton * cancelBtn; QPushButton * forgetBtn; QPushButton * confimBtn; QFrame * pageFrame; KTabBar *m_netTabBar = nullptr; QString m_name; QString m_uuid; QString m_deviceName; PluginType m_pluginType; bool m_isPppoe; bool isIpv4Ok; bool isIpv6Ok; bool isConfirmBtnEnable; ConInfo m_info; private Q_SLOTS: void on_btnConfirm_clicked(); void on_btnForget_clicked(); void onPaletteChanged(); protected Q_SLOTS: void currentRowChangeSlot(int row); Q_SIGNALS: void detailPageClose(QString, QString); void currentChanged(int); void deleteConnect(QString); void needUpdate(QString, QString); }; #endif // NETDETAIL_H kylin-nm-plugin/plugins/netconnect/translate_generation.sh0000775000175000017500000000232415167660365023142 0ustar fengfeng#!/bin/bash # -*- Mode: Shell-script; tab-width: 4; indent-tabs-mode: nil; sh-basic-offset: 4 -*- # # Copyright (C) 2019 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. # export PATH="/usr/lib/qt6/bin:$PATH" 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 kylin-nm-plugin/plugins/netconnect/netconnect.h0000775000175000017500000001445415160520531020675 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 NETCONNECT_H #define NETCONNECT_H #include "kswitchbutton.h" #include "kborderlessbutton.h" using namespace kdk; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "lanitem.h" #include "../component/DeviceFrame/deviceframe.h" #include "itemframe.h" #include "../component/Divider/divider.h" #include "netdetail.h" enum { DISCONNECTED, NOINTERNET, CONNECTED }; class NetConnect : public Interface { Q_OBJECT Q_PLUGIN_METADATA(IID "org.kylin.network") Q_INTERFACES(Interface) public: NetConnect(); ~NetConnect(); QWidget * pluginUi() Q_DECL_OVERRIDE; // 插件主界面---setPluginType后调用 void setPluginType(PluginType type, bool useSwitch = true) Q_DECL_OVERRIDE; // 设置插件类型 void setParentWidget(QWidget* widget){ if (parentWidget != nullptr) { return; } parentWidget = widget; } void setWidgetVisable(bool) {;} bool checkPluginIsHidden(); void hideTitle(); private: bool m_isSimpleMode = true; bool m_useSwitch = true; void initSystemDbus(); void initUi(); void initComponent(); void initConnect(); void runExternalApp(); void showDesktopNotify(const QString &message, QString soundName); //开关相关 void setSwitchStatus(); void hideLayout(QVBoxLayout * layout); void showLayout(QVBoxLayout * layout); int getInsertPos(QString connName, QVBoxLayout* layout); void activeConnect(QString uuid, QString deviceName); void deActiveConnect(QString uuid); //获取设备列表 void getDeviceStatusMap(QMap &map); void initNet(); void initNetListFromDevice(QString deviceName); //处理列表增加 void addLanItem(ItemFrame *frame, QString devName, KyWiredItem item); //增加设备 void addDeviceFrame(QString devName, bool isEnable); //减少设备 void removeDeviceFrame(QString devName); //增加一项 void addOneLanFrame(ItemFrame *frame, QString devName, QStringList infoList); //减少一项 void removeOneLanFrame(ItemFrame *frame, QString deviceName, QString uuid); //单个lan连接状态变化 void itemActiveConnectionStatusChanged(LanItem *item, KyConnectState status); //显示网速 void showRate(); void getDetailConfInfo(QString devName, QString uuid, ConInfo &conInfo); bool getWiredMainSwitch(); // protected: // bool eventFilter(QObject *w,QEvent *e); private: KyNetworkManager* manager; QThread* thread; QWidget* parentWidget = nullptr; QWidget* pluginWidget = nullptr; bool mFirstLoad = true; bool msettingLoad = false; QVBoxLayout* m_mainLayout = nullptr; QFrame* m_titleFrame = nullptr; QHBoxLayout* m_titleLayout = nullptr; QLabel* m_titleLabel = nullptr; KSwitchButton* m_wiredSwitch = nullptr; Divider* m_titleDivider = nullptr; QFrame* m_scrollFrame = nullptr; QVBoxLayout* m_scrollLayout = nullptr; QScrollArea* m_scrollArea = nullptr; QWidget* m_listWidget = nullptr; QVBoxLayout* m_scrollAreaLayout = nullptr; Divider* m_settingsDivider = nullptr; QFrame* m_settingsFrame = nullptr; QHBoxLayout* m_settingsLayout = nullptr; KBorderlessButton* m_settingsLabel = nullptr; QMap deviceStatusMap; QMap deviceFrameMap; QTimer * m_setNetSpeedTimer = nullptr; NetDetail* m_netdtail = nullptr; PluginType m_pluginType; QDBusInterface *m_pSysBusIntfs; Q_SIGNALS: void updatePluginHidden(bool); //general void setWiredEnabled(bool enabled); //有线无线公用 void deleteConnect(const QString &connectUuid); void activateConnection(const QString connectUuid, const QString deviceName); void deactivateConnection(const QString &activeConnectUuid); //wired 单设备启用禁用 void setWiredDeviceEnable(const QString &interface, bool enable); void createWiredConnect(KyConnectSetting connectSettingsInfo); void updateIpv4AndIpv6SettingInfo(const QString &uuid, const KyConnectSetting &connectSettingsInfo); private Q_SLOTS: void updateLanInfo(QString deviceName, QString connectUuid, QString connectName, QString connectPath); void onLanAdd(QString devName, QString connectUuid, QString connectName, QString connectPath); void onLanRemove(QString dbusPath); void onActiveConnectionChanged(QString deviceName, QString uuid, KyConnectState status); // void onDeviceStatusChanged(); void onDeviceNameChanged(QString, QString); void onDeviceCarrierChange(QString deviceName, bool pluged); void onDeviceManagedChange(QString, bool); void onWiredEnabledChanged(bool); void onDeviceAdd(QString deviceName); void onDeviceRemove(QString deviceName); void onSetNetSpeed(); void onShowDetailPage(QString, QString); void onUpdateSettings(QString, QString); void onWiredMainSwitchSLot(bool); void onWiredMainSwitchChanged(bool); }; #endif // NETCONNECT_H kylin-nm-plugin/plugins/netconnect/netconnect.pro0000775000175000017500000000312715160520531021241 0ustar fengfengQT += widgets network dbus gui core TEMPLATE = lib CONFIG += plugin include(../component/infobutton.pri) include(../component/divider.pri) include(../component/deviceframe.pri) include(../component/RadioItemButton.pri) include(../component/fixlabel.pri) include(netdetails/netdetails.pri) TARGET = $$qtLibraryTarget(netconnect) DESTDIR = ../.. CONFIG(release, debug|release) { !system($$PWD/translate_generation.sh): error("Failed to generate translation") } INCLUDEPATH += \ $$PROJECT_COMPONENTSOURCE \ $$PROJECT_ROOTDIR \ LIBS += -L$$[QT_INSTALL_LIBS] -lkylin-nm-base CONFIG += c++11 \ link_pkgconfig \ no_keywords PKGCONFIG += gsettings-qt6 \ kysdk-applications \ kylin-nm-base #DEFINES += QT_DEPRECATED_WARNINGS SOURCES += \ itemframe.cpp \ lanitem.cpp \ netconnect.cpp HEADERS += \ itemframe.h \ lanitem.h \ netconnect.h TRANSLATIONS += \ translations/zh_CN.ts \ translations/zh_HK.ts \ translations/zh_Hant.ts \ translations/tr.ts \ translations/bo.ts \ translations/bo_CN.ts \ translations/ug_CN.ts \ translations/ug.ts \ translations/ky.ts \ translations/mn.ts target.path = /usr/lib/kylin-nm qm_files.path = /usr/share/kylin-nm-plugin/netconnect/ qm_files.files = translations/*.qm ts_files.path = /usr/share/kylin-nm-plugin/netconnect/ ts_files.files = translations/*.ts INSTALLS += target \ qm_files RESOURCES += \ resource.qrc DISTFILES += \ translations/bo_CN.ts kylin-nm-plugin/plugins/netconnect/itemframe.h0000664000175000017500000000366415167660365020525 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 #include #include "lanitem.h" #include "../component/DeviceFrame/deviceframe.h" #include "../component/Divider/divider.h" #include class ItemFrame : public QFrame { Q_OBJECT public: ItemFrame(QString devName, QWidget *parent = nullptr); ~ItemFrame(); //单设备整体layout QVBoxLayout * deviceLanLayout = nullptr; Divider * m_divider; //单设备名称 单设备开关 DeviceFrame * deviceFrame = nullptr; //单设备列表Frame QFrame * lanItemFrame = nullptr; //单设备列表layout QVBoxLayout * lanItemLayout = nullptr; //单设备item列表 key:uuid QMap itemMap; //获取当前网速子线程 KyNetLoadRateThread *m_updateNetSpeedThread; QString m_deviceName; //更新网速显示 void startNetSpeedThread(); void stopNetSpeedThread(); void updateNetSpeed(); private: void setNetSpeed(long int rcvRate, long int txRate, LanItem *lanItem); }; #endif // ITEMFRAME_H kylin-nm-plugin/plugins/netconnect/lanitem.cpp0000775000175000017500000001243115160520531020512 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 #define RADIUS 6.0 #define LOADIMG_SIZE 16,16 LanItem::LanItem(bool isSimple, QWidget *parent) : QFrame(parent),isSimple(isSimple) { this->setFixedSize(404, 48); QHBoxLayout *mLanLyt = new QHBoxLayout(this); mLanLyt->setContentsMargins(16,0,0,0); mLanLyt->setSpacing(0); radioBtn = new RadioItemButton(this); titileLabel = new FixLabel(this); titileLabel->setMaximumWidth(MAX_WIDTH_DEACTIVATED); m_lbLoadUp = new QLabel(this); m_lbLoadDown = new QLabel(this); m_lbLoadDownImg = new QLabel(this); m_lbLoadUpImg = new QLabel(this); m_lbLoadUp->hide(); m_lbLoadDown->hide(); m_lbLoadDownImg->hide(); m_lbLoadUpImg->hide(); 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/icon/load-down.png"))); m_lbLoadUpImg->setPixmap(QPixmap(QLatin1String("://res/icon/load-up.png"))); m_lbLoadDownImg->setFixedSize(LOADIMG_SIZE); m_lbLoadUpImg->setFixedSize(LOADIMG_SIZE); mLanLyt->addWidget(radioBtn); mLanLyt->addSpacing(10); mLanLyt->addWidget(titileLabel,Qt::AlignLeft); mLanLyt->addStretch(); mLanLyt->addSpacing(8); mLanLyt->addWidget(m_lbLoadUpImg); mLanLyt->addWidget(m_lbLoadUp); mLanLyt->addSpacing(2); mLanLyt->addWidget(m_lbLoadDownImg); mLanLyt->addWidget(m_lbLoadDown); if (!isSimple) { infoLabel = new InfoButton(this); mLanLyt->addSpacing(8); mLanLyt->addWidget(infoLabel); connect(infoLabel, &InfoButton::released, this, [&](){ Q_EMIT infoButtonClick(m_uuid); }); } 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")); waitTimer = new QTimer(this); connect(waitTimer, &QTimer::timeout, this, &LanItem::updateIcon); m_menu = new QMenu(this);//右键菜单 m_menu->setWindowFlag(Qt::X11BypassWindowManagerHint); connect(m_menu, &QMenu::triggered, this, &LanItem::itemClick); } void LanItem::updateIcon() { if (currentIconIndex > 6) { currentIconIndex = 0; } radioBtn->setButtonIcon(loadIcons.at(currentIconIndex)); currentIconIndex ++; } void LanItem::startLoading() { waitTimer->start(FRAME_SPEED); m_loading = true; } void LanItem::stopLoading(){ waitTimer->stop(); m_loading = false; } void LanItem::mousePressEvent(QMouseEvent *event) { return QFrame::mousePressEvent(event); } void LanItem::mouseReleaseEvent(QMouseEvent *event) { if(event->button() == Qt::RightButton) { if (!m_menu) { return QFrame::mouseReleaseEvent(event); } m_menu->clear(); if (m_isAcitve || m_loading) { m_menu->addAction(new QAction(tr("Disconnect"), this)); } else if (!m_isAcitve && !m_loading) { m_menu->addAction(new QAction(tr("Connect"), this)); } m_menu->move(cursor().pos()); m_menu->show(); } else { if (!m_isAcitve && !m_loading) { Q_EMIT itemClick(); } } return QFrame::mouseReleaseEvent(event); } void LanItem::enterEvent(QEnterEvent *event) { m_isIn = true; update(); return QFrame::enterEvent(event); } void LanItem::leaveEvent(QEvent *event) { m_isIn = false; update(); return QFrame::leaveEvent(event); } void LanItem::paintEvent(QPaintEvent *event) { QPalette pal = this->palette(); QPainter painter(this); painter.setRenderHint(QPainter:: Antialiasing, true); //设置渲染,启动反锯齿 painter.setPen(Qt::NoPen); if (m_isIn) { QColor color(240, 240, 240); color.setAlphaF(0.39); painter.setBrush(color); } else painter.setBrush(pal.color(QPalette::Base)); QRect rect = this->rect(); QPainterPath path; path.addRoundedRect(rect, RADIUS, RADIUS); painter.drawPath(path); return QFrame::paintEvent(event); } kylin-nm-plugin/plugins/component/0000775000175000017500000000000015160520531016213 5ustar fengfengkylin-nm-plugin/plugins/component/SwitchButton/0000775000175000017500000000000015160520516020653 5ustar fengfengkylin-nm-plugin/plugins/component/SwitchButton/switchbutton.h0000664000175000017500000000615015160520516023563 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 SWITCHBUTTON_H #define SWITCHBUTTON_H #include #include #include #include #include #include #define OFF_BG_DARK_COLOR "#404040" #define OFF_HOVER_BG_DARK_COLOR "#666666" #define ON_BG_DARK_COLOR "#3790FA" #define ON_HOVER_BG_DARK_COLOR "#40A9FB" #define DISABLE_DARK_COLOR "#474747" #define DISABLE_RECT_DARK_COLOR "#6E6E6E" #define ENABLE_RECT_DARK_COLOR "#FFFFFF" #define OFF_BG_LIGHT_COLOR "#E0E0E0" #define OFF_HOVER_BG_LIGHT_COLOR "#B3B3B3" #define ON_BG_LIGHT_COLOR "#3790FA" #define ON_HOVER_BG_LIGHT_COLOR "#40A9FB" #define DISABLE_LIGHT_COLOR "#E9E9E9" #define DISABLE_RECT_LIGHT_COLOR "#B3B3B3" #define ENABLE_RECT_LIGHT_COLOR "#FFFFFF" class SwitchButton : public QWidget { Q_OBJECT public: SwitchButton(QWidget *parent = 0, bool useDisableStyle = true); ~SwitchButton(); void setChecked(bool checked); void setAnimation(bool on); bool isChecked(); void setDisabledFlag(bool); bool getDisabledFlag(); protected: void mousePressEvent(QMouseEvent *); void resizeEvent(QResizeEvent *); void paintEvent(QPaintEvent *); void enterEvent(QEvent *event); void leaveEvent(QEvent *event); void drawBg(QPainter * painter); void drawSlider(QPainter * painter); void changeColor(const QString &themes); private: bool checked; //切换的判断 bool disabled; void animation(QPainter *painter); QRect rect; bool isMoving; //滑块动作判断 bool isAnimation; // 是否允许动画执行 QColor bgColorOff; QColor bgColorOn; QColor bgHoverOnColor; QColor bgHoverOffColor; QColor bgColorDisabled; QColor sliderColorEnabled; QColor sliderColorDisabled; QColor rectColorEnabled; QColor rectColorDisabled; QColor sliderColorOff; QColor sliderColorOn; QGSettings *m_qtThemeSetting; QGSettings *m_gtkThemeSetting; int space; //滑块离背景间隔 int rectRadius; //圆角角度 int mStep; //移动步长 int mStartX; int mEndX; bool hover; QTimer * mTimer; bool m_useDisableStyle; private Q_SLOTS: void updatevalue(); Q_SIGNALS: void checkedChanged(bool checked); void disabledClick(); }; #endif // SWITCHBUTTON_H kylin-nm-plugin/plugins/component/SwitchButton/switchbutton.cpp0000664000175000017500000002173115160520516024120 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 "switchbutton.h" #include #define THEME_QT_SCHEMA "org.ukui.style" #define THEME_GTK_SCHEMA "org.mate.interface" #define TIMER_INTERVAL 5 //每隔5ms动画移动一次 #define MOVING_STEPS 40 //动画总共移动40次 SwitchButton::SwitchButton(QWidget *parent, bool useDisableStyle) : QWidget(parent) { // this->resize(QSize(52, 24)); this->setFixedSize(QSize(50, 24)); checked = false; hover = false; disabled = false; isMoving = false; isAnimation = true; m_useDisableStyle = useDisableStyle; space = 4; rectRadius = height()/2; mStep = width()/MOVING_STEPS;//也就是40次动画就可以走完,每次时间间隔是固定的5ms mStartX = 0; mEndX= 0; mTimer = new QTimer(this); mTimer->setInterval(TIMER_INTERVAL);//动画更新时间 connect(mTimer, SIGNAL(timeout()), this, SLOT(updatevalue())); if(QGSettings::isSchemaInstalled(THEME_GTK_SCHEMA) && QGSettings::isSchemaInstalled(THEME_QT_SCHEMA)) { QByteArray qtThemeID(THEME_QT_SCHEMA); QByteArray gtkThemeID(THEME_GTK_SCHEMA); m_gtkThemeSetting = new QGSettings(gtkThemeID,QByteArray(),this); m_qtThemeSetting = new QGSettings(qtThemeID,QByteArray(),this); QString style = m_qtThemeSetting->get("styleName").toString(); changeColor(style); connect(m_qtThemeSetting,&QGSettings::changed, [this] (const QString &key) { QString style = m_qtThemeSetting->get("styleName").toString(); if (key == "styleName") { changeColor(style); } }); } } SwitchButton::~SwitchButton() { } void SwitchButton::paintEvent(QPaintEvent *){ QPainter painter(this); //启用反锯齿 painter.setRenderHint(QPainter::Antialiasing, true); painter.setCompositionMode(QPainter::CompositionMode_Source); drawBg(&painter); if(!isAnimation)//动画如果禁用,则圆形滑块isMoving始终为false isMoving =false; if(isMoving) animation(&painter); drawSlider(&painter); painter.end(); } void SwitchButton::changeColor(const QString &themes) { if (hover) { return ;//在鼠标下,禁止切换颜色鼠标离开时切换颜色 } if (themes == "ukui-dark" || themes == "ukui-black") { bgColorOff = QColor(OFF_BG_DARK_COLOR); bgColorOn = QColor(ON_BG_DARK_COLOR); rectColorEnabled = QColor(ENABLE_RECT_DARK_COLOR); rectColorDisabled = QColor(DISABLE_RECT_DARK_COLOR); sliderColorDisabled = QColor(DISABLE_RECT_DARK_COLOR); sliderColorEnabled = QColor(ENABLE_RECT_DARK_COLOR); bgHoverOnColor = QColor(ON_HOVER_BG_DARK_COLOR); bgHoverOffColor = QColor(OFF_HOVER_BG_DARK_COLOR); bgColorDisabled = QColor(DISABLE_DARK_COLOR); } else { bgColorOff = QColor(OFF_BG_LIGHT_COLOR); bgColorOn = QColor(ON_BG_LIGHT_COLOR); rectColorEnabled = QColor(ENABLE_RECT_LIGHT_COLOR); rectColorDisabled = QColor(DISABLE_RECT_LIGHT_COLOR); sliderColorDisabled = QColor(DISABLE_RECT_LIGHT_COLOR); sliderColorEnabled = QColor(ENABLE_RECT_LIGHT_COLOR); bgHoverOnColor = QColor(ON_HOVER_BG_LIGHT_COLOR); bgHoverOffColor = QColor(OFF_HOVER_BG_LIGHT_COLOR); bgColorDisabled = QColor(DISABLE_LIGHT_COLOR); } } //动画绘制 void SwitchButton::animation(QPainter *painter){ painter->save(); int h = height(); int w = width(); painter->setPen(Qt::NoPen); //颜色设置 if(checked){ //开关在左侧时 painter->setBrush(bgColorOn); rect.setRect(0,0,h+mStartX,h); }else{ painter->setBrush(bgColorOff); rect.setRect(mStartX,0,w-mStartX,h); } painter->drawRoundedRect(rect,rectRadius,rectRadius); painter->restore(); } //绘制背景 void SwitchButton::drawBg(QPainter *painter){ int w = width(); int h = height(); painter->save(); painter->setPen(Qt::NoPen); if (disabled && m_useDisableStyle) { painter->setPen(Qt::NoPen); painter->setBrush(bgColorDisabled); } else { if(checked){ if(isMoving){ painter->setBrush(bgColorOff); rect.setRect(mStartX,0,w-mStartX,h); }else { painter->setBrush(bgColorOn); rect.setRect(0, 0, w, h); } }else{ if(isMoving){ painter->setBrush(bgColorOn); rect.setRect(0,0,mStartX+h,h); } else { painter->setBrush(bgColorOff); rect.setRect(0, 0, w, h); } } } //半径为高度的一半 painter->drawRoundedRect(rect,rectRadius,rectRadius); painter->restore(); } //绘制滑块,也就是圆形按钮 void SwitchButton::drawSlider(QPainter *painter){ painter->save(); painter->setPen(Qt::NoPen); if (!disabled || !m_useDisableStyle){ painter->setBrush(sliderColorEnabled); } else painter->setBrush(sliderColorDisabled); if (disabled) { if (!checked){ QRect smallRect(8, height() / 2 - 2, 10 , 4); painter->drawRoundedRect(smallRect,3,3); }else{ QRect smallRect(width() - 8 * 2, height() / 2 - 2, 10 , 4); painter->drawRoundedRect(smallRect,3,3); } } QRect rect(0, 0, width(), height()); int sliderWidth = rect.height() - space * 2; QRect sliderRect(mStartX + space, space, sliderWidth, sliderWidth); painter->drawEllipse(sliderRect); painter->restore(); } void SwitchButton::mousePressEvent(QMouseEvent *){ qDebug()<start(); isMoving = true; } } void SwitchButton::resizeEvent(QResizeEvent *){ //每次开始的x坐标都是跳过圆角,从直线的地方开始计算 mStep = width() / MOVING_STEPS; if (checked){ //circle out // startX = width() - height() + space; //circle in mStartX = width() - height(); } else mStartX = 0; rectRadius = height()/2; update(); } void SwitchButton::enterEvent(QEvent *event) { bgColorOn = bgHoverOnColor; bgColorOff = bgHoverOffColor; hover = true; update(); return QWidget::enterEvent(event); } void SwitchButton::leaveEvent(QEvent *event) { hover = false; QString style = m_qtThemeSetting->get("styleName").toString(); changeColor(style); update(); return QWidget::leaveEvent(event); } //根据事件向左还是向右移动 void SwitchButton::updatevalue(){ if (checked) if (mStartX < mEndX-mStep){ mStartX = mStartX + mStep; } else{ mStartX = mEndX; mTimer->stop(); isMoving = false; } else{ if (mStartX > mEndX+mStep){ mStartX = mStartX - mStep; } else{ mStartX = mEndX; mTimer->stop(); isMoving = false; } } update(); } void SwitchButton::setChecked(bool checked){ if (this->checked != checked){ this->checked = checked; Q_EMIT checkedChanged(checked); update(); } mStep = width() / MOVING_STEPS; if (checked){ //circle out // endX = width() - height() + space; //circle in mEndX = width() - height(); } else{ mEndX = 0; } mTimer->start(); isMoving = true; } bool SwitchButton::isChecked(){ return this->checked; } void SwitchButton::setDisabledFlag(bool value) { disabled = value; update(); } bool SwitchButton::getDisabledFlag() { return disabled; } void SwitchButton::setAnimation(bool on){ isAnimation = on; } kylin-nm-plugin/plugins/component/DrownLabel/0000775000175000017500000000000015167660365020265 5ustar fengfengkylin-nm-plugin/plugins/component/DrownLabel/drownlabel.h0000664000175000017500000000260215167660365022567 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 #include #include #include #include class DrownLabel : public QLabel { Q_OBJECT public: explicit DrownLabel(QString devName, QWidget * parent = nullptr); ~DrownLabel(); void setDropDownStatus(bool status); QString m_devName; bool isChecked = true; private: void loadPixmap(bool isChecked); protected: virtual void mouseReleaseEvent(QMouseEvent * event); Q_SIGNALS: void labelClicked(); }; #endif // DROWNLABEL_H kylin-nm-plugin/plugins/component/DrownLabel/drownlabel.cpp0000664000175000017500000000316415160520531023105 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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" #define ICONSIZE 16,16 DrownLabel::DrownLabel(QString devName, QWidget * parent) : QLabel(parent) { m_devName = devName; setFixedSize(36,36); loadPixmap(isChecked); this->setProperty("useIconHighlightEffect", 0x2); } DrownLabel::~DrownLabel() { } void DrownLabel::setDropDownStatus(bool status) { isChecked = status; loadPixmap(isChecked); } void DrownLabel::loadPixmap(bool isChecked) { if (isChecked) { setPixmap(QIcon::fromTheme("ukui-up-symbolic").pixmap(ICONSIZE)); } else { setPixmap(QIcon::fromTheme("ukui-down-symbolic").pixmap(ICONSIZE)); } } void DrownLabel::mouseReleaseEvent(QMouseEvent *event) { emit labelClicked(); QWidget::mouseReleaseEvent(event); } kylin-nm-plugin/plugins/component/Divider/0000775000175000017500000000000015167660365017622 5ustar fengfengkylin-nm-plugin/plugins/component/Divider/divider.cpp0000664000175000017500000000250215160520531021732 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 Divider::Divider(QWidget * parent) : QFrame(parent) { this->setFixedHeight(1); } void Divider::paintEvent(QPaintEvent * e) { QPainter p(this); QColor color = qApp->palette().color(QPalette::BrightText); color.setAlphaF(0.08); p.save(); p.setBrush(color); p.setPen(Qt::transparent); p.drawRoundedRect(this->rect(), 6, 6); p.restore(); return QFrame::paintEvent(e); } kylin-nm-plugin/plugins/component/Divider/divider.h0000664000175000017500000000212715167660365021423 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 class Divider : public QFrame { public: Divider(QWidget * parent = nullptr); ~Divider() = default; protected: void paintEvent(QPaintEvent *event); }; #endif // DIVIDER_H kylin-nm-plugin/plugins/component/DeviceFrame/0000775000175000017500000000000015167660365020406 5ustar fengfengkylin-nm-plugin/plugins/component/DeviceFrame/deviceframe.cpp0000664000175000017500000000256415160520531023352 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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" #define LAYOUT_MARGINS 24,0,0,0 #define FRAME_HEIGHT 36 DeviceFrame::DeviceFrame(QString devName, QWidget *parent) : QFrame(parent) { this->setFixedHeight(FRAME_HEIGHT); QHBoxLayout *deviceLayout = new QHBoxLayout(this); deviceLayout->setContentsMargins(LAYOUT_MARGINS); setLayout(deviceLayout); deviceLabel = new QLabel(this); deviceLabel->setText(devName); deviceLabel->setDisabled(true); deviceLayout->addWidget(deviceLabel); deviceLayout->addStretch(); } kylin-nm-plugin/plugins/component/DeviceFrame/deviceframe.h0000664000175000017500000000225415167660365023034 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 #include #include #include #include class DeviceFrame : public QFrame { public: DeviceFrame(QString devName, QWidget *parent = nullptr); public: QLabel * deviceLabel = nullptr; }; #endif // DEVICEFRAME_H kylin-nm-plugin/plugins/component/FixLabel/0000775000175000017500000000000015167660365017722 5ustar fengfengkylin-nm-plugin/plugins/component/FixLabel/freqlabel.h0000664000175000017500000000226015167660365022030 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 FREQLABEL_H #define FREQLABEL_H #include #include class FreqLabel : public QLabel { Q_OBJECT public: FreqLabel(QWidget *parent = nullptr); ~FreqLabel() = default; protected: void paintEvent(QPaintEvent *event); private Q_SLOTS: void changedFontSlot(); }; #endif // FREQLABEL_H kylin-nm-plugin/plugins/component/FixLabel/freqlabel.cpp0000664000175000017500000000422115167660365022362 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 "freqlabel.h" #include #include #include #define FREQLABLE_HIGHT 18 #define FREQLABLE_MARGINS 4,0,4,0 #define RADIUS 6.0 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(); setText("..."); setFixedHeight(FREQLABLE_HIGHT); setContentsMargins(FREQLABLE_MARGINS); } 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, RADIUS, RADIUS); QLabel::paintEvent(event); } kylin-nm-plugin/plugins/component/FixLabel/fixlabel.h0000664000175000017500000000230515167660365021661 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 FIXLABEL_H #define FIXLABEL_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; }; #endif // FIXLABEL_H kylin-nm-plugin/plugins/component/FixLabel/fixlabel.cpp0000664000175000017500000000333315160520531022175 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 "fixlabel.h" #include FixLabel::FixLabel(QWidget *parent) : QLabel(parent) { const QByteArray id("org.ukui.style"); QGSettings * fontSetting = new QGSettings(id, QByteArray(), this); 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.horizontalAdvance(mStr); if (fontSize > this->width()) { setText(fontMetrics.elidedText(mStr, Qt::ElideRight, this->width())); setToolTip(mStr); } else { setText(mStr); setToolTip(""); } } kylin-nm-plugin/plugins/component/RadioItemButton.pri0000664000175000017500000000026315160520516022004 0ustar fengfeng #LIBINTERFACE_NAME = $$qtLibraryTarget(divider) SOURCES += \ $$PWD/RadioItemButton/radioitembutton.cpp \ HEADERS += \ $$PWD/RadioItemButton/radioitembutton.h \ kylin-nm-plugin/plugins/component/FixPushButton/0000775000175000017500000000000015167660365021016 5ustar fengfengkylin-nm-plugin/plugins/component/FixPushButton/fixpushbutton.cpp0000775000175000017500000000345415167660365024455 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 "fixpushbutton.h" #include 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.horizontalAdvance(mStr); if (fontSize > 65) { setText(fontMetrics.elidedText(mStr, Qt::ElideRight, 65)); setToolTip(mStr); } else { setText(mStr); setToolTip(""); } } kylin-nm-plugin/plugins/component/FixPushButton/fixpushbutton.h0000664000175000017500000000234315167660365024113 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 FIXPUSHBUTTON_H #define FIXPUSHBUTTON_H #include #include 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; }; #endif // FIXPUSHBUTTON_H kylin-nm-plugin/plugins/component/RadioItemButton/0000775000175000017500000000000015167660365021305 5ustar fengfengkylin-nm-plugin/plugins/component/RadioItemButton/radioitembutton.cpp0000664000175000017500000001406215160520531025204 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 #include #include #include #include #define BUTTON_SIZE 36,36 #define ICON_SIZE 16,16 #define BACKGROUND_COLOR QColor(0,0,0,0) RadioItemButton::RadioItemButton(QWidget *parent) : QPushButton(parent) { this->setAutoFillBackground(false); m_iconLabel = new QLabel(this); this->setFixedSize(BUTTON_SIZE); m_iconLabel->setFixedSize(BUTTON_SIZE); m_iconLabel->setAlignment(Qt::AlignCenter); setActive(false); //JXJ_TODO loading动画 connect(qApp, &QApplication::paletteChanged, this, &RadioItemButton::onPaletteChanged); } //设置图标 void RadioItemButton::setButtonIcon(const QIcon &icon) { if (icon.isNull()) { return; } m_pixmap = icon.pixmap(ICON_SIZE); refreshButtonIcon(); } //显示默认图标 void RadioItemButton::setDefaultPixmap() { m_iconLabel->setPixmap(m_pixmap); } //根据连接状态更改图标颜色 void RadioItemButton::setActive(const bool &isActive) { m_isActivated = isActive; refreshButtonIcon(); } void RadioItemButton::onPaletteChanged() { refreshButtonIcon(); } void RadioItemButton::paintEvent(QPaintEvent *event) { QPalette pal = this->palette(); pal.setColor(QPalette::Base, BACKGROUND_COLOR); pal.setColor(QPalette::Text, m_backgroundColor); QPainterPath cPath; cPath.addRect(0, 0, this->width(), this->height()); cPath.addEllipse(0, 0, this->width(), this->width()); QPainterPath innerPath; innerPath.addEllipse(0, 0, this->width(), this->width()); QPainter painter(this); painter.setRenderHint(QPainter:: Antialiasing, true); //设置渲染,启动反锯齿 painter.setPen(Qt::NoPen); painter.setBrush(pal.color(QPalette::Base)); painter.drawPath(cPath); painter.fillPath(innerPath, pal.color(QPalette::Text)); } void RadioItemButton::mousePressEvent(QMouseEvent *event) { if (m_isActivated) { m_backgroundColor = qApp->palette().highlight().color(); } else { m_backgroundColor = qApp->palette().brightText().color(); m_backgroundColor.setAlphaF(0.21); } this->update(); return QPushButton::mousePressEvent(event); } void RadioItemButton::mouseReleaseEvent(QMouseEvent *event) { if (m_isActivated) { m_backgroundColor = qApp->palette().highlight().color(); } else { m_backgroundColor = qApp->palette().brightText().color(); m_backgroundColor.setAlphaF(0.18); } this->update(); return QPushButton::mouseReleaseEvent(event); } void RadioItemButton::enterEvent(QEnterEvent *event) { if (m_isActivated) { m_backgroundColor = qApp->palette().highlight().color(); } else { m_backgroundColor = qApp->palette().brightText().color(); m_backgroundColor.setAlphaF(0.32); } this->update(); return QPushButton::enterEvent(event); } void RadioItemButton::leaveEvent(QEvent *event) { if (m_isActivated) { m_backgroundColor = qApp->palette().highlight().color(); } else { m_backgroundColor = qApp->palette().brightText().color(); m_backgroundColor.setAlphaF(0.18); } this->update(); return QPushButton::leaveEvent(event); } void RadioItemButton::refreshButtonIcon() { if (m_isActivated) { m_backgroundColor = qApp->palette().highlight().color(); m_iconLabel->setPixmap(loadSvg(m_pixmap, PixmapColor::WHITE)); } else { m_backgroundColor = qApp->palette().brightText().color(); m_backgroundColor.setAlphaF(0.18); // if (qApp->palette().base().color().red() > MIDDLE_COLOR) { m_iconLabel->setPixmap(m_pixmap); // } else { // m_iconLabel->setPixmap(loadSvg(m_pixmap, PixmapColor::WHITE)); // } } return; } const QPixmap RadioItemButton::loadSvg(const QPixmap &source, const PixmapColor &cgColor) { QImage img = source.toImage(); for (int x = 0; x < img.width(); x++) { for (int y = 0; y < img.height(); y++) { auto color = img.pixelColor(x, y); if (color.alpha() > 0) { switch (cgColor) { case PixmapColor::WHITE: color.setRed(255); color.setGreen(255); color.setBlue(255); img.setPixelColor(x, y, color); break; case PixmapColor::BLACK: color.setRed(0); color.setGreen(0); color.setBlue(0); img.setPixelColor(x, y, color); break; case PixmapColor::GRAY: color.setRed(152); color.setGreen(163); color.setBlue(164); img.setPixelColor(x, y, color); break; case PixmapColor::BLUE: color.setRed(61); color.setGreen(107); color.setBlue(229); img.setPixelColor(x, y, color); break; default: return source; break; } } } } return QPixmap::fromImage(img); } kylin-nm-plugin/plugins/component/RadioItemButton/radioitembutton.h0000664000175000017500000000361115167660365024670 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 #include #include #include #include #define MIDDLE_COLOR 178 class RadioItemButton : public QPushButton { Q_OBJECT public: RadioItemButton(QWidget * parent = nullptr); // ~RadioItemButton(); void setButtonIcon(const QIcon &icon); void setDefaultPixmap(); void setActive(const bool &isActive); enum PixmapColor { WHITE = 0, BLACK, GRAY, BLUE, }; const QPixmap loadSvg(const QPixmap &source, const PixmapColor &color); protected: void paintEvent(QPaintEvent *event); void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); void enterEvent(QEnterEvent *event); void leaveEvent(QEvent *event); private: bool m_isActivated = false; QLabel * m_iconLabel = nullptr; QColor m_backgroundColor; QPixmap m_pixmap; void refreshButtonIcon(); private Q_SLOTS: void onPaletteChanged(); }; #endif // NETBUTTON_H kylin-nm-plugin/plugins/component/divider.pri0000664000175000017500000000021715160520516020360 0ustar fengfeng#LIBINTERFACE_NAME = $$qtLibraryTarget(drownlabel) SOURCES += \ $$PWD/Divider/divider.cpp \ HEADERS += \ $$PWD/Divider/divider.h \ kylin-nm-plugin/plugins/component/InfoButton/0000775000175000017500000000000015167660365020323 5ustar fengfengkylin-nm-plugin/plugins/component/InfoButton/infobutton.h0000664000175000017500000000311415167660365022662 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 #include #include class InfoButton : public QPushButton { Q_OBJECT public: explicit InfoButton(QWidget * parent = nullptr); ~InfoButton() = default; protected: void paintEvent(QPaintEvent *event); void enterEvent(QEnterEvent *event); void leaveEvent(QEvent *event); void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); private: void initUI(); private: QColor m_backgroundColor; QColor m_foregroundColor; //监听主题的Gsettings QGSettings * m_styleGsettings = nullptr; private Q_SLOTS: void onGSettingChaned(const QString &key); }; #endif // INFOBUTTON_H kylin-nm-plugin/plugins/component/InfoButton/infobutton.cpp0000664000175000017500000000723715160520531023206 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2019 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 #define BUTTON_SIZE 36,36 #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 BUTTON_SIZE 36,36 #define THEME_SCHAME "org.ukui.style" #define COLOR_THEME "styleName" InfoButton::InfoButton(QWidget *parent) : QPushButton(parent) { this->setFixedSize(BUTTON_SIZE); initUI(); const QByteArray style_id(THEME_SCHAME); if (QGSettings::isSchemaInstalled(style_id)) { m_styleGsettings = new QGSettings(style_id); connect(m_styleGsettings, &QGSettings::changed, this, &InfoButton::onGSettingChaned); } else { qDebug() << "Gsettings interface \"org.ukui.style\" is not exist!"; } } void InfoButton::initUI() { this->setFixedSize(BUTTON_SIZE); m_backgroundColor = BACKGROUND_COLOR; m_foregroundColor = FOREGROUND_COLOR_NORMAL; } void InfoButton::onGSettingChaned(const QString &key) { if (key == COLOR_THEME) { m_foregroundColor = FOREGROUND_COLOR_NORMAL; this->repaint(); } } void InfoButton::paintEvent(QPaintEvent *event) { QPalette pal = this->palette(); pal.setColor(QPalette::Base, m_backgroundColor); pal.setColor(QPalette::Text, m_foregroundColor); QPainterPath cPath; cPath.addRect(0, 0, ICON_SIZE); cPath.addEllipse(0, 0, ICON_SIZE); QPainterPath outerPath; outerPath.addEllipse(OUTER_PATH); QPainterPath innerPath; innerPath.addEllipse(INNER_PATH); outerPath -= innerPath; QPainter painter(this); painter.setRenderHint(QPainter:: Antialiasing, true); //设置渲染,启动反锯齿 painter.setPen(Qt::NoPen); painter.setBrush(pal.color(QPalette::Base)); painter.drawPath(cPath); painter.fillPath(outerPath, pal.color(QPalette::Text)); painter.setPen(m_foregroundColor); QFont font("Noto Sans CJK SC", 11, QFont::Normal, false); painter.setFont(font); painter.drawText(TEXT_POS, "i"); } void InfoButton::enterEvent(QEnterEvent *event) { m_foregroundColor = FOREGROUND_COLOR_HOVER; this->repaint(); } void InfoButton::leaveEvent(QEvent *event) { m_foregroundColor = FOREGROUND_COLOR_NORMAL; this->repaint(); } void InfoButton::mousePressEvent(QMouseEvent *event) { m_foregroundColor = FOREGROUND_COLOR_PRESS; this->repaint(); return QPushButton::mousePressEvent(event); } void InfoButton::mouseReleaseEvent(QMouseEvent *event) { m_foregroundColor = FOREGROUND_COLOR_HOVER; this->repaint(); return QPushButton::mouseReleaseEvent(event); } kylin-nm-plugin/plugins/component/fixpushbutton.pri0000664000175000017500000000024315160520531021650 0ustar fengfeng #LIBINTERFACE_NAME = $$qtLibraryTarget(divider) SOURCES += \ $$PWD/FixPushButton/fixpushbutton.cpp \ HEADERS += \ $$PWD/FixPushButton/fixpushbutton.h \ kylin-nm-plugin/plugins/component/infobutton.pri0000664000175000017500000000024315160520516021120 0ustar fengfeng#LIBINTERFACE_NAME = $$qtLibraryTarget(infobutton) SOURCES += \ $$PWD/InfoButton/infobutton.cpp \ HEADERS += \ $$PWD/InfoButton/infobutton.h \ kylin-nm-plugin/plugins/component/fixlabel.pri0000664000175000017500000000034315160520531020515 0ustar fengfeng #LIBINTERFACE_NAME = $$qtLibraryTarget(divider) SOURCES += \ $$PWD/FixLabel/fixlabel.cpp \ $$PWD/FixLabel/freqlabel.cpp \ HEADERS += \ $$PWD/FixLabel/fixlabel.h \ $$PWD/FixLabel/freqlabel.h \ kylin-nm-plugin/plugins/component/switchbutton.pri0000664000175000017500000000022315160520516021464 0ustar fengfeng #LIBINTERFACE_NAME = $$qtLibraryTarget(divider) SOURCES += \ $$PWD/Divider/divider.cpp \ HEADERS += \ $$PWD/Divider/divider.h \ kylin-nm-plugin/plugins/component/drownlabel.pri0000664000175000017500000000023315160520516021061 0ustar fengfeng#LIBINTERFACE_NAME = $$qtLibraryTarget(drownlabel) SOURCES += \ $$PWD/DrownLabel/drownlabel.cpp \ HEADERS += \ $$PWD/DrownLabel/drownlabel.h \ kylin-nm-plugin/plugins/component/deviceframe.pri0000664000175000017500000000024315160520516021203 0ustar fengfeng #LIBINTERFACE_NAME = $$qtLibraryTarget(divider) SOURCES += \ $$PWD/DeviceFrame/deviceframe.cpp \ HEADERS += \ $$PWD/DeviceFrame/deviceframe.h \