diff --git a/CMakeLists.txt b/CMakeLists.txt index ea2408d4..05c2f3f5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,88 +1,105 @@ -project(plasma-networkmanagement) +cmake_minimum_required(VERSION 3.0) -cmake_minimum_required(VERSION 2.8.12 FATAL_ERROR) -set(QT_MIN_VERSION "5.4.0") +project(plasma-networkmanagement) -set(PROJECT_VERSION "5.12.80") +set(PROJECT_VERSION "5.14.80") set(PROJECT_VERSION_MAJOR 5) +set(QT_MIN_VERSION "5.11.0") +set(KF5_MIN_VERSION "5.50.0") + ################# set KDE specific information ################# -find_package(ECM 1.3.0 REQUIRED NO_MODULE) +find_package(ECM ${KF5_MIN_VERSION} REQUIRED NO_MODULE) set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${ECM_MODULE_PATH} ${ECM_KDE_MODULE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/cmake) include(KDEInstallDirs) include(KDECMakeSettings) include(KDECompilerSettings NO_POLICY_SCOPE) -include(ECMPackageConfigHelpers) -include(ECMOptionalAddSubdirectory) include(FeatureSummary) find_package(Qt5 ${QT_MIN_VERSION} CONFIG REQUIRED COMPONENTS Core DBus Network Quick - QuickWidgets - UiTools Widgets ) -find_package(KF5 REQUIRED - I18n WindowSystem Service Completion WidgetsAddons KIO CoreAddons Wallet ItemViews XmlGui - ConfigWidgets IconThemes Solid DBusAddons Notifications Plasma Declarative Init KDELibs4Support) - -find_package(KF5NetworkManagerQt REQUIRED 5.42.0) +find_package(KF5 ${KF5_MIN_VERSION} REQUIRED + I18n + WindowSystem + Service + Completion + WidgetsAddons + KIO + CoreAddons + Wallet + ConfigWidgets + IconThemes + Solid + DBusAddons + Notifications + Plasma + Declarative + NetworkManagerQt +) -find_package(KF5ModemManagerQt 5.14.0) +find_package(KF5ModemManagerQt ${KF5_MIN_VERSION}) set_package_properties(KF5ModemManagerQt PROPERTIES TYPE OPTIONAL) # Required only for getting information about NetworkManager version in CMake -find_package(NetworkManager 1.0.0) +find_package(NetworkManager 1.4.0) set_package_properties(NetworkManager PROPERTIES TYPE REQUIRED) find_package(MobileBroadbandProviderInfo) set_package_properties(MobileBroadbandProviderInfo PROPERTIES DESCRIPTION "Database of mobile broadband service providers" URL "http://live.gnome.org/NetworkManager/MobileBroadband/ServiceProviders" TYPE OPTIONAL) find_package(Qca-qt5 2.1.0) set_package_properties(Qca-qt5 PROPERTIES DESCRIPTION "Support for encryption" URL "http://download.kde.org/stable/qca-qt5/" TYPE REQUIRED) if (DISABLE_MODEMMANAGER_SUPPORT) message(STATUS "Disabling ModemManager support") set(WITH_MODEMMANAGER_SUPPORT 0) else() if (KF5ModemManagerQt_FOUND) message(STATUS "Enabling ModemManager support") set(WITH_MODEMMANAGER_SUPPORT 1) else() message(STATUS "ModemManager or ModemManagerQt not found") set(WITH_MODEMMANAGER_SUPPORT 0) endif() endif() add_definitions(-DQT_DISABLE_DEPRECATED_BEFORE=0) -add_definitions(-DQT_USE_FAST_CONCATENATION -DQT_USE_FAST_OPERATOR_PLUS) +add_definitions(-DQT_USE_FAST_OPERATOR_PLUS) add_definitions(-DQT_NO_URL_CAST_FROM_STRING) remove_definitions(-DQT_NO_CAST_FROM_ASCII -DQT_NO_CAST_FROM_BYTEARRAY) add_definitions(-DWITH_MODEMMANAGER_SUPPORT=${WITH_MODEMMANAGER_SUPPORT}) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/libs ${CMAKE_CURRENT_SOURCE_DIR}/libs/editor/) add_subdirectory(applet) add_subdirectory(kded) add_subdirectory(kcm) add_subdirectory(libs) add_subdirectory(vpn) add_subdirectory(mobile) + +# Enable unit testing +if (BUILD_TESTING) + add_subdirectory(tests) +endif () + feature_summary(WHAT ALL INCLUDE_QUIET_PACKAGES FATAL_ON_MISSING_REQUIRED_PACKAGES) diff --git a/applet/contents/ui/ConnectionItem.qml b/applet/contents/ui/ConnectionItem.qml index b141ba43..cb3c582b 100644 --- a/applet/contents/ui/ConnectionItem.qml +++ b/applet/contents/ui/ConnectionItem.qml @@ -1,393 +1,375 @@ /* Copyright 2013-2017 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ import QtQuick 2.2 +import QtQuick.Layouts 1.2 import org.kde.kcoreaddons 1.0 as KCoreAddons -import org.kde.kquickcontrolsaddons 2.0 as KQuickControlsAddons import org.kde.plasma.components 2.0 as PlasmaComponents import org.kde.plasma.core 2.0 as PlasmaCore -import org.kde.plasma.extras 2.0 as PlasmaExtras import org.kde.plasma.networkmanagement 0.2 as PlasmaNM PlasmaComponents.ListItem { id: connectionItem - property bool activating: ConnectionState == PlasmaNM.Enums.Activating; - property int baseHeight: connectionItemBase.height + property bool activating: ConnectionState == PlasmaNM.Enums.Activating + property int baseHeight: Math.max(units.iconSizes.medium, connectionNameLabel.height + connectionStatusLabel.height) + Math.round(units.gridUnit / 2) property bool expanded: visibleDetails || visiblePasswordDialog property bool predictableWirelessPassword: !Uuid && Type == PlasmaNM.Enums.Wireless && (SecurityType == PlasmaNM.Enums.StaticWep || SecurityType == PlasmaNM.Enums.WpaPsk || SecurityType == PlasmaNM.Enums.Wpa2Psk) - property bool showSpeed: ConnectionState == PlasmaNM.Enums.Activated && + property bool showSpeed: plasmoid.expanded && + ConnectionState == PlasmaNM.Enums.Activated && (Type == PlasmaNM.Enums.Wired || Type == PlasmaNM.Enums.Wireless || Type == PlasmaNM.Enums.Gsm || Type == PlasmaNM.Enums.Cdma) property bool visibleDetails: false property bool visiblePasswordDialog: false + property real rxBytes: 0 + property real txBytes: 0 + checked: connectionItem.containsMouse enabled: true - height: expanded ? baseHeight + expandableComponentLoader.height + Math.round(units.gridUnit / 3) : baseHeight - - PlasmaCore.DataSource { - id: dataSource - - property string downloadSource: "network/interfaces/" + DeviceName + "/receiver/data" - property string uploadSource: "network/interfaces/" + DeviceName + "/transmitter/data" - - connectedSources: showSpeed && plasmoid.expanded ? [downloadSource, uploadSource] : [] - engine: "systemmonitor" - interval: 2000 - } - - Item { - id: connectionItemBase - - anchors { - left: parent.left - right: parent.right - top: parent.top - // Reset top margin from PlasmaComponents.ListItem - topMargin: -Math.round(units.gridUnit / 3) - } - height: Math.max(units.iconSizes.medium, connectionNameLabel.height + connectionStatusLabel.height) + Math.round(units.gridUnit / 2) - - PlasmaCore.SvgItem { - id: connectionSvgIcon - - anchors { - left: parent.left - verticalCenter: parent.verticalCenter - } - elementId: ConnectionIcon - height: units.iconSizes.medium; width: height - svg: PlasmaCore.Svg { - multipleImages: true - imagePath: "icons/network" - colorGroup: PlasmaCore.ColorScope.colorGroup + height: expanded ? baseHeight + separator.height + expandableComponentLoader.height + (2 * Math.round(units.gridUnit / 3)) : baseHeight + + ColumnLayout { + anchors.fill: parent + + RowLayout { + Layout.fillWidth: true + spacing: Math.round(units.gridUnit / 2) + + PlasmaCore.SvgItem { + id: connectionSvgIcon + Layout.alignment: Qt.AlignVCenter | Qt.AlignLeft + Layout.preferredHeight: units.iconSizes.medium + Layout.preferredWidth: units.iconSizes.medium + elementId: ConnectionIcon + svg: PlasmaCore.Svg { + multipleImages: true + imagePath: "icons/network" + colorGroup: PlasmaCore.ColorScope.colorGroup + } } - } - PlasmaComponents.Label { - id: connectionNameLabel + ColumnLayout { + Layout.alignment: Qt.AlignVCenter | Qt.AlignLeft + spacing: 0 + + PlasmaComponents.Label { + id: connectionNameLabel + Layout.fillWidth: true + height: paintedHeight + elide: Text.ElideRight + font.weight: ConnectionState == PlasmaNM.Enums.Activated ? Font.DemiBold : Font.Normal + font.italic: ConnectionState == PlasmaNM.Enums.Activating ? true : false + text: ItemUniqueName + textFormat: Text.PlainText + } - anchors { - bottom: connectionSvgIcon.verticalCenter - left: connectionSvgIcon.right - leftMargin: Math.round(units.gridUnit / 2) - right: stateChangeButton.visible ? stateChangeButton.left : parent.right + PlasmaComponents.Label { + id: connectionStatusLabel + Layout.fillWidth: true + height: paintedHeight + elide: Text.ElideRight + font.pointSize: theme.smallestFont.pointSize + opacity: 0.6 + text: itemText() + } } - height: paintedHeight - elide: Text.ElideRight - font.weight: ConnectionState == PlasmaNM.Enums.Activated ? Font.DemiBold : Font.Normal - font.italic: ConnectionState == PlasmaNM.Enums.Activating ? true : false - text: ItemUniqueName - textFormat: Text.PlainText - } - PlasmaComponents.Label { - id: connectionStatusLabel - - anchors { - left: connectionSvgIcon.right - leftMargin: Math.round(units.gridUnit / 2) - right: stateChangeButton.visible ? stateChangeButton.left : parent.right - top: connectionNameLabel.bottom + PlasmaComponents.BusyIndicator { + id: connectingIndicator + Layout.alignment: Qt.AlignVCenter | Qt.AlignRight + Layout.fillHeight: true + running: plasmoid.expanded && !stateChangeButton.visible && ConnectionState == PlasmaNM.Enums.Activating + visible: running + opacity: visible } - height: paintedHeight - elide: Text.ElideRight - font.pointSize: theme.smallestFont.pointSize - opacity: 0.6 - text: itemText() - } - PlasmaComponents.BusyIndicator { - id: connectingIndicator + PlasmaComponents.Button { + id: stateChangeButton + Layout.alignment: Qt.AlignVCenter | Qt.AlignRight + opacity: connectionView.currentVisibleButtonIndex == index ? 1 : 0 + visible: opacity != 0 + text: (ConnectionState == PlasmaNM.Enums.Deactivated) ? i18n("Connect") : i18n("Disconnect") - anchors { - right: stateChangeButton.visible ? stateChangeButton.left : parent.right - rightMargin: Math.round(units.gridUnit / 2) - verticalCenter: connectionSvgIcon.verticalCenter - } - height: units.iconSizes.medium; width: height - running: plasmoid.expanded && !stateChangeButton.visible && ConnectionState == PlasmaNM.Enums.Activating - visible: running - } - - PlasmaComponents.Button { - id: stateChangeButton + Behavior on opacity { NumberAnimation { duration: units.shortDuration } } - anchors { - right: parent.right - rightMargin: Math.round(units.gridUnit / 2) - verticalCenter: connectionSvgIcon.verticalCenter + onClicked: changeState() } - opacity: connectionView.currentVisibleButtonIndex == index ? 1 : 0 - visible: opacity != 0 - text: (ConnectionState == PlasmaNM.Enums.Deactivated) ? i18n("Connect") : i18n("Disconnect") - - Behavior on opacity { NumberAnimation { duration: units.shortDuration } } - - onClicked: changeState() } - } - Loader { - id: expandableComponentLoader + PlasmaCore.SvgItem { + id: separator + height: lineSvg.elementSize("horizontal-line").height + Layout.fillWidth: true + Layout.maximumHeight: height + elementId: "horizontal-line" + svg: PlasmaCore.Svg { id: lineSvg; imagePath: "widgets/line" } + visible: connectionItem.expanded + opacity: visible + } - anchors { - left: parent.left - right: parent.right - top: connectionItemBase.bottom + Loader { + id: expandableComponentLoader + Layout.fillHeight: true + Layout.fillWidth: true + height: childrenRect.height } } Component { id: detailsComponent Item { height: childrenRect.height - Separator { - id: detailsSeparator - anchors { - left: parent.left - right: parent.right - top: parent.top - } - } - PlasmaComponents.TabBar { - id: detailsTabBar; + id: detailsTabBar anchors { left: parent.left right: parent.right - top: detailsSeparator.bottom - topMargin: Math.round(units.gridUnit / 3) + top: parent.top } height: visible ? implicitHeight : 0 - visible: showSpeed && dataSource.data && dataSource.data[dataSource.downloadSource] && dataSource.data[dataSource.uploadSource] + visible: showSpeed PlasmaComponents.TabButton { - id: speedTabButton; - text: i18n("Speed"); + id: speedTabButton + text: i18n("Speed") } PlasmaComponents.TabButton { - id: detailsTabButton; - text: i18n("Details"); + id: detailsTabButton + text: i18n("Details") } Component.onCompleted: { if (!speedTabButton.visible) { - currentTab = detailsTabButton; + currentTab = detailsTabButton } } } DetailsText { anchors { left: parent.left leftMargin: units.iconSizes.medium right: parent.right - top: detailsTabBar.visible ? detailsTabBar.bottom : detailsSeparator.bottom + top: detailsTabBar.visible ? detailsTabBar.bottom : parent.top topMargin: Math.round(units.gridUnit / 3) } details: ConnectionDetails visible: detailsTabBar.currentTab == detailsTabButton } TrafficMonitor { anchors { left: parent.left right: parent.right - top: detailsTabBar.visible ? detailsTabBar.bottom : detailsSeparator.bottom + top: detailsTabBar.visible ? detailsTabBar.bottom : parent.top topMargin: Math.round(units.gridUnit / 3) } - dataEngine: dataSource - deviceName: DeviceName + rxBytes: RxBytes + txBytes: TxBytes + interval: 2000 visible: detailsTabBar.currentTab == speedTabButton } } } Component { id: passwordDialogComponent Item { property alias password: passwordField.text property alias passwordInput: passwordField height: childrenRect.height - Separator { - id: passwordSeparator + PasswordField { + id: passwordField anchors { left: parent.left right: parent.right top: parent.top } - } - - PasswordField { - id: passwordField - anchors { - horizontalCenter: parent.horizontalCenter - top: passwordSeparator.bottom - topMargin: Math.round(units.gridUnit / 3) - } securityType: SecurityType onAccepted: { stateChangeButton.clicked() } onAcceptableInputChanged: { stateChangeButton.enabled = acceptableInput } Component.onCompleted: { stateChangeButton.enabled = false } Component.onDestruction: { stateChangeButton.enabled = true } } } } + Timer { + id: timer + repeat: true + interval: 2000 + running: showSpeed + property real prevRxBytes + property real prevTxBytes + Component.onCompleted: { + prevRxBytes = RxBytes + prevTxBytes = TxBytes + } + onTriggered: { + rxBytes = (RxBytes - prevRxBytes) * 1000 / interval + txBytes = (TxBytes - prevTxBytes) * 1000 / interval + prevRxBytes = RxBytes + prevTxBytes = TxBytes + } + } + states: [ State { name: "collapsed" when: !(visibleDetails || visiblePasswordDialog) StateChangeScript { script: if (expandableComponentLoader.status == Loader.Ready) {expandableComponentLoader.sourceComponent = undefined} } }, State { name: "expandedDetails" when: visibleDetails StateChangeScript { script: createContent() } }, State { name: "expandedPasswordDialog" when: visiblePasswordDialog StateChangeScript { script: createContent() } PropertyChanges { target: stateChangeButton; opacity: 1 } } ] function createContent() { if (visibleDetails) { expandableComponentLoader.sourceComponent = detailsComponent } else if (visiblePasswordDialog) { expandableComponentLoader.sourceComponent = passwordDialogComponent expandableComponentLoader.item.passwordInput.forceActiveFocus() } } function changeState() { visibleDetails = false if (Uuid || !predictableWirelessPassword || visiblePasswordDialog) { if (ConnectionState == PlasmaNM.Enums.Deactivated) { if (!predictableWirelessPassword && !Uuid) { - handler.addAndActivateConnection(DevicePath, SpecificPath); + handler.addAndActivateConnection(DevicePath, SpecificPath) } else if (visiblePasswordDialog) { if (expandableComponentLoader.item.password != "") { - handler.addAndActivateConnection(DevicePath, SpecificPath, expandableComponentLoader.item.password); - visiblePasswordDialog = false; + handler.addAndActivateConnection(DevicePath, SpecificPath, expandableComponentLoader.item.password) + visiblePasswordDialog = false } else { - connectionItem.clicked(); + connectionItem.clicked() } } else { - handler.activateConnection(ConnectionPath, DevicePath, SpecificPath); + handler.activateConnection(ConnectionPath, DevicePath, SpecificPath) } } else { - handler.deactivateConnection(ConnectionPath, DevicePath); + handler.deactivateConnection(ConnectionPath, DevicePath) } } else if (predictableWirelessPassword) { - appletProxyModel.dynamicSortFilter = false; - visiblePasswordDialog = true; + appletProxyModel.dynamicSortFilter = false + visiblePasswordDialog = true } } function itemText() { if (ConnectionState == PlasmaNM.Enums.Activating) { if (Type == PlasmaNM.Enums.Vpn) - return VpnState; + return VpnState else - return DeviceState; + return DeviceState } else if (ConnectionState == PlasmaNM.Enums.Deactivating) { if (Type == PlasmaNM.Enums.Vpn) - return VpnState; + return VpnState else - return DeviceState; + return DeviceState } else if (ConnectionState == PlasmaNM.Enums.Deactivated) { - var result = LastUsed; + var result = LastUsed if (SecurityType > PlasmaNM.Enums.NoneSecurity) - result += ", " + SecurityTypeString; - return result; + result += ", " + SecurityTypeString + return result } else if (ConnectionState == PlasmaNM.Enums.Activated) { - if (showSpeed && dataSource.data && dataSource.data[dataSource.downloadSource] && dataSource.data[dataSource.uploadSource]) { - var downloadColor = theme.highlightColor; + if (showSpeed) { + var downloadColor = theme.highlightColor // cycle upload color by 180 degrees - var uploadColor = Qt.hsva((downloadColor.hsvHue + 0.5) % 1, downloadColor.hsvSaturation, downloadColor.hsvValue, downloadColor.a); + var uploadColor = Qt.hsva((downloadColor.hsvHue + 0.5) % 1, downloadColor.hsvSaturation, downloadColor.hsvValue, downloadColor.a) - return i18n("Connected, %2/s, %4/s", + return i18n("Connected, %2, %4", downloadColor, - KCoreAddons.Format.formatByteSize(dataSource.data[dataSource.downloadSource].value * 1024 || 0), + KCoreAddons.Format.formatByteSize(rxBytes), uploadColor, - KCoreAddons.Format.formatByteSize(dataSource.data[dataSource.uploadSource].value * 1024 || 0)); + KCoreAddons.Format.formatByteSize(txBytes)) } else { - return i18n("Connected"); + return i18n("Connected") } } } + onShowSpeedChanged: { + connectionModel.setDeviceStatisticsRefreshRateMs(DevicePath, showSpeed ? 2000 : 0) + } + onActivatingChanged: { if (ConnectionState == PlasmaNM.Enums.Activating) { ListView.view.positionViewAtBeginning() } } onClicked: { if (visiblePasswordDialog) { appletProxyModel.dynamicSortFilter = true visiblePasswordDialog = false } else { visibleDetails = !visibleDetails } if (visibleDetails || visiblePasswordDialog) { ListView.view.currentIndex = index } else { ListView.view.currentIndex = -1 } } onContainsMouseChanged: { if (connectionItem.containsMouse) { connectionView.currentVisibleButtonIndex = index } } } diff --git a/applet/contents/ui/Header.qml b/applet/contents/ui/Header.qml index 0a426f07..63c12f7d 100644 --- a/applet/contents/ui/Header.qml +++ b/applet/contents/ui/Header.qml @@ -1,99 +1,59 @@ /* Copyright 2013-2017 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ import QtQuick 2.2 import org.kde.plasma.components 2.0 as PlasmaComponents import org.kde.plasma.core 2.0 as PlasmaCore import org.kde.plasma.networkmanagement 0.2 as PlasmaNM PlasmaComponents.ListItem { id: header property alias text: headerLabel.text height: headerLabel.height + units.gridUnit; width: parent.width sectionDelegate: true PlasmaNM.EnabledConnections { id: enabledConnections } PlasmaComponents.Label { id: headerLabel anchors.centerIn: parent height: paintedHeight font.weight: Font.DemiBold } - /* INFO: Disabled for now as wifi scanning is now automatical - PlasmaComponents.ToolButton { - anchors { - top: parent.top - bottom: parent.bottom - margins: -Math.round(units.gridUnit / 3) - right: parent.right - rightMargin: units.gridUnit / 2 - } - width: height - flat: true - tooltip: i18n("Rescan wireless networks") - visible: (header.text === i18n("Available connections") || !connectionView.availableConnectionsVisible) && - enabledConnections.wirelessEnabled && enabledConnections.wirelessHwEnabled && availableDevices.wirelessDeviceAvailable - - onClicked: { - handler.requestScan(); - refreshAnimation.restart(); - } - - PlasmaCore.SvgItem { - anchors { - fill: parent - margins: Math.round(units.gridUnit / 3) - } - elementId: "view-refresh" - svg: PlasmaCore.FrameSvg { imagePath: "icons/view" } - - RotationAnimator on rotation { - id: refreshAnimation - - duration: 1000 - running: false - from: 0 - to: 720 - } - } - } - */ - Component.onCompleted: { if (header.text === i18n("Available connections")) { connectionView.availableConnectionsVisible = true } } Component.onDestruction: { connectionView.availableConnectionsVisible = false } onVisibleChanged: { connectionView.availableConnectionsVisible = visible } } diff --git a/applet/contents/ui/Separator.qml b/applet/contents/ui/Separator.qml deleted file mode 100644 index f28639d9..00000000 --- a/applet/contents/ui/Separator.qml +++ /dev/null @@ -1,29 +0,0 @@ -/* - Copyright 2013-2017 Jan Grulich - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) version 3, or any - later version accepted by the membership of KDE e.V. (or its - successor approved by the membership of KDE e.V.), which shall - act as a proxy defined in Section 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -import QtQuick 2.2 -import org.kde.plasma.core 2.0 as PlasmaCore - -PlasmaCore.SvgItem { - height: lineSvg.elementSize("horizontal-line").height; width: parent.width - elementId: "horizontal-line" - svg: PlasmaCore.Svg { id: lineSvg; imagePath: "widgets/line" } -} - diff --git a/applet/contents/ui/TrafficMonitor.qml b/applet/contents/ui/TrafficMonitor.qml index f9aee901..636b9bce 100644 --- a/applet/contents/ui/TrafficMonitor.qml +++ b/applet/contents/ui/TrafficMonitor.qml @@ -1,94 +1,98 @@ /* Copyright 2013-2017 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ import QtQuick 2.2 import org.kde.kcoreaddons 1.0 as KCoreAddons import org.kde.kquickcontrolsaddons 2.0 as KQuickControlsAddons import org.kde.plasma.components 2.0 as PlasmaComponents Item { - property QtObject dataEngine: null - property string deviceName + property real rxBytes: 0 + property real txBytes: 0 + property alias interval: timer.interval height: visible ? plotter.height + units.gridUnit : 0 Repeater { model: 5 PlasmaComponents.Label { anchors { left: parent.left top: parent.top topMargin: Math.round(units.gridUnit / 3) + (index * plotter.height / 5) } height: paintedHeight font.pointSize: theme.smallestFont.pointSize lineHeight: 1.75 - text: KCoreAddons.Format.formatByteSize((plotter.maxValue * 1024) * (1 - index / 5)) + text: KCoreAddons.Format.formatByteSize(plotter.maxValue * (1 - index / 5)) + i18n("/s") } } KQuickControlsAddons.Plotter { id: plotter - + property variant downloadColor: theme.highlightColor + property variant uploadColor: Qt.hsva((downloadColor.hsvHue + 0.5) % 1, downloadColor.hsvSaturation, downloadColor.hsvValue, downloadColor.a) // Joining two QList in QML/javascript doesn't seem to work so I'm getting maximum from both list separately readonly property int maxValue: Math.max(Math.max.apply(null, downloadPlotData.values), Math.max.apply(null, uploadPlotData.values)) anchors { left: parent.left leftMargin: units.gridUnit * 3 right: parent.right top: parent.top topMargin: units.gridUnit } width: units.gridUnit * 20 height: units.gridUnit * 8 horizontalGridLineCount: 5 dataSets: [ KQuickControlsAddons.PlotData { id: downloadPlotData label: i18n("Download") - color: theme.highlightColor + color: plotter.downloadColor }, KQuickControlsAddons.PlotData { id: uploadPlotData label: i18n("Upload") - color: cycle(theme.highlightColor, -180) + color: plotter.uploadColor } ] - Connections { - target: dataEngine; - onNewData: { - if (sourceName.indexOf("network/interfaces/" + deviceName) != 0) { - return; - } - var rx = dataEngine.data[dataEngine.downloadSource]; - var tx = dataEngine.data[dataEngine.uploadSource]; - if (rx === undefined || rx.value === undefined || - tx === undefined || tx.value === undefined) { - return; - } - - plotter.addSample([rx.value, tx.value]); + Timer { + id: timer + repeat: true + running: parent.visible + property real prevRxBytes + property real prevTxBytes + Component.onCompleted: { + prevRxBytes = rxBytes + prevTxBytes = txBytes + } + onTriggered: { + var rxSpeed = (rxBytes - prevRxBytes) * 1000 / interval + var txSpeed = (txBytes - prevTxBytes) * 1000 / interval + prevRxBytes = rxBytes + prevTxBytes = txBytes + plotter.addSample([rxSpeed, txSpeed]); } } } } diff --git a/applet/metadata.desktop b/applet/metadata.desktop index ff84402d..5fd51c81 100644 --- a/applet/metadata.desktop +++ b/applet/metadata.desktop @@ -1,110 +1,112 @@ [Desktop Entry] Name=Networks Name[ar]=الشّبكات -Name[ast]=Redes Name[bs]=Mreže Name[ca]=Xarxes Name[ca@valencia]=Xarxes Name[cs]=Sítě Name[da]=Netværk Name[de]=Netzwerke Name[el]=Δίκτυα Name[en_GB]=Networks Name[es]=Redes Name[et]=Võrgud Name[eu]=Sareak Name[fi]=Verkot Name[fr]=Réseaux Name[gl]=Redes Name[he]=רשתות Name[hu]=Hálózatok Name[ia]=Retes +Name[id]=Networks Name[it]=Reti Name[ko]=네트워크 Name[lt]=Tinklai Name[nb]=Nettverk Name[nds]=Nettwarken Name[nl]=Netwerken Name[nn]=Nettverk Name[pa]=ਨੈੱਟਵਰਕ Name[pl]=Sieci Name[pt]=Redes Name[pt_BR]=Redes Name[ru]=Сети Name[sk]=Siete Name[sl]=Omrežja Name[sr]=Мреже Name[sr@ijekavian]=Мреже Name[sr@ijekavianlatin]=Mreže Name[sr@latin]=Mreže Name[sv]=Nätverk Name[tr]=Ağlar Name[uk]=Мережі Name[x-test]=xxNetworksxx Name[zh_CN]=网络 Name[zh_TW]=網路 Comment=Network status and control Comment[ar]=حالة الشّبكة والتّحكّم بها Comment[bg]=Състояние и контрол на мрежата Comment[bs]=Kontrola i status mreže Comment[ca]=Control i estat de la xarxa Comment[ca@valencia]=Control i estat de la xarxa Comment[cs]=Stav a ovládání sítě Comment[da]=Status og kontrol over netværk Comment[de]=Netzwerkstatus und -steuerung Comment[el]=Κατάσταση δικτύου και έλεγχος Comment[en_GB]=Network status and control Comment[es]=Estado y control de redes Comment[et]=Võrgu olek ja juhtimine Comment[eu]=Sareen egoera eta kontrola Comment[fi]=Verkon tila ja hallinta Comment[fr]=État et contrôle du réseau Comment[gl]=Monitorización e control da rede Comment[he]=מצב ושליטה על הרשת Comment[hu]=Hálózatállapot és vezérlés Comment[ia]=Stato e controlo de rete +Comment[id]=Kendali dan status network Comment[it]=Stato e controllo della rete Comment[ko]=네트워크 상태 및 제어 Comment[lt]=Tinklo būsena ir kontrolė Comment[nb]=Nettverksstatus og styring Comment[nds]=Nettwarkstatus un -stüern Comment[nl]=Netwerkstatus en besturing Comment[nn]=Nettverksstatus og -styring Comment[pa]=ਨੈੱਟਵਰਕ ਹਾਲਤ ਅਤੇ ਕੰਟਰੋਲ Comment[pl]=Stan i obsługa sieci Comment[pt]=Estado e controlo da rede Comment[pt_BR]=Estado e controle da rede Comment[ro]=Starea și controlul rețelei Comment[ru]=Состояние и управление сетью Comment[sk]=Správa a ovládanie siete Comment[sl]=Stanje omrežja in nadzor Comment[sr]=Стање и управљање мрежом Comment[sr@ijekavian]=Стање и управљање мрежом Comment[sr@ijekavianlatin]=Stanje i upravljanje mrežom Comment[sr@latin]=Stanje i upravljanje mrežom Comment[sv]=Nätverksstatus och kontroll Comment[tr]=Ağ denetim ve durum izleme Comment[uk]=Стеження за станом і керування мережею Comment[x-test]=xxNetwork status and controlxx Comment[zh_CN]=网络状态和控制 Comment[zh_TW]=網路狀態與控制 Icon=org.kde.plasma.networkmanagement Type=Service X-KDE-ServiceTypes=Plasma/Applet X-Plasma-API=declarativeappletscript X-Plasma-MainScript=ui/main.qml X-Plasma-NotificationArea=true +X-Plasma-NotificationAreaCategory=Hardware X-Plasma-DBusActivationService=org.freedesktop.NetworkManager X-KDE-PluginInfo-Name=org.kde.plasma.networkmanagement X-KDE-PluginInfo-Category=System Information X-KDE-PluginInfo-Author=Jan Grulich,Lukáš Tinkl X-KDE-PluginInfo-Email=jgrulich@redhat.com,ltinkl@redhat.com X-KDE-PluginInfo-Version=1.0.0 X-KDE-PluginInfo-Website=https://projects.kde.org/projects/kde/workspace/plasma-nm X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=true diff --git a/kcm/CMakeLists.txt b/kcm/CMakeLists.txt index daaef060..7a89883a 100755 --- a/kcm/CMakeLists.txt +++ b/kcm/CMakeLists.txt @@ -1,44 +1,38 @@ include_directories(${CMAKE_SOURCE_DIR}/libs/editor ${CMAKE_SOURCE_DIR}/libs/editor/widgets) #KI18N Translation Domain for this library add_definitions(-DTRANSLATION_DOMAIN=\"plasmanetworkmanagement-kcm\") set(kcm_networkmanagement_PART_SRCS ../libs/debug.cpp kcm.cpp ) ki18n_wrap_ui(kcm_networkmanagement_PART_SRCS kcm.ui ) add_library(kcm_networkmanagement MODULE ${kcm_networkmanagement_PART_SRCS}) target_link_libraries(kcm_networkmanagement plasmanm_internal plasmanm_editor - Qt5::DBus Qt5::Quick - Qt5::QuickWidgets - Qt5::UiTools - KF5::Completion KF5::ConfigWidgets KF5::Declarative KF5::I18n - KF5::NetworkManagerQt - KF5::WindowSystem KF5::Service ) -install(TARGETS kcm_networkmanagement DESTINATION ${PLUGIN_INSTALL_DIR} ) +install(TARGETS kcm_networkmanagement DESTINATION ${KDE_INSTALL_PLUGINDIR} ) ########### install files ############### -install( FILES kcm_networkmanagement.desktop DESTINATION ${SERVICES_INSTALL_DIR} ) +install( FILES kcm_networkmanagement.desktop DESTINATION ${KDE_INSTALL_KSERVICES5DIR} ) install( FILES qml/ConnectionItem.qml qml/Dialog.qml qml/Header.qml qml/ListItem.qml qml/main.qml - DESTINATION ${DATA_INSTALL_DIR}/kcm_networkmanagement/qml) + DESTINATION ${KDE_INSTALL_DATADIR}/kcm_networkmanagement/qml) diff --git a/kcm/kcm.cpp b/kcm/kcm.cpp index 88e9b244..a8ff4846 100755 --- a/kcm/kcm.cpp +++ b/kcm/kcm.cpp @@ -1,523 +1,523 @@ /* Copyright 2016 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "kcm.h" #include "debug.h" #include "connectioneditordialog.h" #include "mobileconnectionwizard.h" #include "uiutils.h" #include "vpnuiplugin.h" // KDE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // Qt #include #include #include #include #include #include #include #include K_PLUGIN_FACTORY(KCMNetworkConfigurationFactory, registerPlugin();) KCMNetworkmanagement::KCMNetworkmanagement(QWidget *parent, const QVariantList &args) : KCModule(parent, args) , m_handler(new Handler(this)) , m_tabWidget(nullptr) , m_ui(new Ui::KCMForm) , m_quickView(nullptr) { QWidget *mainWidget = new QWidget(this); m_ui->setupUi(mainWidget); - m_quickView = new QQuickView(0); + m_quickView = new QQuickView(nullptr); KDeclarative::KDeclarative kdeclarative; kdeclarative.setDeclarativeEngine(m_quickView->engine()); kdeclarative.setTranslationDomain(QStringLiteral(TRANSLATION_DOMAIN)); kdeclarative.setupBindings(); QWidget *widget = QWidget::createWindowContainer(m_quickView, this); widget->setMinimumWidth(300); QVBoxLayout *layout = new QVBoxLayout(m_ui->connectionView); layout->addWidget(widget); m_quickView->rootContext()->setContextProperty("alternateBaseColor", mainWidget->palette().color(QPalette::Active, QPalette::AlternateBase)); m_quickView->rootContext()->setContextProperty("backgroundColor", mainWidget->palette().color(QPalette::Active, QPalette::Window)); m_quickView->rootContext()->setContextProperty("baseColor", mainWidget->palette().color(QPalette::Active, QPalette::Base)); m_quickView->rootContext()->setContextProperty("highlightColor", mainWidget->palette().color(QPalette::Active, QPalette::Highlight)); m_quickView->rootContext()->setContextProperty("textColor", mainWidget->palette().color(QPalette::Active, QPalette::Text)); m_quickView->rootContext()->setContextProperty("connectionModified", false); m_quickView->setResizeMode(QQuickView::SizeRootObjectToView); m_quickView->setSource(QUrl::fromLocalFile(QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("kcm_networkmanagement/qml/main.qml")))); QObject *rootItem = m_quickView->rootObject(); connect(rootItem, SIGNAL(selectedConnectionChanged(QString)), this, SLOT(onSelectedConnectionChanged(QString))); connect(rootItem, SIGNAL(requestCreateConnection(int,QString,QString,bool)), this, SLOT(onRequestCreateConnection(int,QString,QString,bool))); connect(rootItem, SIGNAL(requestExportConnection(QString)), this, SLOT(onRequestExportConnection(QString))); connect(rootItem, SIGNAL(requestToChangeConnection(QString,QString)), this, SLOT(onRequestToChangeConnection(QString,QString))); QVBoxLayout *l = new QVBoxLayout(this); l->addWidget(mainWidget); setButtons(Button::Apply); // Pre-select currently active primary connection and if there is none then just select // the very first connection NetworkManager::ActiveConnection::Ptr activeConnection = NetworkManager::primaryConnection(); if (activeConnection && activeConnection->isValid()) { // Also check if the connection type is supported by KCM const NetworkManager::ConnectionSettings::ConnectionType type = activeConnection->type(); if (UiUtils::isConnectionTypeSupported(type)) { QMetaObject::invokeMethod(rootItem, "selectConnection", Q_ARG(QVariant, activeConnection->id()), Q_ARG(QVariant, activeConnection->connection()->path())); } } else { // Select first connection NetworkManager::Connection::List connectionList = NetworkManager::listConnections(); std::sort(connectionList.begin(), connectionList.end(), [] (const NetworkManager::Connection::Ptr &left, const NetworkManager::Connection::Ptr &right) { const QString leftName = left->settings()->id(); const UiUtils::SortedConnectionType leftType = UiUtils::connectionTypeToSortedType(left->settings()->connectionType()); const QDateTime leftDate = left->settings()->timestamp(); const QString rightName = right->settings()->id(); const UiUtils::SortedConnectionType rightType = UiUtils::connectionTypeToSortedType(right->settings()->connectionType()); const QDateTime rightDate = right->settings()->timestamp(); if (leftType < rightType) { return true; } else if (leftType > rightType) { return false; } if (leftDate > rightDate) { return true; } else if (leftDate < rightDate) { return false; } if (QString::localeAwareCompare(leftName, rightName) > 0) { return true; } else { return false; } }); Q_FOREACH (const NetworkManager::Connection::Ptr &connection, connectionList) { const NetworkManager::ConnectionSettings::ConnectionType type = connection->settings()->connectionType(); if (UiUtils::isConnectionTypeSupported(type)) { QMetaObject::invokeMethod(rootItem, "selectConnection", Q_ARG(QVariant, connection->settings()->id()), Q_ARG(QVariant, connection->path())); break; } } } connect(NetworkManager::settingsNotifier(), &NetworkManager::SettingsNotifier::connectionAdded, this, &KCMNetworkmanagement::onConnectionAdded, Qt::UniqueConnection); // Initialize first scan and then scan every 15 seconds m_handler->requestScan(); m_timer = new QTimer(this); m_timer->setInterval(15000); connect(m_timer, &QTimer::timeout, [this] () { m_handler->requestScan(); m_timer->start(); }); m_timer->start(); } KCMNetworkmanagement::~KCMNetworkmanagement() { delete m_handler; if (m_tabWidget) { delete m_tabWidget; } delete m_quickView; delete m_ui; } void KCMNetworkmanagement::defaults() { KCModule::defaults(); } void KCMNetworkmanagement::load() { // If there is no loaded connection do nothing if (m_currentConnectionPath.isEmpty()) { return; } NetworkManager::Connection::Ptr connection = NetworkManager::findConnection(m_currentConnectionPath); if (connection) { NetworkManager::ConnectionSettings::Ptr connectionSettings = connection->settings(); // Re-load the connection again to load stored values if (m_tabWidget) { m_tabWidget->setConnection(connectionSettings); } } KCModule::load(); } void KCMNetworkmanagement::save() { NetworkManager::Connection::Ptr connection = NetworkManager::findConnection(m_currentConnectionPath); if (connection) { m_handler->updateConnection(connection, m_tabWidget->setting()); } kcmChanged(false); KCModule::save(); } void KCMNetworkmanagement::onConnectionAdded(const QString &connection) { if (m_createdConnectionUuid.isEmpty()) { return; } NetworkManager::Connection::Ptr newConnection = NetworkManager::findConnection(connection); if (newConnection) { NetworkManager::ConnectionSettings::Ptr connectionSettings = newConnection->settings(); if (connectionSettings && connectionSettings->uuid() == m_createdConnectionUuid) { QObject *rootItem = m_quickView->rootObject(); loadConnectionSettings(connectionSettings); QMetaObject::invokeMethod(rootItem, "selectConnection", Q_ARG(QVariant, connectionSettings->id()), Q_ARG(QVariant, newConnection->path())); m_createdConnectionUuid.clear(); } } } void KCMNetworkmanagement::onRequestCreateConnection(int connectionType, const QString &vpnType, const QString &specificType, bool shared) { NetworkManager::ConnectionSettings::ConnectionType type = static_cast(connectionType); if (type == NetworkManager::ConnectionSettings::Vpn && vpnType == "imported") { importVpn(); } else if (type == NetworkManager::ConnectionSettings::Gsm) { // launch the mobile broadband wizard, both gsm/cdma #if WITH_MODEMMANAGER_SUPPORT QPointer wizard = new MobileConnectionWizard(NetworkManager::ConnectionSettings::Unknown, this); connect(wizard.data(), &MobileConnectionWizard::accepted, [wizard, this] () { if (wizard->getError() == MobileProviders::Success) { qCDebug(PLASMA_NM) << "Mobile broadband wizard finished:" << wizard->type() << wizard->args(); if (wizard->args().count() == 2) { QVariantMap tmp = qdbus_cast(wizard->args().value(1)); NetworkManager::ConnectionSettings::Ptr connectionSettings; connectionSettings = NetworkManager::ConnectionSettings::Ptr(new NetworkManager::ConnectionSettings(wizard->type())); connectionSettings->setId(wizard->args().value(0).toString()); if (wizard->type() == NetworkManager::ConnectionSettings::Gsm) { NetworkManager::GsmSetting::Ptr gsmSetting = connectionSettings->setting(NetworkManager::Setting::Gsm).staticCast(); gsmSetting->fromMap(tmp); gsmSetting->setPasswordFlags(NetworkManager::Setting::NotRequired); gsmSetting->setPinFlags(NetworkManager::Setting::NotRequired); } else if (wizard->type() == NetworkManager::ConnectionSettings::Cdma) { connectionSettings->setting(NetworkManager::Setting::Cdma)->fromMap(tmp); } else { qCWarning(PLASMA_NM) << Q_FUNC_INFO << "Unhandled setting type"; } // Generate new UUID connectionSettings->setUuid(NetworkManager::ConnectionSettings::createNewUuid()); addConnection(connectionSettings); } else { qCWarning(PLASMA_NM) << Q_FUNC_INFO << "Unexpected number of args to parse"; } } }); connect(wizard.data(), &MobileConnectionWizard::finished, [wizard] () { if (wizard) { wizard->deleteLater(); } }); wizard->setModal(true); wizard->show(); #endif } else { NetworkManager::ConnectionSettings::Ptr connectionSettings; connectionSettings = NetworkManager::ConnectionSettings::Ptr(new NetworkManager::ConnectionSettings(type)); if (type == NetworkManager::ConnectionSettings::Vpn) { NetworkManager::VpnSetting::Ptr vpnSetting = connectionSettings->setting(NetworkManager::Setting::Vpn).dynamicCast(); vpnSetting->setServiceType(vpnType); // Set VPN subtype in case of Openconnect to add support for juniper if (vpnType == QLatin1String("org.freedesktop.NetworkManager.openconnect")) { NMStringMap data = vpnSetting->data(); data.insert(QLatin1String("protocol"), specificType); vpnSetting->setData(data); } } if (type == NetworkManager::ConnectionSettings::Wired || type == NetworkManager::ConnectionSettings::Wireless) { // Set auto-negotiate to true, NM sets it to false by default, but we used to have this before and also // I don't think it's wise to request users to specify speed and duplex as most of them don't know what is that // and what to set if (type == NetworkManager::ConnectionSettings::Wired) { NetworkManager::WiredSetting::Ptr wiredSetting = connectionSettings->setting(NetworkManager::Setting::Wired).dynamicCast(); wiredSetting->setAutoNegotiate(true); } if (shared) { if (type == NetworkManager::ConnectionSettings::Wireless) { NetworkManager::WirelessSetting::Ptr wifiSetting = connectionSettings->setting(NetworkManager::Setting::Wireless).dynamicCast(); wifiSetting->setMode(NetworkManager::WirelessSetting::Adhoc); wifiSetting->setSsid(i18n("my_shared_connection").toUtf8()); Q_FOREACH (const NetworkManager::Device::Ptr & device, NetworkManager::networkInterfaces()) { if (device->type() == NetworkManager::Device::Wifi) { NetworkManager::WirelessDevice::Ptr wifiDev = device.objectCast(); if (wifiDev) { if (wifiDev->wirelessCapabilities().testFlag(NetworkManager::WirelessDevice::ApCap)) { wifiSetting->setMode(NetworkManager::WirelessSetting::Ap); wifiSetting->setMacAddress(NetworkManager::macAddressFromString(wifiDev->permanentHardwareAddress())); } } } } } NetworkManager::Ipv4Setting::Ptr ipv4Setting = connectionSettings->setting(NetworkManager::Setting::Ipv4).dynamicCast(); ipv4Setting->setMethod(NetworkManager::Ipv4Setting::Shared); connectionSettings->setAutoconnect(false); } } // Generate new UUID connectionSettings->setUuid(NetworkManager::ConnectionSettings::createNewUuid()); addConnection(connectionSettings); } } void KCMNetworkmanagement::onRequestExportConnection(const QString &connectionPath) { NetworkManager::Connection::Ptr connection = NetworkManager::findConnection(connectionPath); if (!connection) { return; } NetworkManager::ConnectionSettings::Ptr connSettings = connection->settings(); if (connSettings->connectionType() != NetworkManager::ConnectionSettings::Vpn) return; NetworkManager::VpnSetting::Ptr vpnSetting = connSettings->setting(NetworkManager::Setting::Vpn).dynamicCast(); qCDebug(PLASMA_NM) << "Exporting VPN connection" << connection->name() << "type:" << vpnSetting->serviceType(); QString error; VpnUiPlugin * vpnPlugin = KServiceTypeTrader::createInstanceFromQuery(QStringLiteral("PlasmaNetworkManagement/VpnUiPlugin"), QStringLiteral("[X-NetworkManager-Services]=='%1'").arg(vpnSetting->serviceType()), this, QVariantList(), &error); if (vpnPlugin) { if (vpnPlugin->suggestedFileName(connSettings).isEmpty()) { // this VPN doesn't support export qCWarning(PLASMA_NM) << "This VPN doesn't support export"; return; } const QString url = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + QDir::separator() + vpnPlugin->suggestedFileName(connSettings); const QString filename = QFileDialog::getSaveFileName(this, i18n("Export VPN Connection"), url, vpnPlugin->supportedFileExtensions()); if (!filename.isEmpty()) { if (!vpnPlugin->exportConnectionSettings(connSettings, filename)) { // TODO display failure qCWarning(PLASMA_NM) << "Failed to export VPN connection"; } else { // TODO display success } } delete vpnPlugin; } else { qCWarning(PLASMA_NM) << "Error getting VpnUiPlugin for export:" << error; } } void KCMNetworkmanagement::onRequestToChangeConnection( const QString &connectionName, const QString &connectionPath) { NetworkManager::Connection::Ptr connection = NetworkManager::findConnection(m_currentConnectionPath); if (connection) { if (KMessageBox::questionYesNo(this, i18n("Do you want to save changes made to the connection '%1'?", connection->name()), i18nc("@title:window", "Save Changes"), KStandardGuiItem::save(), KStandardGuiItem::discard(), QString(), KMessageBox::Notify) == KMessageBox::Yes) { save(); } } QObject *rootItem = m_quickView->rootObject(); QMetaObject::invokeMethod(rootItem, "selectConnection", Q_ARG(QVariant, connectionName), Q_ARG(QVariant, connectionPath)); } void KCMNetworkmanagement::onSelectedConnectionChanged(const QString &connectionPath) { if (connectionPath.isEmpty()) { resetSelection(); return; } m_currentConnectionPath = connectionPath; NetworkManager::Connection::Ptr connection = NetworkManager::findConnection(m_currentConnectionPath); if (connection) { NetworkManager::ConnectionSettings::Ptr connectionSettings = connection->settings(); loadConnectionSettings(connectionSettings); } } void KCMNetworkmanagement::addConnection(const NetworkManager::ConnectionSettings::Ptr &connectionSettings) { QPointer editor = new ConnectionEditorDialog(connectionSettings); connect(editor.data(), &ConnectionEditorDialog::accepted, [connectionSettings, editor, this] () { // We got confirmation so watch this connection and select it once it is created m_createdConnectionUuid = connectionSettings->uuid(); m_handler->addConnection(editor->setting()); }); connect(editor.data(), &ConnectionEditorDialog::finished, [editor] () { if (editor) { editor->deleteLater(); } }); editor->setModal(true); editor->show(); } void KCMNetworkmanagement::kcmChanged(bool kcmChanged) { m_quickView->rootContext()->setContextProperty("connectionModified", kcmChanged); Q_EMIT changed(kcmChanged); } void KCMNetworkmanagement::loadConnectionSettings(const NetworkManager::ConnectionSettings::Ptr& connectionSettings) { if (m_tabWidget) { m_tabWidget->setConnection(connectionSettings); } else { m_tabWidget = new ConnectionEditorTabWidget(connectionSettings); connect(m_tabWidget, &ConnectionEditorTabWidget::settingChanged, [this] () { if (m_tabWidget->isInitialized() && m_tabWidget->isValid()) { kcmChanged(true); } }); connect(m_tabWidget, &ConnectionEditorTabWidget::validityChanged, [this] (bool valid) { if (m_tabWidget->isInitialized()) { kcmChanged(valid); } }); QVBoxLayout *layout = new QVBoxLayout(m_ui->connectionConfiguration); layout->addWidget(m_tabWidget); } kcmChanged(false); } void KCMNetworkmanagement::importVpn() { // get the list of supported extensions const KService::List services = KServiceTypeTrader::self()->query("PlasmaNetworkManagement/VpnUiPlugin"); QString extensions; Q_FOREACH (const KService::Ptr &service, services) { VpnUiPlugin * vpnPlugin = service->createInstance(this); if (vpnPlugin) { extensions += vpnPlugin->supportedFileExtensions() % QStringLiteral(" "); delete vpnPlugin; } } const QString &filename = QFileDialog::getOpenFileName(this, i18n("Import VPN Connection"), QDir::homePath(), extensions.simplified()); if (!filename.isEmpty()) { const KService::List services = KServiceTypeTrader::self()->query("PlasmaNetworkManagement/VpnUiPlugin"); QFileInfo fi(filename); const QString ext = QStringLiteral("*.") % fi.suffix(); qCDebug(PLASMA_NM) << "Importing VPN connection " << filename << "extension:" << ext; Q_FOREACH (const KService::Ptr &service, services) { VpnUiPlugin * vpnPlugin = service->createInstance(this); if (vpnPlugin && vpnPlugin->supportedFileExtensions().contains(ext)) { qCDebug(PLASMA_NM) << "Found VPN plugin" << service->name() << ", type:" << service->property("X-NetworkManager-Services", QVariant::String).toString(); NMVariantMapMap connection = vpnPlugin->importConnectionSettings(filename); // qCDebug(PLASMA_NM) << "Raw connection:" << connection; NetworkManager::ConnectionSettings connectionSettings; connectionSettings.fromMap(connection); connectionSettings.setUuid(NetworkManager::ConnectionSettings::createNewUuid()); // qCDebug(PLASMA_NM) << "Converted connection:" << connectionSettings; m_handler->addConnection(connectionSettings.toMap()); // qCDebug(PLASMA_NM) << "Adding imported connection under id:" << conId; if (connection.isEmpty()) { // the "positive" part will arrive with connectionAdded // TODO display success } else { delete vpnPlugin; break; // stop iterating over the plugins if the import produced at least some output } delete vpnPlugin; } } } } void KCMNetworkmanagement::resetSelection() { // Reset selected connections m_currentConnectionPath.clear(); QObject *rootItem = m_quickView->rootObject(); QMetaObject::invokeMethod(rootItem, "deselectConnections"); if (m_tabWidget) { delete m_ui->connectionConfiguration->layout(); delete m_tabWidget; m_tabWidget = nullptr; } Q_EMIT changed(false); } #include "kcm.moc" diff --git a/kcm/kcm.h b/kcm/kcm.h index 462c99c0..a232fa35 100755 --- a/kcm/kcm.h +++ b/kcm/kcm.h @@ -1,67 +1,67 @@ /* Copyright 2016 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_KCM_H #define PLASMA_NM_KCM_H #include "connectioneditortabwidget.h" #include "handler.h" #include #include class QQuickView; class KCMNetworkmanagement : public KCModule { Q_OBJECT public: explicit KCMNetworkmanagement(QWidget *parent = nullptr, const QVariantList &args = QVariantList()); - virtual ~KCMNetworkmanagement(); + ~KCMNetworkmanagement() override; public Q_SLOTS: void defaults() override; void load() override; void save() override; private Q_SLOTS: void onConnectionAdded(const QString &connection); void onSelectedConnectionChanged(const QString &connectionPath); void onRequestCreateConnection(int connectionType, const QString &vpnType, const QString &specificType, bool shared); void onRequestExportConnection(const QString &connectionPath); void onRequestToChangeConnection(const QString &connectionName, const QString &connectionPath); private: void addConnection(const NetworkManager::ConnectionSettings::Ptr &connectionSettings); void importVpn(); void kcmChanged(bool kcmChanged); void loadConnectionSettings(const NetworkManager::ConnectionSettings::Ptr &connectionSettings); void resetSelection(); QString m_currentConnectionPath; QString m_createdConnectionUuid; Handler *m_handler; ConnectionEditorTabWidget *m_tabWidget; QTimer *m_timer; Ui::KCMForm *m_ui; QQuickView *m_quickView; }; #endif diff --git a/kcm/kcm_networkmanagement.desktop b/kcm/kcm_networkmanagement.desktop index 70aba9b1..8c41e955 100755 --- a/kcm/kcm_networkmanagement.desktop +++ b/kcm/kcm_networkmanagement.desktop @@ -1,122 +1,125 @@ [Desktop Entry] Exec=kcmshell5 kcm_networkmanagement Icon=preferences-system-network Type=Service X-KDE-ServiceTypes=KCModule X-KDE-Library=kcm_networkmanagement X-KDE-ParentApp=kcontrol X-KDE-System-Settings-Parent-Category=network X-KDE-Weight=40 Name=Connections Name[ar]=الاتّصالات Name[ca]=Connexions Name[ca@valencia]=Connexions Name[cs]=Spojení Name[da]=Forbindelser Name[de]=Verbindungen Name[el]=Συνδέσεις Name[en_GB]=Connections Name[es]=Conexiones Name[eu]=Konexioak Name[fi]=Yhteydet Name[fr]=Connexions Name[gl]=Conexións Name[he]=חיבורים Name[hu]=Kapcsolatok +Name[id]=Connections Name[it]=Connessioni Name[ko]=연결 Name[lt]=Ryšiai Name[nl]=Verbindingen Name[nn]=Tilkoplingar Name[pa]=ਕਨੈਕਸ਼ਨ Name[pl]=Połączenia Name[pt]=Ligações Name[pt_BR]=Conexões Name[ru]=Соединения Name[sk]=Pripojenia Name[sl]=Povezave Name[sr]=Везе Name[sr@ijekavian]=Везе Name[sr@ijekavianlatin]=Veze Name[sr@latin]=Veze Name[sv]=Anslutningar Name[tr]=Bağlantılar Name[uk]=З’єднання Name[x-test]=xxConnectionsxx Name[zh_CN]=连接 Name[zh_TW]=連線 Comment=Edit your Network Connections Comment[ar]=حرّر اتّصالاتك الشّبكيّة Comment[ca]=Edita les connexions de xarxa Comment[ca@valencia]=Edita les connexions de xarxa Comment[cs]=Upravit vaše síťová spojení Comment[da]=Redigér dine netværksforbindelser Comment[de]=Bearbeiten Sie Ihre Netzwerkverbindungen Comment[el]=Επεξεργασία των συνδέσεων δικτύου Comment[en_GB]=Edit your Network Connections Comment[es]=Editar las conexiones de red Comment[eu]=Editatu zure sareko konexioak Comment[fi]=Verkkoyhteyksien muokkaus Comment[fr]=Modifier vos connexions réseau Comment[gl]=Edite as súas conexións de rede Comment[he]=ערוך את חיבורי הרשת שלך Comment[hu]=A hálózati kapcsolatok szerkesztése +Comment[id]=Edit Koneksi Networkmu Comment[it]=Modifica le tue connessioni di rete Comment[ko]=네트워크 연결 편집 Comment[lt]=Keisti tinklo ryšius Comment[nl]=Bewerk uw netwerkverbindingen Comment[nn]=Rediger nettverkstilkoplingar Comment[pa]=ਆਪਣੇ ਨੈੱਟਵਰਕ ਕਨੈਕਸ਼ਨਾਂ ਨੂੰ ਸੋਧੋ Comment[pl]=Edytuj swoje połączenia sieciowe Comment[pt]=Editar as Suas Ligações de Rede Comment[pt_BR]=Edite suas conexões de rede Comment[ru]=Настройка сетевых соединений Comment[sk]=Upraviť vaše sieťové pripojenia Comment[sl]=Uredite vaše omrežne povezave Comment[sr]=Уређујте мрежне везе Comment[sr@ijekavian]=Уређујте мрежне везе Comment[sr@ijekavianlatin]=Uređujte mrežne veze Comment[sr@latin]=Uređujte mrežne veze Comment[sv]=Redigera dina nätverksanslutningar Comment[tr]=Ağ bağlantılarınızı düzenleyin Comment[uk]=Редагування ваших записів з’єднань з мережею Comment[x-test]=xxEdit your Network Connectionsxx Comment[zh_CN]=编辑您的网络连接 Comment[zh_TW]=編輯您的網路連線 X-KDE-Keywords=network,wifi,ethernet,mobile,broadband,vpn,internet,traffic X-KDE-Keywords[ar]=شبكة,واي,فاي,إيثرنت,ايثرنت,هاتف,برودباند,vpn,إنترنت,انترنت X-KDE-Keywords[ca]=xarxa,wifi,ethernet,mòbil,banda ampla,vpn,internet,tràfic X-KDE-Keywords[ca@valencia]=xarxa,wifi,ethernet,mòbil,banda ampla,vpn,internet,tràfic X-KDE-Keywords[da]=netværk,wifi,ethernet,mobilt,bredbånd,vpn,internet,trafik X-KDE-Keywords[de]=network,wifi,ethernet,mobile,broadband,vpn,internet,traffic,netzwerk,mobil,breitband X-KDE-Keywords[el]=δίκτυο,wifi,ethernet,κινητό,ευρυζωνική,vpn,internet,κίνηση X-KDE-Keywords[en_GB]=network,wifi,ethernet,mobile,broadband,vpn,internet,traffic X-KDE-Keywords[es]=red,wifi,ethernet,móvil,banda ancha,vpn,internet,tráfico X-KDE-Keywords[eu]=sarea,wifi,ethernet,mugikor,banda zabala,vpn,internet,trafikoa X-KDE-Keywords[fi]=verkko,langaton,ethernet,mobiili,laajakaista,vpn,internet,liikenne X-KDE-Keywords[fr]=réseau,wifi,ethernet,mobile,large bande,vpn,internet,traffic X-KDE-Keywords[gl]=network,rede,wifi,ethernet,mobile,móbil,broadband,banda larga,vpn,internet,traffic,tráfico X-KDE-Keywords[he]=network,wifi,ethernet,mobile,broadband,vpn,internet,traffic,רשת,ויפי,אינטרנט,תעבורה X-KDE-Keywords[hu]=hálózat,wifi,ethernet,mobil,szélessáv,vpn,internet,forgalom +X-KDE-Keywords[id]=network,wifi,ethernet,mobile,broadband,vpn,internet,traffic X-KDE-Keywords[it]=rete,wifi,ethernet,mobile,banda larga,vpn,internet,traffico X-KDE-Keywords[ko]=network,wifi,ethernet,mobile,broadband,vpn,internet,traffic,네트워크,와이파이,무선랜,이더넷,모바일,광대역,인터넷,트래픽 X-KDE-Keywords[nl]=netwerk,wifi,ethernet,mobiel,breedband,vpn,internet,verkeer X-KDE-Keywords[nn]=nettverk,wifi,trådlaus,Ethernet,mobilt,breiband,VPN,Internett,trafikk,tilkopling,samband X-KDE-Keywords[pa]=ਨੈੱਟਵਰਕ,ਵਾਈਫਾਈ,ਵਾਈ-ਫਾਈ,ਮੋਬਾਈਲ,ਬਰਾਂਡਬੈਂਡ,ਵੀਪੀਐਨ,ਇੰਟਰਨੈੱਟ,ਟਰੈਫਿਕ X-KDE-Keywords[pl]=sieć,wifi,ethernet,komórkowy,mobilny,przenośny,szerokopasmowy,vpn,internet,ruch X-KDE-Keywords[pt]=rede,wifi,ethernet,móvel,banda larga,vpn,internet,tráfego X-KDE-Keywords[pt_BR]=rede,wifi,ethernet,cabeada,móvel,modem,vpn,internet,tráfego X-KDE-Keywords[ru]=network,wifi,ethernet,mobile,broadband,vpn,internet,traffic,сеть,беспроводная сеть,мобильный Интернет,широкополосная сеть,Интернет,трафик,вайфай,впн,виртуальная частная сеть,локальная сеть X-KDE-Keywords[sk]=sieť,wifi,ethernet,mobil,broadband,vpn,internet,prenos X-KDE-Keywords[sl]=omrežje,mreža,wifi,eternet,mobilno,širokopasovno,vpn,internet,promet X-KDE-Keywords[sr]=network,wifi,ethernet,mobile,broadband,vpn,internet,traffic,мрежа,вај‑фај,етернет,мобилни,широкопојасни,ВПН,Интернет,саобраћај X-KDE-Keywords[sr@ijekavian]=network,wifi,ethernet,mobile,broadband,vpn,internet,traffic,мрежа,вај‑фај,етернет,мобилни,широкопојасни,ВПН,Интернет,саобраћај X-KDE-Keywords[sr@ijekavianlatin]=network,wifi,ethernet,mobile,broadband,vpn,internet,traffic,mreža,Wi‑Fi,Ethernet,mobilni,širokopojasni,VPN,Internet,saobraćaj X-KDE-Keywords[sr@latin]=network,wifi,ethernet,mobile,broadband,vpn,internet,traffic,mreža,Wi‑Fi,Ethernet,mobilni,širokopojasni,VPN,Internet,saobraćaj X-KDE-Keywords[sv]=nätverk,wifi,ethernet,mobil,bredband,vpn,internet,trafik X-KDE-Keywords[tr]=ağ,wifi,ethernet,mobil,geniş bant,VPN,internet,trafik,kablosuz X-KDE-Keywords[uk]=network,wifi,ethernet,mobile,broadband,vpn,internet,traffic,мережа,вайфай,езернет,мобільна,широкосмугова,впн,інтернет,обмін,даними X-KDE-Keywords[x-test]=xxnetworkxx,xxwifixx,xxethernetxx,xxmobilexx,xxbroadbandxx,xxvpnxx,xxinternetxx,xxtrafficxx X-KDE-Keywords[zh_CN]=network,wifi,ethernet,mobile,broadband,vpn,internet,traffic,网络,无线,以太网,移动,宽带,互联网,因特网,流量 X-KDE-Keywords[zh_TW]=network,wifi,ethernet,mobile,broadband,vpn,internet,traffic diff --git a/kcm/qml/main.qml b/kcm/qml/main.qml index e8c4b2eb..d8f7a7c3 100755 --- a/kcm/qml/main.qml +++ b/kcm/qml/main.qml @@ -1,214 +1,214 @@ /* Copyright 2016 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ import QtQuick 2.1 import QtQuick.Dialogs 1.1 import QtQuick.Controls 1.2 as QtControls import org.kde.plasma.core 2.0 as PlasmaCore import org.kde.plasma.extras 2.0 as PlasmaExtras import org.kde.plasma.networkmanagement 0.2 as PlasmaNM Item { id: root anchors.fill: parent focus: true signal selectedConnectionChanged(string connection) signal requestCreateConnection(int type, string vpnType, string specificType, bool shared) signal requestExportConnection(string connection) signal requestToChangeConnection(string name, string path) Rectangle { id: background anchors.fill: parent focus: true color: baseColor } PlasmaNM.Handler { id: handler } PlasmaNM.KcmIdentityModel { id: connectionModel } PlasmaNM.EditorProxyModel { id: editorProxyModel sourceModel: connectionModel } QtControls.TextField { id: searchField anchors { left: parent.left right: parent.right top: parent.top } placeholderText: i18n("Type here to search connections...") onTextChanged: { editorProxyModel.setFilterRegExp(text) } } - PlasmaExtras.ScrollArea { + QtControls.ScrollView { id: scrollView anchors { bottom: buttonRow.top bottomMargin: Math.round(units.gridUnit / 3) left: parent.left right: parent.right top: searchField.bottom } ListView { id: connectionView property bool currentConnectionExportable: false property string currentConnectionName property string currentConnectionPath anchors.fill: parent clip: true model: editorProxyModel currentIndex: -1 boundsBehavior: Flickable.StopAtBounds section.property: "KcmConnectionType" section.delegate: Header { text: section } delegate: ConnectionItem { onAboutToChangeConnection: { // Shouldn't be problem to set this in advance connectionView.currentConnectionExportable = exportable if (connectionModified) { requestToChangeConnection(name, path) } else { connectionView.currentConnectionName = name connectionView.currentConnectionPath = path } } onAboutToExportConnection: { requestExportConnection(path) } onAboutToRemoveConnection: { deleteConfirmationDialog.connectionName = name deleteConfirmationDialog.connectionPath = path deleteConfirmationDialog.open() } } onCurrentConnectionPathChanged: { root.selectedConnectionChanged(currentConnectionPath) } } } Row { id: buttonRow anchors { bottom: parent.bottom right: parent.right margins: Math.round(units.gridUnit / 3) } spacing: Math.round(units.gridUnit / 2) QtControls.ToolButton { id: addConnectionButton iconName: "list-add" tooltip: i18n("Add new connection") onClicked: { addNewConnectionDialog.open() } } QtControls.ToolButton { id: removeConnectionButton enabled: connectionView.currentConnectionPath && connectionView.currentConnectionPath.length iconName: "list-remove" tooltip: i18n("Remove selected connection") onClicked: { deleteConfirmationDialog.connectionName = connectionView.currentConnectionName deleteConfirmationDialog.connectionPath = connectionView.currentConnectionPath deleteConfirmationDialog.open() } } QtControls.ToolButton { id: exportConnectionButton enabled: connectionView.currentConnectionExportable iconName: "document-export" tooltip: i18n("Export selected connection") onClicked: { root.requestExportConnection(connectionView.currentConnectionPath) } } } MessageDialog { id: deleteConfirmationDialog property string connectionName property string connectionPath icon: StandardIcon.Question standardButtons: StandardButton.Ok | StandardButton.Cancel title: i18nc("@title:window", "Remove Connection") text: i18n("Do you want to remove the connection '%1'?", connectionName) onAccepted: { if (connectionPath == connectionView.currentConnectionPath) { // Deselect now non-existing connection deselectConnections() } handler.removeConnection(connectionPath) } } Dialog { id: addNewConnectionDialog onRequestCreateConnection: { root.requestCreateConnection(type, vpnType, specificType, shared) } } function deselectConnections() { connectionView.currentConnectionPath = "" } function selectConnection(connectionName, connectionPath) { connectionView.currentConnectionName = connectionName connectionView.currentConnectionPath = connectionPath } } diff --git a/kded/CMakeLists.txt b/kded/CMakeLists.txt index 5a10c0fb..7d6b7864 100644 --- a/kded/CMakeLists.txt +++ b/kded/CMakeLists.txt @@ -1,68 +1,62 @@ add_definitions(-DTRANSLATION_DOMAIN=\"plasmanetworkmanagement-kded\") include_directories(${CMAKE_SOURCE_DIR}/libs/editor/widgets) if (WITH_MODEMMANAGER_SUPPORT) set(kded_networkmanagement_SRCS ../libs/debug.cpp bluetoothmonitor.cpp notification.cpp modemmonitor.cpp monitor.cpp passworddialog.cpp pindialog.cpp portalmonitor.cpp secretagent.cpp service.cpp ) ki18n_wrap_ui(kded_networkmanagement_SRCS pinwidget.ui passworddialog.ui ) else() set(kded_networkmanagement_SRCS ../libs/debug.cpp bluetoothmonitor.cpp notification.cpp monitor.cpp passworddialog.cpp portalmonitor.cpp secretagent.cpp service.cpp ) ki18n_wrap_ui(kded_networkmanagement_SRCS passworddialog.ui ) endif() add_library(kded_networkmanagement MODULE ${kded_networkmanagement_SRCS}) set_target_properties(kded_networkmanagement PROPERTIES OUTPUT_NAME networkmanagement) kcoreaddons_desktop_to_json(kded_networkmanagement networkmanagement.desktop) target_link_libraries(kded_networkmanagement plasmanm_internal plasmanm_editor - Qt5::Widgets - Qt5::Network - Qt5::DBus - KF5::NetworkManagerQt KF5::Service KF5::Solid - KF5::Completion + KF5::ConfigCore KF5::I18n - KF5::WidgetsAddons KF5::DBusAddons KF5::Notifications + KF5::IconThemes KF5::Wallet KF5::WindowSystem - KF5::KIOWidgets - KF5::CoreAddons ) if (WITH_MODEMMANAGER_SUPPORT) target_link_libraries(kded_networkmanagement KF5::ModemManagerQt) endif() -install(TARGETS kded_networkmanagement DESTINATION ${PLUGIN_INSTALL_DIR}/kf5/kded) +install(TARGETS kded_networkmanagement DESTINATION ${KDE_INSTALL_PLUGINDIR}/kf5/kded) -install(FILES networkmanagement.notifyrc DESTINATION ${KNOTIFYRC_INSTALL_DIR}) +install(FILES networkmanagement.notifyrc DESTINATION ${KDE_INSTALL_KNOTIFY5RCDIR}) diff --git a/kded/bluetoothmonitor.cpp b/kded/bluetoothmonitor.cpp index 6e12e8e4..99d85fbc 100644 --- a/kded/bluetoothmonitor.cpp +++ b/kded/bluetoothmonitor.cpp @@ -1,146 +1,146 @@ /* Copyright 2011 Lamarque Souza Copyright 2013 Lukas Tinkl Copyright 2013-2014 Jan Grulich Copyright 2015 David Rosca This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "bluetoothmonitor.h" #include "debug.h" #include #include #include #include #include #include #include BluetoothMonitor::BluetoothMonitor(QObject * parent) : QObject(parent) { } BluetoothMonitor::~BluetoothMonitor() { } bool BluetoothMonitor::bluetoothConnectionExists(const QString &bdAddr, const QString &service) { if (bdAddr.isEmpty() || service.isEmpty()) { return false; } NetworkManager::BluetoothSetting::ProfileType profile; if (service == QLatin1String("dun")) { profile = NetworkManager::BluetoothSetting::Dun; } else if (service == QLatin1String("nap")) { profile = NetworkManager::BluetoothSetting::Panu; } else { return false; } Q_FOREACH (const NetworkManager::Connection::Ptr &con, NetworkManager::listConnections()) { if (con && con->settings() && con->settings()->connectionType() == NetworkManager::ConnectionSettings::Bluetooth) { NetworkManager::BluetoothSetting::Ptr btSetting = con->settings()->setting(NetworkManager::Setting::Bluetooth).staticCast(); if (btSetting->profileType() == profile && btSetting->bluetoothAddress() == NetworkManager::macAddressFromString(bdAddr)) { return true; } } } return false; } void BluetoothMonitor::addBluetoothConnection(const QString &bdAddr, const QString &service, const QString &connectionName) { qCDebug(PLASMA_NM) << "Adding BT connection:" << bdAddr << service; if (bdAddr.isEmpty() || service.isEmpty() || connectionName.isEmpty()) { return; } if (service != QLatin1String("dun") && service != QLatin1String("nap")) { - KMessageBox::sorry(0, i18n("Only 'dun' and 'nap' services are supported.")); + KMessageBox::sorry(nullptr, i18n("Only 'dun' and 'nap' services are supported.")); return; } qCDebug(PLASMA_NM) << "Bdaddr == " << bdAddr; if (bluetoothConnectionExists(bdAddr, service)) { return; } if (service == QLatin1String("nap")) { NetworkManager::ConnectionSettings connectionSettings(NetworkManager::ConnectionSettings::Bluetooth, NM_BT_CAPABILITY_NAP); connectionSettings.setUuid(NetworkManager::ConnectionSettings::createNewUuid()); connectionSettings.setId(connectionName); NetworkManager::BluetoothSetting::Ptr btSetting = connectionSettings.setting(NetworkManager::Setting::Bluetooth).staticCast(); btSetting->setBluetoothAddress(NetworkManager::macAddressFromString(bdAddr)); btSetting->setProfileType(NetworkManager::BluetoothSetting::Panu); btSetting->setInitialized(true); NetworkManager::addConnection(connectionSettings.toMap()); } #if WITH_MODEMMANAGER_SUPPORT else if (service == QLatin1String("dun")) { QPointer mobileConnectionWizard = new MobileConnectionWizard(NetworkManager::ConnectionSettings::Bluetooth); connect(mobileConnectionWizard.data(), &MobileConnectionWizard::accepted, [bdAddr, connectionName, mobileConnectionWizard, this] () { if (mobileConnectionWizard->getError() == MobileProviders::Success) { qCDebug(PLASMA_NM) << "Mobile broadband wizard finished:" << mobileConnectionWizard->type() << mobileConnectionWizard->args(); if (mobileConnectionWizard->args().count() == 2) { //GSM or CDMA qCDebug(PLASMA_NM) << "Creating new DUN connection for BT device:" << bdAddr; QVariantMap tmp = qdbus_cast(mobileConnectionWizard->args().value(1)); NetworkManager::ConnectionSettings connectionSettings(NetworkManager::ConnectionSettings::Bluetooth, NM_BT_CAPABILITY_DUN); connectionSettings.setUuid(NetworkManager::ConnectionSettings::createNewUuid()); connectionSettings.setId(connectionName); NetworkManager::BluetoothSetting::Ptr btSetting = connectionSettings.setting(NetworkManager::Setting::Bluetooth).staticCast(); btSetting->setBluetoothAddress(NetworkManager::macAddressFromString(bdAddr)); btSetting->setProfileType(NetworkManager::BluetoothSetting::Dun); btSetting->setInitialized(true); if (mobileConnectionWizard->type() == NetworkManager::ConnectionSettings::Gsm) { connectionSettings.setting(NetworkManager::Setting::Gsm)->fromMap(tmp); connectionSettings.setting(NetworkManager::Setting::Gsm)->setInitialized(true); } else if (mobileConnectionWizard->type() == NetworkManager::ConnectionSettings::Cdma) { connectionSettings.setting(NetworkManager::Setting::Cdma)->fromMap(tmp); connectionSettings.setting(NetworkManager::Setting::Cdma)->setInitialized(true); } qCDebug(PLASMA_NM) << "Adding DUN connection" << connectionSettings; NetworkManager::addConnection(connectionSettings.toMap()); } } }); connect(mobileConnectionWizard.data(), &MobileConnectionWizard::finished, [mobileConnectionWizard] () { if (mobileConnectionWizard) { mobileConnectionWizard->deleteLater(); } }); mobileConnectionWizard->setModal(true); mobileConnectionWizard->show(); } #endif } diff --git a/kded/bluetoothmonitor.h b/kded/bluetoothmonitor.h index 2103b3e9..7f7d5c53 100644 --- a/kded/bluetoothmonitor.h +++ b/kded/bluetoothmonitor.h @@ -1,43 +1,43 @@ /* Copyright 2011 Lamarque Souza Copyright 2013 Lukas Tinkl Copyright 2013-2014 Jan Grulich Copyright 2015 David Rosca This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_BLUETOOTH_MONITOR_H #define PLASMA_NM_BLUETOOTH_MONITOR_H #if WITH_MODEMMANAGER_SUPPORT #include "mobileconnectionwizard.h" #include #endif #include class BluetoothMonitor: public QObject { Q_OBJECT public: explicit BluetoothMonitor(QObject * parent); - ~BluetoothMonitor(); + ~BluetoothMonitor() override; bool bluetoothConnectionExists(const QString &bdAddr, const QString &service); void addBluetoothConnection(const QString &bdAddr, const QString &service, const QString &connectionName); }; #endif diff --git a/kded/modemmonitor.cpp b/kded/modemmonitor.cpp index 1075f168..27eee8a8 100644 --- a/kded/modemmonitor.cpp +++ b/kded/modemmonitor.cpp @@ -1,209 +1,209 @@ /* Copyright 2009 Will Stephenson Copyright 2013 Lukas Tinkl Copyright 2014 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "debug.h" #include "modemmonitor.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include "pindialog.h" class ModemMonitorPrivate { public: QWeakPointer dialog; }; ModemMonitor::ModemMonitor(QObject * parent) :QObject(parent), d_ptr(new ModemMonitorPrivate) { Q_D(ModemMonitor); d->dialog.clear(); KSharedConfigPtr config = KSharedConfig::openConfig(QLatin1String("plasma-nm")); KConfigGroup grp(config, QLatin1String("General")); if (grp.isValid()) { if (grp.readEntry(QLatin1String("UnlockModemOnDetection"), true)) { connect(ModemManager::notifier(), &ModemManager::Notifier::modemAdded, this, &ModemMonitor::unlockModem); Q_FOREACH (const ModemManager::ModemDevice::Ptr &iface, ModemManager::modemDevices()) { unlockModem(iface->uni()); } } } } ModemMonitor::~ModemMonitor() { delete d_ptr; } void ModemMonitor::unlockModem(const QString &modemUni) { Q_D(ModemMonitor); ModemManager::Modem::Ptr modem; ModemManager::ModemDevice::Ptr modemDevice = ModemManager::findModemDevice(modemUni); if (modemDevice) { modem = modemDevice->interface(ModemManager::ModemDevice::ModemInterface).objectCast(); } else { return; } connect(modem.data(), &ModemManager::Modem::unlockRequiredChanged, this, &ModemMonitor::requestPin, Qt::UniqueConnection); if (d->dialog || (modem && modem->unlockRequired() == MM_MODEM_LOCK_NONE) || (modem && modem->unlockRequired() == MM_MODEM_LOCK_UNKNOWN)) { return; } if (modem) { // Using queued invocation to prevent kded stalling here until user enters the pin. QMetaObject::invokeMethod(modem.data(), "unlockRequiredChanged", Qt::QueuedConnection, Q_ARG(MMModemLock, modem->unlockRequired())); } } void ModemMonitor::requestPin(MMModemLock lock) { Q_D(ModemMonitor); qCDebug(PLASMA_NM) << "unlockRequired == " << lock; // Handle just SIM-PIN and SIM-PUK, because some other types may cause problems and they are not also handled by nm-applet if (lock == MM_MODEM_LOCK_NONE || lock == MM_MODEM_LOCK_UNKNOWN || (lock != MM_MODEM_LOCK_SIM_PIN && lock != MM_MODEM_LOCK_SIM_PUK)) { return; } ModemManager::Modem *modem = qobject_cast(sender()); if (!modem) { return; } if (d->dialog) { qCDebug(PLASMA_NM) << "PinDialog already running"; return; } if (lock == MM_MODEM_LOCK_SIM_PIN) { d->dialog = new PinDialog(modem, PinDialog::SimPin); } else if (lock == MM_MODEM_LOCK_SIM_PIN2) { d->dialog = new PinDialog(modem, PinDialog::SimPin2); } else if (lock == MM_MODEM_LOCK_SIM_PUK) { d->dialog = new PinDialog(modem, PinDialog::SimPuk); } else if (lock == MM_MODEM_LOCK_SIM_PUK2 ) { d->dialog = new PinDialog(modem, PinDialog::SimPuk); } else if (lock == MM_MODEM_LOCK_PH_SP_PIN) { d->dialog = new PinDialog(modem, PinDialog::ModemServiceProviderPin); } else if (lock == MM_MODEM_LOCK_PH_SP_PUK) { d->dialog = new PinDialog(modem, PinDialog::ModemServiceProviderPuk); } else if (lock == MM_MODEM_LOCK_PH_NET_PIN) { d->dialog = new PinDialog(modem, PinDialog::ModemNetworkPin); } else if (lock == MM_MODEM_LOCK_PH_NET_PUK) { d->dialog = new PinDialog(modem, PinDialog::ModemNetworkPuk); } else if (lock == MM_MODEM_LOCK_PH_SIM_PIN) { d->dialog = new PinDialog(modem, PinDialog::ModemPin); } else if (lock == MM_MODEM_LOCK_PH_CORP_PIN) { d->dialog = new PinDialog(modem, PinDialog::ModemCorporatePin); } else if (lock == MM_MODEM_LOCK_PH_CORP_PUK) { d->dialog = new PinDialog(modem, PinDialog::ModemCorporatePuk); } else if (lock == MM_MODEM_LOCK_PH_FSIM_PIN) { d->dialog = new PinDialog(modem, PinDialog::ModemPhFsimPin); } else if (lock == MM_MODEM_LOCK_PH_FSIM_PUK) { d->dialog = new PinDialog(modem, PinDialog::ModemPhFsimPuk); } else if (lock == MM_MODEM_LOCK_PH_NETSUB_PIN) { d->dialog = new PinDialog(modem, PinDialog::ModemNetworkSubsetPin); } else if (lock == MM_MODEM_LOCK_PH_NETSUB_PUK) { d->dialog = new PinDialog(modem, PinDialog::ModemNetworkSubsetPuk); } if (d->dialog.data()->exec() != QDialog::Accepted) { goto OUT; } qCDebug(PLASMA_NM) << "Sending unlock code"; { ModemManager::Sim::Ptr sim; ModemManager::ModemDevice::Ptr modemDevice = ModemManager::findModemDevice(modem->uni()); if (modemDevice && modemDevice->sim()) { sim = modemDevice->sim(); } if (!sim) { return; } - QDBusPendingCallWatcher *watcher = 0; + QDBusPendingCallWatcher *watcher = nullptr; PinDialog::Type type = d->dialog.data()->type(); if (type == PinDialog::SimPin || type == PinDialog::SimPin2 || type == PinDialog::ModemServiceProviderPin || type == PinDialog::ModemNetworkPin || type == PinDialog::ModemPin || type == PinDialog::ModemCorporatePin || type == PinDialog::ModemPhFsimPin || type == PinDialog::ModemNetworkSubsetPin) { QDBusPendingCall reply = sim->sendPin(d->dialog.data()->pin()); watcher = new QDBusPendingCallWatcher(reply, sim.data()); } else if (type == PinDialog::SimPuk || type == PinDialog::SimPuk2 || type == PinDialog::ModemServiceProviderPuk || type == PinDialog::ModemNetworkPuk || type == PinDialog::ModemCorporatePuk || type == PinDialog::ModemPhFsimPuk || type == PinDialog::ModemNetworkSubsetPuk) { QDBusPendingCall reply = sim->sendPuk(d->dialog.data()->puk(), d->dialog.data()->pin()); watcher = new QDBusPendingCallWatcher(reply, sim.data()); } connect(watcher, &QDBusPendingCallWatcher::finished, this, &ModemMonitor::onSendPinArrived); } OUT: if(d->dialog) { d->dialog.data()->deleteLater(); } d->dialog.clear(); } void ModemMonitor::onSendPinArrived(QDBusPendingCallWatcher * watcher) { QDBusPendingReply<> reply = *watcher; if (reply.isValid()) { // Automatically enabling this for cell phones with expensive data plans is not a good idea. //NetworkManager::setWwanEnabled(true); } else { - KMessageBox::error(0, i18nc("Text in GSM PIN/PUK unlock error dialog", "Error unlocking modem: %1", reply.error().message()), + KMessageBox::error(nullptr, i18nc("Text in GSM PIN/PUK unlock error dialog", "Error unlocking modem: %1", reply.error().message()), i18nc("Title for GSM PIN/PUK unlock error dialog", "PIN/PUK unlock error")); } watcher->deleteLater(); } diff --git a/kded/modemmonitor.h b/kded/modemmonitor.h index 870b9a95..86365917 100644 --- a/kded/modemmonitor.h +++ b/kded/modemmonitor.h @@ -1,54 +1,54 @@ /* Copyright 2009 Will Stephenson Copyright 2013 Lukas Tinkl Copyright 2014 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_MODEM_MONITOR_H #define PLASMA_NM_MODEM_MONITOR_H #include #include #include #include class ModemMonitorPrivate; /** * Monitors modem hardware and provides a PIN unlock dialog */ class Q_DECL_EXPORT ModemMonitor : public QObject { Q_OBJECT Q_DECLARE_PRIVATE(ModemMonitor) public: explicit ModemMonitor(QObject * parent); - virtual ~ModemMonitor(); + ~ModemMonitor() override; public Q_SLOTS: void unlockModem(const QString &modemUni); private Q_SLOTS: void requestPin(MMModemLock lock); void onSendPinArrived(QDBusPendingCallWatcher *); private: ModemMonitorPrivate * d_ptr; }; #endif // PLASMA_NM_MODEM_MONITOR_H diff --git a/kded/monitor.h b/kded/monitor.h index 4c809045..4947a7b9 100644 --- a/kded/monitor.h +++ b/kded/monitor.h @@ -1,54 +1,54 @@ /* Copyright 2014 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_MONITOR_H #define PLASMA_NM_MONITOR_H #include #include #include "bluetoothmonitor.h" #if WITH_MODEMMANAGER_SUPPORT #include "modemmonitor.h" #endif class Q_DECL_EXPORT Monitor : public QObject { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.plasmanetworkmanagement") public: explicit Monitor(QObject * parent); - virtual ~Monitor(); + ~Monitor() override; public Q_SLOTS: Q_SCRIPTABLE bool bluetoothConnectionExists(const QString &bdAddr, const QString &service); Q_SCRIPTABLE void addBluetoothConnection(const QString &bdAddr, const QString &service, const QString &connectionName); #if WITH_MODEMMANAGER_SUPPORT Q_SCRIPTABLE void unlockModem(const QString &modem); #endif private: BluetoothMonitor * m_bluetoothMonitor; #if WITH_MODEMMANAGER_SUPPORT ModemMonitor * m_modemMonitor; #endif }; #endif // PLASMA_NM_MONITOR_H diff --git a/kded/networkmanagement.desktop b/kded/networkmanagement.desktop index b55ca6cb..423178bb 100644 --- a/kded/networkmanagement.desktop +++ b/kded/networkmanagement.desktop @@ -1,99 +1,100 @@ [Desktop Entry] Name=Plasma Networkmanagement module Name[ar]=وحدة بلازما لإدارة الشّبكة Name[bg]=Модул за настройка на мрежата Name[bs]=Plasma Networkmanagement režim Name[ca]=Mòdul de Plasma per a la Gestió de la xarxa Name[ca@valencia]=Mòdul de Plasma per a la Gestió de la xarxa Name[cs]=Modul Plasma Networkmanagement Name[da]=Plasma netværkshåndteringsmodul Name[de]=Plasma-Netzwerkverwaltungsmodul Name[el]=Άρθρωμα Plasma για τη διαχείριση δικτύων Name[en_GB]=Plasma Networkmanagement module Name[es]=Modulo de gestión de redes de Plasma Name[et]=Plasma võrguhalduse moodul Name[eu]=Plasmaren Networkmanagement modulua Name[fi]=Plasman verkonhallintamoduuli Name[fr]=Module « Networkmanagement » pour Plasma Name[gl]=Módulo de xestión da rede de Plasma Name[he]=מודול ניהול רשתות של פלזמה Name[hu]=Plasma hálózatkezelés modul Name[ia]=Modulo de gestion de rete de Plasma +Name[id]=Modul Plasma Networkmanagement Name[it]=Modulo della gestione di rete di Plasma Name[ko]=Plasma 네트워크 관리 모듈 Name[lt]=Plasma tinklo valdymo modulis Name[nb]=Plasma-modul for nettverksstyring Name[nds]=Plasma-Nettwarkpleegmoduul Name[nl]=Plasma module voor netwerkbeheer Name[nn]=Plasma-modul for nettverksstyring Name[pa]=ਪਲਾਜ਼ਮਾ ਨੈੱਟਵਰਕਮੈਨਜੇਮੈਂਟ ਮੋਡਿਊਲ Name[pl]=Moduł zarządzania siecią Plazmy Name[pt]=Módulo de Gestão de Rede do Plasma Name[pt_BR]=Módulo Networkmanagement do Plasma Name[ro]=Modul Plasma pentru gestiunea rețelei Name[ru]=Модуль для управления сетью Name[sk]=Modul Plasma správa siete Name[sl]=Modul upravljanja omrežij za Plasmo Name[sr]=Плазма модул за управљање мрежом Name[sr@ijekavian]=Плазма модул за управљање мрежом Name[sr@ijekavianlatin]=Plasma modul za upravljanje mrežom Name[sr@latin]=Plasma modul za upravljanje mrežom Name[sv]=Plasma nätverkshanteringsmodul Name[tr]=Plasma Ağ yönetimi modülü Name[uk]=Модуль керування мережею Плазми Name[x-test]=xxPlasma Networkmanagement modulexx Name[zh_CN]=Plasma 网络管理模块 Name[zh_TW]=Plasma 網路管理員模組 Comment=Provides secrets to the NetworkManager daemon Comment[ar]=توفّر الأسرار لعفريت «مديرالشّبكة» Comment[bs]=Pruža tajne Upravljaču mreže daemon Comment[ca]=Proporciona secrets al dimoni NetworkManager Comment[ca@valencia]=Proporciona secrets al dimoni NetworkManager Comment[cs]=Poskytuje přihlašovací informace pro službu NetworkManageru Comment[da]=Giver hemmeligheder til NetworkManager-dæmonen Comment[de]=Stellt dem NetworkManager-Dienst vertrauliche Daten zur Verfügung Comment[el]=Παρέχει κωδικούς ασφαλείας στον δαίμονα NetworkManager Comment[en_GB]=Provides secrets to the NetworkManager daemon Comment[es]=Proporciona contraseñas al demonio de NetworkManager Comment[et]=Saladuste edastamine NetworkManageri deemonile Comment[eu]=NetworkManager daimonari sekretuak hornitzen dizkio Comment[fi]=Välittää salaisuuksia NetworkManager-palvelulle Comment[fr]=Fournit des mots de passe pour le démon NetworkManager Comment[gl]=Fornece segredos ao servizo de xestión da rede Comment[he]=מספק סיסמאות לשירות מנהל הרשתות Comment[hu]=Titkokat biztosít a NetworkManager démonhoz Comment[ia]=Forni secretos per le demon de NetworkManager +Comment[id]=Menyediakan rahasia ke daemon NetworkManager Comment[it]=Fornisce i segreti al demone NetworkManager Comment[ko]=NetworkManager 데몬에 비밀 정보 제공 Comment[lt]=Teikia slapukus NetworkManager tarnybai Comment[nb]=Forsyner NetworkManager-daemonen med hemmeligheter Comment[nds]=Stellt Anmellinformatschonen för den NetworkManager-Dämoon praat Comment[nl]=Levert secrets aan de NetworkManager-daemon Comment[nn]=Forsyner NetworkManager-tenesta med løyndomar Comment[pa]=ਨੈੱਟਵਰਕਮੈਨੇਜਰ ਡੈਮਨ ਲਈ ਭੇਤ ਦਿੰਦਾ ਹੈ Comment[pl]=Dostarcza danych poufnych do usługi Zarządzania Siecią Comment[pt]=Fornece as senhas do serviço NetworkManager Comment[pt_BR]=Fornece as senhas do serviço NetworkManager Comment[ro]=Furnizează secrete către demonul NetworkManager Comment[ru]=Предоставляет пароли и ключи демону NetworkManager Comment[sk]=Poskytuje tajnosti k démonu NetworkManager Comment[sl]=Ponuja skrivnosti za ozadnji program NetworkManager Comment[sr]=Доставља тајне демону Менаџера мреже Comment[sr@ijekavian]=Доставља тајне демону Менаџера мреже Comment[sr@ijekavianlatin]=Dostavlja tajne demonu Menadžera mreže Comment[sr@latin]=Dostavlja tajne demonu Menadžera mreže Comment[sv]=Tillhandahåller hemligheter till nätverkshanteringsdemonen Comment[tr]=AğYönetici yardımcısına şifreleri sağlar Comment[uk]=Надає реєстраційні дані фоновій службі NetworkManager Comment[x-test]=xxProvides secrets to the NetworkManager daemonxx Comment[zh_CN]=为 NetworkManager 守护程序提供密码 Comment[zh_TW]=提供網路管理員伺服程式的密碼 Type=Service X-KDE-ServiceTypes=KDEDModule X-KDE-ModuleType=Library X-KDE-Library=networkmanagement -X-KDE-DBus-ModuleName=networkmanagement X-KDE-Kded-autoload=true X-KDE-Kded-load-on-demand=true X-KDE-Kded-phase=1 OnlyShowIn=KDE; diff --git a/kded/networkmanagement.notifyrc b/kded/networkmanagement.notifyrc index 71d965f7..0a201f91 100644 --- a/kded/networkmanagement.notifyrc +++ b/kded/networkmanagement.notifyrc @@ -1,780 +1,797 @@ [Global] IconName=applications-internet Name=Network management Name[ar]=إدارة الشّبكات Name[bs]=Upravljanje mrežom Name[ca]=Gestió de la xarxa Name[ca@valencia]=Gestió de la xarxa Name[cs]=Správa sítě Name[da]=Netværkshåndtering Name[de]=Netzwerkverwaltung Name[el]=Διαχείριση δικτύων Name[en_GB]=Network management Name[es]=Gestión de redes Name[et]=Võrguhaldur Name[eu]=Sare-kudeaketa Name[fi]=Verkonhallinta Name[fr]=Gestion du réseau Name[gl]=Xestión da rede Name[he]=ניהול רשת Name[hu]=Hálózatkezelés Name[ia]=Gestion de rete +Name[id]=Network management Name[it]=Gestione di rete Name[ko]=네트워크 관리 Name[lt]=Tinklo valdymas Name[nb]=Nettverksstyring Name[nds]=Nettwarkpleeg Name[nl]=Netwerkbeheer Name[nn]=Nettverksstyring Name[pa]=ਨੈੱਟਵਰਕ ਪਰਬੰਧ Name[pl]=Zarządzanie siecią Name[pt]=Gestão de rede Name[pt_BR]=Gerenciamento de redes Name[ru]=Управление сетью Name[sk]=Správa siete Name[sl]=Upravljanje omrežij Name[sr]=Управљање мрежом Name[sr@ijekavian]=Управљање мрежом Name[sr@ijekavianlatin]=Upravljanje mrežom Name[sr@latin]=Upravljanje mrežom Name[sv]=Nätverkshantering Name[tr]=Ağ yönetimi Name[uk]=Керування мережею Name[x-test]=xxNetwork managementxx Name[zh_CN]=网络管理 Name[zh_TW]=網路管理 Comment=Network management Comment[ar]=إدارة الشّبكات Comment[bs]=Upravljanje mrežom Comment[ca]=Gestió de la xarxa Comment[ca@valencia]=Gestió de la xarxa Comment[cs]=Správa sítě Comment[da]=Netværkshåndtering Comment[de]=Netzwerkverwaltung Comment[el]=Διαχείριση δικτύων Comment[en_GB]=Network management Comment[es]=Gestión de redes Comment[et]=Võrguhaldur Comment[eu]=Sare-kudeaketa Comment[fi]=Verkonhallinta Comment[fr]=Gestion du réseau Comment[gl]=Xestión da rede Comment[he]=ניהול רשת Comment[hu]=Hálózatkezelés Comment[ia]=Gestion de rete +Comment[id]=Pengelolaan network Comment[it]=Gestione di rete Comment[ko]=네트워크 관리 Comment[lt]=Tinklo valdymas Comment[nb]=Nettverksstyring Comment[nds]=Nettwarkpleeg Comment[nl]=Netwerkbeheer Comment[nn]=Nettverksstyring Comment[pa]=ਨੈੱਟਵਰਕ ਪਰਬੰਧ Comment[pl]=Zarządzanie siecią Comment[pt]=Gestão de rede Comment[pt_BR]=Gerenciamento de redes Comment[ru]=Управление сетью Comment[sk]=Správa siete Comment[sl]=Upravljanje omrežij Comment[sr]=Управљање мрежом Comment[sr@ijekavian]=Управљање мрежом Comment[sr@ijekavianlatin]=Upravljanje mrežom Comment[sr@latin]=Upravljanje mrežom Comment[sv]=Nätverkshantering Comment[tr]=Ağ yönetimi Comment[uk]=Керування мережею Comment[x-test]=xxNetwork managementxx Comment[zh_CN]=网络管理 Comment[zh_TW]=網路管理 [Event/ConnectionActivated] Name=Connection activated Name[ar]=فُعّل الاتّصال Name[bs]=Konekcija aktivirana Name[ca]=Connexió activada Name[ca@valencia]=Connexió activada Name[cs]=Spojení aktivováno Name[da]=Forbindelse aktiveret Name[de]=Verbindung aktiviert Name[el]=Η σύνδεση ενεργοποιήθηκε Name[en_GB]=Connection activated Name[es]=Conexión activada Name[et]=Ühendus on aktiivne Name[eu]=Konexioa aktibatu da Name[fi]=Yhteys muodostettu Name[fr]=Connexion activée Name[gl]=Activouse unha conexión Name[he]=החיבור פעיל Name[hu]=Kapcsolat aktiválva Name[ia]=Connexion activate +Name[id]=Koneksi yang diaktifkan Name[it]=Connessione attivata Name[ko]=연결 활성화됨 Name[lt]=Ryšys aktyvuotas Name[nb]=Tilkobling aktivert Name[nds]=Verbinnen anmaakt Name[nl]=Verbinding geactiveerd Name[nn]=Kopla til Name[pa]=ਕੁਨੈਕਸ਼ਨ ਸਰਗਰਮ ਹੈ Name[pl]=Nawiązano połączenie Name[pt]=Ligação activada Name[pt_BR]=Conexão ativada Name[ru]=Соединение установлено Name[sk]=Pripojenie aktivované Name[sl]=Povezava omogočena Name[sr]=Веза активирана Name[sr@ijekavian]=Веза активирана Name[sr@ijekavianlatin]=Veza aktivirana Name[sr@latin]=Veza aktivirana Name[sv]=Anslutning aktiverad Name[tr]=Bağlantı etkinleştirildi Name[uk]=З’єднання задіяно Name[x-test]=xxConnection activatedxx Name[zh_CN]=连接已激活 Name[zh_TW]=連線已啟動 IconName=applications-internet Action=Popup [Event/ConnectionDeactivated] Name=Connection deactivated Name[ar]=عُطّل الاتّصال Name[bs]=Konekcija deaktivirana Name[ca]=Connexió desactivada Name[ca@valencia]=Connexió desactivada Name[cs]=Spojení deaktivováno Name[da]=Forbindelse deaktiveret Name[de]=Verbindung deaktiviert Name[el]=Η σύνδεση απενεργοποιήθηκε Name[en_GB]=Connection deactivated Name[es]=Conexión desactivada Name[et]=Ühendus ei ole aktiivne Name[eu]=Konexioa desaktibatu da Name[fi]=Yhteys katkaistu Name[fr]=Connexion désactivée Name[gl]=Desactivouse a conexión Name[he]=החיבור לא פעיל Name[hu]=Kapcsolat deaktiválva Name[ia]=Connexion deactivate +Name[id]=Koneksi yang dinonaktifkan Name[it]=Connessione disattivata Name[ko]=연결 비활성화됨 Name[lt]=Ryšys išjungtas Name[nb]=Tilkobling deaktivert Name[nds]=Verbinnen utmaakt Name[nl]=Verbinding gedeactiveerd Name[nn]=Kopla frå Name[pa]=ਕਨੈਕਸ਼ਨ ਡਿ-ਐਕਟੀਵੇਟ ਹੈ Name[pl]=Zerwano połączenie Name[pt]=Ligação desactivada Name[pt_BR]=Conexão desativada Name[ru]=Соединение отключено Name[sk]=Pripojenie deaktivované Name[sl]=Povezava onemogočena Name[sr]=Веза деактивирана Name[sr@ijekavian]=Веза деактивирана Name[sr@ijekavianlatin]=Veza deaktivirana Name[sr@latin]=Veza deaktivirana Name[sv]=Anslutning inaktiverad Name[tr]=Bağlantı sonlandırıldı Name[uk]=З’єднання вимкнено Name[x-test]=xxConnection deactivatedxx Name[zh_CN]=连接已取消激活 Name[zh_TW]=連線已中止 IconName=applications-internet Action=Popup [Event/ConnectionAdded] Name=Connection added Name[ar]=أُضيف الاتّصال Name[bs]=Konekcija dodana Name[ca]=S'ha afegit una connexió Name[ca@valencia]=S'ha afegit una connexió Name[cs]=Spojení bylo přidáno Name[da]=Forbindelse tilføjet Name[de]=Verbindung hinzugefügt Name[el]=Η σύνδεση προστέθηκε Name[en_GB]=Connection added Name[es]=Conexión añadida Name[et]=Ühendus lisati Name[eu]=Konexioa gehitu da Name[fi]=Yhteys lisätty Name[fr]=Connexion ajoutée Name[gl]=Engadiuse unha conexión Name[he]=נוסף חיבור Name[hu]=Kapcsolat hozzáadva Name[ia]=Connexion addite +Name[id]=Koneksi yang ditambahkan Name[it]=Connessione aggiunta Name[ko]=연결 추가됨 Name[lt]=Ryšys pridėtas Name[nb]=Tilkobling lagt til Name[nds]=Verbinnen toföögt Name[nl]=Verbinding toegevoegd Name[nn]=Lagt til tilkopling Name[pa]=ਕੁਨੈਕਸ਼ਨ ਜੋੜਿਆ Name[pl]=Dodano połączenie Name[pt]=Ligação adicionada Name[pt_BR]=Conexão adicionada Name[ru]=Соединение добавлено Name[sk]=Pripojenie pridané Name[sl]=Povezava dodana Name[sr]=Веза додата Name[sr@ijekavian]=Веза додата Name[sr@ijekavianlatin]=Veza dodata Name[sr@latin]=Veza dodata Name[sv]=Anslutning har lagts till Name[tr]=Bağlantı eklendi Name[uk]=Додано з’єднання Name[x-test]=xxConnection addedxx Name[zh_CN]=连接已添加 Name[zh_TW]=連線已新增 IconName=applications-internet Action=None [Event/ConnectionRemoved] Name=Connection removed Name[ar]=أُزيل الاتّصال Name[bs]=Konekcija uklonjena Name[ca]=S'ha eliminat una connexió Name[ca@valencia]=S'ha eliminat una connexió Name[cs]=Spojení bylo odstraněno Name[da]=Forbindelse fjernet Name[de]=Verbindung entfernt Name[el]=Η σύνδεση αφαιρέθηκε Name[en_GB]=Connection removed Name[es]=Conexión eliminada Name[et]=Ühendus eemaldati Name[eu]=Konexioa kendu da Name[fi]=Yhteys poistettu Name[fr]=Connexion supprimée Name[gl]=Retirouse unha conexión Name[he]=הוסר חיבור Name[hu]=Kapcsolat eltávolítva Name[ia]=Connexion removite +Name[id]=Koneksi yang dihapus Name[it]=Connessione rimossa Name[ko]=연결 삭제됨 Name[lt]=Ryšys pašalintas Name[nb]=Tilkobling fjernet Name[nds]=Verbinnen wegmaakt Name[nl]=Verbinding verwijderd Name[nn]=Fjerna tilkopling Name[pa]=ਕੁਨੈਕਸ਼ਨ ਹਟਾਇਆ Name[pl]=Usunięto połączenie Name[pt]=Ligação removida Name[pt_BR]=Conexão removida Name[ru]=Соединение удалено Name[sk]=Pripojenie odstránené Name[sl]=Povezava odstranjena Name[sr]=Веза уклоњена Name[sr@ijekavian]=Веза уклоњена Name[sr@ijekavianlatin]=Veza uklonjena Name[sr@latin]=Veza uklonjena Name[sv]=Anslutning borttagen Name[tr]=Bağlantı silindi Name[uk]=Вилучено з’єднання Name[x-test]=xxConnection removedxx Name[zh_CN]=连接已删除 Name[zh_TW]=連線已移除 IconName=applications-internet Action=None [Event/ConnectionUpdated] Name=Connection updated Name[ar]=حُدّث الاتّصال Name[bs]=Konekcija ažurirana Name[ca]=S'ha actualitzat una connexió Name[ca@valencia]=S'ha actualitzat una connexió Name[cs]=Spojení bylo aktualizováno Name[da]=Forbindelse opdateret Name[de]=Verbindung aktualisiert Name[el]=Η σύνδεση ενημερώθηκε Name[en_GB]=Connection updated Name[es]=Conexión actualizada Name[et]=Ühendust uuendati Name[eu]=Konexioa eguneratu da Name[fi]=Yhteys päivitetty Name[fr]=Connexion mise à jour Name[gl]=Actualizouse unha conexión Name[he]=חיבור עודכן Name[hu]=Kapcsolat frissítve Name[ia]=Connexion actualisate +Name[id]=Koneksi yang diupdate Name[it]=Connessione aggiornata Name[ko]=연결 업데이트됨 Name[lt]=Ryšys atnaujintas Name[nb]=Tilkobling oppdatert Name[nds]=Verbinnen opfrischt Name[nl]=Verbinding bijgewerkt Name[nn]=Oppdatert tilkopling Name[pa]=ਕੁਨੈਕਸ਼ਨ ਅੱਪਡੇਟ ਕੀਤਾ Name[pl]=Uaktualniono połączenie Name[pt]=Ligação actualizada Name[pt_BR]=Conexão atualizada Name[ru]=Соединение обновлено Name[sk]=Pripojenie aktualizované Name[sl]=Povezava posodobljena Name[sr]=Веза ажурирана Name[sr@ijekavian]=Веза ажурирана Name[sr@ijekavianlatin]=Veza ažurirana Name[sr@latin]=Veza ažurirana Name[sv]=Anslutning uppdaterad Name[tr]=Bağlantı güncellendi Name[uk]=Оновлено з’єднання Name[x-test]=xxConnection updatedxx Name[zh_CN]=连接已更新 Name[zh_TW]=連線已更新 IconName=applications-internet Action=None [Event/DeviceFailed] Name=Device failed Name[ar]=فشل الجهاز Name[bs]=Uređaj pao Name[ca]=El dispositiu ha fallat Name[ca@valencia]=El dispositiu ha fallat Name[cs]=Zařízení selhalo Name[da]=Enheden fejlede Name[de]=Gerät nicht bereit Name[el]=Η συσκευή απέτυχε Name[en_GB]=Device failed Name[es]=El dispositivo ha fallado Name[et]=Seade nurjus Name[eu]=Gailuak huts egin du Name[fi]=Laite lakkasi toimimasta Name[fr]=Le périphérique a rencontré une erreur Name[gl]=O dispositivo fallou. Name[he]=ההתקן נכשל Name[hu]=Az eszköz meghiúsult Name[ia]=Dispositivo falleva +Name[id]=Perangkat yang gagal Name[it]=Dispositivo non funzionante Name[ko]=장치 오류 Name[lt]=Įrenginys sutriko Name[nb]=Enhet sviktet Name[nds]=Reedschap-Fehler Name[nl]=Apparaat is mislukt Name[nn]=Eining svikta Name[pa]=ਜੰਤਰ ਫੇਲ੍ਹ ਹੈ Name[pl]=Niepowodzenie urządzenia Name[pt]=Não foi possível activar o dispositivo Name[pt_BR]=Falha no dispositivo Name[ru]=Сбой устройства Name[sk]=Zariadenie zlyhalo Name[sl]=Naprava je spodletela Name[sr]=Уређај пропао Name[sr@ijekavian]=Уређај пропао Name[sr@ijekavianlatin]=Uređaj propao Name[sr@latin]=Uređaj propao Name[sv]=Enhet misslyckades Name[tr]=Aygıt başarısız oldu Name[uk]=Помилка пристрою Name[x-test]=xxDevice failedxx Name[zh_CN]=设备失败 Name[zh_TW]=裝置失敗 IconName=applications-internet Action=Popup [Event/FailedToActivateConnection] Name=Failed to activate connection Name[ar]=فشل تفعيل الاتّصال Name[bs]=Neuspjela aktivacija konekcije Name[ca]=Ha fallat en activar la connexió Name[ca@valencia]=Ha fallat en activar la connexió Name[cs]=Spojení nelze aktivovat Name[da]=Kunne ikke aktivere forbindelsen Name[de]=Die Verbindung kann nicht aktiviert werden Name[el]=Αποτυχία ενεργοποίησης σύνδεσης Name[en_GB]=Failed to activate connection Name[es]=La activación de la conexión ha fallado Name[et]=Ühenduse aktiveerimine nurjus Name[eu]=Konexioa aktibatzeak huts egin du Name[fi]=Yhteyden muodostaminen epäonnistui Name[fr]=Impossible d'activer la connexion Name[gl]=Non se puido activar a conexión Name[he]=נכשל בהפעלת החיבור Name[hu]=Nem sikerült aktiválni a kapcsolatot Name[ia]=Il faleva activar connexion +Name[id]=Gagal mengaktifkan koneksi Name[it]=Attivazione del dispositivo non riuscita Name[ko]=연결을 활성화할 수 없음 Name[lt]=Nepavyko aktyvuoti ryšio Name[nb]=Klarte ikke å aktivere tilkobling Name[nds]=Verbinnen lett sik nich anmaken Name[nl]=Activeren van verbinding is mislukt Name[nn]=Klarte ikkje å starta tilkopling Name[pa]=ਕੁਨੈਕਸ਼ਨ ਸਰਗਰਮ ਕਰਨ ਲਈ ਫੇਲ੍ਹ ਹੈ Name[pl]=Nieudane nawiązywanie połączenia Name[pt]=Não foi possível activar a ligação Name[pt_BR]=Falha ao ativar a conexão Name[ru]=Не удалось задействовать соединение Name[sk]=Zlyhalo aktivovanie pripojenia Name[sl]=Povezave ni bilo mogoče omogočiti Name[sr]=Пропало активирање везе Name[sr@ijekavian]=Пропало активирање везе Name[sr@ijekavianlatin]=Propalo aktiviranje veze Name[sr@latin]=Propalo aktiviranje veze Name[sv]=Aktivering av anslutningen misslyckades Name[tr]=Bağlantı etkinleştirilemedi Name[uk]=Не вдалося задіяти з’єднання Name[x-test]=xxFailed to activate connectionxx Name[zh_CN]=连接激活失败 Name[zh_TW]=啟動連線失敗 IconName=applications-internet Action=Popup [Event/FailedToAddConnection] Name=Failed to add connection Name[ar]=فشلت إضافة الاتّصال Name[bs]=Neuspjelo dodavanje konekcije Name[ca]=Ha fallat en afegir la connexió Name[ca@valencia]=Ha fallat en afegir la connexió Name[cs]=Přidání spojení selhalo Name[da]=Kunne ikke tilføje forbindelsen Name[de]=Die Verbindung kann nicht hinzugefügt werden Name[el]=Αποτυχία προσθήκης σύνδεσης Name[en_GB]=Failed to add connection Name[es]=Ha ocurrido un fallo al añadir la conexión Name[et]=Ühenduse lisamine nurjus Name[eu]=Konexioa gehitzeak huts egin du Name[fi]=Yhteyden lisääminen epäonnistui Name[fr]=Impossible d'ajouter la connexion Name[gl]=Non se puido engadir a conexión Name[he]=נכשל בהוספת חיבור Name[hu]=Nem sikerült hozzáadni a kapcsolatot Name[ia]=Il falleva adder connexion +Name[id]=Gagal menambahkan koneksi Name[it]=Aggiunta della connessione non riuscita Name[ko]=연결을 추가할 수 없음 Name[lt]=Nepavyko pridėti ryšio Name[nb]=Klarte ikke å legge til tilkobling Name[nds]=Verbinnen lett sik nich tofögen Name[nl]=Toevoegen van verbinding is mislukt Name[nn]=Klarte ikkje å leggja til tilkopling Name[pa]=ਕਨੈਕਸ਼ਨ ਜੋੜਨ ਲਈ ਫੇਲ੍ਹ ਹੈ Name[pl]=Nieudane dodawanie połączenia Name[pt]=Não foi possível adicionar a ligação Name[pt_BR]=Falha ao adicionar uma conexão Name[ru]=Не удалось добавить соединение Name[sk]=Zlyhalo pridanie pripojenia Name[sl]=Povezave ni bilo mogoče dodati Name[sr]=Пропало додавање везе Name[sr@ijekavian]=Пропало додавање везе Name[sr@ijekavianlatin]=Propalo dodavanje veze Name[sr@latin]=Propalo dodavanje veze Name[sv]=Tillägg av anslutning misslyckades Name[tr]=Bağlantı eklenemedi Name[uk]=Не вдалося додати з’єднання Name[x-test]=xxFailed to add connectionxx Name[zh_CN]=添加连接失败 Name[zh_TW]=新增連線失敗 IconName=applications-internet Action=Popup [Event/FailedToDeactivateConnection] Name=Failed to deactivate connection Name[ar]=فشل تعطيل الاتّصال Name[bs]=Neuspjelo deaktiviranje konekcije Name[ca]=Ha fallat en desactivar la connexió Name[ca@valencia]=Ha fallat en desactivar la connexió Name[cs]=Spojení nelze deaktivovat Name[da]=Kunne ikke deaktivere forbindelsen Name[de]=Die Verbindung kann nicht deaktiviert werden Name[el]=Αποτυχία απενεργοποίησης σύνδεσης Name[en_GB]=Failed to deactivate connection Name[es]=La desactivación de la conexión ha fallado Name[et]=Ühenduse deaktiveerimine nurjus Name[eu]=Konexioa desaktibatzeak huts egin du Name[fi]=Yhteyden katkaiseminen epäonnistui Name[fr]=Impossible de désactiver la connexion Name[gl]=Non se puido desactivar a conexión Name[he]=נכשל בכיבוי חיבור Name[hu]=Nem sikerült deaktiválni a kapcsolatot Name[ia]=Il falleva deactivar connexion +Name[id]=Gagal menonaktifkan koneksi Name[it]=Disattivazione della connessione non riuscita Name[ko]=연결을 비활성화할 수 없음 Name[lt]=Nepavyko išjungti ryšio Name[nb]=Klarte ikke å deaktivere tilkobling Name[nds]=Verbinnen lett sik nich utmaken Name[nl]=Deactiveren van verbinding is mislukt Name[nn]=Klarte ikkje å stoppa tilkopling Name[pa]=ਕਨੈਕਸ਼ਨ ਡਿ-ਐਕਟੀਵੇਟ ਕਰਨ ਲਈ ਫੇਲ੍ਹ ਹੈ Name[pl]=Nieudane wyłączanie połączenia Name[pt]=Não foi possível desactivar a ligação Name[pt_BR]=Falha ao desativar a conexão Name[ru]=Не удалось отключить соединение Name[sk]=Zlyhala deaktivácia pripojenia Name[sl]=Povezave ni bilo mogoče onemogočiti Name[sr]=Пропало деактивирање везе Name[sr@ijekavian]=Пропало деактивирање везе Name[sr@ijekavianlatin]=Propalo deaktiviranje veze Name[sr@latin]=Propalo deaktiviranje veze Name[sv]=Inaktivering av anslutningen misslyckades Name[tr]=Bağlantı kapatılamadı Name[uk]=Не вдалося вимкнути з’єднання Name[x-test]=xxFailed to deactivate connectionxx Name[zh_CN]=取消激活连接失败 Name[zh_TW]=中止連線失敗 IconName=applications-internet Action=Popup [Event/FailedToRemoveConnection] Name=Failed to remove connection Name[ar]=فشلت إزالة الاتّصال Name[bs]=Neuspjelo uklanjanje konekcije Name[ca]=Ha fallat en eliminar la connexió Name[ca@valencia]=Ha fallat en eliminar la connexió Name[cs]=Spojení nelze odstranit Name[da]=Kunne ikke fjerne forbindelsen Name[de]=Die Verbindung kann nicht entfernt werden Name[el]=Αποτυχία αφαίρεσης σύνδεσης Name[en_GB]=Failed to remove connection Name[es]=La eliminación de la conexión ha fallado Name[et]=Ühenduse eemaldamine nurjus Name[eu]=Konexioa kentzeak huts egin du Name[fi]=Yhteyden poisto epäonnistui Name[fr]=Impossible de supprimer la connexion Name[gl]=Non se puido retirar a conexión Name[he]=נכשל בהסרת חיבור Name[hu]=Nem sikerült eltávolítani a kapcsolatot Name[ia]=Il afelleva remover connexion +Name[id]=Gagal menghapus koneksi Name[it]=Rimozione della connessione non riuscita Name[ko]=연결을 삭제할 수 없음 Name[lt]=Nepavyko pašalinti ryšio Name[nb]=Klarte ikke å fjerne tilkobling Name[nds]=Verbinnen lett sik nich wegmaken Name[nl]=Verwijderen van verbinding is mislukt Name[nn]=Klarte ikkje å fjerna tilkopling Name[pa]=ਕਨੈਕਸ਼ਨ ਹਟਾਉਣ ਲਈ ਫੇਲ੍ਹ ਹੈ Name[pl]=Nieudane usuwanie połączenia Name[pt]=Não foi possível remover a ligação Name[pt_BR]=Falha ao remover a conexão Name[ru]=Не удалось удалить соединение Name[sk]=Zlyhalo odstránenie pripojenie Name[sl]=Povezave ni bilo mogoče odstraniti Name[sr]=Пропало уклањање везе Name[sr@ijekavian]=Пропало уклањање везе Name[sr@ijekavianlatin]=Propalo uklanjanje veze Name[sr@latin]=Propalo uklanjanje veze Name[sv]=Borttagning av anslutning misslyckades Name[tr]=Bağlantı silinemedi Name[uk]=Не вдалося вилучити з’єднання Name[x-test]=xxFailed to remove connectionxx Name[zh_CN]=删除连接失败 Name[zh_TW]=移除連線失敗 IconName=applications-internet Action=Popup [Event/FailedToGetSecrets] Name=Failed to get secrets Name[ar]=فشل جلب الأسرار Name[bs]=Nesupjelo uzimanje tajni Name[ca]=Ha fallat en obtenir els secrets Name[ca@valencia]=Ha fallat en obtindre els secrets Name[cs]=Selhalo získávání přístupu Name[da]=Kunne ikke hente hemmeligheder Name[de]=Anmeldedaten können nicht bezogen werden Name[el]=Αποτυχία ανάκτησης κωδικών Name[en_GB]=Failed to get secrets Name[es]=La obtención de claves secretas ha fallado Name[et]=Saladuste hankimine nurjus Name[eu]=Sekretuak eskuratzeak huts egin du Name[fi]=Salaisuuksien saaminen epäonnistui Name[fr]=Impossible d'obtenir les informations secrètes Name[gl]=Non se puideron obter os segredos Name[he]=נכשל בקבלת סיסמאות Name[hu]=Nem sikerült megszerezni a titkos adatokat Name[ia]=Il falleva obtener secretos +Name[id]=Gagal mendapatkan rahasiaan Name[it]=Impossibile ottenere i segreti Name[ko]=비밀 정보를 가져올 수 없음 Name[lt]=Nepavyko gauti slapukų Name[nb]=Klarte ikke hente hemmeligheter Name[nds]=Anmellinformatschonen laat sik nich halen Name[nl]=Geheimen ophalen is mislukt Name[nn]=Klarte ikkje henta løyndomar Name[pa]=ਭੇਤ ਲੈਣ ਲਈ ਫੇਲ੍ਹ ਹੈ Name[pl]=Nieudane uzyskiwanie danych poufnych Name[pt]=Não foi possível obter as senhas Name[pt_BR]=Falha ao obter as senhas Name[ru]=Не удалось получить пароли и ключи Name[sk]=Zlyhalo získanie secrets Name[sl]=Ni bilo mogoče dobiti skrivnosti Name[sr]=Пропало добављање тајни Name[sr@ijekavian]=Пропало добављање тајни Name[sr@ijekavianlatin]=Propalo dobavljanje tajni Name[sr@latin]=Propalo dobavljanje tajni Name[sv]=Misslyckades hämta hemligheter Name[tr]=Sırlar alınamadı Name[uk]=Не вдалося отримати дані для розпізнавання Name[x-test]=xxFailed to get secretsxx Name[zh_CN]=获取密码失败 Name[zh_TW]=取得密碼失敗 IconName=applications-internet Action=Popup [Event/FailedToUpdateConnection] Name=Failed to update connection Name[ar]=فشل تحدي الاتّصال Name[bs]=Neuspjelo ažuriranje konekcije Name[ca]=Ha fallat en actualitzar la connexió Name[ca@valencia]=Ha fallat en actualitzar la connexió Name[cs]=Spojení nelze aktualizovat Name[da]=Kunne ikke opdatere forbindelsen Name[de]=Die Verbindung kann nicht aktualisiert werden Name[el]=Αποτυχία ενημέρωσης σύνδεσης Name[en_GB]=Failed to update connection Name[es]=La actualización de la conexión ha fallado Name[et]=Ühenduse uuendamine nurjus Name[eu]=Konexioa eguneratzeak huts egin du Name[fi]=Yhteyden päivittäminen epäonnistui Name[fr]=Impossible de mettre à jour la connexion Name[gl]=Non se puido actualizar a conexión Name[he]=נכשל בעדכון חיבור Name[hu]=Nem sikerült frissíteni a kapcsolatot Name[ia]=Il falleva actualisar connexion +Name[id]=Gagal mengupdate koneksi Name[it]=Aggiornamento della connessione non riuscito Name[ko]=연결을 업데이트할 수 없음 Name[lt]=Nepavyko atnaujinti ryšio Name[nb]=Klarte ikke å oppdatere tilkobling Name[nds]=Verbinnen lett sik nich opfrischen Name[nl]=Bijwerken van verbinding is mislukt Name[nn]=Klarte ikkje å oppdatera tilkopling Name[pa]=ਕਨੈਕਸ਼ਨ ਅੱਪਡੇਟ ਕਰਨ ਲਈ ਫੇਲ੍ਹ ਹੈ Name[pl]=Nieudane uaktualnianie połączenia Name[pt]=Não foi possível actualizar a ligação Name[pt_BR]=Falha ao atualizar a conexão Name[ru]=Не удалось обновить соединение Name[sk]=Zlyhala aktualizácia pripojenia Name[sl]=Povezave ni bilo mogoče posodobiti Name[sr]=Пропало ажурирање везе Name[sr@ijekavian]=Пропало ажурирање везе Name[sr@ijekavianlatin]=Propalo ažuriranje veze Name[sr@latin]=Propalo ažuriranje veze Name[sv]=Misslyckades uppdatera anslutning Name[tr]=Bağlantı güncellenemedi Name[uk]=Не вдалося оновити з’єднання Name[x-test]=xxFailed to update connectionxx Name[zh_CN]=更新连接失败 Name[zh_TW]=更新連線失敗 IconName=applications-internet Action=Popup [Event/MissingVpnPlugin] Name=Missing VPN plugin Name[ar]=ملحقة VPN مفقودة Name[bg]=Лшпсваща приставка за VPN Name[bs]=Nedostaje VPN dodatak Name[ca]=Manca el connector VPN Name[ca@valencia]=Falta el connector VPN Name[cs]=Chybějící modul VPN Name[da]=Mangler VPN-plugin Name[de]=Fehlendes VPN-Modul Name[el]=Λείπει το πρόσθετο VPN Name[en_GB]=Missing VPN plugin Name[es]=Falta el complemento VPN Name[et]=VPN-i plugin puudub Name[eu]=VPN plugina falta da Name[fi]=Puuttuva VPN-liitännäinen Name[fr]=Module VPN manquant Name[gl]=Non se atopou o complemento de VPN Name[he]=חסר תוסף VPN Name[hu]=Hiányzó VPN bővítmény Name[ia]=Plugin de VPN mancante +Name[id]=Plugin VPN yang hilang Name[it]=Estensione VPN mancante Name[ko]=VPN 플러그인 없음 Name[lt]=Trūksta VPN papildinio Name[nb]=Mangler VPN-programtillegg Name[nds]=VPN-Moduul fehlt Name[nl]=VPN-plug-in ontbreekt Name[nn]=Manglar VPN-tillegg Name[pa]=VPN ਪਲੱਗਇਨ ਗ਼ੈਰ-ਮੌਜੂਦ ਹੈ Name[pl]=Brak wtyczki VPN Name[pt]='Plugin' de VPN em falta Name[pt_BR]=Plugin de VPN ausente Name[ru]=Отсутствует модуль VPN Name[sk]=Chýba VPN plugin Name[sl]=Manjka vstavek VPN Name[sr]=Недостаје ВПН прикључак Name[sr@ijekavian]=Недостаје ВПН прикључак Name[sr@ijekavianlatin]=Nedostaje VPN priključak Name[sr@latin]=Nedostaje VPN priključak Name[sv]=Saknar VPN-insticksprogram Name[tr]=VPN eklentisi eksik Name[uk]=Не вистачає додатка VPN Name[x-test]=xxMissing VPN pluginxx Name[zh_CN]=缺少 OpenVPN 插件 Name[zh_TW]=遺失 VPN 外掛程式 IconName=applications-internet Action=Popup [Event/NoLongerConnected] Name=No longer connected to a network Name[ar]=لم تعد متّصلًا بأيّ شّبكة Name[ca]=No connectat a cap xarxa Name[ca@valencia]=No connectat a cap xarxa Name[da]=Ikke længere forbundet til et netværk Name[de]=Nicht mehr mit einem Netzwerk verbunden Name[el]=Χωρίς σύνδεση πλέον σε κάποιο δίκτυο Name[en_GB]=No longer connected to a network Name[es]=Ya no está conectado a una red Name[et]=Pole enam võrku ühendatud Name[eu]=Jada ez dago sarera konektatuta Name[fi]=Ei enää yhteydessä verkkoon Name[fr]=Vous n'êtes plus connecté à un réseau Name[gl]=Xa non está conectado a unha rede Name[he]=לא מחובר יותר לרשת Name[hu]=Nem kapcsolódik tovább hálózathoz +Name[id]=Tidak lagi terkonek ke sebuah network Name[it]=Non più connesso a una rete Name[ko]=더 이상 네트워크에 연결되지 않음 Name[lt]=Nebeprisijungta prie tinklo Name[nl]=Niet langer verbonden met een netwerk Name[nn]=Ikkje lenger tilkopla eit nettverk Name[pa]=ਹੁਣ ਨੈੱਟਵਰਕ ਨਾਲ ਕਨੈਕਟ ਨਹੀਂ ਹੈ Name[pl]=Brak połączenia do sieci Name[pt]=Não está mais ligado a nenhuma rede Name[pt_BR]=Não está mais conectado a uma rede Name[ru]=Вы больше не подключены к сети. Name[sk]=Už nepripojený k sieti Name[sl]=Niste več povezani z omrežjem Name[sr]=Више нисте повезани на мрежу Name[sr@ijekavian]=Више нисте повезани на мрежу Name[sr@ijekavianlatin]=Više niste povezani na mrežu Name[sr@latin]=Više niste povezani na mrežu Name[sv]=Inte längre ansluten till ett nätverk Name[tr]=Artık bir ağa bağlı değil Name[uk]=Більше не з’єднано із мережею Name[x-test]=xxNo longer connected to a networkxx Name[zh_CN]=已断开网络连接 Name[zh_TW]=已不再連線到網路 IconName=applications-internet Action=Popup [Event/CaptivePortal] Name=Captive portal detected Name[ca]=S'ha detectat un portal captiu Name[ca@valencia]=S'ha detectat un portal captiu Name[da]=Captive portal detekteret Name[de]=Captive-Portal erkannt Name[en_GB]=Captive portal detected Name[es]=Se ha detectado un portal cautivo Name[et]=Tuvastati pääsuleht Name[eu]=Atari gatibua detektatu da Name[fi]=Verkon kirjautumissivu havaittu Name[fr]=Portail captif détecté Name[gl]=Detectouse un portal cativo Name[hu]=Hitelesítési portál észlelve +Name[id]=Portal tawanan terdeteksi Name[it]=Captive portal rilevato Name[ko]=인증 포털 감지됨 Name[nl]=Vangstportaal gedetecteerd Name[nn]=Oppdaga innloggingsside Name[pa]=ਕੈਪਟਿਵ ਪੋਰਟਲ ਖੋਜਿਆ Name[pl]=Wykryto portal Captive Name[pt]=Foi detectado um portal captivo Name[pt_BR]=Captive portal detectado Name[ru]=Обнаружено подключение, требующее дополнительной аутентификации. Name[sk]=Zistil sa zajatý portál Name[sl]=Zaznan prijavni portal Name[sr]=Откривен приступни портал Name[sr@ijekavian]=Откривен приступни портал Name[sr@ijekavianlatin]=Otkriven pristupni portal Name[sr@latin]=Otkriven pristupni portal Name[sv]=Captive portal detekterades Name[tr]=Captive portal tespit edildi Name[uk]=Виявлено керований портал Name[x-test]=xxCaptive portal detectedxx Name[zh_CN]=检测到强制网络门户 Name[zh_TW]=偵測到強制入口 IconName=dialog-password Action=Popup diff --git a/kded/notification.cpp b/kded/notification.cpp index 6cd36c72..9ab57456 100644 --- a/kded/notification.cpp +++ b/kded/notification.cpp @@ -1,610 +1,610 @@ /* Copyright 2009 Will Stephenson Copyright 2013 by Daniel Nicoletti Copyright 2013 Lukas Tinkl Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "debug.h" #include "notification.h" #include #include #include #include #include #include #include #include Notification::Notification(QObject *parent) : QObject(parent) { // devices Q_FOREACH (const NetworkManager::Device::Ptr &device, NetworkManager::networkInterfaces()) { addDevice(device); } connect(NetworkManager::notifier(), &NetworkManager::Notifier::deviceAdded, this, &Notification::deviceAdded); // connections Q_FOREACH (const NetworkManager::ActiveConnection::Ptr &ac, NetworkManager::activeConnections()) { addActiveConnection(ac); } - connect(NetworkManager::notifier(), &NetworkManager::Notifier::activeConnectionAdded, this, static_cast(&Notification::addActiveConnection)); + connect(NetworkManager::notifier(), &NetworkManager::Notifier::activeConnectionAdded, this, QOverload::of(&Notification::addActiveConnection)); QDBusConnection::systemBus().connect(QStringLiteral("org.freedesktop.login1"), QStringLiteral("/org/freedesktop/login1"), QStringLiteral("org.freedesktop.login1.Manager"), QStringLiteral("PrepareForSleep"), this, SLOT(onPrepareForSleep(bool))); } void Notification::deviceAdded(const QString &uni) { NetworkManager::Device::Ptr device = NetworkManager::findNetworkInterface(uni); addDevice(device); } void Notification::addDevice(const NetworkManager::Device::Ptr &device) { connect(device.data(), &NetworkManager::Device::stateChanged, this, &Notification::stateChanged); } void Notification::stateChanged(NetworkManager::Device::State newstate, NetworkManager::Device::State oldstate, NetworkManager::Device::StateChangeReason reason) { Q_UNUSED(oldstate) NetworkManager::Device *device = qobject_cast(sender()); if (newstate == NetworkManager::Device::Activated && m_notifications.contains(device->uni())) { KNotification *notify = m_notifications.value(device->uni()); notify->deleteLater(); m_notifications.remove(device->uni()); return; } else if (newstate != NetworkManager::Device::Failed) { return; } const QString identifier = UiUtils::prettyInterfaceName(device->type(), device->interfaceName()); QString text; switch (reason) { case NetworkManager::Device::NoReason: case NetworkManager::Device::UnknownReason: case NetworkManager::Device::NowManagedReason: case NetworkManager::Device::NowUnmanagedReason: return; case NetworkManager::Device::ConfigFailedReason: text = i18nc("@info:status Notification when the device failed due to ConfigFailedReason", "The device could not be configured"); break; case NetworkManager::Device::ConfigUnavailableReason: text = i18nc("@info:status Notification when the device failed due to ConfigUnavailableReason", "IP configuration was unavailable"); break; case NetworkManager::Device::ConfigExpiredReason: text = i18nc("@info:status Notification when the device failed due to ConfigExpiredReason", "IP configuration expired"); break; case NetworkManager::Device::NoSecretsReason: text = i18nc("@info:status Notification when the device failed due to NoSecretsReason", "No secrets were provided"); break; case NetworkManager::Device::AuthSupplicantDisconnectReason: text = i18nc("@info:status Notification when the device failed due to AuthSupplicantDisconnectReason", "Authorization supplicant disconnected"); break; case NetworkManager::Device::AuthSupplicantConfigFailedReason: text = i18nc("@info:status Notification when the device failed due to AuthSupplicantConfigFailedReason", "Authorization supplicant's configuration failed"); break; case NetworkManager::Device::AuthSupplicantFailedReason: text = i18nc("@info:status Notification when the device failed due to AuthSupplicantFailedReason", "Authorization supplicant failed"); break; case NetworkManager::Device::AuthSupplicantTimeoutReason: text = i18nc("@info:status Notification when the device failed due to AuthSupplicantTimeoutReason", "Authorization supplicant timed out"); break; case NetworkManager::Device::PppStartFailedReason: text = i18nc("@info:status Notification when the device failed due to PppStartFailedReason", "PPP failed to start"); break; case NetworkManager::Device::PppDisconnectReason: text = i18nc("@info:status Notification when the device failed due to PppDisconnectReason", "PPP disconnected"); break; case NetworkManager::Device::PppFailedReason: text = i18nc("@info:status Notification when the device failed due to PppFailedReason", "PPP failed"); break; case NetworkManager::Device::DhcpStartFailedReason: text = i18nc("@info:status Notification when the device failed due to DhcpStartFailedReason", "DHCP failed to start"); break; case NetworkManager::Device::DhcpErrorReason: text = i18nc("@info:status Notification when the device failed due to DhcpErrorReason", "A DHCP error occurred"); break; case NetworkManager::Device::DhcpFailedReason: text = i18nc("@info:status Notification when the device failed due to DhcpFailedReason", "DHCP failed "); break; case NetworkManager::Device::SharedStartFailedReason: text = i18nc("@info:status Notification when the device failed due to SharedStartFailedReason", "The shared service failed to start"); break; case NetworkManager::Device::SharedFailedReason: text = i18nc("@info:status Notification when the device failed due to SharedFailedReason", "The shared service failed"); break; case NetworkManager::Device::AutoIpStartFailedReason: text = i18nc("@info:status Notification when the device failed due to AutoIpStartFailedReason", "The auto IP service failed to start"); break; case NetworkManager::Device::AutoIpErrorReason: text = i18nc("@info:status Notification when the device failed due to AutoIpErrorReason", "The auto IP service reported an error"); break; case NetworkManager::Device::AutoIpFailedReason: text = i18nc("@info:status Notification when the device failed due to AutoIpFailedReason", "The auto IP service failed"); break; case NetworkManager::Device::ModemBusyReason: text = i18nc("@info:status Notification when the device failed due to ModemBusyReason", "The modem is busy"); break; case NetworkManager::Device::ModemNoDialToneReason: text = i18nc("@info:status Notification when the device failed due to ModemNoDialToneReason", "The modem has no dial tone"); break; case NetworkManager::Device::ModemNoCarrierReason: text = i18nc("@info:status Notification when the device failed due to ModemNoCarrierReason", "The modem shows no carrier"); break; case NetworkManager::Device::ModemDialTimeoutReason: text = i18nc("@info:status Notification when the device failed due to ModemDialTimeoutReason", "The modem dial timed out"); break; case NetworkManager::Device::ModemDialFailedReason: text = i18nc("@info:status Notification when the device failed due to ModemDialFailedReason", "The modem dial failed"); break; case NetworkManager::Device::ModemInitFailedReason: text = i18nc("@info:status Notification when the device failed due to ModemInitFailedReason", "The modem could not be initialized"); break; case NetworkManager::Device::GsmApnSelectFailedReason: text = i18nc("@info:status Notification when the device failed due to GsmApnSelectFailedReason", "The GSM APN could not be selected"); break; case NetworkManager::Device::GsmNotSearchingReason: text = i18nc("@info:status Notification when the device failed due to GsmNotSearchingReason", "The GSM modem is not searching"); break; case NetworkManager::Device::GsmRegistrationDeniedReason: text = i18nc("@info:status Notification when the device failed due to GsmRegistrationDeniedReason", "GSM network registration was denied"); break; case NetworkManager::Device::GsmRegistrationTimeoutReason: text = i18nc("@info:status Notification when the device failed due to GsmRegistrationTimeoutReason", "GSM network registration timed out"); break; case NetworkManager::Device::GsmRegistrationFailedReason: text = i18nc("@info:status Notification when the device failed due to GsmRegistrationFailedReason", "GSM registration failed"); break; case NetworkManager::Device::GsmPinCheckFailedReason: text = i18nc("@info:status Notification when the device failed due to GsmPinCheckFailedReason", "The GSM PIN check failed"); break; case NetworkManager::Device::FirmwareMissingReason: text = i18nc("@info:status Notification when the device failed due to FirmwareMissingReason", "Device firmware is missing"); break; case NetworkManager::Device::DeviceRemovedReason: text = i18nc("@info:status Notification when the device failed due to DeviceRemovedReason", "The device was removed"); break; case NetworkManager::Device::SleepingReason: text = i18nc("@info:status Notification when the device failed due to SleepingReason", "The networking system is now sleeping"); break; case NetworkManager::Device::ConnectionRemovedReason: text = i18nc("@info:status Notification when the device failed due to ConnectionRemovedReason", "The connection was removed"); break; case NetworkManager::Device::UserRequestedReason: return; case NetworkManager::Device::CarrierReason: text = i18nc("@info:status Notification when the device failed due to CarrierReason", "The cable was disconnected"); break; case NetworkManager::Device::ConnectionAssumedReason: case NetworkManager::Device::SupplicantAvailableReason: return; case NetworkManager::Device::ModemNotFoundReason: text = i18nc("@info:status Notification when the device failed due to ModemNotFoundReason", "The modem could not be found"); break; case NetworkManager::Device::BluetoothFailedReason: text = i18nc("@info:status Notification when the device failed due to BluetoothFailedReason", "The bluetooth connection failed or timed out"); break; case NetworkManager::Device::GsmSimNotInserted: text = i18nc("@info:status Notification when the device failed due to GsmSimNotInserted", "GSM Modem's SIM Card not inserted"); break; case NetworkManager::Device::GsmSimPinRequired: text = i18nc("@info:status Notification when the device failed due to GsmSimPinRequired", "GSM Modem's SIM Pin required"); break; case NetworkManager::Device::GsmSimPukRequired: text = i18nc("@info:status Notification when the device failed due to GsmSimPukRequired", "GSM Modem's SIM Puk required"); break; case NetworkManager::Device::GsmSimWrong: text = i18nc("@info:status Notification when the device failed due to GsmSimWrong", "GSM Modem's SIM wrong"); break; case NetworkManager::Device::InfiniBandMode: text = i18nc("@info:status Notification when the device failed due to InfiniBandMode", "InfiniBand device does not support connected mode"); break; case NetworkManager::Device::DependencyFailed: text = i18nc("@info:status Notification when the device failed due to DependencyFailed", "A dependency of the connection failed"); break; case NetworkManager::Device::Br2684Failed: text = i18nc("@info:status Notification when the device failed due to Br2684Failed", "Problem with the RFC 2684 Ethernet over ADSL bridge"); break; case NetworkManager::Device::ModemManagerUnavailable: text = i18nc("@info:status Notification when the device failed due to ModemManagerUnavailable", "ModemManager not running"); break; case NetworkManager::Device::SsidNotFound: text = i18nc("@info:status Notification when the device failed due to SsidNotFound", "The WiFi network could not be found"); break; case NetworkManager::Device::SecondaryConnectionFailed: text = i18nc("@info:status Notification when the device failed due to SecondaryConnectionFailed", "A secondary connection of the base connection failed"); break; #if NM_CHECK_VERSION(0, 9, 10) case NetworkManager::Device::DcbFcoeFailed: text = i18nc("@info:status Notification when the device failed due to DcbFcoeFailed", "DCB or FCoE setup failed"); break; case NetworkManager::Device::TeamdControlFailed: text = i18nc("@info:status Notification when the device failed due to TeamdControlFailed", "teamd control failed"); break; case NetworkManager::Device::ModemFailed: text = i18nc("@info:status Notification when the device failed due to ModemFailed", "Modem failed or no longer available"); break; case NetworkManager::Device::ModemAvailable: text = i18nc("@info:status Notification when the device failed due to ModemAvailable", "Modem now ready and available"); break; case NetworkManager::Device::SimPinIncorrect: text = i18nc("@info:status Notification when the device failed due to SimPinIncorrect", "The SIM PIN was incorrect"); break; #endif #if NM_CHECK_VERSION(1, 0, 4) case NetworkManager::Device::NewActivation: text = i18nc("@info:status Notification when the device failed due to NewActivation", "A new connection activation was enqueued"); break; case NetworkManager::Device::ParentChanged: text = i18nc("@info:status Notification when the device failed due to ParentChanged", "The device's parent changed"); break; case NetworkManager::Device::ParentManagedChanged: text = i18nc("@info:status Notification when the device failed due to ParentManagedChanged", "The device parent's management changed"); break; #endif case NetworkManager::Device::Reserved: return; } if (m_notifications.contains(device->uni())) { KNotification *notify = m_notifications.value(device->uni()); notify->setText(text); notify->update(); } else { KNotification *notify = new KNotification(QStringLiteral("DeviceFailed"), KNotification::CloseOnTimeout, this); connect(notify, &KNotification::closed, this, &Notification::notificationClosed); notify->setProperty("uni", device->uni()); notify->setComponentName(QStringLiteral("networkmanagement")); notify->setPixmap(QIcon::fromTheme(QStringLiteral("dialog-warning")).pixmap(KIconLoader::SizeHuge)); notify->setTitle(identifier); notify->setText(text); notify->sendEvent(); if (notify->id() != -1) { m_notifications[device->uni()] = notify; } } } void Notification::addActiveConnection(const QString &path) { NetworkManager::ActiveConnection::Ptr ac = NetworkManager::findActiveConnection(path); if (ac && ac->isValid()) { addActiveConnection(ac); } } void Notification::addActiveConnection(const NetworkManager::ActiveConnection::Ptr &ac) { if (ac->vpn()) { NetworkManager::VpnConnection::Ptr vpnConnection = ac.objectCast(); connect(vpnConnection.data(), &NetworkManager::VpnConnection::stateChanged, this, &Notification::onVpnConnectionStateChanged); #if NM_CHECK_VERSION(0, 9, 10) } else if (ac->type() != NetworkManager::ConnectionSettings::Bond && ac->type() != NetworkManager::ConnectionSettings::Bridge && ac->type() != NetworkManager::ConnectionSettings::Generic && ac->type() != NetworkManager::ConnectionSettings::Infiniband && ac->type() != NetworkManager::ConnectionSettings::Team && #if NM_CHECK_VERSION(1, 1, 92) ac->type() != NetworkManager::ConnectionSettings::Vlan && ac->type() != NetworkManager::ConnectionSettings::Tun) { #else ac->type() != NetworkManager::ConnectionSettings::Vlan) { #endif #else } else if (ac->type() != NetworkManager::ConnectionSettings::Bond && ac->type() != NetworkManager::ConnectionSettings::Bridge && ac->type() != NetworkManager::ConnectionSettings::Infiniband && ac->type() != NetworkManager::ConnectionSettings::Vlan) { #endif connect(ac.data(), &NetworkManager::ActiveConnection::stateChanged, this, &Notification::onActiveConnectionStateChanged); } } void Notification::onActiveConnectionStateChanged(NetworkManager::ActiveConnection::State state) { NetworkManager::ActiveConnection *ac = qobject_cast(sender()); QString eventId, text, iconName; const QString acName = ac->id(); const QString connectionId = ac->path(); if (state == NetworkManager::ActiveConnection::Activated) { auto foundConnection = std::find_if(m_activeConnectionsBeforeSleep.constBegin(), m_activeConnectionsBeforeSleep.constEnd(), [ac](const QString &uuid) { return uuid == ac->uuid(); }); if (foundConnection != m_activeConnectionsBeforeSleep.constEnd()) { qCDebug(PLASMA_NM) << "Not emitting conection activated notification as the connection was active prior to suspend"; return; } eventId = QStringLiteral("ConnectionActivated"); text = i18n("Connection '%1' activated.", acName); switch (ac->type()) { case NetworkManager::ConnectionSettings::Wireless: iconName = QStringLiteral("network-wireless-on"); break; case NetworkManager::ConnectionSettings::Wired: iconName = QStringLiteral("network-wired-activated"); break; default: // silence warning break; } } else if (state == NetworkManager::ActiveConnection::Deactivated) { if (m_preparingForSleep) { qCDebug(PLASMA_NM) << "Not emitting connection deactivated notification as we're about to suspend"; return; } eventId = QStringLiteral("ConnectionDeactivated"); text = i18n("Connection '%1' deactivated.", acName); switch (ac->type()) { case NetworkManager::ConnectionSettings::Wireless: iconName = QStringLiteral("network-wireless-disconnected"); break; case NetworkManager::ConnectionSettings::Wired: iconName = QStringLiteral("network-unavailable"); break; default: // silence warning break; } } else { qCWarning(PLASMA_NM) << "Unhandled active connection state change: " << state; return; } KNotification *notify = new KNotification(eventId, KNotification::CloseOnTimeout, this); connect(notify, &KNotification::closed, this, &Notification::notificationClosed); notify->setProperty("uni", connectionId); notify->setComponentName(QStringLiteral("networkmanagement")); if (!iconName.isEmpty()) { notify->setIconName(iconName); } else { if (state == NetworkManager::ActiveConnection::Activated) { notify->setIconName(QStringLiteral("dialog-information")); } else { notify->setIconName(QStringLiteral("dialog-warning")); } } notify->setTitle(acName); notify->setText(text); notify->sendEvent(); if (notify->id() != -1) { m_notifications[connectionId] = notify; } } void Notification::onVpnConnectionStateChanged(NetworkManager::VpnConnection::State state, NetworkManager::VpnConnection::StateChangeReason reason) { NetworkManager::VpnConnection *vpn = qobject_cast(sender()); QString eventId, text; const QString vpnName = vpn->connection()->name(); const QString connectionId = vpn->path(); if (state == NetworkManager::VpnConnection::Activated) { eventId = QStringLiteral("ConnectionActivated"); text = i18n("VPN connection '%1' activated.", vpnName); } else if (state == NetworkManager::VpnConnection::Failed) { eventId = QStringLiteral("FailedToActivateConnection"); text = i18n("VPN connection '%1' failed.", vpnName); } else if (state == NetworkManager::VpnConnection::Disconnected) { eventId = QStringLiteral("ConnectionDeactivated"); text = i18n("VPN connection '%1' disconnected.", vpnName); } else { qCWarning(PLASMA_NM) << "Unhandled VPN connection state change: " << state; return; } switch (reason) { case NetworkManager::VpnConnection::UserDisconnectedReason: text = i18n("The VPN connection changed state because the user disconnected it."); break; case NetworkManager::VpnConnection::DeviceDisconnectedReason: text = i18n("The VPN connection changed state because the device it was using was disconnected."); break; case NetworkManager::VpnConnection::ServiceStoppedReason: text = i18n("The service providing the VPN connection was stopped."); break; case NetworkManager::VpnConnection::IpConfigInvalidReason: text = i18n("The IP config of the VPN connection was invalid."); break; case NetworkManager::VpnConnection::ConnectTimeoutReason: text = i18n("The connection attempt to the VPN service timed out."); break; case NetworkManager::VpnConnection::ServiceStartTimeoutReason: text = i18n("A timeout occurred while starting the service providing the VPN connection."); break; case NetworkManager::VpnConnection::ServiceStartFailedReason: text = i18n("Starting the service providing the VPN connection failed."); break; case NetworkManager::VpnConnection::NoSecretsReason: text = i18n("Necessary secrets for the VPN connection were not provided."); break; case NetworkManager::VpnConnection::LoginFailedReason: text = i18n("Authentication to the VPN server failed."); break; case NetworkManager::VpnConnection::ConnectionRemovedReason: text = i18n("The connection was deleted from settings."); break; default: case NetworkManager::VpnConnection::UnknownReason: case NetworkManager::VpnConnection::NoneReason: break; } KNotification *notify = new KNotification(eventId, KNotification::CloseOnTimeout, this); connect(notify, &KNotification::closed, this, &Notification::notificationClosed); notify->setProperty("uni", connectionId); notify->setComponentName("networkmanagement"); if (state == NetworkManager::VpnConnection::Activated) { notify->setIconName(QStringLiteral("dialog-information")); } else { notify->setIconName(QStringLiteral("dialog-warning")); } notify->setTitle(vpnName); notify->setText(text); notify->sendEvent(); if (notify->id() != -1) { m_notifications[connectionId] = notify; } } void Notification::notificationClosed() { KNotification *notify = qobject_cast(sender()); m_notifications.remove(notify->property("uni").toString()); notify->deleteLater(); } void Notification::onPrepareForSleep(bool sleep) { m_preparingForSleep = sleep; if (m_checkActiveConnectionOnResumeTimer) { m_checkActiveConnectionOnResumeTimer->stop(); } if (sleep) { // store all active notifications so we don't show a "is connected" notification // on resume if we were connected previously m_activeConnectionsBeforeSleep.clear(); const auto &connections = NetworkManager::activeConnections(); for (const auto &connection : connections) { if (!connection->vpn() && connection->state() == NetworkManager::ActiveConnection::State::Activated) { m_activeConnectionsBeforeSleep << connection->uuid(); } } } else { if (!m_checkActiveConnectionOnResumeTimer) { m_checkActiveConnectionOnResumeTimer = new QTimer(this); m_checkActiveConnectionOnResumeTimer->setInterval(10000); m_checkActiveConnectionOnResumeTimer->setSingleShot(true); connect(m_checkActiveConnectionOnResumeTimer, &QTimer::timeout, this, &Notification::onCheckActiveConnectionOnResume); } m_checkActiveConnectionOnResumeTimer->start(); } } void Notification::onCheckActiveConnectionOnResume() { if (m_activeConnectionsBeforeSleep.isEmpty()) { // if we weren't connected before, don't bother telling us now :) return; } m_activeConnectionsBeforeSleep.clear(); const auto &connections = NetworkManager::activeConnections(); for (const auto &connection : connections) { if (connection->state() == NetworkManager::ActiveConnection::State::Activated || connection->state() == NetworkManager::ActiveConnection::State::Activating) { // we have an active or activating connection, don't tell the user we're no longer connected return; } } KNotification *notify = new KNotification(QStringLiteral("NoLongerConnected"), KNotification::CloseOnTimeout, this); connect(notify, &KNotification::closed, this, &Notification::notificationClosed); const QString uni = QStringLiteral("offlineNotification"); notify->setProperty("uni", uni); notify->setComponentName("networkmanagement"); notify->setIconName(QStringLiteral("dialog-warning")); notify->setTitle(i18n("No Network Connection")); notify->setText(i18n("You are no longer connected to a network.")); notify->sendEvent(); if (notify->id() != -1) { m_notifications[uni] = notify; } } diff --git a/kded/notification.h b/kded/notification.h index e9f2ba40..07b7f2ad 100644 --- a/kded/notification.h +++ b/kded/notification.h @@ -1,65 +1,65 @@ /* Copyright 2009 Will Stephenson Copyright 2013 by Daniel Nicoletti Copyright 2013 Lukas Tinkl Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_NOTIFICATION_H #define PLASMA_NM_NOTIFICATION_H #include #include #include class QTimer; class KNotification; class Notification : public QObject { Q_OBJECT public: - explicit Notification(QObject *parent = 0); + explicit Notification(QObject *parent = nullptr); private Q_SLOTS: void deviceAdded(const QString &uni); void addDevice(const NetworkManager::Device::Ptr &device); void stateChanged(NetworkManager::Device::State newstate, NetworkManager::Device::State oldstate, NetworkManager::Device::StateChangeReason reason); void addActiveConnection(const QString & path); void addActiveConnection(const NetworkManager::ActiveConnection::Ptr & ac); void onActiveConnectionStateChanged(NetworkManager::ActiveConnection::State state); void onVpnConnectionStateChanged(NetworkManager::VpnConnection::State state, NetworkManager::VpnConnection::StateChangeReason reason); void notificationClosed(); void onPrepareForSleep(bool sleep); void onCheckActiveConnectionOnResume(); private: QHash m_notifications; bool m_preparingForSleep = false; QStringList m_activeConnectionsBeforeSleep; QTimer *m_checkActiveConnectionOnResumeTimer = nullptr; }; #endif // PLASMA_NM_NOTIFICATION_H diff --git a/kded/passworddialog.cpp b/kded/passworddialog.cpp index 5db577c8..410d7085 100644 --- a/kded/passworddialog.cpp +++ b/kded/passworddialog.cpp @@ -1,173 +1,173 @@ /* Copyright 2013 Lukas Tinkl Copyright 2013 by Daniel Nicoletti This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "debug.h" #include "passworddialog.h" #include "ui_passworddialog.h" #include "uiutils.h" #include #include #include #include #include #include #include #include using namespace NetworkManager; PasswordDialog::PasswordDialog(const NetworkManager::ConnectionSettings::Ptr &connectionSettings, SecretAgent::GetSecretsFlags flags, const QString &setting_name, QWidget *parent) : QDialog(parent), - m_ui(0), + m_ui(nullptr), m_hasError(false), m_settingName(setting_name), m_connectionSettings(connectionSettings), m_error(SecretAgent::NoSecrets), m_flags(flags), - m_vpnWidget(0) + m_vpnWidget(nullptr) { setWindowIcon(QIcon::fromTheme(QStringLiteral("dialog-password"))); initializeUi(); } PasswordDialog::~PasswordDialog() { delete m_ui; } void PasswordDialog::initializeUi() { m_ui = new Ui::PasswordDialog; m_ui->setupUi(this); // TODO fix this for high DPI m_ui->labelIcon->setPixmap(QIcon::fromTheme(QStringLiteral("dialog-password")).pixmap(KIconLoader::SizeHuge)); m_ui->labelHeadline->setText(i18n("Authenticate %1", m_connectionSettings->id())); connect(m_ui->buttonBox, &QDialogButtonBox::accepted, this, &PasswordDialog::accept); connect(m_ui->buttonBox, &QDialogButtonBox::rejected, this, &PasswordDialog::reject); if (m_connectionSettings->connectionType() != NetworkManager::ConnectionSettings::Vpn) { NetworkManager::Setting::Ptr setting = m_connectionSettings->setting(m_settingName); m_neededSecrets = setting->needSecrets(m_flags & SecretAgent::RequestNew); if (m_neededSecrets.isEmpty()) { qCWarning(PLASMA_NM) << "list of secrets is empty!!!"; m_hasError = true; m_error = SecretAgent::InternalError; m_errorMessage = QLatin1String("No secrets were requested"); return; } WirelessSetting::Ptr wifi = m_connectionSettings->setting(Setting::Wireless).dynamicCast(); Setting::SettingType connectionType = setting->type(); if (wifi && (connectionType == Setting::WirelessSecurity || connectionType == Setting::Security8021x)) { const QString ssid = QString::fromUtf8(wifi->ssid()); m_ui->labelText->setText(i18n("For accessing the wireless network %1 you need to provide a password below:", ssid)); } else { m_ui->labelText->setText(i18n("Please provide the password for activating connection %1:", m_connectionSettings->id())); } QString connectionLabel; UiUtils::iconAndTitleForConnectionSettingsType(m_connectionSettings->connectionType(), connectionLabel); setFocusProxy(m_ui->password); setWindowTitle(i18n("%1 password dialog", connectionLabel)); } else { NetworkManager::VpnSetting::Ptr vpnSetting = m_connectionSettings->setting(Setting::Vpn).dynamicCast(); qWarning() << "VPN Setting " << *vpnSetting; if (!vpnSetting) { qCWarning(PLASMA_NM) << "Missing VPN setting!"; m_hasError = true; m_error = SecretAgent::InternalError; m_errorMessage = QLatin1String("VPN settings are missing"); } else { VpnUiPlugin *vpnUiPlugin; QString error; const QString serviceType = vpnSetting->serviceType(); vpnUiPlugin = KServiceTypeTrader::createInstanceFromQuery(QLatin1String("PlasmaNetworkManagement/VpnUiPlugin"), QString::fromLatin1("[X-NetworkManager-Services]=='%1'").arg(serviceType), this, QVariantList(), &error); if (vpnUiPlugin && error.isEmpty()) { const QString shortName = serviceType.section('.', -1); m_vpnWidget = vpnUiPlugin->askUser(vpnSetting, this); QVBoxLayout *layout = new QVBoxLayout(); layout->addWidget(m_vpnWidget); m_ui->vpnWidget->setLayout(layout); m_ui->labelText->setText(i18n("For accessing the vpn connection %1 you need to provide secrets below:", m_connectionSettings->id())); setWindowTitle(i18n("VPN secrets (%1) dialog", shortName)); // Hide generic password field and OK button in case of openconnect dialog m_ui->labelPass->setVisible(false); m_ui->password->setVisible(false); if (shortName == QLatin1String("openconnect")) { QAbstractButton *button = m_ui->buttonBox->button(QDialogButtonBox::Ok); m_ui->buttonBox->removeButton(button); } setFocusProxy(m_vpnWidget); m_vpnWidget->setFocus(Qt::OtherFocusReason); } else { qCWarning(PLASMA_NM) << error << ", serviceType == " << serviceType; m_hasError = true; m_error = SecretAgent::InternalError; m_errorMessage = error; } } } // Workaround to force m_ui->password to get focus. focusNextChild(); } bool PasswordDialog::hasError() const { return m_hasError; } SecretAgent::Error PasswordDialog::error() const { return m_error; } QString PasswordDialog::errorMessage() const { return m_errorMessage; } NMVariantMapMap PasswordDialog::secrets() const { NMVariantMapMap ret = m_connectionSettings->toMap(); QVariantMap result; if (m_vpnWidget) { result = m_vpnWidget->setting(); } else if (!m_ui->password->text().isEmpty() && !m_neededSecrets.isEmpty()) { result.insert(m_neededSecrets.first(), m_ui->password->text()); } ret.insert(m_settingName, result); return ret; } diff --git a/kded/passworddialog.h b/kded/passworddialog.h index cf7c13b7..4f95f465 100644 --- a/kded/passworddialog.h +++ b/kded/passworddialog.h @@ -1,67 +1,67 @@ /* Copyright 2013 Lukas Tinkl Copyright 2013 by Daniel Nicoletti This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_PASSWORD_DIALOG_H #define PLASMA_NM_PASSWORD_DIALOG_H #include #include #include namespace Ui { class PasswordDialog; } class SettingWidget; class Q_DECL_EXPORT PasswordDialog : public QDialog { Q_OBJECT public: explicit PasswordDialog(const NetworkManager::ConnectionSettings::Ptr &connectionSettings, NetworkManager::SecretAgent::GetSecretsFlags flags, const QString &setting_name, - QWidget *parent = 0); - ~PasswordDialog(); + QWidget *parent = nullptr); + ~PasswordDialog() override; bool hasError() const; NetworkManager::SecretAgent::Error error() const; QString errorMessage() const; NMVariantMapMap secrets() const; private: void initializeUi(); Ui::PasswordDialog *m_ui; bool m_hasError; QString m_errorMessage; QString m_settingName; QStringList m_neededSecrets; NetworkManager::ConnectionSettings::Ptr m_connectionSettings; NetworkManager::SecretAgent::Error m_error; NetworkManager::SecretAgent::GetSecretsFlags m_flags; SettingWidget *m_vpnWidget; }; #endif // PLASMA_NM_PASSWORD_DIALOG_H diff --git a/kded/passworddialog.ui b/kded/passworddialog.ui index c2322a75..7008cbb3 100644 --- a/kded/passworddialog.ui +++ b/kded/passworddialog.ui @@ -1,139 +1,139 @@ PasswordDialog 0 0 480 147 0 0 640 16777215 Password dialog 1 IconLabel 8 -1 font-weight: bold TextLabel - + 0 0 16777215 16777215 TextLabel true Password: 64 true Qt::Vertical QSizePolicy::Preferred 20 40 QDialogButtonBox::Cancel|QDialogButtonBox::Ok PasswordField QLineEdit
passwordfield.h
diff --git a/kded/pindialog.h b/kded/pindialog.h index 73d4250b..07458225 100644 --- a/kded/pindialog.h +++ b/kded/pindialog.h @@ -1,85 +1,84 @@ /* Copyright 2011 Lamarque Souza 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef PLASMA_NM_PIN_DIALOG_H #define PLASMA_NM_PIN_DIALOG_H #include #include -#include #include #include #include #include "ui_pinwidget.h" class PinWidget; class PinDialog : public QDialog { Q_OBJECT public: enum Type { SimPin, SimPin2, SimPuk, SimPuk2, ModemServiceProviderPin, ModemServiceProviderPuk, ModemNetworkPin, ModemNetworkPuk, ModemPin, ModemCorporatePin, ModemCorporatePuk, ModemPhFsimPin, ModemPhFsimPuk, ModemNetworkSubsetPin, ModemNetworkSubsetPuk }; enum ErrorCode {PinCodeTooShort, PinCodesDoNotMatch, PukCodeTooShort}; - explicit PinDialog(ModemManager::Modem *modem, const Type type = SimPin, QWidget *parent=0); - ~PinDialog(); + explicit PinDialog(ModemManager::Modem *modem, const Type type = SimPin, QWidget *parent = nullptr); + ~PinDialog() override; Type type() const; QString pin() const; QString pin2() const; QString puk() const; public Q_SLOTS: - void accept(); + void accept() override; private Q_SLOTS: void chkShowPassToggled(bool on); void modemRemoved(const QString &udi); private: void showErrorMessage(const PinDialog::ErrorCode); bool isPukDialog() const; bool isPinDialog() const; Ui::PinWidget * ui; QLabel* pixmapLabel; QString m_name; Type m_type; QString m_udi; }; #endif // PLASMA_NM_PIN_DIALOG_H diff --git a/kded/portalmonitor.h b/kded/portalmonitor.h index 303b4733..b3108e5c 100644 --- a/kded/portalmonitor.h +++ b/kded/portalmonitor.h @@ -1,41 +1,41 @@ /* * Copyright 2016 Jan Grulich * * 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) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * 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 . * */ #ifndef PLASMA_NM_PORTAL_MONITOR_H #define PLASMA_NM_PORTAL_MONITOR_H #include #include class PortalMonitor : public QObject { Q_OBJECT public: explicit PortalMonitor(QObject *parent); - ~PortalMonitor(); + ~PortalMonitor() override; private Q_SLOTS: void connectivityChanged(NetworkManager::Connectivity connectivity); void checkConnectivity(); }; #endif // PLASMA_NM_PORTAL_MONITOR_H diff --git a/kded/secretagent.cpp b/kded/secretagent.cpp index c53f7413..702c4a5a 100644 --- a/kded/secretagent.cpp +++ b/kded/secretagent.cpp @@ -1,622 +1,645 @@ /* Copyright 2013 Jan Grulich Copyright 2013 Lukas Tinkl Copyright 2013 by Daniel Nicoletti This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "passworddialog.h" #include "secretagent.h" #include "debug.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include -#include +#include SecretAgent::SecretAgent(QObject* parent) : NetworkManager::SecretAgent("org.kde.plasma.networkmanagement", parent) , m_openWalletFailed(false) - , m_wallet(0) - , m_dialog(0) + , m_wallet(nullptr) + , m_dialog(nullptr) { connect(NetworkManager::notifier(), &NetworkManager::Notifier::serviceDisappeared, this, &SecretAgent::killDialogs); // We have to import secrets previously stored in plaintext files importSecretsFromPlainTextFiles(); } SecretAgent::~SecretAgent() { } NMVariantMapMap SecretAgent::GetSecrets(const NMVariantMapMap &connection, const QDBusObjectPath &connection_path, const QString &setting_name, const QStringList &hints, uint flags) { qCDebug(PLASMA_NM) << Q_FUNC_INFO; qCDebug(PLASMA_NM) << "Path:" << connection_path.path(); qCDebug(PLASMA_NM) << "Setting name:" << setting_name; qCDebug(PLASMA_NM) << "Hints:" << hints; qCDebug(PLASMA_NM) << "Flags:" << flags; const QString callId = connection_path.path() % setting_name; Q_FOREACH (const SecretsRequest & request, m_calls) { if (request == callId) { qCWarning(PLASMA_NM) << "GetSecrets was called again! This should not happen, cancelling first call" << connection_path.path() << setting_name; CancelGetSecrets(connection_path, setting_name); break; } } setDelayedReply(true); SecretsRequest request(SecretsRequest::GetSecrets); request.callId = callId; request.connection = connection; request.connection_path = connection_path; request.flags = static_cast(flags); request.hints = hints; request.setting_name = setting_name; request.message = message(); m_calls << request; processNext(); return NMVariantMapMap(); } void SecretAgent::SaveSecrets(const NMVariantMapMap &connection, const QDBusObjectPath &connection_path) { qCDebug(PLASMA_NM) << Q_FUNC_INFO; qCDebug(PLASMA_NM) << "Path:" << connection_path.path(); // qCDebug(PLASMA_NM) << "Setting:" << connection; setDelayedReply(true); SecretsRequest::Type type; if (hasSecrets(connection)) { type = SecretsRequest::SaveSecrets; } else { type = SecretsRequest::DeleteSecrets; } SecretsRequest request(type); request.connection = connection; request.connection_path = connection_path; request.message = message(); m_calls << request; processNext(); } void SecretAgent::DeleteSecrets(const NMVariantMapMap &connection, const QDBusObjectPath &connection_path) { qCDebug(PLASMA_NM) << Q_FUNC_INFO; qCDebug(PLASMA_NM) << "Path:" << connection_path.path(); // qCDebug(PLASMA_NM) << "Setting:" << connection; setDelayedReply(true); SecretsRequest request(SecretsRequest::DeleteSecrets); request.connection = connection; request.connection_path = connection_path; request.message = message(); m_calls << request; processNext(); } void SecretAgent::CancelGetSecrets(const QDBusObjectPath &connection_path, const QString &setting_name) { qCDebug(PLASMA_NM) << Q_FUNC_INFO; qCDebug(PLASMA_NM) << "Path:" << connection_path.path(); qCDebug(PLASMA_NM) << "Setting name:" << setting_name; QString callId = connection_path.path() % setting_name; for (int i = 0; i < m_calls.size(); ++i) { SecretsRequest request = m_calls.at(i); if (request.type == SecretsRequest::GetSecrets && callId == request.callId) { if (m_dialog == request.dialog) { - m_dialog = 0; + m_dialog = nullptr; } delete request.dialog; sendError(SecretAgent::AgentCanceled, QLatin1String("Agent canceled the password dialog"), request.message); m_calls.removeAt(i); break; } } processNext(); } void SecretAgent::dialogAccepted() { for (int i = 0; i < m_calls.size(); ++i) { SecretsRequest request = m_calls[i]; if (request.type == SecretsRequest::GetSecrets && request.dialog == m_dialog) { NMStringMap tmpOpenconnectSecrets; NMVariantMapMap connection = request.dialog->secrets(); if (connection.contains(QLatin1String("vpn"))) { if (connection.value(QStringLiteral("vpn")).contains(QLatin1String("tmp-secrets"))) { QVariantMap vpnSetting = connection.value(QLatin1String("vpn")); tmpOpenconnectSecrets = qdbus_cast(vpnSetting.take(QLatin1String("tmp-secrets"))); connection.insert(QLatin1String("vpn"), vpnSetting); } } sendSecrets(connection, request.message); NetworkManager::ConnectionSettings::Ptr connectionSettings = NetworkManager::ConnectionSettings::Ptr(new NetworkManager::ConnectionSettings(connection)); NetworkManager::ConnectionSettings::Ptr completeConnectionSettings; NetworkManager::Connection::Ptr con = NetworkManager::findConnectionByUuid(connectionSettings->uuid()); if (con) { completeConnectionSettings = con->settings(); } else { completeConnectionSettings = connectionSettings; } if (request.saveSecretsWithoutReply && completeConnectionSettings->connectionType() != NetworkManager::ConnectionSettings::Vpn) { bool requestOffline = true; if (completeConnectionSettings->connectionType() == NetworkManager::ConnectionSettings::Gsm) { NetworkManager::GsmSetting::Ptr gsmSetting = completeConnectionSettings->setting(NetworkManager::Setting::Gsm).staticCast(); if (gsmSetting) { if (gsmSetting->passwordFlags().testFlag(NetworkManager::Setting::NotSaved) || gsmSetting->passwordFlags().testFlag(NetworkManager::Setting::NotRequired)) { requestOffline = false; } else if (gsmSetting->pinFlags().testFlag(NetworkManager::Setting::NotSaved) || gsmSetting->pinFlags().testFlag(NetworkManager::Setting::NotRequired)) { requestOffline = false; } } } else if (completeConnectionSettings->connectionType() == NetworkManager::ConnectionSettings::Wireless) { NetworkManager::WirelessSecuritySetting::Ptr wirelessSecuritySetting = completeConnectionSettings->setting(NetworkManager::Setting::WirelessSecurity).staticCast(); if (wirelessSecuritySetting && wirelessSecuritySetting->keyMgmt() == NetworkManager::WirelessSecuritySetting::WpaEap) { NetworkManager::Security8021xSetting::Ptr security8021xSetting = completeConnectionSettings->setting(NetworkManager::Setting::Security8021x).staticCast(); if (security8021xSetting) { if (security8021xSetting->eapMethods().contains(NetworkManager::Security8021xSetting::EapMethodFast) || security8021xSetting->eapMethods().contains(NetworkManager::Security8021xSetting::EapMethodTtls) || security8021xSetting->eapMethods().contains(NetworkManager::Security8021xSetting::EapMethodPeap)) { if (security8021xSetting->passwordFlags().testFlag(NetworkManager::Setting::NotSaved) || security8021xSetting->passwordFlags().testFlag(NetworkManager::Setting::NotRequired)) { requestOffline = false; } } } } } if (requestOffline) { SecretsRequest requestOffline(SecretsRequest::SaveSecrets); requestOffline.connection = connection; requestOffline.connection_path = request.connection_path; requestOffline.saveSecretsWithoutReply = true; m_calls << requestOffline; } } else if (request.saveSecretsWithoutReply && completeConnectionSettings->connectionType() == NetworkManager::ConnectionSettings::Vpn && !tmpOpenconnectSecrets.isEmpty()) { NetworkManager::VpnSetting::Ptr vpnSetting = completeConnectionSettings->setting(NetworkManager::Setting::Vpn).staticCast(); if (vpnSetting) { NMStringMap data = vpnSetting->data(); NMStringMap secrets = vpnSetting->secrets(); // Load secrets from auth dialog which are returned back to NM if (connection.value(QLatin1String("vpn")).contains(QLatin1String("secrets"))) { secrets.unite(qdbus_cast(connection.value(QLatin1String("vpn")).value(QLatin1String("secrets")))); } // Load temporary secrets from auth dialog which are not returned to NM Q_FOREACH (const QString &key, tmpOpenconnectSecrets.keys()) { if (secrets.contains(QLatin1Literal("save_passwords")) && secrets.value(QLatin1Literal("save_passwords")) == QLatin1String("yes")) { data.insert(key + QLatin1String("-flags"), QString::number(NetworkManager::Setting::AgentOwned)); } else { data.insert(key + QLatin1String("-flags"), QString::number(NetworkManager::Setting::NotSaved)); } secrets.insert(key, tmpOpenconnectSecrets.value(key)); } vpnSetting->setData(data); vpnSetting->setSecrets(secrets); if (!con) { con = NetworkManager::findConnection(request.connection_path.path()); } if (con) { con->update(completeConnectionSettings->toMap()); } } } m_calls.removeAt(i); break; } } m_dialog->deleteLater(); - m_dialog = 0; + m_dialog = nullptr; processNext(); } void SecretAgent::dialogRejected() { for (int i = 0; i < m_calls.size(); ++i) { SecretsRequest request = m_calls[i]; if (request.type == SecretsRequest::GetSecrets && request.dialog == m_dialog) { sendError(SecretAgent::UserCanceled, QLatin1String("User canceled the password dialog"), request.message); m_calls.removeAt(i); break; } } m_dialog->deleteLater(); - m_dialog = 0; + m_dialog = nullptr; processNext(); } void SecretAgent::killDialogs() { int i = 0; while (i < m_calls.size()) { SecretsRequest request = m_calls[i]; if (request.type == SecretsRequest::GetSecrets) { delete request.dialog; m_calls.removeAt(i); } ++i; } } void SecretAgent::walletOpened(bool success) { if (!success) { m_openWalletFailed = true; m_wallet->deleteLater(); - m_wallet = 0; + m_wallet = nullptr; } else { m_openWalletFailed = false; } processNext(); } void SecretAgent::walletClosed() { if (m_wallet) { m_wallet->deleteLater(); } - m_wallet = 0; + m_wallet = nullptr; } void SecretAgent::processNext() { int i = 0; while (i < m_calls.size()) { SecretsRequest &request = m_calls[i]; switch (request.type) { case SecretsRequest::GetSecrets: if (processGetSecrets(request)) { m_calls.removeAt(i); continue; } break; case SecretsRequest::SaveSecrets: if (processSaveSecrets(request)) { m_calls.removeAt(i); continue; } break; case SecretsRequest::DeleteSecrets: if (processDeleteSecrets(request)) { m_calls.removeAt(i); continue; } break; } ++i; } } bool SecretAgent::processGetSecrets(SecretsRequest &request) const { if (m_dialog) { return false; } NetworkManager::ConnectionSettings::Ptr connectionSettings = NetworkManager::ConnectionSettings::Ptr(new NetworkManager::ConnectionSettings(request.connection)); NetworkManager::Setting::Ptr setting = connectionSettings->setting(request.setting_name); const bool requestNew = request.flags & RequestNew; const bool userRequested = request.flags & UserRequested; const bool allowInteraction = request.flags & AllowInteraction; const bool isVpn = (setting->type() == NetworkManager::Setting::Vpn); + if (isVpn) { + NetworkManager::VpnSetting::Ptr vpnSetting = connectionSettings->setting(NetworkManager::Setting::Vpn).dynamicCast(); + if (vpnSetting->serviceType() == QLatin1String("org.freedesktop.NetworkManager.ssh") && vpnSetting->data()["auth-type"] == QLatin1String("ssh-agent")) { + QString authSock = qgetenv("SSH_AUTH_SOCK"); + qCDebug(PLASMA_NM) << Q_FUNC_INFO << "Sending SSH auth socket" << authSock; + + if (authSock.isEmpty()) { + sendError(SecretAgent::NoSecrets, + QLatin1String("SSH_AUTH_SOCK not present"), + request.message); + } else { + NMStringMap secrets; + secrets.insert(QLatin1String("ssh-auth-sock"), authSock); + + QVariantMap secretData; + secretData.insert(QLatin1String("secrets"), QVariant::fromValue(secrets)); + request.connection[request.setting_name] = secretData; + sendSecrets(request.connection, request.message); + } + return true; + } + } + NMStringMap secretsMap; if (!requestNew && useWallet()) { if (m_wallet->isOpen()) { if (m_wallet->hasFolder("Network Management") && m_wallet->setFolder("Network Management")) { QString key = QLatin1Char('{') % connectionSettings->uuid() % QLatin1Char('}') % QLatin1Char(';') % request.setting_name; m_wallet->readMap(key, secretsMap); } } else { qCDebug(PLASMA_NM) << Q_FUNC_INFO << "Waiting for the wallet to open"; return false; } } if (!secretsMap.isEmpty()) { setting->secretsFromStringMap(secretsMap); if (!isVpn && setting->needSecrets(requestNew).isEmpty()) { // Enough secrets were retrieved from storage request.connection[request.setting_name] = setting->secretsToMap(); sendSecrets(request.connection, request.message); return true; } } if (requestNew || (allowInteraction && !setting->needSecrets(requestNew).isEmpty()) || (allowInteraction && userRequested) || (isVpn && allowInteraction)) { m_dialog = new PasswordDialog(connectionSettings, request.flags, request.setting_name); connect(m_dialog, &PasswordDialog::accepted, this, &SecretAgent::dialogAccepted); connect(m_dialog, &PasswordDialog::rejected, this, &SecretAgent::dialogRejected); if (m_dialog->hasError()) { sendError(m_dialog->error(), m_dialog->errorMessage(), request.message); delete m_dialog; - m_dialog = 0; + m_dialog = nullptr; return true; } else { request.dialog = m_dialog; request.saveSecretsWithoutReply = !connectionSettings->permissions().isEmpty(); m_dialog->show(); KWindowSystem::setState(m_dialog->winId(), NET::KeepAbove); KWindowSystem::forceActiveWindow(m_dialog->winId()); return false; } } else if (isVpn && userRequested) { // just return what we have NMVariantMapMap result; NetworkManager::VpnSetting::Ptr vpnSetting; vpnSetting = connectionSettings->setting(NetworkManager::Setting::Vpn).dynamicCast(); //FIXME workaround when NM is asking for secrets which should be system-stored, if we send an empty map it // won't ask for additional secrets with AllowInteraction flag which would display the authentication dialog if (vpnSetting->secretsToMap().isEmpty()) { // Insert an empty secrets map as it was before I fixed it in NetworkManagerQt to make sure NM will ask again // with flags we need QVariantMap secretsMap; secretsMap.insert(QLatin1String("secrets"), QVariant::fromValue(NMStringMap())); result.insert("vpn", secretsMap); } else { result.insert("vpn", vpnSetting->secretsToMap()); } sendSecrets(result, request.message); return true; } else if (setting->needSecrets().isEmpty()) { NMVariantMapMap result; result.insert(setting->name(), setting->secretsToMap()); sendSecrets(result, request.message); return true; } else { sendError(SecretAgent::InternalError, QLatin1String("Plasma-nm did not know how to handle the request"), request.message); return true; } } bool SecretAgent::processSaveSecrets(SecretsRequest &request) const { if (useWallet()) { if (m_wallet->isOpen()) { NetworkManager::ConnectionSettings connectionSettings(request.connection); if (!m_wallet->hasFolder("Network Management")) { m_wallet->createFolder("Network Management"); } if (m_wallet->setFolder("Network Management")) { Q_FOREACH (const NetworkManager::Setting::Ptr &setting, connectionSettings.settings()) { NMStringMap secretsMap = setting->secretsToStringMap(); if (!secretsMap.isEmpty()) { QString entryName = QLatin1Char('{') % connectionSettings.uuid() % QLatin1Char('}') % QLatin1Char(';') % setting->name(); m_wallet->writeMap(entryName, secretsMap); } } } else if (!request.saveSecretsWithoutReply) { sendError(SecretAgent::InternalError, QLatin1String("Could not store secrets in the wallet."), request.message); return true; } } else { qCDebug(PLASMA_NM) << Q_FUNC_INFO << "Waiting for the wallet to open"; return false; } } if (!request.saveSecretsWithoutReply) { QDBusMessage reply = request.message.createReply(); if (!QDBusConnection::systemBus().send(reply)) { qCWarning(PLASMA_NM) << "Failed put save secrets reply into the queue"; } } return true; } bool SecretAgent::processDeleteSecrets(SecretsRequest &request) const { if (useWallet()) { if (m_wallet->isOpen()) { if (m_wallet->hasFolder("Network Management") && m_wallet->setFolder("Network Management")) { NetworkManager::ConnectionSettings connectionSettings(request.connection); Q_FOREACH (const NetworkManager::Setting::Ptr &setting, connectionSettings.settings()) { QString entryName = QLatin1Char('{') % connectionSettings.uuid() % QLatin1Char('}') % QLatin1Char(';') % setting->name(); Q_FOREACH (const QString &entry, m_wallet->entryList()) { if (entry.startsWith(entryName)) { m_wallet->removeEntry(entryName); } } } } } else { qCDebug(PLASMA_NM) << Q_FUNC_INFO << "Waiting for the wallet to open"; return false; } } QDBusMessage reply = request.message.createReply(); if (!QDBusConnection::systemBus().send(reply)) { qCWarning(PLASMA_NM) << "Failed put delete secrets reply into the queue"; } return true; } bool SecretAgent::useWallet() const { if (m_wallet) { return true; } /* If opening of KWallet failed before, we should not try to open it again and * we should return false instead */ if (m_openWalletFailed) { m_openWalletFailed = false; return false; } if (KWallet::Wallet::isEnabled()) { m_wallet = KWallet::Wallet::openWallet(KWallet::Wallet::LocalWallet(), 0, KWallet::Wallet::Asynchronous); if (m_wallet) { connect(m_wallet, &KWallet::Wallet::walletOpened, this, &SecretAgent::walletOpened); connect(m_wallet, &KWallet::Wallet::walletClosed, this, &SecretAgent::walletClosed); return true; } else { qCWarning(PLASMA_NM) << "Error opening kwallet."; } } else if (m_wallet) { m_wallet->deleteLater(); - m_wallet = 0; + m_wallet = nullptr; } return false; } bool SecretAgent::hasSecrets(const NMVariantMapMap &connection) const { NetworkManager::ConnectionSettings connectionSettings(connection); Q_FOREACH (const NetworkManager::Setting::Ptr &setting, connectionSettings.settings()) { if (!setting->secretsToMap().isEmpty()) { return true; } } return false; } void SecretAgent::sendSecrets(const NMVariantMapMap &secrets, const QDBusMessage &message) const { QDBusMessage reply; reply = message.createReply(QVariant::fromValue(secrets)); if (!QDBusConnection::systemBus().send(reply)) { qCWarning(PLASMA_NM) << "Failed put the secret into the queue"; } } void SecretAgent::importSecretsFromPlainTextFiles() { KConfig config(QLatin1String("plasma-networkmanagement"), KConfig::SimpleConfig); // No action is required when the list of secrets is empty if (!config.groupList().isEmpty()) { Q_FOREACH (const QString &groupName, config.groupList()) { QString loadedUuid = groupName.split(';').first().remove('{').remove('}'); QString loadedSettingType = groupName.split(';').last(); NetworkManager::Connection::Ptr connection = NetworkManager::findConnectionByUuid(loadedUuid); if (connection) { NetworkManager::Setting::SecretFlags secretFlags = KWallet::Wallet::isEnabled() ? NetworkManager::Setting::AgentOwned : NetworkManager::Setting::None; QMap secrets = config.entryMap(groupName); NMVariantMapMap settings = connection->settings()->toMap(); Q_FOREACH (const QString &setting, settings.keys()) { if (setting == QLatin1String("vpn")) { NetworkManager::VpnSetting::Ptr vpnSetting = connection->settings()->setting(NetworkManager::Setting::Vpn).staticCast(); if (vpnSetting) { // Add loaded secrets from the config file vpnSetting->secretsFromStringMap(secrets); NMStringMap vpnData = vpnSetting->data(); // Reset flags, we can't save secrets to our secret agent when KWallet is not enabled, because // we dropped support for plaintext files, therefore they need to be stored to NetworkManager Q_FOREACH (const QString &key, vpnData.keys()) { if (key.endsWith(QLatin1String("-flags"))) { vpnData.insert(key, QString::number((int)secretFlags)); } } vpnSetting->setData(vpnData); settings.insert(setting, vpnSetting->toMap()); connection->update(settings); } } else { if (setting == loadedSettingType) { QVariantMap tmpSetting = settings.value(setting); // Reset flags, we can't save secrets to our secret agent when KWallet is not enabled, because // we dropped support for plaintext files, therefore they need to be stored to NetworkManager Q_FOREACH (const QString &key, tmpSetting.keys()) { if (key.endsWith(QLatin1String("-flags"))) { tmpSetting.insert(key, (int)secretFlags); } } // Add loaded secrets from the config file QMap::const_iterator it = secrets.constBegin(); QMap::const_iterator end = secrets.constEnd(); for (; it != end; ++it) { tmpSetting.insert(it.key(), it.value()); } // Replace the old setting with the new one settings.insert(setting, tmpSetting); // Update the connection which re-saves secrets connection->update(settings); } } } } // Remove the group KConfigGroup group(&config, groupName); group.deleteGroup(); } } } diff --git a/kded/secretagent.h b/kded/secretagent.h index 3ae9f2ac..4228f514 100644 --- a/kded/secretagent.h +++ b/kded/secretagent.h @@ -1,125 +1,125 @@ /* Copyright 2013 Jan Grulich Copyright 2013 Lukas Tinkl Copyright 2013 by Daniel Nicoletti This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_SECRET_AGENT_H #define PLASMA_NM_SECRET_AGENT_H #include namespace KWallet { class Wallet; } class PasswordDialog; class SecretsRequest { public: enum Type { GetSecrets, SaveSecrets, DeleteSecrets }; explicit SecretsRequest(Type _type) : type(_type), flags(NetworkManager::SecretAgent::None), saveSecretsWithoutReply(false), - dialog(0) + dialog(nullptr) {} inline bool operator==(const QString &other) const { return callId == other; } Type type; QString callId; NMVariantMapMap connection; QDBusObjectPath connection_path; QString setting_name; QStringList hints; NetworkManager::SecretAgent::GetSecretsFlags flags; /** * When a user connection is called on GetSecrets, * the secret agent is supposed to save the secrets * typed by user, when true proccessSaveSecrets * should skip the DBus reply. */ bool saveSecretsWithoutReply; QDBusMessage message; PasswordDialog *dialog; }; class Q_DECL_EXPORT SecretAgent : public NetworkManager::SecretAgent { Q_OBJECT public: - explicit SecretAgent(QObject* parent = 0); - virtual ~SecretAgent(); + explicit SecretAgent(QObject* parent = nullptr); + ~SecretAgent() override; public Q_SLOTS: - virtual NMVariantMapMap GetSecrets(const NMVariantMapMap&, const QDBusObjectPath&, const QString&, const QStringList&, uint) Q_DECL_OVERRIDE; - virtual void SaveSecrets(const NMVariantMapMap &connection, const QDBusObjectPath &connection_path) Q_DECL_OVERRIDE; - virtual void DeleteSecrets(const NMVariantMapMap &, const QDBusObjectPath &) Q_DECL_OVERRIDE; - virtual void CancelGetSecrets(const QDBusObjectPath &, const QString &) Q_DECL_OVERRIDE; + NMVariantMapMap GetSecrets(const NMVariantMapMap&, const QDBusObjectPath&, const QString&, const QStringList&, uint) override; + void SaveSecrets(const NMVariantMapMap &connection, const QDBusObjectPath &connection_path) override; + void DeleteSecrets(const NMVariantMapMap &, const QDBusObjectPath &) override; + void CancelGetSecrets(const QDBusObjectPath &, const QString &) override; private Q_SLOTS: void dialogAccepted(); void dialogRejected(); void killDialogs(); void walletOpened(bool success); void walletClosed(); private: void processNext(); /** * @brief processGetSecrets requests * @param request the request we are processing * @param ignoreWallet true if the code should avoid Wallet * nomally if it failed to open * @return true if the item was processed */ bool processGetSecrets(SecretsRequest &request) const; bool processSaveSecrets(SecretsRequest &request) const; bool processDeleteSecrets(SecretsRequest &request) const; /** * @brief useWallet checks if the KWallet system is enabled * and tries to open it async. * @return return true if the method should use the wallet, * the caller MUST always check if the wallet is opened. */ bool useWallet() const; /** * @brief hasSecrets verifies if the desired connection has secrets to store * @param connection map with or without secrets * @return true if the connection has secrets, false otherwise */ bool hasSecrets(const NMVariantMapMap &connection) const; void sendSecrets(const NMVariantMapMap &secrets, const QDBusMessage &message) const; mutable bool m_openWalletFailed; mutable KWallet::Wallet *m_wallet; mutable PasswordDialog *m_dialog; QList m_calls; void importSecretsFromPlainTextFiles(); }; #endif // PLASMA_NM_SECRET_AGENT_H diff --git a/kded/service.h b/kded/service.h index 59106692..a865e3c8 100644 --- a/kded/service.h +++ b/kded/service.h @@ -1,56 +1,56 @@ /* Copyright 2009 Dario Freddi Copyright 2009 Will Stephenson Copyright 2012 Lamarque V. Souza Copyright 2013 Lukas Tinkl Copyright 2013-2014 Jan Grulich 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef PLASMANM_KDED_SERVICE_H #define PLASMANM_KDED_SERVICE_H #include #include class NetworkManagementServicePrivate; class Q_DECL_EXPORT NetworkManagementService : public KDEDModule { Q_CLASSINFO("D-Bus Interface", "org.kde.plasmanetworkmanagement") Q_OBJECT Q_DECLARE_PRIVATE(NetworkManagementService) public: NetworkManagementService(QObject * parent, const QVariantList&); - virtual ~NetworkManagementService(); + ~NetworkManagementService() override; public Q_SLOTS: Q_SCRIPTABLE void init(); Q_SIGNALS: Q_SCRIPTABLE void registered(); private Q_SLOTS: void slotRegistered(const QDBusObjectPath &path); private: NetworkManagementServicePrivate * const d_ptr; }; #endif // PLASMANM_KDED_SERVICE_H diff --git a/libs/CMakeLists.txt b/libs/CMakeLists.txt index 0468e51d..29e7298a 100644 --- a/libs/CMakeLists.txt +++ b/libs/CMakeLists.txt @@ -1,41 +1,41 @@ add_definitions(-DTRANSLATION_DOMAIN=\"plasmanetworkmanagement-libs\") set(plasmanm_internal_SRCS models/appletproxymodel.cpp models/creatableconnectionsmodel.cpp models/editorproxymodel.cpp models/kcmidentitymodel.cpp models/mobileproxymodel.cpp models/networkitemslist.cpp models/networkmodel.cpp models/networkmodelitem.cpp configuration.cpp debug.cpp handler.cpp uiutils.cpp ) add_library(plasmanm_internal SHARED ${plasmanm_internal_SRCS}) target_link_libraries(plasmanm_internal - plasmanm_editor +PUBLIC KF5::NetworkManagerQt - KF5::Solid - KF5::Completion + plasmanm_editor +PRIVATE + KF5::Service KF5::I18n KF5::IconThemes - KF5::Plasma KF5::Notifications - Qt5::Xml - Qt5::Network + KF5::Wallet + KF5::WindowSystem ) if (WITH_MODEMMANAGER_SUPPORT) - target_link_libraries(plasmanm_internal KF5::ModemManagerQt) + target_link_libraries(plasmanm_internal PUBLIC KF5::ModemManagerQt) endif() install(TARGETS plasmanm_internal ${INSTALL_TARGETS_DEFAULT_ARGS}) add_subdirectory(declarative) add_subdirectory(editor) diff --git a/libs/declarative/CMakeLists.txt b/libs/declarative/CMakeLists.txt index 4bd177c7..275cd531 100644 --- a/libs/declarative/CMakeLists.txt +++ b/libs/declarative/CMakeLists.txt @@ -1,30 +1,26 @@ include_directories(${CMAKE_SOURCE_DIR}/libs/models) set(plasmanm_qml_plugins_SRCS availabledevices.cpp connectionicon.cpp enabledconnections.cpp enums.cpp networkstatus.cpp qmlplugins.cpp ) add_library(plasmanm_qmlplugins SHARED ${plasmanm_qml_plugins_SRCS}) target_link_libraries(plasmanm_qmlplugins plasmanm_internal plasmanm_editor Qt5::Quick - Qt5::DBus - Qt5::Network - KF5::NetworkManagerQt KF5::I18n - KF5::WindowSystem ) if (WITH_MODEMMANAGER_SUPPORT) target_link_libraries(plasmanm_qmlplugins KF5::ModemManagerQt) endif() -install(TARGETS plasmanm_qmlplugins DESTINATION ${QML_INSTALL_DIR}/org/kde/plasma/networkmanagement) -install(FILES qmldir DESTINATION ${QML_INSTALL_DIR}/org/kde/plasma/networkmanagement) +install(TARGETS plasmanm_qmlplugins DESTINATION ${KDE_INSTALL_QMLDIR}/org/kde/plasma/networkmanagement) +install(FILES qmldir DESTINATION ${KDE_INSTALL_QMLDIR}/org/kde/plasma/networkmanagement) diff --git a/libs/declarative/availabledevices.h b/libs/declarative/availabledevices.h index 99aa1063..7a65988f 100644 --- a/libs/declarative/availabledevices.h +++ b/libs/declarative/availabledevices.h @@ -1,76 +1,76 @@ /* Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_AVAILABLE_DEVICES_H #define PLASMA_NM_AVAILABLE_DEVICES_H #include #include class AvailableDevices : public QObject { /** * Return true when there is present wired device */ Q_PROPERTY(bool wiredDeviceAvailable READ isWiredDeviceAvailable NOTIFY wiredDeviceAvailableChanged) /** * Return true when there is present wireless device */ Q_PROPERTY(bool wirelessDeviceAvailable READ isWirelessDeviceAvailable NOTIFY wirelessDeviceAvailableChanged) /** * Return true when there is present modem device */ Q_PROPERTY(bool modemDeviceAvailable READ isModemDeviceAvailable NOTIFY modemDeviceAvailableChanged) /** * Return true when there is present bluetooth device * Bluetooth device is visible for NetworkManager only when there is some Bluetooth connection */ Q_PROPERTY(bool bluetoothDeviceAvailable READ isBluetoothDeviceAvailable NOTIFY bluetoothDeviceAvailableChanged) Q_OBJECT public: - explicit AvailableDevices(QObject* parent = 0); - virtual ~AvailableDevices(); + explicit AvailableDevices(QObject* parent = nullptr); + ~AvailableDevices() override; public Q_SLOTS: bool isWiredDeviceAvailable() const; bool isWirelessDeviceAvailable() const; bool isModemDeviceAvailable() const; bool isBluetoothDeviceAvailable() const; private Q_SLOTS: void deviceAdded(const QString& dev); void deviceRemoved(); Q_SIGNALS: void wiredDeviceAvailableChanged(bool available); void wirelessDeviceAvailableChanged(bool available); void modemDeviceAvailableChanged(bool available); void bluetoothDeviceAvailableChanged(bool available); private: bool m_wiredDeviceAvailable; bool m_wirelessDeviceAvailable; bool m_modemDeviceAvailable; bool m_bluetoothDeviceAvailable; }; #endif // PLASMA_NM_AVAILABLE_DEVICES_H diff --git a/libs/declarative/connectionicon.cpp b/libs/declarative/connectionicon.cpp index b792f924..a3f0caee 100644 --- a/libs/declarative/connectionicon.cpp +++ b/libs/declarative/connectionicon.cpp @@ -1,681 +1,681 @@ /* Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "connectionicon.h" #include "uiutils.h" #include #include #include #include #include #include #include #include #include #if WITH_MODEMMANAGER_SUPPORT #include #include #endif ConnectionIcon::ConnectionIcon(QObject* parent) : QObject(parent) , m_signal(0) - , m_wirelessNetwork(0) + , m_wirelessNetwork(nullptr) , m_connecting(false) , m_limited(false) , m_vpn(false) , m_airplaneMode(false) #if WITH_MODEMMANAGER_SUPPORT - , m_modemNetwork(0) + , m_modemNetwork(nullptr) #endif { connect(NetworkManager::notifier(), &NetworkManager::Notifier::primaryConnectionChanged, this, &ConnectionIcon::primaryConnectionChanged); connect(NetworkManager::notifier(), &NetworkManager::Notifier::activatingConnectionChanged, this, &ConnectionIcon::activatingConnectionChanged); connect(NetworkManager::notifier(), &NetworkManager::Notifier::activeConnectionAdded, this, &ConnectionIcon::activeConnectionAdded); connect(NetworkManager::notifier(), &NetworkManager::Notifier::connectivityChanged, this, &ConnectionIcon::connectivityChanged); connect(NetworkManager::notifier(), &NetworkManager::Notifier::deviceAdded, this, &ConnectionIcon::deviceAdded); connect(NetworkManager::notifier(), &NetworkManager::Notifier::deviceRemoved, this, &ConnectionIcon::deviceRemoved); connect(NetworkManager::notifier(), &NetworkManager::Notifier::networkingEnabledChanged, this, &ConnectionIcon::networkingEnabledChanged); connect(NetworkManager::notifier(), &NetworkManager::Notifier::statusChanged, this, &ConnectionIcon::statusChanged); connect(NetworkManager::notifier(), &NetworkManager::Notifier::wirelessEnabledChanged, this, &ConnectionIcon::wirelessEnabledChanged); connect(NetworkManager::notifier(), &NetworkManager::Notifier::wirelessHardwareEnabledChanged, this, &ConnectionIcon::wirelessEnabledChanged); connect(NetworkManager::notifier(), &NetworkManager::Notifier::wwanEnabledChanged, this, &ConnectionIcon::wwanEnabledChanged); connect(NetworkManager::notifier(), &NetworkManager::Notifier::wwanHardwareEnabledChanged, this, &ConnectionIcon::wwanEnabledChanged); Q_FOREACH (NetworkManager::Device::Ptr device, NetworkManager::networkInterfaces()) { if (device->type() == NetworkManager::Device::Ethernet) { NetworkManager::WiredDevice::Ptr wiredDevice = device.staticCast(); if (wiredDevice) { connect(wiredDevice.data(), &NetworkManager::WiredDevice::carrierChanged, this, &ConnectionIcon::carrierChanged); } } else if (device->type() == NetworkManager::Device::Wifi) { NetworkManager::WirelessDevice::Ptr wifiDevice = device.staticCast(); if (wifiDevice) { connect(wifiDevice.data(), &NetworkManager::WirelessDevice::availableConnectionAppeared, this, &ConnectionIcon::wirelessNetworkAppeared); connect(wifiDevice.data(), &NetworkManager::WirelessDevice::networkAppeared, this, &ConnectionIcon::wirelessNetworkAppeared); } } } Q_FOREACH (NetworkManager::ActiveConnection::Ptr activeConnection, NetworkManager::activeConnections()) { addActiveConnection(activeConnection->path()); } setStates(); connectivityChanged(); + setIcons(); } ConnectionIcon::~ConnectionIcon() { } bool ConnectionIcon::connecting() const { return m_connecting; } QString ConnectionIcon::connectionIcon() const { if (m_vpn && !m_connectionIcon.contains("available")) { return m_connectionIcon + "-locked"; } if (m_limited && !m_connectionIcon.contains("available")) { return m_connectionIcon + "-limited"; } return m_connectionIcon; } QString ConnectionIcon::connectionTooltipIcon() const { return m_connectionTooltipIcon; } bool ConnectionIcon::airplaneMode() const { return m_airplaneMode; } void ConnectionIcon::setAirplaneMode(bool airplaneMode) { if (m_airplaneMode != airplaneMode) { m_airplaneMode = airplaneMode; Q_EMIT airplaneModeChanged(airplaneMode); setIcons(); } } void ConnectionIcon::activatingConnectionChanged(const QString& connection) { Q_UNUSED(connection); setIcons(); } void ConnectionIcon::addActiveConnection(const QString &activeConnection) { NetworkManager::ActiveConnection::Ptr active = NetworkManager::findActiveConnection(activeConnection); if (active) { NetworkManager::VpnConnection::Ptr vpnConnection; connect(active.data(), &NetworkManager::ActiveConnection::destroyed, this, &ConnectionIcon::activeConnectionDestroyed); if (active->vpn()) { vpnConnection = active.objectCast(); connect(vpnConnection.data(), &NetworkManager::VpnConnection::stateChanged, this, &ConnectionIcon::vpnConnectionStateChanged); } else { connect(active.data(), &NetworkManager::ActiveConnection::stateChanged, this, &ConnectionIcon::activeConnectionStateChanged, Qt::UniqueConnection); } } } void ConnectionIcon::activeConnectionAdded(const QString &activeConnection) { addActiveConnection(activeConnection); setStates(); } void ConnectionIcon::activeConnectionStateChanged(NetworkManager::ActiveConnection::State state) { Q_UNUSED(state); setStates(); } void ConnectionIcon::activeConnectionDestroyed() { setStates(); } void ConnectionIcon::carrierChanged(bool carrier) { Q_UNUSED(carrier); setIcons(); } void ConnectionIcon::connectivityChanged() { NetworkManager::Connectivity conn = NetworkManager::connectivity(); - m_limited = (conn == NetworkManager::Portal || conn == NetworkManager::Limited); - setIcons(); + setLimited(conn == NetworkManager::Portal || conn == NetworkManager::Limited); } void ConnectionIcon::deviceAdded(const QString& device) { NetworkManager::Device::Ptr dev = NetworkManager::findNetworkInterface(device); if (!dev) { return; } if (dev->type() == NetworkManager::Device::Ethernet) { NetworkManager::WiredDevice::Ptr wiredDev = dev.objectCast(); connect(wiredDev.data(), &NetworkManager::WiredDevice::carrierChanged, this, &ConnectionIcon::carrierChanged); } } void ConnectionIcon::deviceRemoved(const QString& device) { Q_UNUSED(device); if (NetworkManager::status() == NetworkManager::Disconnected) { setDisconnectedIcon(); } } #if WITH_MODEMMANAGER_SUPPORT void ConnectionIcon::modemNetworkRemoved() { m_modemNetwork.clear(); } void ConnectionIcon::modemSignalChanged(const ModemManager::SignalQualityPair &signalQuality) { int diff = m_signal - signalQuality.signal; if (diff >= 10 || diff <= -10) { m_signal = signalQuality.signal; setIconForModem(); } } #endif void ConnectionIcon::networkingEnabledChanged(bool enabled) { if (!enabled) { setConnectionIcon("network-unavailable"); } } void ConnectionIcon::primaryConnectionChanged(const QString& connection) { if (!connection.isEmpty()) { setIcons(); } } void ConnectionIcon::statusChanged(NetworkManager::Status status) { if (status == NetworkManager::Disconnected) { setDisconnectedIcon(); } } void ConnectionIcon::vpnConnectionStateChanged(NetworkManager::VpnConnection::State state, NetworkManager::VpnConnection::StateChangeReason reason) { Q_UNUSED(state); Q_UNUSED(reason); setStates(); setIcons(); } void ConnectionIcon::wirelessEnabledChanged(bool enabled) { Q_UNUSED(enabled); setIcons(); } void ConnectionIcon::wwanEnabledChanged(bool enabled) { Q_UNUSED(enabled); setIcons(); } void ConnectionIcon::wirelessNetworkAppeared(const QString& network) { Q_UNUSED(network); setIcons(); } void ConnectionIcon::setStates() { bool connecting = false; bool vpn = false; Q_FOREACH (NetworkManager::ActiveConnection::Ptr activeConnection, NetworkManager::activeConnections()) { NetworkManager::VpnConnection::Ptr vpnConnection; if (activeConnection->vpn()) { vpnConnection = activeConnection.objectCast(); } if (!vpnConnection) { if (activeConnection->state() == NetworkManager::ActiveConnection::Activating && UiUtils::isConnectionTypeSupported(activeConnection->type())) { connecting = true; } } else { if (vpnConnection->state() == NetworkManager::VpnConnection::Activated) { vpn = true; } else if (vpnConnection->state() == NetworkManager::VpnConnection::Prepare || vpnConnection->state() == NetworkManager::VpnConnection::NeedAuth || vpnConnection->state() == NetworkManager::VpnConnection::Connecting || vpnConnection->state() == NetworkManager::VpnConnection::GettingIpConfig) { connecting = true; } } } setVpn(vpn); setConnecting(connecting); } void ConnectionIcon::setIcons() { m_signal = 0; #if WITH_MODEMMANAGER_SUPPORT if (m_modemNetwork) { - disconnect(m_modemNetwork.data(), 0, this, 0); + disconnect(m_modemNetwork.data(), nullptr, this, nullptr); m_modemNetwork.clear(); } #endif if (m_wirelessNetwork) { - disconnect(m_wirelessNetwork.data(), 0, this, 0); + disconnect(m_wirelessNetwork.data(), nullptr, this, nullptr); m_wirelessNetwork.clear(); } NetworkManager::ActiveConnection::Ptr connection = NetworkManager::activatingConnection(); if (!connection) { connection = NetworkManager::primaryConnection(); } // Workaround, because PrimaryConnection is kinda broken in NM 0.9.8.x and // doesn't work correctly with some VPN connections. This shouldn't be necessary // for NM 0.9.9.0 or the upcoming bugfix release NM 0.9.8.10 #if !NM_CHECK_VERSION(0, 9, 10) if (!connection) { bool defaultRoute = false; NetworkManager::ActiveConnection::Ptr mainActiveConnection; Q_FOREACH (const NetworkManager::ActiveConnection::Ptr & activeConnection, NetworkManager::activeConnections()) { if ((activeConnection->default4() || activeConnection->default6()) && activeConnection->vpn()) { defaultRoute = true; mainActiveConnection = activeConnection; break; } } if (!defaultRoute) { Q_FOREACH (const NetworkManager::ActiveConnection::Ptr & activeConnection, NetworkManager::activeConnections()) { if (activeConnection->vpn()) { mainActiveConnection = activeConnection; break; } } } if (mainActiveConnection) { NetworkManager::ActiveConnection::Ptr baseActiveConnection; baseActiveConnection = NetworkManager::findActiveConnection(mainActiveConnection->specificObject()); if (baseActiveConnection) { connection = baseActiveConnection; } } } #endif /* Fallback: If we still don't have an active connection with default route or the default route goes through a connection of generic type (some type of VPNs) we need to go through all other active connections and pick the one with hightest probability of being the main one (order is: vpn, wired, wireless, gsm, cdma, bluetooth) */ #if NM_CHECK_VERSION(1, 2, 0) if ((!connection && !NetworkManager::activeConnections().isEmpty()) || (connection && connection->type() == NetworkManager::ConnectionSettings::Generic) || (connection && connection->type() == NetworkManager::ConnectionSettings::Tun)) { #elif NM_CHECK_VERSION(0, 9, 10) if ((!connection && !NetworkManager::activeConnections().isEmpty()) || (connection && connection->type() == NetworkManager::ConnectionSettings::Generic)) { #else if (!connection && !NetworkManager::activeConnections().isEmpty()) { #endif #if NM_CHECK_VERSION(0, 9, 10) Q_FOREACH (const NetworkManager::ActiveConnection::Ptr &activeConnection, NetworkManager::activeConnections()) { const NetworkManager::ConnectionSettings::ConnectionType type = activeConnection->type(); if (type == NetworkManager::ConnectionSettings::Bluetooth) { if (connection && connection->type() <= NetworkManager::ConnectionSettings::Bluetooth) { connection = activeConnection; } } else if (type == NetworkManager::ConnectionSettings::Cdma) { if (connection && connection->type() <= NetworkManager::ConnectionSettings::Cdma) { connection = activeConnection; } } else if (type == NetworkManager::ConnectionSettings::Gsm) { if (connection && connection->type() <= NetworkManager::ConnectionSettings::Gsm) { connection = activeConnection; } } else if (type == NetworkManager::ConnectionSettings::Vpn) { connection = activeConnection; } else if (type == NetworkManager::ConnectionSettings::Wired) { if (connection && connection->type() != NetworkManager::ConnectionSettings::Vpn) { connection = activeConnection; } } else if (type == NetworkManager::ConnectionSettings::Wireless) { if (connection && (connection->type() != NetworkManager::ConnectionSettings::Vpn && (connection->type() != NetworkManager::ConnectionSettings::Wired))) { connection = activeConnection; } } } #else connection = NetworkManager::activeConnections().first(); #endif } if (connection && !connection->devices().isEmpty()) { NetworkManager::Device::Ptr device = NetworkManager::findNetworkInterface(connection->devices().first()); if (device) { NetworkManager::Device::Type type = device->type(); if (type == NetworkManager::Device::Wifi) { NetworkManager::WirelessDevice::Ptr wifiDevice = device.objectCast(); if (wifiDevice->mode() == NetworkManager::WirelessDevice::Adhoc) { setWirelessIconForSignalStrength(100); } else { NetworkManager::AccessPoint::Ptr ap = wifiDevice->activeAccessPoint(); if (ap) { setWirelessIcon(device, ap->ssid()); } } } else if (type == NetworkManager::Device::Ethernet) { setConnectionIcon("network-wired-activated"); setConnectionTooltipIcon("network-wired-activated"); } else if (type == NetworkManager::Device::Modem) { #if WITH_MODEMMANAGER_SUPPORT setModemIcon(device); #else setConnectionIcon("network-mobile-0"); setConnectionTooltipIcon("phone"); #endif } else if (type == NetworkManager::Device::Bluetooth) { NetworkManager::BluetoothDevice::Ptr btDevice = device.objectCast(); if (btDevice) { if (btDevice->bluetoothCapabilities().testFlag(NetworkManager::BluetoothDevice::Dun)) { #if WITH_MODEMMANAGER_SUPPORT setModemIcon(device); #else setConnectionIcon("network-mobile-0"); setConnectionTooltipIcon("phone"); #endif } else { setConnectionIcon("network-bluetooth-activated"); setConnectionTooltipIcon("preferences-system-bluetooth"); } } } else { // Ignore other devices (bond/bridge/team etc.) setDisconnectedIcon(); } } } else { setDisconnectedIcon(); } } void ConnectionIcon::setDisconnectedIcon() { if (m_airplaneMode) { setConnectionIcon(QStringLiteral("network-flightmode-on")); return; } if (NetworkManager::status() == NetworkManager::Unknown || NetworkManager::status() == NetworkManager::Asleep) { setConnectionIcon("network-unavailable"); return; } bool wired = false; bool wireless = false; bool modem = false; m_limited = false; m_vpn = false; Q_FOREACH (const NetworkManager::Device::Ptr &device, NetworkManager::networkInterfaces()) { if (device->type() == NetworkManager::Device::Ethernet) { NetworkManager::WiredDevice::Ptr wiredDev = device.objectCast(); if (wiredDev->carrier()) { wired = true; } } else if (device->type() == NetworkManager::Device::Wifi && NetworkManager::isWirelessEnabled() && NetworkManager::isWirelessHardwareEnabled()) { NetworkManager::WirelessDevice::Ptr wifiDevice = device.objectCast(); if (!wifiDevice->accessPoints().isEmpty() || !wifiDevice->availableConnections().isEmpty()) { wireless = true; } } else if (device->type() == NetworkManager::Device::Modem && NetworkManager::isWwanEnabled() && NetworkManager::isWwanHardwareEnabled()) { modem = true; } } if (wired) { setConnectionIcon("network-wired-available"); setConnectionTooltipIcon("network-wired"); return; } else if (wireless) { setConnectionIcon("network-wireless-available"); setConnectionTooltipIcon("network-wireless-connected-00"); return; } else if (modem) { setConnectionIcon("network-mobile-available"); setConnectionTooltipIcon("phone"); return; } else { setConnectionIcon("network-unavailable"); setConnectionTooltipIcon("network-wired"); } } #if WITH_MODEMMANAGER_SUPPORT void ConnectionIcon::setModemIcon(const NetworkManager::Device::Ptr & device) { NetworkManager::ModemDevice::Ptr modemDevice = device.objectCast(); if (!modemDevice) { setConnectionIcon("network-mobile-100"); return; } ModemManager::ModemDevice::Ptr modem = ModemManager::findModemDevice(device->udi()); if (modem) { if (modem->hasInterface(ModemManager::ModemDevice::ModemInterface)) { m_modemNetwork = modem->interface(ModemManager::ModemDevice::ModemInterface).objectCast(); } } if (m_modemNetwork) { connect(m_modemNetwork.data(), &ModemManager::Modem::signalQualityChanged, this, &ConnectionIcon::modemSignalChanged, Qt::UniqueConnection); connect(m_modemNetwork.data(), &ModemManager::Modem::accessTechnologiesChanged, this, &ConnectionIcon::setIconForModem, Qt::UniqueConnection); connect(m_modemNetwork.data(), &ModemManager::Modem::destroyed, this, &ConnectionIcon::modemNetworkRemoved); m_signal = m_modemNetwork->signalQuality().signal; setIconForModem(); } else { setConnectionIcon("network-mobile-0"); setConnectionTooltipIcon("phone"); return; } } void ConnectionIcon::setIconForModem() { if (!m_signal) { m_signal = m_modemNetwork->signalQuality().signal; } QString strength = "00"; if (m_signal == 0) { strength = '0'; } else if (m_signal < 20) { strength = "20"; } else if (m_signal < 40) { strength = "40"; } else if (m_signal < 60) { strength = "60"; } else if (m_signal < 80) { strength = "80"; } else { strength = "100"; } QString result; switch(m_modemNetwork->accessTechnologies()) { case MM_MODEM_ACCESS_TECHNOLOGY_GSM: case MM_MODEM_ACCESS_TECHNOLOGY_GSM_COMPACT: result = "network-mobile-%1"; break; case MM_MODEM_ACCESS_TECHNOLOGY_GPRS: result = "network-mobile-%1-gprs"; break; case MM_MODEM_ACCESS_TECHNOLOGY_EDGE: result = "network-mobile-%1-edge"; break; case MM_MODEM_ACCESS_TECHNOLOGY_UMTS: result = "network-mobile-%1-umts"; break; case MM_MODEM_ACCESS_TECHNOLOGY_HSDPA: result = "network-mobile-%1-hsdpa"; break; case MM_MODEM_ACCESS_TECHNOLOGY_HSUPA: result = "network-mobile-%1-hsupa"; break; case MM_MODEM_ACCESS_TECHNOLOGY_HSPA: case MM_MODEM_ACCESS_TECHNOLOGY_HSPA_PLUS: result = "network-mobile-%1-hspa"; break; case MM_MODEM_ACCESS_TECHNOLOGY_LTE: result = "network-mobile-%1-lte"; break; default: result = "network-mobile-%1"; break; } setConnectionIcon(QString(result).arg(strength)); setConnectionTooltipIcon("phone"); } #endif void ConnectionIcon::setWirelessIcon(const NetworkManager::Device::Ptr &device, const QString& ssid) { NetworkManager::WirelessDevice::Ptr wirelessDevice = device.objectCast(); if (device) { m_wirelessNetwork = wirelessDevice->findNetwork(ssid); } else { m_wirelessNetwork.clear(); } if (m_wirelessNetwork) { connect(m_wirelessNetwork.data(), &NetworkManager::WirelessNetwork::signalStrengthChanged, this, &ConnectionIcon::setWirelessIconForSignalStrength, Qt::UniqueConnection); setWirelessIconForSignalStrength(m_wirelessNetwork->signalStrength()); } else { setDisconnectedIcon(); } } void ConnectionIcon::setWirelessIconForSignalStrength(int strength) { int iconStrength = 100; if (strength == 0) { iconStrength = 0; setConnectionTooltipIcon("network-wireless-connected-00"); } else if (strength < 20) { iconStrength = 20; setConnectionTooltipIcon("network-wireless-connected-20"); } else if (strength < 40) { iconStrength = 40; setConnectionTooltipIcon("network-wireless-connected-40"); } else if (strength < 60) { iconStrength = 60; setConnectionTooltipIcon("network-wireless-connected-60"); } else if (strength < 80) { iconStrength = 80; setConnectionTooltipIcon("network-wireless-connected-80"); } else if (strength < 100) { setConnectionTooltipIcon("network-wireless-connected-100"); } QString icon = QString("network-wireless-%1").arg(iconStrength); setConnectionIcon(icon); } void ConnectionIcon::setConnecting(bool connecting) { if (connecting != m_connecting) { m_connecting = connecting; Q_EMIT connectingChanged(m_connecting); } } void ConnectionIcon::setConnectionIcon(const QString & icon) { if (icon != m_connectionIcon) { m_connectionIcon = icon; Q_EMIT connectionIconChanged(connectionIcon()); } } void ConnectionIcon::setConnectionTooltipIcon(const QString & icon) { if (icon != m_connectionTooltipIcon) { m_connectionTooltipIcon = icon; Q_EMIT connectionTooltipIconChanged(m_connectionTooltipIcon); } } void ConnectionIcon::setVpn(bool vpn) { if (m_vpn != vpn) { m_vpn = vpn; Q_EMIT connectionIconChanged(connectionIcon()); } } void ConnectionIcon::setLimited(bool limited) { if (m_limited != limited) { m_limited = limited; Q_EMIT connectionIconChanged(connectionIcon()); } } diff --git a/libs/declarative/connectionicon.h b/libs/declarative/connectionicon.h index 91db99c6..742127df 100644 --- a/libs/declarative/connectionicon.h +++ b/libs/declarative/connectionicon.h @@ -1,106 +1,106 @@ /* Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_CONNECTION_ICON_H #define PLASMA_NM_CONNECTION_ICON_H #include #include #include #include #if WITH_MODEMMANAGER_SUPPORT #include #endif class ConnectionIcon : public QObject { Q_PROPERTY(bool connecting READ connecting NOTIFY connectingChanged) Q_PROPERTY(QString connectionIcon READ connectionIcon NOTIFY connectionIconChanged) Q_PROPERTY(QString connectionTooltipIcon READ connectionTooltipIcon NOTIFY connectionTooltipIconChanged) Q_PROPERTY(bool airplaneMode READ airplaneMode WRITE setAirplaneMode NOTIFY airplaneModeChanged) Q_OBJECT public: - explicit ConnectionIcon(QObject* parent = 0); - virtual ~ConnectionIcon(); + explicit ConnectionIcon(QObject* parent = nullptr); + ~ConnectionIcon() override; bool connecting() const; QString connectionIcon() const; QString connectionTooltipIcon() const; bool airplaneMode() const; void setAirplaneMode(bool airplaneMode); private Q_SLOTS: void activatingConnectionChanged(const QString & connection); void activeConnectionAdded(const QString & activeConnection); void activeConnectionDestroyed(); void activeConnectionStateChanged(NetworkManager::ActiveConnection::State state); void carrierChanged(bool carrier); void connectivityChanged(); void deviceAdded(const QString & device); void deviceRemoved(const QString & device); void networkingEnabledChanged(bool enabled); void primaryConnectionChanged(const QString & connection); #if WITH_MODEMMANAGER_SUPPORT void modemNetworkRemoved(); void modemSignalChanged(const ModemManager::SignalQualityPair &signalQuality); void setIconForModem(); #endif void statusChanged(NetworkManager::Status status); void setWirelessIconForSignalStrength(int strength); void vpnConnectionStateChanged(NetworkManager::VpnConnection::State state, NetworkManager::VpnConnection::StateChangeReason reason); void wirelessEnabledChanged(bool enabled); void wirelessNetworkAppeared(const QString &network); void wwanEnabledChanged(bool enabled); Q_SIGNALS: void connectingChanged(bool connecting); void connectionIconChanged(const QString & icon); void connectionTooltipIconChanged(const QString & icon); void airplaneModeChanged(bool airplaneMode); private: void addActiveConnection(const QString & activeConnection); void setConnecting(bool connecting); void setConnectionIcon(const QString & icon); void setConnectionTooltipIcon(const QString & icon); void setVpn(bool vpn); void setLimited(bool limited); uint m_signal; NetworkManager::WirelessNetwork::Ptr m_wirelessNetwork; bool m_connecting; bool m_limited; bool m_vpn; QString m_connectionIcon; QString m_connectionTooltipIcon; bool m_airplaneMode; void setDisconnectedIcon(); void setIcons(); void setStates(); void setWirelessIcon(const NetworkManager::Device::Ptr & device, const QString & ssid); #if WITH_MODEMMANAGER_SUPPORT ModemManager::Modem::Ptr m_modemNetwork; void setModemIcon(const NetworkManager::Device::Ptr & device); #endif }; #endif // PLASMA_NM_CONNECTION_ICON_H diff --git a/libs/declarative/enabledconnections.h b/libs/declarative/enabledconnections.h index bcb7dfb8..bf461436 100644 --- a/libs/declarative/enabledconnections.h +++ b/libs/declarative/enabledconnections.h @@ -1,83 +1,83 @@ /* Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_ENABLED_CONNECTIONS_H #define PLASMA_NM_ENABLED_CONNECTIONS_H #include #include class EnabledConnections : public QObject { /** * Indicates if overall networking is currently enabled or not */ Q_PROPERTY(bool networkingEnabled READ isNetworkingEnabled NOTIFY networkingEnabled) /** * Indicates if wireless is currently enabled or not */ Q_PROPERTY(bool wirelessEnabled READ isWirelessEnabled NOTIFY wirelessEnabled) /** * Indicates if the wireless hardware is currently enabled, i.e. the state of the RF kill switch */ Q_PROPERTY(bool wirelessHwEnabled READ isWirelessHwEnabled NOTIFY wirelessHwEnabled) /** * Indicates if mobile broadband devices are currently enabled or not. */ Q_PROPERTY(bool wwanEnabled READ isWwanEnabled NOTIFY wwanEnabled) /** * Indicates if the mobile broadband hardware is currently enabled, i.e. the state of the RF kill switch. */ Q_PROPERTY(bool wwanHwEnabled READ isWwanHwEnabled NOTIFY wwanHwEnabled) Q_OBJECT public: - explicit EnabledConnections(QObject* parent = 0); - virtual ~EnabledConnections(); + explicit EnabledConnections(QObject* parent = nullptr); + ~EnabledConnections() override; bool isNetworkingEnabled() const; bool isWirelessEnabled() const; bool isWirelessHwEnabled() const; bool isWwanEnabled() const; bool isWwanHwEnabled() const; public Q_SLOTS: void onNetworkingEnabled(bool enabled); void onWirelessEnabled(bool enabled); void onWirelessHwEnabled(bool enabled); void onWwanEnabled(bool enabled); void onWwanHwEnabled(bool enabled); Q_SIGNALS: void networkingEnabled(bool enabled); void wirelessEnabled(bool enabled); void wirelessHwEnabled(bool enabled); void wwanEnabled(bool enabled); void wwanHwEnabled(bool enabled); private: bool m_networkingEnabled; bool m_wirelessEnabled; bool m_wirelessHwEnabled; bool m_wwanEnabled; bool m_wwanHwEnabled; }; #endif // PLASMA_NM_ENABLED_CONNECTIONS_H diff --git a/libs/declarative/enums.h b/libs/declarative/enums.h index 37e5f898..685a730b 100644 --- a/libs/declarative/enums.h +++ b/libs/declarative/enums.h @@ -1,76 +1,76 @@ /* Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_ENUMS_H #define PLASMA_NM_ENUMS_H #include class Enums : public QObject { Q_OBJECT Q_ENUMS(ConnectionStatus) Q_ENUMS(ConnectionType) Q_ENUMS(SecurityType) public: - explicit Enums(QObject* parent = 0); - virtual ~Enums(); + explicit Enums(QObject* parent = nullptr); + ~Enums() override; enum ConnectionStatus { UnknownState = 0, Activating, Activated, Deactivating, Deactivated }; enum ConnectionType { UnknownConnectionType = 0, Adsl, Bluetooth, Bond, Bridge, Cdma, Gsm, Infiniband, OLPCMesh, Pppoe, Vlan, Vpn, Wimax, Wired, Wireless }; enum SecurityType { UnknownSecurity = -1, NoneSecurity = 0, StaticWep, DynamicWep, Leap, WpaPsk, WpaEap, Wpa2Psk, Wpa2Eap }; }; #endif // PLASMA_NM_ENUMS_H diff --git a/libs/declarative/networkstatus.cpp b/libs/declarative/networkstatus.cpp index 75df4a77..21abd950 100644 --- a/libs/declarative/networkstatus.cpp +++ b/libs/declarative/networkstatus.cpp @@ -1,240 +1,239 @@ /* Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "networkstatus.h" #include "uiutils.h" #include #include #include #include NetworkStatus::SortedConnectionType NetworkStatus::connectionTypeToSortedType(NetworkManager::ConnectionSettings::ConnectionType type) { switch (type) { case NetworkManager::ConnectionSettings::Adsl: return NetworkStatus::NetworkStatus::Adsl; break; case NetworkManager::ConnectionSettings::Bluetooth: return NetworkStatus::Bluetooth; break; case NetworkManager::ConnectionSettings::Cdma: return NetworkStatus::Cdma; break; case NetworkManager::ConnectionSettings::Gsm: return NetworkStatus::Gsm; break; case NetworkManager::ConnectionSettings::Infiniband: return NetworkStatus::Infiniband; break; case NetworkManager::ConnectionSettings::OLPCMesh: return NetworkStatus::OLPCMesh; break; case NetworkManager::ConnectionSettings::Pppoe: return NetworkStatus::Pppoe; break; case NetworkManager::ConnectionSettings::Vpn: return NetworkStatus::Vpn; break; case NetworkManager::ConnectionSettings::Wired: return NetworkStatus::Wired; break; case NetworkManager::ConnectionSettings::Wireless: return NetworkStatus::Wireless; break; default: return NetworkStatus::Other; break; } } NetworkStatus::NetworkStatus(QObject* parent) : QObject(parent) { connect(NetworkManager::notifier(), &NetworkManager::Notifier::statusChanged, this, &NetworkStatus::statusChanged); - connect(NetworkManager::notifier(), &NetworkManager::Notifier::activeConnectionsChanged, this, static_cast(&NetworkStatus::activeConnectionsChanged)); + connect(NetworkManager::notifier(), &NetworkManager::Notifier::activeConnectionsChanged, this, QOverload<>::of(&NetworkStatus::activeConnectionsChanged)); activeConnectionsChanged(); statusChanged(NetworkManager::status()); } NetworkStatus::~NetworkStatus() { } QString NetworkStatus::activeConnections() const { return m_activeConnections; } QString NetworkStatus::networkStatus() const { return m_networkStatus; } void NetworkStatus::activeConnectionsChanged() { Q_FOREACH (const NetworkManager::ActiveConnection::Ptr & active, NetworkManager::activeConnections()) { connect(active.data(), &NetworkManager::ActiveConnection::default4Changed, this, &NetworkStatus::defaultChanged, Qt::UniqueConnection); connect(active.data(), &NetworkManager::ActiveConnection::default6Changed, this, &NetworkStatus::defaultChanged, Qt::UniqueConnection); connect(active.data(), &NetworkManager::ActiveConnection::stateChanged, this, &NetworkStatus::changeActiveConnections); } changeActiveConnections(); } void NetworkStatus::defaultChanged() { statusChanged(NetworkManager::status()); } void NetworkStatus::statusChanged(NetworkManager::Status status) { switch (status) { case NetworkManager::ConnectedLinkLocal: m_networkStatus = i18nc("A network device is connected, but there is only link-local connectivity", "Connected"); break; case NetworkManager::ConnectedSiteOnly: m_networkStatus = i18nc("A network device is connected, but there is only site-local connectivity", "Connected"); break; case NetworkManager::Connected: m_networkStatus = i18nc("A network device is connected, with global network connectivity", "Connected"); break; case NetworkManager::Asleep: m_networkStatus = i18nc("Networking is inactive and all devices are disabled", "Inactive"); break; case NetworkManager::Disconnected: m_networkStatus = i18nc("There is no active network connection", "Disconnected"); break; case NetworkManager::Disconnecting: m_networkStatus = i18nc("Network connections are being cleaned up", "Disconnecting"); break; case NetworkManager::Connecting: m_networkStatus = i18nc("A network device is connecting to a network and there is no other available network connection", "Connecting"); break; default: m_networkStatus = checkUnknownReason(); break; } if (status == NetworkManager::ConnectedLinkLocal || status == NetworkManager::ConnectedSiteOnly || status == NetworkManager::Connected) { changeActiveConnections(); } else { m_activeConnections = m_networkStatus; Q_EMIT activeConnectionsChanged(m_activeConnections); } Q_EMIT networkStatusChanged(m_networkStatus); } void NetworkStatus::changeActiveConnections() { if (NetworkManager::status() != NetworkManager::Connected && NetworkManager::status() != NetworkManager::ConnectedLinkLocal && NetworkManager::status() != NetworkManager::ConnectedSiteOnly) { return; } QString activeConnections; const QString format = QStringLiteral("%1: %2"); QList activeConnectionList = NetworkManager::activeConnections(); std::sort(activeConnectionList.begin(), activeConnectionList.end(), [] (const NetworkManager::ActiveConnection::Ptr &left, const NetworkManager::ActiveConnection::Ptr &right) { return NetworkStatus::connectionTypeToSortedType(left->type()) < NetworkStatus::connectionTypeToSortedType(right->type()); }); Q_FOREACH (const NetworkManager::ActiveConnection::Ptr & active, activeConnectionList) { if (!active->devices().isEmpty() && UiUtils::isConnectionTypeSupported(active->type())) { NetworkManager::Device::Ptr device = NetworkManager::findNetworkInterface(active->devices().first()); #if NM_CHECK_VERSION(0, 9, 10) if (device && device->type() != NetworkManager::Device::Generic && device->type() <= NetworkManager::Device::Team) { #else if (device) { #endif bool connecting = false; bool connected = false; QString conType; QString status; NetworkManager::VpnConnection::Ptr vpnConnection; if (active->vpn()) { conType = i18n("VPN"); vpnConnection = active.objectCast(); } else { conType = UiUtils::interfaceTypeLabel(device->type(), device); } if (vpnConnection && active->vpn()) { if (vpnConnection->state() >= NetworkManager::VpnConnection::Prepare && vpnConnection->state() <= NetworkManager::VpnConnection::GettingIpConfig) { connecting = true; } else if (vpnConnection->state() == NetworkManager::VpnConnection::Activated) { connected = true; } } else { if (active->state() == NetworkManager::ActiveConnection::Activated) { connected = true; } else if (active->state() == NetworkManager::ActiveConnection::Activating) { connecting = true; } } NetworkManager::Connection::Ptr connection = active->connection(); - const QString connectionName = connection->name().replace('&', "&").replace('<', "<").replace('>', ">"); if (connecting) { - status = i18n("Connecting to %1", connectionName); + status = i18n("Connecting to %1", connection->name()); } else if (connected) { - status = i18n("Connected to %1", connectionName); + status = i18n("Connected to %1", connection->name()); } if (!activeConnections.isEmpty()) { activeConnections += '\n'; } activeConnections += format.arg(conType, status); connect(connection.data(), &NetworkManager::Connection::updated, this, &NetworkStatus::changeActiveConnections, Qt::UniqueConnection); } } } m_activeConnections = activeConnections; Q_EMIT activeConnectionsChanged(activeConnections); } QString NetworkStatus::checkUnknownReason() const { // Check if NetworkManager is running. if (!QDBusConnection::systemBus().interface()->isServiceRegistered(NM_DBUS_INTERFACE)) { return i18n("NetworkManager not running"); } // Check for compatible NetworkManager version. if (NetworkManager::compareVersion(0, 9, 8) < 0) { return i18n("NetworkManager 0.9.8 required, found %1.", NetworkManager::version()); } return i18nc("global connection state", "Unknown"); } diff --git a/libs/declarative/networkstatus.h b/libs/declarative/networkstatus.h index 750f5775..8c03682f 100644 --- a/libs/declarative/networkstatus.h +++ b/libs/declarative/networkstatus.h @@ -1,78 +1,78 @@ /* Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_NETWORK_STATUS_H #define PLASMA_NM_NETWORK_STATUS_H #include #include class NetworkStatus : public QObject { /** * Returns a formated list of active connections or NM status when there is no active connection */ Q_PROPERTY(QString activeConnections READ activeConnections NOTIFY activeConnectionsChanged) /** * Returns the current status of NetworkManager */ Q_PROPERTY(QString networkStatus READ networkStatus NOTIFY networkStatusChanged) Q_OBJECT public: enum SortedConnectionType { Wired, Wireless, Gsm, Cdma, Pppoe, Adsl, Infiniband, OLPCMesh, Bluetooth, Vpn, Other }; static SortedConnectionType connectionTypeToSortedType(NetworkManager::ConnectionSettings::ConnectionType type); - explicit NetworkStatus(QObject* parent = 0); - virtual ~NetworkStatus(); + explicit NetworkStatus(QObject* parent = nullptr); + ~NetworkStatus() override; QString activeConnections() const; QString networkStatus() const; private Q_SLOTS: void activeConnectionsChanged(); void defaultChanged(); void statusChanged(NetworkManager::Status status); void changeActiveConnections(); Q_SIGNALS: void activeConnectionsChanged(const QString & activeConnections); void networkStatusChanged(const QString & status); private: QString m_activeConnections; QString m_networkStatus; QString checkUnknownReason() const; }; #endif // PLAMA_NM_NETWORK_STATUS_H diff --git a/libs/declarative/qmlplugins.cpp b/libs/declarative/qmlplugins.cpp index 683231e8..15f18d86 100644 --- a/libs/declarative/qmlplugins.cpp +++ b/libs/declarative/qmlplugins.cpp @@ -1,69 +1,69 @@ /* Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "qmlplugins.h" -#include +#include #include "availabledevices.h" #include "connectionicon.h" #include "enabledconnections.h" #include "networkstatus.h" #include "appletproxymodel.h" #include "configuration.h" #include "creatableconnectionsmodel.h" #include "editorproxymodel.h" #include "kcmidentitymodel.h" #include "networkmodel.h" #include "mobileproxymodel.h" #include "handler.h" #include "enums.h" void QmlPlugins::registerTypes(const char* uri) { // @uri org.kde.plasma.networkmanagement.AvailableDevices qmlRegisterType(uri, 0, 2, "AvailableDevices"); // @uri org.kde.plasma.networkmanagement.ConnectionIcon qmlRegisterType(uri, 0, 2, "ConnectionIcon"); // @uri org.kde.plasma.networkmanagement.Configuration qmlRegisterType(uri, 0, 2, "Configuration"); // @uri org.kde.plasma.networkmanagement.EnabledConnections qmlRegisterType(uri, 0, 2, "EnabledConnections"); // @uri org.kde.plasma.networkmanagement.Enums qmlRegisterUncreatableType(uri, 0, 2, "Enums", "You cannot create Enums on yourself"); // @uri org.kde.plasma.networkmanagement.NetworkStatus qmlRegisterType(uri, 0, 2, "NetworkStatus"); // @uri org.kde.plasma.networkmanagement.Handler qmlRegisterType(uri, 0, 2, "Handler"); // @uri org.kde.plasma.networkmanagement.NetworkModel qmlRegisterType(uri, 0, 2, "NetworkModel"); // @uri org.kde.plasma.networkmanagement.AppletProxyModel qmlRegisterType(uri, 0, 2, "AppletProxyModel"); // @uri org.kde.plasma.networkmanagement.EditorProxyModel qmlRegisterType(uri, 0, 2, "EditorProxyModel"); // @uri org.kde.plasma.networkmanagement.KcmIdentityModel qmlRegisterType(uri, 0, 2, "KcmIdentityModel"); // @uri org.kde.plasma.networkmanagement.CreatableConnectionsModel qmlRegisterType(uri, 0, 2, "CreatableConnectionsModel"); // @uri org.kde.plasma.networkmanagement.MobileProxyModel qmlRegisterType(uri, 0, 2, "MobileProxyModel"); } diff --git a/libs/declarative/qmlplugins.h b/libs/declarative/qmlplugins.h index 8754d4ca..ebfe0b9f 100644 --- a/libs/declarative/qmlplugins.h +++ b/libs/declarative/qmlplugins.h @@ -1,34 +1,34 @@ /* Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_QML_PLUGINS_H #define PLASMA_NM_QML_PLUGINS_H #include class QmlPlugins : public QQmlExtensionPlugin { Q_OBJECT Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtensionInterface") public: - virtual void registerTypes(const char * uri); + void registerTypes(const char * uri) override; }; #endif // PLASMA_NM_QML_PLUGINS_H diff --git a/libs/editor/CMakeLists.txt b/libs/editor/CMakeLists.txt index dd63248c..74bb255f 100644 --- a/libs/editor/CMakeLists.txt +++ b/libs/editor/CMakeLists.txt @@ -1,114 +1,110 @@ include_directories(${CMAKE_CURRENT_SOURCE_DIR}/widgets) set(plasmanm_editor_SRCS settings/bondwidget.cpp settings/bridgewidget.cpp settings/btwidget.cpp settings/cdmawidget.cpp settings/connectionwidget.cpp settings/gsmwidget.cpp settings/infinibandwidget.cpp settings/ipv4widget.cpp settings/ipv6widget.cpp settings/pppoewidget.cpp settings/pppwidget.cpp settings/security802-1x.cpp settings/teamwidget.cpp settings/vlanwidget.cpp settings/wificonnectionwidget.cpp settings/wifisecurity.cpp settings/wiredconnectionwidget.cpp settings/wiredsecurity.cpp widgets/advancedpermissionswidget.cpp widgets/bssidcombobox.cpp widgets/delegate.cpp widgets/editlistdialog.cpp widgets/hwaddrcombobox.cpp widgets/intdelegate.cpp widgets/ipv4delegate.cpp widgets/ipv4routeswidget.cpp widgets/ipv6delegate.cpp widgets/ipv6routeswidget.cpp widgets/passwordfield.cpp widgets/settingwidget.cpp widgets/ssidcombobox.cpp connectioneditorbase.cpp connectioneditordialog.cpp connectioneditortabwidget.cpp listvalidator.cpp simpleipv4addressvalidator.cpp simpleipv6addressvalidator.cpp + simpleiplistvalidator.cpp vpnuiplugin.cpp ../configuration.cpp ../debug.cpp ../uiutils.cpp ) if (WITH_MODEMMANAGER_SUPPORT) set(plasmanm_editor_SRCS ${plasmanm_editor_SRCS} widgets/mobileconnectionwizard.cpp mobileproviders.cpp) endif() ki18n_wrap_ui(plasmanm_editor_SRCS settings/ui/802-1x.ui settings/ui/bond.ui settings/ui/bridge.ui settings/ui/bt.ui settings/ui/cdma.ui settings/ui/connectionwidget.ui settings/ui/gsm.ui settings/ui/infiniband.ui settings/ui/ipv4.ui settings/ui/ipv6.ui settings/ui/ppp.ui settings/ui/pppoe.ui settings/ui/team.ui settings/ui/vlan.ui settings/ui/team.ui settings/ui/wificonnectionwidget.ui settings/ui/wifisecurity.ui settings/ui/wiredconnectionwidget.ui settings/ui/wiredsecurity.ui widgets/ui/advancedpermissionswidget.ui widgets/ui/ipv4routes.ui widgets/ui/ipv6routes.ui connectioneditortabwidget.ui ) add_library(plasmanm_editor SHARED ${plasmanm_editor_SRCS}) target_link_libraries(plasmanm_editor +PUBLIC + KF5::NetworkManagerQt + KF5::WidgetsAddons + KF5::Completion Qt5::Widgets +PRIVATE Qt5::Network Qt5::DBus qca-qt5 - KF5::NetworkManagerQt - KF5::Service - KF5::Completion KF5::I18n - KF5::WidgetsAddons - KF5::KIOCore KF5::KIOWidgets - KF5::CoreAddons - KF5::Wallet - KF5::ItemViews - KF5::XmlGui KF5::IconThemes KF5::Notifications KF5::Wallet KF5::Solid - KF5::KDELibs4Support ) if (WITH_MODEMMANAGER_SUPPORT) - target_link_libraries(plasmanm_editor KF5::ModemManagerQt) + target_link_libraries(plasmanm_editor PUBLIC KF5::ModemManagerQt) endif() install(TARGETS plasmanm_editor ${INSTALL_TARGETS_DEFAULT_ARGS}) -install(FILES plasma-networkmanagement-vpnuiplugin.desktop DESTINATION ${SERVICETYPES_INSTALL_DIR}) +install(FILES plasma-networkmanagement-vpnuiplugin.desktop DESTINATION ${KDE_INSTALL_KSERVICETYPES5DIR}) diff --git a/libs/editor/connectioneditorbase.cpp b/libs/editor/connectioneditorbase.cpp index 6e423a53..b3540119 100644 --- a/libs/editor/connectioneditorbase.cpp +++ b/libs/editor/connectioneditorbase.cpp @@ -1,482 +1,482 @@ /* Copyright 2013-2016 Jan Grulich Copyright 2013, 2014 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "connectioneditorbase.h" #include "debug.h" #include "settings/bondwidget.h" #include "settings/bridgewidget.h" #include "settings/btwidget.h" #include "settings/cdmawidget.h" #include "settings/connectionwidget.h" #include "settings/gsmwidget.h" #include "settings/infinibandwidget.h" #include "settings/ipv4widget.h" #include "settings/ipv6widget.h" #include "settings/pppwidget.h" #include "settings/pppoewidget.h" #include "settings/teamwidget.h" #include "settings/vlanwidget.h" #include "settings/wificonnectionwidget.h" #include "settings/wifisecurity.h" #include "settings/wiredconnectionwidget.h" #include "settings/wiredsecurity.h" #include "vpnuiplugin.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include ConnectionEditorBase::ConnectionEditorBase(const NetworkManager::ConnectionSettings::Ptr &connection, QWidget *parent, Qt::WindowFlags f) : QWidget(parent, f) , m_initialized(false) , m_valid(false) , m_pendingReplies(0) , m_connection(connection) { } ConnectionEditorBase::ConnectionEditorBase(QWidget *parent, Qt::WindowFlags f) : QWidget(parent, f) { } ConnectionEditorBase::~ConnectionEditorBase() { m_connection.clear(); } void ConnectionEditorBase::setConnection(const NetworkManager::ConnectionSettings::Ptr &connection) { // Set connection settings m_connection.clear(); m_connection = connection; m_initialized = false; // Reset UI setting widgets delete m_connectionWidget; m_connectionWidget = nullptr; qDeleteAll(m_settingWidgets); m_settingWidgets.clear(); initialize(); } NMVariantMapMap ConnectionEditorBase::setting() const { NMVariantMapMap settings = m_connectionWidget->setting(); Q_FOREACH (SettingWidget *widget, m_settingWidgets) { const QString type = widget->type(); if (type != NetworkManager::Setting::typeAsString(NetworkManager::Setting::Security8021x) && type != NetworkManager::Setting::typeAsString(NetworkManager::Setting::WirelessSecurity)) { settings.insert(type, widget->setting()); } // add 802.1x security if needed QVariantMap security8021x; if (type == NetworkManager::Setting::typeAsString(NetworkManager::Setting::WirelessSecurity)) { WifiSecurity *wifiSecurity = static_cast(widget); if (wifiSecurity->enabled()) { settings.insert(type, wifiSecurity->setting()); } if (wifiSecurity->enabled8021x()) { security8021x = static_cast(widget)->setting8021x(); settings.insert(NetworkManager::Setting::typeAsString(NetworkManager::Setting::Security8021x), security8021x); } } else if (type == NetworkManager::Setting::typeAsString(NetworkManager::Setting::Security8021x)) { WiredSecurity *wiredSecurity = static_cast(widget); if (wiredSecurity->enabled8021x()) { security8021x = static_cast(widget)->setting(); settings.insert(NetworkManager::Setting::typeAsString(NetworkManager::Setting::Security8021x), security8021x); } } } // Set properties which are not returned from setting widgets NetworkManager::ConnectionSettings::Ptr connectionSettings = NetworkManager::ConnectionSettings::Ptr(new NetworkManager::ConnectionSettings(m_connection->connectionType())); connectionSettings->fromMap(settings); connectionSettings->setId(connectionName()); connectionSettings->setUuid(m_connection->uuid()); if (connectionSettings->connectionType() == NetworkManager::ConnectionSettings::Wireless) { NetworkManager::WirelessSecuritySetting::Ptr securitySetting = connectionSettings->setting(NetworkManager::Setting::WirelessSecurity).staticCast(); NetworkManager::WirelessSetting::Ptr wirelessSetting = connectionSettings->setting(NetworkManager::Setting::Wireless).staticCast(); if (securitySetting && wirelessSetting) { if (securitySetting->keyMgmt() != NetworkManager::WirelessSecuritySetting::WirelessSecuritySetting::Unknown) { wirelessSetting->setSecurity("802-11-wireless-security"); } } } return connectionSettings->toMap(); } bool ConnectionEditorBase::isInitialized() const { return m_initialized; } bool ConnectionEditorBase::isValid() const { return m_valid; } void ConnectionEditorBase::addConnectionWidget(ConnectionWidget *widget, const QString &text) { m_connectionWidget = widget; connect(widget, &ConnectionWidget::settingChanged, this, &ConnectionEditorBase::settingChanged); addWidget(widget, text); } void ConnectionEditorBase::addSettingWidget(SettingWidget *widget, const QString &text) { m_settingWidgets << widget; connect(widget, &SettingWidget::settingChanged, this, &ConnectionEditorBase::settingChanged); addWidget(widget, text); } void ConnectionEditorBase::initialize() { const bool emptyConnection = m_connection->id().isEmpty(); const NetworkManager::ConnectionSettings::ConnectionType type = m_connection->connectionType(); if (emptyConnection) { m_connection->addToPermissions(KUser().loginName(), QString()); } // General configuration common to all connection types ConnectionWidget *connectionWidget = new ConnectionWidget(m_connection); addConnectionWidget(connectionWidget, i18nc("General", "General configuration")); // Add the rest of widgets QString serviceType; if (type == NetworkManager::ConnectionSettings::Wired) { WiredConnectionWidget *wiredWidget = new WiredConnectionWidget(m_connection->setting(NetworkManager::Setting::Wired), this); addSettingWidget(wiredWidget, i18n("Wired")); WiredSecurity *wiredSecurity = new WiredSecurity(m_connection->setting(NetworkManager::Setting::Security8021x).staticCast(), this); addSettingWidget(wiredSecurity, i18n("802.1x Security")); } else if (type == NetworkManager::ConnectionSettings::Wireless) { WifiConnectionWidget *wifiWidget = new WifiConnectionWidget(m_connection->setting(NetworkManager::Setting::Wireless), this); addSettingWidget(wifiWidget, i18n("Wi-Fi")); WifiSecurity *wifiSecurity = new WifiSecurity(m_connection->setting(NetworkManager::Setting::WirelessSecurity), m_connection->setting(NetworkManager::Setting::Security8021x).staticCast(), this); addSettingWidget(wifiSecurity, i18n("Wi-Fi Security")); - connect(wifiWidget, static_cast(&WifiConnectionWidget::ssidChanged), wifiSecurity, &WifiSecurity::onSsidChanged); + connect(wifiWidget, QOverload::of(&WifiConnectionWidget::ssidChanged), wifiSecurity, &WifiSecurity::onSsidChanged); } else if (type == NetworkManager::ConnectionSettings::Pppoe) { // DSL PppoeWidget *pppoeWidget = new PppoeWidget(m_connection->setting(NetworkManager::Setting::Pppoe), this); addSettingWidget(pppoeWidget, i18n("DSL")); WiredConnectionWidget *wiredWidget = new WiredConnectionWidget(m_connection->setting(NetworkManager::Setting::Wired), this); addSettingWidget(wiredWidget, i18n("Wired")); } else if (type == NetworkManager::ConnectionSettings::Gsm) { // GSM GsmWidget *gsmWidget = new GsmWidget(m_connection->setting(NetworkManager::Setting::Gsm), this); addSettingWidget(gsmWidget, i18n("Mobile Broadband (%1)", m_connection->typeAsString(m_connection->connectionType()))); } else if (type == NetworkManager::ConnectionSettings::Cdma) { // CDMA CdmaWidget *cdmaWidget = new CdmaWidget(m_connection->setting(NetworkManager::Setting::Cdma), this); addSettingWidget(cdmaWidget, i18n("Mobile Broadband (%1)", m_connection->typeAsString(m_connection->connectionType()))); } else if (type == NetworkManager::ConnectionSettings::Bluetooth) { // Bluetooth BtWidget *btWidget = new BtWidget(m_connection->setting(NetworkManager::Setting::Bluetooth), this); addSettingWidget(btWidget, i18n("Bluetooth")); NetworkManager::BluetoothSetting::Ptr btSetting = m_connection->setting(NetworkManager::Setting::Bluetooth).staticCast(); if (btSetting->profileType() == NetworkManager::BluetoothSetting::Dun) { GsmWidget *gsmWidget = new GsmWidget(m_connection->setting(NetworkManager::Setting::Gsm), this); addSettingWidget(gsmWidget, i18n("GSM")); PPPWidget *pppWidget = new PPPWidget(m_connection->setting(NetworkManager::Setting::Ppp), this); addSettingWidget(pppWidget, i18n("PPP")); } } else if (type == NetworkManager::ConnectionSettings::Infiniband) { // Infiniband InfinibandWidget *infinibandWidget = new InfinibandWidget(m_connection->setting(NetworkManager::Setting::Infiniband), this); addSettingWidget(infinibandWidget, i18n("Infiniband")); } else if (type == NetworkManager::ConnectionSettings::Bond) { // Bond BondWidget *bondWidget = new BondWidget(m_connection->uuid(), m_connection->setting(NetworkManager::Setting::Bond), this); addSettingWidget(bondWidget, i18n("Bond")); } else if (type == NetworkManager::ConnectionSettings::Bridge) { // Bridge BridgeWidget *bridgeWidget = new BridgeWidget(m_connection->uuid(), m_connection->setting(NetworkManager::Setting::Bridge), this); addSettingWidget(bridgeWidget, i18n("Bridge")); } else if (type == NetworkManager::ConnectionSettings::Vlan) { // Vlan VlanWidget *vlanWidget = new VlanWidget(m_connection->setting(NetworkManager::Setting::Vlan), this); addSettingWidget(vlanWidget, i18n("Vlan")); } else if (type == NetworkManager::ConnectionSettings::Team) { // Team TeamWidget *teamWidget = new TeamWidget(m_connection->uuid(), m_connection->setting(NetworkManager::Setting::Team), this); addSettingWidget(teamWidget, i18n("Team")); } else if (type == NetworkManager::ConnectionSettings::Vpn) { // VPN QString error; - VpnUiPlugin *vpnPlugin = 0; + VpnUiPlugin *vpnPlugin = nullptr; NetworkManager::VpnSetting::Ptr vpnSetting = m_connection->setting(NetworkManager::Setting::Vpn).staticCast(); if (!vpnSetting) { qCWarning(PLASMA_NM) << "Missing VPN setting!"; } else { serviceType = vpnSetting->serviceType(); vpnPlugin = KServiceTypeTrader::createInstanceFromQuery(QString::fromLatin1("PlasmaNetworkManagement/VpnUiPlugin"), QString::fromLatin1("[X-NetworkManager-Services]=='%1'").arg(serviceType), this, QVariantList(), &error); if (vpnPlugin && error.isEmpty()) { const QString shortName = serviceType.section('.', -1); SettingWidget *vpnWidget = vpnPlugin->widget(vpnSetting, this); addSettingWidget(vpnWidget, i18n("VPN (%1)", shortName)); } else { qCWarning(PLASMA_NM) << error << ", serviceType == " << serviceType; } } } // PPP widget if (type == NetworkManager::ConnectionSettings::Pppoe || type == NetworkManager::ConnectionSettings::Cdma || type == NetworkManager::ConnectionSettings::Gsm) { PPPWidget *pppWidget = new PPPWidget(m_connection->setting(NetworkManager::Setting::Ppp), this); addSettingWidget(pppWidget, i18n("PPP")); } // IPv4 widget if (!m_connection->isSlave()) { IPv4Widget *ipv4Widget = new IPv4Widget(m_connection->setting(NetworkManager::Setting::Ipv4), this); addSettingWidget(ipv4Widget, i18n("IPv4")); } // IPv6 widget if ((type == NetworkManager::ConnectionSettings::Wired || type == NetworkManager::ConnectionSettings::Wireless || type == NetworkManager::ConnectionSettings::Infiniband #if NM_CHECK_VERSION(0, 9, 10) || type == NetworkManager::ConnectionSettings::Team #endif #if NM_CHECK_VERSION(1, 0, 0) || type == NetworkManager::ConnectionSettings::Cdma || type == NetworkManager::ConnectionSettings::Gsm #endif || type == NetworkManager::ConnectionSettings::Bond || type == NetworkManager::ConnectionSettings::Bridge || type == NetworkManager::ConnectionSettings::Vlan || (type == NetworkManager::ConnectionSettings::Vpn && serviceType == QLatin1String("org.freedesktop.NetworkManager.openvpn"))) && !m_connection->isSlave()) { IPv6Widget *ipv6Widget = new IPv6Widget(m_connection->setting(NetworkManager::Setting::Ipv6), this); addSettingWidget(ipv6Widget, i18n("IPv6")); } // Re-check validation bool valid = true; Q_FOREACH (SettingWidget *widget, m_settingWidgets) { valid = valid && widget->isValid(); connect(widget, &SettingWidget::validChanged, this, &ConnectionEditorBase::validChanged); } m_valid = valid; Q_EMIT validityChanged(valid); KAcceleratorManager::manage(this); // If the connection is not empty (not new) we want to load its secrets if (!emptyConnection) { NetworkManager::Connection::Ptr connection = NetworkManager::findConnectionByUuid(m_connection->uuid()); if (connection) { QStringList requiredSecrets; QString settingName; QVariantMap setting; QDBusPendingReply reply; if (m_connection->connectionType() == NetworkManager::ConnectionSettings::Adsl) { NetworkManager::AdslSetting::Ptr adslSetting = connection->settings()->setting(NetworkManager::Setting::Adsl).staticCast(); if (adslSetting && !adslSetting->needSecrets().isEmpty()) { requiredSecrets = adslSetting->needSecrets(); setting = adslSetting->toMap(); settingName = QLatin1String("adsl"); } } else if (m_connection->connectionType() == NetworkManager::ConnectionSettings::Bluetooth) { NetworkManager::GsmSetting::Ptr gsmSetting = connection->settings()->setting(NetworkManager::Setting::Gsm).staticCast(); if (gsmSetting && !gsmSetting->needSecrets().isEmpty()) { requiredSecrets = gsmSetting->needSecrets(); setting = gsmSetting->toMap(); settingName = QLatin1String("gsm"); } } else if (m_connection->connectionType() == NetworkManager::ConnectionSettings::Cdma) { NetworkManager::CdmaSetting::Ptr cdmaSetting = connection->settings()->setting(NetworkManager::Setting::Cdma).staticCast(); if (cdmaSetting && !cdmaSetting->needSecrets().isEmpty()) { requiredSecrets = cdmaSetting->needSecrets(); setting = cdmaSetting->toMap(); settingName = QLatin1String("cdma"); } } else if (m_connection->connectionType() == NetworkManager::ConnectionSettings::Gsm) { NetworkManager::GsmSetting::Ptr gsmSetting = connection->settings()->setting(NetworkManager::Setting::Gsm).staticCast(); if (gsmSetting && !gsmSetting->needSecrets().isEmpty()) { requiredSecrets = gsmSetting->needSecrets(); setting = gsmSetting->toMap(); settingName = QLatin1String("gsm"); } } else if (m_connection->connectionType() == NetworkManager::ConnectionSettings::Pppoe) { NetworkManager::PppoeSetting::Ptr pppoeSetting = connection->settings()->setting(NetworkManager::Setting::Pppoe).staticCast(); if (pppoeSetting && !pppoeSetting->needSecrets().isEmpty()) { requiredSecrets = pppoeSetting->needSecrets(); setting = pppoeSetting->toMap(); settingName = QLatin1String("pppoe"); } } else if (m_connection->connectionType() == NetworkManager::ConnectionSettings::Wired) { NetworkManager::Security8021xSetting::Ptr securitySetting = connection->settings()->setting(NetworkManager::Setting::Security8021x).staticCast(); if (securitySetting && !securitySetting->needSecrets().isEmpty()) { requiredSecrets = securitySetting->needSecrets(); setting = securitySetting->toMap(); settingName = QLatin1String("802-1x"); } } else if (m_connection->connectionType() == NetworkManager::ConnectionSettings::Wireless) { NetworkManager::WirelessSecuritySetting::Ptr wifiSecuritySetting = connection->settings()->setting(NetworkManager::Setting::WirelessSecurity).staticCast(); if (wifiSecuritySetting && (wifiSecuritySetting->keyMgmt() == NetworkManager::WirelessSecuritySetting::WpaEap || (wifiSecuritySetting->keyMgmt() == NetworkManager::WirelessSecuritySetting::WirelessSecuritySetting::Ieee8021x && wifiSecuritySetting->authAlg() != NetworkManager::WirelessSecuritySetting::Leap))) { NetworkManager::Security8021xSetting::Ptr securitySetting = connection->settings()->setting(NetworkManager::Setting::Security8021x).staticCast(); if (securitySetting && !securitySetting->needSecrets().isEmpty()) { requiredSecrets = securitySetting->needSecrets(); setting = securitySetting->toMap(); settingName = QLatin1String("802-1x"); if (requiredSecrets.contains(NM_SETTING_802_1X_PASSWORD_RAW)) { requiredSecrets.removeAll(NM_SETTING_802_1X_PASSWORD_RAW); } } } else { if (!wifiSecuritySetting->needSecrets().isEmpty()) { requiredSecrets = wifiSecuritySetting->needSecrets(); setting = wifiSecuritySetting->toMap(); settingName = QLatin1String("802-11-wireless-security"); } } } else if (m_connection->connectionType() == NetworkManager::ConnectionSettings::Vpn) { settingName = QLatin1String("vpn"); } if (!requiredSecrets.isEmpty() || m_connection->connectionType() == NetworkManager::ConnectionSettings::Vpn) { bool requestSecrets = false; if (m_connection->connectionType() == NetworkManager::ConnectionSettings::Vpn) { requestSecrets = true; } else { Q_FOREACH (const QString &secret, requiredSecrets) { if (setting.contains(secret + QLatin1String("-flags"))) { NetworkManager::Setting::SecretFlagType secretFlag = (NetworkManager::Setting::SecretFlagType)setting.value(secret + QLatin1String("-flags")).toInt(); if (secretFlag == NetworkManager::Setting::None || secretFlag == NetworkManager::Setting::AgentOwned) { requestSecrets = true; } } else { requestSecrets = true; } } } if (requestSecrets) { m_pendingReplies++; reply = connection->secrets(settingName); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this); watcher->setProperty("connection", connection->name()); watcher->setProperty("settingName", settingName); connect(watcher, &QDBusPendingCallWatcher::finished, this, &ConnectionEditorBase::replyFinished); m_valid = false; Q_EMIT validityChanged(false); return; } } } } // We should be now fully initialized as we don't wait for secrets if (m_pendingReplies == 0) { m_initialized = true; } } void ConnectionEditorBase::replyFinished(QDBusPendingCallWatcher *watcher) { QDBusPendingReply reply = *watcher; const QString settingName = watcher->property("settingName").toString(); if (reply.isValid()) { NMVariantMapMap secrets = reply.argumentAt<0>(); Q_FOREACH (const QString &key, secrets.keys()) { if (key == settingName) { NetworkManager::Setting::Ptr setting = m_connection->setting(NetworkManager::Setting::typeFromString(key)); if (setting) { setting->secretsFromMap(secrets.value(key)); Q_FOREACH (SettingWidget *widget, m_settingWidgets) { const QString type = widget->type(); if (type == settingName || (settingName == NetworkManager::Setting::typeAsString(NetworkManager::Setting::Security8021x) && type == NetworkManager::Setting::typeAsString(NetworkManager::Setting::WirelessSecurity))) { widget->loadSecrets(setting); } } } } } } else { KNotification *notification = new KNotification("FailedToGetSecrets", KNotification::CloseOnTimeout); notification->setComponentName("networkmanagement"); notification->setTitle(i18n("Failed to get secrets for %1", watcher->property("connection").toString())); notification->setText(reply.error().message()); notification->setPixmap(QIcon::fromTheme("dialog-warning").pixmap(KIconLoader::SizeHuge)); notification->sendEvent(); } watcher->deleteLater(); validChanged(true); // We should be now fully with secrets m_pendingReplies--; m_initialized = true; } void ConnectionEditorBase::validChanged(bool valid) { if (!valid) { m_valid = false; Q_EMIT validityChanged(false); return; } else { Q_FOREACH (SettingWidget *widget, m_settingWidgets) { if (!widget->isValid()) { m_valid = false; Q_EMIT validityChanged(false); return; } } } m_valid = true; Q_EMIT validityChanged(true); } diff --git a/libs/editor/connectioneditorbase.h b/libs/editor/connectioneditorbase.h index 30aa809d..398aeb27 100644 --- a/libs/editor/connectioneditorbase.h +++ b/libs/editor/connectioneditorbase.h @@ -1,87 +1,87 @@ /* Copyright 2013-2016 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_CONNECTION_EDITOR_BASE_H #define PLASMA_NM_CONNECTION_EDITOR_BASE_H #include #include #include class ConnectionWidget; class SettingWidget; class Q_DECL_EXPORT ConnectionEditorBase : public QWidget { Q_OBJECT public: explicit ConnectionEditorBase(const NetworkManager::ConnectionSettings::Ptr &connection, QWidget *parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); explicit ConnectionEditorBase(QWidget *parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); - virtual ~ConnectionEditorBase(); + ~ConnectionEditorBase() override; // When reimplementing do not forget to call the base method as well to initialize widgets virtual void setConnection(const NetworkManager::ConnectionSettings::Ptr &connection); NMVariantMapMap setting() const; // Returns whether the editor is fully initialized (including secrets) bool isInitialized() const; // Returns whether the filled values are valid bool isValid() const; Q_SIGNALS: // The default value is supposed to be false, watch this property for validity change after // proper initialization with secrets void validityChanged(bool valid); // Emited when user changed configuration void settingChanged(); private Q_SLOTS: void replyFinished(QDBusPendingCallWatcher *watcher); void validChanged(bool valid); protected: // Subclassed widget is supposed to take care of layouting for setting widgets virtual void addWidget(QWidget *widget, const QString &text) = 0; // Subclassed widget is supposed to provide an UI (input label) for editing connection name separately virtual QString connectionName() const = 0; // Subclassed widget is supposed to call initialization after the UI is initialized void initialize(); private: bool m_initialized; bool m_valid; int m_pendingReplies; NetworkManager::ConnectionSettings::Ptr m_connection; ConnectionWidget *m_connectionWidget; QList m_settingWidgets; void addConnectionWidget(ConnectionWidget *widget, const QString &text); void addSettingWidget(SettingWidget *widget, const QString &text); }; #endif // PLASMA_NM_CONNECTION_EDITOR_BASE_H diff --git a/libs/editor/connectioneditordialog.h b/libs/editor/connectioneditordialog.h index 6b791490..75900a11 100644 --- a/libs/editor/connectioneditordialog.h +++ b/libs/editor/connectioneditordialog.h @@ -1,49 +1,49 @@ /* Copyright 2016 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_CONNECTION_EDITOR_DIALOG_H #define PLASMA_NM_CONNECTION_EDITOR_DIALOG_H #include "connectioneditortabwidget.h" #include #include #include class Q_DECL_EXPORT ConnectionEditorDialog : public QDialog { Q_OBJECT public: explicit ConnectionEditorDialog(const NetworkManager::ConnectionSettings::Ptr &connection, QWidget *parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); - virtual ~ConnectionEditorDialog(); + ~ConnectionEditorDialog() override; NMVariantMapMap setting() const; private Q_SLOTS: void onValidityChanged(bool valid); private: QDialogButtonBox *m_buttonBox; ConnectionEditorTabWidget *m_connectionEditorTabWidget; }; #endif // PLASMA_NM_CONNECTION_EDITOR_BASE_H diff --git a/libs/editor/connectioneditortabwidget.h b/libs/editor/connectioneditortabwidget.h index ff9bf5ae..5d5426d8 100644 --- a/libs/editor/connectioneditortabwidget.h +++ b/libs/editor/connectioneditortabwidget.h @@ -1,55 +1,55 @@ /* Copyright 2016 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_CONNECTION_EDITOR_TAB_WIDGET_H #define PLASMA_NM_CONNECTION_EDITOR_TAB_WIDGET_H #include "connectioneditorbase.h" #include #include namespace Ui { class ConnectionEditorTabWidget; } class Q_DECL_EXPORT ConnectionEditorTabWidget : public ConnectionEditorBase { Q_OBJECT public: explicit ConnectionEditorTabWidget(const NetworkManager::ConnectionSettings::Ptr &connection, QWidget *parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); - virtual ~ConnectionEditorTabWidget(); + ~ConnectionEditorTabWidget() override; void setConnection(const NetworkManager::ConnectionSettings::Ptr &connection) override; protected: void addWidget(QWidget *widget, const QString &text) override; QString connectionName() const override; private: Ui::ConnectionEditorTabWidget *m_ui; void initializeTabWidget(const NetworkManager::ConnectionSettings::Ptr &connection); }; #endif // PLASMA_NM_CONNECTION_EDITOR_TAB_WIDGET_H diff --git a/libs/editor/listvalidator.h b/libs/editor/listvalidator.h index bb1ad96c..268ff0b0 100644 --- a/libs/editor/listvalidator.h +++ b/libs/editor/listvalidator.h @@ -1,47 +1,47 @@ /* Copyright 2009 Andrey Batyiev Copyright 2015 Jan Grulich 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef PLASMA_NM_LIST_VALIDATOR_H #define PLASMA_NM_LIST_VALIDATOR_H #include /** * This class validates each string item with a validator. * String items are separated by comma. * The validator should be set with setInnerValidator(..) method. * Please note, space characters are allowed only after comma characters. */ class ListValidator : public QValidator { public: - ListValidator(QObject *parent); - virtual ~ListValidator(); + explicit ListValidator(QObject *parent); + ~ListValidator() override; - virtual State validate(QString &text, int &pos) const; + State validate(QString &text, int &pos) const override; void setInnerValidator(QValidator *validator); private: QValidator *inner; }; #endif // PLASMA_NM_LIST_VALIDATOR_H diff --git a/libs/editor/mobileproviders.cpp b/libs/editor/mobileproviders.cpp index 568cb349..113458ff 100644 --- a/libs/editor/mobileproviders.cpp +++ b/libs/editor/mobileproviders.cpp @@ -1,323 +1,337 @@ /* Copyright 2010-2012 Lamarque Souza 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include "debug.h" #include "mobileproviders.h" #include #include - -#include +#include const QString MobileProviders::ProvidersFile = "/usr/share/mobile-broadband-provider-info/serviceproviders.xml"; bool localeAwareCompare(const QString & one, const QString & two) { return one.localeAwareCompare(two) < 0; } MobileProviders::MobileProviders() { - const QStringList allCountries = KLocale::global()->allCountriesList(); - Q_FOREACH (const QString & cc, allCountries) { - // qCDebug(PLASMA_NM) << "Inserting" << cc.toUpper() << KLocale::global()->countryCodeToName(cc); - mCountries.insert(cc.toUpper(), KLocale::global()->countryCodeToName(cc)); + for (int c = 1; c <= QLocale::LastCountry; c++) { + const auto country = static_cast(c); + QLocale locale(QLocale::AnyLanguage, country); + if (locale.country() == country) { + const QString localeName = locale.name(); + const auto idx = localeName.indexOf(QLatin1Char('_')); + if (idx != -1) { + const QString countryCode = localeName.mid(idx + 1); + QString countryName = locale.nativeCountryName(); + if (countryName.isEmpty()) { + countryName = QLocale::countryToString(country); + } + mCountries.insert(countryCode, countryName); + } + } } mError = Success; QFile file2(ProvidersFile); if (file2.open(QIODevice::ReadOnly)) { if (mDocProviders.setContent(&file2)) { docElement = mDocProviders.documentElement(); if (docElement.isNull()) { qCWarning(PLASMA_NM) << ProvidersFile << ": document is null"; mError = ProvidersIsNull; } else { if (docElement.isNull() || docElement.tagName() != "serviceproviders") { qCWarning(PLASMA_NM) << ProvidersFile << ": wrong format"; mError = ProvidersWrongFormat; } else { if (docElement.attribute("format") != "2.0") { qCWarning(PLASMA_NM) << ProvidersFile << ": mobile broadband provider database format '" << docElement.attribute("format") << "' not supported."; mError = ProvidersFormatNotSupported; } else { // qCDebug(PLASMA_NM) << "Everything is alright so far"; } } } } file2.close(); } else { qCWarning(PLASMA_NM) << "Error opening providers file" << ProvidersFile; mError = ProvidersMissing; } } MobileProviders::~MobileProviders() { } QStringList MobileProviders::getCountryList() const { QStringList temp = mCountries.values(); qSort(temp.begin(), temp.end(), localeAwareCompare); return temp; } QString MobileProviders::countryFromLocale() const { - return KLocale::global()->country().toUpper(); + const QString localeName = QLocale().name(); + const auto idx = localeName.indexOf(QLatin1Char('_')); + if (idx != -1) { + return localeName.mid(idx + 1); + } + return QString(); } QStringList MobileProviders::getProvidersList(QString country, NetworkManager::ConnectionSettings::ConnectionType type) { mProvidersGsm.clear(); mProvidersCdma.clear(); QDomNode n = docElement.firstChild(); // country is a country name and we parse country codes. if (!mCountries.key(country).isNull()) { country = mCountries.key(country); } QMap sortedGsm; QMap sortedCdma; while (!n.isNull()) { QDomElement e = n.toElement(); // if (!e.isNull() && e.attribute("code").toUpper() == country) { QDomNode n2 = e.firstChild(); while (!n2.isNull()) { QDomElement e2 = n2.toElement(); // if (!e2.isNull() && e2.tagName().toLower() == "provider") { QDomNode n3 = e2.firstChild(); bool hasGsm = false; bool hasCdma = false; QMap localizedProviderNames; while (!n3.isNull()) { QDomElement e3 = n3.toElement(); // if (!e3.isNull()) { if (e3.tagName().toLower() == "gsm") { hasGsm = true; } else if (e3.tagName().toLower() == "cdma") { hasCdma = true; } else if (e3.tagName().toLower() == "name") { QString lang = e3.attribute("xml:lang"); if (lang.isEmpty()) { lang = "en"; // English is default } else { lang = lang.toLower(); lang.remove(QRegExp("\\-.*$")); // Remove everything after '-' in xml:lang attribute. } localizedProviderNames.insert(lang, e3.text()); } } n3 = n3.nextSibling(); } const QString name = getNameByLocale(localizedProviderNames); if (hasGsm) { mProvidersGsm.insert(name, e2.firstChild()); sortedGsm.insert(name.toLower(), name); } if (hasCdma) { mProvidersCdma.insert(name, e2.firstChild()); sortedCdma.insert(name.toLower(), name); } } n2 = n2.nextSibling(); } break; } n = n.nextSibling(); } if (type == NetworkManager::ConnectionSettings::Gsm) { return sortedGsm.values(); } return sortedCdma.values(); } QStringList MobileProviders::getApns(const QString & provider) { mApns.clear(); mNetworkIds.clear(); if (!mProvidersGsm.contains(provider)) { return QStringList(); } QDomNode n = mProvidersGsm[provider]; while (!n.isNull()) { QDomElement e = n.toElement(); // if (!e.isNull() && e.tagName().toLower() == "gsm") { QDomNode n2 = e.firstChild(); while (!n2.isNull()) { QDomElement e2 = n2.toElement(); // if (!e2.isNull() && e2.tagName().toLower() == "apn") { bool isInternet = true; QDomNode n3 = e2.firstChild(); while (!n3.isNull()) { QDomElement e3 = n3.toElement(); // if (!e3.isNull() && e3.tagName().toLower() == "usage" && !e3.attribute("type").isNull() && e3.attribute("type").toLower() != "internet") { // qCDebug(PLASMA_NM) << "apn" << e2.attribute("value") << "ignored because of usage" << e3.attribute("type"); isInternet = false; break; } n3 = n3.nextSibling(); } if (isInternet) { mApns.insert(e2.attribute("value"), e2.firstChild()); } } else if (!e2.isNull() && e2.tagName().toLower() == "network-id") { mNetworkIds.append(e2.attribute("mcc") + '-' + e2.attribute("mnc")); } n2 = n2.nextSibling(); } } n = n.nextSibling(); } QStringList temp = mApns.keys(); temp.sort(); return temp; } QStringList MobileProviders::getNetworkIds(const QString & provider) { if (mNetworkIds.isEmpty()) { getApns(provider); } return mNetworkIds; } QVariantMap MobileProviders::getApnInfo(const QString & apn) { QVariantMap temp; QDomNode n = mApns[apn]; QStringList dnsList; QMap localizedPlanNames; while (!n.isNull()) { QDomElement e = n.toElement(); // if (!e.isNull()) { if (e.tagName().toLower() == "name") { QString lang = e.attribute("xml:lang"); if (lang.isEmpty()) { lang = "en"; // English is default } else { lang = lang.toLower(); lang.remove(QRegExp("\\-.*$")); // Remove everything after '-' in xml:lang attribute. } localizedPlanNames.insert(lang, e.text()); } else if (e.tagName().toLower() == "username") { temp.insert("username", e.text()); } else if (e.tagName().toLower() == "password") { temp.insert("password", e.text()); } else if (e.tagName().toLower() == "dns") { dnsList.append(e.text()); } } n = n.nextSibling(); } QString name = getNameByLocale(localizedPlanNames); if (!name.isEmpty()) { temp.insert("name", QVariant::fromValue(name)); } temp.insert("number", getGsmNumber()); temp.insert("apn", apn); temp.insert("dnsList", dnsList); return temp; } QVariantMap MobileProviders::getCdmaInfo(const QString & provider) { if (!mProvidersCdma.contains(provider)) { return QVariantMap(); } QVariantMap temp; QDomNode n = mProvidersCdma[provider]; QStringList sidList; while (!n.isNull()) { QDomElement e = n.toElement(); // if (!e.isNull() && e.tagName().toLower() == "cdma") { QDomNode n2 = e.firstChild(); while (!n2.isNull()) { QDomElement e2 = n2.toElement(); // if (!e2.isNull()) { if (e2.tagName().toLower() == "username") { temp.insert("username", e2.text()); } else if (e2.tagName().toLower() == "password") { temp.insert("password", e2.text()); } else if (e2.tagName().toLower() == "sid") { sidList.append(e2.text()); } } n2 = n2.nextSibling(); } } n = n.nextSibling(); } temp.insert("number", getCdmaNumber()); temp.insert("sidList", sidList); return temp; } QString MobileProviders::getNameByLocale(const QMap & localizedNames) const { QString name; - const QStringList locales = KLocale::global()->languageList(); + const QStringList locales = QLocale().uiLanguages(); Q_FOREACH (const QString & locale, locales) { - QString language, country, modifier, charset; - KLocale::splitLocale(locale, language, country, modifier, charset); + QString language = locale.split(QLatin1Char('-')).at(0); if (localizedNames.contains(language)) { return localizedNames[language]; } } name = localizedNames["en"]; // Use any language if no proper localized name were found. if (name.isEmpty() && !localizedNames.isEmpty()) { name = localizedNames.constBegin().value(); } return name; } diff --git a/libs/editor/plasma-networkmanagement-vpnuiplugin.desktop b/libs/editor/plasma-networkmanagement-vpnuiplugin.desktop index 5f53a971..900ac59b 100644 --- a/libs/editor/plasma-networkmanagement-vpnuiplugin.desktop +++ b/libs/editor/plasma-networkmanagement-vpnuiplugin.desktop @@ -1,92 +1,94 @@ [Desktop Entry] Type=ServiceType X-KDE-ServiceType=PlasmaNetworkManagement/VpnUiPlugin Name=Network Management VPN UI Plugin Name[bs]=Dodatak za upravljanje mrežom VPN UI Name[ca]=Connector de la IU per a la VPN del Gestor de la xarxa Name[ca@valencia]=Connector de la IU per a la VPN del Gestor de la xarxa Name[cs]=VPN UI modul pro správu sítě Name[da]=VPN UI-plugin til netværkshåndtering Name[de]=Netzwerkverwaltung - VPN-UI-Modul Name[el]=Πρόσθετο VPN UI της διαχείρισης δικτύων Name[en_GB]=Network Management VPN UI Plugin Name[es]=Complemento de la interfaz de usuario de gestión de redes Name[et]=Võrguhalduri VPN-i UI plugin Name[eu]=Sare-kudeaketaren VPN UI plugina Name[fi]=Verkonhallinnan VPN-käyttöliittymäliitännäinen Name[fr]=Module externe d'interface utilisateur VPN de gestion de réseau Name[gl]=Complemento de interface de VPN para a xestión da rede Name[he]=תוסף ממשק משתמש לניהול רשתות VPN Name[hu]=Hálózatkezelő VPN UI bővítmény Name[ia]=Plugin de VPN UI de gestion de rete +Name[id]=Plugin UI VPN Network Management Name[it]=Estensione interfaccia di gestione di rete di KDE Name[ko]=네트워크 관리 VPN UI 플러그인 Name[lt]=Tinklo valdymo VPN UI papildinys Name[nb]=Programtillegg til nettverkstyring med VPN brukerflate Name[nds]=Nettwarkpleger-VPN-Böversietmoduul Name[nl]=Netwerkbeheer VPN UI-plugin Name[nn]=Programtillegg for brukarflate for VPN Name[pa]=ਨੈੱਟਵਰਕ ਪਰਬੰਧ VPN UI ਪਲੱਗਇਨ Name[pl]=Wtyczka VPN interfejsu użytkownika dla zarządzania siecią Name[pt]='Plugin' de Interface VPN da Gestão de Rede Name[pt_BR]=Plugin de interface VPN do gerenciamento de redes Name[ro]=Modul de interfață VPN pentru gestiunea rețelei Name[ru]=Графический модуль управления сетевыми VPN-соединениями Name[sk]=Modul pre správu siete VPN Name[sl]=Vstavek vmesnika za upravljanje omrežij VPN Name[sr]=Прикључак ВПН сучеља за управљање мрежом Name[sr@ijekavian]=Прикључак ВПН сучеља за управљање мрежом Name[sr@ijekavianlatin]=Priključak VPN sučelja za upravljanje mrežom Name[sr@latin]=Priključak VPN sučelja za upravljanje mrežom Name[sv]=Insticksprogram till nätverkshantering med VPN-användargränssnitt Name[tr]=Ağ Yönetimi VPN UI Eklentisi Name[ug]=تور باشقۇرۇش VPN UI قىستۇرمىسى Name[uk]=Додаток графічного інтерфейсу керування мережею VPN Name[x-test]=xxNetwork Management VPN UI Pluginxx Name[zh_CN]=网络管理 VPN 用户界面插件 Name[zh_TW]=網路管理 VPN 使用者介面外掛程式 Comment=Defines KDE Network Management UI Plugins Comment[bs]=Definiše KDE dodatke za upravljanje mrežom Comment[ca]=Defineix els connectors de la IU del Gestor de la xarxa del KDE Comment[ca@valencia]=Defineix els connectors de la IU del Gestor de la xarxa del KDE Comment[cs]=Definuje grafické moduly správy sítě KDE Comment[da]=Definerer UI-plugins til KDE netværkshåndtering Comment[de]=Legt die Module der KDE-Netzwerkverwaltung fest Comment[el]=Καθορίζει τα πρόσθετα UI της διαχείρισης δικτύων Comment[en_GB]=Defines KDE Network Management UI Plugins Comment[es]=Define los complementos de la interfaz de usuario de la gestión de redes de KDE Comment[et]=Võrguhalduri UI pluginate määratlus Comment[eu]=KDEren sare-kudeaketaren UI pluginak Comment[fi]=Määrittää KDE:n verkonhallinnan käyttöliittymäliitännäiset Comment[fr]=Définit les modules externes d'interface utilisateur de gestion de réseau pour KDE Comment[gl]=Define complementos de interface para a xestión de redes de KDE Comment[hu]=Meghatározza a KDE hálózatkezelő UI bővítményeket Comment[ia]=Define Plugins de UI de gestion de rete de KDE +Comment[id]=Menentukan Plugin UI Pengelolaan Network KDE Comment[it]=Definisce le estensioni dell'interfaccia di gestione rete di KDE Comment[ko]=KDE 네트워크 관리 UI 플러그인 정의 Comment[lt]=Apibrėžia KDE Tinklo valdymo UI papildinius Comment[nb]=Definerer brukerflate-tillegg til KDE nettverkstyring Comment[nds]=Leggt Böversietmodulen för de KDE-Nettwarkpleeg fast Comment[nl]=Definieert KDE netwerkbeheer UI-plugins Comment[nn]=Definerer brukarflate-tillegg til KDE-nettverksstyring Comment[pa]=KDE ਨੈੱਟਵਰਕ ਪਰਬੰਧ UI ਪਲੱਗਇਨ ਪਰਿਭਾਸ਼ਿਤ ਕਰੋ Comment[pl]=Określa wtyczki interfejsu użytkownika dla zarządzania siecią Comment[pt]=Define os 'plugins' de interface da Gestão de Rede Comment[pt_BR]=Define os plugins de interface do gerenciamento de redes Comment[ro]=Definește modulele de interfață pentru gestiunea rețelei Comment[ru]=Графический модуль управления сетевыми соединениями для KDE Comment[sk]=Definuje moduly pre správu siete KDE Comment[sl]=Določa vstavke za KDE-jev vmesnik za upravljanje omrežij Comment[sr]=Дефинише КДЕ прикључке за управљање мрежом Comment[sr@ijekavian]=Дефинише КДЕ прикључке за управљање мрежом Comment[sr@ijekavianlatin]=Definiše KDE priključke za upravljanje mrežom Comment[sr@latin]=Definiše KDE priključke za upravljanje mrežom Comment[sv]=Definierar insticksprogram för KDE:s nätverkshantering Comment[tr]=KDE Ağ Yönetimi UI Eklentilerini tanımlar Comment[uk]=Визначає додатки інтерфейсу засобу керування мережею KDE Comment[x-test]=xxDefines KDE Network Management UI Pluginsxx Comment[zh_CN]=定义 KDE 网络管理用户界面插件 Comment[zh_TW]=定義 KDE 網路管理介面外掛程式 [PropertyDef::X-NetworkManager-Services] Type=QString diff --git a/libs/editor/settings/bondwidget.cpp b/libs/editor/settings/bondwidget.cpp index f1ea3ff3..63b8aa07 100644 --- a/libs/editor/settings/bondwidget.cpp +++ b/libs/editor/settings/bondwidget.cpp @@ -1,305 +1,305 @@ /* Copyright 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "bondwidget.h" #include "ui_bond.h" #include "connectioneditordialog.h" #include "debug.h" #include #include #include #include #include #include #include #define NM_SETTING_BOND_OPTION_MII_MONITOR "mii" #define NM_SETTING_BOND_OPTION_ARP_MONITOR "arp" BondWidget::BondWidget(const QString & masterUuid, const NetworkManager::Setting::Ptr &setting, QWidget* parent, Qt::WindowFlags f): SettingWidget(setting, parent, f), m_uuid(masterUuid), m_ui(new Ui::BondWidget) { m_ui->setupUi(this); // Action buttons and menu m_menu = new QMenu(this); QAction * action = new QAction(i18n("Ethernet"), this); action->setData(NetworkManager::ConnectionSettings::Wired); m_menu->addAction(action); action = new QAction(i18n("InfiniBand"), this); action->setData(NetworkManager::ConnectionSettings::Infiniband); m_menu->addAction(action); m_ui->btnAdd->setMenu(m_menu); connect(m_menu, &QMenu::triggered, this, &BondWidget::addBond); connect(m_ui->btnEdit, &QPushButton::clicked, this, &BondWidget::editBond); connect(m_ui->btnDelete, &QPushButton::clicked, this, &BondWidget::deleteBond); // mode m_ui->mode->addItem(i18nc("bond mode", "Round-robin"), QLatin1String("balance-rr")); m_ui->mode->addItem(i18nc("bond mode", "Active backup"), QLatin1String("active-backup")); m_ui->mode->addItem(i18nc("bond mode", "Broadcast"), QLatin1String("broadcast")); m_ui->mode->addItem(i18nc("bond mode", "802.3ad"), QLatin1String("802.3ad")); m_ui->mode->addItem(i18nc("bond mode", "Adaptive transmit load balancing"), QLatin1String("balance-tlb")); m_ui->mode->addItem(i18nc("bond mode", "Adaptive load balancing"), QLatin1String("balance-alb")); // link monitor m_ui->linkMonitoring->addItem(i18nc("bond link monitoring", "MII (recommended)"), NM_SETTING_BOND_OPTION_MII_MONITOR); m_ui->linkMonitoring->addItem(i18nc("bond link monitoring", "ARP"), NM_SETTING_BOND_OPTION_ARP_MONITOR); // bonds populateBonds(); connect(m_ui->bonds, &QListWidget::currentItemChanged, this, &BondWidget::currentBondChanged); connect(m_ui->bonds, &QListWidget::itemDoubleClicked, this, &BondWidget::editBond); connect(m_ui->ifaceName, &KLineEdit::textChanged, this, &BondWidget::slotWidgetChanged); connect(m_ui->arpTargets, &KLineEdit::textChanged, this, &BondWidget::slotWidgetChanged); - connect(m_ui->linkMonitoring, static_cast(&KComboBox::currentIndexChanged), this, &BondWidget::slotWidgetChanged); + connect(m_ui->linkMonitoring, QOverload::of(&KComboBox::currentIndexChanged), this, &BondWidget::slotWidgetChanged); // Connect for setting check watchChangedSetting(); KAcceleratorManager::manage(this); KAcceleratorManager::manage(m_menu); if (setting) { loadConfig(setting); } } BondWidget::~BondWidget() { delete m_ui; } void BondWidget::loadConfig(const NetworkManager::Setting::Ptr &setting) { NetworkManager::BondSetting::Ptr bondSetting = setting.staticCast(); m_ui->ifaceName->setText(bondSetting->interfaceName()); const NMStringMap options = bondSetting->options(); // mode int modeIndex = m_ui->mode->findData(options.value(NM_SETTING_BOND_OPTION_MODE)); if (modeIndex == -1) modeIndex = 0; m_ui->mode->setCurrentIndex(modeIndex); const QString arpTargets = options.value(NM_SETTING_BOND_OPTION_ARP_IP_TARGET); if (!arpTargets.isEmpty()) { // ARP m_ui->linkMonitoring->setCurrentIndex(m_ui->linkMonitoring->findData(NM_SETTING_BOND_OPTION_ARP_MONITOR)); bool ok = false; const int arpMonFreq = options.value(NM_SETTING_BOND_OPTION_ARP_INTERVAL).toInt(&ok); if (ok && arpMonFreq > 0) m_ui->monitorFreq->setValue(arpMonFreq); m_ui->arpTargets->setText(arpTargets); } else { // MII m_ui->linkMonitoring->setCurrentIndex(m_ui->linkMonitoring->findData(NM_SETTING_BOND_OPTION_MII_MONITOR)); bool ok = false; const int miiMonFreq = options.value(NM_SETTING_BOND_OPTION_MIIMON).toInt(&ok); if (ok && miiMonFreq > 0) m_ui->monitorFreq->setValue(miiMonFreq); ok = false; const int upDelay = options.value(NM_SETTING_BOND_OPTION_UPDELAY).toInt(&ok); if (ok && upDelay > 0) m_ui->upDelay->setValue(upDelay); ok = false; const int downDelay = options.value(NM_SETTING_BOND_OPTION_DOWNDELAY).toInt(&ok); if (ok && downDelay > 0) m_ui->upDelay->setValue(downDelay); } } QVariantMap BondWidget::setting() const { NetworkManager::BondSetting setting; setting.setInterfaceName(m_ui->ifaceName->text()); NMStringMap options; options.insert(NM_SETTING_BOND_OPTION_MODE, m_ui->mode->itemData(m_ui->mode->currentIndex()).toString()); if (m_ui->linkMonitoring->itemData(m_ui->linkMonitoring->currentIndex()).toString() == NM_SETTING_BOND_OPTION_MII_MONITOR) { // MII options.insert(NM_SETTING_BOND_OPTION_MIIMON, QString::number(m_ui->monitorFreq->value())); const int upDelay = m_ui->upDelay->value(); if (upDelay) options.insert(NM_SETTING_BOND_OPTION_UPDELAY, QString::number(upDelay)); const int downDelay = m_ui->downDelay->value(); if (downDelay) options.insert(NM_SETTING_BOND_OPTION_DOWNDELAY, QString::number(downDelay)); } else { // ARP options.insert(NM_SETTING_BOND_OPTION_ARP_INTERVAL, QString::number(m_ui->monitorFreq->value())); const QString arpTargets = m_ui->arpTargets->text(); if (!arpTargets.isEmpty()) options.insert(NM_SETTING_BOND_OPTION_ARP_IP_TARGET, arpTargets); } setting.setOptions(options); return setting.toMap(); } void BondWidget::addBond(QAction *action) { qCDebug(PLASMA_NM) << "Adding bonded connection:" << action->data(); qCDebug(PLASMA_NM) << "Master UUID:" << m_uuid; qCDebug(PLASMA_NM) << "Slave type:" << type(); NetworkManager::ConnectionSettings::ConnectionType connectionType = static_cast(action->data().toInt()); NetworkManager::ConnectionSettings::Ptr connectionSettings = NetworkManager::ConnectionSettings::Ptr(new NetworkManager::ConnectionSettings(connectionType)); connectionSettings->setUuid(NetworkManager::ConnectionSettings::createNewUuid()); connectionSettings->setMaster(m_uuid); connectionSettings->setSlaveType(type()); connectionSettings->setAutoconnect(false); QPointer bondEditor = new ConnectionEditorDialog(connectionSettings); connect(bondEditor.data(), &ConnectionEditorDialog::accepted, [bondEditor, this] () { qCDebug(PLASMA_NM) << "Saving slave connection"; // qCDebug(PLASMA_NM) << bondEditor->setting(); QDBusPendingReply reply = NetworkManager::addConnection(bondEditor->setting()); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this); connect(watcher, &QDBusPendingCallWatcher::finished, this, &BondWidget::bondAddComplete); }); connect(bondEditor.data(), &ConnectionEditorDialog::finished, [bondEditor] () { if (bondEditor) { bondEditor->deleteLater(); } }); bondEditor->setModal(true); bondEditor->show(); } void BondWidget::currentBondChanged(QListWidgetItem *current, QListWidgetItem *previous) { Q_UNUSED(previous) m_ui->btnEdit->setEnabled(current); m_ui->btnDelete->setEnabled(current); } void BondWidget::bondAddComplete(QDBusPendingCallWatcher * watcher) { QDBusPendingReply reply = *watcher; if (reply.isValid()) { // find the slave connection with matching UUID NetworkManager::Connection::Ptr connection = NetworkManager::findConnection(reply.value().path()); if (connection && connection->settings()->master() == m_uuid) { const QString label = QString("%1 (%2)").arg(connection->name()).arg(connection->settings()->typeAsString(connection->settings()->connectionType())); QListWidgetItem * slaveItem = new QListWidgetItem(label, m_ui->bonds); slaveItem->setData(Qt::UserRole, connection->uuid()); slotWidgetChanged(); } } else { qCWarning(PLASMA_NM) << "Bonded connection not added:" << reply.error().message(); } } void BondWidget::editBond() { QListWidgetItem * currentItem = m_ui->bonds->currentItem(); if (!currentItem) return; const QString uuid = currentItem->data(Qt::UserRole).toString(); NetworkManager::Connection::Ptr connection = NetworkManager::findConnectionByUuid(uuid); if (connection) { // qCDebug(PLASMA_NM) << "Editing bonded connection" << currentItem->text() << uuid; QPointer bondEditor = new ConnectionEditorDialog(connection->settings()); connect(bondEditor.data(), &ConnectionEditorDialog::accepted, [connection, bondEditor, this] () { connection->update(bondEditor->setting()); connect(connection.data(), &NetworkManager::Connection::updated, this, &BondWidget::populateBonds); }); connect(bondEditor.data(), &ConnectionEditorDialog::finished, [bondEditor] () { if (bondEditor) { bondEditor->deleteLater(); } }); bondEditor->setModal(true); bondEditor->show(); } } void BondWidget::deleteBond() { QListWidgetItem * currentItem = m_ui->bonds->currentItem(); if (!currentItem) return; const QString uuid = currentItem->data(Qt::UserRole).toString(); NetworkManager::Connection::Ptr connection = NetworkManager::findConnectionByUuid(uuid); if (connection) { // qCDebug(PLASMA_NM) << "About to delete bonded connection" << currentItem->text() << uuid; if (KMessageBox::questionYesNo(this, i18n("Do you want to remove the connection '%1'?", connection->name()), i18n("Remove Connection"), KStandardGuiItem::remove(), KStandardGuiItem::no(), QString(), KMessageBox::Dangerous) == KMessageBox::Yes) { connection->remove(); delete currentItem; slotWidgetChanged(); } } } void BondWidget::populateBonds() { m_ui->bonds->clear(); Q_FOREACH (const NetworkManager::Connection::Ptr &connection, NetworkManager::listConnections()) { NetworkManager::ConnectionSettings::Ptr settings = connection->settings(); if (settings->master() == m_uuid && settings->slaveType() == type()) { const QString label = QString("%1 (%2)").arg(connection->name()).arg(connection->settings()->typeAsString(connection->settings()->connectionType())); QListWidgetItem * slaveItem = new QListWidgetItem(label, m_ui->bonds); slaveItem->setData(Qt::UserRole, connection->uuid()); } } } bool BondWidget::isValid() const { if (m_ui->linkMonitoring->itemData(m_ui->linkMonitoring->currentIndex()).toString() == NM_SETTING_BOND_OPTION_ARP_MONITOR) { const QStringList ipAddresses = m_ui->arpTargets->text().split(','); if (ipAddresses.isEmpty()) { return false; } Q_FOREACH (const QString & ip, ipAddresses) { QHostAddress ipAddress(ip); if (ipAddress.isNull()) { return false; } } } return !m_ui->ifaceName->text().isEmpty() && m_ui->bonds->count() > 0; } diff --git a/libs/editor/settings/bondwidget.h b/libs/editor/settings/bondwidget.h index b485cf2e..24a8cdfc 100644 --- a/libs/editor/settings/bondwidget.h +++ b/libs/editor/settings/bondwidget.h @@ -1,68 +1,68 @@ /* Copyright 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_BOND_WIDGET_H #define PLASMA_NM_BOND_WIDGET_H #include #include #include #include #include #include "settingwidget.h" namespace Ui { class BondWidget; } class Q_DECL_EXPORT BondWidget : public SettingWidget { Q_OBJECT public: explicit BondWidget(const QString & masterUuid, const NetworkManager::Setting::Ptr &setting = NetworkManager::Setting::Ptr(), - QWidget* parent = 0, Qt::WindowFlags f = 0); - virtual ~BondWidget(); + QWidget* parent = nullptr, Qt::WindowFlags f = {}); + ~BondWidget() override; - void loadConfig(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; - QVariantMap setting() const Q_DECL_OVERRIDE; + QVariantMap setting() const override; - virtual bool isValid() const Q_DECL_OVERRIDE; + bool isValid() const override; private Q_SLOTS: void addBond(QAction * action); void currentBondChanged(QListWidgetItem * current, QListWidgetItem * previous); void bondAddComplete(QDBusPendingCallWatcher * watcher); void editBond(); void deleteBond(); void populateBonds(); private: QString m_uuid; Ui::BondWidget * m_ui; QMenu * m_menu; }; #endif // PLASMA_NM_BOND_WIDGET_H diff --git a/libs/editor/settings/bridgewidget.h b/libs/editor/settings/bridgewidget.h index f1f505d0..2e04b9e3 100644 --- a/libs/editor/settings/bridgewidget.h +++ b/libs/editor/settings/bridgewidget.h @@ -1,68 +1,68 @@ /* Copyright 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_BRIDGE_WIDGET_H #define PLASMA_NM_BRIDGE_WIDGET_H #include #include #include #include #include #include "settingwidget.h" namespace Ui { class BridgeWidget; } class Q_DECL_EXPORT BridgeWidget : public SettingWidget { Q_OBJECT public: explicit BridgeWidget(const QString & masterUuid, const NetworkManager::Setting::Ptr &setting = NetworkManager::Setting::Ptr(), - QWidget* parent = 0, Qt::WindowFlags f = 0); - virtual ~BridgeWidget(); + QWidget* parent = nullptr, Qt::WindowFlags f = {}); + ~BridgeWidget() override; - void loadConfig(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; - QVariantMap setting() const Q_DECL_OVERRIDE; + QVariantMap setting() const override; - virtual bool isValid() const Q_DECL_OVERRIDE; + bool isValid() const override; private Q_SLOTS: void addBridge(QAction * action); void currentBridgeChanged(QListWidgetItem * current, QListWidgetItem * previous); void bridgeAddComplete(QDBusPendingCallWatcher * watcher); void editBridge(); void deleteBridge(); void populateBridges(); private: QString m_uuid; Ui::BridgeWidget * m_ui; QMenu * m_menu; }; #endif // PLASMA_NM_BRIDGE_WIDGET_H diff --git a/libs/editor/settings/btwidget.h b/libs/editor/settings/btwidget.h index ee556e96..f3b53ed7 100644 --- a/libs/editor/settings/btwidget.h +++ b/libs/editor/settings/btwidget.h @@ -1,52 +1,52 @@ /* Copyright 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_BT_WIDGET_H #define PLASMA_NM_BT_WIDGET_H #include #include #include "settingwidget.h" namespace Ui { class BtWidget; } class Q_DECL_EXPORT BtWidget : public SettingWidget { Q_OBJECT public: - explicit BtWidget(const NetworkManager::Setting::Ptr &setting = NetworkManager::Setting::Ptr(), QWidget* parent = 0, Qt::WindowFlags f = 0); - virtual ~BtWidget(); + explicit BtWidget(const NetworkManager::Setting::Ptr &setting = NetworkManager::Setting::Ptr(), QWidget* parent = nullptr, Qt::WindowFlags f = {}); + ~BtWidget() override; - void loadConfig(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; - QVariantMap setting() const Q_DECL_OVERRIDE; + QVariantMap setting() const override; - virtual bool isValid() const Q_DECL_OVERRIDE; + bool isValid() const override; private: Ui::BtWidget * m_ui; }; #endif // PLASMA_NM_BT_WIDGET_H diff --git a/libs/editor/settings/cdmawidget.h b/libs/editor/settings/cdmawidget.h index b1b480b3..e9d259e0 100644 --- a/libs/editor/settings/cdmawidget.h +++ b/libs/editor/settings/cdmawidget.h @@ -1,53 +1,53 @@ /* Copyright 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_CDMA_WIDGET_H #define PLASMA_NM_CDMA_WIDGET_H #include #include #include "settingwidget.h" namespace Ui { class CdmaWidget; } class Q_DECL_EXPORT CdmaWidget : public SettingWidget { Q_OBJECT public: - explicit CdmaWidget(const NetworkManager::Setting::Ptr &setting = NetworkManager::Setting::Ptr(), QWidget *parent = 0, Qt::WindowFlags f = 0); - virtual ~CdmaWidget(); + explicit CdmaWidget(const NetworkManager::Setting::Ptr &setting = NetworkManager::Setting::Ptr(), QWidget *parent = nullptr, Qt::WindowFlags f = {}); + ~CdmaWidget() override; - void loadConfig(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; - void loadSecrets(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; + void loadSecrets(const NetworkManager::Setting::Ptr &setting) override; - QVariantMap setting() const Q_DECL_OVERRIDE; + QVariantMap setting() const override; - virtual bool isValid() const Q_DECL_OVERRIDE; + bool isValid() const override; private: Ui::CdmaWidget *m_ui; }; #endif // PLASMA_NM_CDMA_WIDGET_H diff --git a/libs/editor/settings/connectionwidget.cpp b/libs/editor/settings/connectionwidget.cpp index 17455f2d..365a0188 100644 --- a/libs/editor/settings/connectionwidget.cpp +++ b/libs/editor/settings/connectionwidget.cpp @@ -1,217 +1,217 @@ /* Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "connectionwidget.h" #include "ui_connectionwidget.h" #include "advancedpermissionswidget.h" #include #include #include #include #include #include #include #include #include ConnectionWidget::ConnectionWidget(const NetworkManager::ConnectionSettings::Ptr &settings, QWidget* parent, Qt::WindowFlags f): QWidget(parent, f), m_widget(new Ui::ConnectionWidget), m_type(settings->connectionType()), m_masterUuid(settings->master()), m_slaveType(settings->slaveType()) { m_widget->setupUi(this); m_widget->firewallZone->addItems(firewallZones()); // VPN combo populateVpnConnections(); if (settings->connectionType() == NetworkManager::ConnectionSettings::Vpn) { m_widget->autoconnectVpn->setEnabled(false); m_widget->vpnCombobox->setEnabled(false); m_widget->autoconnect->setEnabled(false); } else { m_widget->autoconnectVpn->setEnabled(true); m_widget->autoconnect->setEnabled(true); } connect(m_widget->autoconnectVpn, &QCheckBox::toggled, this, &ConnectionWidget::autoVpnToggled); if (NetworkManager::compareVersion(QLatin1String("1.0.0")) >= 0) { m_widget->prioritySpin->setEnabled(true); m_widget->nmVersionWarning->setVisible(false); } else { m_widget->prioritySpin->setEnabled(false); m_widget->nmVersionWarning->setVisible(true); } if (settings) { loadConfig(settings); } m_tmpSetting.setPermissions(settings->permissions()); KAcceleratorManager::manage(this); connect(m_widget->autoconnect, &QCheckBox::stateChanged, this, &ConnectionWidget::settingChanged); connect(m_widget->allUsers, &QCheckBox::stateChanged, this, &ConnectionWidget::settingChanged); connect(m_widget->autoconnectVpn, &QCheckBox::stateChanged, this, &ConnectionWidget::settingChanged); connect(m_widget->pushButtonPermissions, &QPushButton::clicked, this, &ConnectionWidget::settingChanged); - connect(m_widget->firewallZone, static_cast(&QComboBox::currentIndexChanged), this, &ConnectionWidget::settingChanged); + connect(m_widget->firewallZone, QOverload::of(&QComboBox::currentIndexChanged), this, &ConnectionWidget::settingChanged); connect(m_widget->firewallZone, &QComboBox::currentTextChanged, this, &ConnectionWidget::settingChanged); - connect(m_widget->vpnCombobox, static_cast(&QComboBox::currentIndexChanged), this, &ConnectionWidget::settingChanged); + connect(m_widget->vpnCombobox, QOverload::of(&QComboBox::currentIndexChanged), this, &ConnectionWidget::settingChanged); connect(m_widget->vpnCombobox, &QComboBox::currentTextChanged, this, &ConnectionWidget::settingChanged); - connect(m_widget->prioritySpin, static_cast(&QSpinBox::valueChanged), this, &ConnectionWidget::settingChanged); + connect(m_widget->prioritySpin, QOverload::of(&QSpinBox::valueChanged), this, &ConnectionWidget::settingChanged); connect(m_widget->pushButtonPermissions, &QPushButton::clicked, this, &ConnectionWidget::openAdvancedPermissions); } ConnectionWidget::~ConnectionWidget() { delete m_widget; } void ConnectionWidget::loadConfig(const NetworkManager::ConnectionSettings::Ptr &settings) { if (settings->permissions().isEmpty()) { m_widget->allUsers->setChecked(true); } else { m_widget->allUsers->setChecked(false); } const QString zone = settings->zone(); m_widget->firewallZone->setCurrentIndex(m_widget->firewallZone->findText(zone)); const QStringList secondaries = settings->secondaries(); const QStringList vpnKeys = vpnConnections().keys(); if (!secondaries.isEmpty() && !vpnKeys.isEmpty()) { Q_FOREACH (const QString & vpnKey, vpnKeys) { if (secondaries.contains(vpnKey)) { m_widget->vpnCombobox->setCurrentIndex(m_widget->vpnCombobox->findData(vpnKey)); m_widget->autoconnectVpn->setChecked(true); break; } } } else { m_widget->autoconnectVpn->setChecked(false); } m_widget->autoconnect->setChecked(settings->autoconnect()); #if NM_CHECK_VERSION(1, 0, 0) if (m_widget->prioritySpin->isEnabled()) { m_widget->prioritySpin->setValue(settings->autoconnectPriority()); } #endif } NMVariantMapMap ConnectionWidget::setting() const { NetworkManager::ConnectionSettings settings; settings.setConnectionType(m_type); settings.setAutoconnect(m_widget->autoconnect->isChecked()); settings.setMaster(m_masterUuid); settings.setSlaveType(m_slaveType); if (m_widget->allUsers->isChecked()) { settings.setPermissions(QHash()); } else { if (m_tmpSetting.permissions().isEmpty()) { settings.addToPermissions(KUser().loginName(), QString()); } else { settings.setPermissions(m_tmpSetting.permissions()); } } if (m_widget->autoconnectVpn->isChecked() && m_widget->vpnCombobox->count() > 0) { settings.setSecondaries(QStringList() << m_widget->vpnCombobox->itemData(m_widget->vpnCombobox->currentIndex()).toString()); } const QString zone = m_widget->firewallZone->currentText(); if (!zone.isEmpty()) { settings.setZone(zone); } #if NM_CHECK_VERSION(1, 0, 0) if (m_widget->prioritySpin->isEnabled()) { settings.setAutoconnectPriority(m_widget->prioritySpin->value()); } #endif return settings.toMap(); } void ConnectionWidget::autoVpnToggled(bool on) { m_widget->vpnCombobox->setEnabled(on); } void ConnectionWidget::openAdvancedPermissions() { QPointer dialog = new AdvancedPermissionsWidget(m_tmpSetting.permissions(), this); dialog->setWindowTitle(i18nc("@title:window advanced permissions editor", "Advanced Permissions Editor")); if (dialog->exec() == QDialog::Accepted) { m_tmpSetting.setPermissions(dialog->currentUsers()); } delete dialog; } NMStringMap ConnectionWidget::vpnConnections() const { NetworkManager::Connection::List list = NetworkManager::listConnections(); NMStringMap result; Q_FOREACH (const NetworkManager::Connection::Ptr & conn, list) { NetworkManager::ConnectionSettings::Ptr conSet = conn->settings(); if (conSet->connectionType() == NetworkManager::ConnectionSettings::Vpn) { // qCDebug(PLASMA_NM) << "Found VPN" << conSet->id() << conSet->uuid(); result.insert(conSet->uuid(), conSet->id()); } } return result; } QStringList ConnectionWidget::firewallZones() const { QDBusMessage msg = QDBusMessage::createMethodCall("org.fedoraproject.FirewallD1", "/org/fedoraproject/FirewallD1", "org.fedoraproject.FirewallD1.zone", "getZones"); QDBusPendingReply reply = QDBusConnection::systemBus().asyncCall(msg); reply.waitForFinished(); if (reply.isValid()) return reply.value(); return QStringList(); } void ConnectionWidget::populateVpnConnections() { QMapIterator it(vpnConnections()); while (it.hasNext()) { it.next(); m_widget->vpnCombobox->addItem(it.value(), it.key()); } } diff --git a/libs/editor/settings/connectionwidget.h b/libs/editor/settings/connectionwidget.h index e93f66cd..3f3f9b2a 100644 --- a/libs/editor/settings/connectionwidget.h +++ b/libs/editor/settings/connectionwidget.h @@ -1,67 +1,67 @@ /* Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_CONNECTION_WIDGET_H #define PLASMA_NM_CONNECTION_WIDGET_H #include #include namespace Ui { class ConnectionWidget; } class ConnectionWidget : public QWidget { Q_OBJECT public: explicit ConnectionWidget(const NetworkManager::ConnectionSettings::Ptr &settings = NetworkManager::ConnectionSettings::Ptr(), - QWidget* parent = 0, Qt::WindowFlags f = 0); - virtual ~ConnectionWidget(); + QWidget* parent = nullptr, Qt::WindowFlags f = {}); + ~ConnectionWidget() override; void loadConfig(const NetworkManager::ConnectionSettings::Ptr &settings); NMVariantMapMap setting() const; private Q_SLOTS: void autoVpnToggled(bool on); void openAdvancedPermissions(); Q_SIGNALS: void settingChanged(); private: // list of VPN: UUID, name NMStringMap vpnConnections() const; // list of firewalld zones QStringList firewallZones() const; void populateVpnConnections(); Ui::ConnectionWidget * m_widget; NetworkManager::ConnectionSettings m_tmpSetting; NetworkManager::ConnectionSettings::ConnectionType m_type; QString m_masterUuid; QString m_slaveType; }; #endif // PLASMA_NM_CONNECTION_WIDGET_H diff --git a/libs/editor/settings/gsmwidget.h b/libs/editor/settings/gsmwidget.h index 2e394dda..ea16c476 100644 --- a/libs/editor/settings/gsmwidget.h +++ b/libs/editor/settings/gsmwidget.h @@ -1,53 +1,53 @@ /* Copyright 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_GSM_WIDGET_H #define PLASMA_NM_GSM_WIDGET_H #include #include #include "settingwidget.h" namespace Ui { class GsmWidget; } class Q_DECL_EXPORT GsmWidget : public SettingWidget { Q_OBJECT public: - explicit GsmWidget(const NetworkManager::Setting::Ptr &setting = NetworkManager::Setting::Ptr(), QWidget *parent = 0, Qt::WindowFlags f = 0); - virtual ~GsmWidget(); + explicit GsmWidget(const NetworkManager::Setting::Ptr &setting = NetworkManager::Setting::Ptr(), QWidget *parent = nullptr, Qt::WindowFlags f = {}); + ~GsmWidget() override; - void loadConfig(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; - void loadSecrets(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; + void loadSecrets(const NetworkManager::Setting::Ptr &setting) override; - QVariantMap setting() const Q_DECL_OVERRIDE; + QVariantMap setting() const override; - virtual bool isValid() const Q_DECL_OVERRIDE; + bool isValid() const override; private: Ui::GsmWidget *m_ui; }; #endif // PLASMA_NM_GSM_WIDGET_H diff --git a/libs/editor/settings/infinibandwidget.h b/libs/editor/settings/infinibandwidget.h index 84081775..9e8e90b7 100644 --- a/libs/editor/settings/infinibandwidget.h +++ b/libs/editor/settings/infinibandwidget.h @@ -1,52 +1,52 @@ /* Copyright 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_INFINIBAND_WIDGET_H #define PLASMA_NM_INFINIBAND_WIDGET_H #include #include #include "settingwidget.h" namespace Ui { class InfinibandWidget; } class Q_DECL_EXPORT InfinibandWidget : public SettingWidget { Q_OBJECT public: - explicit InfinibandWidget(const NetworkManager::Setting::Ptr &setting = NetworkManager::Setting::Ptr(), QWidget* parent = 0, Qt::WindowFlags f = 0); - virtual ~InfinibandWidget(); + explicit InfinibandWidget(const NetworkManager::Setting::Ptr &setting = NetworkManager::Setting::Ptr(), QWidget* parent = nullptr, Qt::WindowFlags f = {}); + ~InfinibandWidget() override; - void loadConfig(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; - QVariantMap setting() const Q_DECL_OVERRIDE; + QVariantMap setting() const override; - virtual bool isValid() const Q_DECL_OVERRIDE; + bool isValid() const override; private: Ui::InfinibandWidget * m_ui; }; #endif // PLASMA_NM_INFI_WIDGET_H diff --git a/libs/editor/settings/ipv4widget.cpp b/libs/editor/settings/ipv4widget.cpp index 65951d39..84ea38c1 100644 --- a/libs/editor/settings/ipv4widget.cpp +++ b/libs/editor/settings/ipv4widget.cpp @@ -1,500 +1,500 @@ /* Copyright (c) 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "ipv4widget.h" #include "ui_ipv4.h" #include "ipv4delegate.h" #include #include #include #include #include #include #include quint32 suggestNetmask(quint32 ip) { /* A 0 0.0.0.0 <-->127.255.255.255 255.0.0.0 <--->/8 B 10 128.0.0.0 <>191.255.255.255 255.255.0.0 <->/16 C 110 192.0.0.0 <>223.255.255.255 255.255.255.0 >/24 D 1110 224.0.0.0 <>239.255.255.255 not defined <->not defined E 1111 240.0.0.0 <>255.255.255.254 not defined <->not defined */ quint32 netmask = 0; if (!(ip & 0x80000000)) { // test 0 leading bit netmask = 0xFF000000; } else if (!(ip & 0x40000000)) { // test 10 leading bits netmask = 0xFFFF0000; } else if (!(ip & 0x20000000)) { // test 110 leading bits netmask = 0xFFFFFF00; } return netmask; } class IPv4Widget::Private { public: Private() : model(0,3) { QStandardItem * headerItem = new QStandardItem(i18nc("Header text for IPv4 address", "Address")); model.setHorizontalHeaderItem(0, headerItem); headerItem = new QStandardItem(i18nc("Header text for IPv4 netmask", "Netmask")); model.setHorizontalHeaderItem(1, headerItem); headerItem = new QStandardItem(i18nc("Header text for IPv4 gateway", "Gateway")); model.setHorizontalHeaderItem(2, headerItem); } QStandardItemModel model; }; IPv4Widget::IPv4Widget(const NetworkManager::Setting::Ptr &setting, QWidget* parent, Qt::WindowFlags f): SettingWidget(setting, parent, f), m_ui(new Ui::IPv4Widget), d(new IPv4Widget::Private()) { m_ui->setupUi(this); m_ui->tableViewAddresses->setModel(&d->model); m_ui->tableViewAddresses->horizontalHeader()->setResizeMode(QHeaderView::Interactive); m_ui->tableViewAddresses->horizontalHeader()->setStretchLastSection(true); IpV4Delegate *ipDelegate = new IpV4Delegate(this); m_ui->tableViewAddresses->setItemDelegateForColumn(0, ipDelegate); m_ui->tableViewAddresses->setItemDelegateForColumn(1, ipDelegate); m_ui->tableViewAddresses->setItemDelegateForColumn(2, ipDelegate); connect(m_ui->btnAdd, &QPushButton::clicked, this, &IPv4Widget::slotAddIPAddress); connect(m_ui->btnRemove, &QPushButton::clicked, this, &IPv4Widget::slotRemoveIPAddress); connect(m_ui->dnsMorePushButton, &QPushButton::clicked, this, &IPv4Widget::slotDnsServers); connect(m_ui->dnsSearchMorePushButton, &QPushButton::clicked, this, &IPv4Widget::slotDnsDomains); connect(m_ui->tableViewAddresses->selectionModel(), &QItemSelectionModel::selectionChanged, this, &IPv4Widget::selectionChanged); connect(&d->model, &QStandardItemModel::itemChanged, this, &IPv4Widget::tableViewItemChanged); if (setting) { loadConfig(setting); } - connect(m_ui->method, static_cast(&KComboBox::currentIndexChanged), this, &IPv4Widget::slotModeComboChanged); + connect(m_ui->method, QOverload::of(&KComboBox::currentIndexChanged), this, &IPv4Widget::slotModeComboChanged); slotModeComboChanged(m_ui->method->currentIndex()); connect(m_ui->btnRoutes, &QPushButton::clicked, this, &IPv4Widget::slotRoutesDialog); // Connect for setting check watchChangedSetting(); // Connect for validity check connect(m_ui->dns, &KLineEdit::textChanged, this, &IPv4Widget::slotWidgetChanged); - connect(m_ui->method, static_cast(&KComboBox::currentIndexChanged), this, &IPv4Widget::slotWidgetChanged); + connect(m_ui->method, QOverload::of(&KComboBox::currentIndexChanged), this, &IPv4Widget::slotWidgetChanged); connect(&d->model, &QStandardItemModel::dataChanged, this, &IPv4Widget::slotWidgetChanged); connect(&d->model, &QStandardItemModel::rowsRemoved, this, &IPv4Widget::slotWidgetChanged); KAcceleratorManager::manage(this); } IPv4Widget::~IPv4Widget() { delete d; delete m_ui; } void IPv4Widget::loadConfig(const NetworkManager::Setting::Ptr &setting) { NetworkManager::Ipv4Setting::Ptr ipv4Setting = setting.staticCast(); m_tmpIpv4Setting.setRoutes(ipv4Setting->routes()); m_tmpIpv4Setting.setNeverDefault(ipv4Setting->neverDefault()); m_tmpIpv4Setting.setIgnoreAutoRoutes(ipv4Setting->ignoreAutoRoutes()); // method switch (ipv4Setting->method()) { case NetworkManager::Ipv4Setting::Automatic: if (ipv4Setting->ignoreAutoDns()) { m_ui->method->setCurrentIndex(AutomaticOnlyIP); } else { m_ui->method->setCurrentIndex(Automatic); } break; case NetworkManager::Ipv4Setting::Manual: m_ui->method->setCurrentIndex(Manual); break; case NetworkManager::Ipv4Setting::LinkLocal: m_ui->method->setCurrentIndex(LinkLocal); break; case NetworkManager::Ipv4Setting::Shared: m_ui->method->setCurrentIndex(Shared); break; case NetworkManager::Ipv4Setting::Disabled: m_ui->method->setCurrentIndex(Disabled); break; } // dns QStringList tmp; Q_FOREACH (const QHostAddress & addr, ipv4Setting->dns()) { tmp.append(addr.toString()); } m_ui->dns->setText(tmp.join(",")); m_ui->dnsSearch->setText(ipv4Setting->dnsSearch().join(",")); m_ui->dhcpClientId->setText(ipv4Setting->dhcpClientId()); // addresses Q_FOREACH (const NetworkManager::IpAddress &addr, ipv4Setting->addresses()) { QList item; item << new QStandardItem(addr.ip().toString()) << new QStandardItem(addr.netmask().toString()) << new QStandardItem(addr.gateway().toString()); d->model.appendRow(item); } // may-fail m_ui->ipv4RequiredCB->setChecked(!ipv4Setting->mayFail()); } QVariantMap IPv4Widget::setting() const { NetworkManager::Ipv4Setting ipv4Setting; ipv4Setting.setRoutes(m_tmpIpv4Setting.routes()); ipv4Setting.setNeverDefault(m_tmpIpv4Setting.neverDefault()); ipv4Setting.setIgnoreAutoRoutes(m_tmpIpv4Setting.ignoreAutoRoutes()); // method switch ((MethodIndex)m_ui->method->currentIndex()) { case Automatic: ipv4Setting.setMethod(NetworkManager::Ipv4Setting::Automatic); break; case IPv4Widget::AutomaticOnlyIP: ipv4Setting.setMethod(NetworkManager::Ipv4Setting::Automatic); ipv4Setting.setIgnoreAutoDns(true); break; case Manual: ipv4Setting.setMethod(NetworkManager::Ipv4Setting::Manual); break; case LinkLocal: ipv4Setting.setMethod(NetworkManager::Ipv4Setting::LinkLocal); break; case Shared: ipv4Setting.setMethod(NetworkManager::Ipv4Setting::Shared); break; case Disabled: ipv4Setting.setMethod(NetworkManager::Ipv4Setting::Disabled); break; } // dns if (m_ui->dns->isEnabled() && !m_ui->dns->text().isEmpty()) { QStringList tmp = m_ui->dns->text().split(','); QList tmpAddrList; Q_FOREACH (const QString & str, tmp) { QHostAddress addr(str); if (!addr.isNull()) tmpAddrList.append(addr); } ipv4Setting.setDns(tmpAddrList); } if (m_ui->dnsSearch->isEnabled() && !m_ui->dnsSearch->text().isEmpty()) { ipv4Setting.setDnsSearch(m_ui->dnsSearch->text().split(',')); } // dhcp id if (m_ui->dhcpClientId->isEnabled() && !m_ui->dhcpClientId->text().isEmpty()) { ipv4Setting.setDhcpClientId(m_ui->dhcpClientId->text()); } // addresses if (m_ui->tableViewAddresses->isEnabled()) { QList list; for (int i = 0, rowCount = d->model.rowCount(); i < rowCount; i++) { NetworkManager::IpAddress address; address.setIp(QHostAddress(d->model.item(i, 0)->text())); address.setNetmask(QHostAddress(d->model.item(i, 1)->text())); address.setGateway(QHostAddress(d->model.item(i, 2)->text())); list << address; } if (!list.isEmpty()) { ipv4Setting.setAddresses(list); } } // may-fail if (m_ui->ipv4RequiredCB->isEnabled()) { ipv4Setting.setMayFail(!m_ui->ipv4RequiredCB->isChecked()); } return ipv4Setting.toMap(); } void IPv4Widget::slotModeComboChanged(int index) { if (index == Automatic) { // Automatic m_ui->dnsLabel->setText(i18n("Other DNS Servers:")); m_ui->dns->setEnabled(true); m_ui->dnsMorePushButton->setEnabled(true); m_ui->dnsSearch->setEnabled(true); m_ui->dnsSearchMorePushButton->setEnabled(true); m_ui->dhcpClientId->setEnabled(true); m_ui->ipv4RequiredCB->setEnabled(true); m_ui->btnRoutes->setEnabled(true); m_ui->tableViewAddresses->setEnabled(false); m_ui->btnAdd->setEnabled(false); m_ui->btnRemove->setEnabled(false); } else if (index == AutomaticOnlyIP) { m_ui->dnsLabel->setText(i18n("DNS Servers:")); m_ui->dns->setEnabled(true); m_ui->dnsMorePushButton->setEnabled(true); m_ui->dnsSearch->setEnabled(true); m_ui->dnsSearchMorePushButton->setEnabled(true); m_ui->dhcpClientId->setEnabled(true); m_ui->ipv4RequiredCB->setEnabled(true); m_ui->btnRoutes->setEnabled(true); m_ui->tableViewAddresses->setEnabled(false); m_ui->btnAdd->setEnabled(false); m_ui->btnRemove->setEnabled(false); } else if (index == Manual) { // Manual m_ui->dnsLabel->setText(i18n("DNS Servers:")); m_ui->dns->setEnabled(true); m_ui->dnsMorePushButton->setEnabled(true); m_ui->dnsSearch->setEnabled(true); m_ui->dnsSearchMorePushButton->setEnabled(true); m_ui->dhcpClientId->setEnabled(false); m_ui->ipv4RequiredCB->setEnabled(true); m_ui->btnRoutes->setEnabled(true); m_ui->tableViewAddresses->setEnabled(true); m_ui->btnAdd->setEnabled(true); m_ui->btnRemove->setEnabled(true); } else if (index == LinkLocal || index == Shared) { // Link-local or Shared m_ui->dnsLabel->setText(i18n("DNS Servers:")); m_ui->dns->setEnabled(false); m_ui->dnsMorePushButton->setEnabled(false); m_ui->dnsSearch->setEnabled(false); m_ui->dnsSearchMorePushButton->setEnabled(false); m_ui->dhcpClientId->setEnabled(false); m_ui->ipv4RequiredCB->setEnabled(true); m_ui->btnRoutes->setEnabled(false); m_ui->tableViewAddresses->setEnabled(false); m_ui->btnAdd->setEnabled(false); m_ui->btnRemove->setEnabled(false); } else if (index == Disabled) { // Disabled m_ui->dnsLabel->setText(i18n("DNS Servers:")); m_ui->dns->setEnabled(false); m_ui->dnsMorePushButton->setEnabled(false); m_ui->dnsSearch->setEnabled(false); m_ui->dnsSearchMorePushButton->setEnabled(false); m_ui->dhcpClientId->setEnabled(false); m_ui->ipv4RequiredCB->setEnabled(false); m_ui->btnRoutes->setEnabled(false); m_ui->tableViewAddresses->setEnabled(false); m_ui->btnAdd->setEnabled(false); m_ui->btnRemove->setEnabled(false); } } void IPv4Widget::slotAddIPAddress() { QList item; item << new QStandardItem << new QStandardItem << new QStandardItem; d->model.appendRow(item); const int rowCount = d->model.rowCount(); if (rowCount > 0) { m_ui->tableViewAddresses->selectRow(rowCount - 1); QItemSelectionModel * selectionModel = m_ui->tableViewAddresses->selectionModel(); QModelIndexList list = selectionModel->selectedIndexes(); if (!list.isEmpty()) { // QTableView is configured to select only rows. // So, list[0] - IP address. m_ui->tableViewAddresses->edit(list[0]); } } } void IPv4Widget::slotRemoveIPAddress() { QItemSelectionModel * selectionModel = m_ui->tableViewAddresses->selectionModel(); if (selectionModel->hasSelection()) { QModelIndexList indexes = selectionModel->selectedIndexes(); d->model.takeRow(indexes[0].row()); } m_ui->btnRemove->setEnabled(m_ui->tableViewAddresses->selectionModel()->hasSelection()); } void IPv4Widget::selectionChanged(const QItemSelection & selected) { m_ui->btnRemove->setEnabled(!selected.isEmpty()); } void IPv4Widget::tableViewItemChanged(QStandardItem *item) { if (item->text().isEmpty()) { return; } const int column = item->column(); if (column == 0) { // ip int row = item->row(); QStandardItem *netmaskItem = d->model.item(row, column + 1); // netmask if (netmaskItem && netmaskItem->text().isEmpty()) { QHostAddress addr(item->text()); const quint32 netmask = suggestNetmask(addr.toIPv4Address()); if (netmask) { QHostAddress v(netmask); netmaskItem->setText(v.toString()); } } } } void IPv4Widget::slotRoutesDialog() { QPointer dlg = new IpV4RoutesWidget(this); dlg->setRoutes(m_tmpIpv4Setting.routes()); dlg->setNeverDefault(m_tmpIpv4Setting.neverDefault()); if (m_ui->method->currentIndex() == 2) { // manual dlg->setIgnoreAutoRoutesCheckboxEnabled(false); } else { dlg->setIgnoreAutoRoutes(m_tmpIpv4Setting.ignoreAutoRoutes()); } connect(dlg.data(), &QDialog::accepted, [dlg, this] () { m_tmpIpv4Setting.setRoutes(dlg->routes()); m_tmpIpv4Setting.setNeverDefault(dlg->neverDefault()); m_tmpIpv4Setting.setIgnoreAutoRoutes(dlg->ignoreautoroutes()); }); connect(dlg.data(), &QDialog::finished, [dlg] () { if (dlg) { dlg->deleteLater(); } }); dlg->setModal(true); dlg->show(); } void IPv4Widget::slotDnsServers() { QPointer dialog = new QDialog(this); dialog->setWindowTitle(i18n("Edit DNS servers")); dialog->setLayout(new QVBoxLayout); QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel, dialog); connect(buttons, &QDialogButtonBox::accepted, dialog.data(), &QDialog::accept); connect(buttons, &QDialogButtonBox::rejected, dialog.data(), &QDialog::reject); KEditListWidget * listWidget = new KEditListWidget(dialog); listWidget->setItems(m_ui->dns->text().split(',').replaceInStrings(" ", "")); listWidget->lineEdit()->setFocus(Qt::OtherFocusReason); dialog->layout()->addWidget(listWidget); dialog->layout()->addWidget(buttons); connect(dialog.data(), &QDialog::accepted, [listWidget, this] () { QString text = listWidget->items().join(","); if (text.endsWith(',')) { text.chop(1); } m_ui->dns->setText(text); }); connect(dialog.data(), &QDialog::finished, [dialog] () { if (dialog) { dialog->deleteLater(); } }); dialog->setModal(true); dialog->show(); } void IPv4Widget::slotDnsDomains() { QPointer dialog = new QDialog(this); dialog->setWindowTitle(i18n("Edit DNS search domains")); dialog->setLayout(new QVBoxLayout); QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel, dialog); connect(buttons, &QDialogButtonBox::accepted, dialog.data(), &QDialog::accept); connect(buttons, &QDialogButtonBox::rejected, dialog.data(), &QDialog::reject); KEditListWidget * listWidget = new KEditListWidget(dialog); listWidget->setItems(m_ui->dnsSearch->text().split(',').replaceInStrings(" ", "")); listWidget->lineEdit()->setFocus(Qt::OtherFocusReason); dialog->layout()->addWidget(listWidget); dialog->layout()->addWidget(buttons); connect(dialog.data(), &QDialog::accepted, [listWidget, this] () { QString text = listWidget->items().join(","); if (text.endsWith(',')) { text.chop(1); } m_ui->dnsSearch->setText(text); }); connect(dialog.data(), &QDialog::finished, [dialog] () { if (dialog) { dialog->deleteLater(); } }); dialog->setModal(true); dialog->show(); } bool IPv4Widget::isValid() const { if (m_ui->method->currentIndex() == Manual) { if (!d->model.rowCount()) { return false; } for (int i = 0, rowCount = d->model.rowCount(); i < rowCount; i++) { QHostAddress ip = QHostAddress(d->model.item(i, 0)->text()); QHostAddress netmask = QHostAddress(d->model.item(i, 1)->text()); QHostAddress gateway = QHostAddress(d->model.item(i, 2)->text()); if (ip.isNull() || netmask.isNull() || (gateway.isNull() && !d->model.item(i, 2)->text().isEmpty())) { return false; } } } if (!m_ui->dns->text().isEmpty() && (m_ui->method->currentIndex() == Automatic || m_ui->method->currentIndex() == Manual || m_ui->method->currentIndex() == AutomaticOnlyIP)) { const QStringList tmp = m_ui->dns->text().split(','); Q_FOREACH (const QString & str, tmp) { QHostAddress addr(str); if (addr.isNull()) { return false; } } } return true; } diff --git a/libs/editor/settings/ipv4widget.h b/libs/editor/settings/ipv4widget.h index 5dd70fee..b88771ed 100644 --- a/libs/editor/settings/ipv4widget.h +++ b/libs/editor/settings/ipv4widget.h @@ -1,71 +1,71 @@ /* Copyright (c) 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_IPV4_WIDGET_H #define PLASMA_NM_IPV4_WIDGET_H #include #include #include "settingwidget.h" #include "ipv4routeswidget.h" namespace Ui { class IPv4Widget; } class Q_DECL_EXPORT IPv4Widget : public SettingWidget { Q_OBJECT public: enum MethodIndex { Automatic = 0, AutomaticOnlyIP, LinkLocal, Manual, Shared, Disabled }; - explicit IPv4Widget(const NetworkManager::Setting::Ptr &setting = NetworkManager::Setting::Ptr(), QWidget* parent = 0, Qt::WindowFlags f = 0); - virtual ~IPv4Widget(); + explicit IPv4Widget(const NetworkManager::Setting::Ptr &setting = NetworkManager::Setting::Ptr(), QWidget* parent = nullptr, Qt::WindowFlags f = {}); + ~IPv4Widget() override; - void loadConfig(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; - QVariantMap setting() const Q_DECL_OVERRIDE; + QVariantMap setting() const override; - virtual bool isValid() const Q_DECL_OVERRIDE; + bool isValid() const override; private Q_SLOTS: void slotModeComboChanged(int index); void slotRoutesDialog(); void slotDnsServers(); void slotDnsDomains(); void slotAddIPAddress(); void slotRemoveIPAddress(); void selectionChanged(const QItemSelection & selected); void tableViewItemChanged(QStandardItem * item); private: Ui::IPv4Widget * m_ui; NetworkManager::Ipv4Setting m_tmpIpv4Setting; class Private; Private * const d; }; #endif // PLASMA_NM_IPV4_WIDGET_H diff --git a/libs/editor/settings/ipv6widget.cpp b/libs/editor/settings/ipv6widget.cpp index c871374d..8d01aedd 100644 --- a/libs/editor/settings/ipv6widget.cpp +++ b/libs/editor/settings/ipv6widget.cpp @@ -1,491 +1,491 @@ /* Copyright (c) 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "ipv6widget.h" #include "ui_ipv6.h" #include "ipv6delegate.h" #include "intdelegate.h" #include #include #include #include #include #include #include quint32 suggestNetmask(Q_IPV6ADDR ip) { Q_UNUSED(ip); /* TODO: find out common IPv6-netmasks and make a complete function */ quint32 netmask = 64; return netmask; } class IPv6Widget::Private { public: Private() : model(0,3) { QStandardItem * headerItem = new QStandardItem(i18nc("Header text for IPv6 address", "Address")); model.setHorizontalHeaderItem(0, headerItem); headerItem = new QStandardItem(i18nc("Header text for IPv6 prefix", "Prefix")); model.setHorizontalHeaderItem(1, headerItem); headerItem = new QStandardItem(i18nc("Header text for IPv6 gateway", "Gateway")); model.setHorizontalHeaderItem(2, headerItem); } QStandardItemModel model; }; IPv6Widget::IPv6Widget(const NetworkManager::Setting::Ptr &setting, QWidget* parent, Qt::WindowFlags f): SettingWidget(setting, parent, f), m_ui(new Ui::IPv6Widget), d(new IPv6Widget::Private()) { m_ui->setupUi(this); m_ui->tableViewAddresses->setModel(&d->model); m_ui->tableViewAddresses->horizontalHeader()->setResizeMode(QHeaderView::Interactive); m_ui->tableViewAddresses->horizontalHeader()->setStretchLastSection(true); IpV6Delegate *ipDelegate = new IpV6Delegate(this); IntDelegate *prefixDelegate = new IntDelegate (0, 128, this); m_ui->tableViewAddresses->setItemDelegateForColumn(0, ipDelegate); m_ui->tableViewAddresses->setItemDelegateForColumn(1, prefixDelegate); m_ui->tableViewAddresses->setItemDelegateForColumn(2, ipDelegate); connect(m_ui->btnAdd, &QPushButton::clicked, this, &IPv6Widget::slotAddIPAddress); connect(m_ui->btnRemove, &QPushButton::clicked, this, &IPv6Widget::slotRemoveIPAddress); connect(m_ui->dnsMorePushButton, &QPushButton::clicked, this, &IPv6Widget::slotDnsServers); connect(m_ui->dnsSearchMorePushButton, &QPushButton::clicked, this, &IPv6Widget::slotDnsDomains); connect(m_ui->tableViewAddresses->selectionModel(), &QItemSelectionModel::selectionChanged, this, &IPv6Widget::selectionChanged); connect(&d->model, &QStandardItemModel::itemChanged, this, &IPv6Widget::tableViewItemChanged); if (setting) { loadConfig(setting); } - connect(m_ui->method, static_cast(&KComboBox::currentIndexChanged), this, &IPv6Widget::slotModeComboChanged); + connect(m_ui->method, QOverload::of(&KComboBox::currentIndexChanged), this, &IPv6Widget::slotModeComboChanged); slotModeComboChanged(m_ui->method->currentIndex()); connect(m_ui->btnRoutes, &QPushButton::clicked, this, &IPv6Widget::slotRoutesDialog); // Connect for setting check watchChangedSetting(); // Connect for validity check connect(m_ui->dns, &KLineEdit::textChanged, this, &IPv6Widget::slotWidgetChanged); - connect(m_ui->method, static_cast(&KComboBox::currentIndexChanged), this, &IPv6Widget::slotWidgetChanged); + connect(m_ui->method, QOverload::of(&KComboBox::currentIndexChanged), this, &IPv6Widget::slotWidgetChanged); connect(&d->model, &QStandardItemModel::dataChanged, this, &IPv6Widget::slotWidgetChanged); connect(&d->model, &QStandardItemModel::rowsRemoved, this, &IPv6Widget::slotWidgetChanged); KAcceleratorManager::manage(this); } IPv6Widget::~IPv6Widget() { delete d; delete m_ui; } void IPv6Widget::loadConfig(const NetworkManager::Setting::Ptr &setting) { NetworkManager::Ipv6Setting::Ptr ipv6Setting = setting.staticCast(); m_tmpIpv6Setting.setRoutes(ipv6Setting->routes()); m_tmpIpv6Setting.setNeverDefault(ipv6Setting->neverDefault()); m_tmpIpv6Setting.setIgnoreAutoRoutes(ipv6Setting->ignoreAutoRoutes()); // method switch (ipv6Setting->method()) { case NetworkManager::Ipv6Setting::Automatic: if (ipv6Setting->ignoreAutoDns()) { m_ui->method->setCurrentIndex(AutomaticOnlyIP); } else { m_ui->method->setCurrentIndex(Automatic); } break; case NetworkManager::Ipv6Setting::Dhcp: m_ui->method->setCurrentIndex(AutomaticOnlyDHCP); break; case NetworkManager::Ipv6Setting::Manual: m_ui->method->setCurrentIndex(Manual); break; case NetworkManager::Ipv6Setting::LinkLocal: m_ui->method->setCurrentIndex(LinkLocal); break; case NetworkManager::Ipv6Setting::Ignored: m_ui->method->setCurrentIndex(Disabled); break; } // dns QStringList tmp; Q_FOREACH (const QHostAddress & addr, ipv6Setting->dns()) { tmp.append(addr.toString()); } m_ui->dns->setText(tmp.join(",")); m_ui->dnsSearch->setText(ipv6Setting->dnsSearch().join(",")); // addresses Q_FOREACH (const NetworkManager::IpAddress &address, ipv6Setting->addresses()) { QList item; item << new QStandardItem(address.ip().toString()) << new QStandardItem(QString::number(address.prefixLength(),10)) << new QStandardItem(address.gateway().toString()); d->model.appendRow(item); } // may-fail m_ui->ipv6RequiredCB->setChecked(!ipv6Setting->mayFail()); // privacy if (ipv6Setting->privacy() != NetworkManager::Ipv6Setting::Unknown) { m_ui->privacyCombo->setCurrentIndex(static_cast(ipv6Setting->privacy()) + 1); } } QVariantMap IPv6Widget::setting() const { NetworkManager::Ipv6Setting ipv6Setting; ipv6Setting.setRoutes(m_tmpIpv6Setting.routes()); ipv6Setting.setNeverDefault(m_tmpIpv6Setting.neverDefault()); ipv6Setting.setIgnoreAutoRoutes(m_tmpIpv6Setting.ignoreAutoRoutes()); // method switch ((MethodIndex)m_ui->method->currentIndex()) { case Automatic: ipv6Setting.setMethod(NetworkManager::Ipv6Setting::Automatic); break; case AutomaticOnlyIP: ipv6Setting.setMethod(NetworkManager::Ipv6Setting::Automatic); ipv6Setting.setIgnoreAutoDns(true); break; case IPv6Widget::AutomaticOnlyDHCP: ipv6Setting.setMethod(NetworkManager::Ipv6Setting::Dhcp); break; case Manual: ipv6Setting.setMethod(NetworkManager::Ipv6Setting::Manual); break; case LinkLocal: ipv6Setting.setMethod(NetworkManager::Ipv6Setting::LinkLocal); break; case Disabled: ipv6Setting.setMethod(NetworkManager::Ipv6Setting::Ignored); break; } // dns if (m_ui->dns->isEnabled() && !m_ui->dns->text().isEmpty()) { QStringList tmp = m_ui->dns->text().split(','); QList tmpAddrList; Q_FOREACH (const QString & str, tmp) { QHostAddress addr(str); if (!addr.isNull()) tmpAddrList.append(addr); } ipv6Setting.setDns(tmpAddrList); } if (m_ui->dnsSearch->isEnabled() && !m_ui->dnsSearch->text().isEmpty()) { ipv6Setting.setDnsSearch(m_ui->dnsSearch->text().split(',')); } // addresses if (m_ui->tableViewAddresses->isEnabled()) { QList list; for (int i = 0, rowCount = d->model.rowCount(); i < rowCount; i++) { NetworkManager::IpAddress address; address.setIp(QHostAddress(d->model.item(i, 0)->text())); address.setPrefixLength(d->model.item(i, 1)->text().toInt()); address.setGateway(QHostAddress(d->model.item(i, 2)->text())); list << address; } ipv6Setting.setAddresses(list); } // may-fail if (m_ui->ipv6RequiredCB->isEnabled()) { ipv6Setting.setMayFail(!m_ui->ipv6RequiredCB->isChecked()); } // privacy if (m_ui->privacyCombo->isEnabled() && m_ui->privacyCombo->currentIndex()) { ipv6Setting.setPrivacy(static_cast(m_ui->privacyCombo->currentIndex() - 1)); } return ipv6Setting.toMap(); } void IPv6Widget::slotModeComboChanged(int index) { if (index == Automatic) { // Automatic m_ui->dnsLabel->setText(i18n("Other DNS Servers:")); m_ui->dns->setEnabled(true); m_ui->dnsMorePushButton->setEnabled(true); m_ui->dnsSearch->setEnabled(true); m_ui->dnsSearchMorePushButton->setEnabled(true); m_ui->ipv6RequiredCB->setEnabled(true); m_ui->privacyCombo->setEnabled(true); m_ui->btnRoutes->setEnabled(true); m_ui->tableViewAddresses->setEnabled(false); m_ui->btnAdd->setEnabled(false); m_ui->btnRemove->setEnabled(false); } else if (index == AutomaticOnlyIP) { m_ui->dnsLabel->setText(i18n("DNS Servers:")); m_ui->dns->setEnabled(true); m_ui->dnsMorePushButton->setEnabled(true); m_ui->dnsSearch->setEnabled(true); m_ui->dnsSearchMorePushButton->setEnabled(true); m_ui->ipv6RequiredCB->setEnabled(true); m_ui->privacyCombo->setEnabled(true); m_ui->btnRoutes->setEnabled(true); m_ui->tableViewAddresses->setEnabled(false); m_ui->btnAdd->setEnabled(false); m_ui->btnRemove->setEnabled(false); } else if (index == Manual) { // Manual m_ui->dnsLabel->setText(i18n("DNS Servers:")); m_ui->dns->setEnabled(true); m_ui->dnsMorePushButton->setEnabled(true); m_ui->dnsSearch->setEnabled(true); m_ui->dnsSearchMorePushButton->setEnabled(true); m_ui->ipv6RequiredCB->setEnabled(true); m_ui->privacyCombo->setEnabled(true); m_ui->btnRoutes->setEnabled(true); m_ui->tableViewAddresses->setEnabled(true); m_ui->btnAdd->setEnabled(true); m_ui->btnRemove->setEnabled(true); } else if (index == AutomaticOnlyDHCP || index == LinkLocal) { // Link-local or DHCP m_ui->dnsLabel->setText(i18n("DNS Servers:")); m_ui->dns->setEnabled(false); m_ui->dnsMorePushButton->setEnabled(false); m_ui->dnsSearch->setEnabled(false); m_ui->dnsSearchMorePushButton->setEnabled(false); m_ui->ipv6RequiredCB->setEnabled(true); m_ui->privacyCombo->setEnabled(true); m_ui->btnRoutes->setEnabled(false); m_ui->tableViewAddresses->setEnabled(false); m_ui->btnAdd->setEnabled(false); m_ui->btnRemove->setEnabled(false); } else if (index == Disabled) { // Ignored m_ui->dnsLabel->setText(i18n("DNS Servers:")); m_ui->dns->setEnabled(false); m_ui->dnsMorePushButton->setEnabled(false); m_ui->dnsSearch->setEnabled(false); m_ui->dnsSearchMorePushButton->setEnabled(false); m_ui->ipv6RequiredCB->setEnabled(false); m_ui->privacyCombo->setEnabled(false); m_ui->btnRoutes->setEnabled(false); m_ui->tableViewAddresses->setEnabled(false); m_ui->btnAdd->setEnabled(false); m_ui->btnRemove->setEnabled(false); } } void IPv6Widget::slotAddIPAddress() { QList item; item << new QStandardItem << new QStandardItem << new QStandardItem; d->model.appendRow(item); const int rowCount = d->model.rowCount(); if (rowCount > 0) { m_ui->tableViewAddresses->selectRow(rowCount - 1); QItemSelectionModel * selectionModel = m_ui->tableViewAddresses->selectionModel(); QModelIndexList list = selectionModel->selectedIndexes(); if (list.size()) { // QTableView is configured to select only rows. // So, list[0] - IP address. m_ui->tableViewAddresses->edit(list[0]); } } } void IPv6Widget::slotRemoveIPAddress() { QItemSelectionModel * selectionModel = m_ui->tableViewAddresses->selectionModel(); if (selectionModel->hasSelection()) { QModelIndexList indexes = selectionModel->selectedIndexes(); d->model.takeRow(indexes[0].row()); } m_ui->btnRemove->setEnabled(m_ui->tableViewAddresses->selectionModel()->hasSelection()); } void IPv6Widget::selectionChanged(const QItemSelection & selected) { m_ui->btnRemove->setEnabled(!selected.isEmpty()); } void IPv6Widget::tableViewItemChanged(QStandardItem *item) { if (item->text().isEmpty()) { return; } const int column = item->column(); if (column == 0) { // ip int row = item->row(); QStandardItem *netmaskItem = d->model.item(row, column + 1); // netmask if (netmaskItem && netmaskItem->text().isEmpty()) { QHostAddress addr(item->text()); const quint32 netmask = suggestNetmask(addr.toIPv6Address()); if (netmask) { netmaskItem->setText(QString::number(netmask,10)); } } } } void IPv6Widget::slotRoutesDialog() { QPointer dlg = new IpV6RoutesWidget(this); dlg->setRoutes(m_tmpIpv6Setting.routes()); dlg->setNeverDefault(m_tmpIpv6Setting.neverDefault()); if (m_ui->method->currentIndex() == 3) { // manual dlg->setIgnoreAutoRoutesCheckboxEnabled(false); } else { dlg->setIgnoreAutoRoutes(m_tmpIpv6Setting.ignoreAutoRoutes()); } connect(dlg.data(), &QDialog::accepted, [dlg, this] () { m_tmpIpv6Setting.setRoutes(dlg->routes()); m_tmpIpv6Setting.setNeverDefault(dlg->neverDefault()); m_tmpIpv6Setting.setIgnoreAutoRoutes(dlg->ignoreautoroutes()); }); connect(dlg.data(), &QDialog::finished, [dlg] () { if (dlg) { dlg->deleteLater(); } }); dlg->setModal(true); dlg->show(); } void IPv6Widget::slotDnsServers() { QPointer dialog = new QDialog(this); dialog->setWindowTitle(i18n("Edit DNS servers")); dialog->setLayout(new QVBoxLayout); QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel, dialog); connect(buttons, &QDialogButtonBox::accepted, dialog.data(), &QDialog::accept); connect(buttons, &QDialogButtonBox::rejected, dialog.data(), &QDialog::reject); KEditListWidget * listWidget = new KEditListWidget(dialog); listWidget->setItems(m_ui->dns->text().split(',').replaceInStrings(" ", "")); listWidget->lineEdit()->setFocus(Qt::OtherFocusReason); dialog->layout()->addWidget(listWidget); dialog->layout()->addWidget(buttons); connect(dialog.data(), &QDialog::accepted, [listWidget, this] () { QString text = listWidget->items().join(","); if (text.endsWith(',')) { text.chop(1); } m_ui->dns->setText(text); }); connect(dialog.data(), &QDialog::finished, [dialog] () { if (dialog) { dialog->deleteLater(); } }); dialog->setModal(true); dialog->show(); } void IPv6Widget::slotDnsDomains() { QPointer dialog = new QDialog(this); dialog->setWindowTitle(i18n("Edit DNS search domains")); dialog->setLayout(new QVBoxLayout); QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel, dialog); connect(buttons, &QDialogButtonBox::accepted, dialog.data(), &QDialog::accept); connect(buttons, &QDialogButtonBox::rejected, dialog.data(), &QDialog::reject); KEditListWidget * listWidget = new KEditListWidget(dialog); listWidget->setItems(m_ui->dnsSearch->text().split(',').replaceInStrings(" ", "")); listWidget->lineEdit()->setFocus(Qt::OtherFocusReason); dialog->layout()->addWidget(listWidget); dialog->layout()->addWidget(buttons); connect(dialog.data(), &QDialog::accepted, [listWidget, this] () { QString text = listWidget->items().join(","); if (text.endsWith(',')) { text.chop(1); } m_ui->dnsSearch->setText(text); }); connect(dialog.data(), &QDialog::finished, [dialog] () { if (dialog) { dialog->deleteLater(); } }); dialog->setModal(true); dialog->show(); } bool IPv6Widget::isValid() const { if (m_ui->method->currentIndex() == Manual) { if (!d->model.rowCount()) { return false; } for (int i = 0, rowCount = d->model.rowCount(); i < rowCount; i++) { QHostAddress ip = QHostAddress(d->model.item(i, 0)->text()); const int prefix = d->model.item(i,1)->text().toInt(); QHostAddress gateway = QHostAddress(d->model.item(i, 2)->text()); if (ip.isNull() || !(prefix >= 1 && prefix <= 128) || (gateway.isNull() && !d->model.item(i, 2)->text().isEmpty())) { return false; } } } if (!m_ui->dns->text().isEmpty() && (m_ui->method->currentIndex() == Automatic || m_ui->method->currentIndex() == Manual || m_ui->method->currentIndex() == AutomaticOnlyIP)) { const QStringList tmp = m_ui->dns->text().split(','); Q_FOREACH (const QString & str, tmp) { QHostAddress addr(str); if (addr.isNull()) { return false; } } } return true; } diff --git a/libs/editor/settings/ipv6widget.h b/libs/editor/settings/ipv6widget.h index cb851bb0..4dc80ba2 100644 --- a/libs/editor/settings/ipv6widget.h +++ b/libs/editor/settings/ipv6widget.h @@ -1,71 +1,71 @@ /* Copyright (c) 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_IPV6_WIDGET_H #define PLASMA_NM_IPV6_WIDGET_H #include #include #include "settingwidget.h" #include "ipv6routeswidget.h" namespace Ui { class IPv6Widget; } class Q_DECL_EXPORT IPv6Widget : public SettingWidget { Q_OBJECT public: enum MethodIndex { Automatic = 0, AutomaticOnlyIP, AutomaticOnlyDHCP, LinkLocal, Manual, Disabled }; - explicit IPv6Widget(const NetworkManager::Setting::Ptr &setting = NetworkManager::Setting::Ptr(), QWidget* parent = 0, Qt::WindowFlags f = 0); - virtual ~IPv6Widget(); + explicit IPv6Widget(const NetworkManager::Setting::Ptr &setting = NetworkManager::Setting::Ptr(), QWidget* parent = nullptr, Qt::WindowFlags f = {}); + ~IPv6Widget() override; - void loadConfig(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; - QVariantMap setting() const Q_DECL_OVERRIDE; + QVariantMap setting() const override; - virtual bool isValid() const Q_DECL_OVERRIDE; + bool isValid() const override; private Q_SLOTS: void slotModeComboChanged(int index); void slotRoutesDialog(); void slotDnsServers(); void slotDnsDomains(); void slotAddIPAddress(); void slotRemoveIPAddress(); void selectionChanged(const QItemSelection & selected); void tableViewItemChanged(QStandardItem * item); private: Ui::IPv6Widget * m_ui; NetworkManager::Ipv6Setting m_tmpIpv6Setting; class Private; Private * const d; }; #endif // PLASMA_NM_IPV4_WIDGET_H diff --git a/libs/editor/settings/pppoewidget.h b/libs/editor/settings/pppoewidget.h index 42121ac1..a3ee7ba6 100644 --- a/libs/editor/settings/pppoewidget.h +++ b/libs/editor/settings/pppoewidget.h @@ -1,53 +1,53 @@ /* Copyright 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_PPPOE_WIDGET_H #define PLASMA_NM_PPPOE_WIDGET_H #include #include #include "settingwidget.h" namespace Ui { class PppoeWidget; } class Q_DECL_EXPORT PppoeWidget : public SettingWidget { Q_OBJECT public: - explicit PppoeWidget(const NetworkManager::Setting::Ptr &setting = NetworkManager::Setting::Ptr(), QWidget* parent = 0, Qt::WindowFlags f = 0); - virtual ~PppoeWidget(); + explicit PppoeWidget(const NetworkManager::Setting::Ptr &setting = NetworkManager::Setting::Ptr(), QWidget* parent = nullptr, Qt::WindowFlags f = {}); + ~PppoeWidget() override; - void loadConfig(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; - void loadSecrets(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; + void loadSecrets(const NetworkManager::Setting::Ptr &setting) override; - QVariantMap setting() const Q_DECL_OVERRIDE; + QVariantMap setting() const override; - virtual bool isValid() const Q_DECL_OVERRIDE; + bool isValid() const override; private: Ui::PppoeWidget *m_ui; }; #endif // PLASMA_NM_PPPOE_WIDGET_H diff --git a/libs/editor/settings/pppwidget.h b/libs/editor/settings/pppwidget.h index ea8e5823..bb6e0035 100644 --- a/libs/editor/settings/pppwidget.h +++ b/libs/editor/settings/pppwidget.h @@ -1,50 +1,50 @@ /* Copyright 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_PPP_WIDGET_H #define PLASMA_NM_PPP_WIDGET_H #include #include #include "settingwidget.h" namespace Ui { class PPPWidget; } class Q_DECL_EXPORT PPPWidget : public SettingWidget { Q_OBJECT public: - explicit PPPWidget(const NetworkManager::Setting::Ptr &setting = NetworkManager::Setting::Ptr(), QWidget* parent = 0, Qt::WindowFlags f = 0); - virtual ~PPPWidget(); + explicit PPPWidget(const NetworkManager::Setting::Ptr &setting = NetworkManager::Setting::Ptr(), QWidget* parent = nullptr, Qt::WindowFlags f = {}); + ~PPPWidget() override; - void loadConfig(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; - QVariantMap setting() const Q_DECL_OVERRIDE; + QVariantMap setting() const override; private: Ui::PPPWidget *m_ui; }; #endif // PLASMA_NM_PPP_WIDGET_H diff --git a/libs/editor/settings/security802-1x.cpp b/libs/editor/settings/security802-1x.cpp index 461a38cd..78c7e3b2 100644 --- a/libs/editor/settings/security802-1x.cpp +++ b/libs/editor/settings/security802-1x.cpp @@ -1,638 +1,638 @@ /* Copyright (c) 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "security802-1x.h" #include "ui_802-1x.h" #include "editlistdialog.h" #include "listvalidator.h" #include #include #include Security8021x::Security8021x(const NetworkManager::Setting::Ptr &setting, bool wifiMode, QWidget *parent, Qt::WindowFlags f) : SettingWidget(setting, parent, f) , m_ui(new Ui::Security8021x) { m_setting = setting.staticCast(); m_ui->setupUi(this); m_ui->fastPassword->setPasswordOptionsEnabled(true); m_ui->leapPassword->setPasswordOptionsEnabled(true); m_ui->md5Password->setPasswordOptionsEnabled(true); m_ui->peapPassword->setPasswordOptionsEnabled(true); m_ui->pwdPassword->setPasswordOptionsEnabled(true); m_ui->tlsPrivateKeyPassword->setPasswordOptionsEnabled(true); m_ui->ttlsPassword->setPasswordOptionsEnabled(true); if (wifiMode) { m_ui->auth->removeItem(0); // MD 5 m_ui->stackedWidget->removeWidget(m_ui->md5Page); m_ui->auth->setItemData(0, NetworkManager::Security8021xSetting::EapMethodTls); m_ui->auth->setItemData(1, NetworkManager::Security8021xSetting::EapMethodLeap); m_ui->auth->setItemData(2, NetworkManager::Security8021xSetting::EapMethodPwd); m_ui->auth->setItemData(3, NetworkManager::Security8021xSetting::EapMethodFast); m_ui->auth->setItemData(4, NetworkManager::Security8021xSetting::EapMethodTtls); m_ui->auth->setItemData(5, NetworkManager::Security8021xSetting::EapMethodPeap); } else { m_ui->auth->removeItem(2); // LEAP m_ui->stackedWidget->removeWidget(m_ui->leapPage); m_ui->auth->setItemData(0, NetworkManager::Security8021xSetting::EapMethodMd5); m_ui->auth->setItemData(1, NetworkManager::Security8021xSetting::EapMethodTls); m_ui->auth->setItemData(2, NetworkManager::Security8021xSetting::EapMethodPwd); m_ui->auth->setItemData(3, NetworkManager::Security8021xSetting::EapMethodFast); m_ui->auth->setItemData(4, NetworkManager::Security8021xSetting::EapMethodTtls); m_ui->auth->setItemData(5, NetworkManager::Security8021xSetting::EapMethodPeap); } // Set PEAP authentication as default m_ui->auth->setCurrentIndex(m_ui->auth->findData(NetworkManager::Security8021xSetting::EapMethodPeap)); connect(m_ui->btnTlsAltSubjectMatches, &QPushButton::clicked, this, &Security8021x::altSubjectMatchesButtonClicked); connect(m_ui->btnTlsConnectToServers, &QPushButton::clicked, this, &Security8021x::connectToServersButtonClicked); // Connect for setting check watchChangedSetting(); // Connect for validity check - connect(m_ui->auth, static_cast(&KComboBox::currentIndexChanged), this, &Security8021x::slotWidgetChanged); + connect(m_ui->auth, QOverload::of(&KComboBox::currentIndexChanged), this, &Security8021x::slotWidgetChanged); connect(m_ui->md5UserName, &KLineEdit::textChanged, this, &Security8021x::slotWidgetChanged); connect(m_ui->md5Password, &PasswordField::textChanged, this, &Security8021x::slotWidgetChanged); connect(m_ui->md5Password, &PasswordField::passwordOptionChanged, this, &Security8021x::slotWidgetChanged); connect(m_ui->tlsIdentity, &KLineEdit::textChanged, this, &Security8021x::slotWidgetChanged); connect(m_ui->tlsCACert, &KUrlRequester::textChanged, this, &Security8021x::slotWidgetChanged); connect(m_ui->tlsUserCert, &KUrlRequester::textChanged, this, &Security8021x::slotWidgetChanged); connect(m_ui->tlsPrivateKey, &KUrlRequester::textChanged, this, &Security8021x::slotWidgetChanged); connect(m_ui->tlsPrivateKeyPassword, &PasswordField::textChanged, this, &Security8021x::slotWidgetChanged); connect(m_ui->tlsPrivateKeyPassword, &PasswordField::passwordOptionChanged, this, &Security8021x::slotWidgetChanged); connect(m_ui->leapUsername, &KLineEdit::textChanged, this, &Security8021x::slotWidgetChanged); connect(m_ui->leapPassword, &PasswordField::textChanged, this, &Security8021x::slotWidgetChanged); connect(m_ui->leapPassword, &PasswordField::passwordOptionChanged, this, &Security8021x::slotWidgetChanged); connect(m_ui->fastAllowPacProvisioning, &QCheckBox::stateChanged, this, &Security8021x::slotWidgetChanged); connect(m_ui->pacFile, &KUrlRequester::textChanged, this, &Security8021x::slotWidgetChanged); connect(m_ui->pwdUsername, &KLineEdit::textChanged, this, &Security8021x::slotWidgetChanged); connect(m_ui->pwdPassword, &PasswordField::textChanged, this, &Security8021x::slotWidgetChanged); connect(m_ui->fastUsername, &KLineEdit::textChanged, this, &Security8021x::slotWidgetChanged); connect(m_ui->fastPassword, &PasswordField::textChanged, this, &Security8021x::slotWidgetChanged); connect(m_ui->fastPassword, &PasswordField::passwordOptionChanged, this, &Security8021x::slotWidgetChanged); connect(m_ui->ttlsCACert, &KUrlRequester::textChanged, this, &Security8021x::slotWidgetChanged); connect(m_ui->ttlsUsername, &KLineEdit::textChanged, this, &Security8021x::slotWidgetChanged); connect(m_ui->ttlsPassword, &PasswordField::textChanged, this, &Security8021x::slotWidgetChanged); connect(m_ui->ttlsPassword, &PasswordField::passwordOptionChanged, this, &Security8021x::slotWidgetChanged); connect(m_ui->peapCACert, &KUrlRequester::textChanged, this, &Security8021x::slotWidgetChanged); connect(m_ui->peapUsername, &KLineEdit::textChanged, this, &Security8021x::slotWidgetChanged); connect(m_ui->peapPassword, &PasswordField::textChanged, this, &Security8021x::slotWidgetChanged); connect(m_ui->peapPassword, &PasswordField::passwordOptionChanged, this, &Security8021x::slotWidgetChanged); KAcceleratorManager::manage(this); connect(m_ui->stackedWidget, &QStackedWidget::currentChanged, this, &Security8021x::currentAuthChanged); altSubjectValidator = new QRegExpValidator(QRegExp(QLatin1String("^(DNS:[a-zA-Z0-9_-]+\\.[a-zA-Z0-9_.-]+|EMAIL:[a-zA-Z0-9._-]+@[a-zA-Z0-9_-]+\\.[a-zA-Z0-9_.-]+|URI:[a-zA-Z0-9.+-]+:.+|)$")), this); serversValidator = new QRegExpValidator(QRegExp(QLatin1String("^[a-zA-Z0-9_-]+\\.[a-zA-Z0-9_.-]+$")), this); ListValidator *altSubjectListValidator = new ListValidator(this); altSubjectListValidator->setInnerValidator(altSubjectValidator); m_ui->leTlsSubjectMatch->setValidator(altSubjectListValidator); ListValidator *serverListValidator = new ListValidator(this); serverListValidator->setInnerValidator(serversValidator); m_ui->leTlsConnectToServers->setValidator(serverListValidator); if (setting) { loadConfig(setting); } } Security8021x::~Security8021x() { delete m_ui; } void Security8021x::loadConfig(const NetworkManager::Setting::Ptr &setting) { NetworkManager::Security8021xSetting::Ptr securitySetting = setting.staticCast(); const QList eapMethods = securitySetting->eapMethods(); const NetworkManager::Security8021xSetting::AuthMethod phase2AuthMethod = securitySetting->phase2AuthMethod(); if (eapMethods.contains(NetworkManager::Security8021xSetting::EapMethodMd5)) { m_ui->auth->setCurrentIndex(m_ui->auth->findData(NetworkManager::Security8021xSetting::EapMethodMd5)); m_ui->md5UserName->setText(securitySetting->identity()); if (securitySetting->passwordFlags().testFlag(NetworkManager::Setting::None)) { m_ui->md5Password->setPasswordOption(PasswordField::StoreForAllUsers); } else if (securitySetting->passwordFlags().testFlag(NetworkManager::Setting::AgentOwned)) { m_ui->md5Password->setPasswordOption(PasswordField::StoreForUser); } else { m_ui->md5Password->setPasswordOption(PasswordField::AlwaysAsk); } } else if (eapMethods.contains(NetworkManager::Security8021xSetting::EapMethodTls)) { QStringList servers; m_ui->auth->setCurrentIndex(m_ui->auth->findData(NetworkManager::Security8021xSetting::EapMethodTls)); m_ui->tlsIdentity->setText(securitySetting->identity()); m_ui->tlsDomain->setText(securitySetting->domainSuffixMatch()); m_ui->tlsUserCert->setUrl(QUrl::fromLocalFile(securitySetting->clientCertificate())); m_ui->tlsCACert->setUrl(QUrl::fromLocalFile(securitySetting->caCertificate())); m_ui->leTlsSubjectMatch->setText(securitySetting->subjectMatch()); m_ui->leTlsAlternativeSubjectMatches->setText(securitySetting->altSubjectMatches().join(QLatin1String(", "))); Q_FOREACH (const QString &match, securitySetting->altSubjectMatches()) { if (match.startsWith(QLatin1String("DNS:"))) { servers.append(match.right(match.length()-4)); } } m_ui->leTlsConnectToServers->setText(servers.join(QLatin1String(", "))); m_ui->tlsPrivateKey->setUrl(QUrl::fromLocalFile(securitySetting->privateKey())); if (securitySetting->passwordFlags().testFlag(NetworkManager::Setting::None)) { m_ui->tlsPrivateKeyPassword->setPasswordOption(PasswordField::StoreForAllUsers); } else if (securitySetting->passwordFlags().testFlag(NetworkManager::Setting::AgentOwned)) { m_ui->tlsPrivateKeyPassword->setPasswordOption(PasswordField::StoreForUser); } else { m_ui->tlsPrivateKeyPassword->setPasswordOption(PasswordField::AlwaysAsk); } } else if (eapMethods.contains(NetworkManager::Security8021xSetting::EapMethodLeap)) { m_ui->auth->setCurrentIndex(m_ui->auth->findData(NetworkManager::Security8021xSetting::EapMethodLeap)); m_ui->leapUsername->setText(securitySetting->identity()); if (securitySetting->passwordFlags().testFlag(NetworkManager::Setting::None)) { m_ui->leapPassword->setPasswordOption(PasswordField::StoreForAllUsers); } else if (securitySetting->passwordFlags().testFlag(NetworkManager::Setting::AgentOwned)) { m_ui->leapPassword->setPasswordOption(PasswordField::StoreForUser); } else { m_ui->leapPassword->setPasswordOption(PasswordField::AlwaysAsk); } } else if (eapMethods.contains(NetworkManager::Security8021xSetting::EapMethodPwd)) { m_ui->auth->setCurrentIndex(m_ui->auth->findData(NetworkManager::Security8021xSetting::EapMethodPwd)); m_ui->pwdUsername->setText(securitySetting->identity()); if (securitySetting->passwordFlags().testFlag(NetworkManager::Setting::None)) { m_ui->pwdPassword->setPasswordOption(PasswordField::StoreForAllUsers); } else if (securitySetting->passwordFlags().testFlag(NetworkManager::Setting::AgentOwned)) { m_ui->pwdPassword->setPasswordOption(PasswordField::StoreForUser); } else { m_ui->pwdPassword->setPasswordOption(PasswordField::AlwaysAsk); } } else if (eapMethods.contains(NetworkManager::Security8021xSetting::EapMethodFast)) { m_ui->auth->setCurrentIndex(m_ui->auth->findData(NetworkManager::Security8021xSetting::EapMethodFast)); m_ui->fastAnonIdentity->setText(securitySetting->anonymousIdentity()); m_ui->fastAllowPacProvisioning->setChecked((int)securitySetting->phase1FastProvisioning() > 0); m_ui->pacMethod->setCurrentIndex(securitySetting->phase1FastProvisioning() - 1); m_ui->pacFile->setUrl(QUrl::fromLocalFile(securitySetting->pacFile())); if (phase2AuthMethod == NetworkManager::Security8021xSetting::AuthMethodGtc) { m_ui->fastInnerAuth->setCurrentIndex(0); } else { m_ui->fastInnerAuth->setCurrentIndex(1); } m_ui->fastUsername->setText(securitySetting->identity()); if (securitySetting->passwordFlags().testFlag(NetworkManager::Setting::None)) { m_ui->fastPassword->setPasswordOption(PasswordField::StoreForAllUsers); } else if (securitySetting->passwordFlags().testFlag(NetworkManager::Setting::AgentOwned)) { m_ui->fastPassword->setPasswordOption(PasswordField::StoreForUser); } else { m_ui->fastPassword->setPasswordOption(PasswordField::AlwaysAsk); } } else if (eapMethods.contains(NetworkManager::Security8021xSetting::EapMethodTtls)) { m_ui->auth->setCurrentIndex(m_ui->auth->findData(NetworkManager::Security8021xSetting::EapMethodTtls)); m_ui->ttlsAnonIdentity->setText(securitySetting->anonymousIdentity()); m_ui->ttlsDomain->setText(securitySetting->domainSuffixMatch()); m_ui->ttlsCACert->setUrl(QUrl::fromLocalFile(securitySetting->caCertificate())); if (phase2AuthMethod == NetworkManager::Security8021xSetting::AuthMethodPap) { m_ui->ttlsInnerAuth->setCurrentIndex(0); } else if (phase2AuthMethod == NetworkManager::Security8021xSetting::AuthMethodMschap) { m_ui->ttlsInnerAuth->setCurrentIndex(1); } else if (phase2AuthMethod == NetworkManager::Security8021xSetting::AuthMethodMschapv2) { m_ui->ttlsInnerAuth->setCurrentIndex(2); } else if (phase2AuthMethod == NetworkManager::Security8021xSetting::AuthMethodChap) { m_ui->ttlsInnerAuth->setCurrentIndex(3); } m_ui->ttlsUsername->setText(securitySetting->identity()); if (securitySetting->passwordFlags().testFlag(NetworkManager::Setting::None)) { m_ui->ttlsPassword->setPasswordOption(PasswordField::StoreForAllUsers); } else if (securitySetting->passwordFlags().testFlag(NetworkManager::Setting::AgentOwned)) { m_ui->ttlsPassword->setPasswordOption(PasswordField::StoreForUser); } else { m_ui->ttlsPassword->setPasswordOption(PasswordField::AlwaysAsk); } } else if (eapMethods.contains(NetworkManager::Security8021xSetting::EapMethodPeap)) { m_ui->auth->setCurrentIndex(m_ui->auth->findData(NetworkManager::Security8021xSetting::EapMethodPeap)); m_ui->peapAnonIdentity->setText(securitySetting->anonymousIdentity()); m_ui->peapDomain->setText(securitySetting->domainSuffixMatch()); m_ui->peapCACert->setUrl(QUrl::fromLocalFile(securitySetting->caCertificate())); m_ui->peapVersion->setCurrentIndex(securitySetting->phase1PeapVersion() + 1); if (phase2AuthMethod == NetworkManager::Security8021xSetting::AuthMethodMschapv2) { m_ui->peapInnerAuth->setCurrentIndex(0); } else if (phase2AuthMethod == NetworkManager::Security8021xSetting::AuthMethodMd5) { m_ui->peapInnerAuth->setCurrentIndex(1); } else if (phase2AuthMethod == NetworkManager::Security8021xSetting::AuthMethodGtc) { m_ui->peapInnerAuth->setCurrentIndex(2); } m_ui->peapUsername->setText(securitySetting->identity()); if (securitySetting->passwordFlags().testFlag(NetworkManager::Setting::None)) { m_ui->peapPassword->setPasswordOption(PasswordField::StoreForAllUsers); } else if (securitySetting->passwordFlags().testFlag(NetworkManager::Setting::AgentOwned)) { m_ui->peapPassword->setPasswordOption(PasswordField::StoreForUser); } else { m_ui->peapPassword->setPasswordOption(PasswordField::AlwaysAsk); } } loadSecrets(setting); } void Security8021x::loadSecrets(const NetworkManager::Setting::Ptr &setting) { NetworkManager::Security8021xSetting::Ptr securitySetting = setting.staticCast(); const QString password = securitySetting->password(); const QList eapMethods = securitySetting->eapMethods(); if (!password.isEmpty()) { if (eapMethods.contains(NetworkManager::Security8021xSetting::EapMethodMd5)) { m_ui->md5Password->setText(securitySetting->password()); } else if (eapMethods.contains(NetworkManager::Security8021xSetting::EapMethodLeap)) { m_ui->leapPassword->setText(securitySetting->password()); } else if (eapMethods.contains(NetworkManager::Security8021xSetting::EapMethodFast)) { m_ui->fastPassword->setText(securitySetting->password()); } else if (eapMethods.contains(NetworkManager::Security8021xSetting::EapMethodPwd)) { m_ui->pwdPassword->setText(securitySetting->password()); } else if (eapMethods.contains(NetworkManager::Security8021xSetting::EapMethodTtls)) { m_ui->ttlsPassword->setText(securitySetting->password()); } else if (eapMethods.contains(NetworkManager::Security8021xSetting::EapMethodPeap)) { m_ui->peapPassword->setText(securitySetting->password()); } } if (eapMethods.contains(NetworkManager::Security8021xSetting::EapMethodTls)) { const QString privateKeyPassword = securitySetting->privateKeyPassword(); if (!privateKeyPassword.isEmpty()) { m_ui->tlsPrivateKeyPassword->setText(securitySetting->privateKeyPassword()); } } } QVariantMap Security8021x::setting() const { NetworkManager::Security8021xSetting setting; NetworkManager::Security8021xSetting::EapMethod method = static_cast(m_ui->auth->itemData(m_ui->auth->currentIndex()).toInt()); setting.setEapMethods(QList() << method); if (method == NetworkManager::Security8021xSetting::EapMethodMd5) { if (!m_ui->md5UserName->text().isEmpty()) { setting.setIdentity(m_ui->md5UserName->text()); } if (m_ui->md5Password->passwordOption() == PasswordField::StoreForAllUsers) { setting.setPasswordFlags(NetworkManager::Setting::None); } else if (m_ui->md5Password->passwordOption() == PasswordField::StoreForUser) { setting.setPasswordFlags(NetworkManager::Setting::AgentOwned); } else { setting.setPasswordFlags(NetworkManager::Setting::NotSaved); } if (!m_ui->md5Password->text().isEmpty()) { setting.setPassword(m_ui->md5Password->text()); } } else if (method == NetworkManager::Security8021xSetting::EapMethodTls) { if (!m_ui->tlsIdentity->text().isEmpty()) { setting.setIdentity(m_ui->tlsIdentity->text()); } if (!m_ui->tlsDomain->text().isEmpty()) { setting.setDomainSuffixMatch(m_ui->tlsDomain->text()); } if (m_ui->tlsUserCert->url().isValid()) { setting.setClientCertificate(m_ui->tlsUserCert->url().toString().toUtf8().append('\0')); } if (m_ui->tlsCACert->url().isValid()) { setting.setCaCertificate(m_ui->tlsCACert->url().toString().toUtf8().append('\0')); } QStringList altsubjectmatches = m_ui->leTlsAlternativeSubjectMatches->text().remove(QLatin1Char(' ')).split(QLatin1Char(','), QString::SkipEmptyParts); Q_FOREACH (const QString &match, m_ui->leTlsConnectToServers->text().remove(QLatin1Char(' ')).split(QLatin1Char(','), QString::SkipEmptyParts)) { const QString tempstr = QLatin1String("DNS:") + match; if (!altsubjectmatches.contains(tempstr)) { altsubjectmatches.append(tempstr); } } setting.setSubjectMatch(m_ui->leTlsSubjectMatch->text()); setting.setAltSubjectMatches(altsubjectmatches); if (m_ui->tlsPrivateKey->url().isValid()) { setting.setPrivateKey(m_ui->tlsPrivateKey->url().toString().toUtf8().append('\0')); } if (!m_ui->tlsPrivateKeyPassword->text().isEmpty()) { setting.setPrivateKeyPassword(m_ui->tlsPrivateKeyPassword->text()); } QCA::Initializer init; QCA::ConvertResult convRes; // Try if the private key is in pkcs12 format bundled with client certificate if (QCA::isSupported("pkcs12")) { QCA::KeyBundle keyBundle = QCA::KeyBundle::fromFile(m_ui->tlsPrivateKey->url().path(), m_ui->tlsPrivateKeyPassword->text().toUtf8(), &convRes); // Set client certificate to the same path as private key if (convRes == QCA::ConvertGood && keyBundle.privateKey().canDecrypt()) { setting.setClientCertificate(m_ui->tlsPrivateKey->url().toString().toUtf8().append('\0')); } } if (m_ui->tlsPrivateKeyPassword->passwordOption() == PasswordField::StoreForAllUsers) { setting.setPrivateKeyPasswordFlags(NetworkManager::Setting::None); } else if (m_ui->tlsPrivateKeyPassword->passwordOption() == PasswordField::StoreForUser) { setting.setPrivateKeyPasswordFlags(NetworkManager::Setting::AgentOwned); } else { setting.setPrivateKeyPasswordFlags(NetworkManager::Setting::NotSaved); } } else if (method == NetworkManager::Security8021xSetting::EapMethodLeap) { if (!m_ui->leapUsername->text().isEmpty()) { setting.setIdentity(m_ui->leapUsername->text()); } if (!m_ui->leapPassword->text().isEmpty()) { setting.setPassword(m_ui->leapPassword->text()); } if (m_ui->leapPassword->passwordOption() == PasswordField::StoreForAllUsers) { setting.setPasswordFlags(NetworkManager::Setting::None); } else if (m_ui->leapPassword->passwordOption() == PasswordField::StoreForUser) { setting.setPasswordFlags(NetworkManager::Setting::AgentOwned); } else { setting.setPasswordFlags(NetworkManager::Setting::NotSaved); } } else if (method == NetworkManager::Security8021xSetting::EapMethodPwd) { if (!m_ui->pwdUsername->text().isEmpty()) { setting.setIdentity(m_ui->pwdUsername->text()); } if (m_ui->pwdPassword->passwordOption() == PasswordField::StoreForAllUsers) { setting.setPasswordFlags(NetworkManager::Setting::None); } else if (m_ui->pwdPassword->passwordOption() == PasswordField::StoreForUser) { setting.setPasswordFlags(NetworkManager::Setting::AgentOwned); } else { setting.setPasswordFlags(NetworkManager::Setting::NotSaved); } if (!m_ui->pwdPassword->text().isEmpty()) { setting.setPassword(m_ui->pwdPassword->text()); } } else if (method == NetworkManager::Security8021xSetting::EapMethodFast) { if (!m_ui->fastAnonIdentity->text().isEmpty()) { setting.setAnonymousIdentity(m_ui->fastAnonIdentity->text()); } if (!m_ui->fastAllowPacProvisioning->isChecked()) { setting.setPhase1FastProvisioning(NetworkManager::Security8021xSetting::FastProvisioningDisabled); } else { setting.setPhase1FastProvisioning(static_cast(m_ui->pacMethod->currentIndex() + 1)); } if (m_ui->pacFile->url().isValid()) { setting.setPacFile(QFile::encodeName(m_ui->pacFile->url().toLocalFile())); } if (m_ui->fastInnerAuth->currentIndex() == 0) { setting.setPhase2AuthMethod(NetworkManager::Security8021xSetting::AuthMethodGtc); } else { setting.setPhase2AuthMethod(NetworkManager::Security8021xSetting::AuthMethodMschapv2); } if (!m_ui->fastUsername->text().isEmpty()) { setting.setIdentity(m_ui->fastUsername->text()); } if (!m_ui->fastPassword->text().isEmpty()) { setting.setPassword(m_ui->fastPassword->text()); } if (m_ui->fastPassword->passwordOption() == PasswordField::StoreForAllUsers) { setting.setPasswordFlags(NetworkManager::Setting::None); } else if (m_ui->fastPassword->passwordOption() == PasswordField::StoreForUser) { setting.setPasswordFlags(NetworkManager::Setting::AgentOwned); } else { setting.setPasswordFlags(NetworkManager::Setting::NotSaved); } } else if (method == NetworkManager::Security8021xSetting::EapMethodTtls) { if (!m_ui->ttlsAnonIdentity->text().isEmpty()) { setting.setAnonymousIdentity(m_ui->ttlsAnonIdentity->text()); } if (!m_ui->ttlsDomain->text().isEmpty()) { setting.setDomainSuffixMatch(m_ui->ttlsDomain->text()); } if (m_ui->ttlsCACert->url().isValid()) { setting.setCaCertificate(m_ui->ttlsCACert->url().toString().toUtf8().append('\0')); } const int innerAuth = m_ui->ttlsInnerAuth->currentIndex(); if (innerAuth == 0) { setting.setPhase2AuthMethod(NetworkManager::Security8021xSetting::AuthMethodPap); } else if (innerAuth == 1) { setting.setPhase2AuthMethod(NetworkManager::Security8021xSetting::AuthMethodMschap); } else if (innerAuth == 2) { setting.setPhase2AuthMethod(NetworkManager::Security8021xSetting::AuthMethodMschapv2); } else if (innerAuth == 3) { setting.setPhase2AuthMethod(NetworkManager::Security8021xSetting::AuthMethodChap); } if (!m_ui->ttlsUsername->text().isEmpty()) { setting.setIdentity(m_ui->ttlsUsername->text()); } if (!m_ui->ttlsPassword->text().isEmpty()) { setting.setPassword(m_ui->ttlsPassword->text()); } if (m_ui->ttlsPassword->passwordOption() == PasswordField::StoreForAllUsers) { setting.setPasswordFlags(NetworkManager::Setting::None); } else if (m_ui->ttlsPassword->passwordOption() == PasswordField::StoreForUser) { setting.setPasswordFlags(NetworkManager::Setting::AgentOwned); } else { setting.setPasswordFlags(NetworkManager::Setting::NotSaved); } } else if (method == NetworkManager::Security8021xSetting::EapMethodPeap) { if (!m_ui->peapAnonIdentity->text().isEmpty()) { setting.setAnonymousIdentity(m_ui->peapAnonIdentity->text()); } if (!m_ui->peapDomain->text().isEmpty()) { setting.setDomainSuffixMatch(m_ui->peapDomain->text()); } if (m_ui->peapCACert->url().isValid()) { setting.setCaCertificate(m_ui->peapCACert->url().toString().toUtf8().append('\0')); } setting.setPhase1PeapVersion(static_cast(m_ui->peapVersion->currentIndex() - 1)); const int innerAuth = m_ui->peapInnerAuth->currentIndex(); if (innerAuth == 0) { setting.setPhase2AuthMethod(NetworkManager::Security8021xSetting::AuthMethodMschapv2); } else if (innerAuth == 1) { setting.setPhase2AuthMethod(NetworkManager::Security8021xSetting::AuthMethodMd5); } else if (innerAuth == 2) { setting.setPhase2AuthMethod(NetworkManager::Security8021xSetting::AuthMethodGtc); } if (!m_ui->peapUsername->text().isEmpty()) { setting.setIdentity(m_ui->peapUsername->text()); } if (!m_ui->peapPassword->text().isEmpty()) { setting.setPassword(m_ui->peapPassword->text()); } if (m_ui->peapPassword->passwordOption() == PasswordField::StoreForAllUsers) { setting.setPasswordFlags(NetworkManager::Setting::None); } else if (m_ui->peapPassword->passwordOption() == PasswordField::StoreForUser) { setting.setPasswordFlags(NetworkManager::Setting::AgentOwned); } else { setting.setPasswordFlags(NetworkManager::Setting::NotSaved); } } return setting.toMap(); } void Security8021x::altSubjectMatchesButtonClicked() { QPointer editor = new EditListDialog(this); editor->setItems(m_ui->leTlsSubjectMatch->text().remove(QLatin1Char(' ')).split(QLatin1Char(','), QString::SkipEmptyParts)); editor->setWindowTitle(i18n("Alternative Subject Matches")); editor->setToolTip(i18n("This entry must be one of:
  • DNS: <name or ip address>
  • EMAIL: <email>
  • URI: <uri, e.g. http://www.kde.org>
")); editor->setValidator(altSubjectValidator); connect(editor.data(), &QDialog::accepted, [editor, this] () { m_ui->leTlsSubjectMatch->setText(editor->items().join(QLatin1String(", "))); }); connect(editor.data(), &QDialog::finished, [editor] () { if (editor) { editor->deleteLater(); } }); editor->setModal(true); editor->show(); } void Security8021x::connectToServersButtonClicked() { QPointer editor = new EditListDialog(this); editor->setItems(m_ui->leTlsConnectToServers->text().remove(QLatin1Char(' ')).split(QLatin1Char(','), QString::SkipEmptyParts)); editor->setWindowTitle(i18n("Connect to these servers only")); editor->setValidator(serversValidator); connect(editor.data(), &QDialog::accepted, [editor, this] () { m_ui->leTlsConnectToServers->setText(editor->items().join(QLatin1String(", "))); }); connect(editor.data(), &QDialog::finished, [editor] () { if (editor) { editor->deleteLater(); } }); editor->setModal(true); editor->show(); } bool Security8021x::isValid() const { NetworkManager::Security8021xSetting::EapMethod method = static_cast(m_ui->auth->itemData(m_ui->auth->currentIndex()).toInt()); if (method == NetworkManager::Security8021xSetting::EapMethodMd5) { return !m_ui->md5UserName->text().isEmpty() && (!m_ui->md5Password->text().isEmpty() || m_ui->md5Password->passwordOption() == PasswordField::AlwaysAsk); } else if (method == NetworkManager::Security8021xSetting::EapMethodTls) { if (m_ui->tlsIdentity->text().isEmpty()) { return false; } if (!m_ui->tlsPrivateKey->url().isValid()) { return false; } if (m_ui->tlsPrivateKeyPassword->passwordOption() == PasswordField::AlwaysAsk) { return true; } if (m_ui->tlsPrivateKeyPassword->text().isEmpty()) { return false; } QCA::Initializer init; QCA::ConvertResult convRes; // Try if the private key is in pkcs12 format bundled with client certificate if (QCA::isSupported("pkcs12")) { QCA::KeyBundle keyBundle = QCA::KeyBundle::fromFile(m_ui->tlsPrivateKey->url().path(), m_ui->tlsPrivateKeyPassword->text().toUtf8(), &convRes); // We can return the result of decryption when we managed to import the private key if (convRes == QCA::ConvertGood) { return keyBundle.privateKey().canDecrypt(); } } // If the private key is not in pkcs12 format, we need client certificate to be set if (!m_ui->tlsUserCert->url().isValid()) { return false; } // Try if the private key is in PEM format and return the result of decryption if we managed to open it QCA::PrivateKey key = QCA::PrivateKey::fromPEMFile(m_ui->tlsPrivateKey->url().path(), m_ui->tlsPrivateKeyPassword->text().toUtf8(), &convRes); if (convRes == QCA::ConvertGood) { return key.canDecrypt(); } // TODO Try other formats (DER - mainly used in Windows) // TODO Validate other certificates?? } else if (method == NetworkManager::Security8021xSetting::EapMethodLeap) { return !m_ui->leapUsername->text().isEmpty() && (!m_ui->leapPassword->text().isEmpty() || m_ui->leapPassword->passwordOption() == PasswordField::AlwaysAsk); } else if (method == NetworkManager::Security8021xSetting::EapMethodPwd) { return !m_ui->pwdUsername->text().isEmpty() && (!m_ui->pwdPassword->text().isEmpty() || m_ui->pwdPassword->passwordOption() == PasswordField::AlwaysAsk); } else if (method == NetworkManager::Security8021xSetting::EapMethodFast) { if (!m_ui->fastAllowPacProvisioning->isChecked() && !m_ui->pacFile->url().isValid()) { return false; } return !m_ui->fastUsername->text().isEmpty() && (!m_ui->fastPassword->text().isEmpty() || m_ui->fastPassword->passwordOption() == PasswordField::AlwaysAsk); } else if (method == NetworkManager::Security8021xSetting::EapMethodTtls) { return !m_ui->ttlsUsername->text().isEmpty() && (!m_ui->ttlsPassword->text().isEmpty() || m_ui->ttlsPassword->passwordOption() == PasswordField::AlwaysAsk); } else if (method == NetworkManager::Security8021xSetting::EapMethodPeap) { return !m_ui->peapUsername->text().isEmpty() && (!m_ui->peapPassword->text().isEmpty() || m_ui->peapPassword->passwordOption() == PasswordField::AlwaysAsk); } return true; } void Security8021x::currentAuthChanged(int index) { Q_UNUSED(index); KAcceleratorManager::manage(m_ui->stackedWidget->currentWidget()); } diff --git a/libs/editor/settings/security802-1x.h b/libs/editor/settings/security802-1x.h index 82c3aad8..c8a93241 100644 --- a/libs/editor/settings/security802-1x.h +++ b/libs/editor/settings/security802-1x.h @@ -1,62 +1,62 @@ /* Copyright (c) 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_SECURITY8021X_H #define PLASMA_NM_SECURITY8021X_H #include #include #include #include "settingwidget.h" namespace Ui { class Security8021x; } class Q_DECL_EXPORT Security8021x: public SettingWidget { Q_OBJECT public: - Security8021x(const NetworkManager::Setting::Ptr &setting = NetworkManager::Setting::Ptr(), bool wifiMode = true, QWidget *parent = 0, Qt::WindowFlags f = 0); - virtual ~Security8021x(); + explicit Security8021x(const NetworkManager::Setting::Ptr &setting = NetworkManager::Setting::Ptr(), bool wifiMode = true, QWidget *parent = nullptr, Qt::WindowFlags f = {}); + ~Security8021x() override; - void loadConfig(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; - void loadSecrets(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; + void loadSecrets(const NetworkManager::Setting::Ptr &setting) override; - QVariantMap setting() const Q_DECL_OVERRIDE; + QVariantMap setting() const override; - virtual bool isValid() const Q_DECL_OVERRIDE; + bool isValid() const override; private Q_SLOTS: void altSubjectMatchesButtonClicked(); void connectToServersButtonClicked(); void currentAuthChanged(int index); private: NetworkManager::Security8021xSetting::Ptr m_setting; Ui::Security8021x *m_ui; QRegExpValidator *altSubjectValidator; QRegExpValidator *serversValidator; }; #endif // SECURITY8021X_H diff --git a/libs/editor/settings/teamwidget.h b/libs/editor/settings/teamwidget.h index 738bfdca..aaea4e53 100644 --- a/libs/editor/settings/teamwidget.h +++ b/libs/editor/settings/teamwidget.h @@ -1,70 +1,70 @@ /* Copyright 2014 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_TEAM_WIDGET_H #define PLASMA_NM_TEAM_WIDGET_H #include #include #include #include #include "settingwidget.h" #include namespace Ui { class TeamWidget; } class Q_DECL_EXPORT TeamWidget : public SettingWidget { Q_OBJECT public: explicit TeamWidget(const QString & masterUuid, const NetworkManager::Setting::Ptr &setting = NetworkManager::Setting::Ptr(), - QWidget* parent = 0, Qt::WindowFlags f = 0); - virtual ~TeamWidget(); + QWidget* parent = nullptr, Qt::WindowFlags f = {}); + ~TeamWidget() override; - void loadConfig(const NetworkManager::Setting::Ptr &setting); + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; - QVariantMap setting() const; + QVariantMap setting() const override; - virtual bool isValid() const; + bool isValid() const override; private Q_SLOTS: void addTeam(QAction * action); void currentTeamChanged(QListWidgetItem * current, QListWidgetItem * previous); void teamAddComplete(QDBusPendingCallWatcher * watcher); void editTeam(); void deleteTeam(); void populateTeams(); void importConfig(); private: QString m_uuid; Ui::TeamWidget * m_ui; QMenu * m_menu; }; #endif // PLASMA_NM_TEAM_WIDGET_H diff --git a/libs/editor/settings/vlanwidget.cpp b/libs/editor/settings/vlanwidget.cpp index 6a8ff37b..a721cf90 100644 --- a/libs/editor/settings/vlanwidget.cpp +++ b/libs/editor/settings/vlanwidget.cpp @@ -1,106 +1,106 @@ /* Copyright 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "vlanwidget.h" #include "ui_vlan.h" #include "uiutils.h" #include #include VlanWidget::VlanWidget(const NetworkManager::Setting::Ptr &setting, QWidget* parent, Qt::WindowFlags f): SettingWidget(setting, parent, f), m_ui(new Ui::VlanWidget) { m_ui->setupUi(this); fillConnections(); connect(m_ui->ifaceName, &KLineEdit::textChanged, this, &VlanWidget::slotWidgetChanged); - connect(m_ui->parent, static_cast(&KComboBox::currentIndexChanged), this, &VlanWidget::slotWidgetChanged); + connect(m_ui->parent, QOverload::of(&KComboBox::currentIndexChanged), this, &VlanWidget::slotWidgetChanged); connect(m_ui->parent->lineEdit(), &QLineEdit::textChanged, this, &VlanWidget::slotWidgetChanged); // Connect for setting check watchChangedSetting(); KAcceleratorManager::manage(this); if (setting) { loadConfig(setting); } } VlanWidget::~VlanWidget() { delete m_ui; } void VlanWidget::loadConfig(const NetworkManager::Setting::Ptr &setting) { NetworkManager::VlanSetting::Ptr vlanSetting = setting.staticCast(); m_ui->parent->setCurrentIndex(m_ui->parent->findData(vlanSetting->parent())); m_ui->id->setValue(vlanSetting->id()); m_ui->ifaceName->setText(vlanSetting->interfaceName()); m_ui->reorderHeaders->setChecked(vlanSetting->flags().testFlag(NetworkManager::VlanSetting::ReorderHeaders)); m_ui->gvrp->setChecked(vlanSetting->flags().testFlag(NetworkManager::VlanSetting::Gvrp)); m_ui->looseBinding->setChecked(vlanSetting->flags().testFlag(NetworkManager::VlanSetting::LooseBinding)); } QVariantMap VlanWidget::setting() const { NetworkManager::VlanSetting setting; setting.setParent(m_ui->parent->itemData(m_ui->parent->currentIndex()).toString()); setting.setId(m_ui->id->value()); const QString ifaceName = m_ui->ifaceName->text(); if (!ifaceName.isEmpty()) setting.setInterfaceName(ifaceName); NetworkManager::VlanSetting::Flags flags; if (m_ui->reorderHeaders->isChecked()) flags |= NetworkManager::VlanSetting::ReorderHeaders; if (m_ui->gvrp->isChecked()) flags |= NetworkManager::VlanSetting::Gvrp; if (m_ui->looseBinding->isChecked()) flags |= NetworkManager::VlanSetting::LooseBinding; if (flags) setting.setFlags(flags); return setting.toMap(); } void VlanWidget::fillConnections() { m_ui->parent->clear(); Q_FOREACH (const NetworkManager::Connection::Ptr &con, NetworkManager::listConnections()) { if (!con->settings()->isSlave() && con->settings()->connectionType() == NetworkManager::ConnectionSettings::Wired) m_ui->parent->addItem(con->name(), con->uuid()); } } bool VlanWidget::isValid() const { return !m_ui->parent->currentText().isEmpty() || !m_ui->ifaceName->text().isEmpty(); } diff --git a/libs/editor/settings/vlanwidget.h b/libs/editor/settings/vlanwidget.h index 08337b88..5aad2dab 100644 --- a/libs/editor/settings/vlanwidget.h +++ b/libs/editor/settings/vlanwidget.h @@ -1,52 +1,52 @@ /* Copyright 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_VLAN_WIDGET_H #define PLASMA_NM_VLAN_WIDGET_H #include #include "settingwidget.h" namespace Ui { class VlanWidget; } class Q_DECL_EXPORT VlanWidget : public SettingWidget { Q_OBJECT public: - explicit VlanWidget(const NetworkManager::Setting::Ptr &setting, QWidget* parent = 0, Qt::WindowFlags f = 0); - virtual ~VlanWidget(); + explicit VlanWidget(const NetworkManager::Setting::Ptr &setting, QWidget* parent = nullptr, Qt::WindowFlags f = {}); + ~VlanWidget() override; - void loadConfig(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; - QVariantMap setting() const Q_DECL_OVERRIDE; + QVariantMap setting() const override; - virtual bool isValid() const Q_DECL_OVERRIDE; + bool isValid() const override; private: void fillConnections(); Ui::VlanWidget * m_ui; }; #endif // PLASMA_NM_VLAN_WIDGET_H diff --git a/libs/editor/settings/wificonnectionwidget.cpp b/libs/editor/settings/wificonnectionwidget.cpp index aa1e337a..90ac4d6a 100644 --- a/libs/editor/settings/wificonnectionwidget.cpp +++ b/libs/editor/settings/wificonnectionwidget.cpp @@ -1,204 +1,204 @@ /* Copyright (c) 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "debug.h" #include "wificonnectionwidget.h" #include "ui_wificonnectionwidget.h" #include #include #include "uiutils.h" WifiConnectionWidget::WifiConnectionWidget(const NetworkManager::Setting::Ptr &setting, QWidget* parent, Qt::WindowFlags f): SettingWidget(setting, parent, f), m_ui(new Ui::WifiConnectionWidget) { qsrand(QTime::currentTime().msec()); m_ui->setupUi(this); connect(m_ui->btnRandomMacAddr, &QPushButton::clicked, this, &WifiConnectionWidget::generateRandomClonedMac); - connect(m_ui->SSIDCombo, &SsidComboBox::ssidChanged, this, static_cast(&WifiConnectionWidget::ssidChanged)); - connect(m_ui->modeComboBox, static_cast(&KComboBox::currentIndexChanged), this, &WifiConnectionWidget::modeChanged); - connect(m_ui->band, static_cast(&KComboBox::currentIndexChanged), this, &WifiConnectionWidget::bandChanged); + connect(m_ui->SSIDCombo, &SsidComboBox::ssidChanged, this, QOverload<>::of(&WifiConnectionWidget::ssidChanged)); + connect(m_ui->modeComboBox, QOverload::of(&KComboBox::currentIndexChanged), this, &WifiConnectionWidget::modeChanged); + connect(m_ui->band, QOverload::of(&KComboBox::currentIndexChanged), this, &WifiConnectionWidget::bandChanged); // Connect for setting check watchChangedSetting(); // Connect for validity check connect(m_ui->macAddress, &HwAddrComboBox::hwAddressChanged, this, &WifiConnectionWidget::slotWidgetChanged); connect(m_ui->BSSIDCombo, &BssidComboBox::bssidChanged, this, &WifiConnectionWidget::slotWidgetChanged); KAcceleratorManager::manage(this); if (setting) { loadConfig(setting); } } WifiConnectionWidget::~WifiConnectionWidget() { delete m_ui; } void WifiConnectionWidget::loadConfig(const NetworkManager::Setting::Ptr &setting) { NetworkManager::WirelessSetting::Ptr wifiSetting = setting.staticCast(); m_ui->SSIDCombo->init(QString::fromUtf8(wifiSetting->ssid())); if (wifiSetting->mode() != NetworkManager::WirelessSetting::Infrastructure) { m_ui->modeComboBox->setCurrentIndex(wifiSetting->mode()); } modeChanged(wifiSetting->mode()); m_ui->BSSIDCombo->init(NetworkManager::macAddressAsString(wifiSetting->bssid()), QString::fromUtf8(wifiSetting->ssid())); m_ui->band->setCurrentIndex(wifiSetting->band()); if (wifiSetting->band() != NetworkManager::WirelessSetting::Automatic) { m_ui->channel->setCurrentIndex(m_ui->channel->findData(wifiSetting->channel())); } m_ui->macAddress->init(NetworkManager::Device::Wifi, NetworkManager::macAddressAsString(wifiSetting->macAddress())); if (!wifiSetting->clonedMacAddress().isEmpty()) { m_ui->clonedMacAddress->setText(NetworkManager::macAddressAsString(wifiSetting->clonedMacAddress())); } if (wifiSetting->mtu()) { m_ui->mtu->setValue(wifiSetting->mtu()); } if (wifiSetting->hidden()) { m_ui->hiddenNetwork->setChecked(true); } } QVariantMap WifiConnectionWidget::setting() const { NetworkManager::WirelessSetting wifiSetting; wifiSetting.setSsid(m_ui->SSIDCombo->ssid().toUtf8()); wifiSetting.setMode(static_cast(m_ui->modeComboBox->currentIndex())); wifiSetting.setBssid(NetworkManager::macAddressFromString(m_ui->BSSIDCombo->bssid())); if (wifiSetting.mode() != NetworkManager::WirelessSetting::Infrastructure && m_ui->band->currentIndex() != 0) { wifiSetting.setBand((NetworkManager::WirelessSetting::FrequencyBand)m_ui->band->currentIndex()); wifiSetting.setChannel(m_ui->channel->itemData(m_ui->channel->currentIndex()).toUInt()); } wifiSetting.setMacAddress(NetworkManager::macAddressFromString(m_ui->macAddress->hwAddress())); if (!m_ui->clonedMacAddress->text().isEmpty() && m_ui->clonedMacAddress->text() != ":::::") { wifiSetting.setClonedMacAddress(NetworkManager::macAddressFromString(m_ui->clonedMacAddress->text())); } if (m_ui->mtu->value()) { wifiSetting.setMtu(m_ui->mtu->value()); } wifiSetting.setHidden(m_ui->hiddenNetwork->isChecked()); return wifiSetting.toMap(); } void WifiConnectionWidget::generateRandomClonedMac() { QByteArray mac; mac.resize(6); for (int i = 0; i < 6; i++) { int random = qrand() % 255; mac[i] = random; } // Disable the multicast bit and enable the locally administered bit. mac[0] = mac[0] & ~0x1; mac[0] = mac[0] | 0x2; m_ui->clonedMacAddress->setText(NetworkManager::macAddressAsString(mac)); } void WifiConnectionWidget::ssidChanged() { m_ui->BSSIDCombo->init(m_ui->BSSIDCombo->bssid(), m_ui->SSIDCombo->ssid()); slotWidgetChanged(); // Emit that SSID has changed so we can pre-configure wireless security Q_EMIT ssidChanged(m_ui->SSIDCombo->ssid()); } void WifiConnectionWidget::modeChanged(int mode) { if (mode == NetworkManager::WirelessSetting::Infrastructure) { m_ui->BSSIDLabel->setVisible(true); m_ui->BSSIDCombo->setVisible(true); m_ui->bandLabel->setVisible(false); m_ui->band->setVisible(false); m_ui->channelLabel->setVisible(false); m_ui->channel->setVisible(false); } else { m_ui->BSSIDLabel->setVisible(false); m_ui->BSSIDCombo->setVisible(false); m_ui->bandLabel->setVisible(true); m_ui->band->setVisible(true); m_ui->channelLabel->setVisible(true); m_ui->channel->setVisible(true); } } void WifiConnectionWidget::bandChanged(int band) { m_ui->channel->clear(); if (band == NetworkManager::WirelessSetting::Automatic) { m_ui->channel->setEnabled(false); } else { fillChannels((NetworkManager::WirelessSetting::FrequencyBand)band); m_ui->channel->setEnabled(true); } } void WifiConnectionWidget::fillChannels(NetworkManager::WirelessSetting::FrequencyBand band) { QList > channels; if (band == NetworkManager::WirelessSetting::A) { channels = NetworkManager::getAFreqs(); } else if (band == NetworkManager::WirelessSetting::Bg) { channels = NetworkManager::getBFreqs(); } else { qCWarning(PLASMA_NM) << Q_FUNC_INFO << "Unhandled band number" << band; return; } QListIterator > i(channels); while (i.hasNext()) { QPair channel = i.next(); m_ui->channel->addItem(i18n("%1 (%2 MHz)", channel.first, channel.second), channel.first); } } bool WifiConnectionWidget::isValid() const { return !m_ui->SSIDCombo->currentText().isEmpty() && m_ui->macAddress->isValid() && m_ui->BSSIDCombo->isValid(); } diff --git a/libs/editor/settings/wificonnectionwidget.h b/libs/editor/settings/wificonnectionwidget.h index f64d0b5c..f737ebae 100644 --- a/libs/editor/settings/wificonnectionwidget.h +++ b/libs/editor/settings/wificonnectionwidget.h @@ -1,63 +1,63 @@ /* Copyright (c) 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_WIFI_CONNECTION_WIDGET_H #define PLASMA_NM_WIFI_CONNECTION_WIDGET_H #include #include #include "settingwidget.h" namespace Ui { class WifiConnectionWidget; } class Q_DECL_EXPORT WifiConnectionWidget : public SettingWidget { Q_OBJECT public: - explicit WifiConnectionWidget(const NetworkManager::Setting::Ptr &setting = NetworkManager::Setting::Ptr(), QWidget* parent = 0, Qt::WindowFlags f = 0); - virtual ~WifiConnectionWidget(); + explicit WifiConnectionWidget(const NetworkManager::Setting::Ptr &setting = NetworkManager::Setting::Ptr(), QWidget* parent = nullptr, Qt::WindowFlags f = {}); + ~WifiConnectionWidget() override; - void loadConfig(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; - QVariantMap setting() const Q_DECL_OVERRIDE; + QVariantMap setting() const override; - virtual bool isValid() const Q_DECL_OVERRIDE; + bool isValid() const override; Q_SIGNALS: void ssidChanged(const QString &ssid); private Q_SLOTS: void generateRandomClonedMac(); void ssidChanged(); void modeChanged(int mode); void bandChanged(int band); private: Ui::WifiConnectionWidget * m_ui; void fillChannels(NetworkManager::WirelessSetting::FrequencyBand band); }; #endif // PLASMA_NM_WIFI_CONNECTION_WIDGET_H diff --git a/libs/editor/settings/wifisecurity.cpp b/libs/editor/settings/wifisecurity.cpp index f806ac54..93a8480d 100644 --- a/libs/editor/settings/wifisecurity.cpp +++ b/libs/editor/settings/wifisecurity.cpp @@ -1,381 +1,381 @@ /* Copyright (c) 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "wifisecurity.h" #include "ui_wifisecurity.h" #include #include #include #include WifiSecurity::WifiSecurity(const NetworkManager::Setting::Ptr &setting, const NetworkManager::Security8021xSetting::Ptr &setting8021x, QWidget *parent, Qt::WindowFlags f) : SettingWidget(setting, parent, f) , m_ui(new Ui::WifiSecurity) { m_wifiSecurity = setting.staticCast(); m_ui->setupUi(this); m_ui->leapPassword->setPasswordOptionsEnabled(true); m_ui->psk->setPasswordOptionsEnabled(true); m_ui->wepKey->setPasswordOptionsEnabled(true); m_8021xWidget = new Security8021x(setting8021x, true, this); // Dynamic WEP m_WPA2Widget = new Security8021x(setting8021x, true, this); // WPA(2) Enterprise m_ui->stackedWidget->insertWidget(3, m_8021xWidget); m_ui->stackedWidget->insertWidget(5, m_WPA2Widget); - connect(m_ui->securityCombo, static_cast(&KComboBox::currentIndexChanged), this, &WifiSecurity::securityChanged); - connect(m_ui->wepIndex, static_cast(&KComboBox::currentIndexChanged), this, &WifiSecurity::setWepKey); + connect(m_ui->securityCombo, QOverload::of(&KComboBox::currentIndexChanged), this, &WifiSecurity::securityChanged); + connect(m_ui->wepIndex, QOverload::of(&KComboBox::currentIndexChanged), this, &WifiSecurity::setWepKey); // Connect for setting check watchChangedSetting(); // Connect for validity check connect(m_ui->wepKey, &PasswordField::textChanged, this, &WifiSecurity::slotWidgetChanged); connect(m_ui->wepKey, &PasswordField::passwordOptionChanged, this, &WifiSecurity::slotWidgetChanged); connect(m_ui->leapUsername, &KLineEdit::textChanged, this, &WifiSecurity::slotWidgetChanged); connect(m_ui->leapPassword, &PasswordField::textChanged, this, &WifiSecurity::slotWidgetChanged); connect(m_ui->leapPassword, &PasswordField::passwordOptionChanged, this, &WifiSecurity::slotWidgetChanged); connect(m_ui->psk, &PasswordField::textChanged, this, &WifiSecurity::slotWidgetChanged); connect(m_ui->psk, &PasswordField::passwordOptionChanged, this, &WifiSecurity::slotWidgetChanged); - connect(m_ui->wepIndex, static_cast(&KComboBox::currentIndexChanged), this, &WifiSecurity::slotWidgetChanged); - connect(m_ui->securityCombo, static_cast(&KComboBox::currentIndexChanged), this, &WifiSecurity::slotWidgetChanged); + connect(m_ui->wepIndex, QOverload::of(&KComboBox::currentIndexChanged), this, &WifiSecurity::slotWidgetChanged); + connect(m_ui->securityCombo, QOverload::of(&KComboBox::currentIndexChanged), this, &WifiSecurity::slotWidgetChanged); connect(m_8021xWidget, &Security8021x::validChanged, this, &WifiSecurity::slotWidgetChanged); connect(m_WPA2Widget, &Security8021x::validChanged, this, &WifiSecurity::slotWidgetChanged); KAcceleratorManager::manage(this); if (setting && !setting->isNull()) { loadConfig(setting); } } WifiSecurity::~WifiSecurity() { delete m_ui; } bool WifiSecurity::enabled() const { return m_ui->securityCombo->currentIndex() > 0; } bool WifiSecurity::enabled8021x() const { if (m_ui->securityCombo->currentIndex() == 4 || m_ui->securityCombo->currentIndex() == 6) { return true; } return false; } bool WifiSecurity::isValid() const { const int securityIndex = m_ui->securityCombo->currentIndex(); if (securityIndex == WepHex) { // WEP Hex return NetworkManager::wepKeyIsValid(m_ui->wepKey->text(), NetworkManager::WirelessSecuritySetting::Hex) || m_ui->wepKey->passwordOption() == PasswordField::AlwaysAsk; } else if (securityIndex == WepPassphrase) { // WEP Passphrase return NetworkManager::wepKeyIsValid(m_ui->wepKey->text(), NetworkManager::WirelessSecuritySetting::Passphrase) || m_ui->wepKey->passwordOption() == PasswordField::AlwaysAsk;; }else if (securityIndex == Leap) { // LEAP return !m_ui->leapUsername->text().isEmpty() && (!m_ui->leapPassword->text().isEmpty() || m_ui->leapPassword->passwordOption() == PasswordField::AlwaysAsk); } else if (securityIndex == WpaPsk) { // WPA return NetworkManager::wpaPskIsValid(m_ui->psk->text()) || m_ui->psk->passwordOption() == PasswordField::AlwaysAsk;; } else if (securityIndex == DynamicWep) { return m_8021xWidget->isValid(); } else if (securityIndex == WpaEap) { return m_WPA2Widget->isValid(); } return true; } void WifiSecurity::loadConfig(const NetworkManager::Setting::Ptr &setting) { NetworkManager::WirelessSecuritySetting::Ptr wifiSecurity = setting.staticCast(); const NetworkManager::WirelessSecuritySetting::KeyMgmt keyMgmt = wifiSecurity->keyMgmt(); const NetworkManager::WirelessSecuritySetting::AuthAlg authAlg = wifiSecurity->authAlg(); if (keyMgmt == NetworkManager::WirelessSecuritySetting::Unknown) { m_ui->securityCombo->setCurrentIndex(None); // None } else if (keyMgmt == NetworkManager::WirelessSecuritySetting::Wep) { if (wifiSecurity->wepKeyType() == NetworkManager::WirelessSecuritySetting::Hex || wifiSecurity->wepKeyType() == NetworkManager::WirelessSecuritySetting::NotSpecified) { m_ui->securityCombo->setCurrentIndex(WepHex); // WEP Hex } else { m_ui->securityCombo->setCurrentIndex(WepPassphrase); } const int keyIndex = static_cast(wifiSecurity->wepTxKeyindex()); m_ui->wepIndex->setCurrentIndex(keyIndex); if (wifiSecurity->authAlg() == NetworkManager::WirelessSecuritySetting::Open) { m_ui->wepAuth->setCurrentIndex(0); } else { m_ui->wepAuth->setCurrentIndex(1); } if (wifiSecurity->wepKeyFlags().testFlag(NetworkManager::Setting::None)) { m_ui->wepKey->setPasswordOption(PasswordField::StoreForAllUsers); } else if (wifiSecurity->wepKeyFlags().testFlag(NetworkManager::Setting::AgentOwned)) { m_ui->wepKey->setPasswordOption(PasswordField::StoreForUser); } else { m_ui->wepKey->setPasswordOption(PasswordField::AlwaysAsk); } } else if (keyMgmt == NetworkManager::WirelessSecuritySetting::Ieee8021x && authAlg == NetworkManager::WirelessSecuritySetting::Leap) { m_ui->securityCombo->setCurrentIndex(Leap); // LEAP m_ui->leapUsername->setText(wifiSecurity->leapUsername()); m_ui->leapPassword->setText(wifiSecurity->leapPassword()); if (wifiSecurity->leapPasswordFlags().testFlag(NetworkManager::Setting::None)) { m_ui->leapPassword->setPasswordOption(PasswordField::StoreForAllUsers); } else if (wifiSecurity->leapPasswordFlags().testFlag(NetworkManager::Setting::AgentOwned)) { m_ui->leapPassword->setPasswordOption(PasswordField::StoreForUser); } else { m_ui->leapPassword->setPasswordOption(PasswordField::AlwaysAsk); } } else if (keyMgmt == NetworkManager::WirelessSecuritySetting::Ieee8021x) { m_ui->securityCombo->setCurrentIndex(DynamicWep); // Dynamic WEP // done in the widget } else if (keyMgmt == NetworkManager::WirelessSecuritySetting::WpaPsk) { m_ui->securityCombo->setCurrentIndex(WpaPsk); // WPA if (wifiSecurity->pskFlags().testFlag(NetworkManager::Setting::None)) { m_ui->psk->setPasswordOption(PasswordField::StoreForAllUsers); } else if (wifiSecurity->pskFlags().testFlag(NetworkManager::Setting::AgentOwned)) { m_ui->psk->setPasswordOption(PasswordField::StoreForUser); } else { m_ui->psk->setPasswordOption(PasswordField::AlwaysAsk); } } else if (keyMgmt == NetworkManager::WirelessSecuritySetting::WpaEap) { m_ui->securityCombo->setCurrentIndex(WpaEap); // WPA2 Enterprise // done in the widget } if (keyMgmt != NetworkManager::WirelessSecuritySetting::Ieee8021x && keyMgmt != NetworkManager::WirelessSecuritySetting::WpaEap) { loadSecrets(setting); } } void WifiSecurity::loadSecrets(const NetworkManager::Setting::Ptr &setting) { const NetworkManager::WirelessSecuritySetting::KeyMgmt keyMgmt = m_wifiSecurity->keyMgmt(); const NetworkManager::WirelessSecuritySetting::AuthAlg authAlg = m_wifiSecurity->authAlg(); if ((keyMgmt == NetworkManager::WirelessSecuritySetting::Ieee8021x && authAlg != NetworkManager::WirelessSecuritySetting::Leap) || keyMgmt == NetworkManager::WirelessSecuritySetting::WpaEap) { NetworkManager::Security8021xSetting::Ptr security8021xSetting = setting.staticCast(); if (security8021xSetting) { if (keyMgmt == NetworkManager::WirelessSecuritySetting::Ieee8021x) { m_8021xWidget->loadSecrets(security8021xSetting); } else { m_WPA2Widget->loadSecrets(security8021xSetting); } } } else { NetworkManager::WirelessSecuritySetting::Ptr wifiSecurity = setting.staticCast(); if (wifiSecurity) { if (keyMgmt == NetworkManager::WirelessSecuritySetting::Wep) { m_wifiSecurity->secretsFromMap(wifiSecurity->secretsToMap()); const int keyIndex = static_cast(m_wifiSecurity->wepTxKeyindex()); setWepKey(keyIndex); } else if (keyMgmt == NetworkManager::WirelessSecuritySetting::Ieee8021x && authAlg == NetworkManager::WirelessSecuritySetting::Leap) { const QString leapPassword = wifiSecurity->leapPassword(); if (!leapPassword.isEmpty()) { m_ui->leapPassword->setText(leapPassword); } } else if (keyMgmt == NetworkManager::WirelessSecuritySetting::WpaPsk) { const QString psk = wifiSecurity->psk(); if (!psk.isEmpty()) { m_ui->psk->setText(psk); } } } } } QVariantMap WifiSecurity::setting() const { NetworkManager::WirelessSecuritySetting wifiSecurity; const int securityIndex = m_ui->securityCombo->currentIndex(); if (securityIndex == None) { wifiSecurity.setKeyMgmt(NetworkManager::WirelessSecuritySetting::Unknown); } else if (securityIndex == WepHex || securityIndex == WepPassphrase) { // WEP wifiSecurity.setKeyMgmt(NetworkManager::WirelessSecuritySetting::Wep); if (securityIndex == WepHex) { wifiSecurity.setWepKeyType(NetworkManager::WirelessSecuritySetting::Hex); } else { wifiSecurity.setWepKeyType(NetworkManager::WirelessSecuritySetting::Passphrase); } const int keyIndex = m_ui->wepIndex->currentIndex(); const QString wepKey = m_ui->wepKey->text(); wifiSecurity.setWepTxKeyindex(keyIndex); if (keyIndex == 0) { wifiSecurity.setWepKey0(wepKey); } else if (keyIndex == 1) { wifiSecurity.setWepKey1(wepKey); } else if (keyIndex == 2) { wifiSecurity.setWepKey2(wepKey); } else if (keyIndex == 3) { wifiSecurity.setWepKey3(wepKey); } if (m_ui->wepKey->passwordOption() == PasswordField::StoreForAllUsers) { wifiSecurity.setWepKeyFlags(NetworkManager::Setting::None); } else if (m_ui->wepKey->passwordOption() == PasswordField::StoreForUser) { wifiSecurity.setWepKeyFlags(NetworkManager::Setting::AgentOwned); } else { wifiSecurity.setWepKeyFlags(NetworkManager::Setting::NotSaved); } if (m_ui->wepAuth->currentIndex() == 0) { wifiSecurity.setAuthAlg(NetworkManager::WirelessSecuritySetting::Open); } else { wifiSecurity.setAuthAlg(NetworkManager::WirelessSecuritySetting::Shared); } } else if (securityIndex == Leap) { // LEAP wifiSecurity.setKeyMgmt(NetworkManager::WirelessSecuritySetting::Ieee8021x); wifiSecurity.setAuthAlg(NetworkManager::WirelessSecuritySetting::Leap); wifiSecurity.setLeapUsername(m_ui->leapUsername->text()); wifiSecurity.setLeapPassword(m_ui->leapPassword->text()); if (m_ui->leapPassword->passwordOption() == PasswordField::StoreForAllUsers) { wifiSecurity.setLeapPasswordFlags(NetworkManager::Setting::None); } else if (m_ui->leapPassword->passwordOption() == PasswordField::StoreForUser) { wifiSecurity.setLeapPasswordFlags(NetworkManager::Setting::AgentOwned); } else { wifiSecurity.setLeapPasswordFlags(NetworkManager::Setting::NotSaved); } } else if (securityIndex == DynamicWep) { // Dynamic WEP wifiSecurity.setKeyMgmt(NetworkManager::WirelessSecuritySetting::Ieee8021x); } else if (securityIndex == WpaPsk) { // WPA wifiSecurity.setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaPsk); wifiSecurity.setPsk(m_ui->psk->text()); if (m_ui->psk->passwordOption() == PasswordField::StoreForAllUsers) { wifiSecurity.setPskFlags(NetworkManager::Setting::None); } else if (m_ui->psk->passwordOption() == PasswordField::StoreForUser) { wifiSecurity.setPskFlags(NetworkManager::Setting::AgentOwned); } else { wifiSecurity.setPskFlags(NetworkManager::Setting::NotSaved); } } else if (securityIndex == WpaEap) { // WPA2 Enterprise wifiSecurity.setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaEap); } return wifiSecurity.toMap(); } QVariantMap WifiSecurity::setting8021x() const { if (m_ui->securityCombo->currentIndex() == DynamicWep) { // Dynamic WEP return m_8021xWidget->setting(); } else if (m_ui->securityCombo->currentIndex() == WpaEap) { // WPA2 Enterprise return m_WPA2Widget->setting(); } return QVariantMap(); } void WifiSecurity::onSsidChanged(const QString &ssid) { Q_FOREACH (const NetworkManager::Device::Ptr &device, NetworkManager::networkInterfaces()) { if (device->type() == NetworkManager::Device::Wifi) { NetworkManager::WirelessDevice::Ptr wifiDevice = device.staticCast(); if (wifiDevice) { Q_FOREACH (const NetworkManager::WirelessNetwork::Ptr wifiNetwork, wifiDevice->networks()) { if (wifiNetwork && wifiNetwork->ssid() == ssid) { NetworkManager::AccessPoint::Ptr ap = wifiNetwork->referenceAccessPoint(); NetworkManager::WirelessSecurityType securityType = NetworkManager::findBestWirelessSecurity(wifiDevice->wirelessCapabilities(), true, (wifiDevice->mode() == NetworkManager::WirelessDevice::Adhoc), ap->capabilities(), ap->wpaFlags(), ap->rsnFlags()); switch (securityType) { case NetworkManager::WirelessSecurityType::StaticWep: m_ui->securityCombo->setCurrentIndex(WepHex); break; case NetworkManager::WirelessSecurityType::DynamicWep: m_ui->securityCombo->setCurrentIndex(DynamicWep); break; case NetworkManager::WirelessSecurityType::Leap: m_ui->securityCombo->setCurrentIndex(Leap); break; case NetworkManager::WirelessSecurityType::WpaPsk: m_ui->securityCombo->setCurrentIndex(WpaPsk); break; case NetworkManager::WirelessSecurityType::Wpa2Psk: m_ui->securityCombo->setCurrentIndex(WpaPsk); break; case NetworkManager::WirelessSecurityType::WpaEap: m_ui->securityCombo->setCurrentIndex(WpaEap); break; case NetworkManager::WirelessSecurityType::Wpa2Eap: m_ui->securityCombo->setCurrentIndex(WpaEap); break; default: m_ui->securityCombo->setCurrentIndex(None); } return; } } } } } // Reset to none security if we don't find any AP or Wifi device m_ui->securityCombo->setCurrentIndex(None); } void WifiSecurity::setWepKey(int keyIndex) { if (keyIndex == 0) { m_ui->wepKey->setText(m_wifiSecurity->wepKey0()); } else if (keyIndex == 1) { m_ui->wepKey->setText(m_wifiSecurity->wepKey1()); } else if (keyIndex == 2) { m_ui->wepKey->setText(m_wifiSecurity->wepKey2()); } else if (keyIndex == 3) { m_ui->wepKey->setText(m_wifiSecurity->wepKey3()); } } void WifiSecurity::securityChanged(int index) { if (index == 0) { m_ui->stackedWidget->setCurrentIndex(0); } else if (index == 1 || index == 2) { m_ui->stackedWidget->setCurrentIndex(1); } else { m_ui->stackedWidget->setCurrentIndex(index-1); } KAcceleratorManager::manage(m_ui->stackedWidget->currentWidget()); } diff --git a/libs/editor/settings/wifisecurity.h b/libs/editor/settings/wifisecurity.h index 77d8c88b..24462c6c 100644 --- a/libs/editor/settings/wifisecurity.h +++ b/libs/editor/settings/wifisecurity.h @@ -1,74 +1,74 @@ /* Copyright (c) 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_WIFI_SECURITY_H #define PLASMA_NM_WIFI_SECURITY_H #include #include #include #include "settingwidget.h" #include "security802-1x.h" namespace Ui { class WifiSecurity; } class Q_DECL_EXPORT WifiSecurity : public SettingWidget { Q_OBJECT public: // Keep this in sync with NetworkManager::WirelessSecurityType from // NetworkManagerQt. enum SecurityTypeIndex { None = 0, WepHex, WepPassphrase, Leap, DynamicWep, WpaPsk, WpaEap }; explicit WifiSecurity(const NetworkManager::Setting::Ptr &setting = NetworkManager::Setting::Ptr(), const NetworkManager::Security8021xSetting::Ptr &setting8021x = NetworkManager::Security8021xSetting::Ptr(), - QWidget *parent = 0, Qt::WindowFlags f = 0); - virtual ~WifiSecurity(); - void loadConfig(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; - void loadSecrets(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; + QWidget *parent = nullptr, Qt::WindowFlags f = {}); + ~WifiSecurity() override; + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; + void loadSecrets(const NetworkManager::Setting::Ptr &setting) override; - QVariantMap setting() const Q_DECL_OVERRIDE; + QVariantMap setting() const override; QVariantMap setting8021x() const; bool enabled() const; bool enabled8021x() const; - virtual bool isValid() const Q_DECL_OVERRIDE; + bool isValid() const override; public Q_SLOTS: void onSsidChanged(const QString &ssid); private Q_SLOTS: void securityChanged(int index); void setWepKey(int keyIndex); private: Ui::WifiSecurity *m_ui; Security8021x *m_8021xWidget; Security8021x *m_WPA2Widget; NetworkManager::WirelessSecuritySetting::Ptr m_wifiSecurity; }; #endif // PLASMA_NM_WIFI_SECURITY_H diff --git a/libs/editor/settings/wiredconnectionwidget.cpp b/libs/editor/settings/wiredconnectionwidget.cpp index cb060922..986627ec 100644 --- a/libs/editor/settings/wiredconnectionwidget.cpp +++ b/libs/editor/settings/wiredconnectionwidget.cpp @@ -1,159 +1,159 @@ /* Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "wiredconnectionwidget.h" #include "ui_wiredconnectionwidget.h" #include "uiutils.h" #include #include WiredConnectionWidget::WiredConnectionWidget(const NetworkManager::Setting::Ptr &setting, QWidget* parent, Qt::WindowFlags f): SettingWidget(setting, parent, f), m_widget(new Ui::WiredConnectionWidget) { qsrand(QTime::currentTime().msec()); m_widget->setupUi(this); m_widget->speedLabel->setHidden(true); m_widget->speed->setHidden(true); m_widget->duplexLabel->setHidden(true); m_widget->duplex->setHidden(true); connect(m_widget->btnRandomMacAddr, &QPushButton::clicked, this, &WiredConnectionWidget::generateRandomClonedMac); // Connect for setting check watchChangedSetting(); // Connect for validity check connect(m_widget->autonegotiate, &QCheckBox::stateChanged, this, &WiredConnectionWidget::slotWidgetChanged); connect(m_widget->clonedMacAddress, &KLineEdit::textChanged, this, &WiredConnectionWidget::slotWidgetChanged); connect(m_widget->macAddress, &HwAddrComboBox::hwAddressChanged, this, &WiredConnectionWidget::slotWidgetChanged); - connect(m_widget->speed, static_cast(&QSpinBox::valueChanged), this, &WiredConnectionWidget::slotWidgetChanged); + connect(m_widget->speed, QOverload::of(&QSpinBox::valueChanged), this, &WiredConnectionWidget::slotWidgetChanged); KAcceleratorManager::manage(this); if (setting) { loadConfig(setting); } } WiredConnectionWidget::~WiredConnectionWidget() { delete m_widget; } void WiredConnectionWidget::loadConfig(const NetworkManager::Setting::Ptr &setting) { NetworkManager::WiredSetting::Ptr wiredSetting = setting.staticCast(); m_widget->macAddress->init(NetworkManager::Device::Ethernet, NetworkManager::macAddressAsString(wiredSetting->macAddress())); if (!wiredSetting->clonedMacAddress().isEmpty()) { m_widget->clonedMacAddress->setText(NetworkManager::macAddressAsString(wiredSetting->clonedMacAddress())); } if (wiredSetting->mtu()) { m_widget->mtu->setValue(wiredSetting->mtu()); } if (!wiredSetting->autoNegotiate()) { m_widget->autonegotiate->setChecked(false); if (wiredSetting->speed()) { m_widget->speed->setValue(wiredSetting->speed()); } if (wiredSetting->duplexType() == NetworkManager::WiredSetting::Full) { m_widget->duplex->setCurrentIndex(0); } else { m_widget->duplex->setCurrentIndex(1); } } } QVariantMap WiredConnectionWidget::setting() const { NetworkManager::WiredSetting wiredSetting; wiredSetting.setMacAddress(NetworkManager::macAddressFromString(m_widget->macAddress->hwAddress())); if (!m_widget->clonedMacAddress->text().isEmpty() && m_widget->clonedMacAddress->text() != ":::::") { wiredSetting.setClonedMacAddress(NetworkManager::macAddressFromString(m_widget->clonedMacAddress->text())); } if (m_widget->mtu->value()) { wiredSetting.setMtu(m_widget->mtu->value()); } if (m_widget->autonegotiate->isChecked()) { wiredSetting.setAutoNegotiate(true); wiredSetting.setDuplexType(NetworkManager::WiredSetting::UnknownDuplexType); wiredSetting.setSpeed(0); } else { wiredSetting.setAutoNegotiate(false); wiredSetting.setSpeed(m_widget->speed->value()); if (m_widget->duplex->currentIndex() == 0) { wiredSetting.setDuplexType(NetworkManager::WiredSetting::Full); } else { wiredSetting.setDuplexType(NetworkManager::WiredSetting::Half); } } return wiredSetting.toMap(); } void WiredConnectionWidget::generateRandomClonedMac() { QByteArray mac; mac.resize(6); for (int i = 0; i < 6; i++) { int random = qrand() % 255; mac[i] = random; } // Disable the multicast bit and enable the locally administered bit. mac[0] = mac[0] & ~0x1; mac[0] = mac[0] | 0x2; m_widget->clonedMacAddress->setText(NetworkManager::macAddressAsString(mac)); } bool WiredConnectionWidget::isValid() const { if (!m_widget->macAddress->isValid()) { return false; } if (m_widget->clonedMacAddress->text() != ":::::") { if (!NetworkManager::macAddressIsValid(m_widget->clonedMacAddress->text())) { return false; } } if (!m_widget->autonegotiate->isChecked()) { if (!m_widget->speed->value()) { return false; } } return true; } diff --git a/libs/editor/settings/wiredconnectionwidget.h b/libs/editor/settings/wiredconnectionwidget.h index 38ed4923..9dd12617 100644 --- a/libs/editor/settings/wiredconnectionwidget.h +++ b/libs/editor/settings/wiredconnectionwidget.h @@ -1,54 +1,54 @@ /* Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_WIRED_CONNECTION_WIDGET_H #define PLASMA_NM_WIRED_CONNECTION_WIDGET_H #include #include "settingwidget.h" namespace Ui { class WiredConnectionWidget; } class Q_DECL_EXPORT WiredConnectionWidget : public SettingWidget { Q_OBJECT public: - explicit WiredConnectionWidget(const NetworkManager::Setting::Ptr &setting, QWidget* parent = 0, Qt::WindowFlags f = 0); - virtual ~WiredConnectionWidget(); + explicit WiredConnectionWidget(const NetworkManager::Setting::Ptr &setting, QWidget* parent = nullptr, Qt::WindowFlags f = {}); + ~WiredConnectionWidget() override; - void loadConfig(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; - QVariantMap setting() const Q_DECL_OVERRIDE; + QVariantMap setting() const override; - bool isValid() const Q_DECL_OVERRIDE; + bool isValid() const override; private Q_SLOTS: void generateRandomClonedMac(); private: Ui::WiredConnectionWidget * m_widget; }; #endif // PLASMA_NM_WIRED_CONNECTION_WIDGET_H diff --git a/libs/editor/settings/wiredsecurity.h b/libs/editor/settings/wiredsecurity.h index 2444c654..7c677cf6 100644 --- a/libs/editor/settings/wiredsecurity.h +++ b/libs/editor/settings/wiredsecurity.h @@ -1,54 +1,54 @@ /* Copyright (c) 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_WIRED_SECURITY_H #define PLASMA_NM_WIRED_SECURITY_H #include #include #include "settingwidget.h" #include "security802-1x.h" namespace Ui { class WiredSecurity; } class Q_DECL_EXPORT WiredSecurity : public SettingWidget { Q_OBJECT public: - explicit WiredSecurity(const NetworkManager::Security8021xSetting::Ptr &setting8021x = NetworkManager::Security8021xSetting::Ptr(), QWidget* parent = 0, Qt::WindowFlags f = 0); - virtual ~WiredSecurity(); - void loadConfig(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; - void loadSecrets(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; - QVariantMap setting() const Q_DECL_OVERRIDE; + explicit WiredSecurity(const NetworkManager::Security8021xSetting::Ptr &setting8021x = NetworkManager::Security8021xSetting::Ptr(), QWidget* parent = nullptr, Qt::WindowFlags f = {}); + ~WiredSecurity() override; + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; + void loadSecrets(const NetworkManager::Setting::Ptr &setting) override; + QVariantMap setting() const override; bool enabled8021x() const; private: Ui::WiredSecurity * m_ui; Security8021x * m_8021xWidget; NetworkManager::Security8021xSetting::Ptr m_8021xSetting; }; #endif // PLASMA_NM_WIRED_SECURITY_H diff --git a/libs/editor/simpleiplistvalidator.cpp b/libs/editor/simpleiplistvalidator.cpp new file mode 100644 index 00000000..1dcf8766 --- /dev/null +++ b/libs/editor/simpleiplistvalidator.cpp @@ -0,0 +1,108 @@ +/* +Copyright 2018 Bruce Anderson + +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) version 3 or any later version +accepted by the membership of KDE e.V. (or its successor approved +by the membership of KDE e.V.), which shall act as a proxy +defined in Section 14 of version 3 of the license. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +#include "simpleiplistvalidator.h" + +#include +#include + +SimpleIpListValidator::SimpleIpListValidator(QObject *parent, + AddressStyle style, + AddressType type) + : QValidator(parent) + , m_ipv6Validator(nullptr) + , m_ipv4Validator(nullptr) +{ + if (type == Ipv4 || type == Both) { + SimpleIpV4AddressValidator::AddressStyle ipv4Style; + if (style == Base) + ipv4Style = SimpleIpV4AddressValidator::AddressStyle::Base; + else if (style == WithCidr) + ipv4Style = SimpleIpV4AddressValidator::AddressStyle::WithCidr; + else + ipv4Style = SimpleIpV4AddressValidator::AddressStyle::WithPort; + m_ipv4Validator = new SimpleIpV4AddressValidator(this, ipv4Style); + } + if (type == Ipv6 || type == Both) { + SimpleIpV6AddressValidator::AddressStyle ipv6Style; + if (style == Base) + ipv6Style = SimpleIpV6AddressValidator::AddressStyle::Base; + else if (style == WithCidr) + ipv6Style = SimpleIpV6AddressValidator::AddressStyle::WithCidr; + else + ipv6Style = SimpleIpV6AddressValidator::AddressStyle::WithPort; + m_ipv6Validator = new SimpleIpV6AddressValidator(this, ipv6Style); + } +} + +SimpleIpListValidator::~SimpleIpListValidator() +{ +} + +QValidator::State SimpleIpListValidator::validate(QString &address, int &pos) const +{ + Q_UNUSED(pos) + + // Split the incoming address on commas possibly with spaces on either side + QStringList addressList = address.split(","); + + // Use a local variable for position in the validators so it doesn't screw + // up the position of the cursor when we return + int localPos = 0; + QValidator::State result = QValidator::Acceptable; + + for (QString &rawAddr : addressList) { + QValidator::State ipv4Result = QValidator::Acceptable; + QValidator::State ipv6Result = QValidator::Acceptable; + + QString addr = rawAddr.trimmed(); + + // If we are starting a new address and all the previous addressess + // are not Acceptable then the previous addresses need to be completed + // before a new one is started + if (result != QValidator::Acceptable) + return QValidator::Invalid; + + // See if it is an IPv4 address. If we are not testing for IPv4 + // then by definition IPv4 is Invalid + if (m_ipv4Validator != nullptr) + ipv4Result = m_ipv4Validator->validate(addr, localPos); + else + ipv4Result = QValidator::Invalid; + + // See if it is an IPv6 address. If we are not testing for IPv6 + // then by definition IPv6 is Invalid + if (m_ipv6Validator != nullptr) + ipv6Result = m_ipv6Validator->validate(addr, localPos); + else + ipv6Result = QValidator::Invalid; + + // If this address is not at least an Intermediate then get out because the list is Invalid + if (ipv6Result == QValidator::Invalid && ipv4Result == QValidator::Invalid) + return QValidator::Invalid; + + // If either validator judged this address to be Intermediate then that's the best the + // final result can be for the whole list. No need to test for Acceptable because + // that's the default set on entry and we only downgrade it from there. + if (ipv4Result == QValidator::Intermediate || ipv6Result == QValidator::Intermediate) + result = QValidator::Intermediate; + } + return result; +} diff --git a/libs/editor/simpleipv4addressvalidator.h b/libs/editor/simpleiplistvalidator.h similarity index 53% copy from libs/editor/simpleipv4addressvalidator.h copy to libs/editor/simpleiplistvalidator.h index be4fc81b..fa027c52 100644 --- a/libs/editor/simpleipv4addressvalidator.h +++ b/libs/editor/simpleiplistvalidator.h @@ -1,43 +1,46 @@ /* -Copyright 2009 Paul Marchouk +Copyright 2018 Bruce Anderson 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ -#ifndef SIMPLEIPV4ADDRESSVALIDATOR_H -#define SIMPLEIPV4ADDRESSVALIDATOR_H +#ifndef SIMPLEIPLISTVALIDATOR_H +#define SIMPLEIPLISTVALIDATOR_H #include +#include "simpleipv4addressvalidator.h" +#include "simpleipv6addressvalidator.h" -class Q_DECL_EXPORT SimpleIpV4AddressValidator : public QValidator +class Q_DECL_EXPORT SimpleIpListValidator : public QValidator { public: - explicit SimpleIpV4AddressValidator(QObject *parent); - virtual ~SimpleIpV4AddressValidator(); - - virtual State validate(QString &, int &) const; - - /** Check input value with a regular expression describing simple input mask. - */ - QValidator::State checkWithInputMask(QString &, int &) const; - /** Function split intput string into tetrads and check them for valid values. - * In the tetrads are placed into QList. Input string may be changed. - */ - QValidator::State checkTetradsRanges(QString &, QList&) const; + enum AddressType {Ipv4, Ipv6, Both}; + enum AddressStyle {Base, WithCidr, WithPort}; + + explicit SimpleIpListValidator(QObject *parent, + AddressStyle style = AddressStyle::Base, + AddressType allow = AddressType::Both); + ~SimpleIpListValidator() override; + + State validate(QString &, int &) const override; + +private: + SimpleIpV6AddressValidator *m_ipv6Validator; + SimpleIpV4AddressValidator *m_ipv4Validator; }; #endif // SIMPLEIPV4ADDRESSVALIDATOR_H diff --git a/libs/editor/simpleipv4addressvalidator.cpp b/libs/editor/simpleipv4addressvalidator.cpp index 56c188d3..ce0af31e 100644 --- a/libs/editor/simpleipv4addressvalidator.cpp +++ b/libs/editor/simpleipv4addressvalidator.cpp @@ -1,99 +1,169 @@ /* Copyright 2009 Paul Marchouk 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include "simpleipv4addressvalidator.h" #include #include -SimpleIpV4AddressValidator::SimpleIpV4AddressValidator(QObject *parent) +SimpleIpV4AddressValidator::SimpleIpV4AddressValidator(QObject *parent, AddressStyle style) : QValidator(parent) + , m_addressStyle(style) { + switch (style) { + case Base: + m_validator.setRegularExpression(QRegularExpression(QLatin1String("[0-9, ]{1,3}\\.[0-9, ]{1,3}\\.[0-9, ]{1,3}\\.[0-9, ]{1,3}"))); + break; + case WithCidr: + m_validator.setRegularExpression(QRegularExpression(QLatin1String("([0-9]{1,3}\\.){3,3}[0-9]{1,3}/[0-9]{1,2}"))); + break; + case WithPort: + m_validator.setRegularExpression(QRegularExpression(QLatin1String("([0-9]{1,3}\\.){3,3}[0-9]{1,3}:[0-9]{1,5}"))); + break; + } } SimpleIpV4AddressValidator::~SimpleIpV4AddressValidator() { } QValidator::State SimpleIpV4AddressValidator::validate(QString &address, int &pos) const { - if (QValidator::Invalid == checkWithInputMask(address, pos)) { + QValidator::State maskResult = checkWithInputMask(address, pos); + if (QValidator::Invalid == maskResult) { return QValidator::Invalid; } // this list will be filled with tetrad values. It can be used to make // some additional correctness checks on the last validation step. QList tetrads; - return checkTetradsRanges(address, tetrads); + QValidator::State tetradResult = checkTetradsRanges(address, tetrads); + if (QValidator::Invalid == tetradResult) + return QValidator::Invalid; + else if (QValidator::Intermediate == tetradResult || QValidator::Intermediate == maskResult) + return QValidator::Intermediate; + else + return QValidator::Acceptable; } QValidator::State SimpleIpV4AddressValidator::checkWithInputMask(QString &value, int &pos) const { - QRegExpValidator v(QRegExp(QLatin1String("[0-9, ]{1,3}\\.[0-9, ]{1,3}\\.[0-9, ]{1,3}\\.[0-9, ]{1,3}")), 0); - - return v.validate(value, pos); + return m_validator.validate(value, pos); } QValidator::State SimpleIpV4AddressValidator::checkTetradsRanges(QString &value, QList &tetrads) const { QStringList temp; - const QVector addrParts = value.splitRef(QLatin1Char('.')); + QVector addrParts; + QStringList cidrParts; + QStringList portParts; + + switch (m_addressStyle) { + case Base: + addrParts = value.splitRef(QLatin1Char('.')); + break; + + case WithCidr: + cidrParts = value.split(QLatin1Char('/')); + addrParts = cidrParts[0].splitRef(QLatin1Char('.')); + break; + + case WithPort: + portParts = value.split(QLatin1Char(':')); + addrParts = portParts[0].splitRef(QLatin1Char('.')); + break; + } + int i = 0; // fill in the list with invalid values tetrads << -1 << -1 << -1 << -1; // lets check address parts Q_FOREACH (const QStringRef &part, addrParts) { if (part.isEmpty()) { if (i != (addrParts.size() - 1)) { // qCDebug(PLASMA_NM) << "part.isEmpty()"; return QValidator::Invalid; } // the last tetrad can be empty, continue... return QValidator::Intermediate; } tetrads[i] = part.toInt(); if (tetrads[i] > 255) { // qCDebug(PLASMA_NM) << "tetrads[i] > 255"; return QValidator::Invalid; } // correct tetrad value: for example, 001 -> 1 temp.append(QString::number(tetrads[i])); i++; } // replace input string with the corrected version value = temp.join(QLatin1String(".")); if (i < 4) { // not all tetrads are filled... continue // qCDebug(PLASMA_NM) << "QValidator::Intermediate"; return QValidator::Intermediate; } else { + if (m_addressStyle == WithCidr) { + if (cidrParts.size() > 1) { + value += QLatin1String("/"); + if (!cidrParts[1].isEmpty()) { + int cidrValue = cidrParts[1].toInt(); + if (cidrValue > 32) { + return QValidator::Invalid; + } else { + value += cidrParts[1]; + return QValidator::Acceptable; + } + } + else { + return QValidator::Intermediate; + } + } + } else if (m_addressStyle == WithPort) { + if (portParts.size() > 1) { + value += QLatin1String(":"); + if (!portParts[1].isEmpty()) { + int portValue = portParts[1].toInt(); + if (portValue > 65535) { + return QValidator::Invalid; + } else { + value += portParts[1]; + return QValidator::Acceptable; + } + } + else { + return QValidator::Intermediate; + } + } + } + // qCDebug(PLASMA_NM) << "QValidator::Acceptable"; return QValidator::Acceptable; } } diff --git a/libs/editor/simpleipv4addressvalidator.h b/libs/editor/simpleipv4addressvalidator.h index be4fc81b..3645995a 100644 --- a/libs/editor/simpleipv4addressvalidator.h +++ b/libs/editor/simpleipv4addressvalidator.h @@ -1,43 +1,48 @@ /* Copyright 2009 Paul Marchouk 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef SIMPLEIPV4ADDRESSVALIDATOR_H #define SIMPLEIPV4ADDRESSVALIDATOR_H #include class Q_DECL_EXPORT SimpleIpV4AddressValidator : public QValidator { public: - explicit SimpleIpV4AddressValidator(QObject *parent); - virtual ~SimpleIpV4AddressValidator(); + enum AddressStyle {Base, WithCidr, WithPort}; - virtual State validate(QString &, int &) const; + explicit SimpleIpV4AddressValidator(QObject *parent, AddressStyle style = AddressStyle::Base); + ~SimpleIpV4AddressValidator() override; + + State validate(QString &, int &) const override; /** Check input value with a regular expression describing simple input mask. */ QValidator::State checkWithInputMask(QString &, int &) const; /** Function split intput string into tetrads and check them for valid values. * In the tetrads are placed into QList. Input string may be changed. */ QValidator::State checkTetradsRanges(QString &, QList&) const; +private: + AddressStyle m_addressStyle; + QRegularExpressionValidator m_validator; }; #endif // SIMPLEIPV4ADDRESSVALIDATOR_H diff --git a/libs/editor/simpleipv6addressvalidator.cpp b/libs/editor/simpleipv6addressvalidator.cpp index 99cb2911..483c4f54 100644 --- a/libs/editor/simpleipv6addressvalidator.cpp +++ b/libs/editor/simpleipv6addressvalidator.cpp @@ -1,85 +1,187 @@ /* Copyright 2011 Ilia Kats , based on work by Paul Marchouk 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include "simpleipv6addressvalidator.h" #include +#include -SimpleIpV6AddressValidator::SimpleIpV6AddressValidator(QObject *parent) +SimpleIpV6AddressValidator::SimpleIpV6AddressValidator(QObject *parent, AddressStyle style) : QValidator(parent) + , m_addressStyle(style) { + switch (style) { + case Base: + m_validator.setRegularExpression(QRegularExpression(QLatin1String("([0-9a-fA-F]{1,4}|:)+"))); + break; + case WithCidr: + m_validator.setRegularExpression(QRegularExpression(QLatin1String("([0-9a-fA-F]{1,4}|:){2,15}/[0-9]{1,3}"))); + break; + case WithPort: + m_validator.setRegularExpression(QRegularExpression(QLatin1String("\\[([0-9a-fA-F]{1,4}|:)+\\]:[0-9]{1,5}"))); + } } SimpleIpV6AddressValidator::~SimpleIpV6AddressValidator() { } QValidator::State SimpleIpV6AddressValidator::validate(QString &address, int &pos) const { if (QValidator::Invalid == checkWithInputMask(address, pos)) { return QValidator::Invalid; } return checkTetradsRanges(address); } QValidator::State SimpleIpV6AddressValidator::checkWithInputMask(QString &value, int &pos) const { - QRegExpValidator v(QRegExp(QLatin1String("([0-9a-fA-F]{1,4}|:)+")), 0); - - return v.validate(value, pos); + return m_validator.validate(value, pos); } QValidator::State SimpleIpV6AddressValidator::checkTetradsRanges(QString &value) const { - const QStringList addrParts = value.split(QLatin1Char(':')); + QStringList addrParts; + QStringList cidrParts; + QStringList portParts; + bool foundBracket = false; + QValidator::State result = QValidator::Acceptable; + + switch (m_addressStyle) { + case Base: + addrParts = value.split(QLatin1Char(':')); + break; + + case WithCidr: + cidrParts = value.split(QLatin1Char('/')); + addrParts = cidrParts[0].split(QLatin1Char(':')); + break; + + case WithPort: + if (value.isEmpty()) + return QValidator::Intermediate; + if (value[0] != '[') { + return QValidator::Invalid; + } else { + // Input: "[1:2:3:4:5:6:7:8]:123" + // bracketParts: "[1:2:3:4:5:6:7:8" , ":123" + // addrParts: "" , "1:2:3:4:5:6:7:8" + // portParts: "", "123" + QStringList bracketParts = value.split(QLatin1Char(']')); + if (bracketParts.size() < 2) + portParts = QStringList(); + else { + foundBracket = true; + if (!bracketParts[1].isEmpty() && bracketParts[1][0] != ':') + return QValidator::Invalid; + else + portParts = bracketParts[1].split(QLatin1Char(':')); + } + addrParts = bracketParts[0].split(QLatin1Char('['))[1].split(QLatin1Char(':')); + } + } + int number = addrParts.size(); - if (number > 8) { + // There is no case where can be more than 8 colons (9 parts) + // and only one unusual case where there are 8 colons (1:2:3:4:5:6:7::) + if (number > 9) + return QValidator::Invalid; + else if (number == 9 && (!addrParts[7].isEmpty() || !addrParts[8].isEmpty())) return QValidator::Invalid; - } // lets check address parts bool emptypresent = false; int i = 1; - Q_FOREACH (QString part, addrParts) { // krazy:exclude=Q_FOREACH + Q_FOREACH (QString part, addrParts) { // krazy:exclude=Q_FOREACH if (part.isEmpty() && i < number) { - if (emptypresent) { + // There is only one case where you can have 3 empty parts + // and that is when you have the string: "::" which is valid + // and useful and of course it can also be extended to ::123 for + // instance. Anywhere other than the beginning though, having 3 empty + // parts indicates either a run of 3 colons ("1:::6")" or two sets of + // 2 colons ("1:2::3:4::") which are always invalid + if (emptypresent && i != 2) { // qCDebug(PLASMA_NM) << "part.isEmpty()"; return QValidator::Invalid; - } - else if (!emptypresent) - { + } else { + // If this is an empty part then set it to zero to not fail + // the next test part.setNum(0,16); emptypresent = true; } } i++; bool ok; if (part.toInt(&ok, 16) > 65535) { return QValidator::Invalid; } } - if (number < 8 && !emptypresent) - return QValidator::Intermediate; + // A special case: a single colon needs to be Intermediate not Acceptable + if (number == 2 && addrParts[0].isEmpty() && addrParts[1].isEmpty()) + result = QValidator::Intermediate; + + // Another special case: a single colon followed by something (i.e. ":123" + // is invalid + else if (number > 1 && addrParts[0].isEmpty() && !addrParts[1].isEmpty()) + result = QValidator::Invalid; + + // If we don't have 8 parts yet and none of them are empty we aren't done yet + else if (number < 8 && !emptypresent) + result = QValidator::Intermediate; + + // If we have 8 parts but the last one is empty we aren't done yet + else if (number == 8 && addrParts[7].isEmpty()) + result = QValidator::Intermediate; + + if (m_addressStyle == WithCidr) { + int cidrSize = cidrParts.size(); - return QValidator::Acceptable; + // If we have a '/' and the basic address portion is not + // yet complete (i.e. Intermediate) then the whole thing is Invalid + if (cidrSize == 2 && result == QValidator::Intermediate) + return QValidator::Invalid; + + if (cidrSize == 1 || (cidrSize == 2 && cidrParts[1].isEmpty())) + return QValidator::Intermediate; + + int cidrValue = cidrParts[1].toInt(); + if (cidrValue > 128) + return QValidator::Invalid; + } else if (m_addressStyle == WithPort) { + int portSize = portParts.size(); + + // If we have a ']' and the basic address portion is not + // yet complete (i.e. Intermediate) then the whole thing is Invalid + if (foundBracket && result == QValidator::Intermediate) + return QValidator::Invalid; + + if (portSize < 2 || (portSize == 2 && portParts[1].isEmpty())) { + return QValidator::Intermediate; + } else { + int portValue = portParts[1].toInt(); + if (portValue > 65535) + return QValidator::Invalid; + } + } + return result; } diff --git a/libs/editor/simpleipv6addressvalidator.h b/libs/editor/simpleipv6addressvalidator.h index f388343d..0767e46f 100644 --- a/libs/editor/simpleipv6addressvalidator.h +++ b/libs/editor/simpleipv6addressvalidator.h @@ -1,43 +1,48 @@ /* Copyright 2011 Ilia Kats , based on work by Paul Marchouk 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef SIMPLEIPV6ADDRESSVALIDATOR_H #define SIMPLEIPV6ADDRESSVALIDATOR_H #include class Q_DECL_EXPORT SimpleIpV6AddressValidator : public QValidator { public: - explicit SimpleIpV6AddressValidator(QObject *parent); - virtual ~SimpleIpV6AddressValidator(); + enum AddressStyle {Base, WithCidr, WithPort}; - virtual State validate(QString &, int &) const; + explicit SimpleIpV6AddressValidator(QObject *parent, AddressStyle style = AddressStyle::Base); + ~SimpleIpV6AddressValidator() override; + + State validate(QString &, int &) const override; /** Check input value with a regular expression describing simple input mask. */ QValidator::State checkWithInputMask(QString &, int &) const; /** Function split intput string into tetrads and check them for valid values. * In the tetrads are placed into QList. Input string may be changed. */ QValidator::State checkTetradsRanges(QString &) const; +private: + AddressStyle m_addressStyle; + QRegularExpressionValidator m_validator; }; #endif // SIMPLEIPV6ADDRESSVALIDATOR_H diff --git a/libs/editor/vpnuiplugin.h b/libs/editor/vpnuiplugin.h index 9ae43fb6..a396d585 100644 --- a/libs/editor/vpnuiplugin.h +++ b/libs/editor/vpnuiplugin.h @@ -1,77 +1,77 @@ /* Copyright 2008 Will Stephenson Copyright 2013 Lukáš Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_VPN_UI_PLUGIN_H #define PLASMA_NM_VPN_UI_PLUGIN_H #include #include #include #include #include #include #include "settingwidget.h" /** * Plugin for UI elements for VPN configuration */ class Q_DECL_EXPORT VpnUiPlugin : public QObject { Q_OBJECT public: enum ErrorType {NoError, NotImplemented, Error}; - explicit VpnUiPlugin(QObject * parent = 0, const QVariantList& = QVariantList()); - virtual ~VpnUiPlugin(); + explicit VpnUiPlugin(QObject * parent = nullptr, const QVariantList& = QVariantList()); + ~VpnUiPlugin() override; - virtual SettingWidget * widget(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = 0) = 0; - virtual SettingWidget * askUser(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = 0) = 0; + virtual SettingWidget * widget(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = nullptr) = 0; + virtual SettingWidget * askUser(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = nullptr) = 0; /** * Suggested file name to save the exported connection configuration. * Try not to use space, parenthesis, or any other Unix unfriendly file name character. */ virtual QString suggestedFileName(const NetworkManager::ConnectionSettings::Ptr &connection) const = 0; /** * File extension to be used in QFileDialog when selecting the file to import. * The format is: *. [*. ...]. For instance: '*.pcf' */ virtual QString supportedFileExtensions() const = 0; /** * If the plugin does not support fileName's extension it must just return an empty QVariantList. * If it supports the extension and import has failed it must set mError with VpnUiPlugin::Error * and mErrorMessage with a custom error message before returning an empty QVariantList. */ virtual NMVariantMapMap importConnectionSettings(const QString &fileName) = 0; virtual bool exportConnectionSettings(const NetworkManager::ConnectionSettings::Ptr &connection, const QString &fileName) = 0; virtual QMessageBox::StandardButtons suggestedAuthDialogButtons() const; ErrorType lastError() const; QString lastErrorMessage(); protected: ErrorType mError; QString mErrorMessage; }; #endif // PLASMA_NM_VPN_UI_PLUGIN_H diff --git a/libs/editor/widgets/advancedpermissionswidget.h b/libs/editor/widgets/advancedpermissionswidget.h index 51fcb4b1..eae674b9 100644 --- a/libs/editor/widgets/advancedpermissionswidget.h +++ b/libs/editor/widgets/advancedpermissionswidget.h @@ -1,56 +1,56 @@ /* Copyright 2011 Ilia Kats Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_ADVANCED_PERMISSIONS_WIDGET_H #define PLASMA_NM_ADVANCED_PERMISSIONS_WIDGET_H #include #include class QTreeWidgetItem; class AdvancedPermissionsWidgetPrivate; class KUser; class AdvancedPermissionsWidget : public QDialog { Q_OBJECT Q_DECLARE_PRIVATE(AdvancedPermissionsWidget) public: - explicit AdvancedPermissionsWidget(QWidget *parent=0); - AdvancedPermissionsWidget(const QHash&, QWidget *parent=0); - ~AdvancedPermissionsWidget(); + explicit AdvancedPermissionsWidget(QWidget *parent = nullptr); + AdvancedPermissionsWidget(const QHash&, QWidget *parent = nullptr); + ~AdvancedPermissionsWidget() override; QHash currentUsers() const; protected: AdvancedPermissionsWidgetPrivate * const d_ptr; private: enum Columns {FullName = 0, LoginName = 1}; void setupCommon(); QTreeWidgetItem * constructItem(const KUser &user, const QString &itemData = QString()); private Q_SLOTS: void leftArrowClicked(); void rightArrowClicked(); }; #endif // PLASMA_NM_ADVANCED_PERMISSIONS_WIDGET_H diff --git a/libs/editor/widgets/bssidcombobox.cpp b/libs/editor/widgets/bssidcombobox.cpp index e497f1a9..5292be18 100644 --- a/libs/editor/widgets/bssidcombobox.cpp +++ b/libs/editor/widgets/bssidcombobox.cpp @@ -1,147 +1,147 @@ /* Copyright 2013 Lukas Tinkl Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "bssidcombobox.h" #include #include #include #include bool signalCompare(const NetworkManager::AccessPoint::Ptr & one, const NetworkManager::AccessPoint::Ptr & two) { return one->signalStrength() > two->signalStrength(); } BssidComboBox::BssidComboBox(QWidget *parent) : QComboBox(parent), m_dirty(false) { setEditable(true); setInsertPolicy(QComboBox::NoInsert); connect(this, &BssidComboBox::editTextChanged, this, &BssidComboBox::slotEditTextChanged); - connect(this, static_cast(&BssidComboBox::activated), this, &BssidComboBox::slotCurrentIndexChanged); + connect(this, QOverload::of(&BssidComboBox::activated), this, &BssidComboBox::slotCurrentIndexChanged); } QString BssidComboBox::bssid() const { QString result; if (!m_dirty) result = itemData(currentIndex()).toString(); else result = currentText(); // qCDebug(PLASMA_NM) << "Result:" << currentIndex() << result; return result; } bool BssidComboBox::isValid() const { if (bssid().isEmpty()) { return true; } return NetworkManager::macAddressIsValid(bssid()); } void BssidComboBox::slotEditTextChanged(const QString &) { m_dirty = true; Q_EMIT bssidChanged(); } void BssidComboBox::slotCurrentIndexChanged(int) { m_dirty = false; setEditText(bssid()); Q_EMIT bssidChanged(); } void BssidComboBox::init(const QString & bssid, const QString &ssid) { m_initialBssid = bssid; // qCDebug(PLASMA_NM) << "Initial ssid:" << m_initialBssid; QList aps; Q_FOREACH (const NetworkManager::Device::Ptr & device, NetworkManager::networkInterfaces()) { if (device->type() == NetworkManager::Device::Wifi) { NetworkManager::WirelessDevice::Ptr wifiDevice = device.objectCast(); NetworkManager::WirelessNetwork::Ptr wifiNetwork = wifiDevice->findNetwork(ssid); if (!wifiNetwork) { continue; } Q_FOREACH (const NetworkManager::AccessPoint::Ptr & newAp, wifiNetwork->accessPoints()) { bool found = false;; Q_FOREACH (const NetworkManager::AccessPoint::Ptr & existingAp, aps) { if (newAp->hardwareAddress() == existingAp->hardwareAddress()) { if (newAp->signalStrength() > existingAp->signalStrength()) { aps.removeOne(existingAp); break; } else { found = true; break; } } } if (!found) { aps << newAp; } } } } qSort(aps.begin(), aps.end(), signalCompare); addBssidsToCombo(aps); const int index = findData(m_initialBssid); if (index == -1) { insertItem(0, m_initialBssid, m_initialBssid); setCurrentIndex(0); } else { setCurrentIndex(index); } setEditText(m_initialBssid); } void BssidComboBox::addBssidsToCombo(const QList & aps) { clear(); if (aps.isEmpty()) { addItem(i18n("First select the SSID")); return; } Q_FOREACH (const NetworkManager::AccessPoint::Ptr & ap, aps) { if (!ap) { continue; } const QString text = i18n("%1 (%2%)\nFrequency: %3 Mhz\nChannel: %4", ap->hardwareAddress(), ap->signalStrength(), ap->frequency(), QString::number(NetworkManager::findChannel(ap->frequency()))); addItem(text, QVariant::fromValue(ap->hardwareAddress())); } } diff --git a/libs/editor/widgets/bssidcombobox.h b/libs/editor/widgets/bssidcombobox.h index af9796c8..40ba4187 100644 --- a/libs/editor/widgets/bssidcombobox.h +++ b/libs/editor/widgets/bssidcombobox.h @@ -1,56 +1,56 @@ /* Copyright 2013 Lukas Tinkl Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_BSSIDCOMBOBOX_H #define PLASMA_NM_BSSIDCOMBOBOX_H #include #include #include class Q_DECL_EXPORT BssidComboBox : public QComboBox { Q_OBJECT public: - explicit BssidComboBox(QWidget *parent = 0); + explicit BssidComboBox(QWidget *parent = nullptr); QString bssid() const; bool isValid() const; Q_SIGNALS: void bssidChanged(); public Q_SLOTS: void init(const QString & bssid, const QString &ssid); private Q_SLOTS: void slotEditTextChanged(const QString &); void slotCurrentIndexChanged(int); private: void addBssidsToCombo(const QList & aps); QString m_initialBssid; bool m_dirty; }; #endif // PLASMA_NM_BSSIDCOMBOBOX_H diff --git a/libs/editor/widgets/delegate.h b/libs/editor/widgets/delegate.h index c4a0fc11..f5628a5e 100644 --- a/libs/editor/widgets/delegate.h +++ b/libs/editor/widgets/delegate.h @@ -1,45 +1,45 @@ /* Copyright 2011 Ilia Kats 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef DELEGATE_H #define DELEGATE_H #include #include class Delegate : public QStyledItemDelegate { Q_OBJECT public: - explicit Delegate(QObject * parent = 0); - virtual ~Delegate(); + explicit Delegate(QObject * parent = nullptr); + ~Delegate() override; - virtual QWidget * createEditor(QWidget *parent, const QStyleOptionViewItem &option, - const QModelIndex &index) const Q_DECL_OVERRIDE; - virtual void setEditorData(QWidget *editor, const QModelIndex &index) const Q_DECL_OVERRIDE; + QWidget * createEditor(QWidget *parent, const QStyleOptionViewItem &option, + const QModelIndex &index) const override; + void setEditorData(QWidget *editor, const QModelIndex &index) const override; - virtual void setModelData(QWidget *editor, QAbstractItemModel *model, - const QModelIndex &index) const Q_DECL_OVERRIDE; + void setModelData(QWidget *editor, QAbstractItemModel *model, + const QModelIndex &index) const override; - virtual void updateEditorGeometry(QWidget *editor, - const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE; + void updateEditorGeometry(QWidget *editor, + const QStyleOptionViewItem &option, const QModelIndex &index) const override; }; #endif diff --git a/libs/editor/widgets/editlistdialog.h b/libs/editor/widgets/editlistdialog.h index 291f450a..37629db0 100644 --- a/libs/editor/widgets/editlistdialog.h +++ b/libs/editor/widgets/editlistdialog.h @@ -1,58 +1,58 @@ /* Copyright 2009 Andrey Batyiev Copyright 2015 Jan Grulich 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef PLASMA_NM_EDIT_LIST_DIALOG_H #define PLASMA_NM_EDIT_LIST_DIALOG_H #include #include class QValidator; class EditListDialog : public QDialog { Q_OBJECT public: explicit EditListDialog(QWidget *parent = nullptr); - virtual ~EditListDialog(); + ~EditListDialog() override; void setItems(const QStringList &items); QStringList items() const; void setValidator(const QValidator *validator); const QValidator *validator() const; void setToolTip(const QString toolTip); Q_SIGNALS: void itemsEdited(const QStringList &items); protected Q_SLOTS: void dialogAccepted(); private: KEditListWidget *editListWidget; void removeEmptyItems(QStringList &list); }; #endif // PLASMA_NM_EDIT_LIST_DIALOG_H diff --git a/libs/editor/widgets/hwaddrcombobox.cpp b/libs/editor/widgets/hwaddrcombobox.cpp index e0d78e4a..04cb7660 100644 --- a/libs/editor/widgets/hwaddrcombobox.cpp +++ b/libs/editor/widgets/hwaddrcombobox.cpp @@ -1,161 +1,161 @@ /* Copyright 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "hwaddrcombobox.h" #include #include #include #include #include #include #include #include #include #include HwAddrComboBox::HwAddrComboBox(QWidget *parent) : QComboBox(parent), m_dirty(false) { setEditable(true); setInsertPolicy(QComboBox::NoInsert); connect(this, &HwAddrComboBox::editTextChanged, this, &HwAddrComboBox::slotEditTextChanged); - connect(this, static_cast(&HwAddrComboBox::currentIndexChanged), this, &HwAddrComboBox::slotCurrentIndexChanged); + connect(this, QOverload::of(&HwAddrComboBox::currentIndexChanged), this, &HwAddrComboBox::slotCurrentIndexChanged); } bool HwAddrComboBox::isValid() const { if (hwAddress().isEmpty()) { return true; } return NetworkManager::macAddressIsValid(hwAddress()); } QString HwAddrComboBox::hwAddress() const { QString result; if (!m_dirty) result = itemData(currentIndex()).toString(); else result = currentText(); // qCDebug(PLASMA_NM)() << "Result:" << currentIndex() << result; return result; } void HwAddrComboBox::slotEditTextChanged(const QString &) { m_dirty = true; Q_EMIT hwAddressChanged(); } void HwAddrComboBox::slotCurrentIndexChanged(int) { m_dirty = false; Q_EMIT hwAddressChanged(); } void HwAddrComboBox::init(const NetworkManager::Device::Type &deviceType, const QString &address) { m_initialAddress = address; // qCDebug(PLASMA_NM) << "Initial address:" << m_initialAddress; QString deviceName; Q_FOREACH (const NetworkManager::Device::Ptr & device, NetworkManager::networkInterfaces()) { const NetworkManager::Device::Type type = device->type(); if (type == deviceType) { if (address == hwAddressFromDevice(device).toString()) { if (device->state() == NetworkManager::Device::Activated) { deviceName = device->ipInterfaceName(); } else { deviceName = device->interfaceName(); } } addAddressToCombo(device); } } const int index = findData(m_initialAddress); if (index == -1) { if (!m_initialAddress.isEmpty()) { const QString text = QStringLiteral("%1 (%2)").arg(deviceName).arg(m_initialAddress); insertItem(0, text, m_initialAddress); } else { insertItem(0, m_initialAddress, m_initialAddress); } setCurrentIndex(0); } else { setCurrentIndex(index); } } void HwAddrComboBox::addAddressToCombo(const NetworkManager::Device::Ptr &device) { const QVariant data = hwAddressFromDevice(device); // qCDebug(PLASMA_NM) << "Data:" << data; QString name; if (device->state() == NetworkManager::Device::Activated) name = device->ipInterfaceName(); else name = device->interfaceName(); // qCDebug(PLASMA_NM) << "Name:" << name; if (!data.isNull()) { if (name == data.toString()) { addItem(data.toString(), data); } else { addItem(QStringLiteral("%1 (%2)").arg(name).arg(data.toString()), data); } } } QVariant HwAddrComboBox::hwAddressFromDevice(const NetworkManager::Device::Ptr& device) { const NetworkManager::Device::Type type = device->type(); QVariant data; if (type == NetworkManager::Device::Ethernet) { data = device->as()->permanentHardwareAddress(); } else if (type == NetworkManager::Device::Wifi) { data = device->as()->permanentHardwareAddress(); } else if (type == NetworkManager::Device::Bluetooth) { data = device->as()->hardwareAddress(); } else if (type == NetworkManager::Device::OlpcMesh) { data = device->as()->hardwareAddress(); } else if (type == NetworkManager::Device::InfiniBand) { data = device->as()->hwAddress(); } else if (type == NetworkManager::Device::Bond) { data = device->as()->hwAddress(); } else if (type == NetworkManager::Device::Bridge) { data = device->as()->hwAddress(); } else if (type == NetworkManager::Device::Vlan) { data = device->as()->hwAddress(); } return data; } diff --git a/libs/editor/widgets/hwaddrcombobox.h b/libs/editor/widgets/hwaddrcombobox.h index fc0b3ce0..2aef3938 100644 --- a/libs/editor/widgets/hwaddrcombobox.h +++ b/libs/editor/widgets/hwaddrcombobox.h @@ -1,53 +1,53 @@ /* Copyright 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_HWADDRCOMBOBOX_H #define PLASMA_NM_HWADDRCOMBOBOX_H #include #include class Q_DECL_EXPORT HwAddrComboBox : public QComboBox { Q_OBJECT public: - explicit HwAddrComboBox(QWidget *parent = 0); + explicit HwAddrComboBox(QWidget *parent = nullptr); void init(const NetworkManager::Device::Type &deviceType, const QString &address); bool isValid() const; QString hwAddress() const; Q_SIGNALS: void hwAddressChanged(); private Q_SLOTS: void slotEditTextChanged(const QString &); void slotCurrentIndexChanged(int); private: void addAddressToCombo(const NetworkManager::Device::Ptr &device); QVariant hwAddressFromDevice(const NetworkManager::Device::Ptr &device); QString m_initialAddress; bool m_dirty; }; #endif // PLASMA_NM_HWADDRCOMBOBOX_H diff --git a/libs/editor/widgets/intdelegate.h b/libs/editor/widgets/intdelegate.h index 7a7bc2eb..345bb1dc 100644 --- a/libs/editor/widgets/intdelegate.h +++ b/libs/editor/widgets/intdelegate.h @@ -1,46 +1,46 @@ /* Copyright 2011 Ilia Kats 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef INTDELEGATE_H #define INTDELEGATE_H #include #include #include #include "delegate.h" class IntDelegate : public Delegate { Q_OBJECT public: - explicit IntDelegate(QObject * parent = 0); - IntDelegate(int min, int max, QObject * parent = 0); - virtual ~IntDelegate(); + explicit IntDelegate(QObject * parent = nullptr); + IntDelegate(int min, int max, QObject * parent = nullptr); + ~IntDelegate() override; - QWidget * createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE; + QWidget * createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override; private: int m_min; int m_max; bool m_boundary; }; #endif diff --git a/libs/editor/widgets/ipv4delegate.h b/libs/editor/widgets/ipv4delegate.h index 04ccb8c7..c73d54aa 100644 --- a/libs/editor/widgets/ipv4delegate.h +++ b/libs/editor/widgets/ipv4delegate.h @@ -1,37 +1,37 @@ /* Copyright 2011 Ilia Kats 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef IPV4DELEGATE_H #define IPV4DELEGATE_H #include #include "delegate.h" class IpV4Delegate : public Delegate { Q_OBJECT public: - explicit IpV4Delegate(QObject * parent = 0); - virtual ~IpV4Delegate(); + explicit IpV4Delegate(QObject * parent = nullptr); + ~IpV4Delegate() override; - QWidget * createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE; + QWidget * createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override; }; #endif diff --git a/libs/editor/widgets/ipv4routeswidget.h b/libs/editor/widgets/ipv4routeswidget.h index d6012a14..272390bd 100644 --- a/libs/editor/widgets/ipv4routeswidget.h +++ b/libs/editor/widgets/ipv4routeswidget.h @@ -1,61 +1,61 @@ /* Copyright 2011 Ilia Kats 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef IPV4ROUTESWIDGET_H #define IPV4ROUTESWIDGET_H #include #include #include class QStandardItem; class QItemSelection; class IpV4RoutesWidget : public QDialog { Q_OBJECT public: - explicit IpV4RoutesWidget(QWidget * parent = 0); - virtual ~IpV4RoutesWidget(); + explicit IpV4RoutesWidget(QWidget * parent = nullptr); + ~IpV4RoutesWidget() override; void setRoutes(const QList &list); QList routes(); void setNeverDefault(bool checked); bool neverDefault() const; void setIgnoreAutoRoutes(bool checked); void setIgnoreAutoRoutesCheckboxEnabled(bool enabled); bool ignoreautoroutes() const; private Q_SLOTS: void addRoute(); void removeRoute(); /** * Update remove IP button depending on if there is a selection */ void selectionChanged(const QItemSelection &); void tableViewItemChanged(QStandardItem *); private: class Private; Private *d; }; #endif // IPV4ROUTESWIDGET_H diff --git a/libs/editor/widgets/ipv6delegate.h b/libs/editor/widgets/ipv6delegate.h index c5da9e12..eb01d261 100644 --- a/libs/editor/widgets/ipv6delegate.h +++ b/libs/editor/widgets/ipv6delegate.h @@ -1,39 +1,39 @@ /* Copyright 2011 Ilia Kats 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef IPV6DELEGATE_H #define IPV6DELEGATE_H #include #include #include "delegate.h" class IpV6Delegate : public Delegate { Q_OBJECT public: - explicit IpV6Delegate(QObject * parent = 0); - virtual ~IpV6Delegate(); + explicit IpV6Delegate(QObject * parent = nullptr); + ~IpV6Delegate() override; - QWidget * createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE; + QWidget * createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override; }; #endif diff --git a/libs/editor/widgets/ipv6routeswidget.h b/libs/editor/widgets/ipv6routeswidget.h index 33de1aa6..79d75cec 100644 --- a/libs/editor/widgets/ipv6routeswidget.h +++ b/libs/editor/widgets/ipv6routeswidget.h @@ -1,61 +1,61 @@ /* Copyright 2011 Ilia Kats 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef IPV6ROUTESWIDGET_H #define IPV6ROUTESWIDGET_H #include #include #include class QStandardItem; class QItemSelection; class IpV6RoutesWidget : public QDialog { Q_OBJECT public: - explicit IpV6RoutesWidget(QWidget * parent = 0); - virtual ~IpV6RoutesWidget(); + explicit IpV6RoutesWidget(QWidget * parent = nullptr); + ~IpV6RoutesWidget() override; void setRoutes(const QList &list); QList routes(); void setNeverDefault(bool checked); bool neverDefault() const; void setIgnoreAutoRoutes(bool checked); void setIgnoreAutoRoutesCheckboxEnabled(bool enabled); bool ignoreautoroutes() const; private Q_SLOTS: void addRoute(); void removeRoute(); /** * Update remove IP button depending on if there is a selection */ void selectionChanged(const QItemSelection &); void tableViewItemChanged(QStandardItem *); private: class Private; Private *d; }; #endif // IPV6ROUTESWIDGET_H diff --git a/libs/editor/widgets/mobileconnectionwizard.cpp b/libs/editor/widgets/mobileconnectionwizard.cpp index 8eff06c1..bc1dbb85 100644 --- a/libs/editor/widgets/mobileconnectionwizard.cpp +++ b/libs/editor/widgets/mobileconnectionwizard.cpp @@ -1,573 +1,573 @@ /* Copyright 2010-2012 Lamarque Souza Copyright 2013 Lukas Tinkl 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include "mobileconnectionwizard.h" #include "uiutils.h" #include #include #include #include #include #include #include #define NUMBER_OF_STATIC_ENTRIES 3 MobileConnectionWizard::MobileConnectionWizard(NetworkManager::ConnectionSettings::ConnectionType connectionType, QWidget * parent) : QWizard(parent) { if (connectionType == NetworkManager::ConnectionSettings::Unknown) { mInitialMethodType = false; } else { mInitialMethodType = true; if (connectionType == NetworkManager::ConnectionSettings::Bluetooth) { mType = NetworkManager::ConnectionSettings::Gsm; } else { mType = connectionType; } } mProviders = new MobileProviders(); setWindowTitle(i18nc("Mobile Connection Wizard", "New Mobile Broadband Connection")); addPage(createIntroPage()); addPage(createCountryPage()); addPage(createProvidersPage()); addPage(createPlansPage()); addPage(createConfirmPage()); setOptions(QWizard::NoBackButtonOnStartPage); } MobileConnectionWizard::~MobileConnectionWizard() { delete mProviders; } MobileProviders::ErrorCodes MobileConnectionWizard::getError() { if (mProviders) { return mProviders->getError(); } return MobileProviders::Success; } void MobileConnectionWizard::initializePage(int id) { switch (id) { case 1: { // Country Page if (country.isEmpty()) { country = mProviders->countryFromLocale(); } if (country.isEmpty()) mCountryList->setCurrentRow(0); else { QList items = mCountryList->findItems(mProviders->getCountryName(country), Qt::MatchExactly); if (!items.empty()) { mCountryList->setCurrentItem(items.first()); } } if (!mInitialMethodType) { NetworkManager::Device::Ptr iface = NetworkManager::findNetworkInterface(mDeviceComboBox->itemData(mDeviceComboBox->currentIndex()).toString()); if (iface) { NetworkManager::ModemDevice::Ptr nmModemIface = iface.objectCast(); if (nmModemIface && UiUtils::modemSubType(nmModemIface->currentCapabilities()) == NetworkManager::ModemDevice::CdmaEvdo) { mType = NetworkManager::ConnectionSettings::Cdma; } else { mType = NetworkManager::ConnectionSettings::Gsm; } } else { mType = static_cast(mDeviceComboBox->itemData(mDeviceComboBox->currentIndex()).toUInt()); } } if (mProviders->getError() != MobileProviders::Success) { accept(); } break; } case 2: // Providers Page country = mCountryList->currentItem()->text(); mProvidersList->clear(); lineEditProvider->clear(); radioAutoProvider->setChecked(true); switch (type()) { case NetworkManager::ConnectionSettings::Gsm: mProvidersList->insertItems(0, mProviders->getProvidersList(country, NetworkManager::ConnectionSettings::Gsm)); break; case NetworkManager::ConnectionSettings::Cdma: mProvidersList->insertItems(0, mProviders->getProvidersList(country, NetworkManager::ConnectionSettings::Cdma)); break; default: break; } mProvidersList->setCurrentRow(0); if (mProvidersList->count() > 0) { mProvidersList->setEnabled(true); radioAutoProvider->setEnabled(true); mProvidersList->setFocus(); } else { mProvidersList->setEnabled(false); radioAutoProvider->setEnabled(false); radioManualProvider->setChecked(true); // TODO: this does not work, try reimplementing QWizardPage::isComplete() //button(QWizard::NextButton)->setEnabled(false); } break; case 3: // Plans Page - disconnect(mPlanComboBox, static_cast(&KComboBox::currentIndexChanged), this, &MobileConnectionWizard::slotEnablePlanEditBox); + disconnect(mPlanComboBox, QOverload::of(&KComboBox::currentIndexChanged), this, &MobileConnectionWizard::slotEnablePlanEditBox); mPlanComboBox->clear(); if (type() != NetworkManager::ConnectionSettings::Gsm) { goto OUT_3; } if (radioManualProvider->isChecked()) { mPlanComboBox->addItem(i18nc("Mobile Connection Wizard", "My plan is not listed...")); if (lineEditProvider->text().isEmpty()) { lineEditProvider->setText(i18nc("Mobile Connection Wizard", "Unknown Provider")); } } else { - if (mProvidersList->currentItem() != 0) { + if (mProvidersList->currentItem() != nullptr) { const QStringList mApns = mProviders->getApns(mProvidersList->currentItem()->text()); if (!mApns.isEmpty()) { mPlanComboBox->insertItems(0, mApns); mPlanComboBox->setItemText(0, i18nc("Mobile Connection Wizard", "Default")); } } if (mPlanComboBox->count()) { mPlanComboBox->insertSeparator(1); } mPlanComboBox->addItem(i18nc("Mobile Connection Wizard", "My plan is not listed...")); } mPlanComboBox->setCurrentIndex(0); slotEnablePlanEditBox(mPlanComboBox->currentText()); OUT_3: - connect(mPlanComboBox, static_cast(&KComboBox::currentIndexChanged), this, &MobileConnectionWizard::slotEnablePlanEditBox); + connect(mPlanComboBox, QOverload::of(&KComboBox::currentIndexChanged), this, &MobileConnectionWizard::slotEnablePlanEditBox); break; case 4: // Confirm Page if (radioManualProvider->isChecked()) { labelProvider->setText(" " + lineEditProvider->text() + ", " + country); provider = lineEditProvider->text(); } else { labelProvider->setText(" " + mProvidersList->currentItem()->text() + ", " + country); provider = mProvidersList->currentItem()->text(); } if (type() == NetworkManager::ConnectionSettings::Cdma) { labelPlanLabel->hide(); labelPlan->hide(); labelApn->hide(); userApn->clear(); apn.clear(); } else { labelPlanLabel->show(); labelPlan->show(); labelApn->show(); if (mPlanComboBox->currentText() == i18nc("Mobile Connection Wizard", "My plan is not listed...")) { labelPlan->setText(" " + userApn->text()); labelApn->setText(" " + i18nc("Mobile Connection Wizard", "APN: %1", userApn->text())); apn = userApn->text(); } else { int i = mPlanComboBox->currentIndex(); i = i > 1 ? (i-1) : 0; // ignores separator's index (i == 1). QStringList mApns = mProviders->getApns(mProvidersList->currentItem()->text()); labelPlan->setText(" " + mPlanComboBox->currentText()); labelApn->setText(" " + i18nc("Mobile Connection Wizard", "APN: %1", mApns.at(i))); apn = mApns.at(i); } } break; } } int MobileConnectionWizard::nextId() const { // Providers page if (currentId() == 2 && type() != NetworkManager::ConnectionSettings::Gsm) { // Jumps to Confirm page instead of Plans page if type != Gsm. return 4; } else { return QWizard::nextId(); } } QVariantList MobileConnectionWizard::args() { QVariantList temp; switch (type()) { case NetworkManager::ConnectionSettings::Cdma: temp << provider << mProviders->getCdmaInfo(provider); break; case NetworkManager::ConnectionSettings::Gsm: temp << provider /*<< mProviders->getNetworkIds(provider)*/ << mProviders->getApnInfo(apn); break; default: break; } return temp; } /**********************************************************/ /* Intro page */ /**********************************************************/ QWizardPage * MobileConnectionWizard::createIntroPage() { QWizardPage *page = new QWizardPage(); page->setTitle(i18nc("Mobile Connection Wizard", "Set up a Mobile Broadband Connection")); QVBoxLayout *layout = new QVBoxLayout; QLabel *label = new QLabel(i18nc("Mobile Connection Wizard", "This assistant helps you easily set up a mobile broadband connection to a cellular (3G) network.")); label->setWordWrap(true); layout->addWidget(label); label = new QLabel('\n' + i18nc("Mobile Connection Wizard", "You will need the following information:")); layout->addWidget(label); label = new QLabel(QString(" . %1\n . %2\n . %3"). arg(i18nc("Mobile Connection Wizard", "Your broadband provider's name")). arg(i18nc("Mobile Connection Wizard", "Your broadband billing plan name")). arg(i18nc("Mobile Connection Wizard", "(in some cases) Your broadband billing plan APN (Access Point Name)"))); layout->addWidget(label); if (!mInitialMethodType) { label = new QLabel('\n' + i18nc("Mobile Connection Wizard", "Create a connection for &this mobile broadband device:")); layout->addWidget(label); mDeviceComboBox = new KComboBox(); mDeviceComboBox->addItem(i18nc("Mobile Connection Wizard", "Any GSM device")); mDeviceComboBox->setItemData(0, NetworkManager::ConnectionSettings::Gsm); mDeviceComboBox->addItem(i18nc("Mobile Connection Wizard", "Any CDMA device")); mDeviceComboBox->setItemData(1, NetworkManager::ConnectionSettings::Cdma); mDeviceComboBox->insertSeparator(NUMBER_OF_STATIC_ENTRIES-1); label->setBuddy(mDeviceComboBox); layout->addWidget(mDeviceComboBox); connect(NetworkManager::notifier(), &NetworkManager::Notifier::deviceAdded, this, &MobileConnectionWizard::introDeviceAdded); connect(NetworkManager::notifier(), &NetworkManager::Notifier::deviceRemoved, this, &MobileConnectionWizard::introDeviceRemoved); connect(NetworkManager::notifier(), &NetworkManager::Notifier::statusChanged, this, &MobileConnectionWizard::introStatusChanged); introAddInitialDevices(); } page->setLayout(layout); return page; } void MobileConnectionWizard::introAddDevice(const NetworkManager::Device::Ptr &device) { QString desc; ModemManager::ModemDevice::Ptr modem = ModemManager::findModemDevice(device->udi()); if (modem) { ModemManager::Modem::Ptr modemInterface = modem->interface(ModemManager::ModemDevice::ModemInterface).objectCast(); if (modemInterface->powerState() == MM_MODEM_POWER_STATE_ON) { desc.append(modemInterface->manufacturer()); desc.append(" "); desc.append(modemInterface->model()); } else { QString deviceName = modemInterface->device(); Q_FOREACH (const Solid::Device &d, Solid::Device::allDevices()) { if (d.udi().contains(deviceName, Qt::CaseInsensitive)) { deviceName = d.product(); if (!deviceName.startsWith(d.vendor())) { deviceName = d.vendor() + ' ' + deviceName; } desc.append(deviceName); break; } } } } NetworkManager::ModemDevice::Ptr nmModemIface = device.objectCast(); if (!nmModemIface) { return; } if (UiUtils::modemSubType(nmModemIface->currentCapabilities()) == NetworkManager::ModemDevice::GsmUmts) { if (desc.isEmpty()) { desc.append(i18nc("Mobile Connection Wizard", "Installed GSM device")); } } else if (UiUtils::modemSubType(nmModemIface->currentCapabilities()) == NetworkManager::ModemDevice::CdmaEvdo) { if (desc.isEmpty()) { desc.append(i18nc("Mobile Connection Wizard", "Installed CDMA device")); } } else { return; } mDeviceComboBox->addItem(desc, device->uni()); if (mDeviceComboBox->count() == NUMBER_OF_STATIC_ENTRIES) { mDeviceComboBox->setCurrentIndex(0); } else { mDeviceComboBox->setCurrentIndex(NUMBER_OF_STATIC_ENTRIES); } } void MobileConnectionWizard::introDeviceAdded(const QString &uni) { introAddDevice(NetworkManager::findNetworkInterface(uni)); } void MobileConnectionWizard::introDeviceRemoved(const QString &uni) { int index = mDeviceComboBox->findData(uni); mDeviceComboBox->removeItem(index); if (mDeviceComboBox->count() == NUMBER_OF_STATIC_ENTRIES) { mDeviceComboBox->setCurrentIndex(0); if (currentId() > 0) { close(); } } else { mDeviceComboBox->setCurrentIndex(NUMBER_OF_STATIC_ENTRIES); } } void MobileConnectionWizard::introStatusChanged(NetworkManager::Status status) { switch (status) { case NetworkManager::Unknown: case NetworkManager::Asleep: case NetworkManager::Disconnected: case NetworkManager::Disconnecting: introRemoveAllDevices(); break; case NetworkManager::Connecting: case NetworkManager::ConnectedLinkLocal: case NetworkManager::ConnectedSiteOnly: case NetworkManager::Connected: introAddInitialDevices(); break; } } void MobileConnectionWizard::introAddInitialDevices() { Q_FOREACH (const NetworkManager::Device::Ptr & n, NetworkManager::networkInterfaces()) { introAddDevice(n); } if (mDeviceComboBox->count() == NUMBER_OF_STATIC_ENTRIES) { mDeviceComboBox->setCurrentIndex(0); } else { mDeviceComboBox->setCurrentIndex(NUMBER_OF_STATIC_ENTRIES); } } void MobileConnectionWizard::introRemoveAllDevices() { mDeviceComboBox->clear(); mDeviceComboBox->addItem(i18nc("Mobile Connection Wizard", "Any GSM device")); mDeviceComboBox->setItemData(0, NetworkManager::ConnectionSettings::Gsm); mDeviceComboBox->addItem(i18nc("Mobile Connection Wizard", "Any CDMA device")); mDeviceComboBox->setItemData(1, NetworkManager::ConnectionSettings::Cdma); mDeviceComboBox->insertSeparator(NUMBER_OF_STATIC_ENTRIES-1); mDeviceComboBox->setCurrentIndex(0); } /**********************************************************/ /* Country page */ /**********************************************************/ QWizardPage * MobileConnectionWizard::createCountryPage() { QWizardPage *page = new QWizardPage(); page->setTitle(i18nc("Mobile Connection Wizard", "Choose your Provider's Country")); QVBoxLayout *layout = new QVBoxLayout; QLabel *label = new QLabel(i18nc("Mobile Connection Wizard", "Country List:")); layout->addWidget(label); mCountryList = new QListWidget(); mCountryList->addItem(i18nc("Mobile Connection Wizard", "My country is not listed")); mCountryList->insertItems(1, mProviders->getCountryList()); layout->addWidget(mCountryList); page->setLayout(layout); return page; } /**********************************************************/ /* Providers page */ /**********************************************************/ QWizardPage * MobileConnectionWizard::createProvidersPage() { QWizardPage *page = new QWizardPage(); page->setTitle(i18nc("Mobile Connection Wizard", "Choose your Provider")); QVBoxLayout *layout = new QVBoxLayout; radioAutoProvider = new QRadioButton(i18nc("Mobile Connection Wizard", "Select your provider from a &list:")); radioAutoProvider->setChecked(true); layout->addWidget(radioAutoProvider); mProvidersList = new QListWidget(); connect(mProvidersList, &QListWidget::itemSelectionChanged, this, &MobileConnectionWizard::slotCheckProviderList); connect(mProvidersList, &QListWidget::itemClicked, this, &MobileConnectionWizard::slotCheckProviderList); layout->addWidget(mProvidersList); radioManualProvider = new QRadioButton(i18nc("Mobile Connection Wizard", "I cannot find my provider and I wish to enter it &manually:")); layout->addWidget(radioManualProvider); connect(radioManualProvider, &QRadioButton::toggled, this, &MobileConnectionWizard::slotEnableProviderEdit); lineEditProvider = new KLineEdit(); layout->addWidget(lineEditProvider); connect(lineEditProvider, &KLineEdit::textEdited, this, &MobileConnectionWizard::slotCheckProviderEdit); page->setLayout(layout); return page; } void MobileConnectionWizard::slotEnableProviderEdit(bool checked) { if (checked) { lineEditProvider->setFocus(); } else { mProvidersList->setFocus(); } } void MobileConnectionWizard::slotCheckProviderEdit() { radioManualProvider->setChecked(true); // TODO: this does not work, try reimplementing QWizardPage::isComplete() //button(QWizard::NextButton)->setEnabled(true); } void MobileConnectionWizard::slotCheckProviderList() { radioAutoProvider->setChecked(true); lineEditProvider->clear(); } /**********************************************************/ /* Plan page */ /**********************************************************/ QWizardPage * MobileConnectionWizard::createPlansPage() { QWizardPage *page = new QWizardPage(); page->setTitle(i18nc("Mobile Connection Wizard", "Choose your Billing Plan")); QBoxLayout *layout = new QBoxLayout(QBoxLayout::TopToBottom); QLabel *label = new QLabel(i18nc("Mobile Connection Wizard", "&Select your plan:")); layout->addWidget(label); mPlanComboBox = new KComboBox(); label->setBuddy(mPlanComboBox); layout->addWidget(mPlanComboBox); label = new QLabel('\n' + i18nc("Mobile Connection Wizard", "Selected plan &APN (Access Point Name):")); layout->addWidget(label); userApn = new KLineEdit(); userApn->setEnabled(false); label->setBuddy(userApn); layout->addWidget(userApn); QHBoxLayout *layout2 = new QHBoxLayout(); label = new QLabel(); label->setPixmap(KIconLoader::global()->loadIcon("dialog-warning", KIconLoader::Dialog)); layout2->addWidget(label, 0, Qt::AlignTop); label = new QLabel(i18nc("Mobile Connection Wizard", "Warning: Selecting an incorrect plan may result in billing issues for your broadband account or may prevent connectivity.\n\nIf you are unsure of your plan please ask your provider for your plan's APN.")); label->setWordWrap(true); layout2->addWidget(label); layout->addWidget(new QLabel("")); layout->addLayout(layout2); page->setLayout(layout); return page; } void MobileConnectionWizard::slotEnablePlanEditBox(const QString & text) { if (type() != NetworkManager::ConnectionSettings::Gsm) { return; } if (text == i18nc("Mobile Connection Wizard", "My plan is not listed...")) { userApn->clear(); userApn->setEnabled(true); } else { - if (mProvidersList->currentItem() != 0) { + if (mProvidersList->currentItem() != nullptr) { int i = mPlanComboBox->currentIndex(); if (i>0) i=i-1; // Skiping the separator (i==1) QStringList mApns = mProviders->getApns(mProvidersList->currentItem()->text()); userApn->setText(mApns.at(i)); } userApn->setEnabled(false); } } /**********************************************************/ /* Confirm page */ /**********************************************************/ QWizardPage * MobileConnectionWizard::createConfirmPage() { QWizardPage *page = new QWizardPage(); page->setTitle(i18nc("Mobile Connection Wizard", "Confirm Mobile Broadband Settings")); QVBoxLayout *layout = new QVBoxLayout; QLabel *label = new QLabel(i18nc("Mobile Connection Wizard", "Your mobile broadband connection is configured with the following settings:")); label->setWordWrap(true); layout->addWidget(label); label = new QLabel('\n' + i18nc("Mobile Connection Wizard", "Your Provider:")); layout->addWidget(label); labelProvider = new QLabel(); layout->addWidget(labelProvider); labelPlanLabel = new QLabel('\n' + i18nc("Mobile Connection Wizard", "Your Plan:")); layout->addWidget(labelPlanLabel); labelPlan = new QLabel(); layout->addWidget(labelPlan); labelApn = new QLabel(); labelApn->setEnabled(false); layout->addWidget(labelApn); page->setLayout(layout); return page; } diff --git a/libs/editor/widgets/mobileconnectionwizard.h b/libs/editor/widgets/mobileconnectionwizard.h index a2005027..bc22da02 100644 --- a/libs/editor/widgets/mobileconnectionwizard.h +++ b/libs/editor/widgets/mobileconnectionwizard.h @@ -1,115 +1,115 @@ /* Copyright 2010-2011 Lamarque Souza Copyright 2013 Lukas Tinkl 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef PLASMA_NM_MOBILE_CONNECTION_WIZARD_H #define PLASMA_NM_MOBILE_CONNECTION_WIZARD_H #include #include #include #include #include #include #include #include #include "mobileproviders.h" class Q_DECL_EXPORT MobileConnectionWizard : public QWizard { Q_OBJECT public: /* * Do not use NetworkManager::ConnectionSettings::Bluetooth here, use either NetworkManager::ConnectionSettings::Gsm * or NetworkManager::ConnectionSettings::Cdma. */ explicit MobileConnectionWizard(NetworkManager::ConnectionSettings::ConnectionType connectionType = NetworkManager::ConnectionSettings::Unknown, - QWidget * parent = 0); - ~MobileConnectionWizard(); + QWidget * parent = nullptr); + ~MobileConnectionWizard() override; /* * Returns the information to configure one connection from the last wizard run. * The format is: * for GSM connections: provider's name + QList of Gsm NetworkIds for that provider (can be an empty QList) + QMap with apn information * where apn information is: dial number + apn + apn name (optional) + username (optional) + password (optional) + QList of name servers (optional) * * for CDMA connections: provider's name + QMap with cdma information. * where cdma information is: name (optional) + username (optional) + password (optional) + list of sids (optional) */ QVariantList args(); NetworkManager::ConnectionSettings::ConnectionType type() const { return mType; } MobileProviders::ErrorCodes getError(); private Q_SLOTS: void introDeviceAdded(const QString &uni); void introDeviceRemoved(const QString &uni); void introStatusChanged(NetworkManager::Status); void slotEnablePlanEditBox(const QString & text); void slotEnableProviderEdit(bool enable); void slotCheckProviderEdit(); void slotCheckProviderList(); private: QWizardPage * createIntroPage(); QWizardPage * createCountryPage(); QWizardPage * createProvidersPage(); QWizardPage * createPlansPage(); QWizardPage * createConfirmPage(); - void initializePage(int id); - int nextId() const; + void initializePage(int id) override; + int nextId() const override; MobileProviders * mProviders; QString getCountryFromLocale(); QString country; QString provider; QString apn; NetworkManager::ConnectionSettings::ConnectionType mType; bool mInitialMethodType; // Intro page KComboBox * mDeviceComboBox; void introAddInitialDevices(); void introRemoveAllDevices(); void introAddDevice(const NetworkManager::Device::Ptr &device); // Country page QListWidget * mCountryList; // Providers page QListWidget * mProvidersList; QRadioButton * radioAutoProvider; QRadioButton * radioManualProvider; KLineEdit * lineEditProvider; // Plan page KComboBox * mPlanComboBox; KLineEdit * userApn; // Confirm page QLabel * labelProvider; QLabel * labelPlanLabel; QLabel * labelPlan; QLabel * labelApn; }; #endif // PLASMA_NM_MOBILE_CONNECTION_WIZARD_H diff --git a/libs/editor/widgets/passwordfield.cpp b/libs/editor/widgets/passwordfield.cpp index 3e3b6741..c70c294d 100644 --- a/libs/editor/widgets/passwordfield.cpp +++ b/libs/editor/widgets/passwordfield.cpp @@ -1,166 +1,166 @@ /* Copyright 2015 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "passwordfield.h" #include #include #include #include -#include +#include PasswordField::PasswordField(QWidget *parent, Qt::WindowFlags f) : QWidget(parent, f) , m_currentPasswordOption(StoreForUser) { m_layout = new QVBoxLayout(this); // The widget will be already in layout, thus reset content margins // to align it with the rest of widgets m_layout->setContentsMargins(0, 0, 0, 0); m_passwordField = new QLineEdit(this); connect(m_passwordField, &QLineEdit::textChanged, this, &PasswordField::textChanged); if (KAuthorized::authorize(QStringLiteral("lineedit_reveal_password"))) { m_toggleEchoModeAction = m_passwordField->addAction(QIcon::fromTheme(QStringLiteral("visibility")), QLineEdit::TrailingPosition); m_toggleEchoModeAction->setVisible(false); m_toggleEchoModeAction->setToolTip(i18n("Change the visibility of the password")); connect(m_passwordField, &QLineEdit::textChanged, this, &PasswordField::showToggleEchoModeAction); connect(m_toggleEchoModeAction, &QAction::triggered, this, &PasswordField::toggleEchoMode); } m_layout->addWidget(m_passwordField); m_passwordOptionsMenu = new QComboBox(this); m_passwordOptionsMenu->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLength); m_passwordOptionsMenu->addItem(QIcon::fromTheme(QStringLiteral("document-save")), i18n("Store password for this user only (encrypted)"), StoreForUser); m_passwordOptionsMenu->addItem(QIcon::fromTheme(QStringLiteral("document-save-all")), i18n("Store password for all users (not encrypted)"), StoreForAllUsers); m_passwordOptionsMenu->addItem(QIcon::fromTheme(QStringLiteral("dialog-messages")), i18n("Ask for this password every time"), AlwaysAsk); // Do not add by default // m_passwordOptionsMenu->addItem(QIcon::fromTheme(QStringLiteral("document-close")), i18n("This password is not required"), NotRequired); if (KWallet::Wallet::isEnabled()) { m_passwordOptionsMenu->setCurrentIndex(0); } else { m_passwordOptionsMenu->setCurrentIndex(1); m_currentPasswordOption = StoreForAllUsers; } - connect(m_passwordOptionsMenu, static_cast(&QComboBox::currentIndexChanged), this, &PasswordField::changePasswordOption); + connect(m_passwordOptionsMenu, QOverload::of(&QComboBox::currentIndexChanged), this, &PasswordField::changePasswordOption); // Disable by default m_passwordOptionsMenu->setVisible(false); // m_layout->addWidget(m_passwordOptionsMenu); setLayout(m_layout); } void PasswordField::setMaxLength(int maxLength) { m_passwordField->setMaxLength(maxLength); } void PasswordField::setPasswordModeEnabled(bool enable) { m_passwordField->setEchoMode(enable ? QLineEdit::Password : QLineEdit::Normal); } void PasswordField::setPasswordOptionsEnabled(bool enable) { if (enable) { m_layout->addWidget(m_passwordOptionsMenu); m_passwordOptionsMenu->setVisible(true); } else { m_layout->removeWidget(m_passwordOptionsMenu); m_passwordOptionsMenu->setVisible(false); } } void PasswordField::setPasswordNotRequiredEnabled(bool enable) { if (enable) { const int index = m_passwordOptionsMenu->findData(NotRequired); if (index == -1) { m_passwordOptionsMenu->addItem(QIcon::fromTheme(QStringLiteral("document-close")), i18n("This password is not required"), NotRequired); } } else { const int index = m_passwordOptionsMenu->findData(NotRequired); if (index != -1) { m_passwordOptionsMenu->removeItem(index); } } } void PasswordField::setText(const QString &text) { m_passwordField->setText(text); } QString PasswordField::text() const { return m_passwordField->text(); } PasswordField::PasswordOption PasswordField::passwordOption() const { return m_currentPasswordOption; } void PasswordField::setPasswordOption(PasswordField::PasswordOption option) { const int index = m_passwordOptionsMenu->findData(option); if (index != -1) { m_passwordOptionsMenu->setCurrentIndex(index); } } void PasswordField::showToggleEchoModeAction(const QString &text) { m_toggleEchoModeAction->setVisible(!text.isEmpty()); } void PasswordField::toggleEchoMode() { if (m_passwordField->echoMode() == QLineEdit::Password) { m_passwordField->setEchoMode(QLineEdit::Normal); m_toggleEchoModeAction->setIcon(QIcon::fromTheme(QStringLiteral("hint"))); } else if (m_passwordField->echoMode() == QLineEdit::Normal) { m_passwordField->setEchoMode(QLineEdit::Password); m_toggleEchoModeAction->setIcon(QIcon::fromTheme(QStringLiteral("visibility"))); } } void PasswordField::changePasswordOption(int index) { Q_UNUSED(index); m_currentPasswordOption = (PasswordOption)m_passwordOptionsMenu->currentData().toUInt(); if (m_currentPasswordOption == PasswordField::NotRequired || m_currentPasswordOption == PasswordField::AlwaysAsk) { m_passwordField->clear(); m_passwordField->setDisabled(true); } else { m_passwordField->setEnabled(true); } Q_EMIT passwordOptionChanged(m_currentPasswordOption); } diff --git a/libs/editor/widgets/passwordfield.h b/libs/editor/widgets/passwordfield.h index cc1c86b3..65bd04bc 100644 --- a/libs/editor/widgets/passwordfield.h +++ b/libs/editor/widgets/passwordfield.h @@ -1,71 +1,71 @@ /* Copyright 2015 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_PASSWORD_FIELD_H #define PLASMA_NM_PASSWORD_FIELD_H #include #include #include class Q_DECL_EXPORT PasswordField : public QWidget { Q_OBJECT Q_PROPERTY(bool passwordModeEnabled WRITE setPasswordModeEnabled) public: enum PasswordOption { StoreForUser, StoreForAllUsers, AlwaysAsk, NotRequired }; - explicit PasswordField(QWidget *parent = 0, Qt::WindowFlags f = Qt::WindowFlags()); + explicit PasswordField(QWidget *parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); void setMaxLength(int maxLength); void setPasswordModeEnabled(bool passwordMode); void setPasswordOptionsEnabled(bool enable); void setPasswordNotRequiredEnabled(bool enable); PasswordOption passwordOption() const; void setPasswordOption(PasswordOption option); void setText(const QString &text); QString text() const; private Q_SLOTS: void changePasswordOption(int index); void showToggleEchoModeAction(const QString &text); void toggleEchoMode(); Q_SIGNALS: void textChanged(const QString &text); void passwordOptionChanged(PasswordOption option); private: PasswordOption m_currentPasswordOption; QVBoxLayout *m_layout; QLineEdit *m_passwordField; QComboBox *m_passwordOptionsMenu; QAction *m_toggleEchoModeAction; }; #endif // PLASMA_NM_PASSWORD_FIELD_H diff --git a/libs/editor/widgets/settingwidget.cpp b/libs/editor/widgets/settingwidget.cpp index 15e13625..b553dce8 100644 --- a/libs/editor/widgets/settingwidget.cpp +++ b/libs/editor/widgets/settingwidget.cpp @@ -1,142 +1,142 @@ /* Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "settingwidget.h" #include "bssidcombobox.h" #include "hwaddrcombobox.h" #include "ssidcombobox.h" #include "passwordfield.h" #include #include #include #include #include #include #include SettingWidget::SettingWidget(const NetworkManager::Setting::Ptr &setting, QWidget* parent, Qt::WindowFlags f): QWidget(parent, f), m_type(setting->name()) { } SettingWidget::~SettingWidget() { } void SettingWidget::loadConfig(const NetworkManager::Setting::Ptr &setting) { Q_UNUSED(setting); } void SettingWidget::loadSecrets(const NetworkManager::Setting::Ptr &setting) { Q_UNUSED(setting); } void SettingWidget::watchChangedSetting() { // Attempt to connect to all widgets representing various configurations // to notify about setting change /************ Qt Widgets ************/ // Connect all QLineEdit widgets QList lineEdits = findChildren(); Q_FOREACH (QLineEdit *lineedit, lineEdits) { connect(lineedit, &QLineEdit::textChanged, this, &SettingWidget::settingChanged); } // Connect all QComboBox widgets QList comboboxes = findChildren(); Q_FOREACH (QComboBox *combobox, comboboxes) { - connect(combobox, static_cast(&QComboBox::currentIndexChanged), this, &SettingWidget::settingChanged); + connect(combobox, QOverload::of(&QComboBox::currentIndexChanged), this, &SettingWidget::settingChanged); connect(combobox, &QComboBox::currentTextChanged, this, &SettingWidget::settingChanged); } // Connect all QCheckBox widgets QList checkboxes = findChildren(); Q_FOREACH (QCheckBox *checkbox, checkboxes) { connect(checkbox, &QCheckBox::stateChanged, this, &SettingWidget::settingChanged); } // Connect all QPushButton widgets QList pushbuttons = findChildren(); Q_FOREACH (QPushButton *pushbutton, pushbuttons) { connect(pushbutton, &QPushButton::clicked, this, &SettingWidget::settingChanged); } // Connect all QSpinBox widgets QList spinboxes = findChildren(); Q_FOREACH (QSpinBox *spinbox, spinboxes) { - connect(spinbox, static_cast(&QSpinBox::valueChanged), this, &SettingWidget::settingChanged); + connect(spinbox, QOverload::of(&QSpinBox::valueChanged), this, &SettingWidget::settingChanged); } // Connect all KUrlRequester widgets QList urlrequesters = findChildren(); Q_FOREACH (KUrlRequester *urlrequester, urlrequesters) { connect(urlrequester, &KUrlRequester::textChanged, this, &SettingWidget::settingChanged); connect(urlrequester, &KUrlRequester::urlSelected, this, &SettingWidget::settingChanged); } // Connect all QTableView widgets QList tableviews = findChildren(); Q_FOREACH(QTableView *tableview, tableviews) { connect(tableview, &QTableView::clicked, this, &SettingWidget::settingChanged); } /********** OUR CUSTOM WIDGETS **********/ // Connect all PasswordField widgets QList passwordfields = findChildren(); Q_FOREACH (PasswordField *passwordfield, passwordfields) { connect(passwordfield, &PasswordField::textChanged, this, &SettingWidget::settingChanged); connect(passwordfield, &PasswordField::passwordOptionChanged, this, &SettingWidget::settingChanged); } // Connect all HwAddrComboBox widgets QList hwAddrcomboboxes = findChildren(); Q_FOREACH (HwAddrComboBox *combobox, hwAddrcomboboxes) { connect(combobox, &HwAddrComboBox::hwAddressChanged, this, &SettingWidget::settingChanged); } // Connect all SssidComboBox widgets QList ssidcomboboxes = findChildren(); Q_FOREACH (SsidComboBox *combobox, ssidcomboboxes) { connect(combobox, &SsidComboBox::ssidChanged, this, &SettingWidget::settingChanged); } // Connect all BssidComboBox widgets QList bssidcomboboxes = findChildren(); Q_FOREACH (BssidComboBox *combobox, bssidcomboboxes) { connect(combobox, &BssidComboBox::bssidChanged, this, &SettingWidget::settingChanged); } } QString SettingWidget::type() const { return m_type; } void SettingWidget::slotWidgetChanged() { Q_EMIT validChanged(isValid()); } diff --git a/libs/editor/widgets/settingwidget.h b/libs/editor/widgets/settingwidget.h index 5f2338d1..fd06e115 100644 --- a/libs/editor/widgets/settingwidget.h +++ b/libs/editor/widgets/settingwidget.h @@ -1,64 +1,64 @@ /* Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef SETTING_WIDGET_H #define SETTING_WIDGET_H #include #include #include class Q_DECL_EXPORT SettingWidget : public QWidget { Q_OBJECT public: class EnumPasswordStorageType { public: enum PasswordStorageType {Store = 0, AlwaysAsk, NotRequired}; }; - explicit SettingWidget(const NetworkManager::Setting::Ptr &setting = NetworkManager::Setting::Ptr(), QWidget* parent = 0, Qt::WindowFlags f = 0); - virtual ~SettingWidget(); + explicit SettingWidget(const NetworkManager::Setting::Ptr &setting = NetworkManager::Setting::Ptr(), QWidget* parent = nullptr, Qt::WindowFlags f = {}); + ~SettingWidget() override; virtual void loadConfig(const NetworkManager::Setting::Ptr &setting); virtual void loadSecrets(const NetworkManager::Setting::Ptr &setting); virtual QVariantMap setting() const = 0; // Do not forget to call this function in the inherited class once initialized void watchChangedSetting(); QString type() const; virtual bool isValid() const { return true; } protected Q_SLOTS: void slotWidgetChanged(); Q_SIGNALS: void validChanged(bool isValid); void settingChanged(); private: QString m_type; }; #endif // SETTING_WIDGET_H diff --git a/libs/editor/widgets/ssidcombobox.cpp b/libs/editor/widgets/ssidcombobox.cpp index c1c501a7..6504ce56 100644 --- a/libs/editor/widgets/ssidcombobox.cpp +++ b/libs/editor/widgets/ssidcombobox.cpp @@ -1,148 +1,148 @@ /* Copyright 2013 Lukas Tinkl Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "ssidcombobox.h" #include "uiutils.h" #include #include #include bool signalCompare(const NetworkManager::WirelessNetwork::Ptr & one, const NetworkManager::WirelessNetwork::Ptr & two) { return one->signalStrength() > two->signalStrength(); } SsidComboBox::SsidComboBox(QWidget *parent) : KComboBox(parent) { setEditable(true); setInsertPolicy(QComboBox::NoInsert); connect(this, &SsidComboBox::editTextChanged, this, &SsidComboBox::slotEditTextChanged); - connect(this, static_cast(&SsidComboBox::activated), this, &SsidComboBox::slotCurrentIndexChanged); + connect(this, QOverload::of(&SsidComboBox::activated), this, &SsidComboBox::slotCurrentIndexChanged); } QString SsidComboBox::ssid() const { if (currentIndex() == 0 || currentText() != itemData(currentIndex()).toString()) { return currentText(); } else { return itemData(currentIndex()).toString(); } } void SsidComboBox::slotEditTextChanged(const QString &text) { if (!text.contains(QLatin1String("Security:")) && !text.contains(QLatin1String("Frequency:"))) { Q_EMIT ssidChanged(); } } void SsidComboBox::slotCurrentIndexChanged(int) { setEditText(itemData(currentIndex()).toString()); } void SsidComboBox::init(const QString &ssid) { m_initialSsid = ssid; // qCDebug(PLASMA_NM) << "Initial ssid:" << m_initialSsid; QList networks; Q_FOREACH (const NetworkManager::Device::Ptr & device, NetworkManager::networkInterfaces()) { if (device->type() == NetworkManager::Device::Wifi) { NetworkManager::WirelessDevice::Ptr wifiDevice = device.objectCast(); Q_FOREACH (const NetworkManager::WirelessNetwork::Ptr & newNetwork, wifiDevice->networks()) { bool found = false; Q_FOREACH (const NetworkManager::WirelessNetwork::Ptr & existingNetwork, networks) { if (newNetwork->ssid() == existingNetwork->ssid()) { if (newNetwork->signalStrength() > existingNetwork->signalStrength()) { networks.removeOne(existingNetwork); break; } else { found = true; break; } } } if (!found) { networks << newNetwork; } } } } qSort(networks.begin(), networks.end(), signalCompare); addSsidsToCombo(networks); int index = findData(m_initialSsid); if (index == -1) { insertItem(0, m_initialSsid, m_initialSsid); setCurrentIndex(0); } else { setCurrentIndex(index); } setEditText(m_initialSsid); } void SsidComboBox::addSsidsToCombo(const QList &networks) { QList wifiDevices; Q_FOREACH (const NetworkManager::Device::Ptr & dev, NetworkManager::networkInterfaces()) { if (dev->type() == NetworkManager::Device::Wifi) { wifiDevices << dev.objectCast(); } } bool empty = true; Q_FOREACH (const NetworkManager::WirelessNetwork::Ptr & network, networks) { NetworkManager::AccessPoint::Ptr accessPoint = network->referenceAccessPoint(); if (!accessPoint) { continue; } Q_FOREACH (const NetworkManager::WirelessDevice::Ptr & wifiDev, wifiDevices) { if (wifiDev->findNetwork(network->ssid()) == network) { if (!empty) { insertSeparator(count()); } empty = false; NetworkManager::WirelessSecurityType security = NetworkManager::findBestWirelessSecurity(wifiDev->wirelessCapabilities(), true, (wifiDev->mode() == NetworkManager::WirelessDevice::Adhoc), accessPoint->capabilities(), accessPoint->wpaFlags(), accessPoint->rsnFlags()); if (security != NetworkManager::UnknownSecurity && security != NetworkManager::NoneSecurity) { const QString text = i18n("%1 (%2%)\nSecurity: %3\nFrequency: %4 Mhz", accessPoint->ssid(), network->signalStrength(), UiUtils::labelFromWirelessSecurity(security), accessPoint->frequency()); addItem(QIcon::fromTheme("object-locked"), text, accessPoint->ssid()); } else { const QString text = i18n("%1 (%2%)\nSecurity: Insecure\nFrequency: %3 Mhz", accessPoint->ssid(), network->signalStrength(), accessPoint->frequency()); addItem(QIcon::fromTheme("object-unlocked"), text, accessPoint->ssid()); } } } } } diff --git a/libs/editor/widgets/ssidcombobox.h b/libs/editor/widgets/ssidcombobox.h index 056a1395..d7e9dd97 100644 --- a/libs/editor/widgets/ssidcombobox.h +++ b/libs/editor/widgets/ssidcombobox.h @@ -1,51 +1,51 @@ /* Copyright 2013 Lukas Tinkl Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_SSIDCOMBOBOX_H #define PLASMA_NM_SSIDCOMBOBOX_H #include #include class Q_DECL_EXPORT SsidComboBox : public KComboBox { Q_OBJECT public: - explicit SsidComboBox(QWidget *parent = 0); + explicit SsidComboBox(QWidget *parent = nullptr); void init(const QString & ssid); QString ssid() const; Q_SIGNALS: void ssidChanged(); private Q_SLOTS: void slotEditTextChanged(const QString &text); void slotCurrentIndexChanged(int); private: void addSsidsToCombo(const QList &networks); QString m_initialSsid; }; #endif // PLASMA_NM_SSIDCOMBOBOX_H diff --git a/libs/handler.cpp b/libs/handler.cpp index ce6287cb..b434c469 100644 --- a/libs/handler.cpp +++ b/libs/handler.cpp @@ -1,523 +1,523 @@ /* Copyright 2013-2014 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "handler.h" #include "connectioneditordialog.h" #include "uiutils.h" #include "debug.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if WITH_MODEMMANAGER_SUPPORT #include #include #endif #include #include #include #include #include #include #include #include #include #include #include -#include +#include #define AGENT_SERVICE "org.kde.kded5" #define AGENT_PATH "/modules/networkmanagement" #define AGENT_IFACE "org.kde.plasmanetworkmanagement" Handler::Handler(QObject *parent) : QObject(parent) , m_tmpWirelessEnabled(NetworkManager::isWirelessEnabled()) , m_tmpWwanEnabled(NetworkManager::isWwanEnabled()) { initKdedModule(); QDBusConnection::sessionBus().connect(QStringLiteral(AGENT_SERVICE), QStringLiteral(AGENT_PATH), QStringLiteral(AGENT_IFACE), QStringLiteral("registered"), this, SLOT(initKdedModule())); } Handler::~Handler() { } void Handler::activateConnection(const QString& connection, const QString& device, const QString& specificObject) { NetworkManager::Connection::Ptr con = NetworkManager::findConnection(connection); if (!con) { qCWarning(PLASMA_NM) << "Not possible to activate this connection"; return; } if (con->settings()->connectionType() == NetworkManager::ConnectionSettings::Vpn) { NetworkManager::VpnSetting::Ptr vpnSetting = con->settings()->setting(NetworkManager::Setting::Vpn).staticCast(); if (vpnSetting) { qCDebug(PLASMA_NM) << "Checking VPN" << con->name() << "type:" << vpnSetting->serviceType(); // get the list of supported VPN service types const KService::List services = KServiceTypeTrader::self()->query("PlasmaNetworkManagement/VpnUiPlugin", QString::fromLatin1("[X-NetworkManager-Services]=='%1'").arg(vpnSetting->serviceType())); if (services.isEmpty()) { qCWarning(PLASMA_NM) << "VPN" << vpnSetting->serviceType() << "not found, skipping"; KNotification *notification = new KNotification("MissingVpnPlugin", KNotification::CloseOnTimeout, this); notification->setComponentName("networkmanagement"); notification->setTitle(con->name()); notification->setText(i18n("Missing VPN plugin")); notification->setPixmap(QIcon::fromTheme("dialog-warning").pixmap(KIconLoader::SizeHuge)); notification->sendEvent(); return; } } } #if WITH_MODEMMANAGER_SUPPORT if (con->settings()->connectionType() == NetworkManager::ConnectionSettings::Gsm) { NetworkManager::ModemDevice::Ptr nmModemDevice = NetworkManager::findNetworkInterface(device).objectCast(); if (nmModemDevice) { ModemManager::ModemDevice::Ptr mmModemDevice = ModemManager::findModemDevice(nmModemDevice->udi()); if (mmModemDevice) { ModemManager::Modem::Ptr modem = mmModemDevice->interface(ModemManager::ModemDevice::ModemInterface).objectCast(); NetworkManager::GsmSetting::Ptr gsmSetting = con->settings()->setting(NetworkManager::Setting::Gsm).staticCast(); if (gsmSetting && gsmSetting->pinFlags() == NetworkManager::Setting::NotSaved && modem && modem->unlockRequired() > MM_MODEM_LOCK_NONE) { QDBusInterface managerIface("org.kde.plasmanetworkmanagement", "/org/kde/plasmanetworkmanagement", "org.kde.plasmanetworkmanagement", QDBusConnection::sessionBus(), this); managerIface.call("unlockModem", mmModemDevice->uni()); connect(modem.data(), &ModemManager::Modem::unlockRequiredChanged, this, &Handler::unlockRequiredChanged); m_tmpConnectionPath = connection; m_tmpDevicePath = device; m_tmpSpecificPath = specificObject; return; } } } } #endif QDBusPendingReply reply = NetworkManager::activateConnection(connection, device, specificObject); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this); watcher->setProperty("action", Handler::ActivateConnection); watcher->setProperty("connection", con->name()); connect(watcher, &QDBusPendingCallWatcher::finished, this, &Handler::replyFinished); } void Handler::addAndActivateConnection(const QString& device, const QString& specificObject, const QString& password) { NetworkManager::AccessPoint::Ptr ap; NetworkManager::WirelessDevice::Ptr wifiDev; Q_FOREACH (const NetworkManager::Device::Ptr & dev, NetworkManager::networkInterfaces()) { if (dev->type() == NetworkManager::Device::Wifi) { wifiDev = dev.objectCast(); ap = wifiDev->findAccessPoint(specificObject); if (ap) { break; } } } if (!ap) { return; } NetworkManager::ConnectionSettings::Ptr settings = NetworkManager::ConnectionSettings::Ptr(new NetworkManager::ConnectionSettings(NetworkManager::ConnectionSettings::Wireless)); settings->setId(ap->ssid()); settings->setUuid(NetworkManager::ConnectionSettings::createNewUuid()); settings->setAutoconnect(true); settings->addToPermissions(KUser().loginName(), QString()); NetworkManager::WirelessSetting::Ptr wifiSetting = settings->setting(NetworkManager::Setting::Wireless).dynamicCast(); wifiSetting->setInitialized(true); wifiSetting = settings->setting(NetworkManager::Setting::Wireless).dynamicCast(); wifiSetting->setSsid(ap->ssid().toUtf8()); if (ap->mode() == NetworkManager::AccessPoint::Adhoc) { wifiSetting->setMode(NetworkManager::WirelessSetting::Adhoc); } NetworkManager::WirelessSecuritySetting::Ptr wifiSecurity = settings->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); NetworkManager::WirelessSecurityType securityType = NetworkManager::findBestWirelessSecurity(wifiDev->wirelessCapabilities(), true, (ap->mode() == NetworkManager::AccessPoint::Adhoc), ap->capabilities(), ap->wpaFlags(), ap->rsnFlags()); if (securityType != NetworkManager::NoneSecurity) { wifiSecurity->setInitialized(true); wifiSetting->setSecurity("802-11-wireless-security"); } if (securityType == NetworkManager::Leap || securityType == NetworkManager::DynamicWep || securityType == NetworkManager::Wpa2Eap || securityType == NetworkManager::WpaEap) { if (securityType == NetworkManager::DynamicWep || securityType == NetworkManager::Leap) { wifiSecurity->setKeyMgmt(NetworkManager::WirelessSecuritySetting::Ieee8021x); if (securityType == NetworkManager::Leap) { wifiSecurity->setAuthAlg(NetworkManager::WirelessSecuritySetting::Leap); } } else { wifiSecurity->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaEap); } m_tmpConnectionUuid = settings->uuid(); m_tmpDevicePath = device; m_tmpSpecificPath = specificObject; QPointer editor = new ConnectionEditorDialog(settings); editor->show(); KWindowSystem::setState(editor->winId(), NET::KeepAbove); KWindowSystem::forceActiveWindow(editor->winId()); connect(editor.data(), &ConnectionEditorDialog::accepted, [editor, this] () { addConnection(editor->setting()); }); connect(editor.data(), &ConnectionEditorDialog::finished, [editor] () { if (editor) { editor->deleteLater(); } }); editor->setModal(true); editor->show(); } else { if (securityType == NetworkManager::StaticWep) { wifiSecurity->setKeyMgmt(NetworkManager::WirelessSecuritySetting::Wep); wifiSecurity->setWepKey0(password); if (KWallet::Wallet::isEnabled()) { wifiSecurity->setWepKeyFlags(NetworkManager::Setting::AgentOwned); } } else { if (ap->mode() == NetworkManager::AccessPoint::Adhoc) { wifiSecurity->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaNone); } else { wifiSecurity->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaPsk); } wifiSecurity->setPsk(password); if (KWallet::Wallet::isEnabled()) { wifiSecurity->setPskFlags(NetworkManager::Setting::AgentOwned); } } QDBusPendingReply reply = NetworkManager::addAndActivateConnection(settings->toMap(), device, specificObject); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this); watcher->setProperty("action", Handler::AddAndActivateConnection); watcher->setProperty("connection", settings->name()); connect(watcher, &QDBusPendingCallWatcher::finished, this, &Handler::replyFinished); } settings.clear(); } void Handler::addConnection(const NMVariantMapMap& map) { QDBusPendingReply reply = NetworkManager::addConnection(map); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this); watcher->setProperty("action", AddConnection); watcher->setProperty("connection", map.value("connection").value("id")); connect(watcher, &QDBusPendingCallWatcher::finished, this, &Handler::replyFinished); } void Handler::deactivateConnection(const QString& connection, const QString& device) { NetworkManager::Connection::Ptr con = NetworkManager::findConnection(connection); if (!con) { qCWarning(PLASMA_NM) << "Not possible to deactivate this connection"; return; } QDBusPendingReply<> reply; Q_FOREACH (const NetworkManager::ActiveConnection::Ptr & active, NetworkManager::activeConnections()) { if (active->uuid() == con->uuid() && ((!active->devices().isEmpty() && active->devices().first() == device) || active->vpn())) { if (active->vpn()) { reply = NetworkManager::deactivateConnection(active->path()); } else { NetworkManager::Device::Ptr device = NetworkManager::findNetworkInterface(active->devices().first()); if (device) { reply = device->disconnectInterface(); } } } } QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this); watcher->setProperty("action", Handler::DeactivateConnection); connect(watcher, &QDBusPendingCallWatcher::finished, this, &Handler::replyFinished); } void Handler::disconnectAll() { Q_FOREACH (const NetworkManager::Device::Ptr & device, NetworkManager::networkInterfaces()) { device->disconnectInterface(); } } void Handler::enableAirplaneMode(bool enable) { if (enable) { m_tmpWirelessEnabled = NetworkManager::isWirelessEnabled(); m_tmpWwanEnabled = NetworkManager::isWwanEnabled(); enableBluetooth(false); enableWireless(false); enableWwan(false); } else { enableBluetooth(true); if (m_tmpWirelessEnabled) { enableWireless(true); } if (m_tmpWwanEnabled) { enableWwan(true); } } } void Handler::enableBluetooth(bool enable) { qDBusRegisterMetaType< QMap >(); QDBusMessage message = QDBusMessage::createMethodCall("org.bluez", "/", "org.freedesktop.DBus.ObjectManager", "GetManagedObjects"); QDBusPendingReply > reply = QDBusConnection::systemBus().asyncCall(message); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this); connect(watcher, &QDBusPendingCallWatcher::finished, [this, enable] (QDBusPendingCallWatcher *watcher) { QDBusPendingReply > reply = *watcher; if (reply.isValid()) { Q_FOREACH (const QDBusObjectPath &path, reply.value().keys()) { const QString objPath = path.path(); qCDebug(PLASMA_NM) << "inspecting path" << objPath; const QStringList interfaces = reply.value().value(path).keys(); qCDebug(PLASMA_NM) << "interfaces:" << interfaces; if (interfaces.contains("org.bluez.Adapter1")) { // We need to check previous state first if (!enable) { QDBusMessage message = QDBusMessage::createMethodCall("org.bluez", objPath, "org.freedesktop.DBus.Properties", "Get"); QList arguments; arguments << QLatin1Literal("org.bluez.Adapter1"); arguments << QLatin1Literal("Powered"); message.setArguments(arguments); QDBusPendingReply getReply = QDBusConnection::systemBus().asyncCall(message); QDBusPendingCallWatcher *getWatcher = new QDBusPendingCallWatcher(getReply, this); connect(getWatcher, &QDBusPendingCallWatcher::finished, [this, objPath] (QDBusPendingCallWatcher *watcher) { QDBusPendingReply reply = *watcher; if (reply.isValid()) { m_bluetoothAdapters.insert(objPath, reply.value().toBool()); QDBusMessage message = QDBusMessage::createMethodCall("org.bluez", objPath, "org.freedesktop.DBus.Properties", "Set"); QList arguments; arguments << QLatin1Literal("org.bluez.Adapter1"); arguments << QLatin1Literal("Powered"); arguments << QVariant::fromValue(QDBusVariant(QVariant(false))); message.setArguments(arguments); QDBusConnection::systemBus().asyncCall(message); } }); getWatcher->deleteLater(); } else if (enable && m_bluetoothAdapters.value(objPath)) { QDBusMessage message = QDBusMessage::createMethodCall("org.bluez", objPath, "org.freedesktop.DBus.Properties", "Set"); QList arguments; arguments << QLatin1Literal("org.bluez.Adapter1"); arguments << QLatin1Literal("Powered"); arguments << QVariant::fromValue(QDBusVariant(QVariant(enable))); message.setArguments(arguments); QDBusConnection::systemBus().asyncCall(message); } } } } }); watcher->deleteLater(); } void Handler::enableNetworking(bool enable) { NetworkManager::setNetworkingEnabled(enable); } void Handler::enableWireless(bool enable) { NetworkManager::setWirelessEnabled(enable); } void Handler::enableWwan(bool enable) { NetworkManager::setWwanEnabled(enable); } void Handler::removeConnection(const QString& connection) { NetworkManager::Connection::Ptr con = NetworkManager::findConnection(connection); if (!con || con->uuid().isEmpty()) { qCWarning(PLASMA_NM) << "Not possible to remove connection " << connection; return; } // Remove slave connections Q_FOREACH (const NetworkManager::Connection::Ptr &connection, NetworkManager::listConnections()) { NetworkManager::ConnectionSettings::Ptr settings = connection->settings(); if (settings->master() == con->uuid()) { connection->remove(); } } QDBusPendingReply<> reply = con->remove(); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this); watcher->setProperty("action", Handler::RemoveConnection); watcher->setProperty("connection", con->name()); connect(watcher, &QDBusPendingCallWatcher::finished, this, &Handler::replyFinished); } void Handler::updateConnection(const NetworkManager::Connection::Ptr& connection, const NMVariantMapMap& map) { QDBusPendingReply<> reply = connection->update(map); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this); watcher->setProperty("action", UpdateConnection); watcher->setProperty("connection", connection->name()); connect(watcher, &QDBusPendingCallWatcher::finished, this, &Handler::replyFinished); } void Handler::requestScan() { Q_FOREACH (NetworkManager::Device::Ptr device, NetworkManager::networkInterfaces()) { if (device->type() == NetworkManager::Device::Wifi) { NetworkManager::WirelessDevice::Ptr wifiDevice = device.objectCast(); if (wifiDevice) { QDBusPendingReply<> reply = wifiDevice->requestScan(); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this); watcher->setProperty("action", Handler::RequestScan); connect(watcher, &QDBusPendingCallWatcher::finished, this, &Handler::replyFinished); } } } } void Handler::initKdedModule() { QDBusMessage initMsg = QDBusMessage::createMethodCall(QStringLiteral(AGENT_SERVICE), QStringLiteral(AGENT_PATH), QStringLiteral(AGENT_IFACE), QStringLiteral("init")); QDBusConnection::sessionBus().send(initMsg); } void Handler::replyFinished(QDBusPendingCallWatcher * watcher) { QDBusPendingReply<> reply = *watcher; if (reply.isError() || !reply.isValid()) { - KNotification *notification = 0; + KNotification *notification = nullptr; QString error = reply.error().message(); Handler::HandlerAction action = (Handler::HandlerAction)watcher->property("action").toUInt(); switch (action) { case Handler::ActivateConnection: notification = new KNotification("FailedToActivateConnection", KNotification::CloseOnTimeout, this); notification->setTitle(i18n("Failed to activate %1", watcher->property("connection").toString())); break; case Handler::AddAndActivateConnection: notification = new KNotification("FailedToAddConnection", KNotification::CloseOnTimeout, this); notification->setTitle(i18n("Failed to add %1", watcher->property("connection").toString())); break; case Handler::AddConnection: notification = new KNotification("FailedToAddConnection", KNotification::CloseOnTimeout, this); notification->setTitle(i18n("Failed to add connection %1", watcher->property("connection").toString())); break; case Handler::DeactivateConnection: notification = new KNotification("FailedToDeactivateConnection", KNotification::CloseOnTimeout, this); notification->setTitle(i18n("Failed to deactivate %1", watcher->property("connection").toString())); break; case Handler::RemoveConnection: notification = new KNotification("FailedToRemoveConnection", KNotification::CloseOnTimeout, this); notification->setTitle(i18n("Failed to remove %1", watcher->property("connection").toString())); break; case Handler::RequestScan: /* INFO: Disabled for now as wifi scanning is now automatical notification = new KNotification("FailedToRequestScan", KNotification::CloseOnTimeout, this); notification->setTitle(i18n("Failed to request scan")); */ break; case Handler::UpdateConnection: notification = new KNotification("FailedToUpdateConnection", KNotification::CloseOnTimeout, this); notification->setTitle(i18n("Failed to update connection %1", watcher->property("connection").toString())); break; default: break; } if (notification) { notification->setComponentName("networkmanagement"); notification->setText(error); notification->setPixmap(QIcon::fromTheme("dialog-warning").pixmap(KIconLoader::SizeHuge)); notification->sendEvent(); } } else { - KNotification *notification = 0; + KNotification *notification = nullptr; Handler::HandlerAction action = (Handler::HandlerAction)watcher->property("action").toUInt(); switch (action) { case Handler::AddConnection: notification = new KNotification("ConnectionAdded", KNotification::CloseOnTimeout, this); notification->setText(i18n("Connection %1 has been added", watcher->property("connection").toString())); break; case Handler::RemoveConnection: notification = new KNotification("ConnectionRemoved", KNotification::CloseOnTimeout, this); notification->setText(i18n("Connection %1 has been removed", watcher->property("connection").toString())); break; case Handler::UpdateConnection: notification = new KNotification("ConnectionUpdated", KNotification::CloseOnTimeout, this); notification->setText(i18n("Connection %1 has been updated", watcher->property("connection").toString())); break; default: break; } if (notification) { notification->setComponentName("networkmanagement"); notification->setTitle(watcher->property("connection").toString()); notification->setPixmap(QIcon::fromTheme("dialog-information").pixmap(KIconLoader::SizeHuge)); notification->sendEvent(); } } watcher->deleteLater(); } #if WITH_MODEMMANAGER_SUPPORT void Handler::unlockRequiredChanged(MMModemLock modemLock) { if (modemLock == MM_MODEM_LOCK_NONE) { activateConnection(m_tmpConnectionPath, m_tmpDevicePath, m_tmpSpecificPath); } } #endif diff --git a/libs/handler.h b/libs/handler.h index 6f713165..ef0d35f2 100644 --- a/libs/handler.h +++ b/libs/handler.h @@ -1,127 +1,127 @@ /* Copyright 2013-2014 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_HANDLER_H #define PLASMA_NM_HANDLER_H #include #include #include #include #if WITH_MODEMMANAGER_SUPPORT #include #endif class Q_DECL_EXPORT Handler : public QObject { Q_OBJECT public: enum HandlerAction { ActivateConnection, AddAndActivateConnection, AddConnection, DeactivateConnection, RemoveConnection, RequestScan, UpdateConnection }; - explicit Handler(QObject* parent = 0); - virtual ~Handler(); + explicit Handler(QObject* parent = nullptr); + ~Handler() override; public Q_SLOTS: /** * Activates given connection * @connection - d-bus path of the connection you want to activate * @device - d-bus path of the device where the connection should be activated * @specificParameter - d-bus path of the specific object you want to use for this activation, i.e access point */ void activateConnection(const QString &connection, const QString &device, const QString &specificParameter); /** * Adds and activates a new wireless connection * @device - d-bus path of the wireless device where the connection should be activated * @specificParameter - d-bus path of the accesspoint you want to connect to * @password - pre-filled password which should be used for the new wireless connection * @autoConnect - boolean value whether this connection should be activated automatically when it's available * * Works automatically for wireless connections with WEP/WPA security, for wireless connections with WPA/WPA * it will open the connection editor for advanced configuration. * */ void addAndActivateConnection(const QString &device, const QString &specificParameter, const QString &password = QString()); /** * Adds a new connection * @map - NMVariantMapMap with connection settings */ void addConnection(const NMVariantMapMap &map); /** * Deactivates given connection * @connection - d-bus path of the connection you want to deactivate * @device - d-bus path of the connection where the connection is activated */ void deactivateConnection(const QString &connection, const QString &device); /** * Disconnects all connections */ void disconnectAll(); void enableAirplaneMode(bool enable); void enableNetworking(bool enable); void enableWireless(bool enable); void enableWwan(bool enable); /** * Removes given connection * @connection - d-bus path of the connection you want to edit */ void removeConnection(const QString & connection); /** * Updates given connection * @connection - connection which should be updated * @map - NMVariantMapMap with new connection settings */ void updateConnection(const NetworkManager::Connection::Ptr &connection, const NMVariantMapMap &map); void requestScan(); private Q_SLOTS: void initKdedModule(); void replyFinished(QDBusPendingCallWatcher *watcher); #if WITH_MODEMMANAGER_SUPPORT void unlockRequiredChanged(MMModemLock modemLock); #endif private: bool m_tmpWirelessEnabled; bool m_tmpWwanEnabled; #if WITH_MODEMMANAGER_SUPPORT QString m_tmpConnectionPath; #endif QString m_tmpConnectionUuid; QString m_tmpDevicePath; QString m_tmpSpecificPath; QMap m_bluetoothAdapters; void enableBluetooth(bool enable); }; #endif // PLASMA_NM_HANDLER_H diff --git a/libs/models/appletproxymodel.cpp b/libs/models/appletproxymodel.cpp index 5a57574b..4944b6c8 100644 --- a/libs/models/appletproxymodel.cpp +++ b/libs/models/appletproxymodel.cpp @@ -1,128 +1,128 @@ /* Copyright 2013-2014 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "appletproxymodel.h" #include "networkmodel.h" #include "uiutils.h" -AppletProxyModel::AppletProxyModel(QObject* parent) +AppletProxyModel::AppletProxyModel(QObject *parent) : QSortFilterProxyModel(parent) { setDynamicSortFilter(true); sort(0, Qt::DescendingOrder); } AppletProxyModel::~AppletProxyModel() { } -bool AppletProxyModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const +bool AppletProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const { const QModelIndex index = sourceModel()->index(source_row, 0, source_parent); // slaves are always filtered-out const bool isSlave = sourceModel()->data(index, NetworkModel::SlaveRole).toBool(); if (isSlave) { return false; } const NetworkManager::ConnectionSettings::ConnectionType type = (NetworkManager::ConnectionSettings::ConnectionType) sourceModel()->data(index, NetworkModel::TypeRole).toUInt(); if (!UiUtils::isConnectionTypeSupported(type)) { return false; } NetworkModelItem::ItemType itemType = (NetworkModelItem::ItemType)sourceModel()->data(index, NetworkModel::ItemTypeRole).toUInt(); if (itemType == NetworkModelItem::AvailableConnection || itemType == NetworkModelItem::AvailableAccessPoint) { return true; } return false; } -bool AppletProxyModel::lessThan(const QModelIndex& left, const QModelIndex& right) const +bool AppletProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { const bool leftAvailable = (NetworkModelItem::ItemType)sourceModel()->data(left, NetworkModel::ItemTypeRole).toUInt() != NetworkModelItem::UnavailableConnection; const bool leftConnected = sourceModel()->data(left, NetworkModel::ConnectionStateRole).toUInt() == NetworkManager::ActiveConnection::Activated; const int leftConnectionState = sourceModel()->data(left, NetworkModel::ConnectionStateRole).toUInt(); const QString leftName = sourceModel()->data(left, NetworkModel::NameRole).toString(); const UiUtils::SortedConnectionType leftType = UiUtils::connectionTypeToSortedType((NetworkManager::ConnectionSettings::ConnectionType) sourceModel()->data(left, NetworkModel::TypeRole).toUInt()); const QString leftUuid = sourceModel()->data(left, NetworkModel::UuidRole).toString(); const int leftSignal = sourceModel()->data(left, NetworkModel::SignalRole).toInt(); const QDateTime leftDate = sourceModel()->data(left, NetworkModel::TimeStampRole).toDateTime(); const bool rightAvailable = (NetworkModelItem::ItemType)sourceModel()->data(right, NetworkModel::ItemTypeRole).toUInt() != NetworkModelItem::UnavailableConnection; const bool rightConnected = sourceModel()->data(right, NetworkModel::ConnectionStateRole).toUInt() == NetworkManager::ActiveConnection::Activated; const int rightConnectionState = sourceModel()->data(right, NetworkModel::ConnectionStateRole).toUInt(); const QString rightName = sourceModel()->data(right, NetworkModel::NameRole).toString(); const UiUtils::SortedConnectionType rightType = UiUtils::connectionTypeToSortedType((NetworkManager::ConnectionSettings::ConnectionType) sourceModel()->data(right, NetworkModel::TypeRole).toUInt()); const QString rightUuid = sourceModel()->data(right, NetworkModel::UuidRole).toString(); const int rightSignal = sourceModel()->data(right, NetworkModel::SignalRole).toInt(); const QDateTime rightDate = sourceModel()->data(right, NetworkModel::TimeStampRole).toDateTime(); if (leftAvailable < rightAvailable) { return true; } else if (leftAvailable > rightAvailable) { return false; } if (leftConnected < rightConnected) { return true; } else if (leftConnected > rightConnected) { return false; } if (leftConnectionState > rightConnectionState) { return true; } else if (leftConnectionState < rightConnectionState) { return false; } if (leftUuid.isEmpty() && !rightUuid.isEmpty()) { return true; } else if (!leftUuid.isEmpty() && rightUuid.isEmpty()) { return false; } if (leftType < rightType) { return false; } else if (leftType > rightType) { return true; } if (leftDate > rightDate) { return false; } else if (leftDate < rightDate) { return true; } if (leftSignal < rightSignal) { return true; } else if (leftSignal > rightSignal) { return false; } if (QString::localeAwareCompare(leftName, rightName) > 0) { return true; } else { return false; } } diff --git a/libs/models/appletproxymodel.h b/libs/models/appletproxymodel.h index 8f11e2cf..eeb305e3 100644 --- a/libs/models/appletproxymodel.h +++ b/libs/models/appletproxymodel.h @@ -1,42 +1,42 @@ /* Copyright 2013-2014 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_APPLET_PROXY_MODEL_H #define PLASMA_NM_APPLET_PROXY_MODEL_H #include #include "networkmodelitem.h" class Q_DECL_EXPORT AppletProxyModel : public QSortFilterProxyModel { Q_OBJECT Q_PROPERTY(QAbstractItemModel * sourceModel READ sourceModel WRITE setSourceModel) public: - explicit AppletProxyModel(QObject* parent = 0); - virtual ~AppletProxyModel(); + explicit AppletProxyModel(QObject *parent = nullptr); + ~AppletProxyModel() override; protected: - bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const Q_DECL_OVERRIDE; - bool lessThan(const QModelIndex& left, const QModelIndex& right) const Q_DECL_OVERRIDE; + bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override; + bool lessThan(const QModelIndex &left, const QModelIndex &right) const override; }; #endif // PLASMA_NM_APPLET_PROXY_MODEL_H diff --git a/libs/models/creatableconnectionsmodel.cpp b/libs/models/creatableconnectionsmodel.cpp index 855618f3..6c05d294 100644 --- a/libs/models/creatableconnectionsmodel.cpp +++ b/libs/models/creatableconnectionsmodel.cpp @@ -1,287 +1,287 @@ /* - Copyright 2016 Jan Grulich + Copyright 2016-2018 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "creatableconnectionsmodel.h" #include "configuration.h" #include #include #include CreatableConnectionItem::CreatableConnectionItem(const QString &typeName, const QString &typeSection, const QString &description, const QString &icon, NetworkManager::ConnectionSettings::ConnectionType type, const QString &vpnType, const QString &specificType, bool shared, QObject *parent) : QObject(parent) , m_shared(shared) , m_connectionType(type) , m_description(description) , m_icon(icon) , m_specificType(specificType) , m_typeName(typeName) , m_typeSection(typeSection) , m_vpnType(vpnType) { } CreatableConnectionItem::CreatableConnectionItem(QObject *parent) : QObject(parent) { } CreatableConnectionItem::~CreatableConnectionItem() { } NetworkManager::ConnectionSettings::ConnectionType CreatableConnectionItem::connectionType() const { return m_connectionType; } void CreatableConnectionItem::setConnectionType(NetworkManager::ConnectionSettings::ConnectionType type) { m_connectionType = type; } QString CreatableConnectionItem::description() const { return m_description; } void CreatableConnectionItem::setDescription(const QString &description) { m_description = description; } QString CreatableConnectionItem::icon() const { return m_icon; } void CreatableConnectionItem::setIcon(const QString &icon) { m_icon = icon; } bool CreatableConnectionItem::shared() const { return m_shared; } void CreatableConnectionItem::setShared(bool shared) { m_shared = shared; } QString CreatableConnectionItem::specificType() const { return m_specificType; } void CreatableConnectionItem::setSpecificType(const QString &specificType) { m_specificType = specificType; } QString CreatableConnectionItem::typeName() const { return m_typeName; } void CreatableConnectionItem::setTypeName(const QString &typeName) { m_typeName = typeName; } QString CreatableConnectionItem::typeSection() const { return m_typeSection; } void CreatableConnectionItem::setTypeSection(const QString &typeSection) { m_typeSection = typeSection; } QString CreatableConnectionItem::vpnType() const { return m_vpnType; } void CreatableConnectionItem::setVpnType(const QString &vpnType) { m_vpnType = vpnType; } CreatableConnectionsModel::CreatableConnectionsModel(QObject *parent) : QAbstractListModel(parent) { CreatableConnectionItem *connectionItem; connectionItem = new CreatableConnectionItem(i18n("DSL"), i18n("Hardware based connections"), i18n("Some DSL description"), QStringLiteral("network-modem"), NetworkManager::ConnectionSettings::Pppoe); m_list << connectionItem; connectionItem = new CreatableConnectionItem(i18n("Infiniband"), i18n("Hardware based connections"), i18n("Some infiniband description"), QStringLiteral("network-wired"), NetworkManager::ConnectionSettings::Infiniband); m_list << connectionItem; #if WITH_MODEMMANAGER_SUPPORT connectionItem = new CreatableConnectionItem(i18n("Mobile Broadband"), i18n("Hardware based connections"), i18n("Some mobile broadband description"), QStringLiteral("smartphone"), NetworkManager::ConnectionSettings::Gsm); m_list << connectionItem; #endif connectionItem = new CreatableConnectionItem(i18n("Wired Ethernet"), i18n("Hardware based connections"), i18n("Some wired ethernet description"), QStringLiteral("network-wired"), NetworkManager::ConnectionSettings::Wired); m_list << connectionItem; connectionItem = new CreatableConnectionItem(i18n("Wired Ethernet (shared)"), i18n("Hardware based connections"), i18n("Some wired ethernet description"), QStringLiteral("network-wired"), NetworkManager::ConnectionSettings::Wired, QString(), QString(), true); // VpnType and SpecificType are empty m_list << connectionItem; connectionItem = new CreatableConnectionItem(i18n("Wi-Fi"), i18n("Hardware based connections"), i18n("Some wi-fi description"), QStringLiteral("network-wireless"), NetworkManager::ConnectionSettings::Wireless); m_list << connectionItem; connectionItem = new CreatableConnectionItem(i18n("Wi-Fi (shared)"), i18n("Hardware based connections"), i18n("Some wi-fi description"), QStringLiteral("network-wireless"), NetworkManager::ConnectionSettings::Wireless, QString(), QString(), true); // VpnType and SpecificType are empty m_list << connectionItem; if (Configuration::manageVirtualConnections()) { connectionItem = new CreatableConnectionItem(i18n("Bond"), i18n("Virtual connections"), i18n("Some bond description"), QStringLiteral("network-wired"), NetworkManager::ConnectionSettings::Bond, QString(), QString(), true); // VpnType and SpecificType are empty m_list << connectionItem; connectionItem = new CreatableConnectionItem(i18n("Bridge"), i18n("Virtual connections"), i18n("Some bond description"), QStringLiteral("network-wired"), NetworkManager::ConnectionSettings::Bridge, QString(), QString(), true); // VpnType and SpecificType are empty m_list << connectionItem; connectionItem = new CreatableConnectionItem(i18n("Team"), i18n("Virtual connections"), i18n("Some team description"), QStringLiteral("network-wired"), NetworkManager::ConnectionSettings::Team, QString(), QString(), true); // VpnType and SpecificType are empty m_list << connectionItem; connectionItem = new CreatableConnectionItem(i18n("Vlan"), i18n("Virtual connections"), i18n("Some vlan description"), QStringLiteral("network-wired"), NetworkManager::ConnectionSettings::Vlan, QString(), QString(), true); // VpnType and SpecificType are empty m_list << connectionItem; } KService::List services = KServiceTypeTrader::self()->query("PlasmaNetworkManagement/VpnUiPlugin"); std::sort(services.begin(), services.end(), [] (const KService::Ptr &left, const KService::Ptr &right) { return QString::localeAwareCompare(left->name(), right->name()) <= 0; }); - Q_FOREACH (const KService::Ptr & service, services) { + for (const KService::Ptr &service : services) { const QString vpnType = service->property("X-NetworkManager-Services", QVariant::String).toString(); const QString vpnSubType = service->property("X-NetworkManager-Services-Subtype", QVariant::String).toString(); const QString vpnDescription = service->property("Comment", QVariant::String).toString(); connectionItem = new CreatableConnectionItem(service->name(), i18n("VPN connections"), vpnDescription, QStringLiteral("network-vpn"), NetworkManager::ConnectionSettings::Vpn, vpnType, vpnSubType, false); m_list << connectionItem; } // Placeholder for VPN import connectionItem = new CreatableConnectionItem(i18n("Import VPN connection..."), i18n("Other"), i18n("Import a saved configuration file"), QStringLiteral("document-import"), NetworkManager::ConnectionSettings::Vpn, QLatin1String("imported"), QLatin1String("imported"), false); m_list << connectionItem; } CreatableConnectionsModel::~CreatableConnectionsModel() { } QVariant CreatableConnectionsModel::data(const QModelIndex &index, int role) const { const int row = index.row(); if (row >= 0 && row < m_list.count()) { - CreatableConnectionItem * item = m_list.at(row); + CreatableConnectionItem *item = m_list.at(row); switch (role) { case ConnectionDescription: return item->description(); case ConnectionIcon: return item->icon(); case ConnectionSpeficType: return item->specificType(); case ConnectionShared: return item->shared(); case ConnectionType: return item->connectionType(); case ConnectionTypeName: return item->typeName(); case ConnectionTypeSection: return item->typeSection(); case ConnectionVpnType: return item->vpnType(); default: break; } } return QVariant(); } QHash CreatableConnectionsModel::roleNames() const { QHash roles = QAbstractListModel::roleNames(); roles[ConnectionDescription] = "ConnectionDescription"; roles[ConnectionIcon] = "ConnectionIcon"; roles[ConnectionSpeficType] = "ConnectionSpecificType"; roles[ConnectionShared] = "ConnectionShared"; roles[ConnectionType] = "ConnectionType"; roles[ConnectionTypeName] = "ConnectionTypeName"; roles[ConnectionTypeSection] = "ConnectionTypeSection"; roles[ConnectionVpnType] = "ConnectionVpnType"; return roles; } int CreatableConnectionsModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return m_list.count(); } diff --git a/libs/models/creatableconnectionsmodel.h b/libs/models/creatableconnectionsmodel.h index 2c8084c0..59eab537 100644 --- a/libs/models/creatableconnectionsmodel.h +++ b/libs/models/creatableconnectionsmodel.h @@ -1,105 +1,105 @@ /* - Copyright 2016 Jan Grulich + Copyright 2016-2018 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_CREATABLE_CONNECTIONS_MODEL_H #define PLASMA_NM_CREATABLE_CONNECTIONS_MODEL_H #include #include class Q_DECL_EXPORT CreatableConnectionItem : public QObject { Q_OBJECT public: explicit CreatableConnectionItem(const QString &typeName, const QString &typeSection, // Visible properties const QString &description, const QString &icon, // Visible properties NetworkManager::ConnectionSettings::ConnectionType type, // Properties needed for creating const QString &vpnType = QString(), // Properties needed for creating const QString &specificType = QString(), // Properties needed for creating bool shared = false, // Properties needed for creating - QObject *parent = 0); - explicit CreatableConnectionItem(QObject *parent = 0); - virtual ~CreatableConnectionItem(); + QObject *parent = nullptr); + explicit CreatableConnectionItem(QObject *parent = nullptr); + ~CreatableConnectionItem() override; NetworkManager::ConnectionSettings::ConnectionType connectionType() const; void setConnectionType(NetworkManager::ConnectionSettings::ConnectionType type); QString description() const; void setDescription(const QString &description); QString icon() const; void setIcon(const QString &icon); QString specificType() const; void setSpecificType(const QString &specificType); bool shared() const; void setShared(bool shared); QString typeName() const; void setTypeName(const QString &typeName); QString typeSection() const; void setTypeSection(const QString &typeSection); QString vpnType() const; void setVpnType(const QString &vpnType); private: bool m_shared; NetworkManager::ConnectionSettings::ConnectionType m_connectionType; QString m_description; QString m_icon; QString m_specificType; QString m_typeName; QString m_typeSection; QString m_vpnType; }; class Q_DECL_EXPORT CreatableConnectionsModel : public QAbstractListModel { Q_OBJECT public: - explicit CreatableConnectionsModel(QObject *parent = 0); - virtual ~CreatableConnectionsModel(); + explicit CreatableConnectionsModel(QObject *parent = nullptr); + ~CreatableConnectionsModel() override; enum ItemRole { ConnectionDescription = Qt::UserRole + 1, ConnectionIcon, ConnectionSpeficType, ConnectionShared, ConnectionType, ConnectionTypeName , ConnectionTypeSection, ConnectionVpnType }; - int rowCount(const QModelIndex& parent) const Q_DECL_OVERRIDE; - QVariant data(const QModelIndex& index, int role) const Q_DECL_OVERRIDE; - virtual QHash< int, QByteArray > roleNames() const Q_DECL_OVERRIDE; + int rowCount(const QModelIndex &parent) const override; + QVariant data(const QModelIndex &index, int role) const override; + QHash< int, QByteArray > roleNames() const override; private: QList m_list; }; #endif // PLASMA_NM_CREATABLE_CONNECTIONS_MODEL_H diff --git a/libs/models/editorproxymodel.cpp b/libs/models/editorproxymodel.cpp index 258c3e5a..c994a610 100644 --- a/libs/models/editorproxymodel.cpp +++ b/libs/models/editorproxymodel.cpp @@ -1,116 +1,116 @@ /* - Copyright 2013-2014 Jan Grulich + Copyright 2013-2018 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "editorproxymodel.h" #include "uiutils.h" -EditorProxyModel::EditorProxyModel(QObject* parent) +EditorProxyModel::EditorProxyModel(QObject *parent) : QSortFilterProxyModel(parent) { setDynamicSortFilter(true); setSortCaseSensitivity(Qt::CaseInsensitive); setSortLocaleAware(true); sort(0, Qt::DescendingOrder); } EditorProxyModel::~EditorProxyModel() { } -bool EditorProxyModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const +bool EditorProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const { const QModelIndex index = sourceModel()->index(source_row, 0, source_parent); // slaves are always filtered-out const bool isSlave = sourceModel()->data(index, NetworkModel::SlaveRole).toBool(); const bool isDuplicate = sourceModel()->data(index, NetworkModel::DuplicateRole).toBool(); if (isSlave || isDuplicate) { return false; } const NetworkManager::ConnectionSettings::ConnectionType type = (NetworkManager::ConnectionSettings::ConnectionType) sourceModel()->data(index, NetworkModel::TypeRole).toUInt(); if (!UiUtils::isConnectionTypeSupported(type)) { return false; } NetworkModelItem::ItemType itemType = (NetworkModelItem::ItemType)sourceModel()->data(index, NetworkModel::ItemTypeRole).toUInt(); if (itemType == NetworkModelItem::AvailableAccessPoint) { return false; } const QString pattern = filterRegExp().pattern(); if (!pattern.isEmpty()) { // filtering on data (connection name), wildcard-only QString data = sourceModel()->data(index, Qt::DisplayRole).toString(); if (data.isEmpty()) { data = sourceModel()->data(index, NetworkModel::NameRole).toString(); } return data.contains(pattern, Qt::CaseInsensitive); } return true; } bool EditorProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { const bool leftConnected = sourceModel()->data(left, NetworkModel::ConnectionStateRole).toUInt() == NetworkManager::ActiveConnection::Activated; const QString leftName = sourceModel()->data(left, NetworkModel::NameRole).toString(); const UiUtils::SortedConnectionType leftType = UiUtils::connectionTypeToSortedType((NetworkManager::ConnectionSettings::ConnectionType) sourceModel()->data(left, NetworkModel::TypeRole).toUInt()); const QString leftVpnType = sourceModel()->data(left, NetworkModel::VpnType).toString(); const QDateTime leftDate = sourceModel()->data(left, NetworkModel::TimeStampRole).toDateTime(); const bool rightConnected = sourceModel()->data(right, NetworkModel::ConnectionStateRole).toUInt() == NetworkManager::ActiveConnection::Activated; const QString rightName = sourceModel()->data(right, NetworkModel::NameRole).toString(); const UiUtils::SortedConnectionType rightType = UiUtils::connectionTypeToSortedType((NetworkManager::ConnectionSettings::ConnectionType) sourceModel()->data(right, NetworkModel::TypeRole).toUInt()); const QString rightVpnType = sourceModel()->data(right, NetworkModel::VpnType).toString(); const QDateTime rightDate = sourceModel()->data(right, NetworkModel::TimeStampRole).toDateTime(); if (leftType < rightType) { return false; } else if (leftType > rightType) { return true; } if (leftType == rightType && leftType == UiUtils::Vpn) { if (QString::localeAwareCompare(leftVpnType, rightVpnType) < 0) { return false; } else if (QString::localeAwareCompare(leftVpnType, rightVpnType) > 0) { return true; } } if (leftConnected < rightConnected) { return true; } else if (leftConnected > rightConnected) { return false; } if (leftDate > rightDate) { return false; } else if (leftDate < rightDate) { return true; } if (QString::localeAwareCompare(leftName, rightName) > 0) { return true; } else { return false; } } diff --git a/libs/models/editorproxymodel.h b/libs/models/editorproxymodel.h index 23daaab2..1b390e3a 100644 --- a/libs/models/editorproxymodel.h +++ b/libs/models/editorproxymodel.h @@ -1,42 +1,42 @@ /* - Copyright 2013-2014 Jan Grulich + Copyright 2013-2018 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_EDITOR_PROXY_MODEL_H #define PLASMA_NM_EDITOR_PROXY_MODEL_H #include "networkmodelitem.h" #include class Q_DECL_EXPORT EditorProxyModel : public QSortFilterProxyModel { Q_OBJECT Q_PROPERTY(QAbstractItemModel * sourceModel READ sourceModel WRITE setSourceModel) public: - explicit EditorProxyModel(QObject* parent = 0); - virtual ~EditorProxyModel(); + explicit EditorProxyModel(QObject *parent = nullptr); + ~EditorProxyModel() override; protected: - bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const Q_DECL_OVERRIDE; - bool lessThan(const QModelIndex &left, const QModelIndex &right) const Q_DECL_OVERRIDE; + bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override; + bool lessThan(const QModelIndex &left, const QModelIndex &right) const override; }; #endif // PLASMA_NM_EDITOR_PROXY_MODEL_H diff --git a/libs/models/kcmidentitymodel.cpp b/libs/models/kcmidentitymodel.cpp index acf66402..2e1a8b8a 100644 --- a/libs/models/kcmidentitymodel.cpp +++ b/libs/models/kcmidentitymodel.cpp @@ -1,117 +1,117 @@ /* - Copyright 2016 Jan Grulich + Copyright 2013-2018 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "kcmidentitymodel.h" #include "networkmodel.h" #include "networkmodelitem.h" #include "uiutils.h" #include #include #include #include KcmIdentityModel::KcmIdentityModel(QObject *parent) : QIdentityProxyModel(parent) { NetworkModel *baseModel = new NetworkModel(this); setSourceModel(baseModel); } KcmIdentityModel::~KcmIdentityModel() { } Qt::ItemFlags KcmIdentityModel::flags(const QModelIndex &index) const { const QModelIndex mappedProxyIndex = index.sibling(index.row(), 0); return QIdentityProxyModel::flags(mappedProxyIndex) | Qt::ItemIsEnabled | Qt::ItemIsSelectable; } int KcmIdentityModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return 3; } QHash KcmIdentityModel::roleNames() const { QHash roles = QIdentityProxyModel::roleNames(); roles[KcmConnectionIconRole] = "KcmConnectionIcon"; roles[KcmConnectionTypeRole] = "KcmConnectionType"; roles[KcmVpnConnectionExportable] = "KcmVpnConnectionExportable"; return roles; } QVariant KcmIdentityModel::data(const QModelIndex &index, int role) const { const QModelIndex sourceIndex = sourceModel()->index(index.row(), 0); NetworkManager::ConnectionSettings::ConnectionType type = static_cast(sourceModel()->data(sourceIndex, NetworkModel::TypeRole).toInt()); NetworkManager::ConnectionSettings::Ptr settings; NetworkManager::VpnSetting::Ptr vpnSetting ; if (type == NetworkManager::ConnectionSettings::Vpn) { settings = NetworkManager::findConnection(sourceModel()->data(sourceIndex, NetworkModel::ConnectionPathRole).toString())->settings(); if (settings) { vpnSetting = settings->setting(NetworkManager::Setting::Vpn).staticCast(); } } QString tooltip; const QString iconName = UiUtils::iconAndTitleForConnectionSettingsType(type, tooltip); if (role == KcmConnectionIconRole) { return iconName; } else if (role == KcmConnectionTypeRole) { if (type == NetworkManager::ConnectionSettings::Vpn && vpnSetting) { return QString("%1 (%2)").arg(tooltip).arg(vpnSetting->serviceType().section('.', -1)); } return tooltip; } else if (role == KcmVpnConnectionExportable) { if (type == NetworkManager::ConnectionSettings::Vpn && vpnSetting) { return (vpnSetting->serviceType().endsWith(QLatin1String("vpnc")) || vpnSetting->serviceType().endsWith(QLatin1String("openvpn"))); } return false; } else { return sourceModel()->data(index, role); } return QVariant(); } QModelIndex KcmIdentityModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); return createIndex(row, column); } QModelIndex KcmIdentityModel::mapToSource(const QModelIndex &proxyIndex) const { if (proxyIndex.column() > 0) { return QModelIndex(); } return QIdentityProxyModel::mapToSource(proxyIndex); } diff --git a/libs/models/kcmidentitymodel.h b/libs/models/kcmidentitymodel.h index 061fe6f3..3ee6382f 100644 --- a/libs/models/kcmidentitymodel.h +++ b/libs/models/kcmidentitymodel.h @@ -1,50 +1,50 @@ /* - Copyright 2016 Jan Grulich + Copyright 2016-2018 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_KCM_IDENTITY_MODEL_H #define PLASMA_NM_KCM_IDENTITY_MODEL_H #include #include class Q_DECL_EXPORT KcmIdentityModel : public QIdentityProxyModel { Q_OBJECT public: - explicit KcmIdentityModel(QObject *parent = 0); - virtual ~KcmIdentityModel(); + explicit KcmIdentityModel(QObject *parent = nullptr); + ~KcmIdentityModel() override; enum KcmItemRole { KcmConnectionIconRole = Qt::UserRole + 100, KcmConnectionTypeRole, KcmVpnConnectionExportable }; - QHash< int, QByteArray > roleNames() const Q_DECL_OVERRIDE; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE; - Qt::ItemFlags flags(const QModelIndex &index) const Q_DECL_OVERRIDE; + QHash< int, QByteArray > roleNames() const override; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + Qt::ItemFlags flags(const QModelIndex &index) const override; - int columnCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; - QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; + int columnCount(const QModelIndex &parent = QModelIndex()) const override; + QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; - QModelIndex mapToSource(const QModelIndex &proxyIndex) const Q_DECL_OVERRIDE; + QModelIndex mapToSource(const QModelIndex &proxyIndex) const override; }; #endif // PLASMA_NM_KCM_IDENTITY_MODEL_H diff --git a/libs/models/networkitemslist.cpp b/libs/models/networkitemslist.cpp index 852ba5ed..524f99da 100644 --- a/libs/models/networkitemslist.cpp +++ b/libs/models/networkitemslist.cpp @@ -1,175 +1,175 @@ /* - Copyright 2013-2014 Jan Grulich + Copyright 2013-2018 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "networkitemslist.h" #include "networkmodelitem.h" -NetworkItemsList::NetworkItemsList(QObject* parent) +NetworkItemsList::NetworkItemsList(QObject *parent) : QObject(parent) { } NetworkItemsList::~NetworkItemsList() { qDeleteAll(m_items); } -bool NetworkItemsList::contains(const NetworkItemsList::FilterType type, const QString& parameter) const +bool NetworkItemsList::contains(const NetworkItemsList::FilterType type, const QString ¶meter) const { - Q_FOREACH (NetworkModelItem * item, m_items) { + for (NetworkModelItem *item : m_items) { switch (type) { case NetworkItemsList::ActiveConnection: if (item->activeConnectionPath() == parameter) { return true; } break; case NetworkItemsList::Connection: if (item->connectionPath() == parameter) { return true; } break; case NetworkItemsList::Device: if (item->devicePath() == parameter) { return true; } break; case NetworkItemsList::Name: if (item->name() == parameter) { return true; } break; case NetworkItemsList::Ssid: if (item->ssid() == parameter) { return true; } break; case NetworkItemsList::Uuid: if (item->uuid() == parameter) { return true; } break; case NetworkItemsList::Type: break; default: break; } } return false; } int NetworkItemsList::count() const { return m_items.count(); } -int NetworkItemsList::indexOf(NetworkModelItem* item) const +int NetworkItemsList::indexOf(NetworkModelItem *item) const { return m_items.indexOf(item); } -void NetworkItemsList::insertItem(NetworkModelItem* item) +void NetworkItemsList::insertItem(NetworkModelItem *item) { m_items << item; } -NetworkModelItem* NetworkItemsList::itemAt(int index) const +NetworkModelItem *NetworkItemsList::itemAt(int index) const { return m_items.at(index); } -QList< NetworkModelItem* > NetworkItemsList::items() const +QList< NetworkModelItem*> NetworkItemsList::items() const { return m_items; } -void NetworkItemsList::removeItem(NetworkModelItem* item) +void NetworkItemsList::removeItem(NetworkModelItem *item) { m_items.removeAll(item); } -QList< NetworkModelItem* > NetworkItemsList::returnItems(const NetworkItemsList::FilterType type, const QString& parameter, const QString& additionalParameter) const +QList< NetworkModelItem*> NetworkItemsList::returnItems(const NetworkItemsList::FilterType type, const QString ¶meter, const QString &additionalParameter) const { QList result; - Q_FOREACH (NetworkModelItem * item, m_items) { + for (NetworkModelItem *item : m_items) { switch (type) { case NetworkItemsList::ActiveConnection: if (item->activeConnectionPath() == parameter) { result << item; } break; case NetworkItemsList::Connection: if (item->connectionPath() == parameter) { if (additionalParameter.isEmpty()) { result << item; } else { if (item->devicePath() == additionalParameter) { result << item; } } } break; case NetworkItemsList::Device: if (item->devicePath() == parameter) { result << item; } break; case NetworkItemsList::Name: if (item->name() == parameter) { result << item; } break; case NetworkItemsList::Ssid: if (item->ssid() == parameter) { if (additionalParameter.isEmpty()) { result << item; } else { if (item->devicePath() == additionalParameter) { result << item; } } } break; case NetworkItemsList::Uuid: if (item->uuid() == parameter) { result << item; } break; case NetworkItemsList::Type: break; } } return result; } -QList< NetworkModelItem* > NetworkItemsList::returnItems(const NetworkItemsList::FilterType type, NetworkManager::ConnectionSettings::ConnectionType typeParameter) const +QList NetworkItemsList::returnItems(const NetworkItemsList::FilterType type, NetworkManager::ConnectionSettings::ConnectionType typeParameter) const { QList result; - Q_FOREACH (NetworkModelItem * item, m_items) { + for (NetworkModelItem *item : m_items) { if (type == NetworkItemsList::Type) { if (item->type() == typeParameter) { result << item; } } } return result; } diff --git a/libs/models/networkitemslist.h b/libs/models/networkitemslist.h index 7a506375..3c834406 100644 --- a/libs/models/networkitemslist.h +++ b/libs/models/networkitemslist.h @@ -1,61 +1,61 @@ /* - Copyright 2013-2014 Jan Grulich + Copyright 2013-2018 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_MODEL_NETWORK_ITEMS_LIST_H #define PLASMA_NM_MODEL_NETWORK_ITEMS_LIST_H #include #include class NetworkModelItem; class NetworkItemsList : public QObject { Q_OBJECT public: enum FilterType { ActiveConnection, Connection, Device, Name, Ssid, Uuid, Type }; - explicit NetworkItemsList(QObject* parent = 0); - virtual ~NetworkItemsList(); + explicit NetworkItemsList(QObject *parent = nullptr); + ~NetworkItemsList() override; - bool contains(const FilterType type, const QString& parameter) const; + bool contains(const FilterType type, const QString ¶meter) const; int count() const; - int indexOf(NetworkModelItem * item) const; - NetworkModelItem * itemAt(int index) const; + int indexOf(NetworkModelItem *item) const; + NetworkModelItem *itemAt(int index) const; QList items() const; - QList returnItems(const FilterType type, const QString& parameter, const QString& additionalParameter = QString()) const; + QList returnItems(const FilterType type, const QString ¶meter, const QString &additionalParameter = QString()) const; QList returnItems(const FilterType type, NetworkManager::ConnectionSettings::ConnectionType typeParameter) const; - void insertItem(NetworkModelItem * item); - void removeItem(NetworkModelItem * item); + void insertItem(NetworkModelItem *item); + void removeItem(NetworkModelItem *item); private: QList m_items; }; #endif // PLASMA_NM_MODEL_NETWORK_ITEMS_LIST_H diff --git a/libs/models/networkmodel.cpp b/libs/models/networkmodel.cpp index 82c3af74..d6215d73 100644 --- a/libs/models/networkmodel.cpp +++ b/libs/models/networkmodel.cpp @@ -1,1007 +1,1049 @@ /* - Copyright 2013-2014 Jan Grulich + Copyright 2013-2018 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "networkmodel.h" #include "networkmodelitem.h" #include "debug.h" #include "uiutils.h" #if WITH_MODEMMANAGER_SUPPORT #include #include #endif #include #include -NetworkModel::NetworkModel(QObject* parent) +NetworkModel::NetworkModel(QObject *parent) : QAbstractListModel(parent) { QLoggingCategory::setFilterRules(QStringLiteral("plasma-nm.debug = false")); initialize(); } NetworkModel::~NetworkModel() { } -QVariant NetworkModel::data(const QModelIndex& index, int role) const +QVariant NetworkModel::data(const QModelIndex &index, int role) const { const int row = index.row(); if (row >= 0 && row < m_list.count()) { - NetworkModelItem * item = m_list.itemAt(row); + NetworkModelItem *item = m_list.itemAt(row); switch (role) { case ConnectionDetailsRole: return item->details(); case ConnectionIconRole: return item->icon(); case ConnectionPathRole: return item->connectionPath(); case ConnectionStateRole: return item->connectionState(); case DeviceName: return item->deviceName(); case DevicePathRole: return item->devicePath(); case DeviceStateRole: return item->deviceState(); case DuplicateRole: return item->duplicate(); case ItemUniqueNameRole: if (m_list.returnItems(NetworkItemsList::Name, item->name()).count() > 1) { return item->originalName(); } else { return item->name(); } case ItemTypeRole: return item->itemType(); case LastUsedRole: return UiUtils::formatLastUsedDateRelative(item->timestamp()); case LastUsedDateOnlyRole: return UiUtils::formatDateRelative(item->timestamp()); case NameRole: return item->name(); case SectionRole: return item->sectionType(); case SignalRole: return item->signal(); case SlaveRole: return item->slave(); case SsidRole: return item->ssid(); case SpecificPathRole: return item->specificPath(); case SecurityTypeRole: return item->securityType(); case SecurityTypeStringRole: return UiUtils::labelFromWirelessSecurity(item->securityType()); case TimeStampRole: return item->timestamp(); case TypeRole: return item->type(); case UniRole: return item->uni(); case UuidRole: return item->uuid(); case VpnState: return item->vpnState(); case VpnType: return item->vpnType(); + case RxBytesRole: + return item->rxBytes(); + case TxBytesRole: + return item->txBytes(); default: break; } } return QVariant(); } -int NetworkModel::rowCount(const QModelIndex& parent) const +int NetworkModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return parent.isValid() ? 0 : m_list.count(); } -QHash< int, QByteArray > NetworkModel::roleNames() const +QHash NetworkModel::roleNames() const { QHash roles = QAbstractListModel::roleNames(); roles[ConnectionDetailsRole] = "ConnectionDetails"; roles[ConnectionIconRole] = "ConnectionIcon"; roles[ConnectionPathRole] = "ConnectionPath"; roles[ConnectionStateRole] = "ConnectionState"; roles[DeviceName] = "DeviceName"; roles[DevicePathRole] = "DevicePath"; roles[DeviceStateRole] = "DeviceState"; roles[DuplicateRole] = "Duplicate"; roles[ItemUniqueNameRole] = "ItemUniqueName"; roles[ItemTypeRole] = "ItemType"; roles[LastUsedRole] = "LastUsed"; roles[LastUsedDateOnlyRole] = "LastUsedDateOnly"; roles[NameRole] = "Name"; roles[SectionRole] = "Section"; roles[SignalRole] = "Signal"; roles[SlaveRole] = "Slave"; roles[SsidRole] = "Ssid"; roles[SpecificPathRole] = "SpecificPath"; roles[SecurityTypeRole] = "SecurityType"; roles[SecurityTypeStringRole] = "SecurityTypeString"; roles[TimeStampRole] = "TimeStamp"; roles[TypeRole] = "Type"; roles[UniRole] = "Uni"; roles[UuidRole] = "Uuid"; roles[VpnState] = "VpnState"; roles[VpnType] = "VpnType"; + roles[RxBytesRole] = "RxBytes"; + roles[TxBytesRole] = "TxBytes"; return roles; } void NetworkModel::initialize() { // Initialize existing connections - Q_FOREACH (const NetworkManager::Connection::Ptr& connection, NetworkManager::listConnections()) { + for (const NetworkManager::Connection::Ptr &connection : NetworkManager::listConnections()) { addConnection(connection); } // Initialize existing devices - Q_FOREACH (const NetworkManager::Device::Ptr& dev, NetworkManager::networkInterfaces()) { + for (const NetworkManager::Device::Ptr &dev : NetworkManager::networkInterfaces()) { addDevice(dev); } // Initialize existing active connections - Q_FOREACH (const NetworkManager::ActiveConnection::Ptr& active, NetworkManager::activeConnections()) { + for (const NetworkManager::ActiveConnection::Ptr &active : NetworkManager::activeConnections()) { addActiveConnection(active); } initializeSignals(); } void NetworkModel::initializeSignals() { connect(NetworkManager::notifier(), &NetworkManager::Notifier::activeConnectionAdded, this, &NetworkModel::activeConnectionAdded, Qt::UniqueConnection); connect(NetworkManager::notifier(), &NetworkManager::Notifier::activeConnectionRemoved, this, &NetworkModel::activeConnectionRemoved, Qt::UniqueConnection); connect(NetworkManager::settingsNotifier(), &NetworkManager::SettingsNotifier::connectionAdded, this, &NetworkModel::connectionAdded, Qt::UniqueConnection); connect(NetworkManager::settingsNotifier(), &NetworkManager::SettingsNotifier::connectionRemoved, this, &NetworkModel::connectionRemoved, Qt::UniqueConnection); connect(NetworkManager::notifier(), &NetworkManager::Notifier::deviceAdded, this, &NetworkModel::deviceAdded, Qt::UniqueConnection); connect(NetworkManager::notifier(), &NetworkManager::Notifier::deviceRemoved, this, &NetworkModel::deviceRemoved, Qt::UniqueConnection); connect(NetworkManager::notifier(), &NetworkManager::Notifier::statusChanged, this, &NetworkModel::statusChanged, Qt::UniqueConnection); } -void NetworkModel::initializeSignals(const NetworkManager::ActiveConnection::Ptr& activeConnection) +void NetworkModel::initializeSignals(const NetworkManager::ActiveConnection::Ptr &activeConnection) { if (activeConnection->vpn()) { NetworkManager::VpnConnection::Ptr vpnConnection = activeConnection.objectCast(); if (vpnConnection) { connect(vpnConnection.data(), &NetworkManager::VpnConnection::stateChanged, this, &NetworkModel::activeVpnConnectionStateChanged, Qt::UniqueConnection); } } else { connect(activeConnection.data(), &NetworkManager::ActiveConnection::stateChanged, this, &NetworkModel::activeConnectionStateChanged, Qt::UniqueConnection); } } -void NetworkModel::initializeSignals(const NetworkManager::Connection::Ptr& connection) +void NetworkModel::initializeSignals(const NetworkManager::Connection::Ptr &connection) { connect(connection.data(), &NetworkManager::Connection::updated, this, &NetworkModel::connectionUpdated, Qt::UniqueConnection); } -void NetworkModel::initializeSignals(const NetworkManager::Device::Ptr& device) +void NetworkModel::initializeSignals(const NetworkManager::Device::Ptr &device) { connect(device.data(), &NetworkManager::Device::availableConnectionAppeared, this, &NetworkModel::availableConnectionAppeared, Qt::UniqueConnection); connect(device.data(), &NetworkManager::Device::availableConnectionDisappeared, this, &NetworkModel::availableConnectionDisappeared, Qt::UniqueConnection); connect(device.data(), &NetworkManager::Device::ipV4ConfigChanged, this, &NetworkModel::ipConfigChanged, Qt::UniqueConnection); connect(device.data(), &NetworkManager::Device::ipV6ConfigChanged, this, &NetworkModel::ipConfigChanged, Qt::UniqueConnection); connect(device.data(), &NetworkManager::Device::ipInterfaceChanged, this, &NetworkModel::ipInterfaceChanged); connect(device.data(), &NetworkManager::Device::stateChanged, this, &NetworkModel::deviceStateChanged, Qt::UniqueConnection); + auto deviceStatistics = device->deviceStatistics(); + connect(deviceStatistics.data(), &NetworkManager::DeviceStatistics::rxBytesChanged, this, [this, device](qulonglong rxBytes) { + for (auto *item : m_list.returnItems(NetworkItemsList::Device, device->uni())) { + item->setRxBytes(rxBytes); + updateItem(item); + } + }); + connect(deviceStatistics.data(), &NetworkManager::DeviceStatistics::txBytesChanged, this, [this, device](qulonglong txBytes) { + for (auto *item : m_list.returnItems(NetworkItemsList::Device, device->uni())) { + item->setTxBytes(txBytes); + updateItem(item); + } + }); + if (device->type() == NetworkManager::Device::Wifi) { NetworkManager::WirelessDevice::Ptr wifiDev = device.objectCast(); connect(wifiDev.data(), &NetworkManager::WirelessDevice::networkAppeared, this, &NetworkModel::wirelessNetworkAppeared, Qt::UniqueConnection); connect(wifiDev.data(), &NetworkManager::WirelessDevice::networkDisappeared, this, &NetworkModel::wirelessNetworkDisappeared, Qt::UniqueConnection); } #if WITH_MODEMMANAGER_SUPPORT else if (device->type() == NetworkManager::Device::Modem) { ModemManager::ModemDevice::Ptr modem = ModemManager::findModemDevice(device->udi()); if (modem) { if (modem->hasInterface(ModemManager::ModemDevice::ModemInterface)) { ModemManager::Modem::Ptr modemNetwork = modem->interface(ModemManager::ModemDevice::ModemInterface).objectCast(); if (modemNetwork) { connect(modemNetwork.data(), &ModemManager::Modem::signalQualityChanged, this, &NetworkModel::gsmNetworkSignalQualityChanged, Qt::UniqueConnection); connect(modemNetwork.data(), &ModemManager::Modem::accessTechnologiesChanged, this, &NetworkModel::gsmNetworkAccessTechnologiesChanged, Qt::UniqueConnection); connect(modemNetwork.data(), &ModemManager::Modem::currentModesChanged, this, &NetworkModel::gsmNetworkCurrentModesChanged, Qt::UniqueConnection); } } } } #endif } -void NetworkModel::initializeSignals(const NetworkManager::WirelessNetwork::Ptr& network) +void NetworkModel::initializeSignals(const NetworkManager::WirelessNetwork::Ptr &network) { connect(network.data(), &NetworkManager::WirelessNetwork::signalStrengthChanged, this, &NetworkModel::wirelessNetworkSignalChanged, Qt::UniqueConnection); connect(network.data(), &NetworkManager::WirelessNetwork::referenceAccessPointChanged, this, &NetworkModel::wirelessNetworkReferenceApChanged, Qt::UniqueConnection); } -void NetworkModel::addActiveConnection(const NetworkManager::ActiveConnection::Ptr& activeConnection) +void NetworkModel::addActiveConnection(const NetworkManager::ActiveConnection::Ptr &activeConnection) { initializeSignals(activeConnection); NetworkManager::Device::Ptr device; NetworkManager::Connection::Ptr connection = activeConnection->connection(); // Not necessary to have device for VPN connections if (activeConnection && !activeConnection->vpn() && !activeConnection->devices().isEmpty()) { device = NetworkManager::findNetworkInterface(activeConnection->devices().first()); } // Check whether we have a base connection if (!m_list.contains(NetworkItemsList::Uuid, connection->uuid())) { // Active connection appeared before a base connection, so we have to add its base connection first addConnection(connection); } beginResetModel(); - Q_FOREACH (NetworkModelItem * item, m_list.returnItems(NetworkItemsList::NetworkItemsList::Uuid, connection->uuid())) { + for (NetworkModelItem *item : m_list.returnItems(NetworkItemsList::NetworkItemsList::Uuid, connection->uuid())) { if (((device && device->uni() == item->devicePath()) || item->devicePath().isEmpty()) || item->type() == NetworkManager::ConnectionSettings::Vpn) { item->setActiveConnectionPath(activeConnection->path()); item->setConnectionState(activeConnection->state()); if (activeConnection->vpn()) { NetworkManager::VpnConnection::Ptr vpnConnection = activeConnection.objectCast(); NetworkManager::VpnConnection::State state = vpnConnection->state(); if (state == NetworkManager::VpnConnection::Prepare || state == NetworkManager::VpnConnection::NeedAuth || state == NetworkManager::VpnConnection::Connecting || state == NetworkManager::VpnConnection::GettingIpConfig) { item->setConnectionState(NetworkManager::ActiveConnection::Activating); } else if (state == NetworkManager::VpnConnection::Activated) { item->setConnectionState(NetworkManager::ActiveConnection::Activated); } else { item->setConnectionState(NetworkManager::ActiveConnection::Deactivated); } item->setVpnState(state); } - item->updateDetails(); + item->invalidateDetails(); qCDebug(PLASMA_NM) << "Item " << item->name() << ": active connection state changed to " << item->connectionState(); + + if (device && device->uni() == item->devicePath()) { + auto deviceStatistics = device->deviceStatistics(); + item->setRxBytes(deviceStatistics->rxBytes()); + item->setTxBytes(deviceStatistics->txBytes()); + } } } endResetModel(); } -void NetworkModel::addAvailableConnection(const QString& connection, const NetworkManager::Device::Ptr& device) +void NetworkModel::addAvailableConnection(const QString &connection, const NetworkManager::Device::Ptr &device) { - checkAndCreateDuplicate(connection, device); + if (!device) { + return; + } - Q_FOREACH (NetworkModelItem * item, m_list.returnItems(NetworkItemsList::Connection, connection)) { + checkAndCreateDuplicate(connection, device->uni()); + + for (NetworkModelItem *item : m_list.returnItems(NetworkItemsList::Connection, connection)) { // The item is already associated with another device - if (!item->devicePath().isEmpty()) { + if (!device || !item->devicePath().isEmpty()) { continue; } if (device->ipInterfaceName().isEmpty()) { item->setDeviceName(device->interfaceName()); } else { item->setDeviceName(device->ipInterfaceName()); } + item->setDevicePath(device->uni()); item->setDeviceState(device->state()); qCDebug(PLASMA_NM) << "Item " << item->name() << ": device changed to " << item->devicePath(); #if WITH_MODEMMANAGER_SUPPORT if (device->type() == NetworkManager::Device::Modem) { ModemManager::ModemDevice::Ptr modemDevice = ModemManager::findModemDevice(device->udi()); if (modemDevice) { ModemManager::Modem::Ptr modemInterface = modemDevice->interface(ModemManager::ModemDevice::ModemInterface).objectCast(); if (modemInterface) { item->setSignal(modemInterface->signalQuality().signal); qCDebug(PLASMA_NM) << "Item " << item->name() << ": signal changed to " << item->signal(); } } } #endif if (item->type() == NetworkManager::ConnectionSettings::Wireless && item->mode() == NetworkManager::WirelessSetting::Infrastructure) { // Find an accesspoint which could be removed, because it will be merged with a connection - Q_FOREACH (NetworkModelItem * secondItem, m_list.returnItems(NetworkItemsList::Ssid, item->ssid())) { + for (NetworkModelItem *secondItem : m_list.returnItems(NetworkItemsList::Ssid, item->ssid())) { if (secondItem->itemType() == NetworkModelItem::AvailableAccessPoint && secondItem->devicePath() == item->devicePath()) { const int row = m_list.indexOf(secondItem); qCDebug(PLASMA_NM) << "Access point " << secondItem->name() << ": merged to " << item->name() << " connection"; if (row >= 0) { beginRemoveRows(QModelIndex(), row, row); m_list.removeItem(secondItem); secondItem->deleteLater(); endRemoveRows(); } break; } } NetworkManager::WirelessDevice::Ptr wifiDevice = device.objectCast(); if (wifiDevice) { NetworkManager::WirelessNetwork::Ptr wifiNetwork = wifiDevice->findNetwork(item->ssid()); if (wifiNetwork) { updateFromWirelessNetwork(item, wifiNetwork, wifiDevice); } } } updateItem(item); break; } } -void NetworkModel::addConnection(const NetworkManager::Connection::Ptr& connection) +void NetworkModel::addConnection(const NetworkManager::Connection::Ptr &connection) { // Can't add a connection without name or uuid if (connection->name().isEmpty() || connection->uuid().isEmpty()) { return; } initializeSignals(connection); NetworkManager::ConnectionSettings::Ptr settings = connection->settings(); NetworkManager::VpnSetting::Ptr vpnSetting; NetworkManager::WirelessSetting::Ptr wirelessSetting; if (settings->connectionType() == NetworkManager::ConnectionSettings::Vpn) { vpnSetting = settings->setting(NetworkManager::Setting::Vpn).dynamicCast(); } else if (settings->connectionType() == NetworkManager::ConnectionSettings::Wireless) { wirelessSetting = settings->setting(NetworkManager::Setting::Wireless).dynamicCast(); } // Check whether the connection is already in the model to avoid duplicates, but this shouldn't happen if (!m_list.contains(NetworkItemsList::Connection, connection->path())) { - NetworkModelItem * item = new NetworkModelItem(); + NetworkModelItem *item = new NetworkModelItem(); item->setConnectionPath(connection->path()); item->setName(settings->id()); item->setTimestamp(settings->timestamp()); item->setType(settings->connectionType()); item->setUuid(settings->uuid()); item->setSlave(settings->isSlave()); if (item->type() == NetworkManager::ConnectionSettings::Vpn) { item->setVpnType(vpnSetting->serviceType().section('.', -1)); } else if (item->type() == NetworkManager::ConnectionSettings::Wireless) { item->setMode(wirelessSetting->mode()); item->setSecurityType(NetworkManager::securityTypeFromConnectionSetting(settings)); item->setSsid(QString::fromUtf8(wirelessSetting->ssid())); } - item->updateDetails(); + item->invalidateDetails(); const int index = m_list.count(); beginInsertRows(QModelIndex(), index, index); m_list.insertItem(item); endInsertRows(); qCDebug(PLASMA_NM) << "New connection " << item->name() << " added"; } } -void NetworkModel::addDevice(const NetworkManager::Device::Ptr& device) +void NetworkModel::addDevice(const NetworkManager::Device::Ptr &device) { initializeSignals(device); if (device->type() == NetworkManager::Device::Wifi) { NetworkManager::WirelessDevice::Ptr wifiDev = device.objectCast(); - Q_FOREACH (const NetworkManager::WirelessNetwork::Ptr& wifiNetwork, wifiDev->networks()) { + for (const NetworkManager::WirelessNetwork::Ptr &wifiNetwork : wifiDev->networks()) { addWirelessNetwork(wifiNetwork, wifiDev); } } - Q_FOREACH (const NetworkManager::Connection::Ptr & connection, device->availableConnections()) { + for (const NetworkManager::Connection::Ptr &connection : device->availableConnections()) { addAvailableConnection(connection->path(), device); } } -void NetworkModel::addWirelessNetwork(const NetworkManager::WirelessNetwork::Ptr& network, const NetworkManager::WirelessDevice::Ptr& device) +void NetworkModel::addWirelessNetwork(const NetworkManager::WirelessNetwork::Ptr &network, const NetworkManager::WirelessDevice::Ptr &device) { initializeSignals(network); // BUG: 386342 // When creating a new hidden wireless network and attempting to connect to it, NM then later reports that AccessPoint appeared, but // it doesn't know its SSID from some reason, this also makes Wireless device to advertise a new available connection, which we later // attempt to merge with an AP, based on its SSID, but it doesn't find any, because we have AP with empty SSID. After this we get another // AccessPoint appeared signal, this time we know SSID, but we don't attempt any merging, because it's usually the other way around, thus // we need to attempt to merge it here with a connection we guess it's related to this new AP - Q_FOREACH (NetworkModelItem * item, m_list.returnItems(NetworkItemsList::Type, NetworkManager::ConnectionSettings::Wireless)) { + for (NetworkModelItem *item : m_list.returnItems(NetworkItemsList::Type, NetworkManager::ConnectionSettings::Wireless)) { if (item->itemType() == NetworkModelItem::AvailableConnection) { NetworkManager::ConnectionSettings::Ptr connectionSettings = NetworkManager::findConnection(item->connectionPath())->settings(); if (connectionSettings && connectionSettings->connectionType() == NetworkManager::ConnectionSettings::Wireless) { NetworkManager::WirelessSetting::Ptr wirelessSetting = connectionSettings->setting(NetworkManager::Setting::Wireless).dynamicCast(); if (QString::fromUtf8(wirelessSetting->ssid()) == network->ssid()) { const QString bssid = NetworkManager::macAddressAsString(wirelessSetting->bssid()); const QString restrictedHw = NetworkManager::macAddressAsString(wirelessSetting->macAddress()); if ((bssid.isEmpty() || bssid == network->referenceAccessPoint()->hardwareAddress()) && (restrictedHw.isEmpty() || restrictedHw == device->hardwareAddress())) { updateFromWirelessNetwork(item, network, device); return; } } } } } NetworkManager::WirelessSetting::NetworkMode mode = NetworkManager::WirelessSetting::Infrastructure; NetworkManager::WirelessSecurityType securityType = NetworkManager::UnknownSecurity; NetworkManager::AccessPoint::Ptr ap = network->referenceAccessPoint(); if (ap && ap->capabilities().testFlag(NetworkManager::AccessPoint::Privacy)) { securityType = NetworkManager::findBestWirelessSecurity(device->wirelessCapabilities(), true, (device->mode() == NetworkManager::WirelessDevice::Adhoc), - ap->capabilities(), ap->wpaFlags(), ap->rsnFlags()); + ap->capabilities(), ap->wpaFlags(), ap->rsnFlags()); if (network->referenceAccessPoint()->mode() == NetworkManager::AccessPoint::Infra) { mode = NetworkManager::WirelessSetting::Infrastructure; } else if (network->referenceAccessPoint()->mode() == NetworkManager::AccessPoint::Adhoc) { mode = NetworkManager::WirelessSetting::Adhoc; } else if (network->referenceAccessPoint()->mode() == NetworkManager::AccessPoint::ApMode) { mode = NetworkManager::WirelessSetting::Ap; } } - NetworkModelItem * item = new NetworkModelItem(); + NetworkModelItem *item = new NetworkModelItem(); if (device->ipInterfaceName().isEmpty()) { item->setDeviceName(device->interfaceName()); } else { item->setDeviceName(device->ipInterfaceName()); } item->setDevicePath(device->uni()); item->setMode(mode); item->setName(network->ssid()); item->setSignal(network->signalStrength()); item->setSpecificPath(network->referenceAccessPoint()->uni()); item->setSsid(network->ssid()); item->setType(NetworkManager::ConnectionSettings::Wireless); item->setSecurityType(securityType); - item->updateDetails(); + item->invalidateDetails(); const int index = m_list.count(); beginInsertRows(QModelIndex(), index, index); m_list.insertItem(item); endInsertRows(); qCDebug(PLASMA_NM) << "New wireless network " << item->name() << " added"; } -void NetworkModel::checkAndCreateDuplicate(const QString& connection, const NetworkManager::Device::Ptr& device) +void NetworkModel::checkAndCreateDuplicate(const QString &connection, const QString &deviceUni) { bool createDuplicate = false; - NetworkModelItem * originalItem = 0; + NetworkModelItem *originalItem = nullptr; - Q_FOREACH (NetworkModelItem * item, m_list.returnItems(NetworkItemsList::Connection, connection)) { + for (NetworkModelItem *item : m_list.returnItems(NetworkItemsList::Connection, connection)) { if (!item->duplicate()) { originalItem = item; } - if (!item->duplicate() && item->itemType() == NetworkModelItem::AvailableConnection && (item->devicePath() != device->uni() && !item->devicePath().isEmpty())) { + if (!item->duplicate() && item->itemType() == NetworkModelItem::AvailableConnection && (item->devicePath() != deviceUni && !item->devicePath().isEmpty())) { createDuplicate = true; } } if (createDuplicate) { - NetworkModelItem * duplicatedItem = new NetworkModelItem(originalItem); - duplicatedItem->updateDetails(); + NetworkModelItem *duplicatedItem = new NetworkModelItem(originalItem); + duplicatedItem->invalidateDetails(); const int index = m_list.count(); beginInsertRows(QModelIndex(), index, index); m_list.insertItem(duplicatedItem); endInsertRows(); } } void NetworkModel::onItemUpdated() { - NetworkModelItem * item = static_cast(sender()); + NetworkModelItem *item = static_cast(sender()); if (item) { updateItem(item); } } -void NetworkModel::updateItem(NetworkModelItem * item) +void NetworkModel::setDeviceStatisticsRefreshRateMs(const QString &devicePath, uint refreshRate) +{ + NetworkManager::Device::Ptr device = NetworkManager::findNetworkInterface(devicePath); + + if (device) { + device->deviceStatistics()->setRefreshRateMs(refreshRate); + } +} + +void NetworkModel::updateItem(NetworkModelItem*item) { const int row = m_list.indexOf(item); if (row >= 0) { - item->updateDetails(); + item->invalidateDetails(); QModelIndex index = createIndex(row, 0); Q_EMIT dataChanged(index, index); } } void NetworkModel::accessPointSignalStrengthChanged(int signal) { - NetworkManager::AccessPoint * apPtr = qobject_cast(sender()); + NetworkManager::AccessPoint *apPtr = qobject_cast(sender()); if (apPtr) { - Q_FOREACH (NetworkModelItem * item, m_list.returnItems(NetworkItemsList::Ssid, apPtr->ssid())) { + for (NetworkModelItem *item : m_list.returnItems(NetworkItemsList::Ssid, apPtr->ssid())) { if (item->specificPath() == apPtr->uni()) { item->setSignal(signal); updateItem(item); qCDebug(PLASMA_NM) << "AccessPoint " << item->name() << ": signal changed to " << item->signal(); } } } } -void NetworkModel::activeConnectionAdded(const QString& activeConnection) +void NetworkModel::activeConnectionAdded(const QString &activeConnection) { NetworkManager::ActiveConnection::Ptr activeCon = NetworkManager::findActiveConnection(activeConnection); if (activeCon) { addActiveConnection(activeCon); } } -void NetworkModel::activeConnectionRemoved(const QString& activeConnection) +void NetworkModel::activeConnectionRemoved(const QString &activeConnection) { - Q_FOREACH (NetworkModelItem * item, m_list.returnItems(NetworkItemsList::ActiveConnection, activeConnection)) { + for (NetworkModelItem *item : m_list.returnItems(NetworkItemsList::ActiveConnection, activeConnection)) { item->setActiveConnectionPath(QString()); item->setConnectionState(NetworkManager::ActiveConnection::Deactivated); item->setVpnState(NetworkManager::VpnConnection::Disconnected); updateItem(item); qCDebug(PLASMA_NM) << "Item " << item->name() << ": active connection removed"; } } void NetworkModel::activeConnectionStateChanged(NetworkManager::ActiveConnection::State state) { - NetworkManager::ActiveConnection * activePtr = qobject_cast(sender()); + NetworkManager::ActiveConnection *activePtr = qobject_cast(sender()); if (activePtr) { beginResetModel(); - Q_FOREACH (NetworkModelItem * item, m_list.returnItems(NetworkItemsList::ActiveConnection, activePtr->path())) { + for (NetworkModelItem *item : m_list.returnItems(NetworkItemsList::ActiveConnection, activePtr->path())) { item->setConnectionState(state); - item->updateDetails(); + item->invalidateDetails(); qCDebug(PLASMA_NM) << "Item " << item->name() << ": active connection changed to " << item->connectionState(); } endResetModel(); } } void NetworkModel::activeVpnConnectionStateChanged(NetworkManager::VpnConnection::State state, NetworkManager::VpnConnection::StateChangeReason reason) { Q_UNUSED(reason) NetworkManager::ActiveConnection *activePtr = qobject_cast(sender()); if (activePtr) { - Q_FOREACH (NetworkModelItem * item, m_list.returnItems(NetworkItemsList::ActiveConnection, activePtr->path())) { + for (NetworkModelItem *item : m_list.returnItems(NetworkItemsList::ActiveConnection, activePtr->path())) { if (state == NetworkManager::VpnConnection::Prepare || state == NetworkManager::VpnConnection::NeedAuth || state == NetworkManager::VpnConnection::Connecting || state == NetworkManager::VpnConnection::GettingIpConfig) { item->setConnectionState(NetworkManager::ActiveConnection::Activating); } else if (state == NetworkManager::VpnConnection::Activated) { item->setConnectionState(NetworkManager::ActiveConnection::Activated); } else { item->setConnectionState(NetworkManager::ActiveConnection::Deactivated); } item->setVpnState(state); updateItem(item); qCDebug(PLASMA_NM) << "Item " << item->name() << ": active connection changed to " << item->connectionState(); } } } -void NetworkModel::availableConnectionAppeared(const QString& connection) +void NetworkModel::availableConnectionAppeared(const QString &connection) { NetworkManager::Device::Ptr device = NetworkManager::findNetworkInterface(qobject_cast(sender())->uni()); - addAvailableConnection(connection, device); + if (device) { + addAvailableConnection(connection, device); + } } -void NetworkModel::availableConnectionDisappeared(const QString& connection) +void NetworkModel::availableConnectionDisappeared(const QString &connection) { - Q_FOREACH (NetworkModelItem * item, m_list.returnItems(NetworkItemsList::Connection, connection)) { + for (NetworkModelItem *item : m_list.returnItems(NetworkItemsList::Connection, connection)) { bool available = false; const QString devicePath = item->devicePath(); const QString specificPath = item->specificPath(); // We have to check whether the connection is still available, because it might be // presented in the model for more devices and we don't want to remove it for all of them. // Check whether the device is still available NetworkManager::Device::Ptr device = NetworkManager::findNetworkInterface(devicePath); if (device) { // Check whether the connection is still listed as available - Q_FOREACH (const NetworkManager::Connection::Ptr & connection, device->availableConnections()) { + for (const NetworkManager::Connection::Ptr &connection : device->availableConnections()) { if (connection->path() == item->connectionPath()) { available = true; break; } } } if (!available) { item->setDeviceName(QString()); item->setDevicePath(QString()); item->setDeviceState(NetworkManager::Device::UnknownState); item->setSignal(0); item->setSpecificPath(QString()); qCDebug(PLASMA_NM) << "Item " << item->name() << " removed as available connection"; // Check whether the connection is still available as an access point, this happens // when we change its properties, like ssid, bssid, security etc. if (item->type() == NetworkManager::ConnectionSettings::Wireless && !specificPath.isEmpty()) { if (device && device->type() == NetworkManager::Device::Wifi) { NetworkManager::WirelessDevice::Ptr wifiDevice = device.objectCast(); if (wifiDevice) { NetworkManager::AccessPoint::Ptr ap = wifiDevice->findAccessPoint(specificPath); if (ap) { NetworkManager::WirelessNetwork::Ptr network = wifiDevice->findNetwork(ap->ssid()); if (network) { addWirelessNetwork(network, wifiDevice); } } } } } if (item->duplicate()) { const int row = m_list.indexOf(item); if (row >= 0) { qCDebug(PLASMA_NM) << "Duplicate item " << item->name() << " removed completely"; beginRemoveRows(QModelIndex(), row, row); m_list.removeItem(item); item->deleteLater(); endRemoveRows(); } } else { updateItem(item); } } available = false; } } -void NetworkModel::connectionAdded(const QString& connection) +void NetworkModel::connectionAdded(const QString &connection) { NetworkManager::Connection::Ptr newConnection = NetworkManager::findConnection(connection); if (newConnection) { addConnection(newConnection); } } -void NetworkModel::connectionRemoved(const QString& connection) +void NetworkModel::connectionRemoved(const QString &connection) { bool remove = false; - Q_FOREACH (NetworkModelItem * item, m_list.returnItems(NetworkItemsList::Connection, connection)) { + for (NetworkModelItem *item : m_list.returnItems(NetworkItemsList::Connection, connection)) { // When the item type is wireless, we can remove only the connection and leave it as an available access point if (item->type() == NetworkManager::ConnectionSettings::Wireless && !item->devicePath().isEmpty()) { - Q_FOREACH (NetworkModelItem * secondItem, m_list.items()) { + for (NetworkModelItem *secondItem : m_list.items()) { // Remove it entirely when there is another connection with the same configuration and for the same device // or it's a shared connection if ((item->mode() != NetworkManager::WirelessSetting::Infrastructure) || (item->connectionPath() != secondItem->connectionPath() && item->devicePath() == secondItem->devicePath() && item->mode() == secondItem->mode() && item->securityType() == secondItem->securityType() && item->ssid() == secondItem->ssid())) { remove = true; break; } } if (!remove) { item->setConnectionPath(QString()); item->setName(item->ssid()); item->setSlave(false); item->setTimestamp(QDateTime()); item->setUuid(QString()); updateItem(item); qCDebug(PLASMA_NM) << "Item " << item->name() << ": connection removed"; } } else { remove = true; } if (remove) { const int row = m_list.indexOf(item); if (row >= 0) { qCDebug(PLASMA_NM) << "Item " << item->name() << " removed completely"; beginRemoveRows(QModelIndex(), row, row); m_list.removeItem(item); item->deleteLater(); endRemoveRows(); } } remove = false; } } void NetworkModel::connectionUpdated() { - NetworkManager::Connection * connectionPtr = qobject_cast(sender()); + NetworkManager::Connection *connectionPtr = qobject_cast(sender()); if (connectionPtr) { NetworkManager::ConnectionSettings::Ptr settings = connectionPtr->settings(); - Q_FOREACH (NetworkModelItem * item, m_list.returnItems(NetworkItemsList::Connection, connectionPtr->path())) { + for (NetworkModelItem *item : m_list.returnItems(NetworkItemsList::Connection, connectionPtr->path())) { item->setConnectionPath(connectionPtr->path()); item->setName(settings->id()); item->setTimestamp(settings->timestamp()); item->setType(settings->connectionType()); item->setUuid(settings->uuid()); if (item->type() == NetworkManager::ConnectionSettings::Wireless) { NetworkManager::WirelessSetting::Ptr wirelessSetting; wirelessSetting = settings->setting(NetworkManager::Setting::Wireless).dynamicCast(); item->setMode(wirelessSetting->mode()); item->setSecurityType(NetworkManager::securityTypeFromConnectionSetting(settings)); item->setSsid(QString::fromUtf8(wirelessSetting->ssid())); // TODO check whether BSSID has changed and update the wireless info } updateItem(item); qCDebug(PLASMA_NM) << "Item " << item->name() << ": connection updated"; } } } -void NetworkModel::deviceAdded(const QString& device) +void NetworkModel::deviceAdded(const QString &device) { NetworkManager::Device::Ptr dev = NetworkManager::findNetworkInterface(device); if (dev) { addDevice(dev); } } -void NetworkModel::deviceRemoved(const QString& device) +void NetworkModel::deviceRemoved(const QString &device) { // Make all items unavailable - Q_FOREACH (NetworkModelItem * item, m_list.returnItems(NetworkItemsList::Device, device)) { + for (NetworkModelItem *item : m_list.returnItems(NetworkItemsList::Device, device)) { availableConnectionDisappeared(item->connectionPath()); } } void NetworkModel::deviceStateChanged(NetworkManager::Device::State state, NetworkManager::Device::State oldState, NetworkManager::Device::StateChangeReason reason) { Q_UNUSED(oldState); Q_UNUSED(reason); NetworkManager::Device::Ptr device = NetworkManager::findNetworkInterface(qobject_cast(sender())->uni()); if (device) { beginResetModel(); - Q_FOREACH (NetworkModelItem * item, m_list.returnItems(NetworkItemsList::Device, device->uni())) { + for (NetworkModelItem *item : m_list.returnItems(NetworkItemsList::Device, device->uni())) { item->setDeviceState(state); - item->updateDetails(); + item->invalidateDetails(); // qCDebug(PLASMA_NM) << "Item " << item->name() << ": device state changed to " << item->deviceState(); } endResetModel(); } } #if WITH_MODEMMANAGER_SUPPORT void NetworkModel::gsmNetworkAccessTechnologiesChanged(QFlags accessTechnologies) { Q_UNUSED(accessTechnologies); - ModemManager::Modem * gsmNetwork = qobject_cast(sender()); + ModemManager::Modem *gsmNetwork = qobject_cast(sender()); if (gsmNetwork) { - Q_FOREACH (const NetworkManager::Device::Ptr & dev, NetworkManager::networkInterfaces()) { + for (const NetworkManager::Device::Ptr &dev : NetworkManager::networkInterfaces()) { if (dev->type() == NetworkManager::Device::Modem) { ModemManager::ModemDevice::Ptr modem = ModemManager::findModemDevice(dev->udi()); if (modem) { if (modem->hasInterface(ModemManager::ModemDevice::ModemInterface)) { ModemManager::Modem::Ptr modemNetwork = modem->interface(ModemManager::ModemDevice::ModemInterface).objectCast(); if (modemNetwork && modemNetwork->device() == gsmNetwork->device()) { // TODO store access technology internally? - Q_FOREACH (NetworkModelItem * item, m_list.returnItems(NetworkItemsList::Device, dev->uni())) { + for (NetworkModelItem *item : m_list.returnItems(NetworkItemsList::Device, dev->uni())) { updateItem(item); } } } } } } } } void NetworkModel::gsmNetworkCurrentModesChanged() { - ModemManager::Modem * gsmNetwork = qobject_cast(sender()); + ModemManager::Modem *gsmNetwork = qobject_cast(sender()); if (gsmNetwork) { - Q_FOREACH (const NetworkManager::Device::Ptr & dev, NetworkManager::networkInterfaces()) { + for (const NetworkManager::Device::Ptr &dev : NetworkManager::networkInterfaces()) { if (dev->type() == NetworkManager::Device::Modem) { ModemManager::ModemDevice::Ptr modem = ModemManager::findModemDevice(dev->udi()); if (modem) { if (modem->hasInterface(ModemManager::ModemDevice::ModemInterface)) { ModemManager::Modem::Ptr modemNetwork = modem->interface(ModemManager::ModemDevice::ModemInterface).objectCast(); if (modemNetwork && modemNetwork->device() == gsmNetwork->device()) { - Q_FOREACH (NetworkModelItem * item, m_list.returnItems(NetworkItemsList::Device, dev->uni())) { + for (NetworkModelItem *item : m_list.returnItems(NetworkItemsList::Device, dev->uni())) { updateItem(item); } } } } } } } } void NetworkModel::gsmNetworkSignalQualityChanged(const ModemManager::SignalQualityPair &signalQuality) { - ModemManager::Modem * gsmNetwork = qobject_cast(sender()); + ModemManager::Modem *gsmNetwork = qobject_cast(sender()); if (gsmNetwork) { - Q_FOREACH (const NetworkManager::Device::Ptr & dev, NetworkManager::networkInterfaces()) { + for (const NetworkManager::Device::Ptr &dev : NetworkManager::networkInterfaces()) { if (dev->type() == NetworkManager::Device::Modem) { ModemManager::ModemDevice::Ptr modem = ModemManager::findModemDevice(dev->udi()); if (modem) { if (modem->hasInterface(ModemManager::ModemDevice::ModemInterface)) { ModemManager::Modem::Ptr modemNetwork = modem->interface(ModemManager::ModemDevice::ModemInterface).objectCast(); if (modemNetwork && modemNetwork->device() == gsmNetwork->device()) { - Q_FOREACH (NetworkModelItem * item, m_list.returnItems(NetworkItemsList::Device, dev->uni())) { + for (NetworkModelItem *item : m_list.returnItems(NetworkItemsList::Device, dev->uni())) { item->setSignal(signalQuality.signal); updateItem(item); } } } } } } } } #endif void NetworkModel::ipConfigChanged() { NetworkManager::Device::Ptr device = NetworkManager::findNetworkInterface(qobject_cast(sender())->uni()); if (device) { - Q_FOREACH (NetworkModelItem * item, m_list.returnItems(NetworkItemsList::Device, device->uni())) { + for (NetworkModelItem *item : m_list.returnItems(NetworkItemsList::Device, device->uni())) { updateItem(item); // qCDebug(PLASMA_NM) << "Item " << item->name() << ": device ipconfig changed"; } } } void NetworkModel::ipInterfaceChanged() { - NetworkManager::Device * device = qobject_cast(sender()); + NetworkManager::Device *device = qobject_cast(sender()); if (device) { - Q_FOREACH (NetworkModelItem * item, m_list.returnItems(NetworkItemsList::Device, device->uni())) { + for (NetworkModelItem *item : m_list.returnItems(NetworkItemsList::Device, device->uni())) { if (device->ipInterfaceName().isEmpty()) { item->setDeviceName(device->interfaceName()); } else { item->setDeviceName(device->ipInterfaceName()); } } } } void NetworkModel::statusChanged(NetworkManager::Status status) { Q_UNUSED(status); qCDebug(PLASMA_NM) << "NetworkManager state changed to " << status; // This has probably effect only for VPN connections - Q_FOREACH (NetworkModelItem * item, m_list.returnItems(NetworkItemsList::Type, NetworkManager::ConnectionSettings::Vpn)) { + for (NetworkModelItem *item : m_list.returnItems(NetworkItemsList::Type, NetworkManager::ConnectionSettings::Vpn)) { updateItem(item); } } -void NetworkModel::wirelessNetworkAppeared(const QString& ssid) +void NetworkModel::wirelessNetworkAppeared(const QString &ssid) { NetworkManager::Device::Ptr device = NetworkManager::findNetworkInterface(qobject_cast(sender())->uni()); if (device && device->type() == NetworkManager::Device::Wifi) { NetworkManager::WirelessDevice::Ptr wirelessDevice = device.objectCast(); NetworkManager::WirelessNetwork::Ptr network = wirelessDevice->findNetwork(ssid); addWirelessNetwork(network, wirelessDevice); } } -void NetworkModel::wirelessNetworkDisappeared(const QString& ssid) +void NetworkModel::wirelessNetworkDisappeared(const QString &ssid) { NetworkManager::Device::Ptr device = NetworkManager::findNetworkInterface(qobject_cast(sender())->uni()); if (device) { - Q_FOREACH (NetworkModelItem * item, m_list.returnItems(NetworkItemsList::Ssid, ssid, device->uni())) { + for (NetworkModelItem *item : m_list.returnItems(NetworkItemsList::Ssid, ssid, device->uni())) { // Remove the entire item, because it's only AP or it's a duplicated available connection if (item->itemType() == NetworkModelItem::AvailableAccessPoint || item->duplicate()) { const int row = m_list.indexOf(item); if (row >= 0) { qCDebug(PLASMA_NM) << "Wireless network " << item->name() << " removed completely"; beginRemoveRows(QModelIndex(), row, row); m_list.removeItem(item); item->deleteLater(); endRemoveRows(); } // Remove only AP and device from the item and leave it as an unavailable connection } else { if (item->mode() == NetworkManager::WirelessSetting::Infrastructure) { item->setDeviceName(QString()); item->setDevicePath(QString()); item->setSpecificPath(QString()); } item->setSignal(0); updateItem(item); qCDebug(PLASMA_NM) << "Item " << item->name() << ": wireless network removed"; } } } } -void NetworkModel::wirelessNetworkReferenceApChanged(const QString& accessPoint) +void NetworkModel::wirelessNetworkReferenceApChanged(const QString &accessPoint) { - NetworkManager::WirelessNetwork * networkPtr = qobject_cast(sender()); + NetworkManager::WirelessNetwork *networkPtr = qobject_cast(sender()); if (networkPtr) { - Q_FOREACH (NetworkModelItem * item, m_list.returnItems(NetworkItemsList::Ssid, networkPtr->ssid(), networkPtr->device())) { + for (NetworkModelItem *item : m_list.returnItems(NetworkItemsList::Ssid, networkPtr->ssid(), networkPtr->device())) { NetworkManager::Connection::Ptr connection = NetworkManager::findConnection(item->connectionPath()); if (connection) { NetworkManager::WirelessSetting::Ptr wirelessSetting = connection->settings()->setting(NetworkManager::Setting::Wireless).staticCast(); if (wirelessSetting) { if (wirelessSetting->bssid().isEmpty()) { item->setSpecificPath(accessPoint); updateItem(item); } } } } } } void NetworkModel::wirelessNetworkSignalChanged(int signal) { - NetworkManager::WirelessNetwork * networkPtr = qobject_cast(sender()); + NetworkManager::WirelessNetwork *networkPtr = qobject_cast(sender()); if (networkPtr) { - Q_FOREACH (NetworkModelItem * item, m_list.returnItems(NetworkItemsList::Ssid, networkPtr->ssid(), networkPtr->device())) { + for (NetworkModelItem *item : m_list.returnItems(NetworkItemsList::Ssid, networkPtr->ssid(), networkPtr->device())) { if (item->specificPath() == networkPtr->referenceAccessPoint()->uni()) { item->setSignal(signal); updateItem(item); // qCDebug(PLASMA_NM) << "Wireless network " << item->name() << ": signal changed to " << item->signal(); } } } } NetworkManager::WirelessSecurityType NetworkModel::alternativeWirelessSecurity(const NetworkManager::WirelessSecurityType type) { if (type == NetworkManager::WpaPsk) { return NetworkManager::Wpa2Psk; } else if (type == NetworkManager::WpaEap) { return NetworkManager::Wpa2Eap; } else if (type == NetworkManager::Wpa2Psk) { return NetworkManager::WpaPsk; } else if (type == NetworkManager::Wpa2Eap) { return NetworkManager::WpaEap; } return type; } -void NetworkModel::updateFromWirelessNetwork(NetworkModelItem* item, const NetworkManager::WirelessNetwork::Ptr& network, const NetworkManager::WirelessDevice::Ptr& device) +void NetworkModel::updateFromWirelessNetwork(NetworkModelItem *item, const NetworkManager::WirelessNetwork::Ptr &network, const NetworkManager::WirelessDevice::Ptr &device) { NetworkManager::WirelessSecurityType securityType = NetworkManager::UnknownSecurity; NetworkManager::AccessPoint::Ptr ap = network->referenceAccessPoint(); if (ap && ap->capabilities().testFlag(NetworkManager::AccessPoint::Privacy)) { securityType = NetworkManager::findBestWirelessSecurity(device->wirelessCapabilities(), true, (device->mode() == NetworkManager::WirelessDevice::Adhoc), ap->capabilities(), ap->wpaFlags(), ap->rsnFlags()); } // Check whether the connection is associated with some concrete AP NetworkManager::Connection::Ptr connection = NetworkManager::findConnection(item->connectionPath()); if (connection) { NetworkManager::WirelessSetting::Ptr wirelessSetting = connection->settings()->setting(NetworkManager::Setting::Wireless).staticCast(); if (wirelessSetting) { if (!wirelessSetting->bssid().isEmpty()) { - Q_FOREACH (const NetworkManager::AccessPoint::Ptr ap, network->accessPoints()) { + for (const NetworkManager::AccessPoint::Ptr ap : network->accessPoints()) { if (ap->hardwareAddress() == NetworkManager::macAddressAsString(wirelessSetting->bssid())) { item->setSignal(ap->signalStrength()); item->setSpecificPath(ap->uni()); // We need to watch this AP for signal changes connect(ap.data(), &NetworkManager::AccessPoint::signalStrengthChanged, this, &NetworkModel::accessPointSignalStrengthChanged, Qt::UniqueConnection); } } } else { item->setSignal(network->signalStrength()); item->setSpecificPath(network->referenceAccessPoint()->uni()); } } } item->setSecurityType(securityType); updateItem(item); } diff --git a/libs/models/networkmodel.h b/libs/models/networkmodel.h index ca3269b5..b8598547 100644 --- a/libs/models/networkmodel.h +++ b/libs/models/networkmodel.h @@ -1,128 +1,131 @@ /* - Copyright 2013-2014 Jan Grulich + Copyright 2013-2018 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_NETWORK_MODEL_H #define PLASMA_NM_NETWORK_MODEL_H #include #include "networkitemslist.h" #include #include #include #include #if WITH_MODEMMANAGER_SUPPORT #include #endif class Q_DECL_EXPORT NetworkModel : public QAbstractListModel { Q_OBJECT public: - explicit NetworkModel(QObject* parent = 0); - virtual ~NetworkModel(); + explicit NetworkModel(QObject *parent = nullptr); + ~NetworkModel() override; enum ItemRole { ConnectionDetailsRole = Qt::UserRole + 1, ConnectionIconRole, ConnectionPathRole, ConnectionStateRole, DeviceName, DevicePathRole, DeviceStateRole, DuplicateRole, ItemUniqueNameRole, ItemTypeRole, LastUsedRole, LastUsedDateOnlyRole, NameRole, SecurityTypeRole, SecurityTypeStringRole, SectionRole, SignalRole, SlaveRole, SsidRole, SpecificPathRole, TimeStampRole, TypeRole, UniRole, UuidRole, VpnState, - VpnType + VpnType, + RxBytesRole, + TxBytesRole }; - int rowCount(const QModelIndex& parent) const Q_DECL_OVERRIDE; - QVariant data(const QModelIndex& index, int role) const Q_DECL_OVERRIDE; - virtual QHash< int, QByteArray > roleNames() const Q_DECL_OVERRIDE; + int rowCount(const QModelIndex &parent) const override; + QVariant data(const QModelIndex &index, int role) const override; + QHash roleNames() const override; public Q_SLOTS: void onItemUpdated(); + void setDeviceStatisticsRefreshRateMs(const QString &devicePath, uint refreshRate); private Q_SLOTS: void accessPointSignalStrengthChanged(int signal); - void activeConnectionAdded(const QString& activeConnection); - void activeConnectionRemoved(const QString& activeConnection); + void activeConnectionAdded(const QString &activeConnection); + void activeConnectionRemoved(const QString &activeConnection); void activeConnectionStateChanged(NetworkManager::ActiveConnection::State state); void activeVpnConnectionStateChanged(NetworkManager::VpnConnection::State state,NetworkManager::VpnConnection::StateChangeReason reason); - void availableConnectionAppeared(const QString& connection); - void availableConnectionDisappeared(const QString& connection); - void connectionAdded(const QString& connection); - void connectionRemoved(const QString& connection); + void availableConnectionAppeared(const QString &connection); + void availableConnectionDisappeared(const QString &connection); + void connectionAdded(const QString &connection); + void connectionRemoved(const QString &connection); void connectionUpdated(); - void deviceAdded(const QString& device); - void deviceRemoved(const QString& device); + void deviceAdded(const QString &device); + void deviceRemoved(const QString &device); void deviceStateChanged(NetworkManager::Device::State state, NetworkManager::Device::State oldState, NetworkManager::Device::StateChangeReason reason); #if WITH_MODEMMANAGER_SUPPORT void gsmNetworkAccessTechnologiesChanged(QFlags accessTechnologies); void gsmNetworkCurrentModesChanged(); void gsmNetworkSignalQualityChanged(const ModemManager::SignalQualityPair &signalQuality); #endif void ipConfigChanged(); void ipInterfaceChanged(); void statusChanged(NetworkManager::Status status); - void wirelessNetworkAppeared(const QString& ssid); - void wirelessNetworkDisappeared(const QString& ssid); + void wirelessNetworkAppeared(const QString &ssid); + void wirelessNetworkDisappeared(const QString &ssid); void wirelessNetworkSignalChanged(int signal); - void wirelessNetworkReferenceApChanged(const QString& accessPoint); + void wirelessNetworkReferenceApChanged(const QString &accessPoint); void initialize(); private: NetworkItemsList m_list; - void addActiveConnection(const NetworkManager::ActiveConnection::Ptr& activeConnection); - void addAvailableConnection(const QString& connection, const NetworkManager::Device::Ptr& device); - void addConnection(const NetworkManager::Connection::Ptr& connection); - void addDevice(const NetworkManager::Device::Ptr& device); - void addWirelessNetwork(const NetworkManager::WirelessNetwork::Ptr& network, const NetworkManager::WirelessDevice::Ptr& device); - void checkAndCreateDuplicate(const QString& connection, const NetworkManager::Device::Ptr& device); + void addActiveConnection(const NetworkManager::ActiveConnection::Ptr &activeConnection); + void addAvailableConnection(const QString &connection, const NetworkManager::Device::Ptr &device); + void addConnection(const NetworkManager::Connection::Ptr &connection); + void addDevice(const NetworkManager::Device::Ptr &device); + void addWirelessNetwork(const NetworkManager::WirelessNetwork::Ptr &network, const NetworkManager::WirelessDevice::Ptr &device); + void checkAndCreateDuplicate(const QString &connection, const QString &deviceUni); void initializeSignals(); - void initializeSignals(const NetworkManager::ActiveConnection::Ptr& activeConnection); - void initializeSignals(const NetworkManager::Connection::Ptr& connection); - void initializeSignals(const NetworkManager::Device::Ptr& device); - void initializeSignals(const NetworkManager::WirelessNetwork::Ptr& network); - void updateItem(NetworkModelItem * item); - void updateFromWirelessNetwork(NetworkModelItem * item, const NetworkManager::WirelessNetwork::Ptr& network, const NetworkManager::WirelessDevice::Ptr& device); + void initializeSignals(const NetworkManager::ActiveConnection::Ptr &activeConnection); + void initializeSignals(const NetworkManager::Connection::Ptr &connection); + void initializeSignals(const NetworkManager::Device::Ptr &device); + void initializeSignals(const NetworkManager::WirelessNetwork::Ptr &network); + void updateItem(NetworkModelItem *item); + void updateFromWirelessNetwork(NetworkModelItem *item, const NetworkManager::WirelessNetwork::Ptr &network, const NetworkManager::WirelessDevice::Ptr &device); NetworkManager::WirelessSecurityType alternativeWirelessSecurity(const NetworkManager::WirelessSecurityType type); }; #endif // PLASMA_NM_NETWORK_MODEL_H diff --git a/libs/models/networkmodelitem.cpp b/libs/models/networkmodelitem.cpp index 0ccfe5f2..17c84108 100644 --- a/libs/models/networkmodelitem.cpp +++ b/libs/models/networkmodelitem.cpp @@ -1,562 +1,597 @@ /* - Copyright 2013-2014 Jan Grulich + Copyright 2013-2018 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "networkmodelitem.h" #include "uiutils.h" #include #include #include #include #include #include #include #include #if NM_CHECK_VERSION (0, 9, 10) #include #endif #include #include #include #include #include #include #include #include #if WITH_MODEMMANAGER_SUPPORT #include #include #include #include #include #endif -NetworkModelItem::NetworkModelItem(QObject* parent) +NetworkModelItem::NetworkModelItem(QObject *parent) : QObject(parent) , m_connectionState(NetworkManager::ActiveConnection::Deactivated) , m_deviceState(NetworkManager::Device::UnknownState) + , m_detailsValid(false) , m_duplicate(false) , m_mode(NetworkManager::WirelessSetting::Infrastructure) , m_securityType(NetworkManager::NoneSecurity) , m_signal(0) , m_slave(false) , m_type(NetworkManager::ConnectionSettings::Unknown) , m_vpnState(NetworkManager::VpnConnection::Unknown) + , m_rxBytes(0) + , m_txBytes(0) { } -NetworkModelItem::NetworkModelItem(const NetworkModelItem* item, QObject* parent) +NetworkModelItem::NetworkModelItem(const NetworkModelItem *item, QObject *parent) : QObject(parent) , m_connectionPath(item->connectionPath()) , m_connectionState(NetworkManager::ActiveConnection::Deactivated) + , m_detailsValid(false) , m_duplicate(true) , m_mode(item->mode()) , m_name(item->name()) , m_securityType(item->securityType()) , m_slave(item->slave()) , m_ssid(item->ssid()) , m_timestamp(item->timestamp()) , m_type(item->type()) , m_uuid(item->uuid()) , m_vpnState(NetworkManager::VpnConnection::Unknown) + , m_rxBytes(0) + , m_txBytes(0) { } NetworkModelItem::~NetworkModelItem() { } QString NetworkModelItem::activeConnectionPath() const { return m_activeConnectionPath; } -void NetworkModelItem::setActiveConnectionPath(const QString& path) +void NetworkModelItem::setActiveConnectionPath(const QString &path) { m_activeConnectionPath = path; } QString NetworkModelItem::connectionPath() const { return m_connectionPath; } -void NetworkModelItem::setConnectionPath(const QString& path) +void NetworkModelItem::setConnectionPath(const QString &path) { m_connectionPath = path; } NetworkManager::ActiveConnection::State NetworkModelItem::connectionState() const { return m_connectionState; } void NetworkModelItem::setConnectionState(NetworkManager::ActiveConnection::State state) { m_connectionState = state; } QStringList NetworkModelItem::details() const { + if (!m_detailsValid) { + updateDetails(); + } return m_details; } QString NetworkModelItem::devicePath() const { return m_devicePath; } QString NetworkModelItem::deviceName() const { return m_deviceName; } -void NetworkModelItem::setDeviceName(const QString& name) +void NetworkModelItem::setDeviceName(const QString &name) { m_deviceName = name; } -void NetworkModelItem::setDevicePath(const QString& path) +void NetworkModelItem::setDevicePath(const QString &path) { m_devicePath = path; } QString NetworkModelItem::deviceState() const { return UiUtils::connectionStateToString(m_deviceState); } void NetworkModelItem::setDeviceState(const NetworkManager::Device::State state) { m_deviceState = state; } bool NetworkModelItem::duplicate() const { return m_duplicate; } QString NetworkModelItem::icon() const { switch (m_type) { case NetworkManager::ConnectionSettings::Adsl: return QStringLiteral("network-mobile-100"); break; case NetworkManager::ConnectionSettings::Bluetooth: if (connectionState() == NetworkManager::ActiveConnection::Activated) { return QStringLiteral("network-bluetooth-activated"); } else { return QStringLiteral("network-bluetooth"); } break; case NetworkManager::ConnectionSettings::Bond: break; case NetworkManager::ConnectionSettings::Bridge: break; case NetworkManager::ConnectionSettings::Cdma: case NetworkManager::ConnectionSettings::Gsm: if (m_signal == 0 ) { return QStringLiteral("network-mobile-0"); } else if (m_signal < 20) { return QStringLiteral("network-mobile-20"); } else if (m_signal < 40) { return QStringLiteral("network-mobile-40"); } else if (m_signal < 60) { return QStringLiteral("network-mobile-60"); } else if (m_signal < 80) { return QStringLiteral("network-mobile-80"); } else { return QStringLiteral("network-mobile-100"); } break; case NetworkManager::ConnectionSettings::Infiniband: break; case NetworkManager::ConnectionSettings::OLPCMesh: break; case NetworkManager::ConnectionSettings::Pppoe: return QStringLiteral("network-mobile-100"); break; case NetworkManager::ConnectionSettings::Vlan: break; case NetworkManager::ConnectionSettings::Vpn: return QStringLiteral("network-vpn"); break; case NetworkManager::ConnectionSettings::Wired: if (connectionState() == NetworkManager::ActiveConnection::Activated) { return QStringLiteral("network-wired-activated"); } else { return QStringLiteral("network-wired"); } break; case NetworkManager::ConnectionSettings::Wireless: if (m_signal == 0 ) { if (m_mode == NetworkManager::WirelessSetting::Adhoc || m_mode == NetworkManager::WirelessSetting::Ap) { return (m_securityType <= NetworkManager::NoneSecurity) ? QStringLiteral("network-wireless-100") : QStringLiteral("network-wireless-100-locked"); } return (m_securityType <= NetworkManager::NoneSecurity) ? QStringLiteral("network-wireless-0") : QStringLiteral("network-wireless-0-locked"); } else if (m_signal < 20) { return (m_securityType <= NetworkManager::NoneSecurity) ? QStringLiteral("network-wireless-20") : QStringLiteral("network-wireless-20-locked"); } else if (m_signal < 40) { return (m_securityType <= NetworkManager::NoneSecurity) ? QStringLiteral("network-wireless-40") : QStringLiteral("network-wireless-40-locked"); } else if (m_signal < 60) { return (m_securityType <= NetworkManager::NoneSecurity) ? QStringLiteral("network-wireless-60") : QStringLiteral("network-wireless-60-locked"); } else if (m_signal < 80) { return (m_securityType <= NetworkManager::NoneSecurity) ? QStringLiteral("network-wireless-80") : QStringLiteral("network-wireless-80-locked"); } else { return (m_securityType <= NetworkManager::NoneSecurity) ? QStringLiteral("network-wireless-100") : QStringLiteral("network-wireless-100-locked"); } break; default: break; } if (connectionState() == NetworkManager::ActiveConnection::Activated) { return QStringLiteral("network-wired-activated"); } else { return QStringLiteral("network-wired"); } } NetworkModelItem::ItemType NetworkModelItem::itemType() const { if (!m_devicePath.isEmpty() || m_type == NetworkManager::ConnectionSettings::Bond || m_type == NetworkManager::ConnectionSettings::Bridge || m_type == NetworkManager::ConnectionSettings::Vlan || #if NM_CHECK_VERSION(0, 9, 10) m_type == NetworkManager::ConnectionSettings::Team || #endif ((NetworkManager::status() == NetworkManager::Connected || NetworkManager::status() == NetworkManager::ConnectedLinkLocal || NetworkManager::status() == NetworkManager::ConnectedSiteOnly) && m_type == NetworkManager::ConnectionSettings::Vpn)) { if (m_connectionPath.isEmpty() && m_type == NetworkManager::ConnectionSettings::Wireless) { return NetworkModelItem::AvailableAccessPoint; } else { return NetworkModelItem::AvailableConnection; } } return NetworkModelItem::UnavailableConnection; } NetworkManager::WirelessSetting::NetworkMode NetworkModelItem::mode() const { return m_mode; } void NetworkModelItem::setMode(const NetworkManager::WirelessSetting::NetworkMode mode) { m_mode = mode; } QString NetworkModelItem::name() const { return m_name; } -void NetworkModelItem::setName(const QString& name) +void NetworkModelItem::setName(const QString &name) { m_name = name; } QString NetworkModelItem::originalName() const { if (m_deviceName.isEmpty()) { return m_name; } return m_name % QLatin1String(" (") % m_deviceName % ')'; } QString NetworkModelItem::sectionType() const { if (m_connectionState == NetworkManager::ActiveConnection::Activated) { return i18n("Active connections"); } else { return i18n("Available connections"); } } NetworkManager::WirelessSecurityType NetworkModelItem::securityType() const { return m_securityType; } void NetworkModelItem::setSecurityType(NetworkManager::WirelessSecurityType type) { m_securityType = type; } int NetworkModelItem::signal() const { return m_signal; } void NetworkModelItem::setSignal(int signal) { m_signal = signal; } bool NetworkModelItem::slave() const { return m_slave; } void NetworkModelItem::setSlave(bool slave) { m_slave = slave; } QString NetworkModelItem::specificPath() const { return m_specificPath; } -void NetworkModelItem::setSpecificPath(const QString& path) +void NetworkModelItem::setSpecificPath(const QString &path) { m_specificPath = path; } QString NetworkModelItem::ssid() const { return m_ssid; } -void NetworkModelItem::setSsid(const QString& ssid) +void NetworkModelItem::setSsid(const QString &ssid) { m_ssid = ssid; } NetworkManager::ConnectionSettings::ConnectionType NetworkModelItem::type() const { return m_type; } QDateTime NetworkModelItem::timestamp() const { return m_timestamp; } -void NetworkModelItem::setTimestamp(const QDateTime& date) +void NetworkModelItem::setTimestamp(const QDateTime &date) { m_timestamp = date; } void NetworkModelItem::setType(NetworkManager::ConnectionSettings::ConnectionType type) { m_type = type; } QString NetworkModelItem::uni() const { if (m_type == NetworkManager::ConnectionSettings::Wireless && m_uuid.isEmpty()) { return m_ssid + '%' + m_devicePath; } else { return m_connectionPath + '%' + m_devicePath; } } QString NetworkModelItem::uuid() const { return m_uuid; } -void NetworkModelItem::setUuid(const QString& uuid) +void NetworkModelItem::setUuid(const QString &uuid) { m_uuid = uuid; } QString NetworkModelItem::vpnState() const { return UiUtils::vpnConnectionStateToString(m_vpnState); } void NetworkModelItem::setVpnState(NetworkManager::VpnConnection::State state) { m_vpnState = state; } QString NetworkModelItem::vpnType() const { return m_vpnType; } void NetworkModelItem::setVpnType(const QString &type) { m_vpnType = type; } -bool NetworkModelItem::operator==(const NetworkModelItem* item) const +qulonglong NetworkModelItem::rxBytes() const +{ + return m_rxBytes; +} + +void NetworkModelItem::setRxBytes(qulonglong bytes) +{ + m_rxBytes = bytes; +} + +qulonglong NetworkModelItem::txBytes() const +{ + return m_txBytes; +} + +void NetworkModelItem::setTxBytes(qulonglong bytes) +{ + m_txBytes = bytes; +} + +bool NetworkModelItem::operator==(const NetworkModelItem *item) const { if (!item->uuid().isEmpty() && !uuid().isEmpty()) { if (item->devicePath() == devicePath() && item->uuid() == uuid()) { return true; } } else if (item->type() == NetworkManager::ConnectionSettings::Wireless && type() == NetworkManager::ConnectionSettings::Wireless) { if (item->ssid() == ssid() && item->devicePath() == devicePath()) { return true; } } return false; } -void NetworkModelItem::updateDetails() +void NetworkModelItem::invalidateDetails() +{ + m_detailsValid = false; +} + +void NetworkModelItem::updateDetails() const { + m_detailsValid = true; m_details.clear(); if (itemType() == NetworkModelItem::UnavailableConnection) { return; } NetworkManager::Device::Ptr device = NetworkManager::findNetworkInterface(m_devicePath); // Get IPv[46]Address if (device && device->ipV4Config().isValid() && m_connectionState == NetworkManager::ActiveConnection::Activated) { if (!device->ipV4Config().addresses().isEmpty()) { QHostAddress addr = device->ipV4Config().addresses().first().ip(); if (!addr.isNull()) { m_details << i18n("IPv4 Address") << addr.toString(); } } } if (device && device->ipV6Config().isValid() && m_connectionState == NetworkManager::ActiveConnection::Activated) { if (!device->ipV6Config().addresses().isEmpty()) { QHostAddress addr = device->ipV6Config().addresses().first().ip(); if (!addr.isNull()) { m_details << i18n("IPv6 Address") << addr.toString(); } } } if (m_type == NetworkManager::ConnectionSettings::Wired) { NetworkManager::WiredDevice::Ptr wiredDevice = device.objectCast(); if (wiredDevice) { if (m_connectionState == NetworkManager::ActiveConnection::Activated) { m_details << i18n("Connection speed") << UiUtils::connectionSpeed(wiredDevice->bitRate()); } m_details << i18n("MAC Address") << wiredDevice->permanentHardwareAddress(); } } else if (m_type == NetworkManager::ConnectionSettings::Wireless) { NetworkManager::WirelessDevice::Ptr wirelessDevice = device.objectCast(); m_details << i18n("Access point (SSID)") << m_ssid; if (m_mode == NetworkManager::WirelessSetting::Infrastructure) { m_details << i18n("Signal strength") << QString("%1%").arg(m_signal); } if (m_connectionState == NetworkManager::ActiveConnection::Activated) { m_details << i18n("Security type") << UiUtils::labelFromWirelessSecurity(m_securityType); } if (wirelessDevice) { if (m_connectionState == NetworkManager::ActiveConnection::Activated) { m_details << i18n("Connection speed") << UiUtils::connectionSpeed(wirelessDevice->bitRate()); } m_details << i18n("MAC Address") << wirelessDevice->permanentHardwareAddress(); } } else if (m_type == NetworkManager::ConnectionSettings::Gsm || m_type == NetworkManager::ConnectionSettings::Cdma) { #if WITH_MODEMMANAGER_SUPPORT NetworkManager::ModemDevice::Ptr modemDevice = device.objectCast(); if (modemDevice) { ModemManager::ModemDevice::Ptr modem = ModemManager::findModemDevice(modemDevice->udi()); if (modem) { ModemManager::Modem::Ptr modemNetwork = modem->interface(ModemManager::ModemDevice::ModemInterface).objectCast(); if (m_type == NetworkManager::ConnectionSettings::Gsm) { ModemManager::Modem3gpp::Ptr gsmNet = modem->interface(ModemManager::ModemDevice::GsmInterface).objectCast(); if (gsmNet) { m_details << i18n("Operator") << gsmNet->operatorName(); } } else { ModemManager::ModemCdma::Ptr cdmaNet = modem->interface(ModemManager::ModemDevice::CdmaInterface).objectCast(); m_details << i18n("Network ID") << QString("%1").arg(cdmaNet->nid()); } if (modemNetwork) { m_details << i18n("Signal Quality") << QString("%1%").arg(modemNetwork->signalQuality().signal); m_details << i18n("Access Technology") << UiUtils::convertAccessTechnologyToString(modemNetwork->accessTechnologies()); } } } #endif } else if (m_type == NetworkManager::ConnectionSettings::Vpn) { m_details << i18n("VPN plugin") << m_vpnType; if (m_connectionState == NetworkManager::ActiveConnection::Activated) { NetworkManager::ActiveConnection::Ptr active = NetworkManager::findActiveConnection(m_activeConnectionPath); NetworkManager::VpnConnection::Ptr vpnConnection; if (active) { vpnConnection = NetworkManager::VpnConnection::Ptr(new NetworkManager::VpnConnection(active->path()), &QObject::deleteLater); } if (vpnConnection && !vpnConnection->banner().isEmpty()) { m_details << i18n("Banner") << vpnConnection->banner().simplified(); } } } else if (m_type == NetworkManager::ConnectionSettings::Bluetooth) { NetworkManager::BluetoothDevice::Ptr bluetoothDevice = device.objectCast(); if (bluetoothDevice) { m_details << i18n("Name") << bluetoothDevice->name(); if (bluetoothDevice->bluetoothCapabilities() == NetworkManager::BluetoothDevice::Pan) { m_details << i18n("Capabilities") << QStringLiteral("PAN"); } else if (bluetoothDevice->bluetoothCapabilities() == NetworkManager::BluetoothDevice::Dun) { m_details << i18n("Capabilities") << QStringLiteral("DUN"); } m_details << i18n("MAC Address") << bluetoothDevice->hardwareAddress(); } } else if (m_type == NetworkManager::ConnectionSettings::Infiniband) { NetworkManager::InfinibandDevice::Ptr infinibandDevice = device.objectCast(); m_details << i18n("Type") << i18n("Infiniband"); if (infinibandDevice) { m_details << i18n("MAC Address") << infinibandDevice->hwAddress(); } } else if (m_type == NetworkManager::ConnectionSettings::Bond) { NetworkManager::BondDevice::Ptr bondDevice = device.objectCast(); m_details << i18n("Type") << i18n("Bond"); if (bondDevice) { m_details << i18n("MAC Address") << bondDevice->hwAddress(); } } else if (m_type == NetworkManager::ConnectionSettings::Bridge) { NetworkManager::BridgeDevice::Ptr bridgeDevice = device.objectCast(); m_details << i18n("Type") << i18n("Bridge"); if (bridgeDevice) { m_details << i18n("MAC Address") << bridgeDevice->hwAddress(); } } else if (m_type == NetworkManager::ConnectionSettings::Vlan) { NetworkManager::VlanDevice::Ptr vlanDevice = device.objectCast(); m_details << i18n("Type") << i18n("Vlan"); if (vlanDevice) { m_details << i18n("Vlan ID") << QString("%1").arg(vlanDevice->vlanId()); m_details << i18n("MAC Address") << vlanDevice->hwAddress(); } } else if (m_type == NetworkManager::ConnectionSettings::Adsl) { m_details << i18n("Type") << i18n("Adsl"); } #if NM_CHECK_VERSION (0, 9, 10) else if (m_type == NetworkManager::ConnectionSettings::Team) { NetworkManager::TeamDevice::Ptr teamDevice = device.objectCast(); m_details << i18n("Type") << i18n("Team"); if (teamDevice) { m_details << i18n("MAC Address") << teamDevice->hwAddress(); } } #endif } diff --git a/libs/models/networkmodelitem.h b/libs/models/networkmodelitem.h index 44714085..0f4f4209 100644 --- a/libs/models/networkmodelitem.h +++ b/libs/models/networkmodelitem.h @@ -1,139 +1,150 @@ /* - Copyright 2013-2014 Jan Grulich + Copyright 2013-2018 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_MODEL_NETWORK_MODEL_ITEM_H #define PLASMA_NM_MODEL_NETWORK_MODEL_ITEM_H #include #include #include #include #include #include "networkmodel.h" class Q_DECL_EXPORT NetworkModelItem : public QObject { Q_OBJECT public: enum ItemType { UnavailableConnection, AvailableConnection, AvailableAccessPoint }; - explicit NetworkModelItem(QObject * parent = 0); - explicit NetworkModelItem(const NetworkModelItem * item, QObject* parent = 0); - virtual ~NetworkModelItem(); + explicit NetworkModelItem(QObject *parent = nullptr); + explicit NetworkModelItem(const NetworkModelItem *item, QObject *parent = nullptr); + ~NetworkModelItem() override; QString activeConnectionPath() const; - void setActiveConnectionPath(const QString& path); + void setActiveConnectionPath(const QString &path); QString connectionPath() const; - void setConnectionPath(const QString& path); + void setConnectionPath(const QString &path); NetworkManager::ActiveConnection::State connectionState() const; void setConnectionState(NetworkManager::ActiveConnection::State state); QStringList details() const; QString deviceName() const; - void setDeviceName(const QString& name); + void setDeviceName(const QString &name); QString devicePath() const; - void setDevicePath(const QString& path); + void setDevicePath(const QString &path); QString deviceState() const; void setDeviceState(const NetworkManager::Device::State state); bool duplicate() const; QString icon() const; ItemType itemType() const; NetworkManager::WirelessSetting::NetworkMode mode() const; void setMode(const NetworkManager::WirelessSetting::NetworkMode mode); QString name() const; - void setName(const QString& name); + void setName(const QString &name); QString originalName() const; QString sectionType() const; NetworkManager::WirelessSecurityType securityType() const; void setSecurityType(NetworkManager::WirelessSecurityType type); int signal() const; void setSignal(int signal); bool slave() const; void setSlave(bool slave); QString specificPath() const; - void setSpecificPath(const QString& path); + void setSpecificPath(const QString &path); QString ssid() const; - void setSsid(const QString& ssid); + void setSsid(const QString &ssid); QDateTime timestamp() const; - void setTimestamp(const QDateTime& date); + void setTimestamp(const QDateTime &date); NetworkManager::ConnectionSettings::ConnectionType type() const; void setType(NetworkManager::ConnectionSettings::ConnectionType type); QString uni() const; QString uuid() const; - void setUuid(const QString& uuid); + void setUuid(const QString &uuid); QString vpnState() const; void setVpnState(NetworkManager::VpnConnection::State state); QString vpnType() const; void setVpnType(const QString &type); - bool operator==(const NetworkModelItem * item) const; + qulonglong rxBytes() const; + void setRxBytes(qulonglong bytes); + + qulonglong txBytes() const; + void setTxBytes(qulonglong bytes); + + bool operator==(const NetworkModelItem *item) const; public Q_SLOTS: - void updateDetails(); + void invalidateDetails(); private: + void updateDetails() const; + QString m_activeConnectionPath; QString m_connectionPath; NetworkManager::ActiveConnection::State m_connectionState; QString m_devicePath; QString m_deviceName; NetworkManager::Device::State m_deviceState; - QStringList m_details; + mutable QStringList m_details; + mutable bool m_detailsValid; bool m_duplicate; NetworkManager::WirelessSetting::NetworkMode m_mode; QString m_name; NetworkManager::WirelessSecurityType m_securityType; int m_signal; bool m_slave; QString m_specificPath; QString m_ssid; QDateTime m_timestamp; NetworkManager::ConnectionSettings::ConnectionType m_type; QString m_uuid; QString m_vpnType; NetworkManager::VpnConnection::State m_vpnState; + qulonglong m_rxBytes; + qulonglong m_txBytes; }; #endif // PLASMA_NM_MODEL_NETWORK_MODEL_ITEM_H diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt new file mode 100644 index 00000000..f68327ec --- /dev/null +++ b/tests/CMakeLists.txt @@ -0,0 +1,23 @@ +include_directories( ${CMAKE_SOURCE_DIR}/libs/editor ) + +########### next target ############### + +include(ECMAddTests) + +find_package(Qt5 ${REQUIRED_QT_VERSION} NO_MODULE REQUIRED Test) +set_package_properties(Qt5Test PROPERTIES PURPOSE "Required for autotests") + +ecm_add_test( + simpleipv6test.cpp + LINK_LIBRARIES Qt5::Test plasmanm_editor +) + +ecm_add_test( + simpleipv4test.cpp + LINK_LIBRARIES Qt5::Test plasmanm_editor +) + +ecm_add_test( + simpleiplisttest.cpp + LINK_LIBRARIES Qt5::Test plasmanm_editor +) diff --git a/tests/simpleiplisttest.cpp b/tests/simpleiplisttest.cpp new file mode 100644 index 00000000..b3cabde3 --- /dev/null +++ b/tests/simpleiplisttest.cpp @@ -0,0 +1,136 @@ +/* +Copyright 2018 Bruce Anderson + +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) version 3 or any later version +accepted by the membership of KDE e.V. (or its successor approved +by the membership of KDE e.V.), which shall act as a proxy +defined in Section 14 of version 3 of the license. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +#include "simpleiplistvalidator.h" +#include + +class SimpleipListTest : public QObject +{ + Q_OBJECT + +public: + SimpleipListTest(); + +private slots: + void baseTest(); + void baseTest_data(); + void cidrTest(); + void cidrTest_data(); + void portTest(); + void portTest_data(); + +private: + SimpleIpListValidator m_vb; + SimpleIpListValidator m_vc; + SimpleIpListValidator m_vp; +}; + +SimpleipListTest::SimpleipListTest() + : m_vb(nullptr, SimpleIpListValidator::AddressStyle::Base) + , m_vc(nullptr, SimpleIpListValidator::AddressStyle::WithCidr) + , m_vp(nullptr, SimpleIpListValidator::AddressStyle::WithPort) +{ +} + +Q_DECLARE_METATYPE(QValidator::State) + +void SimpleipListTest::baseTest_data() +{ + QTest::addColumn("address"); + QTest::addColumn("result"); + + QTest::newRow("") << "" << QValidator::Intermediate; + QTest::newRow("123.12.2") << "123.12.2" << QValidator::Intermediate; + QTest::newRow("123.12.2,") << "123.12.2," << QValidator::Invalid; + QTest::newRow("123.45.22.9") << "123.45.22.9" << QValidator::Acceptable; + QTest::newRow("123.45.22.9,") << "123.45.22.9," << QValidator::Intermediate; + QTest::newRow("123.45.22.9, ") << "123.45.22.9, " << QValidator::Intermediate; + QTest::newRow("123.45.22,") << "123.45.22," << QValidator::Invalid; + QTest::newRow("123.45.22.9, BBEf:0112") << "123.45.22.9, BBEf:0112" << QValidator::Intermediate; + QTest::newRow("123.45.22.9, BBEf:0112::1") << "123.45.22.9, BBEf:0112::1" << QValidator::Acceptable; + QTest::newRow("123.45.22.9, BBEf:0112:,") << "123.45.22.9, BBEf:0112:," << QValidator::Invalid; + QTest::newRow("123.45.22.9, BBEf:0112::1,") << "123.45.22.9, BBEf:0112::1," << QValidator::Intermediate; + QTest::newRow("123.45.22.9, BBEf:0112::1/123,") << "123.45.22.9, BBEf:0112::1/123," << QValidator::Invalid; + QTest::newRow("123.45.22.9, BBEf:0112::1,1.2.3.4") << "123.45.22.9, BBEf:0112::1,1.2.3.4" << QValidator::Acceptable; +} + +void SimpleipListTest::baseTest() +{ + int pos; + + QFETCH(QString, address); + QFETCH(QValidator::State, result); + + QCOMPARE(m_vb.validate(address, pos), result); +} + +void SimpleipListTest::cidrTest_data() +{ + QTest::addColumn("address"); + QTest::addColumn("result"); + + QTest::newRow("10.77.18.4/32") << "10.77.18.4/32" << QValidator::Acceptable; + QTest::newRow("10.77.18.4/32,") << "10.77.18.4/32," << QValidator::Intermediate; + QTest::newRow("10.77.18.4/32,Be00:e00:0:") << "10.77.18.4/32,Be00:e00:0:" << QValidator::Intermediate; + QTest::newRow("10.77.18.4/32,Be00:e00:0:21/3") << "10.77.18.4/32,Be00:e00:0:21/3" << QValidator::Invalid; + QTest::newRow("10.77.18.4/32,Be00:e00::0:21/128") << "10.77.18.4/32,Be00:e00::0:21/128" << QValidator::Acceptable; + QTest::newRow("10.77.18.4/32,Be00:e00::0:21/129") << "10.77.18.4/32,Be00:e00::0:21/129" << QValidator::Invalid; +} + +void SimpleipListTest::cidrTest() +{ + int pos; + + QFETCH(QString, address); + QFETCH(QValidator::State, result); + + QCOMPARE(m_vc.validate(address, pos), result); +} + +void SimpleipListTest::portTest_data() +{ + QTest::addColumn("address"); + QTest::addColumn("result"); + + QTest::newRow("10.77.18.4:32") << "10.77.18.4:32" << QValidator::Acceptable; + QTest::newRow("10.77.18.4:,") << "10.77.18.4:," << QValidator::Invalid; + QTest::newRow("10.77.18.4:234, 1") << "10.77.18.4:234, 1" << QValidator::Intermediate; + QTest::newRow("10.77.18.4:234, 1b") << "10.77.18.4:234, 1b" << QValidator::Invalid; + QTest::newRow("10.77.18.4:234, [1b") << "10.77.18.4:234, [1b" << QValidator::Intermediate; + QTest::newRow("10.77.18.4:234, [10:33:22::1") << "10.77.18.4:234, [10:33:22::1" << QValidator::Intermediate; + QTest::newRow("10.77.18.4:234, [10:33:22::1]") << "10.77.18.4:234, [10:33:22::1]" << QValidator::Intermediate; + QTest::newRow("10.77.18.4:234, [10:33:22::1]:") << "10.77.18.4:234, [10:33:22::1]:" << QValidator::Intermediate; + QTest::newRow("10.77.18.4:234, [10:33:22::1]:22") << "10.77.18.4:234, [10:33:22::1]:22" << QValidator::Acceptable; + QTest::newRow("10.77.18.4:234, [10:33:22::1]:22,12.23.34.45:65535") << "10.77.18.4:234, [10:33:22::1]:22,12.23.34.45:65535" << QValidator::Acceptable; +} + +void SimpleipListTest::portTest() +{ + int pos; + + QFETCH(QString, address); + QFETCH(QValidator::State, result); + + QCOMPARE(m_vp.validate(address, pos), result); +} + +QTEST_GUILESS_MAIN(SimpleipListTest) + +#include "simpleiplisttest.moc" diff --git a/tests/simpleipv4test.cpp b/tests/simpleipv4test.cpp new file mode 100644 index 00000000..b3db71dd --- /dev/null +++ b/tests/simpleipv4test.cpp @@ -0,0 +1,152 @@ +/* +Copyright 2018 Bruce Anderson + +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) version 3 or any later version +accepted by the membership of KDE e.V. (or its successor approved +by the membership of KDE e.V.), which shall act as a proxy +defined in Section 14 of version 3 of the license. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +#include "simpleipv4addressvalidator.h" +#include + +class SimpleIpv4Test : public QObject +{ + Q_OBJECT + +public: + SimpleIpv4Test(); + +private slots: + void baseTest(); + void baseTest_data(); + void cidrTest(); + void cidrTest_data(); + void portTest(); + void portTest_data(); + +private: + SimpleIpV4AddressValidator m_vb; + SimpleIpV4AddressValidator m_vc; + SimpleIpV4AddressValidator m_vp; +}; + + +SimpleIpv4Test::SimpleIpv4Test() + : m_vb(nullptr, SimpleIpV4AddressValidator::AddressStyle::Base) + , m_vc(nullptr, SimpleIpV4AddressValidator::AddressStyle::WithCidr) + , m_vp(nullptr, SimpleIpV4AddressValidator::AddressStyle::WithPort) +{ +} + +Q_DECLARE_METATYPE(QValidator::State) + +void SimpleIpv4Test::baseTest_data() +{ + QTest::addColumn("address"); + QTest::addColumn("result"); + + QTest::newRow("empty string") << "" << QValidator::Intermediate; + QTest::newRow("123.12.2") << "123.12.2" << QValidator::Intermediate; + QTest::newRow("123.45.22.9") << "123.45.22.9" << QValidator::Acceptable; + QTest::newRow("1") << "1" << QValidator::Intermediate; + QTest::newRow("12") << "12" << QValidator::Intermediate; + QTest::newRow("123") << "123" << QValidator::Intermediate; + QTest::newRow("123.") << "123." << QValidator::Intermediate; + QTest::newRow("123.4") << "123.4" << QValidator::Intermediate; + QTest::newRow("123.54") << "123.54" << QValidator::Intermediate; + QTest::newRow("123.54.") << "123.54." << QValidator::Intermediate; + QTest::newRow("123.255") << "123.255" << QValidator::Intermediate; + QTest::newRow("123.255.") << "123.255." << QValidator::Intermediate; + QTest::newRow("123.123.9") << "123.123.9" << QValidator::Intermediate; + QTest::newRow("123.34.99") << "123.34.99" << QValidator::Intermediate; + QTest::newRow("123.22.233") << "123.22.233" << QValidator::Intermediate; + QTest::newRow("255.255.255.") << "255.255.255." << QValidator::Intermediate; + QTest::newRow("1.1.1.7") << "1.1.1.7" << QValidator::Acceptable; + QTest::newRow("12a") << "12a" << QValidator::Invalid; + QTest::newRow("255") << "255" << QValidator::Intermediate; + QTest::newRow("256") << "256" << QValidator::Invalid; + QTest::newRow("255.255.255.255") << "255.255.255.255" << QValidator::Acceptable; + QTest::newRow("256.255.255.255") << "256.255.255.255" << QValidator::Invalid; + QTest::newRow("255.256.255.255") << "255.256.255.255" << QValidator::Invalid; + QTest::newRow("255.255.256.255") << "255.255.256.255" << QValidator::Invalid; + QTest::newRow("255.255.255.256") << "255.255.255.256" << QValidator::Invalid; + QTest::newRow("1.1.1.1.") << "1.1.1.1." << QValidator::Invalid; +} + +void SimpleIpv4Test::baseTest() +{ + int pos; + + QFETCH(QString, address); + QFETCH(QValidator::State, result); + + QCOMPARE(m_vb.validate(address, pos), result); +} + +void SimpleIpv4Test::cidrTest_data() +{ + QTest::addColumn("address"); + QTest::addColumn("result"); + + QTest::newRow("10.77.18.4/32") << "10.77.18.4/32" << QValidator::Acceptable; + QTest::newRow("10.77.18.4/33") << "10.77.18.4/33" << QValidator::Invalid; + QTest::newRow("10.77.14.8") << "10.77.14.8" << QValidator::Intermediate; + QTest::newRow("10.77.13/") << "10.77.13/" << QValidator::Invalid; + QTest::newRow("33.22.55.44/") << "33.22.55.44/" << QValidator::Intermediate; + QTest::newRow("11.23.45./") << "11.23.45./" << QValidator::Invalid; + QTest::newRow("0.0.0.0/0") << "0.0.0.0/0" << QValidator::Acceptable; + QTest::newRow("1.2.3.4/28/") << "1.2.3.4/28/" << QValidator::Invalid; + QTest::newRow("1.2.3.4//") << "1.2.3.4//" << QValidator::Invalid; +} + +void SimpleIpv4Test::cidrTest() +{ + int pos; + + QFETCH(QString, address); + QFETCH(QValidator::State, result); + + QCOMPARE(m_vc.validate(address, pos), result); +} + +void SimpleIpv4Test::portTest_data() +{ + QTest::addColumn("address"); + QTest::addColumn("result"); + + QTest::newRow("10.77.18.4:32") << "10.77.18.4:32" << QValidator::Acceptable; + QTest::newRow("10.77.18.4:65536") << "10.77.18.4:65536" << QValidator::Invalid; + QTest::newRow("10.77.18.4") << "10.77.18.4" << QValidator::Intermediate; + QTest::newRow("10.77.13:") << "10.77.13:" << QValidator::Invalid; + QTest::newRow("33.22.55.44:") << "33.22.55.44:" << QValidator::Intermediate; + QTest::newRow("11.23.45.:") << "11.23.45.:" << QValidator::Invalid; + QTest::newRow("0.0.0.0:65535") << "0.0.0.0:65535" << QValidator::Acceptable; + QTest::newRow("1.2.3.4:0:") << "1.2.3.4:0:" << QValidator::Invalid; + QTest::newRow("1.2.3.4::") << "1.2.3.4::" << QValidator::Invalid; +} + +void SimpleIpv4Test::portTest() +{ + int pos; + + QFETCH(QString, address); + QFETCH(QValidator::State, result); + + QCOMPARE(m_vp.validate(address, pos), result); +} + +QTEST_APPLESS_MAIN(SimpleIpv4Test) + +#include "simpleipv4test.moc" diff --git a/tests/simpleipv6test.cpp b/tests/simpleipv6test.cpp new file mode 100644 index 00000000..2a049c07 --- /dev/null +++ b/tests/simpleipv6test.cpp @@ -0,0 +1,192 @@ +/* +Copyright 2018 Bruce Anderson + +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) version 3 or any later version +accepted by the membership of KDE e.V. (or its successor approved +by the membership of KDE e.V.), which shall act as a proxy +defined in Section 14 of version 3 of the license. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +#include "simpleipv6addressvalidator.h" +#include + +class SimpleIpv6Test : public QObject +{ + Q_OBJECT + +public: + SimpleIpv6Test(); + +private slots: + void baseTest(); + void baseTest_data(); + void cidrTest(); + void cidrTest_data(); + void portTest(); + void portTest_data(); + +private: + SimpleIpV6AddressValidator m_vb; + SimpleIpV6AddressValidator m_vc; + SimpleIpV6AddressValidator m_vp; +}; + +SimpleIpv6Test::SimpleIpv6Test() + : m_vb(nullptr, SimpleIpV6AddressValidator::AddressStyle::Base) + , m_vc(nullptr, SimpleIpV6AddressValidator::AddressStyle::WithCidr) + , m_vp(nullptr, SimpleIpV6AddressValidator::AddressStyle::WithPort) +{ +} + +Q_DECLARE_METATYPE(QValidator::State) + +void SimpleIpv6Test::baseTest_data() +{ + QTest::addColumn("address"); + QTest::addColumn("result"); + + + QTest::newRow("null string") << "" << QValidator::Intermediate; + QTest::newRow("0123:4567:89ab:cdef") << "0123:4567:89ab:cdef" << QValidator::Intermediate; + QTest::newRow("0123:4567:89ab:cdef:0123:4567:89ab:cdef") << "0123:4567:89ab:cdef:0123:4567:89ab:cdef" << QValidator::Acceptable; + QTest::newRow("1") << "1" << QValidator::Intermediate; + QTest::newRow("12") << "12" << QValidator::Intermediate; + QTest::newRow("123") << "123" << QValidator::Intermediate; + QTest::newRow("1234") << "1234" << QValidator::Intermediate; + QTest::newRow("1234:") << "1234:" << QValidator::Intermediate; + QTest::newRow("1234:1") << "1234:1" << QValidator::Intermediate; + QTest::newRow("1234:12") << "1234:12" << QValidator::Intermediate; + QTest::newRow("1234:123") << "1234:123" << QValidator::Intermediate; + QTest::newRow("1234:1234") << "1234:1234" << QValidator::Intermediate; + QTest::newRow("1234:1234:") << "1234:1234:" << QValidator::Intermediate; + QTest::newRow("1234:1234:1") << "1234:1234:1" << QValidator::Intermediate; + QTest::newRow("1234:1234:12") << "1234:1234:12" << QValidator::Intermediate; + QTest::newRow("1234:1234:123") << "1234:1234:123" << QValidator::Intermediate; + QTest::newRow("1234:1234:1234") << "1234:1234:1234" << QValidator::Intermediate; + QTest::newRow("1234:1234:1234:") << "1234:1234:1234:" << QValidator::Intermediate; + QTest::newRow("1234:1234:1234:1") << "1234:1234:1234:1" << QValidator::Intermediate; + QTest::newRow("1234:1234:1234:12") << "1234:1234:1234:12" << QValidator::Intermediate; + QTest::newRow("1234:1234:1234:123") << "1234:1234:1234:123" << QValidator::Intermediate; + QTest::newRow("1234:1234:1234:1234") << "1234:1234:1234:1234" << QValidator::Intermediate; + QTest::newRow("1234:1234:1234:1234:") << "1234:1234:1234:1234:" << QValidator::Intermediate; + QTest::newRow("1234:1234:1234:1234:1") << "1234:1234:1234:1234:1" << QValidator::Intermediate; + QTest::newRow("1234:1234:1234:1234:12") << "1234:1234:1234:1234:12" << QValidator::Intermediate; + QTest::newRow("1234:1234:1234:1234:123") << "1234:1234:1234:1234:123" << QValidator::Intermediate; + QTest::newRow("1234:1234:1234:1234:1234") << "1234:1234:1234:1234:1234" << QValidator::Intermediate; + QTest::newRow("1234:1234:1234:1234:1234:") << "1234:1234:1234:1234:1234:" << QValidator::Intermediate; + QTest::newRow("1234:1234:1234:1234:1234:1") << "1234:1234:1234:1234:1234:1" << QValidator::Intermediate; + QTest::newRow("1234:1234:1234:1234:1234:12") << "1234:1234:1234:1234:1234:12" << QValidator::Intermediate; + QTest::newRow("1234:1234:1234:1234:1234:123") << "1234:1234:1234:1234:1234:123" << QValidator::Intermediate; + QTest::newRow("1234:1234:1234:1234:1234:1234") << "1234:1234:1234:1234:1234:1234" << QValidator::Intermediate; + QTest::newRow("1234:1234:1234:1234:1234:1234:") << "1234:1234:1234:1234:1234:1234:" << QValidator::Intermediate; + QTest::newRow("1234:1234:1234:1234:1234:1234:1") << "1234:1234:1234:1234:1234:1234:1" << QValidator::Intermediate; + QTest::newRow("1234:1234:1234:1234:1234:1234:12") << "1234:1234:1234:1234:1234:1234:12" << QValidator::Intermediate; + QTest::newRow("1234:1234:1234:1234:1234:1234:123") << "1234:1234:1234:1234:1234:1234:123" << QValidator::Intermediate; + QTest::newRow("1234:1234:1234:1234:1234:1234:1234") << "1234:1234:1234:1234:1234:1234:1234" << QValidator::Intermediate; + QTest::newRow("1234:1234:1234:1234:1234:1234:1234:") << "1234:1234:1234:1234:1234:1234:1234:" << QValidator::Intermediate; + QTest::newRow("1234:1234:1234:1234:1234:1234:1234:1") << "1234:1234:1234:1234:1234:1234:1234:1" << QValidator::Acceptable; + QTest::newRow("1234:1234:1234:1234:1234:1234:1234:12") << "1234:1234:1234:1234:1234:1234:1234:12" << QValidator::Acceptable; + QTest::newRow("1234:1234:1234:1234:1234:1234:1234:123") << "1234:1234:1234:1234:1234:1234:1234:123" << QValidator::Acceptable; + QTest::newRow("1234:1234:1234:1234:1234:1234:1234:1234") << "1234:1234:1234:1234:1234:1234:1234:1234" << QValidator::Acceptable; + QTest::newRow(":") << ":" << QValidator::Intermediate; + QTest::newRow("::") << "::" << QValidator::Acceptable; + QTest::newRow("::1:2:3:4") << "::1:2:3:4" << QValidator::Acceptable; + QTest::newRow("1::2:3:4") << "1::2:3:4" << QValidator::Acceptable; + QTest::newRow("1:2345::6:7") << "1:2345::6:7" << QValidator::Acceptable; + QTest::newRow("1:2:3::1:1:1") << "1:2:3::1:1:1" << QValidator::Acceptable; + QTest::newRow("1:2:3:4::1") << "1:2:3:4::1" << QValidator::Acceptable; + QTest::newRow("1:2:3:4:5::1") << "1:2:3:4:5::1" << QValidator::Acceptable; + QTest::newRow("1:2:3:4:5:6::1") << "1:2:3:4:5:6::1" << QValidator::Acceptable; + QTest::newRow("1:2:3:4:5:6:7::") << "1:2:3:4:5:6:7::" << QValidator::Acceptable; + QTest::newRow("1::") << "1::" << QValidator::Acceptable; + QTest::newRow("::1:2:3:4") << "::1:2:3:4" << QValidator::Acceptable; + QTest::newRow("::1:2:3::4") << "::1:2:3::4" << QValidator::Invalid; + QTest::newRow("1:2::3:4:5:6:7:") << "1:2::3:4:5:6:7:" << QValidator::Invalid; + QTest::newRow("1:2::3:4:5:6:7:8") << "1:2::3:4:5:6:7:8" << QValidator::Invalid; + QTest::newRow(":1") << ":1" << QValidator::Invalid; + QTest::newRow("0123:4567:89ab:cdef:0123:4567:89ab:cdeg") << "0123:4567:89ab:cdef:0123:4567:89ab:cdeg" << QValidator::Invalid; + QTest::newRow("0123:4567:89ab:cdef:0123:4567:89ab:cde.") << "0123:4567:89ab:cdef:0123:4567:89ab:cde." << QValidator::Invalid; + QTest::newRow("0123:4567:89ab:cdef:0123:4567:89ab:cden") << "0123:4567:89ab:cdef:0123:4567:89ab:cden" << QValidator::Invalid; + QTest::newRow("0n") << "0n" << QValidator::Invalid; +} + +void SimpleIpv6Test::baseTest() +{ + int pos; + + QFETCH(QString, address); + QFETCH(QValidator::State, result); + + QCOMPARE(m_vb.validate(address, pos), result); +} + +void SimpleIpv6Test::cidrTest_data() +{ + QTest::addColumn("address"); + QTest::addColumn("result"); + + QTest::newRow("1234:2345:3456:4567:5678:6789:789A:89ab/128") << "1234:2345:3456:4567:5678:6789:789A:89ab/128" << QValidator::Acceptable; + QTest::newRow("") << "" << QValidator::Intermediate; + QTest::newRow("1234:2345::6789:789A:89ab/28") << "1234:2345::6789:789A:89ab/28" << QValidator::Acceptable; + QTest::newRow("1234:2345:3456:4567:5678:6789:789A:89ab/129") << "1234:2345:3456:4567:5678:6789:789A:89ab/129" << QValidator::Invalid; + QTest::newRow("1234:2345:3456:4567:5678:6789:789A:89ab/") << "1234:2345:3456:4567:5678:6789:789A:89ab/" << QValidator::Intermediate; + QTest::newRow("1234:2345:3456:4567:5678:6789:789A/") << "1234:2345:3456:4567:5678:6789:789A/" << QValidator::Invalid; + QTest::newRow("1234:2345:/") << "1234:2345:/" << QValidator::Invalid; + QTest::newRow("1234:2345::6789:789A:89ab") << "1234:2345::6789:789A:89ab" << QValidator::Intermediate; + QTest::newRow("::/0") << "::/0" << QValidator::Acceptable; + QTest::newRow("1234:2345::6789:789A:89ab/28/") << "1234:2345::6789:789A:89ab/28/" << QValidator::Invalid; + QTest::newRow("1234:2345::6789:789A:89ab//") << "1234:2345::6789:789A:89ab//" << QValidator::Invalid; +} + +void SimpleIpv6Test::cidrTest() +{ + int pos; + + QFETCH(QString, address); + QFETCH(QValidator::State, result); + + QCOMPARE(m_vc.validate(address, pos), result); +} + +void SimpleIpv6Test::portTest_data() +{ + QTest::addColumn("address"); + QTest::addColumn("result"); + + QTest::newRow("") << "" << QValidator::Intermediate; + QTest::newRow("1") << "1" << QValidator::Invalid; + QTest::newRow("[1") << "[1" << QValidator::Intermediate; + QTest::newRow("[1123:22:44:11]") << "[1123:22:44:11]" << QValidator::Invalid; + QTest::newRow("[1234:2345::6789:789A:89ab]") << "[1234:2345::6789:789A:89ab]" << QValidator::Intermediate; + QTest::newRow("[1234:2345::6789:789A:89ab]:") << "[1234:2345::6789:789A:89ab]:" << QValidator::Intermediate; + QTest::newRow("[1234:2345::6789:789A:89ab]:a") << "[1234:2345::6789:789A:89ab]:a" << QValidator::Invalid; + QTest::newRow("[1234:2345::6789:789A:89ab]:12") << "[1234:2345::6789:789A:89ab]:12" << QValidator::Acceptable; + QTest::newRow("[1234:2345::6789:789A:89ab]:65535") << "[1234:2345::6789:789A:89ab]:65535" << QValidator::Acceptable; + QTest::newRow("[1234:2345::6789:789A:89ab]:65536") << "[1234:2345::6789:789A:89ab]:65536" << QValidator::Invalid; +} + + +void SimpleIpv6Test::portTest() +{ + int pos; + + QFETCH(QString, address); + QFETCH(QValidator::State, result); + + QCOMPARE(m_vp.validate(address, pos), result); +} + +QTEST_GUILESS_MAIN(SimpleIpv6Test) + +#include "simpleipv6test.moc" diff --git a/vpn/fortisslvpn/CMakeLists.txt b/vpn/fortisslvpn/CMakeLists.txt index e6a9e4cb..e8213bf4 100644 --- a/vpn/fortisslvpn/CMakeLists.txt +++ b/vpn/fortisslvpn/CMakeLists.txt @@ -1,32 +1,26 @@ add_definitions(-DTRANSLATION_DOMAIN=\"plasmanetworkmanagement_fortisslvpnui\") set(fortisslvpn_SRCS fortisslvpn.cpp fortisslvpnwidget.cpp fortisslvpnauth.cpp ) ki18n_wrap_ui(fortisslvpn_SRCS fortisslvpn.ui fortisslvpnadvanced.ui fortisslvpnauth.ui) add_library(plasmanetworkmanagement_fortisslvpnui ${fortisslvpn_SRCS}) kcoreaddons_desktop_to_json(plasmanetworkmanagement_fortisslvpnui plasmanetworkmanagement_fortisslvpnui.desktop) target_link_libraries(plasmanetworkmanagement_fortisslvpnui plasmanm_internal plasmanm_editor - Qt5::Widgets - Qt5::Network - Qt5::DBus - KF5::NetworkManagerQt - KF5::Service - KF5::Completion KF5::I18n KF5::WidgetsAddons KF5::KIOWidgets KF5::CoreAddons ) -install(TARGETS plasmanetworkmanagement_fortisslvpnui DESTINATION ${PLUGIN_INSTALL_DIR}) +install(TARGETS plasmanetworkmanagement_fortisslvpnui DESTINATION ${KDE_INSTALL_PLUGINDIR}) -install(FILES plasmanetworkmanagement_fortisslvpnui.desktop DESTINATION ${SERVICES_INSTALL_DIR}) +install(FILES plasmanetworkmanagement_fortisslvpnui.desktop DESTINATION ${KDE_INSTALL_KSERVICES5DIR}) diff --git a/vpn/fortisslvpn/fortisslvpn.h b/vpn/fortisslvpn/fortisslvpn.h index d9316e5e..ed6b1c31 100644 --- a/vpn/fortisslvpn/fortisslvpn.h +++ b/vpn/fortisslvpn/fortisslvpn.h @@ -1,43 +1,43 @@ /* Copyright 2017 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_FORTISSLVPN_H #define PLASMA_NM_FORTISSLVPN_H #include "vpnuiplugin.h" #include class Q_DECL_EXPORT FortisslvpnUiPlugin : public VpnUiPlugin { Q_OBJECT public: explicit FortisslvpnUiPlugin(QObject *parent = nullptr, const QVariantList& = QVariantList()); - virtual ~FortisslvpnUiPlugin(); - SettingWidget *widget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0) Q_DECL_OVERRIDE; - SettingWidget *askUser(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0) Q_DECL_OVERRIDE; - - QString suggestedFileName(const NetworkManager::ConnectionSettings::Ptr &connection) const Q_DECL_OVERRIDE; - QString supportedFileExtensions() const Q_DECL_OVERRIDE; - NMVariantMapMap importConnectionSettings(const QString &fileName) Q_DECL_OVERRIDE; - bool exportConnectionSettings(const NetworkManager::ConnectionSettings::Ptr &connection, const QString &fileName) Q_DECL_OVERRIDE; + ~FortisslvpnUiPlugin() override; + SettingWidget *widget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr) override; + SettingWidget *askUser(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr) override; + + QString suggestedFileName(const NetworkManager::ConnectionSettings::Ptr &connection) const override; + QString supportedFileExtensions() const override; + NMVariantMapMap importConnectionSettings(const QString &fileName) override; + bool exportConnectionSettings(const NetworkManager::ConnectionSettings::Ptr &connection, const QString &fileName) override; }; #endif // PLASMA_NM_FORTISSLVPN_H diff --git a/vpn/fortisslvpn/fortisslvpnauth.h b/vpn/fortisslvpn/fortisslvpnauth.h index 85920bd7..5ca74ec7 100644 --- a/vpn/fortisslvpn/fortisslvpnauth.h +++ b/vpn/fortisslvpn/fortisslvpnauth.h @@ -1,43 +1,43 @@ /* Copyright 2016 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_FORTISSLVPN_AUTH_H #define PLASMA_NM_FORTISSLVPN_AUTH_H #include #include "settingwidget.h" class FortisslvpnAuthDialogPrivate; class FortisslvpnAuthDialog : public SettingWidget { Q_OBJECT Q_DECLARE_PRIVATE(FortisslvpnAuthDialog) public: explicit FortisslvpnAuthDialog(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr); - ~FortisslvpnAuthDialog(); - QVariantMap setting() const Q_DECL_OVERRIDE; + ~FortisslvpnAuthDialog() override; + QVariantMap setting() const override; private: FortisslvpnAuthDialogPrivate *const d_ptr; }; #endif // PLASMA_NM_FORTISSLVPN_AUTH_H diff --git a/vpn/fortisslvpn/fortisslvpnauth.ui b/vpn/fortisslvpn/fortisslvpnauth.ui index 428e878a..c423c61c 100644 --- a/vpn/fortisslvpn/fortisslvpnauth.ui +++ b/vpn/fortisslvpn/fortisslvpnauth.ui @@ -1,48 +1,48 @@ FortisslvpnAuth 0 0 408 136 0 Password: false - le_password + password true PasswordField QLineEdit
passwordfield.h
diff --git a/vpn/fortisslvpn/fortisslvpnwidget.h b/vpn/fortisslvpn/fortisslvpnwidget.h index 049f85f9..8a0fedc6 100644 --- a/vpn/fortisslvpn/fortisslvpnwidget.h +++ b/vpn/fortisslvpn/fortisslvpnwidget.h @@ -1,50 +1,50 @@ /* Copyright 2017 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_FORTISSLVPN_WIDGET_H #define PLASMA_NM_FORTISSLVPN_WIDGET_H #include #include "settingwidget.h" class FortisslvpnWidgetPrivate; class FortisslvpnWidget : public SettingWidget { Q_OBJECT Q_DECLARE_PRIVATE(FortisslvpnWidget) public: - explicit FortisslvpnWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0, Qt::WindowFlags f = 0); - virtual ~FortisslvpnWidget(); + explicit FortisslvpnWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr, Qt::WindowFlags f = {}); + ~FortisslvpnWidget() override; - void loadConfig(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; - void loadSecrets(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; - QVariantMap setting() const Q_DECL_OVERRIDE; - bool isValid() const Q_DECL_OVERRIDE; + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; + void loadSecrets(const NetworkManager::Setting::Ptr &setting) override; + QVariantMap setting() const override; + bool isValid() const override; private Q_SLOTS: void showAdvanced(); private: FortisslvpnWidgetPrivate *const d_ptr; }; #endif // PLASMA_NM_FORTISSLVPN_WIDGET_H diff --git a/vpn/fortisslvpn/plasmanetworkmanagement_fortisslvpnui.desktop b/vpn/fortisslvpn/plasmanetworkmanagement_fortisslvpnui.desktop index 20f00491..0fe3fccb 100644 --- a/vpn/fortisslvpn/plasmanetworkmanagement_fortisslvpnui.desktop +++ b/vpn/fortisslvpn/plasmanetworkmanagement_fortisslvpnui.desktop @@ -1,82 +1,86 @@ [Desktop Entry] Type=Service Icon= ServiceTypes=PlasmaNetworkManagement/VpnUiPlugin X-KDE-Library=plasmanetworkmanagement_fortisslvpnui X-NetworkManager-Services=org.freedesktop.NetworkManager.fortisslvpn X-KDE-PluginInfo-Author=Jan Grulich X-KDE-PluginInfo-Email=jgrulich@redhat.com X-KDE-PluginInfo-Name=plasmanetworkmanagement_fortisslvpnui X-KDE-PluginInfo-Version=0.1 X-KDE-PluginInfo-Website= X-KDE-PluginInfo-Category=VPNService X-KDE-PluginInfo-Depends= X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=false Name=Fortinet SSLVPN (fortisslvpn) Name[ca]=Fortinet SSLVPN (fortisslvpn) Name[ca@valencia]=Fortinet SSLVPN (fortisslvpn) Name[da]=Fortinet SSLVPN (fortisslvpn) Name[de]=Fortinet SSLVPN (fortisslvpn) Name[el]=Fortinet SSLVPN (fortisslvpn) Name[en_GB]=Fortinet SSLVPN (fortisslvpn) Name[es]=SSLVPN de Fortinet (fortisslvpn) Name[eu]=Fortinet SSLVPN (fortisslvpn) Name[fi]=Fortinet SSLVPN (fortisslvpn) Name[fr]=SSLVPN Fortinet (fortisslvpn) Name[gl]=VPN SSL de Fortinet (fortisslvpn) Name[hu]=Fortinet SSLVPN (fortisslvpn) +Name[id]=Fortinet SSLVPN (fortisslvpn) Name[it]=Fortinet SSLVPN (fortisslvpn) Name[ko]=Fortinet SSLVPN (fortisslvpn) Name[nl]=Fortinet SSLVPN (fortisslvpn) Name[nn]=Fortinet SSLVPN (fortisslvpn) Name[pa]=ਫੋਰਟੀਨੈੱਟ SSLVPN (fortisslvpn) Name[pl]=Fortinet SSLVPN (fortisslvpn) Name[pt]=SSLVPN do Fortinet (fortisslvpn) Name[pt_BR]=Fortinet SSLVPN (fortisslvpn) +Name[ru]=Fortinet SSLVPN (fortisslvpn) Name[sk]=Fortinet SSLVPN (fortisslvpn) Name[sl]=Fortinet SSLVPN (fortisslvpn) Name[sr]=Фортинетов ССЛ ВПН Name[sr@ijekavian]=Фортинетов ССЛ ВПН Name[sr@ijekavianlatin]=Fortinetov SSL VPN Name[sr@latin]=Fortinetov SSL VPN Name[sv]=Fortinet SSLVPN (fortisslvpn) Name[tr]=Fortinet SSLVPN (fortisslvpn) Name[uk]=Fortinet SSLVPN (fortisslvpn) Name[x-test]=xxFortinet SSLVPN (fortisslvpn)xx Name[zh_CN]=Fortinet SSLVPN (fortisslvpn) Name[zh_TW]=Fortinet SSLVPN (fortisslvpn) Comment=Fortinet SSLVPN virtual private networks Comment[ca]=Xarxes privades virtuals Fortinet SSLVPN Comment[ca@valencia]=Xarxes privades virtuals Fortinet SSLVPN Comment[da]=Fortinet SSLVPN virtuelle private netværk Comment[de]=Virtuelles privates Netzwerk Fortinet-SSLVPN Comment[el]=Εικονικά ιδωτικά δίκτυα Fortinet SSLVPN Comment[en_GB]=Fortinet SSLVPN virtual private networks Comment[es]=Redes privadas virtuales SSLVPN de Fortinet Comment[eu]=Fortinet SSLVPN alegiazko sare pribatuak Comment[fi]=Fortinet SSLVPN -virtuaaliyksityisverkot Comment[fr]=Réseaux privés virtuels SSLVPN Fortinet Comment[gl]=Redes privadas virtuais SSL de Fortinet Comment[hu]=Fortinet SSLVPN virtuális magánhálózat +Comment[id]=Network privat virtual Fortinet SSLVPN Comment[it]=Reti private virtuali Fortinet SSLVPN Comment[ko]=Fortinet SSLVPN 가상 개인 네트워크 Comment[nl]=Fortinet SSLVPN virtuele private netwerken Comment[nn]=Fortinet SSLVPN virtuelle private nettverk Comment[pa]=ਫੋਰਟੀਨੈੱਟ SSLVPN ਵਰਚੁਅਲ ਪਰਾਈਵੇਟ ਨੈੱਟਵਰਕ Comment[pl]=Fortinet SSLVPN wirtualne prywatne sieci Comment[pt]=Redes privadas virtuais do SSLVPN do Fortinet Comment[pt_BR]=Redes privadas virtuais Fortinet SSLVPN +Comment[ru]=Виртуальные частные сети Fortinet SSLVPN Comment[sk]=Virtuálne privátne siete Fortinet SSLVPN Comment[sl]=Navidezna zasebna omrežja Fortinet SSLVPN Comment[sr]=Виртуелне приватне мреже преко Фортинетовог ССЛ ВПН‑а Comment[sr@ijekavian]=Виртуелне приватне мреже преко Фортинетовог ССЛ ВПН‑а Comment[sr@ijekavianlatin]=Virtuelne privatne mreže preko Fortinetovog SSL VPN‑a Comment[sr@latin]=Virtuelne privatne mreže preko Fortinetovog SSL VPN‑a Comment[sv]=Fortinet SSLVPN virtuella privata nätverk Comment[tr]=Fortinet SSLVPN sanal özel ağlar Comment[uk]=Віртуальні приватні мережі SSLVPN Fortinet Comment[x-test]=xxFortinet SSLVPN virtual private networksxx Comment[zh_CN]=Fortinet SSLVPN 虚拟专网 Comment[zh_TW]=Fortinet SSLVPN 虛擬私人網路 diff --git a/vpn/iodine/CMakeLists.txt b/vpn/iodine/CMakeLists.txt index d0a2bfab..243af59f 100644 --- a/vpn/iodine/CMakeLists.txt +++ b/vpn/iodine/CMakeLists.txt @@ -1,32 +1,25 @@ add_definitions(-DTRANSLATION_DOMAIN=\"plasmanetworkmanagement_iodineui\") set(iodine_SRCS iodine.cpp iodinewidget.cpp iodineauth.cpp ) ki18n_wrap_ui(iodine_SRCS iodine.ui iodineauth.ui) add_library(plasmanetworkmanagement_iodineui ${iodine_SRCS}) kcoreaddons_desktop_to_json(plasmanetworkmanagement_iodineui plasmanetworkmanagement_iodineui.desktop) target_link_libraries(plasmanetworkmanagement_iodineui plasmanm_internal plasmanm_editor - Qt5::Widgets - Qt5::Network - Qt5::DBus - KF5::NetworkManagerQt - KF5::Service - KF5::Completion KF5::I18n KF5::WidgetsAddons - KF5::KIOWidgets KF5::CoreAddons ) -install(TARGETS plasmanetworkmanagement_iodineui DESTINATION ${PLUGIN_INSTALL_DIR}) +install(TARGETS plasmanetworkmanagement_iodineui DESTINATION ${KDE_INSTALL_PLUGINDIR}) -install(FILES plasmanetworkmanagement_iodineui.desktop DESTINATION ${SERVICES_INSTALL_DIR}) +install(FILES plasmanetworkmanagement_iodineui.desktop DESTINATION ${KDE_INSTALL_KSERVICES5DIR}) diff --git a/vpn/iodine/iodine.h b/vpn/iodine/iodine.h index 721ce81c..26d3337c 100644 --- a/vpn/iodine/iodine.h +++ b/vpn/iodine/iodine.h @@ -1,43 +1,43 @@ /* Copyright 2016 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_IODINE_H #define PLASMA_NM_IODINE_H #include "vpnuiplugin.h" #include class Q_DECL_EXPORT IodineUiPlugin : public VpnUiPlugin { Q_OBJECT public: explicit IodineUiPlugin(QObject *parent = nullptr, const QVariantList& = QVariantList()); - virtual ~IodineUiPlugin(); - SettingWidget * widget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0) Q_DECL_OVERRIDE; - SettingWidget * askUser(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0) Q_DECL_OVERRIDE; - - QString suggestedFileName(const NetworkManager::ConnectionSettings::Ptr &connection) const Q_DECL_OVERRIDE; - QString supportedFileExtensions() const Q_DECL_OVERRIDE; - NMVariantMapMap importConnectionSettings(const QString &fileName) Q_DECL_OVERRIDE; - bool exportConnectionSettings(const NetworkManager::ConnectionSettings::Ptr &connection, const QString &fileName) Q_DECL_OVERRIDE; + ~IodineUiPlugin() override; + SettingWidget * widget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr) override; + SettingWidget * askUser(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr) override; + + QString suggestedFileName(const NetworkManager::ConnectionSettings::Ptr &connection) const override; + QString supportedFileExtensions() const override; + NMVariantMapMap importConnectionSettings(const QString &fileName) override; + bool exportConnectionSettings(const NetworkManager::ConnectionSettings::Ptr &connection, const QString &fileName) override; }; #endif // PLASMA_NM_IODINE_H diff --git a/vpn/iodine/iodineauth.h b/vpn/iodine/iodineauth.h index dfb27dc2..7dbf7b23 100644 --- a/vpn/iodine/iodineauth.h +++ b/vpn/iodine/iodineauth.h @@ -1,43 +1,43 @@ /* Copyright 2016 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_IODINE_AUTH_H #define PLASMA_NM_IODINE_AUTH_H #include #include "settingwidget.h" class IodineAuthDialogPrivate; class IodineAuthDialog : public SettingWidget { Q_OBJECT Q_DECLARE_PRIVATE(IodineAuthDialog) public: explicit IodineAuthDialog(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr); - ~IodineAuthDialog(); - QVariantMap setting() const Q_DECL_OVERRIDE; + ~IodineAuthDialog() override; + QVariantMap setting() const override; private: IodineAuthDialogPrivate *const d_ptr; }; #endif // PLASMA_NM_IODINE_AUTH_H diff --git a/vpn/iodine/iodinewidget.h b/vpn/iodine/iodinewidget.h index d3a39d9e..3ae35e41 100644 --- a/vpn/iodine/iodinewidget.h +++ b/vpn/iodine/iodinewidget.h @@ -1,50 +1,50 @@ /* Copyright 2016 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_IODINE_WIDGET_H #define PLASMA_NM_IODINE_WIDGET_H #include #include "settingwidget.h" namespace Ui { class IodineWidget; } class IodineWidget : public SettingWidget { Q_OBJECT public: - explicit IodineWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0, Qt::WindowFlags f = 0); - virtual ~IodineWidget(); + explicit IodineWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr, Qt::WindowFlags f = {}); + ~IodineWidget() override; - void loadConfig(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; - void loadSecrets(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; - QVariantMap setting() const Q_DECL_OVERRIDE; - bool isValid() const Q_DECL_OVERRIDE; + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; + void loadSecrets(const NetworkManager::Setting::Ptr &setting) override; + QVariantMap setting() const override; + bool isValid() const override; private: Ui::IodineWidget *m_ui; NetworkManager::VpnSetting::Ptr m_setting; }; #endif // PLASMA_NM_IODINE_WIDGET_H diff --git a/vpn/iodine/plasmanetworkmanagement_iodineui.desktop b/vpn/iodine/plasmanetworkmanagement_iodineui.desktop index bc3a0dbd..0ea76154 100644 --- a/vpn/iodine/plasmanetworkmanagement_iodineui.desktop +++ b/vpn/iodine/plasmanetworkmanagement_iodineui.desktop @@ -1,84 +1,86 @@ [Desktop Entry] Type=Service Icon= ServiceTypes=PlasmaNetworkManagement/VpnUiPlugin X-KDE-Library=plasmanetworkmanagement_iodineui X-NetworkManager-Services=org.freedesktop.NetworkManager.iodine X-KDE-PluginInfo-Author=Jan Grulich X-KDE-PluginInfo-Email=jgrulich@redhat.com X-KDE-PluginInfo-Name=plasmanetworkmanagement_iodineui X-KDE-PluginInfo-Version=0.1 X-KDE-PluginInfo-Website= X-KDE-PluginInfo-Category=VPNService X-KDE-PluginInfo-Depends= X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=false Name=Iodine DNS tunnel (iodine) Name[ca]=Túnel de DNS Iodine (iodine) Name[ca@valencia]=Túnel de DNS Iodine (iodine) Name[da]=Iodine DNS-tunnel (iodine) Name[de]=Iodine DNS-Tunnel (iodine) Name[el]=Διοχέτευση Iodine DNS (iodine) Name[en_GB]=Iodine DNS tunnel (iodine) Name[es]=Túnel DNS Iodine (iodine) Name[eu]=Iodine DNS-tunela (iodine) Name[fi]=Iodine-DNS-tunneli (iodine) Name[fr]=Tunnel DNS Iodine (iodine) Name[gl]=Túnel DNS de Iodine (iodine) Name[hu]=Iodine DNS tunnel (iodine) +Name[id]=Iodine DNS tunnel (iodine) Name[it]=Tunnel DNS Iodine Name[ko]=Iodine DNS 터널(iodine) Name[lt]=Iodine DNS tunelis (iodine) Name[nl]=Iodine DNS tunnel (iodine) Name[nn]=Iodine DNS-tunell (iodine) Name[pa]=ਆਈਓਡੀਨ DNS ਟਨਲ (iodine) Name[pl]=Tunel Iodine DNS (iodine) Name[pt]=Túnel de DNS do Iodine (iodine) Name[pt_BR]=Tunel Iodine DNS (iodine) Name[ru]=DNS-туннель iodine Name[sk]=Iodine DNS tunel (iodine) Name[sl]=Tunel DNS Iodine (iodine) Name[sr]=Ајодинов ДНС тунеловање (Ајодин) Name[sr@ijekavian]=Ајодинов ДНС тунеловање (Ајодин) Name[sr@ijekavianlatin]=Iodineov DNS tunelovanje (Iodine) Name[sr@latin]=Iodineov DNS tunelovanje (Iodine) Name[sv]=Iodine DNS-tunnel (iodine) Name[tr]=Iodine DNS tüneli (iodine) Name[uk]=Тунель Iodine DNS (iodine) Name[x-test]=xxIodine DNS tunnel (iodine)xx Name[zh_CN]=Iodine DNS 隧道 (iodine) Name[zh_TW]=Iodine DNS 通道 (iodine) Comment=Tunnel connections via DNS Comment[ca]=Túnel de connexions via DNS Comment[ca@valencia]=Túnel de connexions via DNS Comment[da]=Tunnelforbindelser via DNS Comment[de]=Getunnelte Verbindungen via DNS Comment[el]=Διοχέτευση συνδέσεων μέσω DNS Comment[en_GB]=Tunnel connections via DNS Comment[es]=Conexiones de túnel que usan DNS Comment[eu]=Tunel konexioak DNS bidez Comment[fi]=Tunneliyhteydet DNS:n kautta Comment[fr]=Connexions tunnel via DNS Comment[gl]=Conexións por túnel mediante DNS Comment[hu]=Tunnelkapcsolatok DNS-en keresztül +Comment[id]=Koneksi tunnel via DNS Comment[it]=Incapsula le connessioni tramite DNS Comment[ko]=DNS로 연결 터널링 Comment[nl]=Tunnelverbindingen via DNS Comment[nn]=Tunellsamband via DNS Comment[pa]=DNS ਰਾਹੀਂ ਕਨੈਕਸ਼ਨ ਟਨਲ Comment[pl]=Połączenie tunelowe przez DNS Comment[pt]=Ligações-túnel através de DNS Comment[pt_BR]=Conexões tunel via DNS Comment[ru]=Протокол туннелирования iodine через DNS Comment[sk]=Tunelovať pripojenia cez DNS Comment[sl]=Tuneliranje povezav preko DNS Comment[sr]=Тунеловање веза преко ДНС‑а Comment[sr@ijekavian]=Тунеловање веза преко ДНС‑а Comment[sr@ijekavianlatin]=Tunelovanje veza preko DNS‑a Comment[sr@latin]=Tunelovanje veza preko DNS‑a Comment[sv]=Tunnelanslutningar via DNS Comment[tr]=DNS üzerinden tünel bağlantıları Comment[uk]=Тунельоване з’єднання за допомогою DNS Comment[x-test]=xxTunnel connections via DNSxx Comment[zh_CN]=通过 DNS 的隧道链接 Comment[zh_TW]=透過 DNS 的通道連線 diff --git a/vpn/l2tp/CMakeLists.txt b/vpn/l2tp/CMakeLists.txt index 675d245b..d0598318 100644 --- a/vpn/l2tp/CMakeLists.txt +++ b/vpn/l2tp/CMakeLists.txt @@ -1,34 +1,28 @@ add_definitions(-DTRANSLATION_DOMAIN=\"plasmanetworkmanagement_l2tpui\") set(l2tp_SRCS l2tp.cpp l2tpwidget.cpp l2tpauth.cpp l2tpadvancedwidget.cpp l2tppppwidget.cpp ) ki18n_wrap_ui(l2tp_SRCS l2tp.ui l2tpadvanced.ui l2tpauth.ui l2tpppp.ui) add_library(plasmanetworkmanagement_l2tpui ${l2tp_SRCS}) kcoreaddons_desktop_to_json(plasmanetworkmanagement_l2tpui plasmanetworkmanagement_l2tpui.desktop) target_link_libraries(plasmanetworkmanagement_l2tpui plasmanm_internal plasmanm_editor - Qt5::Widgets - Qt5::Network - Qt5::DBus - KF5::NetworkManagerQt - KF5::Service - KF5::Completion KF5::I18n KF5::WidgetsAddons KF5::KIOWidgets KF5::CoreAddons ) -install(TARGETS plasmanetworkmanagement_l2tpui DESTINATION ${PLUGIN_INSTALL_DIR}) +install(TARGETS plasmanetworkmanagement_l2tpui DESTINATION ${KDE_INSTALL_PLUGINDIR}) -install(FILES plasmanetworkmanagement_l2tpui.desktop DESTINATION ${SERVICES_INSTALL_DIR}) +install(FILES plasmanetworkmanagement_l2tpui.desktop DESTINATION ${KDE_INSTALL_KSERVICES5DIR}) diff --git a/vpn/l2tp/l2tp.h b/vpn/l2tp/l2tp.h index 9905f434..50e87720 100644 --- a/vpn/l2tp/l2tp.h +++ b/vpn/l2tp/l2tp.h @@ -1,43 +1,43 @@ /* Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_L2TP_H #define PLASMA_NM_L2TP_H #include "vpnuiplugin.h" #include class Q_DECL_EXPORT L2tpUiPlugin : public VpnUiPlugin { Q_OBJECT public: - explicit L2tpUiPlugin(QObject * parent = 0, const QVariantList& = QVariantList()); - virtual ~L2tpUiPlugin(); - virtual SettingWidget * widget(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = 0); - virtual SettingWidget * askUser(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = 0); - - QString suggestedFileName(const NetworkManager::ConnectionSettings::Ptr &connection) const; - QString supportedFileExtensions() const; - NMVariantMapMap importConnectionSettings(const QString &fileName); - bool exportConnectionSettings(const NetworkManager::ConnectionSettings::Ptr &connection, const QString &fileName); + explicit L2tpUiPlugin(QObject * parent = nullptr, const QVariantList& = QVariantList()); + ~L2tpUiPlugin() override; + SettingWidget * widget(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = nullptr) override; + SettingWidget * askUser(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = nullptr) override; + + QString suggestedFileName(const NetworkManager::ConnectionSettings::Ptr &connection) const override; + QString supportedFileExtensions() const override; + NMVariantMapMap importConnectionSettings(const QString &fileName) override; + bool exportConnectionSettings(const NetworkManager::ConnectionSettings::Ptr &connection, const QString &fileName) override; }; #endif // PLASMA_NM_L2TP_H diff --git a/vpn/l2tp/l2tpadvancedwidget.h b/vpn/l2tp/l2tpadvancedwidget.h index 70e14fd9..420363b8 100644 --- a/vpn/l2tp/l2tpadvancedwidget.h +++ b/vpn/l2tp/l2tpadvancedwidget.h @@ -1,47 +1,47 @@ /* Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_L2TP_ADVANCED_WIDGET_H #define PLASMA_NM_L2TP_ADVANCED_WIDGET_H #include #include namespace Ui { class L2tpAdvancedWidget; } class L2tpAdvancedWidget : public QDialog { Q_OBJECT public: - explicit L2tpAdvancedWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0); - ~L2tpAdvancedWidget(); + explicit L2tpAdvancedWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr); + ~L2tpAdvancedWidget() override; NMStringMap setting() const; private: void loadConfig(const NetworkManager::VpnSetting::Ptr &setting); Ui::L2tpAdvancedWidget * m_ui; }; #endif // PLASMA_NM_L2TP_ADVANCED_WIDGET_H diff --git a/vpn/l2tp/l2tpauth.h b/vpn/l2tp/l2tpauth.h index c1ac1ab8..c0f3c91f 100644 --- a/vpn/l2tp/l2tpauth.h +++ b/vpn/l2tp/l2tpauth.h @@ -1,44 +1,44 @@ /* Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_L2TP_AUTH_H #define PLASMA_NM_L2TP_AUTH_H #include #include "settingwidget.h" class L2tpAuthDialogPrivate; class L2tpAuthDialog : public SettingWidget { Q_OBJECT Q_DECLARE_PRIVATE(L2tpAuthDialog) public: - explicit L2tpAuthDialog(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0); - ~L2tpAuthDialog(); + explicit L2tpAuthDialog(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr); + ~L2tpAuthDialog() override; virtual void readSecrets(); - virtual QVariantMap setting() const; + QVariantMap setting() const override; private: L2tpAuthDialogPrivate *const d_ptr; }; #endif // PLASMA_NM_L2TP_AUTH_H diff --git a/vpn/l2tp/l2tppppwidget.cpp b/vpn/l2tp/l2tppppwidget.cpp index ba9c554d..f047a6ef 100644 --- a/vpn/l2tp/l2tppppwidget.cpp +++ b/vpn/l2tp/l2tppppwidget.cpp @@ -1,201 +1,201 @@ /* Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "l2tppppwidget.h" #include "ui_l2tpppp.h" #include "nm-l2tp-service.h" #include #include L2tpPPPWidget::L2tpPPPWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent) : QDialog(parent) , m_ui(new Ui::L2tpPppWidget) { m_ui->setupUi(this); setWindowTitle(i18n("L2TP PPP Options")); KAcceleratorManager::manage(this); loadConfig(setting); } L2tpPPPWidget::~L2tpPPPWidget() { delete m_ui; } void L2tpPPPWidget::loadConfig(const NetworkManager::VpnSetting::Ptr &setting) { // General settings const NMStringMap dataMap = setting->data(); // Authentication options const QString yesString = QLatin1String("yes"); bool refuse_pap = (dataMap[NM_L2TP_KEY_REFUSE_PAP] == yesString); bool refuse_chap = (dataMap[NM_L2TP_KEY_REFUSE_CHAP] == yesString); bool refuse_mschap = (dataMap[NM_L2TP_KEY_REFUSE_MSCHAP] == yesString); bool refuse_mschapv2 = (dataMap[NM_L2TP_KEY_REFUSE_MSCHAPV2] == yesString); bool refuse_eap = (dataMap[NM_L2TP_KEY_REFUSE_EAP] == yesString); - QListWidgetItem * item = 0; + QListWidgetItem * item = nullptr; item = m_ui->listWidget->item(0); // PAP item->setCheckState(refuse_pap ? Qt::Unchecked : Qt::Checked); item = m_ui->listWidget->item(1); // CHAP item->setCheckState(refuse_chap ? Qt::Unchecked : Qt::Checked); item = m_ui->listWidget->item(2); // MSCHAP item->setCheckState(refuse_mschap ? Qt::Unchecked : Qt::Checked); item = m_ui->listWidget->item(3); // MSCHAPv2 item->setCheckState(refuse_mschapv2 ? Qt::Unchecked : Qt::Checked); item = m_ui->listWidget->item(4); // EAP item->setCheckState(refuse_eap ? Qt::Unchecked : Qt::Checked); // Cryptography and compression const bool mppe = (dataMap[NM_L2TP_KEY_REQUIRE_MPPE] == yesString); const bool mppe40 = (dataMap[NM_L2TP_KEY_REQUIRE_MPPE_40] == yesString); const bool mppe128 = (dataMap[NM_L2TP_KEY_REQUIRE_MPPE_128] == yesString); const bool mppe_stateful = (dataMap[NM_L2TP_KEY_MPPE_STATEFUL] == yesString); if (mppe || mppe40 || mppe128) { // If MPPE is use m_ui->gbMPPE->setChecked(mppe || mppe40 || mppe128); if (mppe128) { m_ui->cbMPPECrypto->setCurrentIndex(1); // 128 bit } else if (mppe40) { m_ui->cbMPPECrypto->setCurrentIndex(2); // 40 bit } else { m_ui->cbMPPECrypto->setCurrentIndex(0); // Any } m_ui->cbstatefulEncryption->setChecked(mppe_stateful); } const bool nobsd = (dataMap[NM_L2TP_KEY_NOBSDCOMP] == yesString); m_ui->cbBSD->setChecked(!nobsd); const bool nodeflate = (dataMap[NM_L2TP_KEY_NODEFLATE] == yesString); m_ui->cbdeflate->setChecked(!nodeflate); const bool novjcomp = (dataMap[NM_L2TP_KEY_NO_VJ_COMP] == yesString); m_ui->cbTCPheaders->setChecked(!novjcomp); const bool nopcomp = (dataMap[NM_L2TP_KEY_NO_PCOMP] == yesString); m_ui->cbCompressionNegotiation->setChecked(!nopcomp); const bool noaccomp = (dataMap[NM_L2TP_KEY_NO_ACCOMP] == yesString); m_ui->cbAddressControlCompression->setChecked(!noaccomp); // Echo const int lcp_echo_interval = QString(dataMap[NM_L2TP_KEY_LCP_ECHO_INTERVAL]).toInt(); m_ui->cbsendEcho->setChecked(lcp_echo_interval > 0); if (dataMap.contains(QLatin1String(NM_L2TP_KEY_MTU))) { m_ui->sbMTU->setValue(QString(dataMap[NM_L2TP_KEY_MTU]).toInt()); } if (dataMap.contains(QLatin1String(NM_L2TP_KEY_MTU))) { m_ui->sbMRU->setValue(QString(dataMap[NM_L2TP_KEY_MRU]).toInt()); } } NMStringMap L2tpPPPWidget::setting() const { NMStringMap result; - QListWidgetItem * item = 0; + QListWidgetItem * item = nullptr; item = m_ui->listWidget->item(0); // PAP const QString yesString = QLatin1String("yes"); if (item->checkState() == Qt::Unchecked) { result.insert(NM_L2TP_KEY_REFUSE_PAP, yesString); } item = m_ui->listWidget->item(1); // CHAP if (item->checkState() == Qt::Unchecked) { result.insert(NM_L2TP_KEY_REFUSE_CHAP, yesString); } item = m_ui->listWidget->item(2); // MSCHAP if (item->checkState() == Qt::Unchecked) { result.insert(NM_L2TP_KEY_REFUSE_MSCHAP, yesString); } item = m_ui->listWidget->item(3); // MSCHAPv2 if (item->checkState() == Qt::Unchecked) { result.insert(NM_L2TP_KEY_REFUSE_MSCHAPV2, yesString); } item = m_ui->listWidget->item(4); // EAP if (item->checkState() == Qt::Unchecked) { result.insert(NM_L2TP_KEY_REFUSE_EAP, yesString); } // Cryptography and compression if (m_ui->gbMPPE->isChecked()) { int index = m_ui->cbMPPECrypto->currentIndex(); switch (index) { case 0: // "Any" result.insert(NM_L2TP_KEY_REQUIRE_MPPE, yesString); break; case 1: // "128 bit" result.insert(NM_L2TP_KEY_REQUIRE_MPPE_128, yesString); break; case 2: // "40 bit" result.insert(NM_L2TP_KEY_REQUIRE_MPPE_40, yesString); break; } if (m_ui->cbstatefulEncryption->isChecked()) { result.insert(NM_L2TP_KEY_MPPE_STATEFUL, yesString); } } if (!m_ui->cbBSD->isChecked()) { result.insert(NM_L2TP_KEY_NOBSDCOMP, yesString); } if (!m_ui->cbdeflate->isChecked()) { result.insert(NM_L2TP_KEY_NODEFLATE, yesString); } if (!m_ui->cbTCPheaders->isChecked()) { result.insert(NM_L2TP_KEY_NO_VJ_COMP, yesString); } if (!m_ui->cbCompressionNegotiation->isChecked()) { result.insert(NM_L2TP_KEY_NO_PCOMP, yesString); } if (!m_ui->cbAddressControlCompression->isChecked()) { result.insert(NM_L2TP_KEY_NO_ACCOMP, yesString); } // Echo if (m_ui->cbsendEcho->isChecked()) { result.insert(NM_L2TP_KEY_LCP_ECHO_FAILURE, "5"); result.insert(NM_L2TP_KEY_LCP_ECHO_INTERVAL, "30"); } if (m_ui->sbMTU->value() != 0) { result.insert(NM_L2TP_KEY_MTU, QString::number(m_ui->sbMTU->value())); } if (m_ui->sbMRU->value() != 0) { result.insert(NM_L2TP_KEY_MRU, QString::number(m_ui->sbMRU->value())); } return result; } diff --git a/vpn/l2tp/l2tppppwidget.h b/vpn/l2tp/l2tppppwidget.h index e154f420..76c7ac07 100644 --- a/vpn/l2tp/l2tppppwidget.h +++ b/vpn/l2tp/l2tppppwidget.h @@ -1,47 +1,47 @@ /* Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_L2TP_PPP_WIDGET_H #define PLASMA_NM_L2TP_PPP_WIDGET_H #include #include namespace Ui { class L2tpPppWidget; } class L2tpPPPWidget : public QDialog { Q_OBJECT public: - explicit L2tpPPPWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0); - ~L2tpPPPWidget(); + explicit L2tpPPPWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr); + ~L2tpPPPWidget() override; NMStringMap setting() const; private: void loadConfig(const NetworkManager::VpnSetting::Ptr &setting); Ui::L2tpPppWidget * m_ui; }; #endif // PLASMA_NM_L2TP_PPP_WIDGET_H diff --git a/vpn/l2tp/l2tpwidget.cpp b/vpn/l2tp/l2tpwidget.cpp index da5725da..49e1e5cc 100644 --- a/vpn/l2tp/l2tpwidget.cpp +++ b/vpn/l2tp/l2tpwidget.cpp @@ -1,285 +1,285 @@ /* Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "l2tpwidget.h" #include "l2tpadvancedwidget.h" #include "l2tppppwidget.h" #include "ui_l2tp.h" #include "nm-l2tp-service.h" #include #include #include L2tpWidget::L2tpWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget* parent, Qt::WindowFlags f) : SettingWidget(setting, parent, f) , m_ui(new Ui::L2tpWidget) , m_setting(setting) { qDBusRegisterMetaType(); m_ui->setupUi(this); m_ui->password->setPasswordOptionsEnabled(true); connect(m_ui->btnIPSecSettings, &QPushButton::clicked, this, &L2tpWidget::showAdvanced); connect(m_ui->btnPPPSettings, &QPushButton::clicked, this, &L2tpWidget::showPpp); // Connect for setting check watchChangedSetting(); // Connect for validity check connect(m_ui->gateway, &QLineEdit::textChanged, this, &L2tpWidget::slotWidgetChanged); connect(m_ui->cbUseCertificate, &QCheckBox::stateChanged, this, &L2tpWidget::certStateChanged); KAcceleratorManager::manage(this); if (setting && !setting->isNull()) { loadConfig(setting); } } L2tpWidget::~L2tpWidget() { m_tmpAdvancedSetting.clear(); m_tmpPppSetting.clear(); delete m_ui; } void L2tpWidget::loadConfig(const NetworkManager::Setting::Ptr &setting) { Q_UNUSED(setting); const NMStringMap data = m_setting->data(); if (data.contains(NM_L2TP_KEY_GATEWAY)) { m_ui->gateway->setText(data.value(NM_L2TP_KEY_GATEWAY)); } if (data.contains(NM_L2TP_KEY_USER)) { m_ui->username->setText(data.value(NM_L2TP_KEY_USER)); } const NetworkManager::Setting::SecretFlags userPassType = static_cast(data.value(NM_L2TP_KEY_PASSWORD"-flags").toInt()); if (userPassType.testFlag(NetworkManager::Setting::None)) { m_ui->password->setPasswordOption(PasswordField::StoreForAllUsers); } else if (userPassType.testFlag(NetworkManager::Setting::AgentOwned)) { m_ui->password->setPasswordOption(PasswordField::StoreForUser); } else { m_ui->password->setPasswordOption(PasswordField::AlwaysAsk); } if (data.contains(NM_L2TP_KEY_DOMAIN)) { m_ui->domain->setText(data.value(NM_L2TP_KEY_DOMAIN)); } if (data.contains(NM_L2TP_KEY_CERT_CA)) { m_ui->urCACertificate->setText(data.value(NM_L2TP_KEY_CERT_CA)); } if (data.contains(NM_L2TP_KEY_CERT_PUB)) { m_ui->urCertificate->setText(data.value(NM_L2TP_KEY_CERT_PUB)); } if (data.contains(NM_L2TP_KEY_CERT_KEY)) { m_ui->urPrivateKey->setText(data.value(NM_L2TP_KEY_CERT_KEY)); } if (data.value(NM_L2TP_KEY_USE_CERT) == QLatin1String("yes")) { m_ui->cbUseCertificate->setChecked(true); } loadSecrets(setting); } void L2tpWidget::loadSecrets(const NetworkManager::Setting::Ptr &setting) { NetworkManager::VpnSetting::Ptr vpnSetting = setting.staticCast(); if (vpnSetting) { const NMStringMap secrets = vpnSetting->secrets(); const QString userPassword = secrets.value(NM_L2TP_KEY_PASSWORD); if (!userPassword.isEmpty()) { m_ui->password->setText(userPassword); } } } QVariantMap L2tpWidget::setting() const { NetworkManager::VpnSetting setting; setting.setServiceType(QLatin1String(NM_DBUS_SERVICE_L2TP)); NMStringMap data; if (!m_tmpAdvancedSetting.isNull()) { data = m_tmpAdvancedSetting->data(); } else { // retrieve the settings if the dialog has not been opened - QScopedPointer adv(new L2tpAdvancedWidget(m_setting, Q_NULLPTR)); + QScopedPointer adv(new L2tpAdvancedWidget(m_setting, nullptr)); data = adv->setting(); } if (!m_tmpPppSetting.isNull()) { data.unite(m_tmpPppSetting->data()); } else { // retrieve the settings if the dialog has not been opened - QScopedPointer ppp(new L2tpPPPWidget(m_setting, Q_NULLPTR)); + QScopedPointer ppp(new L2tpPPPWidget(m_setting, nullptr)); data.unite(ppp->setting()); } NMStringMap secrets; if (!m_ui->gateway->text().isEmpty()) { data.insert(NM_L2TP_KEY_GATEWAY, m_ui->gateway->text()); } if (m_ui->cbUseCertificate->isChecked()) { data.insert(NM_L2TP_KEY_USE_CERT, "yes"); if (!m_ui->urCACertificate->text().isEmpty()) { data.insert(NM_L2TP_KEY_CERT_CA, m_ui->urCACertificate->text()); } if (!m_ui->urCertificate->text().isEmpty()) { data.insert(NM_L2TP_KEY_CERT_PUB, m_ui->urCertificate->text()); } if (!m_ui->urPrivateKey->text().isEmpty()) { data.insert(NM_L2TP_KEY_CERT_KEY, m_ui->urPrivateKey->text()); } data.insert(NM_L2TP_KEY_PASSWORD"-flags", QString::number(NetworkManager::Setting::NotRequired)); } else { if (!m_ui->username->text().isEmpty()) { data.insert(NM_L2TP_KEY_USER, m_ui->username->text()); } if (m_ui->password->isEnabled() && !m_ui->password->text().isEmpty()) { secrets.insert(NM_L2TP_KEY_PASSWORD, m_ui->password->text()); } switch (m_ui->password->passwordOption()) { case PasswordField::StoreForAllUsers: data.insert(NM_L2TP_KEY_PASSWORD"-flags", QString::number(NetworkManager::Setting::None)); break; case PasswordField::StoreForUser: data.insert(NM_L2TP_KEY_PASSWORD"-flags", QString::number(NetworkManager::Setting::AgentOwned)); break; default: data.insert(NM_L2TP_KEY_PASSWORD"-flags", QString::number(NetworkManager::Setting::NotSaved)); }; if (!m_ui->domain->text().isEmpty()) { data.insert(NM_L2TP_KEY_DOMAIN, m_ui->domain->text()); } } setting.setData(data); setting.setSecrets(secrets); return setting.toMap(); } void L2tpWidget::userPasswordTypeChanged(int index) { m_ui->password->setEnabled(index == SettingWidget::EnumPasswordStorageType::Store); } void L2tpWidget::showAdvanced() { QPointer adv; if (m_tmpAdvancedSetting.isNull()) { adv = new L2tpAdvancedWidget(m_setting, this); } else { adv = new L2tpAdvancedWidget(m_tmpAdvancedSetting, this); } connect(adv.data(), &L2tpAdvancedWidget::accepted, [adv, this] () { NMStringMap advData = adv->setting(); if (!advData.isEmpty()) { if (m_tmpAdvancedSetting.isNull()) { m_tmpAdvancedSetting = NetworkManager::VpnSetting::Ptr(new NetworkManager::VpnSetting); } m_tmpAdvancedSetting->setData(advData); } }); connect(adv.data(), &L2tpAdvancedWidget::finished, [adv] () { if (adv) { adv->deleteLater(); } }); adv->setModal(true); adv->show(); } void L2tpWidget::showPpp() { QPointer adv; if (m_tmpPppSetting.isNull()) { adv = new L2tpPPPWidget(m_setting, this); } else { adv = new L2tpPPPWidget(m_tmpPppSetting, this); } connect(adv.data(), &L2tpPPPWidget::accepted, [adv, this] () { NMStringMap advData = adv->setting(); if (!advData.isEmpty()) { if (m_tmpPppSetting.isNull()) { m_tmpPppSetting = NetworkManager::VpnSetting::Ptr(new NetworkManager::VpnSetting); } m_tmpPppSetting->setData(advData); } }); connect(adv.data(), &L2tpPPPWidget::finished, [adv] () { if (adv) { adv->deleteLater(); } }); adv->setModal(true); adv->show(); } bool L2tpWidget::isValid() const { return !m_ui->gateway->text().isEmpty(); } void L2tpWidget::certStateChanged() { if (m_ui->cbUseCertificate->isChecked()) { m_ui->urCACertificate->setEnabled(true); m_ui->urCertificate->setEnabled(true); m_ui->urPrivateKey->setEnabled(true); m_ui->username->setEnabled(false); m_ui->password->setEnabled(false); m_ui->domain->setEnabled(false); } else { m_ui->urCACertificate->setEnabled(false); m_ui->urCertificate->setEnabled(false); m_ui->urPrivateKey->setEnabled(false); m_ui->username->setEnabled(true); m_ui->password->setEnabled(true); m_ui->domain->setEnabled(true); } } diff --git a/vpn/l2tp/l2tpwidget.h b/vpn/l2tp/l2tpwidget.h index a09e6451..147e8792 100644 --- a/vpn/l2tp/l2tpwidget.h +++ b/vpn/l2tp/l2tpwidget.h @@ -1,60 +1,60 @@ /* Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_L2TP_WIDGET_H #define PLASMA_NM_L2TP_WIDGET_H #include #include "settingwidget.h" namespace Ui { class L2tpWidget; } class L2tpWidget : public SettingWidget { Q_OBJECT public: - explicit L2tpWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget* parent = 0, Qt::WindowFlags f = 0); - virtual ~L2tpWidget(); + explicit L2tpWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget* parent = nullptr, Qt::WindowFlags f = {}); + ~L2tpWidget() override; - void loadConfig(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; - void loadSecrets(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; + void loadSecrets(const NetworkManager::Setting::Ptr &setting) override; - QVariantMap setting() const; + QVariantMap setting() const override; - virtual bool isValid() const; + bool isValid() const override; private Q_SLOTS: void userPasswordTypeChanged(int index); void showAdvanced(); void showPpp(); void certStateChanged(); private: Ui::L2tpWidget * m_ui; NetworkManager::VpnSetting::Ptr m_setting; NetworkManager::VpnSetting::Ptr m_tmpAdvancedSetting; NetworkManager::VpnSetting::Ptr m_tmpPppSetting; }; #endif // PLASMA_NM_L2TP_WIDGET_H diff --git a/vpn/l2tp/plasmanetworkmanagement_l2tpui.desktop b/vpn/l2tp/plasmanetworkmanagement_l2tpui.desktop index 1be9ae6a..82824e5c 100644 --- a/vpn/l2tp/plasmanetworkmanagement_l2tpui.desktop +++ b/vpn/l2tp/plasmanetworkmanagement_l2tpui.desktop @@ -1,86 +1,88 @@ [Desktop Entry] Type=Service Icon= ServiceTypes=PlasmaNetworkManagement/VpnUiPlugin X-KDE-Library=plasmanetworkmanagement_l2tpui X-NetworkManager-Services=org.freedesktop.NetworkManager.l2tp X-KDE-PluginInfo-Author=Jan Grulich X-KDE-PluginInfo-Email=jgrulich@redhat.com X-KDE-PluginInfo-Name=plasmanetworkmanagement_l2tpui X-KDE-PluginInfo-Version=0.1 X-KDE-PluginInfo-Website= X-KDE-PluginInfo-Category=VPNService X-KDE-PluginInfo-Depends= X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=false Name=Layer 2 Tunneling Protocol (L2TP) Name[ca]=Protocol per crear túnels de 2 capes (L2TP) Name[ca@valencia]=Protocol per crear túnels de 2 capes (L2TP) Name[da]=Layer 2 tunneling-protokol (L2TP) Name[de]=Layer-2-Tunnel-Protokoll (L2TP) Name[el]=Πρωτόκολλο διοχέτευσης επιπέδου 2 (L2TP) Name[en_GB]=Layer 2 Tunneling Protocol (L2TP) Name[es]=Protocolo de túneles de capa 2 (L2TP) Name[et]=Layer 2 Tunneling Protocol (L2TP) Name[eu]=2. mailako tunel-protokoloa (L2TP) Name[fi]=Tason 2 tunnelointiyhteyskäytäntö (L2TP) Name[fr]=Protocole tunnel niveau 2 (L2TP) Name[gl]=Protocolo de canalización da segunda capa (L2TP) Name[hu]=Layer 2 Tunneling Protocol (L2TP) +Name[id]=Layer 2 Tunneling Protocol (L2TP) Name[it]=Layer 2 Tunneling Protocol (L2TP) Name[ko]=레이어 2 터널링 프로토콜(L2TP) Name[nl]=Layer 2 Tunneling Protocol (L2TP) Name[nn]=Layer 2 Tunneling Protocol (L2TP) Name[pa]=ਲੇਅਰ 2 ਟਨਲਿੰਗ ਪਰੋਟੋਕਾਲ (L2TP) Name[pl]=Protokół tunelujący warstwy 2. (L2TP) Name[pt]=Protocolo de Túneis Nível 2 (L2TP) Name[pt_BR]=Layer 2 Tunneling Protocol (L2TP) Name[ru]=Протокол туннелирования второго уровня (L2TP) Name[sk]=Layer 2 Tunneling Protocol (L2TP) Name[sl]=Layer 2 Tunneling Protocol (L2TP) Name[sr]=Л2ТП (тунелски протокол слоја 2) Name[sr@ijekavian]=Л2ТП (тунелски протокол слоја 2) Name[sr@ijekavianlatin]=L2TP (tunelski protokol sloja 2) Name[sr@latin]=L2TP (tunelski protokol sloja 2) Name[sv]=Lager-2 tunnelprotokoll (L2TP) Name[tr]=Katman 2 Tünel Protokolü (L2TP) Name[uk]=Протокол тунелювання, шар 2 (L2TP) Name[x-test]=xxLayer 2 Tunneling Protocol (L2TP)xx Name[zh_CN]=第二层隧道协议 (L2TP) Name[zh_TW]=第二層通道協定(L2TP) Comment=Compatible with L2TP VPN servers Comment[ca]=Compatible amb els servidors VPN del L2TP Comment[ca@valencia]=Compatible amb els servidors VPN del L2TP Comment[da]=Kompatibel med L2TP VPN-servere Comment[de]=Mit L2TP-VPN-Servern kompatibel Comment[el]=Συμβατό με διακομιστές L2TP VPN Comment[en_GB]=Compatible with L2TP VPN servers Comment[es]=Compatible con servidores VPN de L2TP Comment[et]=Ühildub L2TP VPN-serveritega Comment[eu]=L2TP VPN zerbitzariekin bateragarria Comment[fi]=Yhteensopiva L2TP-VPN-palvelinten kanssa Comment[fr]=Compatible avec les serveurs VPN L2TP Comment[gl]=Compatíbel con servidores de VPN que usen L2TP. Comment[he]=תאימות עם שרתי L2TP VPN Comment[hu]=Kompatibilis L2TP VPN kiszolgálókkal +Comment[id]=Kompatibel dengan server-server VPN L2TP Comment[it]=Compatibile con i server VPN L2TP Comment[ko]=L2TP VPN 서버와 호환됨 Comment[nl]=Compatibel met L2TP VPN servers Comment[nn]=Kompatibel med L2TP VPN-tenarar Comment[pa]=L2TP VPN ਸਰਵਰਾਂ ਨਾਲ ਅਨੁਕੂਲ Comment[pl]=Zgodny z serwerami VPN L2TP Comment[pt]=Compatível com os servidores de VPN L2TP Comment[pt_BR]=Compatível com servidores VPN L2TP Comment[ru]=Совместимая с серверами VPN на основе L2TP Comment[sk]=Kompatibilné s L2TP VPN servermi Comment[sl]=Združljivo s strežniki VPN, ki uporabljajo L2TP Comment[sr]=Сагласно са Л2ТП ВПН серверима Comment[sr@ijekavian]=Сагласно са Л2ТП ВПН серверима Comment[sr@ijekavianlatin]=Saglasno sa L2TP VPN serverima Comment[sr@latin]=Saglasno sa L2TP VPN serverima Comment[sv]=Kompatibel med L2TP VPN-servrar Comment[tr]=L2TP VPN sunucuları ile uyumlu Comment[uk]=Сумісні з L2TP сервери VPN Comment[x-test]=xxCompatible with L2TP VPN serversxx Comment[zh_CN]=兼容 L2TP VPN 服务器 Comment[zh_TW]=與 L2TP VPN 伺服器相容 diff --git a/vpn/openconnect/CMakeLists.txt b/vpn/openconnect/CMakeLists.txt index fbb57b53..c3f07088 100644 --- a/vpn/openconnect/CMakeLists.txt +++ b/vpn/openconnect/CMakeLists.txt @@ -1,71 +1,71 @@ add_definitions(-DTRANSLATION_DOMAIN=\"plasmanetworkmanagement_openconnectui\") set (MINIMUM_OPENCONNECT_VERSION_REQUIRED "3.99") set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_MODULE_PATH}) find_package(OpenConnect ${MINIMUM_OPENCONNECT_VERSION_REQUIRED} MODULE) if (OPENCONNECT_FOUND) + + find_package(Qt5Xml ${QT_MIN_VERSION} CONFIG REQUIRED) + if (${OPENCONNECT_VERSION} VERSION_LESS "3.99") # macro_optional_find_package(OpenSSL) # macro_log_feature(OpenSSL_FOUND "OpenSSL headers" "Encryption suite" "http://www.openssl.org" FALSE "" "Needed for OpenConnect support in Network Management") find_package(OpenSSL) set_package_properties(OpenSSL PROPERTIES DESCRIPTION "Encryption suite" URL "http://www.openssl.org" TYPE OPTIONAL ) if (OpenSSL_FOUND) set (MINIMUM_OPENCONNECT_VERSION_REQUIRED "3.03") set (maybe_OPENSSL_LIBRARIES ${OpenSSL_LIBRARIES}) endif() endif() if (${OPENCONNECT_VERSION} VERSION_GREATER ${MINIMUM_OPENCONNECT_VERSION_REQUIRED} OR ${OPENCONNECT_VERSION} VERSION_EQUAL ${MINIMUM_OPENCONNECT_VERSION_REQUIRED}) include_directories(${OPENCONNECT_INCLUDE_DIRS}) set(openconnect_SRCS ../../libs/debug.cpp openconnectui.cpp openconnectwidget.cpp openconnectauth.cpp openconnectauthworkerthread.cpp ) ki18n_wrap_ui(openconnect_SRCS openconnectprop.ui openconnectauth.ui) add_library(plasmanetworkmanagement_openconnectui ${openconnect_SRCS}) target_link_libraries(plasmanetworkmanagement_openconnectui plasmanm_internal plasmanm_editor ${NETWORKMANAGERQT5_LDFLAGS} - Qt5::Widgets - Qt5::Network - Qt5::DBus - KF5::Service - KF5::Completion KF5::I18n KF5::WidgetsAddons + KF5::IconThemes KF5::KIOWidgets KF5::CoreAddons + Qt5::Xml ${OPENCONNECT_LIBRARIES} ${maybe_OPENSSL_LIBRARIES} ) - install(TARGETS plasmanetworkmanagement_openconnectui DESTINATION ${PLUGIN_INSTALL_DIR}) - install(FILES plasmanetworkmanagement_openconnectui.desktop DESTINATION ${SERVICES_INSTALL_DIR}) - install(FILES plasmanetworkmanagement_openconnect_juniperui.desktop DESTINATION ${SERVICES_INSTALL_DIR}) + install(TARGETS plasmanetworkmanagement_openconnectui DESTINATION ${KDE_INSTALL_PLUGINDIR}) + install(FILES plasmanetworkmanagement_openconnectui.desktop DESTINATION ${KDE_INSTALL_KSERVICES5DIR}) + install(FILES plasmanetworkmanagement_openconnect_juniperui.desktop DESTINATION ${KDE_INSTALL_KSERVICES5DIR}) else() message("ERROR: OpenConnection version '${OPENCONNECT_VERSION}' does not match minimum required (${MINIMUM_OPENCONNECT_VERSION_REQUIRED})") message("OpenConnect plugin will not be built") set(OPENCONNECT_FOUND False) endif() else (OPENCONNECT_FOUND) message("OpenConnect plugin will not be built") endif (OPENCONNECT_FOUND) #macro_log_feature(OPENCONNECT_FOUND "OpenConnect headers and library" "Cisco AnyConnect compatible VPN client" "http://www.infradead.org/openconnect.html" FALSE ${MINIMUM_OPENCONNECT_VERSION_REQUIRED} "Needed for OpenConnect support in Plasma NM") diff --git a/vpn/openconnect/openconnectauth.cpp b/vpn/openconnect/openconnectauth.cpp index 82c01dcc..5c997b61 100644 --- a/vpn/openconnect/openconnectauth.cpp +++ b/vpn/openconnect/openconnectauth.cpp @@ -1,688 +1,687 @@ /* Copyright 2011 Ilia Kats Copyright 2013 Lukáš Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "openconnectauth.h" #include "openconnectauthworkerthread.h" #include "ui_openconnectauth.h" #include "debug.h" #include "passwordfield.h" #include -#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "nm-openconnect-service.h" #include extern "C" { #include #include #include } // name/address: IP/domain name of the host (OpenConnect accepts both, so no difference here) // group: user group on the server typedef struct { QString name; QString group; QString address; } VPNHost; class OpenconnectAuthWidgetPrivate { public: Ui_OpenconnectAuth ui; NetworkManager::VpnSetting::Ptr setting; struct openconnect_info *vpninfo; NMStringMap secrets; NMStringMap tmpSecrets; QMutex mutex; QWaitCondition workerWaiting; OpenconnectAuthWorkerThread *worker; QList hosts; bool userQuit; bool formGroupChanged; int cancelPipes[2]; QList > serverLog; int passwordFormIndex; enum LogLevels {Error = 0, Info, Debug, Trace}; }; OpenconnectAuthWidget::OpenconnectAuthWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent) : SettingWidget(setting, parent) , d_ptr(new OpenconnectAuthWidgetPrivate) { Q_D(OpenconnectAuthWidget); d->setting = setting; d->ui.setupUi(this); d->userQuit = false; d->formGroupChanged = false; if (pipe2(d->cancelPipes, O_NONBLOCK|O_CLOEXEC)) { // Should never happen. Just don't do real cancellation if it does d->cancelPipes[0] = -1; d->cancelPipes[1] = -1; } - connect(d->ui.cmbLogLevel, static_cast(&QComboBox::currentIndexChanged), this, &OpenconnectAuthWidget::logLevelChanged); + connect(d->ui.cmbLogLevel, QOverload::of(&QComboBox::currentIndexChanged), this, &OpenconnectAuthWidget::logLevelChanged); connect(d->ui.viewServerLog, &QCheckBox::toggled, this, &OpenconnectAuthWidget::viewServerLogToggled); connect(d->ui.btnConnect, &QPushButton::clicked, this, &OpenconnectAuthWidget::connectHost); d->ui.cmbLogLevel->setCurrentIndex(OpenconnectAuthWidgetPrivate::Debug); d->ui.btnConnect->setIcon(QIcon::fromTheme("network-connect")); d->ui.viewServerLog->setChecked(false); d->worker = new OpenconnectAuthWorkerThread(&d->mutex, &d->workerWaiting, &d->userQuit, &d->formGroupChanged, d->cancelPipes[0]); // gets the pointer to struct openconnect_info (defined in openconnect.h), which contains data that OpenConnect needs, // and which needs to be populated with settings we get from NM, like host, certificate or private key d->vpninfo = d->worker->getOpenconnectInfo(); - connect(d->worker, static_cast(&OpenconnectAuthWorkerThread::validatePeerCert), this, &OpenconnectAuthWidget::validatePeerCert); + connect(d->worker, QOverload::of(&OpenconnectAuthWorkerThread::validatePeerCert), this, &OpenconnectAuthWidget::validatePeerCert); connect(d->worker, &OpenconnectAuthWorkerThread::processAuthForm, this, &OpenconnectAuthWidget::processAuthForm); connect(d->worker, &OpenconnectAuthWorkerThread::updateLog, this, &OpenconnectAuthWidget::updateLog); - connect(d->worker, static_cast(&OpenconnectAuthWorkerThread::writeNewConfig), this, &OpenconnectAuthWidget::writeNewConfig); + connect(d->worker, QOverload::of(&OpenconnectAuthWorkerThread::writeNewConfig), this, &OpenconnectAuthWidget::writeNewConfig); connect(d->worker, &OpenconnectAuthWorkerThread::cookieObtained, this, &OpenconnectAuthWidget::workerFinished); readConfig(); readSecrets(); // This might be set by readSecrets() so don't connect it until now - connect(d->ui.cmbHosts, static_cast(&QComboBox::currentIndexChanged), this, &OpenconnectAuthWidget::connectHost); + connect(d->ui.cmbHosts, QOverload::of(&QComboBox::currentIndexChanged), this, &OpenconnectAuthWidget::connectHost); KAcceleratorManager::manage(this); } OpenconnectAuthWidget::~OpenconnectAuthWidget() { Q_D(OpenconnectAuthWidget); d->userQuit = true; if (write(d->cancelPipes[1], "x", 1)) { // not a lot we can do } d->workerWaiting.wakeAll(); d->worker->wait(); ::close(d->cancelPipes[0]); ::close(d->cancelPipes[1]); deleteAllFromLayout(d->ui.loginBoxLayout); delete d->worker; delete d; } void OpenconnectAuthWidget::readConfig() { Q_D(OpenconnectAuthWidget); const NMStringMap dataMap = d->setting->data(); if (!dataMap[NM_OPENCONNECT_KEY_GATEWAY].isEmpty()) { const QString gw = dataMap[NM_OPENCONNECT_KEY_GATEWAY]; VPNHost host; const int index = gw.indexOf(QLatin1Char('/')); if (index > -1) { host.name = host.address = gw.left(index); host.group = gw.right(gw.length() - index - 1); } else { host.name = host.address = gw; } d->hosts.append(host); } if (!dataMap[NM_OPENCONNECT_KEY_CACERT].isEmpty()) { const QByteArray crt = QFile::encodeName(dataMap[NM_OPENCONNECT_KEY_CACERT]); openconnect_set_cafile(d->vpninfo, OC3DUP(crt.data())); } if (dataMap[NM_OPENCONNECT_KEY_CSD_ENABLE] == "yes") { char *wrapper; - wrapper = 0; + wrapper = nullptr; if (!dataMap[NM_OPENCONNECT_KEY_CSD_WRAPPER].isEmpty()) { const QByteArray wrapperScript = QFile::encodeName(dataMap[NM_OPENCONNECT_KEY_CSD_WRAPPER]); wrapper = strdup(wrapperScript.data()); } openconnect_setup_csd(d->vpninfo, getuid(), 1, wrapper); } if (!dataMap[NM_OPENCONNECT_KEY_PROXY].isEmpty()) { const QByteArray proxy = QFile::encodeName(dataMap[NM_OPENCONNECT_KEY_PROXY]); openconnect_set_http_proxy(d->vpninfo, OC3DUP(proxy.data())); } if (!dataMap[NM_OPENCONNECT_KEY_USERCERT].isEmpty()) { const QByteArray crt = QFile::encodeName(dataMap[NM_OPENCONNECT_KEY_USERCERT]); const QByteArray key = QFile::encodeName(dataMap[NM_OPENCONNECT_KEY_PRIVKEY]); openconnect_set_client_cert (d->vpninfo, OC3DUP(crt.data()), OC3DUP(key.data())); if (!crt.isEmpty() && dataMap[NM_OPENCONNECT_KEY_PEM_PASSPHRASE_FSID] == "yes") { openconnect_passphrase_from_fsid(d->vpninfo); } } if (!dataMap[NM_OPENCONNECT_KEY_PROTOCOL].isEmpty()) { const QString protocol = dataMap[NM_OPENCONNECT_KEY_PROTOCOL]; openconnect_set_protocol(d->vpninfo, OC3DUP(protocol == "juniper" ? "nc" : protocol.toUtf8().data())); } } void OpenconnectAuthWidget::readSecrets() { Q_D(OpenconnectAuthWidget); d->secrets = d->setting->secrets(); if (!d->secrets["xmlconfig"].isEmpty()) { const QByteArray config = QByteArray::fromBase64(d->secrets["xmlconfig"].toAscii()); QCryptographicHash hash(QCryptographicHash::Sha1); hash.addData(config.data(), config.size()); const char *sha1_text = hash.result().toHex(); openconnect_set_xmlsha1 (d->vpninfo, (char *)sha1_text, strlen(sha1_text)+1); QDomDocument xmlconfig; xmlconfig.setContent(config); const QDomNode anyConnectProfile = xmlconfig.elementsByTagName(QLatin1String("AnyConnectProfile")).at(0); bool matchedGw = false; const QDomNode serverList = anyConnectProfile.firstChildElement(QLatin1String("ServerList")); for (QDomElement entry = serverList.firstChildElement(QLatin1String("HostEntry")); !entry.isNull(); entry = entry.nextSiblingElement(QLatin1String("HostEntry"))) { VPNHost host; host.name = entry.firstChildElement(QLatin1String("HostName")).text(); host.group = entry.firstChildElement(QLatin1String("UserGroup")).text(); host.address = entry.firstChildElement(QLatin1String("HostAddress")).text(); // We added the originally configured host in readConfig(). But if // it matches one of the ones in the XML config (as presumably it // should), remove the original and use the one with the pretty name. if (!matchedGw && host.address == d->hosts.at(0).address) { d->hosts.removeFirst(); matchedGw = true; } d->hosts.append(host); } } for (int i = 0; i < d->hosts.size(); i++) { d->ui.cmbHosts->addItem(d->hosts.at(i).name, i); if (d->secrets["lasthost"] == d->hosts.at(i).name || d->secrets["lasthost"] == d->hosts.at(i).address) { d->ui.cmbHosts->setCurrentIndex(i); } } if (d->secrets["autoconnect"] == "yes") { d->ui.chkAutoconnect->setChecked(true); QTimer::singleShot(0, this, &OpenconnectAuthWidget::connectHost); } if (d->secrets["save_passwords"] == "yes") { d->ui.chkStorePasswords->setChecked(true); } } void OpenconnectAuthWidget::acceptDialog() { // Find top-level widget as this should be the QDialog itself QWidget *widget = parentWidget(); while (widget->parentWidget() != nullptr) { widget = widget->parentWidget(); } QDialog *dialog = qobject_cast(widget); if (dialog) { dialog->accept(); } } // This starts the worker thread, which connects to the selected AnyConnect host // and retrieves the login form void OpenconnectAuthWidget::connectHost() { Q_D(OpenconnectAuthWidget); d->userQuit = true; if (write(d->cancelPipes[1], "x", 1)) { // not a lot we can do } d->workerWaiting.wakeAll(); d->worker->wait(); d->userQuit = false; /* Suck out the cancel byte(s) */ char buf; while (read(d->cancelPipes[0], &buf, 1) == 1) { ; } deleteAllFromLayout(d->ui.loginBoxLayout); int i = d->ui.cmbHosts->currentIndex(); if (i == -1) { return; } i = d->ui.cmbHosts->itemData(i).toInt(); const VPNHost &host = d->hosts.at(i); if (openconnect_parse_url(d->vpninfo, host.address.toAscii().data())) { qCWarning(PLASMA_NM) << "Failed to parse server URL" << host.address; openconnect_set_hostname(d->vpninfo, OC3DUP(host.address.toAscii().data())); } if (!openconnect_get_urlpath(d->vpninfo) && !host.group.isEmpty()) { openconnect_set_urlpath(d->vpninfo, OC3DUP(host.group.toAscii().data())); } d->secrets["lasthost"] = host.name; addFormInfo(QLatin1String("dialog-information"), i18n("Contacting host, please wait...")); d->worker->start(); } QVariantMap OpenconnectAuthWidget::setting() const { Q_D(const OpenconnectAuthWidget); NMStringMap secrets; QVariantMap secretData; secrets.unite(d->secrets); QString host(openconnect_get_hostname(d->vpninfo)); const QString port = QString::number(openconnect_get_port(d->vpninfo)); secrets.insert(QLatin1String(NM_OPENCONNECT_KEY_GATEWAY), host + ':' + port); secrets.insert(QLatin1String(NM_OPENCONNECT_KEY_COOKIE), QLatin1String(openconnect_get_cookie(d->vpninfo))); openconnect_clear_cookie(d->vpninfo); #if OPENCONNECT_CHECK_VER(5,0) const char *fingerprint = openconnect_get_peer_cert_hash(d->vpninfo); #else OPENCONNECT_X509 *cert = openconnect_get_peer_cert(d->vpninfo); char fingerprint[41]; openconnect_get_cert_sha1(d->vpninfo, cert, fingerprint); #endif secrets.insert(QLatin1String(NM_OPENCONNECT_KEY_GWCERT), QLatin1String(fingerprint)); secrets.insert(QLatin1String("autoconnect"), d->ui.chkAutoconnect->isChecked() ? "yes" : "no"); secrets.insert(QLatin1String("save_passwords"), d->ui.chkStorePasswords->isChecked() ? "yes" : "no"); NMStringMap::iterator i = secrets.begin(); while (i != secrets.end()) { if (i.value().isEmpty()) { i = secrets.erase(i); } else { i++; } } secretData.insert("secrets", QVariant::fromValue(secrets)); // These secrets are not officially part of the secrets which would be returned back to NetworkManager. We just // need to somehow get them to our secret agent which will handle them separately and store them. if (!d->tmpSecrets.isEmpty()) { secretData.insert("tmp-secrets", QVariant::fromValue(d->tmpSecrets)); } return secretData; } void OpenconnectAuthWidget::writeNewConfig(const QString & buf) { Q_D(OpenconnectAuthWidget); d->secrets["xmlconfig"] = buf; } void OpenconnectAuthWidget::updateLog(const QString &message, const int &level) { Q_D(OpenconnectAuthWidget); QPair pair; pair.first = message; if (pair.first.endsWith(QLatin1String("\n"))) { pair.first.chop(1); } switch (level) { case PRG_ERR: pair.second = OpenconnectAuthWidgetPrivate::Error; break; case PRG_INFO: pair.second = OpenconnectAuthWidgetPrivate::Info; break; case PRG_DEBUG: pair.second = OpenconnectAuthWidgetPrivate::Debug; break; case PRG_TRACE: pair.second = OpenconnectAuthWidgetPrivate::Trace; break; } if (pair.second <= d->ui.cmbLogLevel->currentIndex()) { d->ui.serverLog->append(pair.first); } d->serverLog.append(pair); if (d->serverLog.size() > 100) { d->serverLog.removeFirst(); } } void OpenconnectAuthWidget::logLevelChanged(int newLevel) { Q_D(OpenconnectAuthWidget); d->ui.serverLog->clear(); QList >::const_iterator i; for (i = d->serverLog.constBegin(); i != d->serverLog.constEnd(); ++i) { QPair pair = *i; if(pair.second <= newLevel) { d->ui.serverLog->append(pair.first); } } } void OpenconnectAuthWidget::addFormInfo(const QString &iconName, const QString &message) { Q_D(OpenconnectAuthWidget); QHBoxLayout *layout = new QHBoxLayout(); QLabel *icon = new QLabel(this); QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(icon->sizePolicy().hasHeightForWidth()); icon->setSizePolicy(sizePolicy); icon->setMinimumSize(QSize(16, 16)); icon->setMaximumSize(QSize(16, 16)); layout->addWidget(icon); QLabel *text = new QLabel(this); text->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter); text->setWordWrap(true); layout->addWidget(text); icon->setPixmap(QIcon::fromTheme(iconName).pixmap(KIconLoader::SizeSmall)); text->setText(message); d->ui.loginBoxLayout->addLayout(layout); } void OpenconnectAuthWidget::processAuthForm(struct oc_auth_form *form) { Q_D(OpenconnectAuthWidget); deleteAllFromLayout(d->ui.loginBoxLayout); if (form->banner) { addFormInfo(QLatin1String("dialog-information"), form->banner); } if (form->message) { addFormInfo(QLatin1String("dialog-information"), form->message); } if (form->error) { addFormInfo(QLatin1String("dialog-error"), form->error); } struct oc_form_opt *opt; QFormLayout *layout = new QFormLayout(); QSizePolicy policy(QSizePolicy::Expanding, QSizePolicy::Fixed); bool focusSet = false; for (opt = form->opts; opt; opt = opt->next) { if (opt->type == OC_FORM_OPT_HIDDEN || IGNORE_OPT(opt)) { continue; } QLabel *text = new QLabel(this); text->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter); text->setText(QString(opt->label)); - QWidget *widget = 0; + QWidget *widget = nullptr; const QString key = QString("form:%1:%2").arg(QLatin1String(form->auth_id)).arg(QLatin1String(opt->name)); const QString value = d->secrets.value(key); if (opt->type == OC_FORM_OPT_PASSWORD || opt->type == OC_FORM_OPT_TEXT) { PasswordField *le = new PasswordField(this); le->setText(value); if (opt->type == OC_FORM_OPT_PASSWORD) { le->setPasswordModeEnabled(true); } if (!focusSet && le->text().isEmpty()) { le->setFocus(Qt::OtherFocusReason); focusSet = true; } widget = qobject_cast(le); } else if (opt->type == OC_FORM_OPT_SELECT) { QComboBox *cmb = new QComboBox(this); struct oc_form_opt_select *sopt = reinterpret_cast(opt); for (int i = 0; i < sopt->nr_choices; i++) { cmb->addItem(QString::fromUtf8(FORMCHOICE(sopt, i)->label), QString::fromUtf8(FORMCHOICE(sopt, i)->name)); if (value == QString::fromUtf8(FORMCHOICE(sopt, i)->name)) { cmb->setCurrentIndex(i); if (sopt == AUTHGROUP_OPT(form) && i != AUTHGROUP_SELECTION(form)) { QTimer::singleShot(0, this, &OpenconnectAuthWidget::formGroupChanged); } } } if (sopt == AUTHGROUP_OPT(form)) { - connect(cmb, static_cast(&QComboBox::currentIndexChanged), this, &OpenconnectAuthWidget::formGroupChanged); + connect(cmb, QOverload::of(&QComboBox::currentIndexChanged), this, &OpenconnectAuthWidget::formGroupChanged); } widget = qobject_cast(cmb); } if (widget) { widget->setProperty("openconnect_opt", (quintptr)opt); widget->setSizePolicy(policy); layout->addRow(text, widget); } } d->ui.loginBoxLayout->addLayout(layout); d->passwordFormIndex = d->ui.loginBoxLayout->count() - 1; QDialogButtonBox *box = new QDialogButtonBox(this); QPushButton *btn = box->addButton(QDialogButtonBox::Ok); btn->setText(i18n("Login")); btn->setDefault(true); d->ui.loginBoxLayout->addWidget(box); box->setProperty("openconnect_form", (quintptr)form); connect(box, &QDialogButtonBox::accepted, this, &OpenconnectAuthWidget::formLoginClicked); } void OpenconnectAuthWidget::validatePeerCert(const QString &fingerprint, const QString &peerCert, const QString &reason, bool *accepted) { Q_D(OpenconnectAuthWidget); const QString host = QLatin1String(openconnect_get_hostname(d->vpninfo)); const QString port = QString::number(openconnect_get_port(d->vpninfo)); const QString key = QString("certificate:%1:%2").arg(host, port); const QString value = d->secrets.value(key); #if !OPENCONNECT_CHECK_VER(5,0) #define openconnect_check_peer_cert_hash(v,d) strcmp(d, fingerprint.toUtf8().data()) #endif if (openconnect_check_peer_cert_hash(d->vpninfo, value.toUtf8().data())) { QWidget *widget = new QWidget(); QVBoxLayout *verticalLayout; QHBoxLayout *horizontalLayout; QLabel *icon; QLabel *infoText; QTextBrowser *certificate; verticalLayout = new QVBoxLayout(widget); horizontalLayout = new QHBoxLayout(widget); icon = new QLabel(widget); QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(icon->sizePolicy().hasHeightForWidth()); icon->setSizePolicy(sizePolicy); icon->setMinimumSize(QSize(48, 48)); icon->setMaximumSize(QSize(48, 48)); horizontalLayout->addWidget(icon); infoText = new QLabel(widget); infoText->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter); horizontalLayout->addWidget(infoText); verticalLayout->addLayout(horizontalLayout); certificate = new QTextBrowser(widget); certificate->setTextInteractionFlags(Qt::TextSelectableByMouse); certificate->setOpenLinks(false); verticalLayout->addWidget(certificate); icon->setPixmap(QIcon::fromTheme("dialog-information").pixmap(KIconLoader::SizeLarge)); infoText->setText(i18n("Check failed for certificate from VPN server \"%1\".\n" "Reason: %2\nAccept it anyway?", openconnect_get_hostname(d->vpninfo),reason)); infoText->setWordWrap(true); certificate->setText(peerCert); QPointer dialog = new QDialog(this); dialog.data()->setWindowModality(Qt::WindowModal); dialog->setLayout(new QVBoxLayout); QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel, dialog); connect(buttons, &QDialogButtonBox::accepted, dialog.data(), &QDialog::accept); connect(buttons, &QDialogButtonBox::rejected, dialog.data(), &QDialog::reject); dialog->layout()->addWidget(widget); dialog->layout()->addWidget(buttons); if(dialog.data()->exec() == QDialog::Accepted) { *accepted = true; } else { *accepted = false; } if (dialog) { dialog.data()->deleteLater(); } widget->deleteLater(); } else { *accepted = true; } if (*accepted) { d->secrets.insert(key, QString(fingerprint)); } d->mutex.lock(); d->workerWaiting.wakeAll(); d->mutex.unlock(); } void OpenconnectAuthWidget::formGroupChanged() { Q_D(OpenconnectAuthWidget); d->formGroupChanged = true; formLoginClicked(); } // Writes the user input from the form into the oc_auth_form structs we got from // libopenconnect, and wakes the worker thread up to try to log in and obtain a // cookie with this data void OpenconnectAuthWidget::formLoginClicked() { Q_D(OpenconnectAuthWidget); const int lastIndex = d->ui.loginBoxLayout->count() - 1; QLayout *layout = d->ui.loginBoxLayout->itemAt(d->passwordFormIndex)->layout(); struct oc_auth_form *form = (struct oc_auth_form *) d->ui.loginBoxLayout->itemAt(lastIndex)->widget()->property("openconnect_form").value(); for (int i = 0; i < layout->count(); i++) { QLayoutItem *item = layout->itemAt(i); QWidget *widget = item->widget(); if (widget && widget->property("openconnect_opt").isValid()) { struct oc_form_opt *opt = (struct oc_form_opt *) widget->property("openconnect_opt").value(); const QString key = QString("form:%1:%2").arg(QLatin1String(form->auth_id)).arg(QLatin1String(opt->name)); if (opt->type == OC_FORM_OPT_PASSWORD || opt->type == OC_FORM_OPT_TEXT) { PasswordField *le = qobject_cast(widget); QByteArray text = le->text().toUtf8(); openconnect_set_option_value(opt, text.data()); if (opt->type == OC_FORM_OPT_TEXT) { d->secrets.insert(key, le->text()); } else { d->tmpSecrets.insert(key, le->text()); } } else if (opt->type == OC_FORM_OPT_SELECT) { QComboBox *cbo = qobject_cast(widget); QByteArray text = cbo->itemData(cbo->currentIndex()).toString().toAscii(); openconnect_set_option_value(opt, text.data()); d->secrets.insert(key,cbo->itemData(cbo->currentIndex()).toString()); } } } deleteAllFromLayout(d->ui.loginBoxLayout); d->workerWaiting.wakeAll(); } void OpenconnectAuthWidget::workerFinished(const int &ret) { Q_D(OpenconnectAuthWidget); if (ret < 0) { QString message; QList >::const_iterator i; for (i = d->serverLog.constEnd()-1; i >= d->serverLog.constBegin(); --i) { QPair pair = *i; if(pair.second <= OpenconnectAuthWidgetPrivate::Error) { message = pair.first; break; } } if (message.isEmpty()) { message = i18n("Connection attempt was unsuccessful."); } deleteAllFromLayout(d->ui.loginBoxLayout); addFormInfo(QLatin1String("dialog-error"), message); } else { deleteAllFromLayout(d->ui.loginBoxLayout); acceptDialog(); } } void OpenconnectAuthWidget::deleteAllFromLayout(QLayout *layout) { while (QLayoutItem *item = layout->takeAt(0)) { if (QLayout *itemLayout = item->layout()) { deleteAllFromLayout(itemLayout); itemLayout->deleteLater(); } else { item->widget()->deleteLater(); } delete item; } layout->invalidate(); } void OpenconnectAuthWidget::viewServerLogToggled(bool toggled) { Q_D(OpenconnectAuthWidget); d->ui.lblLogLevel->setVisible(toggled); d->ui.cmbLogLevel->setVisible(toggled); if (toggled) { delete d->ui.verticalLayout->takeAt(5); QSizePolicy policy = d->ui.serverLogBox->sizePolicy(); policy.setVerticalPolicy(QSizePolicy::Expanding); d->ui.serverLogBox->setSizePolicy(policy); d->ui.serverLog->setVisible(true); } else { QSpacerItem *verticalSpacer = new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding); d->ui.verticalLayout->addItem(verticalSpacer); d->ui.serverLog->setVisible(false); QSizePolicy policy = d->ui.serverLogBox->sizePolicy(); policy.setVerticalPolicy(QSizePolicy::Fixed); d->ui.serverLogBox->setSizePolicy(policy); } } diff --git a/vpn/openconnect/openconnectauth.h b/vpn/openconnect/openconnectauth.h index 1a8a5746..e5f5cfd8 100644 --- a/vpn/openconnect/openconnectauth.h +++ b/vpn/openconnect/openconnectauth.h @@ -1,67 +1,67 @@ /* Copyright 2011 Ilia Kats Copyright 2013 Lukáš Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef OPENCONNECTAUTH_H #define OPENCONNECTAUTH_H #include "settingwidget.h" #include #include class QLayout; struct openconnect_info; struct oc_auth_form; class OpenconnectAuthWidgetPrivate; class OpenconnectAuthWidget : public SettingWidget { Q_OBJECT Q_DECLARE_PRIVATE(OpenconnectAuthWidget) public: - explicit OpenconnectAuthWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0); - ~OpenconnectAuthWidget(); + explicit OpenconnectAuthWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr); + ~OpenconnectAuthWidget() override; virtual void readSecrets(); void readConfig(); - virtual QVariantMap setting() const; + QVariantMap setting() const override; private: OpenconnectAuthWidgetPrivate * const d_ptr; void acceptDialog(); void addFormInfo(const QString &, const QString &); void deleteAllFromLayout(QLayout *); private Q_SLOTS: void writeNewConfig(const QString &); void validatePeerCert(const QString &, const QString &, const QString &, bool*); void processAuthForm(struct oc_auth_form *); void updateLog(const QString &, const int &); void logLevelChanged(int); void formLoginClicked(); void formGroupChanged(); void workerFinished(const int&); void viewServerLogToggled(bool); void connectHost(); }; #endif // OPENCONNECTAUTH_H diff --git a/vpn/openconnect/openconnectauthworkerthread.cpp b/vpn/openconnect/openconnectauthworkerthread.cpp index b720a87e..41041623 100644 --- a/vpn/openconnect/openconnectauthworkerthread.cpp +++ b/vpn/openconnect/openconnectauthworkerthread.cpp @@ -1,234 +1,234 @@ /* Copyright 2011 Ilia Kats This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "openconnectauthworkerthread.h" #include #include #include #include #include extern "C" { #include #include #if !OPENCONNECT_CHECK_VER(1,5) #include #include #include #endif #include } #include class OpenconnectAuthStaticWrapper { public: #if OPENCONNECT_CHECK_VER(5,0) static int writeNewConfig(void *obj, const char *str, int num) { if (obj) return static_cast(obj)->writeNewConfig(str, num); return -1; } static int validatePeerCert(void *obj, const char *str) { if (obj) - return static_cast(obj)->validatePeerCert(NULL, str); + return static_cast(obj)->validatePeerCert(nullptr, str); return -1; } #else static int writeNewConfig(void *obj, char *str, int num) { if (obj) return static_cast(obj)->writeNewConfig(str, num); return -1; } static int validatePeerCert(void *obj, OPENCONNECT_X509 *cert, const char *str) { if (obj) return static_cast(obj)->validatePeerCert(cert, str); return -1; } #endif static int processAuthForm(void *obj, struct oc_auth_form *form) { if (obj) return static_cast(obj)->processAuthFormP(form); return OC_FORM_RESULT_ERR; } static void writeProgress(void *obj, int level, const char *str, ...) { if (obj) { va_list argPtr; va_start(argPtr, str); static_cast(obj)->writeProgress(level, str, argPtr); va_end(argPtr); } } }; OpenconnectAuthWorkerThread::OpenconnectAuthWorkerThread(QMutex *mutex, QWaitCondition *waitForUserInput, bool *userDecidedToQuit, bool *formGroupChanged, int cancelFd) : QThread() , m_mutex(mutex) , m_waitForUserInput(waitForUserInput) , m_userDecidedToQuit(userDecidedToQuit) , m_formGroupChanged(formGroupChanged) { m_openconnectInfo = openconnect_vpninfo_new((char*)"OpenConnect VPN Agent (PlasmaNM - running on KDE)", OpenconnectAuthStaticWrapper::validatePeerCert, OpenconnectAuthStaticWrapper::writeNewConfig, OpenconnectAuthStaticWrapper::processAuthForm, OpenconnectAuthStaticWrapper::writeProgress, this); #if OPENCONNECT_CHECK_VER(1,4) openconnect_set_cancel_fd(m_openconnectInfo, cancelFd); #else // Silence warning about unused parameter Q_UNUSED(cancelFd); #endif } OpenconnectAuthWorkerThread::~OpenconnectAuthWorkerThread() { openconnect_vpninfo_free(m_openconnectInfo); } void OpenconnectAuthWorkerThread::run() { openconnect_init_ssl(); int ret = openconnect_obtain_cookie(m_openconnectInfo); if (*m_userDecidedToQuit) { return; } Q_EMIT cookieObtained(ret); } struct openconnect_info* OpenconnectAuthWorkerThread::getOpenconnectInfo() { return m_openconnectInfo; } int OpenconnectAuthWorkerThread::writeNewConfig(const char *buf, int buflen) { Q_UNUSED(buflen) if (*m_userDecidedToQuit) { return -EINVAL; } Q_EMIT writeNewConfig(QString(QByteArray(buf).toBase64())); return 0; } #if !OPENCONNECT_CHECK_VER(1,5) static char *openconnect_get_cert_details(struct openconnect_info *vpninfo, OPENCONNECT_X509 *cert) { Q_UNUSED(vpninfo) BIO *bp = BIO_new(BIO_s_mem()); BUF_MEM *certinfo; char zero = 0; char *ret; X509_print_ex(bp, cert, 0, 0); BIO_write(bp, &zero, 1); BIO_get_mem_ptr(bp, &certinfo); ret = strdup(certinfo->data); BIO_free(bp); return ret; } #endif int OpenconnectAuthWorkerThread::validatePeerCert(void *cert, const char *reason) { if (*m_userDecidedToQuit) { return -EINVAL; } #if OPENCONNECT_CHECK_VER(5,0) (void)cert; const char *fingerprint = openconnect_get_peer_cert_hash(m_openconnectInfo); char *details = openconnect_get_peer_cert_details(m_openconnectInfo); #else char fingerprint[41]; int ret = 0; ret = openconnect_get_cert_sha1(m_openconnectInfo, cert, fingerprint); if (ret) { return ret; } char *details = openconnect_get_cert_details(m_openconnectInfo, cert); #endif bool accepted = false; m_mutex->lock(); QString qFingerprint(fingerprint); QString qCertinfo(details); QString qReason(reason); Q_EMIT validatePeerCert(qFingerprint, qCertinfo, qReason, &accepted); m_waitForUserInput->wait(m_mutex); m_mutex->unlock(); openconnect_free_cert_info(m_openconnectInfo, details); if (*m_userDecidedToQuit) { return -EINVAL; } if (accepted) { return 0; } else { return -EINVAL; } } int OpenconnectAuthWorkerThread::processAuthFormP(struct oc_auth_form *form) { if (*m_userDecidedToQuit) { return -1; } m_mutex->lock(); *m_formGroupChanged = false; Q_EMIT processAuthForm(form); m_waitForUserInput->wait(m_mutex); m_mutex->unlock(); if (*m_userDecidedToQuit) { return OC_FORM_RESULT_CANCELLED; } if (*m_formGroupChanged) { return OC_FORM_RESULT_NEWGROUP; } return OC_FORM_RESULT_OK; } void OpenconnectAuthWorkerThread::writeProgress(int level, const char *fmt, va_list argPtr) { if (*m_userDecidedToQuit) { return; } QString msg; msg.vsprintf(fmt, argPtr); Q_EMIT updateLog(msg, level); } diff --git a/vpn/openconnect/openconnectauthworkerthread.h b/vpn/openconnect/openconnectauthworkerthread.h index 455b685c..1f539512 100644 --- a/vpn/openconnect/openconnectauthworkerthread.h +++ b/vpn/openconnect/openconnectauthworkerthread.h @@ -1,111 +1,111 @@ /* Copyright 2011 Ilia Kats This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef OPENCONNECTAUTHWORKERTHREAD_H #define OPENCONNECTAUTHWORKERTHREAD_H extern "C" { #include } #if OPENCONNECT_API_VERSION_MAJOR == 1 #define openconnect_vpninfo_new openconnect_vpninfo_new_with_cbdata #define openconnect_init_ssl openconnect_init_openssl #endif #ifndef OPENCONNECT_CHECK_VER #define OPENCONNECT_CHECK_VER(x,y) 0 #endif #if !OPENCONNECT_CHECK_VER(1,5) struct x509_st; #define OPENCONNECT_X509 struct x509_st #define OPENCONNECT_OPENSSL #endif #if OPENCONNECT_CHECK_VER(3,0) #define NEWGROUP_SUPPORTED 1 #define AUTHGROUP_OPT(form) (void *)(form)->authgroup_opt #define AUTHGROUP_SELECTION(form) (form)->authgroup_selection #define FORMCHOICE(sopt, i) ((sopt)->choices[i]) #define IGNORE_OPT(opt) ((opt)->flags & OC_FORM_OPT_IGNORE) #else #define NEWGROUP_SUPPORTED 0 -#define AUTHGROUP_OPT(form) NULL +#define AUTHGROUP_OPT(form) nullptr #define AUTHGROUP_SELECTION(form) 0 #define FORMCHOICE(sopt, i) (&(sopt)->choices[i]) #define IGNORE_OPT(opt) 0 #define OC_FORM_RESULT_ERR -1 #define OC_FORM_RESULT_OK 0 #define OC_FORM_RESULT_CANCELLED 1 #define OC_FORM_RESULT_NEWGROUP 2 #endif #if OPENCONNECT_CHECK_VER(4,0) #define OC3DUP(x) (x) #else #define openconnect_set_option_value(opt, val) do { \ struct oc_form_opt *_o = (opt); \ free(_o->value); _o->value = strdup(val); \ } while (0) #define openconnect_free_cert_info(v, x) ::free(x) #define OC3DUP(x) strdup(x) #endif #include class QMutex; class QWaitCondition; struct openconnect_info; class OpenconnectAuthWorkerThread : public QThread { Q_OBJECT friend class OpenconnectAuthStaticWrapper; public: OpenconnectAuthWorkerThread(QMutex *, QWaitCondition *, bool *, bool *, int); - ~OpenconnectAuthWorkerThread(); + ~OpenconnectAuthWorkerThread() override; struct openconnect_info* getOpenconnectInfo(); Q_SIGNALS: void validatePeerCert(const QString &, const QString &, const QString &, bool*); void processAuthForm(struct oc_auth_form *); void updateLog(const QString &, const int&); void writeNewConfig(const QString &); void cookieObtained(const int&); protected: - void run(); + void run() override; private: int writeNewConfig(const char *, int); int validatePeerCert(void *, const char *); int processAuthFormP(struct oc_auth_form *); void writeProgress(int level, const char *, va_list); QMutex *m_mutex; QWaitCondition *m_waitForUserInput; bool *m_userDecidedToQuit; bool *m_formGroupChanged; struct openconnect_info *m_openconnectInfo; }; #endif diff --git a/vpn/openconnect/openconnectui.h b/vpn/openconnect/openconnectui.h index 85f7aa10..e42d1d9b 100644 --- a/vpn/openconnect/openconnectui.h +++ b/vpn/openconnect/openconnectui.h @@ -1,46 +1,46 @@ /* Copyright 2011 Ilia Kats Copyright 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef OPENCONNECT_UI_H #define OPENCONNECT_UI_H #include "vpnuiplugin.h" #include #include class Q_DECL_EXPORT OpenconnectUiPlugin : public VpnUiPlugin { Q_OBJECT public: - explicit OpenconnectUiPlugin(QObject * parent = 0, const QVariantList& = QVariantList()); - virtual ~OpenconnectUiPlugin(); - virtual SettingWidget * widget(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = 0); - virtual SettingWidget * askUser(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = 0); - - virtual QString suggestedFileName(const NetworkManager::ConnectionSettings::Ptr &connection) const; - virtual QString supportedFileExtensions() const; - virtual QMessageBox::StandardButtons suggestedAuthDialogButtons() const; - virtual NMVariantMapMap importConnectionSettings(const QString &fileName); - virtual bool exportConnectionSettings(const NetworkManager::ConnectionSettings::Ptr &connection, const QString &fileName); + explicit OpenconnectUiPlugin(QObject * parent = nullptr, const QVariantList& = QVariantList()); + ~OpenconnectUiPlugin() override; + SettingWidget * widget(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = nullptr) override; + SettingWidget * askUser(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = nullptr) override; + + QString suggestedFileName(const NetworkManager::ConnectionSettings::Ptr &connection) const override; + QString supportedFileExtensions() const override; + QMessageBox::StandardButtons suggestedAuthDialogButtons() const override; + NMVariantMapMap importConnectionSettings(const QString &fileName) override; + bool exportConnectionSettings(const NetworkManager::ConnectionSettings::Ptr &connection, const QString &fileName) override; }; #endif // OPENCONNECT_UI_H diff --git a/vpn/openconnect/openconnectwidget.h b/vpn/openconnect/openconnectwidget.h index 4e3af72c..f5e06fe2 100644 --- a/vpn/openconnect/openconnectwidget.h +++ b/vpn/openconnect/openconnectwidget.h @@ -1,46 +1,46 @@ /* Copyright 2011 Ilia Kats Copyright 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef OPENCONNECTWIDGET_H #define OPENCONNECTWIDGET_H #include "settingwidget.h" #include class OpenconnectSettingWidgetPrivate; class OpenconnectSettingWidget : public SettingWidget { Q_OBJECT Q_DECLARE_PRIVATE(OpenconnectSettingWidget) public: - explicit OpenconnectSettingWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0); - ~OpenconnectSettingWidget(); - virtual void loadConfig(const NetworkManager::Setting::Ptr &setting); - virtual QVariantMap setting() const; - virtual bool isValid() const; + explicit OpenconnectSettingWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr); + ~OpenconnectSettingWidget() override; + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; + QVariantMap setting() const override; + bool isValid() const override; private: OpenconnectSettingWidgetPrivate *const d_ptr; }; #endif // OPENCONNECTWIDGET_H diff --git a/vpn/openconnect/plasmanetworkmanagement_openconnect_juniperui.desktop b/vpn/openconnect/plasmanetworkmanagement_openconnect_juniperui.desktop index 168a0c20..634cab60 100644 --- a/vpn/openconnect/plasmanetworkmanagement_openconnect_juniperui.desktop +++ b/vpn/openconnect/plasmanetworkmanagement_openconnect_juniperui.desktop @@ -1,84 +1,86 @@ [Desktop Entry] Type=Service Icon= ServiceTypes=PlasmaNetworkManagement/VpnUiPlugin X-KDE-Library=plasmanetworkmanagement_openconnectui X-NetworkManager-Services=org.freedesktop.NetworkManager.openconnect X-NetworkManager-Services-Subtype=nc X-KDE-PluginInfo-Author=Jan Grulich X-KDE-PluginInfo-Email=jgrulich@redhat.com X-KDE-PluginInfo-Name=plasmanetworkmanagement_openconnectui X-KDE-PluginInfo-Version=0.1 X-KDE-PluginInfo-Website= X-KDE-PluginInfo-Category=VPNService X-KDE-PluginInfo-Depends= X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=false Name=Juniper SSL VPN / Pulse Connect Secure (openconnect) Name[ca]=VPN SSL Juniper / Pulse Connect Secure (openconnect) Name[ca@valencia]=VPN SSL Juniper / Pulse Connect Secure (openconnect) Name[da]=Juniper SSL VPN / Pulse Connect Secure (openconnect) Name[de]=Juniper SSL VPN / Pulse Connect Secure (openconnect) Name[el]=Juniper SSL VPN / Pulse Connect Secure (openconnect) Name[en_GB]=Juniper SSL VPN / Pulse Connect Secure (openconnect) Name[es]=Juniper SSL VPN / Pulse Connect Secure (openconnect) Name[eu]=Juniper SSL VPN / Pulse Connect Secure (openconnect) Name[fi]=Juniper SSL VPN / Pulse Connect Secure (openconnect) Name[fr]=VPN SSL Juniper / Pulse Connect Secure (openconnect) Name[gl]=VPN SSL de Juniper / Pulse Connect Secure (openconnect) Name[hu]=Juniper SSL VPN / Pulse Connect Secure (openconnect) +Name[id]=Juniper SSL VPN / Pulse Connect Secure (openconnect) Name[it]=Juniper SSL VPN / Pulse Connect Secure (openconnect) Name[ko]=Juniper SSL VPN / Pulse Connect Secure(openconnect) Name[nl]=Juniper SSL VPN / Pulse Connect Secure (openconnect) Name[nn]=Juniper SSL VPN / Pulse Connect Secure (openconnect) Name[pa]=ਜੂਨੀਪਰ SSL VPN / ਪਲਸ ਕਨੈਕਸ਼ਨ ਸਕਿਉਰ (openconnect) Name[pl]=Juniper SSL VPN / Pulse Connect Secure (openconnect) Name[pt]=Juniper SSL VPN / Pulse Connect Secure (openconnect) Name[pt_BR]=Juniper SSL VPN / Pulse Connect Secure (openconnect) Name[ru]=Juniper SSL VPN или Pulse Connect Secure (openconnect) Name[sk]=Juniper SSL VPN / Pulse Connect Secure (openconnect) Name[sl]=Juniper SSL VPN / Pulse Connect Secure (openconnect) Name[sr]=Џуниперов ССЛ ВПН / пулс конект сикјур (Опенконект) Name[sr@ijekavian]=Џуниперов ССЛ ВПН / пулс конект сикјур (Опенконект) Name[sr@ijekavianlatin]=Juniperov SSL VPN / Pulse Connect Secure (OpenConnect) Name[sr@latin]=Juniperov SSL VPN / Pulse Connect Secure (OpenConnect) Name[sv]=Juniper SSL VPN eller Pulse Connect Secure (openconnect) Name[tr]=Juniper SSL VPN / Pulse Connect Secure (openconnect) Name[uk]=Juniper SSL VPN / Pulse Connect Secure (openconnect) Name[x-test]=xxJuniper SSL VPN / Pulse Connect Secure (openconnect)xx Name[zh_CN]=Juniper SSL VPN / Pulse Connect Secure (openconnect) Name[zh_TW]=Juniper SSL VPN / Pulse Connect Secure (openconnect) Comment=Compatible with Juniper SSL VPN and Pulse Connect Secure Comment[ca]=Compatible amb la VPN SSL Juniper i Pulse Connect Secure Comment[ca@valencia]=Compatible amb la VPN SSL Juniper i Pulse Connect Secure Comment[da]=Kompatibel med Juniper SSL VPN og Pulse Connect Secure Comment[de]=Kompatibel mit Juniper SSL VPN und Pulse Connect Secure Comment[el]=Συμβατό με Juniper SSL VPN και Pulse Connect Secure Comment[en_GB]=Compatible with Juniper SSL VPN and Pulse Connect Secure Comment[es]=Compatible con Juniper SSL VPN y Pulse Connect Secure Comment[eu]=Juniper SSL VPN eta Pulse Connect Secure-kin bateragarria Comment[fi]=Yhteensopiva Juniper SSL VPN:n ja Pulse Connect Securen kanssa Comment[fr]=Compatible avec les VPN SSL Juniper et Pulse Connect Secure Comment[gl]=Compatíbel coas VPN SSL de Juniper e con Pulse Connect Secure. Comment[hu]=Kompatibilis Juniper SSL VPN-nel és Pulse Connect Secure-ral +Comment[id]=Kompatibel dengan Juniper SSL VPN dan Pulse Connect Secure Comment[it]=Compatibile con Juniper SSL VPN e Pulse Connect Secure Comment[ko]=Juniper SSL VPN 및 Pulse Connect Secure와 호환됨 Comment[nl]=Compatibel met Juniper SSL VPN en Pulse Connect Secure Comment[nn]=Kompatibel med Juniper SSL VPN og Pulse Connect Secure Comment[pa]=ਜੂਨੀਪਰ SSL VPN ਅਤੇ ਪਲਸ ਕਨੈਕਟ ਸਕਿਉਰ ਨਾਲ ਅਨੁਕੂਲ Comment[pl]=Zgodny z Juniper SSL VPN oraz Pulse Connect Secure Comment[pt]=Compatível com o Juniper SSL VPN and Pulse Connect Secure Comment[pt_BR]=Compatível com Juniper SSL VPN e Pulse Connect Secure Comment[ru]=Совместимая с Juniper SSL VPN и Pulse Connect Secure Comment[sk]=Kompatibilné s Juniper SSL VPN a Pulse Connect Secure Comment[sl]=Združljivo z Juniper SSL VPN in Pulse Connect Secure Comment[sr]=Сагласно са Џуниперовим ССЛ ВПН‑ом и пулс конект сикјуром Comment[sr@ijekavian]=Сагласно са Џуниперовим ССЛ ВПН‑ом и пулс конект сикјуром Comment[sr@ijekavianlatin]=Saglasno sa Juniperovim SSL VPN‑om i Pulse Connect Secureom Comment[sr@latin]=Saglasno sa Juniperovim SSL VPN‑om i Pulse Connect Secureom Comment[sv]=Kompatibel med Juniper SSL VPN och Pulse Connect Secure Comment[tr]=Juniper SSL VPN ve Pulse Connect Secure ile uyumlu Comment[uk]=Сумісні з Juniper SSL VPN і Pulse Connect Secure Comment[x-test]=xxCompatible with Juniper SSL VPN and Pulse Connect Securexx Comment[zh_CN]=与 Juniper SSL VPN 和 Pulse Connect Secure 兼容 Comment[zh_TW]=與 Juniper SSL VPN 和 Pulse Connect Secure 相容 diff --git a/vpn/openconnect/plasmanetworkmanagement_openconnectui.desktop b/vpn/openconnect/plasmanetworkmanagement_openconnectui.desktop index 54e21f26..2ec1ffc1 100644 --- a/vpn/openconnect/plasmanetworkmanagement_openconnectui.desktop +++ b/vpn/openconnect/plasmanetworkmanagement_openconnectui.desktop @@ -1,87 +1,89 @@ [Desktop Entry] Type=Service Icon= ServiceTypes=PlasmaNetworkManagement/VpnUiPlugin X-KDE-Library=plasmanetworkmanagement_openconnectui X-NetworkManager-Services=org.freedesktop.NetworkManager.openconnect X-NetworkManager-Services-Subtype=anyconnect X-KDE-PluginInfo-Author=Lukáš Tinkl X-KDE-PluginInfo-Email=ltinkl@redhat.com X-KDE-PluginInfo-Name=plasmanetworkmanagement_openconnectui X-KDE-PluginInfo-Version=0.1 X-KDE-PluginInfo-Website= X-KDE-PluginInfo-Category=VPNService X-KDE-PluginInfo-Depends= X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=false Name=Cisco AnyConnect Compatible VPN (openconnect) Name[ca]=VPN compatible amb AnyConnect de Cisco (openconnect) Name[ca@valencia]=VPN compatible amb AnyConnect de Cisco (openconnect) Name[da]=Cisco AnyConnect-kompatibelt VPN (openconnect) Name[de]=VPN kompatibel mit Cisco AnyConnect (openconnect) Name[el]=Συμβατό με Cisco AnyConnect VPN (openconnect) Name[en_GB]=Cisco AnyConnect Compatible VPN (openconnect) Name[es]=VPN compatible con Cisco AnyConnect (openconnect) Name[et]=Cisco AnyConnectiga ühilduv VPN (openconnect) Name[eu]=Cisco AnyConnect-kin bateragarria den VPN (openconnect) Name[fi]=Cisco AnyConnect -yhteensopiva VPN (openconnect) Name[fr]=VPN compatible Cisco AnyConnect (openconnect) Name[gl]=VPN compatíbel con Cisco AnyConnect (openconnect) Name[hu]=Cisco AnyConnect kompatibilis VPN (openconnect) +Name[id]=Cisco AnyConnect Compatible VPN (openconnect) Name[it]=VPN compatibile Cisco AnyConnect (openconnect) Name[ko]=Cisco AnyConnect 호환 VPN(openconnect) Name[nl]=Cisco AnyConnect Compatibele VPN (openconnect) Name[nn]=Cisco AnyConnect-kompatibel VPN (openconnect) Name[pa]=Cisco AnyConnect ਅਨੁਕੂਲ VPN (openconnect) Name[pl]=Zgodny VPN Cisco AnyConnect (openconnect) Name[pt]=VPN Compatível com o AnyConnect da Cisco (openconnect) Name[pt_BR]=VPN compatível com o Cisco AnyConnect (openconnect) Name[ru]=Совместимая с Cisco AnyConnect VPN (openconnect) Name[sk]=Cisco AnyConnect kompatibilná VPN (openconnect) Name[sl]=S Cisco AnyConnect združljiv VPN (openconnect) Name[sr]=ВПН сагласан са Сисковим ениконектом (Опенконект) Name[sr@ijekavian]=ВПН сагласан са Сисковим ениконектом (Опенконект) Name[sr@ijekavianlatin]=VPN saglasan sa Ciscovim AnyConnectom (OpenConnect) Name[sr@latin]=VPN saglasan sa Ciscovim AnyConnectom (OpenConnect) Name[sv]=Cisco AnyConnect-kompatibel VPN (openconnect) Name[tr]=Cisco AnyConnect Uyumlu VPN (openconnect) Name[uk]=VPN. сумісний з Cisco AnyConnect (openconnect) Name[x-test]=xxCisco AnyConnect Compatible VPN (openconnect)xx Name[zh_CN]=Cisco AnyConnect 兼容 VPN (openconnect) Name[zh_TW]=與 Cisco AnyConnect 相容的 VPN (openconnect) Comment=Compatible with Cisco AnyConnect SSL VPN Comment[ca]=VPN sobre SSL compatible amb AnyConnect de Cisco Comment[ca@valencia]=VPN sobre SSL compatible amb AnyConnect de Cisco Comment[da]=Kompatibel med Cisco AnyConnect SSL VPN Comment[de]=Mit Cisco-AnyConnect-SSL-VPN kompatibel Comment[el]=Συμβατό με Cisco AnyConnect SSL VPN Comment[en_GB]=Compatible with Cisco AnyConnect SSL VPN Comment[es]=VPN compatible con Cisco AnyConnect SSL Comment[et]=Ühildub Cisco AnyConnect SSL VPN-iga Comment[eu]=Cisco AnyConnect SSL VPN-rekin bateragarria Comment[fi]=Yhteensopiva Cisco Anyconnect -SSL-VPN:n kanssa Comment[fr]=Compatible avec les VPN SSL Cisco AnyConnect Comment[gl]=Compatíbel con servidores VPN de Cisco AnyConnect que usen SSL. Comment[he]=תאימות עם Cisco AnyConnect SSL VPN Comment[hu]=Kompatibilis Cisco AnyConnect SSL VPN-nel +Comment[id]=Kompatibel dengan VPN SSL Cisco AnyConnect Comment[it]=Compatibile con Cisco AnyConnect SSL VPN Comment[ko]=Cisco AnyConnect SSL VPN과 호환됨 Comment[nl]=Compatibel met Cisco AnyConnect SSL VPN Comment[nn]=Komaptibel med Cisco AnyConnect SSL VPN Comment[pa]=Cisco AnyConnect SSL VPN ਲਈ ਢੁਕਵਾਂ Comment[pl]=Zgodny z VPN Cisco AnyConnect SSL Comment[pt]=Compatível com a VPN AnyConnect da Cisco por SSL Comment[pt_BR]=Compatível com a VPN Cisco AnyConnect por SSL Comment[ru]=Совместимая с Cisco AnyConnect VPN с SSL Comment[sk]=Kompatibilné s Cisco AnyConnect SSL VPN Comment[sl]=S Cisco AnyConnect SSL združljiv VPN Comment[sr]=Сагласно са Сисковим ениконект ССЛ ВПН‑ом Comment[sr@ijekavian]=Сагласно са Сисковим ениконект ССЛ ВПН‑ом Comment[sr@ijekavianlatin]=Saglasno sa Ciscovim AnyConnect SSL VPN‑om Comment[sr@latin]=Saglasno sa Ciscovim AnyConnect SSL VPN‑om Comment[sv]=Kompatibel med Cisco AnyConnect SSL VPN Comment[tr]=Cisco AnyConnect SSL VPN ile uyumlu Comment[uk]=VPN, сумісний з Cisco AnyConnect SSL Comment[x-test]=xxCompatible with Cisco AnyConnect SSL VPNxx Comment[zh_CN]=兼容 Cisco AnyConnect SSL VPN Comment[zh_TW]=與 Cisco AnyConnect SSL VPN 相容 diff --git a/vpn/openswan/CMakeLists.txt b/vpn/openswan/CMakeLists.txt index 646941d6..ab0b9f53 100644 --- a/vpn/openswan/CMakeLists.txt +++ b/vpn/openswan/CMakeLists.txt @@ -1,32 +1,25 @@ add_definitions(-DTRANSLATION_DOMAIN=\"plasmanetworkmanagement_openswanui\") set(openswan_SRCS openswan.cpp openswanwidget.cpp openswanauth.cpp ) ki18n_wrap_ui(openswan_SRCS openswan.ui openswanauth.ui) add_library(plasmanetworkmanagement_openswanui ${openswan_SRCS}) kcoreaddons_desktop_to_json(plasmanetworkmanagement_openswanui plasmanetworkmanagement_openswanui.desktop) target_link_libraries(plasmanetworkmanagement_openswanui plasmanm_internal plasmanm_editor - Qt5::Widgets - Qt5::Network - Qt5::DBus - KF5::NetworkManagerQt - KF5::Service - KF5::Completion KF5::I18n KF5::WidgetsAddons - KF5::KIOWidgets KF5::CoreAddons ) -install(TARGETS plasmanetworkmanagement_openswanui DESTINATION ${PLUGIN_INSTALL_DIR}) +install(TARGETS plasmanetworkmanagement_openswanui DESTINATION ${KDE_INSTALL_PLUGINDIR}) -install(FILES plasmanetworkmanagement_openswanui.desktop DESTINATION ${SERVICES_INSTALL_DIR}) +install(FILES plasmanetworkmanagement_openswanui.desktop DESTINATION ${KDE_INSTALL_KSERVICES5DIR}) diff --git a/vpn/openswan/openswan.h b/vpn/openswan/openswan.h index eb2c8aa3..440e2d1e 100644 --- a/vpn/openswan/openswan.h +++ b/vpn/openswan/openswan.h @@ -1,43 +1,43 @@ /* Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_OPENSWAN_H #define PLASMA_NM_OPENSWAN_H #include "vpnuiplugin.h" #include class Q_DECL_EXPORT OpenswanUiPlugin : public VpnUiPlugin { Q_OBJECT public: - explicit OpenswanUiPlugin(QObject * parent = 0, const QVariantList& = QVariantList()); - virtual ~OpenswanUiPlugin(); - virtual SettingWidget * widget(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = 0); - virtual SettingWidget * askUser(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = 0); - - QString suggestedFileName(const NetworkManager::ConnectionSettings::Ptr &connection) const; - QString supportedFileExtensions() const; - NMVariantMapMap importConnectionSettings(const QString &fileName); - bool exportConnectionSettings(const NetworkManager::ConnectionSettings::Ptr &connection, const QString &fileName); + explicit OpenswanUiPlugin(QObject * parent = nullptr, const QVariantList& = QVariantList()); + ~OpenswanUiPlugin() override; + SettingWidget * widget(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = nullptr) override; + SettingWidget * askUser(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = nullptr) override; + + QString suggestedFileName(const NetworkManager::ConnectionSettings::Ptr &connection) const override; + QString supportedFileExtensions() const override; + NMVariantMapMap importConnectionSettings(const QString &fileName) override; + bool exportConnectionSettings(const NetworkManager::ConnectionSettings::Ptr &connection, const QString &fileName) override; }; #endif // PLASMA_NM_OPENSWAN_H diff --git a/vpn/openswan/openswanauth.h b/vpn/openswan/openswanauth.h index d8efdfb0..2e0f1183 100644 --- a/vpn/openswan/openswanauth.h +++ b/vpn/openswan/openswanauth.h @@ -1,44 +1,44 @@ /* Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_OPENSWAN_AUTH_H #define PLASMA_NM_OPENSWAN_AUTH_H #include #include "settingwidget.h" class OpenswanAuthDialogPrivate; class OpenswanAuthDialog : public SettingWidget { Q_OBJECT Q_DECLARE_PRIVATE(OpenswanAuthDialog) public: - explicit OpenswanAuthDialog(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0); - ~OpenswanAuthDialog(); + explicit OpenswanAuthDialog(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr); + ~OpenswanAuthDialog() override; virtual void readSecrets(); - virtual QVariantMap setting() const; + QVariantMap setting() const override; private: OpenswanAuthDialogPrivate *const d_ptr; }; #endif // PLASMA_NM_OPENSWAN_AUTH_H diff --git a/vpn/openswan/openswanwidget.h b/vpn/openswan/openswanwidget.h index 3abcb996..c6c50c09 100644 --- a/vpn/openswan/openswanwidget.h +++ b/vpn/openswan/openswanwidget.h @@ -1,52 +1,52 @@ /* Copyright 2013 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_OPENSWAN_WIDGET_H #define PLASMA_NM_OPENSWAN_WIDGET_H #include #include "settingwidget.h" namespace Ui { class OpenswanWidget; } class OpenswanWidget : public SettingWidget { Q_OBJECT public: - explicit OpenswanWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0, Qt::WindowFlags f = 0); - virtual ~OpenswanWidget(); + explicit OpenswanWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr, Qt::WindowFlags f = {}); + ~OpenswanWidget() override; - void loadConfig(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; - void loadSecrets(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; + void loadSecrets(const NetworkManager::Setting::Ptr &setting) override; - QVariantMap setting() const; + QVariantMap setting() const override; - virtual bool isValid() const; + bool isValid() const override; private: Ui::OpenswanWidget *m_ui; NetworkManager::VpnSetting::Ptr m_setting; }; #endif // PLASMA_NM_OPENSWAN_WIDGET_H diff --git a/vpn/openswan/plasmanetworkmanagement_openswanui.desktop b/vpn/openswan/plasmanetworkmanagement_openswanui.desktop index 984a6230..8ee83de0 100644 --- a/vpn/openswan/plasmanetworkmanagement_openswanui.desktop +++ b/vpn/openswan/plasmanetworkmanagement_openswanui.desktop @@ -1,86 +1,88 @@ [Desktop Entry] Type=Service Icon= ServiceTypes=PlasmaNetworkManagement/VpnUiPlugin X-KDE-Library=plasmanetworkmanagement_openswanui X-NetworkManager-Services=org.freedesktop.NetworkManager.openswan X-KDE-PluginInfo-Author=Jan Grulich X-KDE-PluginInfo-Email=jgrulich@redhat.com X-KDE-PluginInfo-Name=plasmanetworkmanagement_openswanui X-KDE-PluginInfo-Version=0.1 X-KDE-PluginInfo-Website= X-KDE-PluginInfo-Category=VPNService X-KDE-PluginInfo-Depends= X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=false Name=IPsec based VPN (openswan) Name[ca]=VPN basada en IPsec (openswan) Name[ca@valencia]=VPN basada en IPsec (openswan) Name[da]=IPsec-baseret VPN (openswan) Name[de]=VPN basierend auf IPsec (openswan) Name[el]=VPN βασισμένο σε IPsec (openswan) Name[en_GB]=IPsec based VPN (openswan) Name[es]=VPN basada en IPsec (openswan) Name[et]=IPseci põhine VPN (openswan) Name[eu]=IPsec oinarridun VPN (openswan) Name[fi]=IPsec-pohjainen VPN (openswan) Name[fr]=VPN utilisant IPsec (openswan) Name[gl]=VPN baseada en IPsec (openswan) Name[hu]=IPsec-alapú VPN (openswan) +Name[id]=IPsec based VPN (openswan) Name[it]=VPN basata su IPsec (openswan) Name[ko]=IPSec 기반 VPN(openswan) Name[lt]=VPN (openswan), IPsec pagrindu Name[nl]=Op IPsec gebaseerde VPN (openswan) Name[nn]=IPsec-basert VPN (openswan) Name[pa]=IPsec ਅਧਾਰਿਤ VPN (openswan) Name[pl]=VPN oparty na IPsec (openswan) Name[pt]=VPN baseada em IPsec (openswan) Name[pt_BR]=VPN baseada em IPsec (openswan) Name[ru]=VPN на основе IPsec (openswan) Name[sk]=IPsec založené VPN (openswan) Name[sl]=Na IPsec temelječ VPN (openswan) Name[sr]=ВПН на основу ИПсека (Опенсвон) Name[sr@ijekavian]=ВПН на основу ИПсека (Опенсвон) Name[sr@ijekavianlatin]=VPN na osnovu IPseca (Openswan) Name[sr@latin]=VPN na osnovu IPseca (Openswan) Name[sv]=IPsec-baserad VPN (openswan) Name[tr]=IPsec tabanlı VPN (openswan) Name[uk]=VPN на основі IPsec (openswan) Name[x-test]=xxIPsec based VPN (openswan)xx Name[zh_CN]=基于 IPsec 的 VPN (openswan) Name[zh_TW]=以 IPsec 為底的 VPN (openswan) Comment=IPsec, IKEv1, IKEv2 based VPN Comment[ca]=VPN basada en IKEv1, IKEv2 sobre IPsec Comment[ca@valencia]=VPN basada en IKEv1, IKEv2 sobre IPsec Comment[da]=IPsec, IKEv1, IKEv2 baseret VPN Comment[de]=VPN basierend auf IPsec, IKEv1, IKEv2 Comment[el]=VPN βασισμένο σε IPsec, IKEv1, IKEv2 Comment[en_GB]=IPsec, IKEv1, IKEv2 based VPN Comment[es]=VPN basada en IPsec, IKEv1 e IKEv2 Comment[et]=IPsec, IKEv1, IKEv2 põhine VPN Comment[eu]=IPsec, IKEv1, IKEv2 oinarridun VPN Comment[fi]=IPsec-, IKEv1-, IKEv2-pohjainen VPN Comment[fr]=VPN utilisant IPsec, IKEv1, IKEv2 Comment[gl]=VPN baseada en IPsec, IKEv1 e IKEv2. Comment[hu]=IPsec-, IKEv1-, IKEv2-alapú VPN +Comment[id]=IPsec, IKEv1, IKEv2 berbasiskan VPN Comment[it]=VPN basata su IPsec, IKEv1, IKEv2 Comment[ko]=IPSec, IKEv1, IKEv2 기반 VPN Comment[nl]=Op IPsec, IKEv1, IKEv2 gebaseerde VPN Comment[nn]=IPsec-/IKEv1-/IKEv2-basert VPN Comment[pa]=IPsec, IKEv1, IKEv2 ਅਧਾਰਿਤ VPN Comment[pl]=VPN oparty na IPsec, IKEv1, IKEv2 Comment[pt]=VPN baseada em IPsec, IKEv1, IKEv2 Comment[pt_BR]=VPN baseada em IPsec, IKEv1, IKEv2 Comment[ru]=VPN на основе IPsec, IKEv1, IKEv2 Comment[sk]=IPsec, IKEv1, IKEv2 založené VPN Comment[sl]=Na IPsec, IKEv1, IKEv2 temelječ VPN Comment[sr]=ВПН на основу ИПсека, ИКЕ‑а в1, ИКЕ в2 Comment[sr@ijekavian]=ВПН на основу ИПсека, ИКЕ‑а в1, ИКЕ в2 Comment[sr@ijekavianlatin]=VPN na osnovu IPseca, IKE‑a v1, IKE v2 Comment[sr@latin]=VPN na osnovu IPseca, IKE‑a v1, IKE v2 Comment[sv]=IPsec, IKEv1, IKEv2-baserad VPN Comment[tr]=IPsec, IKEv1, IKEv2 tabanlı VPN Comment[uk]=VPN на основі IPsec, IKEv1, IKEv2 Comment[x-test]=xxIPsec, IKEv1, IKEv2 based VPNxx Comment[zh_CN]=基于 IPsec,IKEv1,IKEv2 的 VPN Comment[zh_TW]=以 IPsec, IKEv1, IKEv2 為基底的 VPN diff --git a/vpn/openvpn/CMakeLists.txt b/vpn/openvpn/CMakeLists.txt index b26e828c..f3cd1d70 100644 --- a/vpn/openvpn/CMakeLists.txt +++ b/vpn/openvpn/CMakeLists.txt @@ -1,30 +1,30 @@ add_definitions(-DTRANSLATION_DOMAIN=\"plasmanetworkmanagement_openvpnui\") # Needed to build this module remove_definitions(-DQT_USE_FAST_OPERATOR_PLUS) set(openvpn_SRCS openvpn.cpp openvpnwidget.cpp openvpnauth.cpp openvpnadvancedwidget.cpp ) ki18n_wrap_ui(openvpn_SRCS openvpn.ui openvpnadvanced.ui) add_library(plasmanetworkmanagement_openvpnui ${openvpn_SRCS}) kcoreaddons_desktop_to_json(plasmanetworkmanagement_openvpnui plasmanetworkmanagement_openvpnui.desktop) target_link_libraries(plasmanetworkmanagement_openvpnui plasmanm_internal plasmanm_editor - Qt5::DBus - KF5::NetworkManagerQt - KF5::KIOCore KF5::KIOWidgets + KF5::I18n + KF5::WidgetsAddons + KF5::CoreAddons ) -install(TARGETS plasmanetworkmanagement_openvpnui DESTINATION ${PLUGIN_INSTALL_DIR}) +install(TARGETS plasmanetworkmanagement_openvpnui DESTINATION ${KDE_INSTALL_PLUGINDIR}) -install(FILES plasmanetworkmanagement_openvpnui.desktop DESTINATION ${SERVICES_INSTALL_DIR}) +install(FILES plasmanetworkmanagement_openvpnui.desktop DESTINATION ${KDE_INSTALL_KSERVICES5DIR}) diff --git a/vpn/openvpn/openvpn.cpp b/vpn/openvpn/openvpn.cpp index f1edc020..f15d8a97 100644 --- a/vpn/openvpn/openvpn.cpp +++ b/vpn/openvpn/openvpn.cpp @@ -1,868 +1,884 @@ /* Copyright 2008 Will Stephenson Copyright 2011-2012 Rajeesh K Nambiar Copyright 2011 Ilia Kats Copyright 2012-2016 Lamarque V. Souza 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include "openvpn.h" +#include #include +#include + #include #include #include -#include #include #include #include #include "openvpnwidget.h" #include "openvpnauth.h" #include #include "nm-openvpn-service.h" K_PLUGIN_FACTORY_WITH_JSON(OpenVpnUiPluginFactory, "plasmanetworkmanagement_openvpnui.json", registerPlugin();) #define AUTH_TAG "auth" #define AUTH_USER_PASS_TAG "auth-user-pass" #define CA_TAG "ca" #define CERT_TAG "cert" #define CIPHER_TAG "cipher" #define CLIENT_TAG "client" #define COMP_TAG "comp-lzo" #define DEV_TAG "dev" #define FRAGMENT_TAG "fragment" #define IFCONFIG_TAG "ifconfig" #define KEY_TAG "key" #define MSSFIX_TAG "mssfix" #define PKCS12_TAG "pkcs12" #define PORT_TAG "port" #define PROTO_TAG "proto" #define HTTP_PROXY_TAG "http-proxy" #define HTTP_PROXY_RETRY_TAG "http-proxy-retry" #define SOCKS_PROXY_TAG "socks-proxy" #define SOCKS_PROXY_RETRY_TAG "socks-proxy-retry" #define REMOTE_TAG "remote" #define RENEG_SEC_TAG "reneg-sec" #define RPORT_TAG "rport" #define SECRET_TAG "secret" #define TLS_AUTH_TAG "tls-auth" #define TLS_CLIENT_TAG "tls-client" #define TLS_REMOTE_TAG "tls-remote" #define TUNMTU_TAG "tun-mtu" #define KEY_DIRECTION_TAG "key-direction" #define BEGIN_KEY_CA_TAG "" #define END_KEY_CA_TAG "" #define BEGIN_KEY_CERT_TAG "" #define END_KEY_CERT_TAG "" #define BEGIN_KEY_KEY_TAG "" #define END_KEY_KEY_TAG "" #define BEGIN_KEY_SECRET_TAG "" #define END_KEY_SECRET_TAG "" #define BEGIN_TLS_AUTH_TAG "" #define END_TLS_AUTH_TAG "" #define PROC_TYPE_TAG "Proc-Type: 4,ENCRYPTED" #define PKCS8_TAG "-----BEGIN ENCRYPTED PRIVATE KEY-----" +QString localCertPath() +{ + return QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + + QLatin1String("/networkmanagement/certificates/"); +} + QString unQuote(QString &certVal, const QString &fileName) { /* Unquote according to openvpn rules * Unquoted filename is returned, and @certVal is modified * to the leftover string */ int nextSep; QString certFile = certVal.trimmed(); if (certFile.startsWith('"') || certFile.startsWith('\'')) { // Quoted certFile.remove(0,1); // Remove the starting quote nextSep = 0; while ((nextSep = certFile.indexOf(QRegExp("\"|'"), nextSep)) != -1) { if (nextSep > 0 && certFile.at(nextSep - 1) != '\\') { // Quote not escaped certVal = certFile.right(certFile.length() - nextSep - 1); // Leftover string certFile.truncate(nextSep); // Quoted string break; } } } else { nextSep = certFile.indexOf(QRegExp("\\s")); // First whitespace if (nextSep != -1) { certVal = certFile.right(certFile.length() - nextSep - 1); // Leftover certFile = certFile.left(nextSep); // value } else { certVal.clear(); } } certFile.replace("\\\\", "\\"); // Replace '\\' with '\' certFile.replace("\\ ", " "); // Replace escaped space with space if (QFileInfo(certFile).isRelative()) { certFile = QFileInfo(fileName).dir().absolutePath() + '/' + certFile; } return certFile; } bool isEncrypted(const QString &fileName) { bool encrypted = false; // TODO: if is_pkcs12(fileName) return true; // NOTE: will have to use SEC_PKCS12DecoderStart and friends from , which will // build a new dependency on nss-devel. See NetworkManager/libnm-util/crypto_nss.c+453 QFile inFile(fileName); if (!inFile.open(QFile::ReadOnly)) { return false; } QTextStream in(&inFile); while (!in.atEnd()) { QString line = in.readLine(); if (!line.isEmpty() && (line.startsWith(PROC_TYPE_TAG) || line.startsWith(PKCS8_TAG))) { encrypted = true; break; } } inFile.close(); return encrypted; } OpenVpnUiPlugin::OpenVpnUiPlugin(QObject * parent, const QVariantList &) : VpnUiPlugin(parent) { } OpenVpnUiPlugin::~OpenVpnUiPlugin() { } SettingWidget * OpenVpnUiPlugin::widget(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent) { OpenVpnSettingWidget * wid = new OpenVpnSettingWidget(setting, parent); return wid; } SettingWidget * OpenVpnUiPlugin::askUser(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent) { return new OpenVpnAuthWidget(setting, parent); } QString OpenVpnUiPlugin::suggestedFileName(const NetworkManager::ConnectionSettings::Ptr &connection) const { return connection->id() + "_openvpn.conf"; } QString OpenVpnUiPlugin::supportedFileExtensions() const { return "*.ovpn *.conf"; } NMVariantMapMap OpenVpnUiPlugin::importConnectionSettings(const QString &fileName) { NMVariantMapMap result; QFile impFile(fileName); if (!impFile.open(QFile::ReadOnly|QFile::Text)) { mError = VpnUiPlugin::Error; mErrorMessage = i18n("Could not open file"); return result; } bool copyCertificates; KMessageBox::ButtonCode buttonCode; if (KMessageBox::shouldBeShownYesNo(QLatin1String("copyCertificatesDialog"), buttonCode)) { - copyCertificates = KMessageBox::questionYesNo(0, i18n("Do you want to copy your certificates to %1?", KStandardDirs::locateLocal("data", "networkmanagement/certificates/")), + copyCertificates = KMessageBox::questionYesNo(nullptr, i18n("Do you want to copy your certificates to %1?", localCertPath()), i18n("Copy certificates"), KStandardGuiItem::yes(), KStandardGuiItem::no(), QLatin1String("copyCertificatesDialog")) == KMessageBox::Yes; } else { copyCertificates = buttonCode == KMessageBox::Yes; } const QString connectionName = QFileInfo(fileName).completeBaseName(); NMStringMap dataMap; NMStringMap secretData; QVariantMap ipv4Data; QString proxy_type; QString proxy_user; QString proxy_passwd; bool have_client = false; bool have_remote = false; bool proxy_set = false; bool have_pass = false; bool have_sk = false; int key_direction = -1; QTextStream in(&impFile); while (!in.atEnd()) { QStringList key_value; QString line = in.readLine(); // Skip comments if (line.indexOf('#') >= 0) { line.truncate(line.indexOf('#')); } if (line.indexOf(';') >= 0) { line.truncate(line.indexOf(';')); } if (line.isEmpty()) { continue; } key_value.clear(); key_value << line.split(QRegExp("\\s+")); // Split at one or more whitespaces if (key_value[0] == CLIENT_TAG || key_value[0] == TLS_CLIENT_TAG) { have_client = true; continue; } if (key_value[0] == DEV_TAG) { if (key_value.count() == 2) { if (key_value[1].startsWith(QLatin1String("tun"))) { // ignore; default is tun } else if (key_value[1].startsWith(QLatin1String("tap"))) { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_TAP_DEV), "yes"); } else { - KMessageBox::information(0, i18n("Unknown option: %1", line)); + KMessageBox::information(nullptr, i18n("Unknown option: %1", line)); } } else { - KMessageBox::information(0, i18n("Invalid number of arguments (expected 1) in option: %1", line)); + KMessageBox::information(nullptr, i18n("Invalid number of arguments (expected 1) in option: %1", line)); } continue; } if (key_value[0] == PROTO_TAG) { if (key_value.count() == 2) { /* Valid parameters are "udp", "tcp-client" and "tcp-server". * 'tcp' isn't technically valid, but it used to be accepted so * we'll handle it here anyway. */ if (key_value[1] == "udp") { // ignore; default is udp } else if (key_value[1] == "tcp-client" || key_value[1] == "tcp-server" || key_value[1] == "tcp") { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_PROTO_TCP), "yes"); } else { - KMessageBox::information(0, i18n("Unknown option: %1", line)); + KMessageBox::information(nullptr, i18n("Unknown option: %1", line)); } } else { - KMessageBox::information(0, i18n("Invalid number of arguments (expected 1) in option: %1", line)); + KMessageBox::information(nullptr, i18n("Invalid number of arguments (expected 1) in option: %1", line)); } continue; } if (key_value[0] == MSSFIX_TAG) { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_MSSFIX), "yes"); continue; } if (key_value[0] == TUNMTU_TAG) { if (key_value.count() == 2) { if (key_value[1].toLong() >= 0 && key_value[1].toLong() < 0xFFFF ) { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_TUNNEL_MTU), key_value[1]); } else { - KMessageBox::information(0, i18n("Invalid size (should be between 0 and 0xFFFF) in option: %1", line)); + KMessageBox::information(nullptr, i18n("Invalid size (should be between 0 and 0xFFFF) in option: %1", line)); } } else { - KMessageBox::information(0, i18n("Invalid number of arguments (expected 1) in option: %1", line)); + KMessageBox::information(nullptr, i18n("Invalid number of arguments (expected 1) in option: %1", line)); } continue; } if (key_value[0] == FRAGMENT_TAG) { if (key_value.count() == 2) { if (key_value[1].toLong() >= 0 && key_value[1].toLong() < 0xFFFF ) { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_FRAGMENT_SIZE), key_value[1]); } else { - KMessageBox::information(0, i18n("Invalid size (should be between 0 and 0xFFFF) in option: %1", line)); + KMessageBox::information(nullptr, i18n("Invalid size (should be between 0 and 0xFFFF) in option: %1", line)); } } else { - KMessageBox::information(0, i18n("Invalid number of arguments (expected 1) in option: %1", line)); + KMessageBox::information(nullptr, i18n("Invalid number of arguments (expected 1) in option: %1", line)); } continue; } if (key_value[0] == COMP_TAG) { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_COMP_LZO), "yes"); continue; } if (key_value[0] == RENEG_SEC_TAG) { if (key_value.count() == 2) { if (key_value[1].toLong() >= 0 && key_value[1].toLong() <= 604800 ) { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_RENEG_SECONDS), key_value[1]); } else { - KMessageBox::information(0, i18n("Invalid size (should be between 0 and 604800) in option: %1", line)); + KMessageBox::information(nullptr, i18n("Invalid size (should be between 0 and 604800) in option: %1", line)); } } else { - KMessageBox::information(0, i18n("Invalid number of arguments (expected 1) in option: %1", line)); + KMessageBox::information(nullptr, i18n("Invalid number of arguments (expected 1) in option: %1", line)); } continue; } if (key_value[0] == HTTP_PROXY_RETRY_TAG || key_value[0] == SOCKS_PROXY_RETRY_TAG) { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_PROXY_RETRY), "yes"); continue; } if (key_value[0] == HTTP_PROXY_TAG) { proxy_type = "http"; } if (key_value[0] == SOCKS_PROXY_TAG) { proxy_type = "socks"; } if (!proxy_type.isEmpty() && !proxy_set && key_value.count() >= 3) { bool success = true; if (proxy_type == "http" && key_value.count() >= 4) { // Parse the HTTP proxy file QFile httpProxyFile(QFileInfo(fileName).dir().absolutePath() + '/' + key_value[3]); if (httpProxyFile.open(QFile::ReadOnly|QFile::Text)) { QTextStream httpProxyIn(&httpProxyFile); while (!httpProxyIn.atEnd()) { QString httpProxyLine = httpProxyIn.readLine(); if (httpProxyLine.isEmpty()) { continue; } if (proxy_user.isEmpty()) { proxy_user = httpProxyLine; } if (proxy_passwd.isEmpty()) { proxy_passwd = httpProxyLine; break; } } if (proxy_user.isEmpty()||proxy_passwd.isEmpty()) { success = false; } } } if (success && !proxy_type.isEmpty() && key_value[2].toLong() > 0 // Port && key_value[2].toLong() < 65536) { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_PROXY_TYPE), proxy_type); dataMap.insert(QLatin1String(NM_OPENVPN_KEY_PROXY_SERVER), key_value[1]); // Proxy server dataMap.insert(QLatin1String(NM_OPENVPN_KEY_PROXY_PORT), key_value[2]); // Port if (!proxy_user.isEmpty()) { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_HTTP_PROXY_USERNAME), proxy_user); } if (!proxy_passwd.isEmpty()) { secretData.insert(QLatin1String(NM_OPENVPN_KEY_HTTP_PROXY_PASSWORD), proxy_passwd); dataMap.insert(QLatin1String(NM_OPENVPN_KEY_HTTP_PROXY_PASSWORD"-flags"), QString::number(NetworkManager::Setting::NotSaved)); } proxy_set = true; } if (!success) { - KMessageBox::information(0, i18n("Invalid proxy option: %1", line)); + KMessageBox::information(nullptr, i18n("Invalid proxy option: %1", line)); } continue; } if (key_value[0] == REMOTE_TAG) { if (key_value.count() >= 2 && key_value.count() <= 4) { - dataMap.insert(QLatin1String(NM_OPENVPN_KEY_REMOTE), key_value[1]); + QString remote = key_value[1]; + if (remote.startsWith(QLatin1Char('\'')) || remote.startsWith(QLatin1Char('"'))) { + remote.remove(0, 1); // Remove first quote + remote.remove(remote.size() - 1, 1); // Remove last quote + } + dataMap.insert(QLatin1String(NM_OPENVPN_KEY_REMOTE), remote); have_remote = true; if (key_value.count() >= 3 && key_value[2].toLong() > 0 && key_value[2].toLong() < 65536) { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_PORT), key_value[2]); if (key_value.count() == 4) { - // TODO + QString protocol = key_value[3]; + if(protocol.startsWith(QLatin1String("tcp"))) { + dataMap[QLatin1String(NM_OPENVPN_KEY_PROTO_TCP)] = QLatin1String("yes"); + } } } } } if (key_value[0] == PORT_TAG || key_value[0] == RPORT_TAG) { // Port specified in 'remote' always takes precedence if (!dataMap.contains(NM_OPENVPN_KEY_PORT)) { if (key_value.count() == 2 ) { if (key_value[1].toLong() > 0 && key_value[1].toLong() < 65536) { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_PORT), key_value[1]); } else { - KMessageBox::information(0, i18n("Invalid port (should be between 1 and 65535) in option: %1", line)); + KMessageBox::information(nullptr, i18n("Invalid port (should be between 1 and 65535) in option: %1", line)); } } else - KMessageBox::information(0, i18n("Invalid number of arguments (expected 1) in option: %1", line)); + KMessageBox::information(nullptr, i18n("Invalid number of arguments (expected 1) in option: %1", line)); } continue; } if (key_value[0] == PKCS12_TAG && key_value.count() > 1) { key_value[1] = line.right(line.length() - line.indexOf(QRegExp("\\s"))); // Get whole string after key QString certFile = unQuote(key_value[1], fileName); dataMap.insert(QLatin1String(NM_OPENVPN_KEY_CA), certFile); dataMap.insert(QLatin1String(NM_OPENVPN_KEY_CERT), certFile); dataMap.insert(QLatin1String(NM_OPENVPN_KEY_KEY), certFile); continue; } if (key_value[0] == CA_TAG && key_value.count() > 1) { key_value[1] = line.right(line.length() - line.indexOf(QRegExp("\\s"))); // Get whole string after key if (key_value[1].trimmed() == QLatin1String("[inline]")) { // No data or file to copy for now, it will be available later when we reach tag. continue; } if (copyCertificates) { const QString absoluteFilePath = tryToCopyToCertificatesDirectory(connectionName, unQuote(key_value[1], fileName)); dataMap.insert(QLatin1String(NM_OPENVPN_KEY_CA), absoluteFilePath); } else { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_CA), unQuote(key_value[1], fileName)); } continue; } if (key_value[0] == CERT_TAG && key_value.count() > 1) { key_value[1] = line.right(line.length() - line.indexOf(QRegExp("\\s"))); // Get whole string after key if (key_value[1].trimmed() == QLatin1String("[inline]")) { // No data or file to copy for now, it will be available later when we reach tag. continue; } if (copyCertificates) { const QString absoluteFilePath = tryToCopyToCertificatesDirectory(connectionName, unQuote(key_value[1], fileName)); dataMap.insert(QLatin1String(NM_OPENVPN_KEY_CERT), absoluteFilePath); } else { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_CERT), unQuote(key_value[1], fileName)); } continue; } if (key_value[0] == KEY_TAG && key_value.count() > 1) { key_value[1] = line.right(line.length() - line.indexOf(QRegExp("\\s"))); // Get whole string after key if (key_value[1].trimmed() == QLatin1String("[inline]")) { // No data or file to copy for now, it will be available later when we reach tag. continue; } if (copyCertificates) { const QString absoluteFilePath = tryToCopyToCertificatesDirectory(connectionName, unQuote(key_value[1], fileName)); dataMap.insert(QLatin1String(NM_OPENVPN_KEY_KEY), absoluteFilePath); } else { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_KEY), unQuote(key_value[1], fileName)); } continue; } if (key_value[0] == SECRET_TAG && key_value.count() > 1) { key_value[1] = line.right(line.length() - line.indexOf(QRegExp("\\s"))); // Get whole string after key if (copyCertificates) { const QString absoluteFilePath = tryToCopyToCertificatesDirectory(connectionName, unQuote(key_value[1], fileName)); dataMap.insert(QLatin1String(NM_OPENVPN_KEY_STATIC_KEY), absoluteFilePath); } else { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_STATIC_KEY), unQuote(key_value[1], fileName)); } if (key_value.count() > 2) { key_value[2] = key_value[1]; if (!key_value[2].isEmpty() && (key_value[2].toLong() == 0 ||key_value[2].toLong() == 1)) { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_STATIC_KEY_DIRECTION), key_value[2]); } } have_sk = true; continue; } if (key_value[0] == TLS_AUTH_TAG && key_value.count() >1) { key_value[1] = line.right(line.length() - line.indexOf(QRegExp("\\s"))); // Get whole string after key // We will copy inline certificate later when we reach tag. if (key_value[1].trimmed() != QLatin1String("[inline]")) { if (copyCertificates) { const QString absoluteFilePath = tryToCopyToCertificatesDirectory(connectionName, unQuote(key_value[1], fileName)); dataMap.insert(QLatin1String(NM_OPENVPN_KEY_TA), absoluteFilePath); } else { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_TA), unQuote(key_value[1], fileName)); } } if (key_value.count() > 2) { key_value[2] = key_value[1]; if (!key_value[2].isEmpty() && (key_value[2].toLong() == 0 ||key_value[2].toLong() == 1)) { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_TA_DIR), key_value[2]); } } continue; } if (key_value[0] == CIPHER_TAG) { if (key_value.count() == 2) { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_CIPHER), key_value[1]); } else { - KMessageBox::information(0, i18n("Invalid number of arguments (expected 1) in option: %1", line)); + KMessageBox::information(nullptr, i18n("Invalid number of arguments (expected 1) in option: %1", line)); } continue; } if (key_value[0] == TLS_REMOTE_TAG) { if (!unQuote(key_value[1], fileName).isEmpty()) { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_TLS_REMOTE), key_value[1]); } else { - KMessageBox::information(0, i18n("Unknown option: %1", line)); + KMessageBox::information(nullptr, i18n("Unknown option: %1", line)); } continue; } if (key_value[0] == IFCONFIG_TAG) { if (key_value.count() == 3) { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_LOCAL_IP), key_value[1]); dataMap.insert(QLatin1String(NM_OPENVPN_KEY_REMOTE_IP), key_value[2]); } else { - KMessageBox::information(0, i18n("Invalid number of arguments (expected 2) in option: %1", line)); + KMessageBox::information(nullptr, i18n("Invalid number of arguments (expected 2) in option: %1", line)); } continue; } if (key_value[0] == AUTH_USER_PASS_TAG) { have_pass = true; } if (key_value[0] == AUTH_TAG) { if (key_value.count() == 2) { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_AUTH), key_value[1]); } else { - KMessageBox::information(0, i18n("Invalid number of arguments (expected 1) in option: %1", line)); + KMessageBox::information(nullptr, i18n("Invalid number of arguments (expected 1) in option: %1", line)); } continue; } if (key_value[0] == KEY_DIRECTION_TAG) { if (key_value.count() == 2) { key_direction = key_value[1].toInt(); } if (key_direction != 0 && key_direction != 1) { - KMessageBox::information(0, i18n("Invalid argument in option: %1", line)); + KMessageBox::information(nullptr, i18n("Invalid argument in option: %1", line)); key_direction = -1; } continue; } if (key_value[0] == BEGIN_KEY_CA_TAG) { const QString caAbsolutePath = saveFile(in, QLatin1String(END_KEY_CA_TAG), connectionName, "ca.crt"); if (!caAbsolutePath.isEmpty()) { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_CA), caAbsolutePath); } continue; } else if (key_value[0] == BEGIN_KEY_CERT_TAG) { const QString certAbsolutePath = saveFile(in, QLatin1String(END_KEY_CERT_TAG), connectionName, "cert.crt"); if (!certAbsolutePath.isEmpty()) { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_CERT), certAbsolutePath); } continue; } else if (key_value[0] == BEGIN_KEY_KEY_TAG) { const QString keyAbsolutePath = saveFile(in, QLatin1String(END_KEY_KEY_TAG), connectionName, "private.key"); if (!keyAbsolutePath.isEmpty()) { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_KEY), keyAbsolutePath); } continue; } else if (key_value[0] == BEGIN_KEY_SECRET_TAG) { const QString secretAbsolutePath = saveFile(in, QLatin1String(END_KEY_SECRET_TAG), connectionName, "secret.key"); if (!secretAbsolutePath.isEmpty()) { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_KEY), secretAbsolutePath); have_sk = true; if (key_direction > -1) { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_STATIC_KEY_DIRECTION), QString().setNum(key_direction)); } } continue; } else if (key_value[0] == BEGIN_TLS_AUTH_TAG) { const QString tlsAuthAbsolutePath = saveFile(in, QLatin1String(END_TLS_AUTH_TAG), connectionName, "tls_auth.key"); if (!tlsAuthAbsolutePath.isEmpty()) { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_TA), tlsAuthAbsolutePath); if (key_direction > -1) { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_TA_DIR), QString().setNum(key_direction)); } } continue; } // Import X-NM-Routes if present if (key_value[0] == "X-NM-Routes") { QList list; for (int i = 1; i < key_value.count(); i++) { NetworkManager::IpRoute ipRoute; ipRoute.setIp(QHostAddress(key_value[1].split('/').first())); ipRoute.setPrefixLength(key_value[1].split('/').at(1).toInt()); list << ipRoute; } QList > dbusRoutes; Q_FOREACH (const NetworkManager::IpRoute &route, list) { QList dbusRoute; dbusRoute << htonl(route.ip().toIPv4Address()) << route.prefixLength() << htonl(route.nextHop().toIPv4Address()) << route.metric(); dbusRoutes << dbusRoute; } ipv4Data.insert("routes", QVariant::fromValue(dbusRoutes)); continue; } } if (!have_client && !have_sk) { mError = VpnUiPlugin::Error; mErrorMessage = i18n("File %1 is not a valid OpenVPN's client configuration file", fileName); return result; } else if (!have_remote) { mError = VpnUiPlugin::Error; mErrorMessage = i18n("File %1 is not a valid OpenVPN configuration (no remote).", fileName); return result; } else { QString conType; bool have_certs = false; bool have_ca = false; if (dataMap.contains(NM_OPENVPN_KEY_CA)) { have_ca = true; } if (have_ca && dataMap.contains(NM_OPENVPN_KEY_CERT) && dataMap.contains(NM_OPENVPN_KEY_KEY)) { have_certs = true; } // Determine connection type if (have_pass) { if (have_certs) { conType = NM_OPENVPN_CONTYPE_PASSWORD_TLS; } else if (have_ca) { conType = NM_OPENVPN_CONTYPE_PASSWORD; } } else if (have_certs) { conType = NM_OPENVPN_CONTYPE_TLS; } else if (have_sk) { conType = NM_OPENVPN_CONTYPE_STATIC_KEY; } if (conType.isEmpty()) { conType = NM_OPENVPN_CONTYPE_TLS; } dataMap.insert(QLatin1String(NM_OPENVPN_KEY_CONNECTION_TYPE), conType); // Default secret flags to be agent-owned if (have_pass) { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_PASSWORD"-flags"), QString::number(NetworkManager::Setting::AgentOwned)); } if (have_certs) { if (dataMap.contains(NM_OPENVPN_KEY_KEY) && isEncrypted(dataMap[NM_OPENVPN_KEY_KEY])) { dataMap.insert(QLatin1String(NM_OPENVPN_KEY_CERTPASS"-flags"), QString::number(NetworkManager::Setting::AgentOwned)); } } } // Set the '...-type' and '...-flags' value also NetworkManager::VpnSetting setting; setting.setServiceType("org.freedesktop.NetworkManager.openvpn"); setting.setData(dataMap); setting.setSecrets(secretData); QVariantMap conn; conn.insert("id", connectionName); conn.insert("type", "vpn"); result.insert("connection", conn); result.insert("vpn", setting.toMap()); if (!ipv4Data.isEmpty()) { result.insert("ipv4", ipv4Data); } impFile.close(); return result; } QString OpenVpnUiPlugin::saveFile(QTextStream &in, const QString &endTag, const QString &connectionName, const QString &fileName) { - const QString certificatesDirectory = KStandardDirs::locateLocal("data", "networkmanagement/certificates/" + connectionName); + const QString certificatesDirectory = localCertPath() + connectionName; const QString absoluteFilePath = certificatesDirectory + '/' + fileName; QFile outFile(absoluteFilePath); QDir().mkpath(certificatesDirectory); if (!outFile.open(QFile::WriteOnly | QFile::Text)) { - KMessageBox::information(0, i18n("Error saving file %1: %2", absoluteFilePath, outFile.errorString())); + KMessageBox::information(nullptr, i18n("Error saving file %1: %2", absoluteFilePath, outFile.errorString())); return QString(); } QTextStream out(&outFile); while (!in.atEnd()) { const QString line = in.readLine(); if (line.indexOf(endTag) >= 0) { break; } out << line << "\n"; } outFile.close(); return absoluteFilePath; } QString OpenVpnUiPlugin::tryToCopyToCertificatesDirectory(const QString &connectionName, const QString &sourceFilePath) { - const QString certificatesDirectory = KStandardDirs::locateLocal("data", "networkmanagement/certificates/"); + const QString certificatesDirectory = localCertPath(); const QString absoluteFilePath = certificatesDirectory + connectionName + '_' + QFileInfo(sourceFilePath).fileName(); QFile sourceFile(sourceFilePath); QDir().mkpath(certificatesDirectory); if (!sourceFile.copy(absoluteFilePath)) { - KMessageBox::information(0, i18n("Error copying certificate to %1: %2", absoluteFilePath, sourceFile.errorString())); + KMessageBox::information(nullptr, i18n("Error copying certificate to %1: %2", absoluteFilePath, sourceFile.errorString())); return sourceFilePath; } return absoluteFilePath; } bool OpenVpnUiPlugin::exportConnectionSettings(const NetworkManager::ConnectionSettings::Ptr &connection, const QString &fileName) { QFile expFile(fileName); if (! expFile.open(QIODevice::WriteOnly | QIODevice::Text) ) { mError = VpnUiPlugin::Error; mErrorMessage = i18n("Could not open file for writing"); return false; } NMStringMap dataMap; NMStringMap secretData; NetworkManager::VpnSetting::Ptr vpnSetting = connection->setting(NetworkManager::Setting::Vpn).dynamicCast(); dataMap = vpnSetting->data(); secretData = vpnSetting->secrets(); QString line; QString cacert, user_cert, private_key; line = QString(CLIENT_TAG) + '\n'; expFile.write(line.toLatin1()); line = QString(REMOTE_TAG) + ' ' + dataMap[NM_OPENVPN_KEY_REMOTE] + (dataMap[NM_OPENVPN_KEY_PORT].isEmpty() ? "\n" : (' ' + dataMap[NM_OPENVPN_KEY_PORT]) + '\n'); expFile.write(line.toLatin1()); if (dataMap[NM_OPENVPN_KEY_CONNECTION_TYPE] == NM_OPENVPN_CONTYPE_TLS || dataMap[NM_OPENVPN_KEY_CONNECTION_TYPE] == NM_OPENVPN_CONTYPE_PASSWORD || dataMap[NM_OPENVPN_KEY_CONNECTION_TYPE] == NM_OPENVPN_CONTYPE_PASSWORD_TLS) { if (!dataMap[NM_OPENVPN_KEY_CA].isEmpty()) { cacert = dataMap[NM_OPENVPN_KEY_CA]; } } if (dataMap[NM_OPENVPN_KEY_CONNECTION_TYPE] == NM_OPENVPN_CONTYPE_TLS || dataMap[NM_OPENVPN_KEY_CONNECTION_TYPE] == NM_OPENVPN_CONTYPE_PASSWORD_TLS) { if (!dataMap[NM_OPENVPN_KEY_CERT].isEmpty()) { user_cert = dataMap[NM_OPENVPN_KEY_CERT]; } if (!dataMap[NM_OPENVPN_KEY_KEY].isEmpty()) { private_key = dataMap[NM_OPENVPN_KEY_KEY]; } } // Handle PKCS#12 (all certs are the same file) if (!cacert.isEmpty() && !user_cert.isEmpty() && !private_key.isEmpty() && cacert == user_cert && cacert == private_key) { line = QString("%1 \"%2\"\n").arg(PKCS12_TAG, cacert); expFile.write(line.toLatin1()); } else { if (!cacert.isEmpty()) { line = QString("%1 \"%2\"\n").arg(CA_TAG, cacert); expFile.write(line.toLatin1()); } if (!user_cert.isEmpty()) { line = QString("%1 \"%2\"\n").arg(CERT_TAG, user_cert); expFile.write(line.toLatin1()); } if (!private_key.isEmpty()) { line = QString("%1 \"%2\"\n").arg(KEY_TAG, private_key); expFile.write(line.toLatin1()); } } if (dataMap[NM_OPENVPN_KEY_CONNECTION_TYPE] == NM_OPENVPN_CONTYPE_TLS || dataMap[NM_OPENVPN_KEY_CONNECTION_TYPE] == NM_OPENVPN_CONTYPE_STATIC_KEY || dataMap[NM_OPENVPN_KEY_CONNECTION_TYPE] == NM_OPENVPN_CONTYPE_PASSWORD || dataMap[NM_OPENVPN_KEY_CONNECTION_TYPE] == NM_OPENVPN_CONTYPE_PASSWORD_TLS) { line = QString(AUTH_USER_PASS_TAG) + '\n'; expFile.write(line.toLatin1()); if (!dataMap[NM_OPENVPN_KEY_TLS_REMOTE].isEmpty()) { line = QString(TLS_REMOTE_TAG) + " \"" + dataMap[NM_OPENVPN_KEY_TLS_REMOTE] + "\"\n"; expFile.write(line.toLatin1()); } if (!dataMap[NM_OPENVPN_KEY_TA].isEmpty()) { line = QString(TLS_AUTH_TAG) + " \"" + dataMap[NM_OPENVPN_KEY_TA] + '\"' + (dataMap[NM_OPENVPN_KEY_TA_DIR].isEmpty() ? "\n" : (' ' + dataMap[NM_OPENVPN_KEY_TA_DIR]) + '\n'); expFile.write(line.toLatin1()); } } if (dataMap[NM_OPENVPN_KEY_CONNECTION_TYPE] == NM_OPENVPN_CONTYPE_STATIC_KEY) { line = QString(SECRET_TAG) + " \"" + dataMap[NM_OPENVPN_KEY_STATIC_KEY] + '\"' + (dataMap[NM_OPENVPN_KEY_STATIC_KEY_DIRECTION].isEmpty() ? "\n" : (' ' + dataMap[NM_OPENVPN_KEY_STATIC_KEY_DIRECTION]) + '\n'); expFile.write(line.toLatin1()); } if (dataMap.contains(NM_OPENVPN_KEY_RENEG_SECONDS) && !dataMap[NM_OPENVPN_KEY_RENEG_SECONDS].isEmpty()) { line = QString(RENEG_SEC_TAG) + ' ' + dataMap[NM_OPENVPN_KEY_RENEG_SECONDS] + '\n'; expFile.write(line.toLatin1()); } if (!dataMap[NM_OPENVPN_KEY_CIPHER].isEmpty()) { line = QString(CIPHER_TAG) + ' ' + dataMap[NM_OPENVPN_KEY_CIPHER] + '\n'; expFile.write(line.toLatin1()); } if (dataMap[NM_OPENVPN_KEY_COMP_LZO] == "yes") { line = QString(COMP_TAG) + " yes\n"; expFile.write(line.toLatin1()); } if (dataMap[NM_OPENVPN_KEY_MSSFIX] == "yes") { line = QString(MSSFIX_TAG) + '\n'; expFile.write(line.toLatin1()); } if (!dataMap[NM_OPENVPN_KEY_TUNNEL_MTU].isEmpty()) { line = QString(TUNMTU_TAG) + ' ' + dataMap[NM_OPENVPN_KEY_TUNNEL_MTU] + '\n'; expFile.write(line.toLatin1()); } if (!dataMap[NM_OPENVPN_KEY_FRAGMENT_SIZE].isEmpty()) { line = QString(FRAGMENT_TAG) + ' ' + dataMap[NM_OPENVPN_KEY_FRAGMENT_SIZE] + '\n'; expFile.write(line.toLatin1()); } line = QString(DEV_TAG) + (dataMap[NM_OPENVPN_KEY_TAP_DEV] == "yes" ? " tap\n" : " tun\n"); expFile.write(line.toLatin1()); line = QString(PROTO_TAG) + (dataMap[NM_OPENVPN_KEY_PROTO_TCP] == "yes" ? " tcp\n" : " udp\n"); expFile.write(line.toLatin1()); // Proxy stuff if (!dataMap[NM_OPENVPN_KEY_PROXY_TYPE].isEmpty()) { QString proxy_port = dataMap[NM_OPENVPN_KEY_PROXY_PORT]; if (dataMap[NM_OPENVPN_KEY_PROXY_TYPE] == "http" && !dataMap[NM_OPENVPN_KEY_PROXY_SERVER].isEmpty() && dataMap.contains(NM_OPENVPN_KEY_PROXY_PORT)) { if (proxy_port.toInt() == 0) { proxy_port = "8080"; } line = QString(HTTP_PROXY_TAG) + ' ' + dataMap[NM_OPENVPN_KEY_PROXY_SERVER] + ' ' + proxy_port + (dataMap[NM_OPENVPN_KEY_HTTP_PROXY_USERNAME].isEmpty() ? "\n" : (' ' + fileName + "-httpauthfile") + '\n'); expFile.write(line.toLatin1()); if (dataMap[NM_OPENVPN_KEY_PROXY_RETRY] == "yes") { line = QString(HTTP_PROXY_RETRY_TAG) + '\n'; expFile.write(line.toLatin1()); } // If there is a username, need to write an authfile if (!dataMap[NM_OPENVPN_KEY_HTTP_PROXY_USERNAME].isEmpty()) { QFile authFile(fileName + "-httpauthfile"); if (authFile.open(QFile::WriteOnly | QFile::Text)) { line = dataMap[NM_OPENVPN_KEY_HTTP_PROXY_USERNAME] + (dataMap[NM_OPENVPN_KEY_HTTP_PROXY_PASSWORD].isEmpty()? "\n" : (dataMap[NM_OPENVPN_KEY_HTTP_PROXY_PASSWORD] + '\n')); authFile.write(line.toLatin1()); authFile.close(); } } } else if (dataMap[NM_OPENVPN_KEY_PROXY_TYPE] == "socks" && !dataMap[NM_OPENVPN_KEY_PROXY_SERVER].isEmpty() && dataMap.contains(NM_OPENVPN_KEY_PROXY_PORT)) { if (proxy_port.toInt() == 0) { proxy_port = "1080"; } line = QString(SOCKS_PROXY_TAG) + dataMap[NM_OPENVPN_KEY_PROXY_SERVER] + ' ' + proxy_port + '\n'; expFile.write(line.toLatin1()); if (dataMap[NM_OPENVPN_KEY_PROXY_RETRY] == "yes") { line = QString(SOCKS_PROXY_RETRY_TAG) + '\n'; expFile.write(line.toLatin1()); } } } NetworkManager::Ipv4Setting::Ptr ipv4Setting = connection->setting(NetworkManager::Setting::Ipv4).dynamicCast(); // Export X-NM-Routes if (!ipv4Setting->routes().isEmpty()) { QString routes; Q_FOREACH (const NetworkManager::IpRoute &route, ipv4Setting->routes()) { routes += route.ip().toString() % QLatin1Char('/') % QString::number(route.prefixLength()) % QLatin1Char(' '); } if (!routes.isEmpty()) { routes = "X-NM-Routes " + routes.trimmed(); expFile.write(routes.toLatin1() + '\n'); } } // Add hard-coded stuff expFile.write("nobind\n" "auth-nocache\n" "script-security 2\n" "persist-key\n" "persist-tun\n" "user nobody\n" "group nobody\n"); expFile.close(); return true; } #include "openvpn.moc" diff --git a/vpn/openvpn/openvpn.h b/vpn/openvpn/openvpn.h index a630b485..69f8c6ee 100644 --- a/vpn/openvpn/openvpn.h +++ b/vpn/openvpn/openvpn.h @@ -1,51 +1,51 @@ /* Copyright 2008 Will Stephenson Copyright 2011 Rajeesh K Nambiar Copyright 2011 Ilia Kats Copyright 2014 Lamarque V. Souza 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef PLASMANM_OPENVPN_H #define PLASMANM_OPENVPN_H #include "vpnuiplugin.h" #include #include class Q_DECL_EXPORT OpenVpnUiPlugin : public VpnUiPlugin { Q_OBJECT public: - explicit OpenVpnUiPlugin(QObject * parent = 0, const QVariantList& = QVariantList()); - virtual ~OpenVpnUiPlugin(); - SettingWidget * widget(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = 0); - SettingWidget * askUser(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = 0); - - QString suggestedFileName(const NetworkManager::ConnectionSettings::Ptr &connection) const; - QString supportedFileExtensions() const; - NMVariantMapMap importConnectionSettings(const QString &fileName); - bool exportConnectionSettings(const NetworkManager::ConnectionSettings::Ptr &connection, const QString &fileName); + explicit OpenVpnUiPlugin(QObject * parent = nullptr, const QVariantList& = QVariantList()); + ~OpenVpnUiPlugin() override; + SettingWidget * widget(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = nullptr) override; + SettingWidget * askUser(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = nullptr) override; + + QString suggestedFileName(const NetworkManager::ConnectionSettings::Ptr &connection) const override; + QString supportedFileExtensions() const override; + NMVariantMapMap importConnectionSettings(const QString &fileName) override; + bool exportConnectionSettings(const NetworkManager::ConnectionSettings::Ptr &connection, const QString &fileName) override; private: QString saveFile(QTextStream &in, const QString &endTag, const QString &connectionName, const QString &fileName); QString tryToCopyToCertificatesDirectory(const QString &connectionName, const QString &sourceFilePath); }; #endif // PLASMANM_OPENVPN_H diff --git a/vpn/openvpn/openvpnadvancedwidget.cpp b/vpn/openvpn/openvpnadvancedwidget.cpp index 2689d554..2f37e86c 100644 --- a/vpn/openvpn/openvpnadvancedwidget.cpp +++ b/vpn/openvpn/openvpnadvancedwidget.cpp @@ -1,703 +1,703 @@ /* Copyright 2013 Lukas Tinkl Copyright 2015 Jan Grulich This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "openvpnadvancedwidget.h" #include "ui_openvpnadvanced.h" #include "nm-openvpn-service.h" #include "settingwidget.h" #include #include #include #include #include #include class OpenVpnAdvancedWidget::Private { public: NetworkManager::VpnSetting::Ptr setting; KProcess *openvpnCipherProcess = nullptr; KProcess *openvpnVersionProcess = nullptr; QByteArray openvpnCiphers; QByteArray openVpnVersion; bool gotOpenVpnCiphers = false; bool gotOpenVpnVersion = false; bool readConfig = false; int versionX = 0; int versionY = 0; int versionZ = 0; class EnumProxyType { public: enum ProxyType {NotRequired = 0, HTTP = 1, SOCKS = 2}; }; class EnumHashingAlgorithms { public: enum HashingAlgorithms {Default = 0, None, Md4, Md5, Sha1, Sha224, Sha256, Sha384, Sha512, Ripemd160}; }; }; OpenVpnAdvancedWidget::OpenVpnAdvancedWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent) : QDialog(parent) , m_ui(new Ui::OpenVpnAdvancedWidget) , d(new Private) { m_ui->setupUi(this); setWindowTitle(i18nc("@title: window advanced openvpn properties", "Advanced OpenVPN properties")); d->setting = setting; m_ui->proxyPassword->setPasswordOptionsEnabled(true); m_ui->proxyPassword->setPasswordNotRequiredEnabled(true); - connect(m_ui->cbCertCheck, static_cast(&QComboBox::currentIndexChanged), this, &OpenVpnAdvancedWidget::certCheckTypeChanged); - connect(m_ui->cmbProxyType, static_cast(&QComboBox::currentIndexChanged), this, &OpenVpnAdvancedWidget::proxyTypeChanged); - connect(m_ui->cboTLSMode, static_cast(&QComboBox::currentIndexChanged), this, [this] (int index) { + connect(m_ui->cbCertCheck, QOverload::of(&QComboBox::currentIndexChanged), this, &OpenVpnAdvancedWidget::certCheckTypeChanged); + connect(m_ui->cmbProxyType, QOverload::of(&QComboBox::currentIndexChanged), this, &OpenVpnAdvancedWidget::proxyTypeChanged); + connect(m_ui->cboTLSMode, QOverload::of(&QComboBox::currentIndexChanged), this, [this] (int index) { if (index == 0) { m_ui->kurlTlsAuthKey->setDisabled(true); m_ui->cboDirection->setDisabled(true); } else if (index == 1) { // TLS-Auth m_ui->kurlTlsAuthKey->setEnabled(true); m_ui->cboDirection->setEnabled(true); } else { // TLS-Crypt m_ui->kurlTlsAuthKey->setEnabled(true); m_ui->cboDirection->setDisabled(true); } }); // start openVPN process and get its cipher list const QString openVpnBinary = QStandardPaths::findExecutable("openvpn", QStringList() << "/sbin" << "/usr/sbin"); const QStringList ciphersArgs(QLatin1String("--show-ciphers")); const QStringList versionArgs(QLatin1String("--version")); d->openvpnCipherProcess = new KProcess(this); d->openvpnCipherProcess->setOutputChannelMode(KProcess::OnlyStdoutChannel); d->openvpnCipherProcess->setReadChannel(QProcess::StandardOutput); - connect(d->openvpnCipherProcess, static_cast(&KProcess::error), this, &OpenVpnAdvancedWidget::openVpnCipherError); + connect(d->openvpnCipherProcess, QOverload::of(&KProcess::error), this, &OpenVpnAdvancedWidget::openVpnCipherError); connect(d->openvpnCipherProcess, &KProcess::readyReadStandardOutput, this, &OpenVpnAdvancedWidget::gotOpenVpnCipherOutput); - connect(d->openvpnCipherProcess, static_cast(&KProcess::finished), this, &OpenVpnAdvancedWidget::openVpnCipherFinished); + connect(d->openvpnCipherProcess, QOverload::of(&KProcess::finished), this, &OpenVpnAdvancedWidget::openVpnCipherFinished); d->openvpnCipherProcess->setProgram(openVpnBinary, ciphersArgs); d->openvpnVersionProcess = new KProcess(this); d->openvpnVersionProcess->setOutputChannelMode(KProcess::OnlyStdoutChannel); d->openvpnVersionProcess->setReadChannel(QProcess::StandardOutput); - connect(d->openvpnVersionProcess, static_cast(&KProcess::error), this, &OpenVpnAdvancedWidget::openVpnVersionError); + connect(d->openvpnVersionProcess, QOverload::of(&KProcess::error), this, &OpenVpnAdvancedWidget::openVpnVersionError); connect(d->openvpnVersionProcess, &KProcess::readyReadStandardOutput, this, &OpenVpnAdvancedWidget::gotOpenVpnVersionOutput); - connect(d->openvpnVersionProcess, static_cast(&KProcess::finished), this, &OpenVpnAdvancedWidget::openVpnVersionFinished); + connect(d->openvpnVersionProcess, QOverload::of(&KProcess::finished), this, &OpenVpnAdvancedWidget::openVpnVersionFinished); d->openvpnVersionProcess->setProgram(openVpnBinary, versionArgs); connect(m_ui->buttonBox, &QDialogButtonBox::accepted, this, &OpenVpnAdvancedWidget::accept); connect(m_ui->buttonBox, &QDialogButtonBox::rejected, this, &OpenVpnAdvancedWidget::reject); KAcceleratorManager::manage(this); if (d->setting) { loadConfig(); } } OpenVpnAdvancedWidget::~OpenVpnAdvancedWidget() { delete d; } void OpenVpnAdvancedWidget::init() { d->openvpnCipherProcess->start(); d->openvpnVersionProcess->start(); } void OpenVpnAdvancedWidget::gotOpenVpnCipherOutput() { d->openvpnCiphers.append(d->openvpnCipherProcess->readAll()); } void OpenVpnAdvancedWidget::openVpnCipherError(QProcess::ProcessError) { m_ui->cboCipher->removeItem(0); m_ui->cboCipher->addItem(i18nc("@item:inlistbox Item added when OpenVPN cipher lookup failed", "OpenVPN cipher lookup failed")); } void OpenVpnAdvancedWidget::openVpnCipherFinished(int exitCode, QProcess::ExitStatus exitStatus) { m_ui->cboCipher->removeItem(0); if (!exitCode && exitStatus == QProcess::NormalExit) { m_ui->cboCipher->addItem(i18nc("@item::inlist Default openvpn cipher item", "Default")); const QList rawOutputLines = d->openvpnCiphers.split('\n'); bool foundFirstSpace = false; Q_FOREACH (const QByteArray &cipher, rawOutputLines) { if (cipher.length() == 0) { foundFirstSpace = true; } else if (foundFirstSpace) { m_ui->cboCipher->addItem(QString::fromLocal8Bit(cipher.left(cipher.indexOf(' ')))); } } if (m_ui->cboCipher->count()) { m_ui->cboCipher->setEnabled(true); } else { m_ui->cboCipher->addItem(i18nc("@item:inlistbox Item added when OpenVPN cipher lookup failed", "No OpenVPN ciphers found")); } } else { m_ui->cboCipher->addItem(i18nc("@item:inlistbox Item added when OpenVPN cipher lookup failed", "OpenVPN cipher lookup failed")); } delete d->openvpnCipherProcess; - d->openvpnCipherProcess = 0; + d->openvpnCipherProcess = nullptr; d->openvpnCiphers = QByteArray(); d->gotOpenVpnCiphers = true; if (d->readConfig) { const NMStringMap dataMap = d->setting->data(); if (dataMap.contains(NM_OPENVPN_KEY_CIPHER)) { m_ui->cboCipher->setCurrentIndex(m_ui->cboCipher->findText(dataMap.value(NM_OPENVPN_KEY_CIPHER))); } } } void OpenVpnAdvancedWidget::gotOpenVpnVersionOutput() { d->openVpnVersion.append(d->openvpnVersionProcess->readAll()); } void OpenVpnAdvancedWidget::openVpnVersionError(QProcess::ProcessError) { // We couldn't identify OpenVPN version so disable tls-remote disableLegacySubjectMatch(); } void OpenVpnAdvancedWidget::openVpnVersionFinished(int exitCode, QProcess::ExitStatus exitStatus) { // OpenVPN returns 1 when you use "--help" and unfortunately returns 1 even when some error occurs if (exitCode == 1 && exitStatus == QProcess::NormalExit) { QStringList list = QString(d->openVpnVersion).split(QLatin1Char(' ')); if (list.count() > 2) { const QStringList versionList = list.at(1).split(QLatin1Char('.')); if (versionList.count() == 3) { d->versionX = versionList.at(0).toInt(); d->versionY = versionList.at(1).toInt(); d->versionZ = versionList.at(2).toInt(); if (compareVersion(2, 4, 0) >= 0) { disableLegacySubjectMatch(); } } } } else { disableLegacySubjectMatch(); } delete d->openvpnVersionProcess; - d->openvpnVersionProcess = 0; + d->openvpnVersionProcess = nullptr; d->openVpnVersion = QByteArray(); d->gotOpenVpnVersion = true; if (d->readConfig) { const NMStringMap dataMap = d->setting->data(); if (dataMap.contains(NM_OPENVPN_KEY_TLS_REMOTE)) { m_ui->subjectMatch->setText(dataMap.value(NM_OPENVPN_KEY_TLS_REMOTE)); } } } int OpenVpnAdvancedWidget::compareVersion(const int x, const int y, const int z) const { if (d->versionX == 0) { // Not valid version return -2; } if (d->versionX > x) { return 1; } else if (d->versionX < x) { return -1; } else if (d->versionY > y) { return 1; } else if (d->versionY < y) { return -1; } else if (d->versionZ > z) { return 1; } else if (d->versionZ < z) { return -1; } return 0; } void OpenVpnAdvancedWidget::disableLegacySubjectMatch() { m_ui->cbCertCheck->removeItem(CertCheckType::VerifySubjectPartially); } void OpenVpnAdvancedWidget::loadConfig() { const NMStringMap dataMap = d->setting->data(); const NMStringMap secrets = d->setting->secrets(); // Optional Settings if (dataMap.contains(QLatin1String(NM_OPENVPN_KEY_PORT))) { m_ui->chkCustomPort->setChecked(true); m_ui->sbCustomPort->setValue(dataMap[QLatin1String(NM_OPENVPN_KEY_PORT)].toUInt()); } else { m_ui->chkCustomPort->setChecked(false); m_ui->sbCustomPort->setValue(1194); // Default value } if (dataMap.contains(QLatin1String(NM_OPENVPN_KEY_TUNNEL_MTU))) { m_ui->chkMtu->setChecked(true); m_ui->sbMtu->setValue(dataMap[QLatin1String(NM_OPENVPN_KEY_TUNNEL_MTU)].toUInt()); } else { m_ui->chkMtu->setChecked(false); m_ui->sbMtu->setValue(1500); // Default value } if (dataMap.contains(QLatin1String(NM_OPENVPN_KEY_FRAGMENT_SIZE))) { m_ui->chkCustomFragmentSize->setChecked(true); m_ui->sbCustomFragmentSize->setValue(dataMap[QLatin1String(NM_OPENVPN_KEY_FRAGMENT_SIZE)].toUInt()); } else { m_ui->chkCustomFragmentSize->setChecked(false); m_ui->sbCustomFragmentSize->setValue(1300); } if (dataMap.contains(QLatin1String(NM_OPENVPN_KEY_RENEG_SECONDS))) { m_ui->chkUseCustomReneg->setChecked(true); m_ui->sbCustomReneg->setValue(dataMap[QLatin1String(NM_OPENVPN_KEY_RENEG_SECONDS)].toUInt()); } else { m_ui->chkUseCustomReneg->setChecked(false); m_ui->sbCustomReneg->setValue(0); } if (dataMap.contains(QLatin1String(NM_OPENVPN_KEY_COMP_LZO))) { const QString compLzo = dataMap[QLatin1String(NM_OPENVPN_KEY_COMP_LZO)]; if (compLzo == QLatin1String("no-by-default")) { m_ui->cmbUseLZO->setCurrentIndex(0); } else if (compLzo == QLatin1String("yes")) { m_ui->cmbUseLZO->setCurrentIndex(1); } else { m_ui->cmbUseLZO->setCurrentIndex(2); } m_ui->chkUseLZO->setChecked(true); } m_ui->chkUseTCP->setChecked(dataMap[QLatin1String(NM_OPENVPN_KEY_PROTO_TCP)] == QLatin1String("yes")); if (dataMap.contains(QLatin1String(NM_OPENVPN_KEY_DEV_TYPE))) { m_ui->chkUseVirtualDeviceType->setChecked(true); if (dataMap[QLatin1String(NM_OPENVPN_KEY_DEV_TYPE)] == QLatin1String("tap")) { m_ui->cmbDeviceType->setCurrentIndex(1); } } if (dataMap.contains(QLatin1String(NM_OPENVPN_KEY_DEV))) { m_ui->chkUseVirtualDeviceName->setChecked(true); m_ui->leVirtualDeviceName->setText(dataMap[QLatin1String(NM_OPENVPN_KEY_DEV)]); } m_ui->chkMssRestrict->setChecked(dataMap[QLatin1String(NM_OPENVPN_KEY_MSSFIX)] == QLatin1String("yes")); m_ui->chkRandRemHosts->setChecked(dataMap[QLatin1String(NM_OPENVPN_KEY_REMOTE_RANDOM)] == QLatin1String("yes")); m_ui->chkIpv6TunLink->setChecked(dataMap[QLatin1String(NM_OPENVPN_KEY_TUN_IPV6)] == QLatin1String("yes")); if (dataMap.contains(QLatin1String(NM_OPENVPN_KEY_PING))) { m_ui->chkPingInterval->setChecked(true); m_ui->sbPingInterval->setValue(dataMap[QLatin1String(NM_OPENVPN_KEY_PING)].toInt()); } if (dataMap.contains(QLatin1String(NM_OPENVPN_KEY_PING_EXIT)) || dataMap.contains(QLatin1String(NM_OPENVPN_KEY_PING_RESTART))) { m_ui->chkSpecifyExitRestartPing->setChecked(true); if (dataMap.contains(QLatin1String(NM_OPENVPN_KEY_PING_EXIT))) { m_ui->cbSpecifyExitRestartPing->setCurrentIndex(0); // Exit m_ui->sbSpecifyExitRestartPing->setValue(dataMap[QLatin1String(NM_OPENVPN_KEY_PING_EXIT)].toInt()); } else { m_ui->cbSpecifyExitRestartPing->setCurrentIndex(1); // Restart m_ui->sbSpecifyExitRestartPing->setValue(dataMap[QLatin1String(NM_OPENVPN_KEY_PING_RESTART)].toInt()); } } m_ui->chkAcceptAuthenticatedPackets->setChecked(dataMap[QLatin1String(NM_OPENVPN_KEY_FLOAT)] == QLatin1String("yes")); if (dataMap.contains(QLatin1String(NM_OPENVPN_KEY_MAX_ROUTES))) { m_ui->chkMaxRoutes->setChecked(true); m_ui->sbMaxRoutes->setValue(dataMap[QLatin1String(NM_OPENVPN_KEY_MAX_ROUTES)].toInt()); } // Optional Security Settings const QString hmacKeyAuth = dataMap[QLatin1String(NM_OPENVPN_KEY_AUTH)]; if (hmacKeyAuth == QLatin1String(NM_OPENVPN_AUTH_NONE)) { m_ui->cboHmac->setCurrentIndex(Private::EnumHashingAlgorithms::None); } else if (hmacKeyAuth == QLatin1String(NM_OPENVPN_AUTH_RSA_MD4)) { m_ui->cboHmac->setCurrentIndex(Private::EnumHashingAlgorithms::Md4); } else if (hmacKeyAuth == QLatin1String(NM_OPENVPN_AUTH_MD5)) { m_ui->cboHmac->setCurrentIndex(Private::EnumHashingAlgorithms::Md5); } else if (hmacKeyAuth == QLatin1String(NM_OPENVPN_AUTH_SHA1)) { m_ui->cboHmac->setCurrentIndex(Private::EnumHashingAlgorithms::Sha1); } else if (hmacKeyAuth == QLatin1String(NM_OPENVPN_AUTH_SHA224)) { m_ui->cboHmac->setCurrentIndex(Private::EnumHashingAlgorithms::Sha224); } else if (hmacKeyAuth == QLatin1String(NM_OPENVPN_AUTH_SHA256)) { m_ui->cboHmac->setCurrentIndex(Private::EnumHashingAlgorithms::Sha256); } else if (hmacKeyAuth == QLatin1String(NM_OPENVPN_AUTH_SHA384)) { m_ui->cboHmac->setCurrentIndex(Private::EnumHashingAlgorithms::Sha384); } else if (hmacKeyAuth == QLatin1String(NM_OPENVPN_AUTH_SHA512)) { m_ui->cboHmac->setCurrentIndex(Private::EnumHashingAlgorithms::Sha512); } else if (hmacKeyAuth == QLatin1String(NM_OPENVPN_AUTH_RIPEMD160)) { m_ui->cboHmac->setCurrentIndex(Private::EnumHashingAlgorithms::Ripemd160); } else { m_ui->cboHmac->setCurrentIndex(Private::EnumHashingAlgorithms::Default); } if (dataMap.contains(QLatin1String(NM_OPENVPN_KEY_KEYSIZE))) { m_ui->chkUseCustomCipherKey->setChecked(true); m_ui->sbCustomCipherKey->setValue(dataMap[QLatin1String(NM_OPENVPN_KEY_KEYSIZE)].toUInt()); } // ciphers populated above? if (d->gotOpenVpnCiphers && dataMap.contains(QLatin1String(NM_OPENVPN_KEY_CIPHER))) { m_ui->cboCipher->setCurrentIndex(m_ui->cboCipher->findText(dataMap[QLatin1String(NM_OPENVPN_KEY_CIPHER)])); } // Optional TLS if (dataMap.contains(QLatin1String(NM_OPENVPN_KEY_TLS_REMOTE))) { m_ui->cbCertCheck->setCurrentIndex(CertCheckType::VerifySubjectPartially); m_ui->subjectMatch->setText(dataMap[QLatin1String(NM_OPENVPN_KEY_TLS_REMOTE)]); } if (dataMap.contains(QLatin1String(NM_OPENVPN_KEY_VERIFY_X509_NAME))) { const QString x509Value = dataMap.value(QLatin1String(NM_OPENVPN_KEY_VERIFY_X509_NAME)); const QStringList x509List = x509Value.split(QLatin1Char(':')); if (x509List.size() == 2) { if (x509List.at(0) == QLatin1String(NM_OPENVPN_VERIFY_X509_NAME_TYPE_SUBJECT)) { m_ui->cbCertCheck->setCurrentIndex(CertCheckType::VerifyWholeSubjectExactly); } else if (x509List.at(0) == QLatin1String(NM_OPENVPN_VERIFY_X509_NAME_TYPE_NAME)) { m_ui->cbCertCheck->setCurrentIndex(CertCheckType::VerifyNameExactly); } else if (x509List.at(0) == QLatin1String(NM_OPENVPN_VERIFY_X509_NAME_TYPE_NAME_PREFIX)) { m_ui->cbCertCheck->setCurrentIndex(CertCheckType::VerifyNameByPrefix); } m_ui->subjectMatch->setText(x509List.at(1)); } } else { m_ui->cbCertCheck->setCurrentIndex(CertCheckType::DontVerify); } if (dataMap.contains(QLatin1String(NM_OPENVPN_KEY_REMOTE_CERT_TLS))) { const QString remoteCertTls = dataMap[QLatin1String(NM_OPENVPN_KEY_REMOTE_CERT_TLS)]; m_ui->chkRemoteCertTls->setChecked(true); m_ui->labelRemoteCertTls->setEnabled(true); m_ui->cmbRemoteCertTls->setEnabled(true); m_ui->cmbRemoteCertTls->setCurrentIndex(remoteCertTls == QLatin1String(NM_OPENVPN_REM_CERT_TLS_SERVER) ? 0 : 1); } if (dataMap.contains(QLatin1String(NM_OPENVPN_KEY_NS_CERT_TYPE))) { const QString remoteCertTls = dataMap[QLatin1String(NM_OPENVPN_KEY_NS_CERT_TYPE)]; m_ui->chkNsCertType->setChecked(true); m_ui->lblNsCertType->setEnabled(true); m_ui->cmbNsCertType->setEnabled(true); m_ui->cmbNsCertType->setCurrentIndex(remoteCertTls == QLatin1String(NM_OPENVPN_NS_CERT_TYPE_SERVER) ? 0 : 1); } const QString openvpnKeyTa = dataMap[QLatin1String(NM_OPENVPN_KEY_TA)]; const QString openvpnKeyTlsCrypt = dataMap[QLatin1String(NM_OPENVPN_KEY_TLS_CRYPT)]; if (!openvpnKeyTlsCrypt.isEmpty()) { m_ui->cboTLSMode->setCurrentIndex(2); // TLS-Crypt m_ui->kurlTlsAuthKey->setUrl(QUrl::fromLocalFile(openvpnKeyTlsCrypt)); } else if (!openvpnKeyTa.isEmpty()) { m_ui->cboTLSMode->setCurrentIndex(1); // TLS-Auth m_ui->kurlTlsAuthKey->setUrl(QUrl::fromLocalFile(openvpnKeyTa)); if (dataMap.contains(QLatin1String(NM_OPENVPN_KEY_TA_DIR))) { const uint tlsAuthDirection = dataMap[QLatin1String(NM_OPENVPN_KEY_TA_DIR)].toUInt(); m_ui->cboDirection->setCurrentIndex(tlsAuthDirection + 1); } } // Proxies if (dataMap[QLatin1String(NM_OPENVPN_KEY_PROXY_TYPE)] == QLatin1String("http")) { m_ui->cmbProxyType->setCurrentIndex(Private::EnumProxyType::HTTP); } else if (dataMap[QLatin1String(NM_OPENVPN_KEY_PROXY_TYPE)] == QLatin1String("socks")) { m_ui->cmbProxyType->setCurrentIndex(Private::EnumProxyType::SOCKS); } else { m_ui->cmbProxyType->setCurrentIndex(Private::EnumProxyType::NotRequired); } proxyTypeChanged(m_ui->cmbProxyType->currentIndex()); m_ui->proxyServerAddress->setText(dataMap[QLatin1String(NM_OPENVPN_KEY_PROXY_SERVER)]); if (dataMap.contains(QLatin1String(NM_OPENVPN_KEY_PROXY_PORT))) { m_ui->sbProxyPort->setValue(dataMap[QLatin1String(NM_OPENVPN_KEY_PROXY_PORT)].toUInt()); } else { m_ui->sbProxyPort->setValue(0); } m_ui->chkProxyRetry->setChecked(dataMap[QLatin1String(NM_OPENVPN_KEY_PROXY_RETRY)] == QLatin1String("yes")); m_ui->proxyUsername->setText(dataMap[QLatin1String(NM_OPENVPN_KEY_HTTP_PROXY_USERNAME)]); d->readConfig = true; NetworkManager::Setting::SecretFlags type; type = (NetworkManager::Setting::SecretFlags)dataMap[NM_OPENVPN_KEY_HTTP_PROXY_PASSWORD"-flags"].toInt(); if (!(type & NetworkManager::Setting::NotSaved || type & NetworkManager::Setting::NotRequired)) { m_ui->proxyPassword->setText(secrets.value(QLatin1String(NM_OPENVPN_KEY_HTTP_PROXY_PASSWORD))); } fillOnePasswordCombo(m_ui->proxyPassword, type); } void OpenVpnAdvancedWidget::fillOnePasswordCombo(PasswordField *passwordField, NetworkManager::Setting::SecretFlags type) { if (type.testFlag(NetworkManager::Setting::None)) { passwordField->setPasswordOption(PasswordField::StoreForAllUsers); } else if (type.testFlag(NetworkManager::Setting::AgentOwned)) { passwordField->setPasswordOption(PasswordField::StoreForUser); } else if (type.testFlag(NetworkManager::Setting::NotSaved)) { passwordField->setPasswordOption(PasswordField::AlwaysAsk); } else { passwordField->setPasswordOption(PasswordField::PasswordField::NotRequired); } } NetworkManager::VpnSetting::Ptr OpenVpnAdvancedWidget::setting() const { NMStringMap data; NMStringMap secretData; // optional settings if (m_ui->chkCustomPort->isChecked()) { data.insert(QLatin1String(NM_OPENVPN_KEY_PORT), QString::number(m_ui->sbCustomPort->value())); } if (m_ui->chkMtu->isChecked()) { data.insert(QLatin1String(NM_OPENVPN_KEY_TUNNEL_MTU), QString::number(m_ui->sbMtu->value())); } if (m_ui->chkCustomFragmentSize->isChecked() ) { data.insert(QLatin1String(NM_OPENVPN_KEY_FRAGMENT_SIZE), QString::number(m_ui->sbCustomFragmentSize->value())); } if (m_ui->chkUseCustomReneg->isChecked()) { data.insert(QLatin1String(NM_OPENVPN_KEY_RENEG_SECONDS), QString::number(m_ui->sbCustomReneg->value())); } data.insert(QLatin1String(NM_OPENVPN_KEY_PROTO_TCP), m_ui->chkUseTCP->isChecked() ? QLatin1String("yes") : QLatin1String("no")); if (m_ui->chkUseLZO->isChecked()) { switch (m_ui->cmbUseLZO->currentIndex()) { case 0: data.insert(QLatin1String(NM_OPENVPN_KEY_COMP_LZO), QLatin1String("no-by-default")); break; case 1: data.insert(QLatin1String(NM_OPENVPN_KEY_COMP_LZO), QLatin1String("yes")); break; case 2: data.insert(QLatin1String(NM_OPENVPN_KEY_COMP_LZO), QLatin1String("adaptive")); break; } } if (m_ui->chkUseVirtualDeviceType->isChecked()) { data.insert(QLatin1String(NM_OPENVPN_KEY_DEV_TYPE), m_ui->cmbDeviceType->currentIndex() == 0 ? QLatin1String("tun") : QLatin1String("tap")); } if (m_ui->chkUseVirtualDeviceName->isChecked()) { data.insert(QLatin1String(NM_OPENVPN_KEY_DEV), m_ui->leVirtualDeviceName->text()); } data.insert(QLatin1String(NM_OPENVPN_KEY_MSSFIX), m_ui->chkMssRestrict->isChecked() ? QLatin1String("yes") : QLatin1String("no")); data.insert(QLatin1String(NM_OPENVPN_KEY_REMOTE_RANDOM), m_ui->chkRandRemHosts->isChecked() ? QLatin1String("yes") : QLatin1String("no")); data.insert(QLatin1String(NM_OPENVPN_KEY_TUN_IPV6), m_ui->chkIpv6TunLink->isChecked() ? QLatin1String("yes") : QLatin1String("no")); if (m_ui->chkPingInterval->isChecked()) { data.insert(QLatin1String(NM_OPENVPN_KEY_PING), QString::number(m_ui->sbPingInterval->value())); } if (m_ui->chkSpecifyExitRestartPing->isChecked()) { if (m_ui->cbSpecifyExitRestartPing->currentIndex() == 0) { // Exit data.insert(QLatin1String(NM_OPENVPN_KEY_PING_EXIT), QString::number(m_ui->sbSpecifyExitRestartPing->value())); } else { // Restart data.insert(QLatin1String(NM_OPENVPN_KEY_PING_RESTART), QString::number(m_ui->sbSpecifyExitRestartPing->value())); } } data.insert(QLatin1String(NM_OPENVPN_KEY_FLOAT), m_ui->chkAcceptAuthenticatedPackets->isChecked() ? QLatin1String("yes") : QLatin1String("no")); if (m_ui->chkMaxRoutes->isChecked()) { data.insert(QLatin1String(NM_OPENVPN_KEY_MAX_ROUTES), QString::number(m_ui->sbMaxRoutes->value())); } // Optional Security switch (m_ui->cboHmac->currentIndex()) { case Private::EnumHashingAlgorithms::Default: break; case Private::EnumHashingAlgorithms::None: data.insert(QLatin1String(NM_OPENVPN_KEY_AUTH), QLatin1String(NM_OPENVPN_AUTH_NONE)); break; case Private::EnumHashingAlgorithms::Md4: data.insert(QLatin1String(NM_OPENVPN_KEY_AUTH), QLatin1String(NM_OPENVPN_AUTH_RSA_MD4)); break; case Private::EnumHashingAlgorithms::Md5: data.insert(QLatin1String(NM_OPENVPN_KEY_AUTH), QLatin1String(NM_OPENVPN_AUTH_MD5)); break; case Private::EnumHashingAlgorithms::Sha1: data.insert(QLatin1String(NM_OPENVPN_KEY_AUTH), QLatin1String(NM_OPENVPN_AUTH_SHA1)); break; case Private::EnumHashingAlgorithms::Sha224: data.insert(QLatin1String(NM_OPENVPN_KEY_AUTH), QLatin1String(NM_OPENVPN_AUTH_SHA224)); break; case Private::EnumHashingAlgorithms::Sha256: data.insert(QLatin1String(NM_OPENVPN_KEY_AUTH), QLatin1String(NM_OPENVPN_AUTH_SHA256)); break; case Private::EnumHashingAlgorithms::Sha384: data.insert(QLatin1String(NM_OPENVPN_KEY_AUTH), QLatin1String(NM_OPENVPN_AUTH_SHA384)); break; case Private::EnumHashingAlgorithms::Sha512: data.insert(QLatin1String(NM_OPENVPN_KEY_AUTH), QLatin1String(NM_OPENVPN_AUTH_SHA512)); break; case Private::EnumHashingAlgorithms::Ripemd160: data.insert(QLatin1String(NM_OPENVPN_KEY_AUTH), QLatin1String(NM_OPENVPN_AUTH_RIPEMD160)); break; } if (m_ui->chkUseCustomCipherKey->isChecked()) { data.insert(QLatin1String(NM_OPENVPN_KEY_KEYSIZE), QString::number(m_ui->sbCustomCipherKey->value())); } if (m_ui->cboCipher->currentIndex() != 0) { data.insert(QLatin1String(NM_OPENVPN_KEY_CIPHER), m_ui->cboCipher->currentText()); } // optional tls authentication switch (m_ui->cbCertCheck->currentIndex()) { case CertCheckType::DontVerify: break; case CertCheckType::VerifyWholeSubjectExactly: data.insert(QLatin1String(NM_OPENVPN_KEY_VERIFY_X509_NAME), QStringLiteral("%1:%2").arg(NM_OPENVPN_VERIFY_X509_NAME_TYPE_SUBJECT).arg(m_ui->subjectMatch->text())); break; case CertCheckType::VerifyNameExactly: data.insert(QLatin1String(NM_OPENVPN_KEY_VERIFY_X509_NAME), QStringLiteral("%1:%2").arg(NM_OPENVPN_VERIFY_X509_NAME_TYPE_NAME).arg(m_ui->subjectMatch->text())); break; case CertCheckType::VerifyNameByPrefix: data.insert(QLatin1String(NM_OPENVPN_KEY_VERIFY_X509_NAME), QStringLiteral("%1:%2").arg(NM_OPENVPN_VERIFY_X509_NAME_TYPE_NAME_PREFIX).arg(m_ui->subjectMatch->text())); break; case CertCheckType::VerifySubjectPartially: data.insert(QLatin1String(NM_OPENVPN_KEY_TLS_REMOTE), m_ui->subjectMatch->text()); break; } if (m_ui->chkRemoteCertTls->isChecked()) { if (m_ui->cmbRemoteCertTls->currentIndex() == 0) { data.insert(QLatin1String(NM_OPENVPN_KEY_REMOTE_CERT_TLS), NM_OPENVPN_REM_CERT_TLS_SERVER); } else { data.insert(QLatin1String(NM_OPENVPN_KEY_REMOTE_CERT_TLS), NM_OPENVPN_REM_CERT_TLS_CLIENT); } } if (m_ui->chkNsCertType->isChecked()) { if (m_ui->cmbNsCertType->currentIndex() == 0) { data.insert(QLatin1String(NM_OPENVPN_KEY_NS_CERT_TYPE), NM_OPENVPN_NS_CERT_TYPE_SERVER); } else { data.insert(QLatin1String(NM_OPENVPN_KEY_NS_CERT_TYPE), NM_OPENVPN_NS_CERT_TYPE_CLIENT); } } if (m_ui->cboTLSMode->currentIndex() == 1) { // TLS-Auth QUrl tlsAuthKeyUrl = m_ui->kurlTlsAuthKey->url(); if (!tlsAuthKeyUrl.isEmpty()) { data.insert(QLatin1String(NM_OPENVPN_KEY_TA), tlsAuthKeyUrl.path()); } if (m_ui->cboDirection->currentIndex() > 0) { data.insert(QLatin1String(NM_OPENVPN_KEY_TA_DIR), QString::number(m_ui->cboDirection->currentIndex() - 1)); } } else if (m_ui->cboTLSMode->currentIndex() == 2) { // TLS-Crypt QUrl tlsCryptKeyUrl = m_ui->kurlTlsAuthKey->url(); if (!tlsCryptKeyUrl.isEmpty()) { data.insert(QLatin1String(NM_OPENVPN_KEY_TLS_CRYPT), tlsCryptKeyUrl.path()); } } // Proxies switch (m_ui->cmbProxyType->currentIndex()) { case Private::EnumProxyType::NotRequired: break; case Private::EnumProxyType::HTTP: data.insert(QLatin1String(NM_OPENVPN_KEY_PROXY_TYPE), QLatin1String("http")); data.insert(QLatin1String(NM_OPENVPN_KEY_PROXY_SERVER), m_ui->proxyServerAddress->text()); data.insert(QLatin1String(NM_OPENVPN_KEY_PROXY_PORT), QString::number(m_ui->sbProxyPort->value())); data.insert(QLatin1String(NM_OPENVPN_KEY_PROXY_RETRY), m_ui->chkProxyRetry->isChecked() ? QLatin1String("yes") : QLatin1String("no")); if (!m_ui->proxyUsername->text().isEmpty()) { data.insert(QLatin1String(NM_OPENVPN_KEY_HTTP_PROXY_USERNAME), m_ui->proxyUsername->text()); secretData.insert(QLatin1String(NM_OPENVPN_KEY_HTTP_PROXY_PASSWORD), m_ui->proxyPassword->text()); handleOnePasswordType(m_ui->proxyPassword, QLatin1String(NM_OPENVPN_KEY_HTTP_PROXY_PASSWORD"-flags"), data); } break; case Private::EnumProxyType::SOCKS: data.insert(QLatin1String(NM_OPENVPN_KEY_PROXY_TYPE), QLatin1String("socks")); data.insert(QLatin1String(NM_OPENVPN_KEY_PROXY_SERVER), m_ui->proxyServerAddress->text()); data.insert(QLatin1String(NM_OPENVPN_KEY_PROXY_PORT), QString::number(m_ui->sbProxyPort->value())); data.insert(QLatin1String(NM_OPENVPN_KEY_PROXY_RETRY), m_ui->chkProxyRetry->isChecked() ? QLatin1String("yes") : QLatin1String("no")); break; } d->setting->setData(data); d->setting->setSecrets(secretData); return d->setting; } void OpenVpnAdvancedWidget::certCheckTypeChanged(int type) { if (type == CertCheckType::DontVerify) { m_ui->lbSubjectMatch->setEnabled(false); m_ui->subjectMatch->setEnabled(false); } else { m_ui->lbSubjectMatch->setEnabled(true); m_ui->subjectMatch->setEnabled(true); } } void OpenVpnAdvancedWidget::proxyTypeChanged(int type) { switch (type) { case Private::EnumProxyType::NotRequired: m_ui->proxyServerAddress->setEnabled(false); m_ui->sbProxyPort->setEnabled(false); m_ui->chkProxyRetry->setEnabled(false); m_ui->proxyUsername->setEnabled(false); m_ui->proxyPassword->setEnabled(false); break; case Private::EnumProxyType::HTTP: m_ui->proxyServerAddress->setEnabled(true); m_ui->sbProxyPort->setEnabled(true); m_ui->chkProxyRetry->setEnabled(true); m_ui->proxyUsername->setEnabled(true); m_ui->proxyPassword->setEnabled(true); break; case Private::EnumProxyType::SOCKS: m_ui->proxyServerAddress->setEnabled(true); m_ui->sbProxyPort->setEnabled(true); m_ui->chkProxyRetry->setEnabled(true); m_ui->proxyUsername->setEnabled(false); m_ui->proxyPassword->setEnabled(false); break; } } void OpenVpnAdvancedWidget::handleOnePasswordType(const PasswordField *passwordField, const QString & key, NMStringMap & data) const { const PasswordField::PasswordOption option = passwordField->passwordOption(); switch (option) { case PasswordField::StoreForAllUsers: data.insert(key, QString::number(NetworkManager::Setting::None)); break; case PasswordField::StoreForUser: data.insert(key, QString::number(NetworkManager::Setting::AgentOwned)); break; case PasswordField::AlwaysAsk: data.insert(key, QString::number(NetworkManager::Setting::NotSaved)); break; case PasswordField::NotRequired: data.insert(key, QString::number(NetworkManager::Setting::NotRequired)); break; } } diff --git a/vpn/openvpn/openvpnadvancedwidget.h b/vpn/openvpn/openvpnadvancedwidget.h index 51a289e9..c25fd934 100644 --- a/vpn/openvpn/openvpnadvancedwidget.h +++ b/vpn/openvpn/openvpnadvancedwidget.h @@ -1,77 +1,77 @@ /* Copyright 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_OPENVPN_ADVANCED_WIDGET_H #define PLASMA_NM_OPENVPN_ADVANCED_WIDGET_H #include "passwordfield.h" #include #include #include namespace Ui { class OpenVpnAdvancedWidget; } class QLineEdit; class OpenVpnAdvancedWidget : public QDialog { Q_OBJECT enum CertCheckType { DontVerify = 0, VerifyWholeSubjectExactly, VerifyNameExactly, VerifyNameByPrefix, VerifySubjectPartially }; public: - explicit OpenVpnAdvancedWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0); - ~OpenVpnAdvancedWidget(); + explicit OpenVpnAdvancedWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr); + ~OpenVpnAdvancedWidget() override; void init(); NetworkManager::VpnSetting::Ptr setting() const; private Q_SLOTS: void gotOpenVpnCipherOutput(); void openVpnCipherError(QProcess::ProcessError); void openVpnCipherFinished(int, QProcess::ExitStatus); void gotOpenVpnVersionOutput(); void openVpnVersionError(QProcess::ProcessError); void openVpnVersionFinished(int, QProcess::ExitStatus); void certCheckTypeChanged(int); void proxyTypeChanged(int); private: int compareVersion(const int x, const int y, const int z) const; void disableLegacySubjectMatch(); void loadConfig(); void fillOnePasswordCombo(PasswordField *passwordField, NetworkManager::Setting::SecretFlags type); void handleOnePasswordType(const PasswordField *passwordField, const QString &key, NMStringMap &data) const; Ui::OpenVpnAdvancedWidget *m_ui; class Private; Private *const d; }; #endif // PLASMA_NM_OPENVPN_ADVANCED_WIDGET_H diff --git a/vpn/openvpn/openvpnauth.h b/vpn/openvpn/openvpnauth.h index 3ba10aea..9fa6c3cb 100644 --- a/vpn/openvpn/openvpnauth.h +++ b/vpn/openvpn/openvpnauth.h @@ -1,45 +1,45 @@ /* Copyright 2011 Ilia Kats Copyright 2013 Lukáš Tinkl 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef OPENVPNAUTH_H #define OPENVPNAUTH_H #include #include "settingwidget.h" class OpenVpnAuthWidgetPrivate; class OpenVpnAuthWidget : public SettingWidget { Q_OBJECT Q_DECLARE_PRIVATE(OpenVpnAuthWidget) public: - explicit OpenVpnAuthWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0); - ~OpenVpnAuthWidget(); + explicit OpenVpnAuthWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr); + ~OpenVpnAuthWidget() override; virtual void readSecrets(); - virtual QVariantMap setting() const; + QVariantMap setting() const override; private: OpenVpnAuthWidgetPrivate *const d_ptr; }; #endif // OPENVPNAUTH_H diff --git a/vpn/openvpn/openvpnwidget.h b/vpn/openvpn/openvpnwidget.h index 7f1cf421..f3e7b11b 100644 --- a/vpn/openvpn/openvpnwidget.h +++ b/vpn/openvpn/openvpnwidget.h @@ -1,62 +1,62 @@ /* Copyright 2008 Will Stephenson Copyright 2013 Lukáš Tinkl 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef OPENVPNWIDGET_H #define OPENVPNWIDGET_H #include "settingwidget.h" #include #include "ui_openvpn.h" #include class QUrl; class QLineEdit; class OpenVpnSettingWidget : public SettingWidget { Q_OBJECT public: - explicit OpenVpnSettingWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0); - ~OpenVpnSettingWidget(); + explicit OpenVpnSettingWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr); + ~OpenVpnSettingWidget() override; - void loadConfig(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; - void loadSecrets(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; + void loadSecrets(const NetworkManager::Setting::Ptr &setting) override; - QVariantMap setting() const; + QVariantMap setting() const override; - virtual bool isValid() const; + bool isValid() const override; private Q_SLOTS: void updateStartDir(const QUrl &); void showAdvanced(); private: class Private; Private *d; void setPasswordType(QLineEdit *, int); void fillOnePasswordCombo(PasswordField *, NetworkManager::Setting::SecretFlags); void handleOnePasswordType(const PasswordField *, const QString &, NMStringMap &) const; }; #endif // OPENVPNWIDGET_H diff --git a/vpn/openvpn/plasmanetworkmanagement_openvpnui.desktop b/vpn/openvpn/plasmanetworkmanagement_openvpnui.desktop index b3c2fabc..99797711 100644 --- a/vpn/openvpn/plasmanetworkmanagement_openvpnui.desktop +++ b/vpn/openvpn/plasmanetworkmanagement_openvpnui.desktop @@ -1,100 +1,102 @@ [Desktop Entry] Type=Service Icon= ServiceTypes=PlasmaNetworkManagement/VpnUiPlugin X-KDE-Library=plasmanetworkmanagement_openvpnui X-NetworkManager-Services=org.freedesktop.NetworkManager.openvpn X-KDE-PluginInfo-Author=Lukáš Tinkl X-KDE-PluginInfo-Email=lukas@kde.org X-KDE-PluginInfo-Name=plasmanetworkmanagement_openvpnui X-KDE-PluginInfo-Version=0.1 X-KDE-PluginInfo-Website= X-KDE-PluginInfo-Category=VPNService X-KDE-PluginInfo-Depends= X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=false Name=OpenVPN Name[ar]=OpenVPN Name[bg]=OpenVPN Name[bs]=OpenVPN Name[ca]=OpenVPN Name[ca@valencia]=OpenVPN Name[cs]=OpenVPN Name[da]=OpenVPN Name[de]=OpenVPN Name[el]=OpenVPN Name[en_GB]=OpenVPN Name[es]=OpenVPN Name[et]=OpenVPN Name[eu]=OpenVPN Name[fi]=OpenVPN Name[fr]=OpenVPN Name[gl]=OpenVPN Name[he]=OpenVPN Name[hu]=OpenVPN Name[ia]=OpenVPN +Name[id]=OpenVPN Name[it]=OpenVPN Name[ko]=OpenVPN Name[lt]=OpenVPN Name[nb]=OpenVPN Name[nds]=OpenVPN Name[nl]=OpenVPN Name[nn]=OpenVPN Name[pa]=OpenVPN Name[pl]=OpenVPN Name[pt]=OpenVPN Name[pt_BR]=OpenVPN Name[ro]=OpenVPN Name[ru]=OpenVPN Name[sk]=OpenVPN Name[sl]=OpenVPN Name[sr]=ОпенВПН Name[sr@ijekavian]=ОпенВПН Name[sr@ijekavianlatin]=OpenVPN Name[sr@latin]=OpenVPN Name[sv]=OpenVPN Name[tr]=OpenVPN Name[ug]=OpenVPN Name[uk]=OpenVPN Name[x-test]=xxOpenVPNxx Name[zh_CN]=OpenVPN Name[zh_TW]=OpenVPN Comment=Compatible with the OpenVPN server Comment[ar]=متوافق مع خادوم OpenVPN Comment[ca]=Compatible amb el servidor OpenVPN Comment[ca@valencia]=Compatible amb el servidor OpenVPN Comment[da]=Kompatibel med OpenVPN-serveren Comment[de]=Mit dem OpenVPN-Server kompatibel Comment[el]=Συμβατό με τον διακομιστή OpenVPN Comment[en_GB]=Compatible with the OpenVPN server Comment[es]=Compatible con el servidor de OpenVPN Comment[et]=Ühildub OpenVPN-serveritega Comment[eu]=OpenVPN zerbitzariarekin bateragarria Comment[fi]=Yhteensopiva OpenVPN-palvelimen kanssa Comment[fr]=Compatible avec le serveur OpenVPN Comment[gl]=Compatíbel con servidores OpenVPN. Comment[he]=תואימות עם שרתי OpenVPN Comment[hu]=Kompatibilis az OpenVPN kiszolgálóval +Comment[id]=Kompatibel dengan server OpenVPN Comment[it]=Compatibile con il server OpenVPN Comment[ko]=OpenVPN 서버와 호환됨 Comment[lt]=Suderinamas su OpenVPN serveriu Comment[nl]=Compatibel met de OpenVPN-server Comment[nn]=Kompatibel med OpenVPN-tenaren Comment[pa]=OpenVPN ਸਰਵਰ ਲਈ ਢੁਕਵਾਂ Comment[pl]=Zgodny z serwerem OpenVPN Comment[pt]=Compatível com o servidor OpenVPN Comment[pt_BR]=Compatível com o servidor OpenVPN Comment[ru]=Совместимая с сервером OpenVPN Comment[sk]=Kompatibilné s OpenVPN serverom Comment[sl]=Združljiv s strežnikom OpenVPN Comment[sr]=Сагласно са сервером ОпенВПН‑а Comment[sr@ijekavian]=Сагласно са сервером ОпенВПН‑а Comment[sr@ijekavianlatin]=Saglasno sa serverom OpenVPN‑a Comment[sr@latin]=Saglasno sa serverom OpenVPN‑a Comment[sv]=Kompatibel med OpenVPN-server Comment[tr]=OpenVPN sunucusuyla uyumlu Comment[uk]=Сумісний із сервером OpenVPN Comment[x-test]=xxCompatible with the OpenVPN serverxx Comment[zh_CN]=兼容 OpenVPN 服务器 Comment[zh_TW]=與 OpenVPN 伺服器相容 diff --git a/vpn/pptp/CMakeLists.txt b/vpn/pptp/CMakeLists.txt index 5fed78ec..96b1d35c 100644 --- a/vpn/pptp/CMakeLists.txt +++ b/vpn/pptp/CMakeLists.txt @@ -1,32 +1,25 @@ add_definitions(-DTRANSLATION_DOMAIN=\"plasmanetworkmanagement_pptpui\") set(pptp_SRCS pptp.cpp pptpwidget.cpp pptpauth.cpp ) ki18n_wrap_ui(pptp_SRCS pptpprop.ui pptpadvanced.ui pptpauth.ui) add_library(plasmanetworkmanagement_pptpui ${pptp_SRCS}) kcoreaddons_desktop_to_json(plasmanetworkmanagement_pptpui plasmanetworkmanagement_pptpui.desktop) target_link_libraries(plasmanetworkmanagement_pptpui plasmanm_internal plasmanm_editor - Qt5::Widgets - Qt5::Network - Qt5::DBus - KF5::NetworkManagerQt - KF5::Service - KF5::Completion KF5::I18n KF5::WidgetsAddons - KF5::KIOWidgets KF5::CoreAddons ) -install(TARGETS plasmanetworkmanagement_pptpui DESTINATION ${PLUGIN_INSTALL_DIR}) +install(TARGETS plasmanetworkmanagement_pptpui DESTINATION ${KDE_INSTALL_PLUGINDIR}) -install(FILES plasmanetworkmanagement_pptpui.desktop DESTINATION ${SERVICES_INSTALL_DIR}) +install(FILES plasmanetworkmanagement_pptpui.desktop DESTINATION ${KDE_INSTALL_KSERVICES5DIR}) diff --git a/vpn/pptp/plasmanetworkmanagement_pptpui.desktop b/vpn/pptp/plasmanetworkmanagement_pptpui.desktop index e4f46bf3..2610286b 100644 --- a/vpn/pptp/plasmanetworkmanagement_pptpui.desktop +++ b/vpn/pptp/plasmanetworkmanagement_pptpui.desktop @@ -1,89 +1,91 @@ [Desktop Entry] Type=Service Icon= ServiceTypes=PlasmaNetworkManagement/VpnUiPlugin X-KDE-Library=plasmanetworkmanagement_pptpui X-NetworkManager-Services=org.freedesktop.NetworkManager.pptp X-KDE-PluginInfo-Author=Lukáš Tinkl X-KDE-PluginInfo-Email=ltinkl@redhat.com X-KDE-PluginInfo-Name=plasmanetworkmanagement_pptpui X-KDE-PluginInfo-Version=0.1 X-KDE-PluginInfo-Website= X-KDE-PluginInfo-Category=VPNService X-KDE-PluginInfo-Depends= X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=false Name=Point-to-Point Tunneling Protocol (PPTP) Name[ca]=Protocol per crear túnels Punt-a-Punt (PPTP) Name[ca@valencia]=Protocol per crear túnels Punt-a-Punt (PPTP) Name[da]=Point-to-Point tunneling-protokol (PPTP) Name[de]=Point-to-Point-Tunnel-Protokoll (PPTP) Name[el]=Πρωτόκολλο διοχέτευσης σημείου προς σημείο (PPTP) Name[en_GB]=Point-to-Point Tunneling Protocol (PPTP) Name[es]=Protocolo de túneles punto a punto (PPTP) Name[et]=Point-to-Point Tunneling Protocol (PPTP) Name[eu]=Puntutik punturako tunel-protokoloa (PPTP) Name[fi]=Point-to-Point-tunnelointiyhteyskäytäntö (PPTP) Name[fr]=Protocole de tunnel point à point (PPTP) Name[gl]=Protocolo de canalización punto a punto (PPTP) Name[he]=Point-to-Point Tunneling Protocol (PPTP) Name[hu]=Point-to-Point Tunneling Protocol (PPTP) +Name[id]=Point-to-Point Tunneling Protocol (PPTP) Name[it]=Point-to-Point Tunneling Protocol (PPTP) Name[ko]=지점 대 지점 터널링 프로토콜(PPTP) Name[nl]=Point-to-Point Tunneling Protocol (PPTP) Name[nn]=Point-to-Point Tunneling Protocol (PPTP) Name[pa]=ਪੁਆਇੰਟ-ਟੂ-ਪੁਆਇੰਟ ਟਨਲਿੰਗ ਪਰੋਟੋਕਾਲ (PPTP) Name[pl]=Protokół tunelujący punkt-do-punktu (PPTP) Name[pt]=Protocolo de Túneis Ponto-a-Ponto (PPTP) Name[pt_BR]=Point-to-Point Tunneling Protocol (PPTP) Name[ru]=Туннельный протокол типа точка-точка (PPTP) Name[sk]=Point-to-Point Tunneling Protocol (PPTP) Name[sl]=Protokol za tuneliranje od točke do točke (PPTP) Name[sr]=ППТП (тунелски протокол тачка–тачка) Name[sr@ijekavian]=ППТП (тунелски протокол тачка–тачка) Name[sr@ijekavianlatin]=PPTP (tunelski protokol tačka–tačka) Name[sr@latin]=PPTP (tunelski protokol tačka–tačka) Name[sv]=Punkt-till-punkt tunnelprotkoll (PPTP) Name[tr]=Noktadan Noktaya Tünel Protokolü (PPTP) Name[uk]=Протокол тунелювання точка-до-точки (PPTP) Name[x-test]=xxPoint-to-Point Tunneling Protocol (PPTP)xx Name[zh_CN]=点到点隧道协议 (PPTP) Name[zh_TW]=點對點通道協定 (PPTP) Comment=Compatible with Microsoft and other PPTP VPN servers Comment[ar]=متوافق مع «مايكروسوفت» وخواديم PPTP VPN الأخرى Comment[ca]=Compatible amb Microsoft i altres servidors VPN sobre PPTP Comment[ca@valencia]=Compatible amb Microsoft i altres servidors VPN sobre PPTP Comment[da]=Kompatibel med Microsoft og andre PPTP VPN-servere Comment[de]=Mit PPTP-VPN-Servern von Microsoft und anderen kompatibel Comment[el]=Συμβατό με διακομιστές Microsoft και άλλους διακομιστές PPTP VPN Comment[en_GB]=Compatible with Microsoft and other PPTP VPN servers Comment[es]=Compatible con Microsoft y otros servidores PPTP VPN Comment[et]=Ühildub Microsofti ja teiste PPTP VPN-serveritega Comment[eu]=Microsoft eta beste PPTP VPN zerbitzari batzuekin bateragarria Comment[fi]=Yhteensopiva Microsoftin ja muiden PPTP-VPN-palvelinten kanssa Comment[fr]=Compatible avec les serveurs Microsoft et autres VPN PPTP Comment[gl]=Compatíbel con servidores de VPN de Microsoft e outros servidores de VPN que usen PPTP. Comment[he]=תאימות עם שרתי מיקרוסופט המשתמשים ב־PPTP VPN Comment[hu]=Kompatibilis a Microsoft és más PPTP VPN kiszolgálókkal +Comment[id]=Kompatibel dengan server Microsoft dan server VPN PPTP lainnya Comment[it]=Compatibile con Microsoft e altri server VPN PPTP Comment[ko]=Microsoft 및 기타 PPTP VPN 서버와 호환됨 Comment[lt]=Suderinamas su Microsoft ir kitais PPTP VPN serveriais Comment[nl]=Compatibel met Microsoft en andere PPTP VPN servers Comment[nn]=Kompatibel med Microsoft og andre PPTP VPN-tenarar Comment[pa]=ਮਾਈਕਰੋਸਾਫਟ ਅਤੇ ਹੋਰ PPTP VPN ਸਰਵਰਾਂ ਲਈ ਢੁਕਵਾਂ Comment[pl]=Zgodny z serwerami VPN Microsoft-u i innymi PPTP Comment[pt]=Compatível com os servidores de VPN PPTP da Microsoft e outros Comment[pt_BR]=Compatível com servidores VPN PPTP da Microsoft e outros Comment[ru]=Совместимая с серверами PPTP от Microsoft и другими Comment[sk]=Kompatibilné s Microsoft a inými PPTP VPN servermi Comment[sl]=Združljiv z Microsoftovimi in drugimi PPTP strežniki VPN Comment[sr]=Сагласно са Мајкрософтовим и другим ППТП ВПН серверима Comment[sr@ijekavian]=Сагласно са Мајкрософтовим и другим ППТП ВПН серверима Comment[sr@ijekavianlatin]=Saglasno sa Microsoftovim i drugim PPTP VPN serverima Comment[sr@latin]=Saglasno sa Microsoftovim i drugim PPTP VPN serverima Comment[sv]=Kompatibel med Microsoft och andra PPTP VPN-servrar Comment[tr]=Microsoft ve diğer PPTP VPN sunucuları ile uyumlu Comment[uk]=Сумісні з Microsoft та іншими серверами VPN PPTP Comment[x-test]=xxCompatible with Microsoft and other PPTP VPN serversxx Comment[zh_CN]=兼容 Microsoft 和其他 PPTP VPN 服务器 Comment[zh_TW]=與微軟還有其他 PPTP VPN 伺服器相容 diff --git a/vpn/pptp/pptp.h b/vpn/pptp/pptp.h index 9f9f11b9..e6d28762 100644 --- a/vpn/pptp/pptp.h +++ b/vpn/pptp/pptp.h @@ -1,44 +1,44 @@ /* Copyright 2009 Will Stephenson Copyright 2013 Lukas Tinkl 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef PLASMA_NM_PPTP_H #define PLASMA_NM_PPTP_H #include "vpnuiplugin.h" #include class Q_DECL_EXPORT PptpUiPlugin : public VpnUiPlugin { Q_OBJECT public: - explicit PptpUiPlugin(QObject * parent = 0, const QVariantList& = QVariantList()); - virtual ~PptpUiPlugin(); - virtual SettingWidget * widget(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = 0); - virtual SettingWidget * askUser(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = 0); - - QString suggestedFileName(const NetworkManager::ConnectionSettings::Ptr &connection) const; - QString supportedFileExtensions() const; - NMVariantMapMap importConnectionSettings(const QString &fileName); - bool exportConnectionSettings(const NetworkManager::ConnectionSettings::Ptr &connection, const QString &fileName); + explicit PptpUiPlugin(QObject * parent = nullptr, const QVariantList& = QVariantList()); + ~PptpUiPlugin() override; + SettingWidget * widget(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = nullptr) override; + SettingWidget * askUser(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = nullptr) override; + + QString suggestedFileName(const NetworkManager::ConnectionSettings::Ptr &connection) const override; + QString supportedFileExtensions() const override; + NMVariantMapMap importConnectionSettings(const QString &fileName) override; + bool exportConnectionSettings(const NetworkManager::ConnectionSettings::Ptr &connection, const QString &fileName) override; }; #endif // PLASMA_NM_PPTP_H diff --git a/vpn/pptp/pptpauth.h b/vpn/pptp/pptpauth.h index 2e7ac7a7..dc0dd2a8 100644 --- a/vpn/pptp/pptpauth.h +++ b/vpn/pptp/pptpauth.h @@ -1,45 +1,45 @@ /* Copyright 2011 Ilia Kats Copyright 2013 Lukáš Tinkl 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef PPTPAUTH_H #define PPTPAUTH_H #include #include "settingwidget.h" class PptpAuthWidgetPrivate; class PptpAuthWidget : public SettingWidget { Q_OBJECT Q_DECLARE_PRIVATE(PptpAuthWidget) public: - explicit PptpAuthWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0); - ~PptpAuthWidget(); + explicit PptpAuthWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr); + ~PptpAuthWidget() override; - virtual QVariantMap setting() const; + QVariantMap setting() const override; private: PptpAuthWidgetPrivate *const d_ptr; }; #endif // PPTPAUTH_H diff --git a/vpn/pptp/pptpwidget.cpp b/vpn/pptp/pptpwidget.cpp index ecca0666..556c4ab4 100644 --- a/vpn/pptp/pptpwidget.cpp +++ b/vpn/pptp/pptpwidget.cpp @@ -1,323 +1,323 @@ /* Copyright 2009 Will Stephenson Copyright 2009 Pavel Andreev Copyright 2013 Lukáš Tinkl 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include "pptpwidget.h" #include "ui_pptpprop.h" #include "ui_pptpadvanced.h" #include #include #include #include "nm-pptp-service.h" class PptpSettingWidgetPrivate { public: Ui_PptpProp ui; Ui_PptpAdvanced advUi; NetworkManager::VpnSetting::Ptr setting; QDialog *advancedDlg; QWidget *advancedWid; }; PptpSettingWidget::PptpSettingWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent) : SettingWidget(setting, parent) , d_ptr(new PptpSettingWidgetPrivate) { Q_D(PptpSettingWidget); d->ui.setupUi(this); d->setting = setting; d->ui.edt_password->setPasswordOptionsEnabled(true); d->ui.edt_password->setPasswordNotRequiredEnabled(true); connect(d->ui.btnAdvanced, &QPushButton::clicked, this, &PptpSettingWidget::doAdvancedDialog); d->advancedDlg = new QDialog(this); d->advancedWid = new QWidget(this); d->advUi.setupUi(d->advancedWid); QVBoxLayout * layout = new QVBoxLayout(d->advancedDlg); layout->addWidget(d->advancedWid); d->advancedDlg->setLayout(layout); QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel, d->advancedDlg); connect(buttons, &QDialogButtonBox::accepted, d->advancedDlg, &QDialog::accept); connect(buttons, &QDialogButtonBox::rejected, d->advancedDlg, &QDialog::reject); layout->addWidget(buttons); // Connect for setting check watchChangedSetting(); // Connect for validity check connect(d->ui.edt_gateway, &QLineEdit::textChanged, this, &PptpSettingWidget::slotWidgetChanged); KAcceleratorManager::manage(this); if (d->setting && !d->setting->isNull()) { loadConfig(d->setting); } } PptpSettingWidget::~PptpSettingWidget() { delete d_ptr; } void PptpSettingWidget::doAdvancedDialog() { Q_D(PptpSettingWidget); d->advancedDlg->setModal(true); d->advancedDlg->show(); } void PptpSettingWidget::loadConfig(const NetworkManager::Setting::Ptr &setting) { Q_D(PptpSettingWidget); Q_UNUSED(setting) // General settings const NMStringMap dataMap = d->setting->data(); // Authentication const QString sGateway = dataMap[NM_PPTP_KEY_GATEWAY]; if (!sGateway.isEmpty()) { d->ui.edt_gateway->setText(sGateway); } const QString sLogin = dataMap[NM_PPTP_KEY_USER]; if (!sLogin.isEmpty()) { d->ui.edt_login->setText(sLogin); } const QString sDomain = dataMap[NM_PPTP_KEY_DOMAIN]; if (!sDomain.isEmpty()) { d->ui.edt_ntDomain->setText(sDomain); } // Options below is belongs to "Advanced" dialog // Authentication options const QString yesString = QLatin1String("yes"); bool refuse_pap = (dataMap[NM_PPTP_KEY_REFUSE_PAP] == yesString); bool refuse_chap = (dataMap[NM_PPTP_KEY_REFUSE_CHAP] == yesString); bool refuse_mschap = (dataMap[NM_PPTP_KEY_REFUSE_MSCHAP] == yesString); bool refuse_mschapv2 = (dataMap[NM_PPTP_KEY_REFUSE_MSCHAPV2] == yesString); bool refuse_eap = (dataMap[NM_PPTP_KEY_REFUSE_EAP] == yesString); - QListWidgetItem * item = 0; + QListWidgetItem * item = nullptr; item = d->advUi.listWidget->item(0); // PAP item->setCheckState(refuse_pap ? Qt::Unchecked : Qt::Checked); item = d->advUi.listWidget->item(1); // CHAP item->setCheckState(refuse_chap ? Qt::Unchecked : Qt::Checked); item = d->advUi.listWidget->item(2); // MSCHAP item->setCheckState(refuse_mschap ? Qt::Unchecked : Qt::Checked); item = d->advUi.listWidget->item(3); // MSCHAPv2 item->setCheckState(refuse_mschapv2 ? Qt::Unchecked : Qt::Checked); item = d->advUi.listWidget->item(4); // EAP item->setCheckState(refuse_eap ? Qt::Unchecked : Qt::Checked); // Cryptography and compression const bool mppe = (dataMap[NM_PPTP_KEY_REQUIRE_MPPE] == yesString); const bool mppe40 = (dataMap[NM_PPTP_KEY_REQUIRE_MPPE_40] == yesString); const bool mppe128 = (dataMap[NM_PPTP_KEY_REQUIRE_MPPE_128] == yesString); const bool mppe_stateful = (dataMap[NM_PPTP_KEY_MPPE_STATEFUL] == yesString); if (mppe || mppe40 || mppe128) { // If MPPE is use d->advUi.gb_MPPE->setChecked(mppe || mppe40 || mppe128); if (mppe128) { d->advUi.cb_MPPECrypto->setCurrentIndex(1); // 128 bit } else if (mppe40) { d->advUi.cb_MPPECrypto->setCurrentIndex(2); // 40 bit } else { d->advUi.cb_MPPECrypto->setCurrentIndex(0); // Any } d->advUi.cb_statefulEncryption->setChecked(mppe_stateful); } const bool nobsd = (dataMap[NM_PPTP_KEY_NOBSDCOMP] == yesString); d->advUi.cb_BSD->setChecked(!nobsd); const bool nodeflate = (dataMap[NM_PPTP_KEY_NODEFLATE] == yesString); d->advUi.cb_deflate->setChecked(!nodeflate); const bool novjcomp = (dataMap[NM_PPTP_KEY_NO_VJ_COMP] == yesString); d->advUi.cb_TCPheaders->setChecked(!novjcomp); // Echo const int lcp_echo_interval = QString(dataMap[NM_PPTP_KEY_LCP_ECHO_INTERVAL]).toInt(); d->advUi.cb_sendEcho->setChecked(lcp_echo_interval > 0); // secrets const NetworkManager::Setting::SecretFlags type = (NetworkManager::Setting::SecretFlags)dataMap[NM_PPTP_KEY_PASSWORD"-flags"].toInt(); fillOnePasswordCombo(d->ui.edt_password, type); loadSecrets(setting); } void PptpSettingWidget::loadSecrets(const NetworkManager::Setting::Ptr &setting) { Q_D(PptpSettingWidget); NetworkManager::VpnSetting::Ptr vpnSetting = setting.staticCast(); if (vpnSetting) { const NMStringMap secrets = vpnSetting->secrets(); const QString keyPassword = secrets.value(QLatin1String(NM_PPTP_KEY_PASSWORD)); if (!keyPassword.isEmpty()) { d->ui.edt_password->setText(keyPassword); } } } QVariantMap PptpSettingWidget::setting() const { Q_D(const PptpSettingWidget); NetworkManager::VpnSetting setting; setting.setServiceType(QLatin1String(NM_DBUS_SERVICE_PPTP)); // save the main dialog's data in the setting // if the advanced dialog is dirty, save its data in the vpn setting too // NMStringMap data; NMStringMap secretData; data.insert(NM_PPTP_KEY_GATEWAY, d->ui.edt_gateway->text()); data.insert(NM_PPTP_KEY_USER, d->ui.edt_login->text()); if (!d->ui.edt_password->text().isEmpty()) { secretData.insert(QLatin1String(NM_PPTP_KEY_PASSWORD), d->ui.edt_password->text()); } handleOnePasswordType(d->ui.edt_password, NM_PPTP_KEY_PASSWORD"-flags", data); if (!d->ui.edt_ntDomain->text().isEmpty()) { data.insert(NM_PPTP_KEY_DOMAIN, d->ui.edt_ntDomain->text()); } // Advanced dialog settings // Authenfication options - QListWidgetItem * item = 0; + QListWidgetItem * item = nullptr; item = d->advUi.listWidget->item(0); // PAP const QString yesString = QLatin1String("yes"); if (item->checkState() == Qt::Unchecked) { data.insert(NM_PPTP_KEY_REFUSE_PAP, yesString); } item = d->advUi.listWidget->item(1); // CHAP if (item->checkState() == Qt::Unchecked) { data.insert(NM_PPTP_KEY_REFUSE_CHAP, yesString); } item = d->advUi.listWidget->item(2); // MSCHAP if (item->checkState() == Qt::Unchecked) { data.insert(NM_PPTP_KEY_REFUSE_MSCHAP, yesString); } item = d->advUi.listWidget->item(3); // MSCHAPv2 if (item->checkState() == Qt::Unchecked) { data.insert(NM_PPTP_KEY_REFUSE_MSCHAPV2, yesString); } item = d->advUi.listWidget->item(4); // EAP if (item->checkState() == Qt::Unchecked) { data.insert(NM_PPTP_KEY_REFUSE_EAP, yesString); } // Cryptography and compression if (d->advUi.gb_MPPE->isChecked()) { int index = d->advUi.cb_MPPECrypto->currentIndex(); switch (index) { case 0: data.insert(NM_PPTP_KEY_REQUIRE_MPPE, yesString); break; case 1: data.insert(NM_PPTP_KEY_REQUIRE_MPPE_128, yesString); break; case 2: data.insert(NM_PPTP_KEY_REQUIRE_MPPE_40, yesString); break; } if (d->advUi.cb_statefulEncryption->isChecked()) { data.insert(NM_PPTP_KEY_MPPE_STATEFUL, yesString); } } if (!d->advUi.cb_BSD->isChecked()) { data.insert(NM_PPTP_KEY_NOBSDCOMP, yesString); } if (!d->advUi.cb_deflate->isChecked()) { data.insert(NM_PPTP_KEY_NODEFLATE, yesString); } if (!d->advUi.cb_TCPheaders->isChecked()) { data.insert(NM_PPTP_KEY_NO_VJ_COMP, yesString); } // Echo if (d->advUi.cb_sendEcho->isChecked()) { data.insert(NM_PPTP_KEY_LCP_ECHO_FAILURE, "5"); data.insert(NM_PPTP_KEY_LCP_ECHO_INTERVAL, "30"); } // save it all setting.setData(data); setting.setSecrets(secretData); return setting.toMap(); } void PptpSettingWidget::fillOnePasswordCombo(PasswordField *passwordField, NetworkManager::Setting::SecretFlags type) { if (type.testFlag(NetworkManager::Setting::None)) { passwordField->setPasswordOption(PasswordField::StoreForAllUsers); } else if (type.testFlag(NetworkManager::Setting::AgentOwned)) { passwordField->setPasswordOption(PasswordField::StoreForUser); } else if (type.testFlag(NetworkManager::Setting::NotSaved)) { passwordField->setPasswordOption(PasswordField::AlwaysAsk); } else { passwordField->setPasswordOption(PasswordField::PasswordField::NotRequired); } } void PptpSettingWidget::handleOnePasswordType(const PasswordField *passwordField, const QString &key, NMStringMap &data) const { const PasswordField::PasswordOption option = passwordField->passwordOption(); switch (option) { case PasswordField::StoreForAllUsers: data.insert(key, QString::number(NetworkManager::Setting::None)); break; case PasswordField::StoreForUser: data.insert(key, QString::number(NetworkManager::Setting::AgentOwned)); break; case PasswordField::AlwaysAsk: data.insert(key, QString::number(NetworkManager::Setting::NotSaved)); break; case PasswordField::NotRequired: data.insert(key, QString::number(NetworkManager::Setting::NotRequired)); break; } } bool PptpSettingWidget::isValid() const { Q_D(const PptpSettingWidget); return !d->ui.edt_gateway->text().isEmpty(); } diff --git a/vpn/pptp/pptpwidget.h b/vpn/pptp/pptpwidget.h index ff96cdf5..5a065dbe 100644 --- a/vpn/pptp/pptpwidget.h +++ b/vpn/pptp/pptpwidget.h @@ -1,55 +1,55 @@ /* Copyright 2009 Will Stephenson Copyright 2013 Lukáš Tinkl 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef PPTPWIDGET_H #define PPTPWIDGET_H #include "passwordfield.h" #include "settingwidget.h" #include class PptpSettingWidgetPrivate; class PptpSettingWidget : public SettingWidget { Q_OBJECT Q_DECLARE_PRIVATE(PptpSettingWidget) public: - explicit PptpSettingWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0); - ~PptpSettingWidget(); + explicit PptpSettingWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr); + ~PptpSettingWidget() override; - void loadConfig(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; - void loadSecrets(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; + void loadSecrets(const NetworkManager::Setting::Ptr &setting) override; - virtual QVariantMap setting() const; - virtual bool isValid() const; + QVariantMap setting() const override; + bool isValid() const override; private Q_SLOTS: void doAdvancedDialog(); private: PptpSettingWidgetPrivate *const d_ptr; void fillOnePasswordCombo(PasswordField *, NetworkManager::Setting::SecretFlags); void handleOnePasswordType(const PasswordField *, const QString &, NMStringMap &) const; }; #endif // PPTPWIDGET_H diff --git a/vpn/ssh/CMakeLists.txt b/vpn/ssh/CMakeLists.txt index 1179fe0b..8a74e134 100644 --- a/vpn/ssh/CMakeLists.txt +++ b/vpn/ssh/CMakeLists.txt @@ -1,32 +1,26 @@ add_definitions(-DTRANSLATION_DOMAIN=\"plasmanetworkmanagement_sshui\") set(ssh_SRCS ssh.cpp sshwidget.cpp sshauth.cpp ) ki18n_wrap_ui(ssh_SRCS sshwidget.ui sshadvanced.ui sshauth.ui) add_library(plasmanetworkmanagement_sshui ${ssh_SRCS}) kcoreaddons_desktop_to_json(plasmanetworkmanagement_sshui plasmanetworkmanagement_sshui.desktop) target_link_libraries(plasmanetworkmanagement_sshui plasmanm_internal plasmanm_editor - Qt5::Widgets - Qt5::Network - Qt5::DBus - KF5::NetworkManagerQt - KF5::Service - KF5::Completion KF5::I18n KF5::WidgetsAddons KF5::KIOWidgets KF5::CoreAddons ) -install(TARGETS plasmanetworkmanagement_sshui DESTINATION ${PLUGIN_INSTALL_DIR}) +install(TARGETS plasmanetworkmanagement_sshui DESTINATION ${KDE_INSTALL_PLUGINDIR}) -install(FILES plasmanetworkmanagement_sshui.desktop DESTINATION ${SERVICES_INSTALL_DIR}) +install(FILES plasmanetworkmanagement_sshui.desktop DESTINATION ${KDE_INSTALL_KSERVICES5DIR}) diff --git a/vpn/ssh/plasmanetworkmanagement_sshui.desktop b/vpn/ssh/plasmanetworkmanagement_sshui.desktop index c285e5f2..b1cbddd5 100644 --- a/vpn/ssh/plasmanetworkmanagement_sshui.desktop +++ b/vpn/ssh/plasmanetworkmanagement_sshui.desktop @@ -1,92 +1,94 @@ [Desktop Entry] Type=Service Icon= ServiceTypes=PlasmaNetworkManagement/VpnUiPlugin X-KDE-Library=plasmanetworkmanagement_sshui X-NetworkManager-Services=org.freedesktop.NetworkManager.ssh X-KDE-PluginInfo-Author=Jan Grulich X-KDE-PluginInfo-Email=jgrulich@redhat.com X-KDE-PluginInfo-Name=plasmanetworkmanagement_sshui X-KDE-PluginInfo-Version=0.1 X-KDE-PluginInfo-Website= X-KDE-PluginInfo-Category=VPNService X-KDE-PluginInfo-Depends= X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=false Name=SSH Name[ca]=SSH Name[ca@valencia]=SSH Name[cs]=SSH Name[da]=SSH Name[de]=SSH Name[el]=SSH Name[en_GB]=SSH Name[es]=SSH Name[et]=SSH Name[eu]=SSH Name[fi]=SSH Name[fr]=SSH Name[gl]=SSH Name[he]=SSH Name[hu]=SSH +Name[id]=SSH Name[it]=SSH Name[ko]=SSH Name[lt]=SSH Name[nb]=SSH Name[nl]=SSH Name[nn]=SSH Name[pa]=SSH Name[pl]=SSH Name[pt]=SSH Name[pt_BR]=SSH Name[ru]=SSH Name[sk]=SSH Name[sl]=SSH Name[sr]=ССХ Name[sr@ijekavian]=ССХ Name[sr@ijekavianlatin]=SSH Name[sr@latin]=SSH Name[sv]=SSH Name[tr]=SSH Name[uk]=SSH Name[x-test]=xxSSHxx Name[zh_CN]=SSH Name[zh_TW]=SSH Comment=Compatible with the SSH server Comment[ar]=متوافق مع خادوم SSH Comment[ca]=Compatible amb el servidor SSH Comment[ca@valencia]=Compatible amb el servidor SSH Comment[da]=Kompatibel med SSH-serveren Comment[de]=Mit dem SSH-Server kompatibel Comment[el]=Συμβατό με τον διακομιστή SSH Comment[en_GB]=Compatible with the SSH server Comment[es]=Compatible con el servidor SSH Comment[et]=Ühildub SSH-serveritega Comment[eu]=SSH zerbitzariarekin bateragarria Comment[fi]=Yhteensopiva SSH-palvelimen kanssa Comment[fr]=Compatible avec le serveur SSH Comment[gl]=Compatíbel con servidores de SSH. Comment[he]=תאימות עם שרתי SSL Comment[hu]=Kompatibilis az SSH kiszolgálókkal +Comment[id]=Kompatibel dengan server SSH Comment[it]=Compatibile con il server SSH Comment[ko]=SSH 서버와 호환됨 Comment[lt]=Suderinamas su SSH serveriu Comment[nl]=Compatibel met de SSH-server Comment[nn]=Kompatibel med SSH-tenaren Comment[pa]=SSH ਸਰਵਰ ਲਈ ਢੁਕਵਾਂ Comment[pl]=Zgodny z serwerem SSH Comment[pt]=Compatível com o servidor SSH Comment[pt_BR]=Compatível com o servidor SSH Comment[ru]=Совместимая с сервером SSH Comment[sk]=Kompatibilné s SSH serverom Comment[sl]=Združljiv s strežnikom SSH Comment[sr]=Сагласно са ССХ сервером Comment[sr@ijekavian]=Сагласно са ССХ сервером Comment[sr@ijekavianlatin]=Saglasno sa SSH serverom Comment[sr@latin]=Saglasno sa SSH serverom Comment[sv]=Kompatibel med SSH-server Comment[tr]=SSH sunucusuyla uyumlu Comment[uk]=Сумісний з сервером SSH Comment[x-test]=xxCompatible with the SSH serverxx Comment[zh_CN]=兼容 SSH 服务器 Comment[zh_TW]=與 SSH 伺服器相容 diff --git a/vpn/ssh/ssh.h b/vpn/ssh/ssh.h index 639b44ff..d2f722a5 100644 --- a/vpn/ssh/ssh.h +++ b/vpn/ssh/ssh.h @@ -1,41 +1,41 @@ /* Copyright 2015 Jan Grulich 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef PLASMA_NM_SSH_H #define PLASMA_NM_SSH_H #include "vpnuiplugin.h" class Q_DECL_EXPORT SshUiPlugin : public VpnUiPlugin { Q_OBJECT public: - explicit SshUiPlugin(QObject * parent = 0, const QVariantList& = QVariantList()); - virtual ~SshUiPlugin(); - virtual SettingWidget * widget(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = 0); - virtual SettingWidget * askUser(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = 0); - virtual QString suggestedFileName(const NetworkManager::ConnectionSettings::Ptr &connection) const; - virtual QString supportedFileExtensions() const; - - virtual NMVariantMapMap importConnectionSettings(const QString &fileName); - virtual bool exportConnectionSettings(const NetworkManager::ConnectionSettings::Ptr &connection, const QString &fileName); + explicit SshUiPlugin(QObject * parent = nullptr, const QVariantList& = QVariantList()); + ~SshUiPlugin() override; + SettingWidget * widget(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = nullptr) override; + SettingWidget * askUser(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = nullptr) override; + QString suggestedFileName(const NetworkManager::ConnectionSettings::Ptr &connection) const override; + QString supportedFileExtensions() const override; + + NMVariantMapMap importConnectionSettings(const QString &fileName) override; + bool exportConnectionSettings(const NetworkManager::ConnectionSettings::Ptr &connection, const QString &fileName) override; }; #endif // PLASMA_NM_SSH_H diff --git a/vpn/ssh/sshauth.h b/vpn/ssh/sshauth.h index 220983e4..2c7ef5b6 100644 --- a/vpn/ssh/sshauth.h +++ b/vpn/ssh/sshauth.h @@ -1,45 +1,45 @@ /* Copyright 2015 Jan Grulich 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef SSH_AUTH_H #define SSH_AUTH_H #include "settingwidget.h" #include class SshAuthWidgetPrivate; class SshAuthWidget : public SettingWidget { Q_OBJECT Q_DECLARE_PRIVATE(SshAuthWidget) public: - explicit SshAuthWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0); - ~SshAuthWidget(); + explicit SshAuthWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr); + ~SshAuthWidget() override; - virtual QVariantMap setting() const; + QVariantMap setting() const override; private: SshAuthWidgetPrivate *const d_ptr; void acceptDialog(); }; #endif // SSH_AUTH_H diff --git a/vpn/ssh/sshwidget.cpp b/vpn/ssh/sshwidget.cpp index 1167777f..027a058a 100644 --- a/vpn/ssh/sshwidget.cpp +++ b/vpn/ssh/sshwidget.cpp @@ -1,394 +1,394 @@ /* Copyright 2015 Jan Grulich 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include "sshwidget.h" #include "ui_sshwidget.h" #include "ui_sshadvanced.h" #include "simpleipv4addressvalidator.h" #include "simpleipv6addressvalidator.h" #include #include #include #include "nm-ssh-service.h" class SshSettingWidgetPrivate { public: Ui_SshWidget ui; Ui_SshAdvanced advUi; NetworkManager::VpnSetting::Ptr setting; QDialog *advancedDlg; QWidget *advancedWid; }; SshSettingWidget::SshSettingWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent) : SettingWidget(setting, parent) , d_ptr(new SshSettingWidgetPrivate) { Q_D(SshSettingWidget); d->ui.setupUi(this); d->setting = setting; d->ui.le_password->setPasswordOptionsEnabled(true); - connect(d->ui.cmb_authType, static_cast(&QComboBox::currentIndexChanged), this, &SshSettingWidget::authTypeChanged); + connect(d->ui.cmb_authType, QOverload::of(&QComboBox::currentIndexChanged), this, &SshSettingWidget::authTypeChanged); connect(d->ui.btn_advancedOption, &QPushButton::clicked, this, &SshSettingWidget::doAdvancedDialog); d->advancedDlg = new QDialog(this); d->advancedDlg->setModal(true); d->advancedWid = new QWidget(this); d->advUi.setupUi(d->advancedWid); QVBoxLayout *layout = new QVBoxLayout(d->advancedDlg); layout->addWidget(d->advancedWid); d->advancedDlg->setLayout(layout); QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel, d->advancedDlg); connect(buttons, &QDialogButtonBox::accepted, d->advancedDlg, &QDialog::accept); connect(buttons, &QDialogButtonBox::rejected, d->advancedDlg, &QDialog::reject); layout->addWidget(buttons); // Connect for setting check watchChangedSetting(); // Connect for validity check connect(d->ui.le_gateway, &QLineEdit::textChanged, this, &SshSettingWidget::slotWidgetChanged); connect(d->ui.le_localIp, &QLineEdit::textChanged, this, &SshSettingWidget::slotWidgetChanged); connect(d->ui.le_netmask, &QLineEdit::textChanged, this, &SshSettingWidget::slotWidgetChanged); connect(d->ui.le_remoteIp, &QLineEdit::textChanged, this, &SshSettingWidget::slotWidgetChanged); SimpleIpV4AddressValidator *ipv4Validator = new SimpleIpV4AddressValidator(this); d->ui.le_localIp->setValidator(ipv4Validator); d->ui.le_remoteIp->setValidator(ipv4Validator); d->ui.le_netmask->setValidator(ipv4Validator); SimpleIpV6AddressValidator *ipv6Validator = new SimpleIpV6AddressValidator(this); d->ui.le_localIpv6->setValidator(ipv6Validator); d->ui.le_remoteIpv6->setValidator(ipv6Validator); d->ui.passwordWidget->setVisible(false); d->advUi.sb_useCustomGatewayPort->setValue(NM_SSH_DEFAULT_PORT); d->advUi.sb_useCustomTunnelMtu->setValue(NM_SSH_DEFAULT_MTU); d->advUi.le_extraSshOptions->setText(QLatin1String(NM_SSH_DEFAULT_EXTRA_OPTS)); d->advUi.sb_remoteDeviceNumber->setValue(NM_SSH_DEFAULT_REMOTE_DEV); d->advUi.le_remoteUsername->setText(QLatin1String(NM_SSH_DEFAULT_REMOTE_USERNAME)); KAcceleratorManager::manage(this); if (d->setting && !d->setting->isNull()) { loadConfig(d->setting); } } SshSettingWidget::~SshSettingWidget() { delete d_ptr; } void SshSettingWidget::loadConfig(const NetworkManager::Setting::Ptr &setting) { Q_D(SshSettingWidget); Q_UNUSED(setting) const NMStringMap dataMap = d->setting->data(); // General const QString gateway = dataMap[QLatin1String(NM_SSH_KEY_REMOTE)]; if (!gateway.isEmpty()) { d->ui.le_gateway->setText(gateway); } // Network settings const QString remoteIp = dataMap[QLatin1String(NM_SSH_KEY_REMOTE_IP)]; if (!remoteIp.isEmpty()) { d->ui.le_remoteIp->setText(remoteIp); } const QString localIp = dataMap[QLatin1String(NM_SSH_KEY_LOCAL_IP)]; if (!localIp.isEmpty()) { d->ui.le_localIp->setText(localIp); } const QString netmask = dataMap[QLatin1String(NM_SSH_KEY_NETMASK)]; if (!netmask.isEmpty()) { d->ui.le_netmask->setText(netmask); } // IPv6 network settings const bool ipv6Enabled = dataMap[QLatin1String(NM_SSH_KEY_IP_6)] == QLatin1String("yes"); d->ui.chk_useIpv6->setChecked(ipv6Enabled); if (ipv6Enabled) { const QString remoteIpv6 = dataMap[QLatin1String(NM_SSH_KEY_REMOTE_IP_6)]; if (!remoteIpv6.isEmpty()) { d->ui.le_remoteIpv6->setText(remoteIpv6); } const QString localIpv6 = dataMap[QLatin1String(NM_SSH_KEY_LOCAL_IP_6)]; if (!localIpv6.isEmpty()) { d->ui.le_localIpv6->setText(localIpv6); } const QString netmaskIpv6 = dataMap[QLatin1String(NM_SSH_KEY_NETMASK_6)]; if (!netmaskIpv6.isEmpty()) { d->ui.le_netmaskIpv6->setText(netmaskIpv6); } } // Authentication const QString sshAuthType = dataMap[QLatin1String(NM_SSH_KEY_AUTH_TYPE)]; if (sshAuthType == QLatin1String(NM_SSH_AUTH_TYPE_SSH_AGENT)) { d->ui.cmb_authType->setCurrentIndex(0); } else if (sshAuthType == QLatin1String(NM_SSH_AUTH_TYPE_PASSWORD)) { d->ui.cmb_authType->setCurrentIndex(1); const NetworkManager::Setting::SecretFlags type = (NetworkManager::Setting::SecretFlags)dataMap[NM_SSH_KEY_PASSWORD"-flags"].toInt(); fillOnePasswordCombo(d->ui.le_password, type); } else if (sshAuthType == QLatin1String(NM_SSH_AUTH_TYPE_KEY)) { d->ui.cmb_authType->setCurrentIndex(2); d->ui.kurl_sshKeyFile->setUrl(QUrl::fromLocalFile(dataMap[QLatin1String(NM_SSH_KEY_KEY_FILE)])); } // Options below is belongs to "Advanced" dialog const QString customGatewayPort = dataMap[QLatin1String(NM_SSH_KEY_PORT)]; if (!customGatewayPort.isEmpty()) { d->advUi.chk_useCustomGatewayPort->setChecked(true); d->advUi.sb_useCustomGatewayPort->setValue(customGatewayPort.toInt()); } const QString customMtu = dataMap[QLatin1String(NM_SSH_KEY_TUNNEL_MTU)]; if (!customMtu.isEmpty()) { d->advUi.chk_useCustomTunnelMtu->setChecked(true); d->advUi.sb_useCustomTunnelMtu->setValue(customMtu.toInt()); } const QString extraSshOptions = dataMap[QLatin1String(NM_SSH_KEY_EXTRA_OPTS)]; if (!extraSshOptions.isEmpty()) { d->advUi.chk_extraSshOptions->setChecked(true); d->advUi.le_extraSshOptions->setText(extraSshOptions); } const QString remoteDeviceNumber = dataMap[QLatin1String(NM_SSH_KEY_REMOTE_DEV)]; if (!remoteDeviceNumber.isEmpty()) { d->advUi.chk_remoteDeviceNumber->setChecked(true); d->advUi.sb_remoteDeviceNumber->setValue(remoteDeviceNumber.toInt()); } const QString useTapDevice = dataMap[QLatin1String(NM_SSH_KEY_TAP_DEV)]; if (!useTapDevice.isEmpty()) { if (useTapDevice == QLatin1String("yes")) { d->advUi.chk_useTapDevice->setChecked(true); } } const QString remoteUsername = dataMap[QLatin1String(NM_SSH_KEY_REMOTE_USERNAME)]; if (!remoteUsername.isEmpty()) { d->advUi.chk_remoteUsername->setChecked(true); d->advUi.le_remoteUsername->setText(remoteUsername); } const QString doNotReplaceDefaultRoute = dataMap[QLatin1String(NM_SSH_KEY_NO_DEFAULT_ROUTE)]; if (!doNotReplaceDefaultRoute.isEmpty()) { if (doNotReplaceDefaultRoute == QLatin1String("yes")) { d->advUi.chk_doNotReplaceDefaultRoute->setChecked(true); } } loadSecrets(setting); } void SshSettingWidget::loadSecrets(const NetworkManager::Setting::Ptr &setting) { Q_D(SshSettingWidget); NetworkManager::VpnSetting::Ptr vpnSetting = setting.staticCast(); if (vpnSetting) { const NMStringMap secrets = vpnSetting->secrets(); const QString keyPassword = secrets.value(NM_SSH_KEY_PASSWORD); if (!keyPassword.isEmpty()) { d->ui.le_password->setText(keyPassword); } } } QVariantMap SshSettingWidget::setting() const { Q_D(const SshSettingWidget); NetworkManager::VpnSetting setting; setting.setServiceType(QLatin1String(NM_DBUS_SERVICE_SSH)); NMStringMap data; NMStringMap secretData; data.insert(QLatin1String(NM_SSH_KEY_REMOTE), d->ui.le_gateway->text()); if (!d->ui.le_remoteIp->text().isEmpty()) { data.insert(QLatin1String(NM_SSH_KEY_REMOTE_IP), d->ui.le_remoteIp->text()); } if (!d->ui.le_localIp->text().isEmpty()) { data.insert(QLatin1String(NM_SSH_KEY_LOCAL_IP), d->ui.le_localIp->text()); } if (!d->ui.le_netmask->text().isEmpty()) { data.insert(QLatin1String(NM_SSH_KEY_NETMASK), d->ui.le_netmask->text()); } if (d->ui.chk_useIpv6->isChecked()) { data.insert(QLatin1String(NM_SSH_KEY_IP_6), QLatin1String("yes")); if (!d->ui.le_remoteIpv6->text().isEmpty()) { data.insert(QLatin1String(NM_SSH_KEY_REMOTE_IP_6), d->ui.le_remoteIpv6->text()); } if (!d->ui.le_localIpv6->text().isEmpty()) { data.insert(QLatin1String(NM_SSH_KEY_LOCAL_IP_6), d->ui.le_localIpv6->text()); } if (!d->ui.le_netmaskIpv6->text().isEmpty()) { data.insert(QLatin1String(NM_SSH_KEY_NETMASK_6), d->ui.le_netmaskIpv6->text()); } } switch (d->ui.cmb_authType->currentIndex()) { case 0: data.insert(QLatin1String(NM_SSH_KEY_AUTH_TYPE), QLatin1String(NM_SSH_AUTH_TYPE_SSH_AGENT)); break; case 1: data.insert(QLatin1String(NM_SSH_KEY_AUTH_TYPE), QLatin1String(NM_SSH_AUTH_TYPE_PASSWORD)); if (!d->ui.le_password->text().isEmpty()) { secretData.insert(QLatin1String(NM_SSH_KEY_PASSWORD), d->ui.le_password->text()); } handleOnePasswordType(d->ui.le_password, NM_SSH_KEY_PASSWORD"-flags", data); break; case 2: data.insert(QLatin1String(NM_SSH_KEY_AUTH_TYPE), QLatin1String(NM_SSH_AUTH_TYPE_KEY)); if (!d->ui.kurl_sshKeyFile->url().isEmpty()) { data.insert(QLatin1String(NM_SSH_KEY_KEY_FILE), d->ui.kurl_sshKeyFile->url().toLocalFile()); } break; } if (d->advUi.chk_useCustomGatewayPort->isChecked()) { data.insert(QLatin1String(NM_SSH_KEY_PORT), QString::number(d->advUi.sb_useCustomGatewayPort->value())); } if (d->advUi.chk_useCustomTunnelMtu->isChecked()) { data.insert(QLatin1String(NM_SSH_KEY_TUNNEL_MTU), QString::number(d->advUi.sb_useCustomTunnelMtu->value())); } if (d->advUi.chk_extraSshOptions->isChecked()) { data.insert(QLatin1String(NM_SSH_KEY_EXTRA_OPTS), d->advUi.le_extraSshOptions->text()); } if (d->advUi.chk_remoteDeviceNumber->isChecked()) { data.insert(QLatin1String(NM_SSH_KEY_REMOTE_DEV), QString::number(d->advUi.sb_remoteDeviceNumber->value())); } if (d->advUi.chk_useTapDevice->isChecked()) { data.insert(QLatin1String(NM_SSH_KEY_TAP_DEV), QLatin1String("yes")); } if (d->advUi.chk_remoteUsername->isChecked()) { data.insert(QLatin1String(NM_SSH_KEY_REMOTE_USERNAME), d->advUi.le_remoteUsername->text()); } if (d->advUi.chk_doNotReplaceDefaultRoute->isChecked()) { data.insert(QLatin1String(NM_SSH_KEY_NO_DEFAULT_ROUTE), QLatin1String("yes")); } // save it all setting.setData(data); setting.setSecrets(secretData); return setting.toMap(); } void SshSettingWidget::authTypeChanged(int index) { Q_D(SshSettingWidget); if (index == 0) { d->ui.stackedWidget->setCurrentIndex(0); d->ui.passwordWidget->setVisible(false); } else if (index == 1) { d->ui.stackedWidget->setCurrentIndex(0); d->ui.passwordWidget->setVisible(true); } else { d->ui.stackedWidget->setCurrentIndex(1); } } void SshSettingWidget::doAdvancedDialog() { Q_D(SshSettingWidget); d->advancedDlg->show(); } void SshSettingWidget::passwordTypeChanged(int index) { Q_D(SshSettingWidget); d->ui.le_password->setEnabled(index == SettingWidget::EnumPasswordStorageType::Store); } void SshSettingWidget::fillOnePasswordCombo(PasswordField *passwordField, NetworkManager::Setting::SecretFlags type) { if (type.testFlag(NetworkManager::Setting::None)) { passwordField->setPasswordOption(PasswordField::StoreForAllUsers); } else if (type.testFlag(NetworkManager::Setting::AgentOwned)) { passwordField->setPasswordOption(PasswordField::StoreForUser); } else if (type.testFlag(NetworkManager::Setting::NotSaved)) { passwordField->setPasswordOption(PasswordField::AlwaysAsk); } else { passwordField->setPasswordOption(PasswordField::PasswordField::NotRequired); } } void SshSettingWidget::handleOnePasswordType(const PasswordField *passwordField, const QString &key, NMStringMap &data) const { const PasswordField::PasswordOption option = passwordField->passwordOption(); switch (option) { case PasswordField::StoreForAllUsers: data.insert(key, QString::number(NetworkManager::Setting::None)); break; case PasswordField::StoreForUser: data.insert(key, QString::number(NetworkManager::Setting::AgentOwned)); break; case PasswordField::AlwaysAsk: data.insert(key, QString::number(NetworkManager::Setting::NotSaved)); break; case PasswordField::NotRequired: data.insert(key, QString::number(NetworkManager::Setting::NotRequired)); break; } } bool SshSettingWidget::isValid() const { Q_D(const SshSettingWidget); return !d->ui.le_gateway->text().isEmpty() && !d->ui.le_localIp->text().isEmpty() && !d->ui.le_remoteIp->text().isEmpty() && !d->ui.le_netmask->text().isEmpty(); } diff --git a/vpn/ssh/sshwidget.h b/vpn/ssh/sshwidget.h index 2a270af6..1f151701 100644 --- a/vpn/ssh/sshwidget.h +++ b/vpn/ssh/sshwidget.h @@ -1,56 +1,56 @@ /* Copyright 2015 Jan Grulich 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef SSH_WIDGET_H #define SSH_WIDGET_H #include "passwordfield.h" #include "settingwidget.h" #include class SshSettingWidgetPrivate; class SshSettingWidget : public SettingWidget { Q_OBJECT Q_DECLARE_PRIVATE(SshSettingWidget) public: - explicit SshSettingWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0); - ~SshSettingWidget(); + explicit SshSettingWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr); + ~SshSettingWidget() override; - void loadConfig(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; - void loadSecrets(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; + void loadSecrets(const NetworkManager::Setting::Ptr &setting) override; - virtual QVariantMap setting() const; - virtual bool isValid() const; + QVariantMap setting() const override; + bool isValid() const override; private Q_SLOTS: void authTypeChanged(int index); void doAdvancedDialog(); void passwordTypeChanged(int index); private: SshSettingWidgetPrivate * const d_ptr; void fillOnePasswordCombo(PasswordField *, NetworkManager::Setting::SecretFlags); void handleOnePasswordType(const PasswordField *, const QString &, NMStringMap &) const; }; #endif // SSH_WIDGET_H diff --git a/vpn/sstp/CMakeLists.txt b/vpn/sstp/CMakeLists.txt index 8fba4286..e4bda1d1 100644 --- a/vpn/sstp/CMakeLists.txt +++ b/vpn/sstp/CMakeLists.txt @@ -1,32 +1,26 @@ add_definitions(-DTRANSLATION_DOMAIN=\"plasmanetworkmanagement_sstpui\") set(sstp_SRCS sstp.cpp sstpwidget.cpp sstpauth.cpp ) ki18n_wrap_ui(sstp_SRCS sstpwidget.ui sstpadvanced.ui sstpauth.ui) add_library(plasmanetworkmanagement_sstpui ${sstp_SRCS}) kcoreaddons_desktop_to_json(plasmanetworkmanagement_sstpui plasmanetworkmanagement_sstpui.desktop) target_link_libraries(plasmanetworkmanagement_sstpui plasmanm_internal plasmanm_editor - Qt5::Widgets - Qt5::Network - Qt5::DBus - KF5::NetworkManagerQt - KF5::Service - KF5::Completion KF5::I18n KF5::WidgetsAddons KF5::KIOWidgets KF5::CoreAddons ) -install(TARGETS plasmanetworkmanagement_sstpui DESTINATION ${PLUGIN_INSTALL_DIR}) +install(TARGETS plasmanetworkmanagement_sstpui DESTINATION ${KDE_INSTALL_PLUGINDIR}) -install(FILES plasmanetworkmanagement_sstpui.desktop DESTINATION ${SERVICES_INSTALL_DIR}) +install(FILES plasmanetworkmanagement_sstpui.desktop DESTINATION ${KDE_INSTALL_KSERVICES5DIR}) diff --git a/vpn/sstp/plasmanetworkmanagement_sstpui.desktop b/vpn/sstp/plasmanetworkmanagement_sstpui.desktop index 9e93c28b..94d8bc65 100644 --- a/vpn/sstp/plasmanetworkmanagement_sstpui.desktop +++ b/vpn/sstp/plasmanetworkmanagement_sstpui.desktop @@ -1,89 +1,91 @@ [Desktop Entry] Type=Service Icon= ServiceTypes=PlasmaNetworkManagement/VpnUiPlugin X-KDE-Library=plasmanetworkmanagement_sstpui X-NetworkManager-Services=org.freedesktop.NetworkManager.sstp X-KDE-PluginInfo-Author=Jan Grulich X-KDE-PluginInfo-Email=jgrulich@redhat.com X-KDE-PluginInfo-Name=plasmanetworkmanagement_sstpui X-KDE-PluginInfo-Version=0.1 X-KDE-PluginInfo-Website= X-KDE-PluginInfo-Category=VPNService X-KDE-PluginInfo-Depends= X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=false Name=Secure Socket Tunneling Protocol (SSTP) Name[ca]=Protocol per crear túnels amb sòcols segurs (SSTP) Name[ca@valencia]=Protocol per crear túnels amb sòcols segurs (SSTP) Name[da]=Secure Socket tunneling-protokol (SSTP) Name[de]=Secure-Socket-Tunnel-Protokoll (SSTP) Name[el]=Πρωτόκολλο Secure Socket Tunneling (SSTP) Name[en_GB]=Secure Socket Tunneling Protocol (SSTP) Name[es]=Protocolo de túneles de conexiones seguras (SSTP) Name[et]=Secure Socket Tunneling Protocol (SSTP) Name[eu]=Socket seguruen tunel-protokoloa (SSTP) Name[fi]=Secure Socket -tunnelointiyhteyskäytäntö (SSTP) Name[fr]=Protocole tunnel socket sécurisé (SSTP) Name[gl]=Protocolo de canalización de sócket seguro (SSTP) Name[he]=Secure Socket Tunneling Protocol (SSTP) Name[hu]=Secure Socket Tunneling Protocol (SSTP) +Name[id]=Secure Socket Tunneling Protocol (SSTP) Name[it]=Secure Socket Tunneling Protocol (SSTP) Name[ko]=보안 소켓 터널링 프로토콜(SSTP) Name[nl]=Secure Socket Tunneling Protocol (SSTP) Name[nn]=Secure Socket Tunneling Protocol (SSTP) Name[pa]=ਸਕਿਉਰ ਸਾਕਟ ਟਨਲਿੰਗ ਪਰੋਟੋਕਾਲ (SSTP) Name[pl]=Protokół tunelujący bezpiecznego gniazda (SSTP) Name[pt]=Protocolo de Túneis por 'Socket' Seguro (SSTP) Name[pt_BR]=Secure Socket Tunneling Protocol (SSTP) Name[ru]=Протокол защищённого туннелирования сокетов (SSTP) Name[sk]=Secure Socket Tunneling Protocol (SSTP) Name[sl]=Protokol za tuneliranje z varnim vtičem (SSTP) Name[sr]=ССТП (безбедни сокетни тунелски протокол) Name[sr@ijekavian]=ССТП (безбедни сокетни тунелски протокол) Name[sr@ijekavianlatin]=SSTP (bezbedni soketni tunelski protokol) Name[sr@latin]=SSTP (bezbedni soketni tunelski protokol) Name[sv]=Säkert uttagstunnelprotokoll (SSTP) Name[tr]=Güvenli Yuva Tünel Protokolü (SSTP) Name[uk]=Протокол тунелювання із безпечними сокетами (SSTP) Name[x-test]=xxSecure Socket Tunneling Protocol (SSTP)xx Name[zh_CN]=安全套接字隧道协议 (SSTP) Name[zh_TW]=安全 Socket 通道協定 (SSTP) Comment=Compatible with Microsoft and other SSTP VPN servers Comment[ar]=متوافق مع «مايكروسوفت» وخواديم SSTP VPN الأخرى Comment[ca]=Compatible amb Microsoft i altres servidors VPN sobre SSTP Comment[ca@valencia]=Compatible amb Microsoft i altres servidors VPN sobre SSTP Comment[da]=Kompatibel med Microsoft og andre SSTP VPN-servere Comment[de]=Mit SSTP-VPN-Servern von Microsoft und anderen kompatibel Comment[el]=Συμβατό με διακομιστές Microsoft και άλλους διακομιστές SSTP VPN Comment[en_GB]=Compatible with Microsoft and other SSTP VPN servers Comment[es]=Compatible con Microsoft y otros servidores SSTP VPN Comment[et]=Ühildub Microsofti ja teiste SSTP VPN-serveritega Comment[eu]=Microsoft eta beste SSTP VPN zerbitzari batzuekin bateragarria Comment[fi]=Yhteensopiva Microsoftin ja muiden SSTP-VPN-palvelinten kanssa Comment[fr]=Compatible avec les serveurs Microsoft et autres VPN SSTP Comment[gl]=Compatíbel con servidores de VPN de Microsoft e outros servidores de VPN que usen SSTP. Comment[he]=תואם למיקרוסופט ושרתי SSTP VPN אחרים Comment[hu]=Kompatibilis a Microsoft és más SSTP VPN kiszolgálókkal +Comment[id]=Kompatibel dengan server Microsoft dan server VPN SSTP lainnya Comment[it]=Compatibile con server VPN SSTP di Microsoft e altri Comment[ko]=Microsoft 및 기타 SSTP VPN 서버와 호환됨 Comment[lt]=Suderinamas su Microsoft ir kitais SSTP VPN serveriais Comment[nl]=Compatibel met Microsoft en andere SSTP VPN servers Comment[nn]=Kompatibel med Microsoft og andre SSTP VPN-tenarar Comment[pa]=ਮਾਈਕਰੋਸਾਫਟ ਅਤੇ ਹੋਰ SSTP VPN ਸਰਵਰਾਂ ਲਈ ਢੁਕਵਾਂ Comment[pl]=Zgodny z serwerami VPN Microsoft-u i innymi SSTP Comment[pt]=Compatível com os servidores de VPN SSTP da Microsoft e outros Comment[pt_BR]=Compatível com servidores VPN SSTP da Microsoft e outros Comment[ru]=Совместимая с серверами SSTP от Microsoft и другими Comment[sk]=Kompatibilné s Microsoft a inými SSTP VPN servermi Comment[sl]=Združljiv z Microsoftovimi in drugimi SSTP strežniki VPN Comment[sr]=Сагласно са Мајкрософтовим и другим ССТП ВПН серверима Comment[sr@ijekavian]=Сагласно са Мајкрософтовим и другим ССТП ВПН серверима Comment[sr@ijekavianlatin]=Saglasno sa Microsoftovim i drugim SSTP VPN serverima Comment[sr@latin]=Saglasno sa Microsoftovim i drugim SSTP VPN serverima Comment[sv]=Kompatibelt med Microsoft och andra SSTP VPN-servrar Comment[tr]=Microsoft ve diğer SSTP VPN sunucuları ile uyumlu Comment[uk]=Сумісні з Microsoft та іншими серверами VPN SSTP Comment[x-test]=xxCompatible with Microsoft and other SSTP VPN serversxx Comment[zh_CN]=兼容 Microsoft 和其他 SSTP VPN 服务器 Comment[zh_TW]=與微軟還有其他 SSTP VPN 伺服器相容 diff --git a/vpn/sstp/sstp.h b/vpn/sstp/sstp.h index b6ebf76a..3447bff5 100644 --- a/vpn/sstp/sstp.h +++ b/vpn/sstp/sstp.h @@ -1,41 +1,41 @@ /* Copyright 2015 Jan Grulich 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef PLASMA_NM_SSTP_H #define PLASMA_NM_SSTP_H #include "vpnuiplugin.h" class Q_DECL_EXPORT SstpUiPlugin : public VpnUiPlugin { Q_OBJECT public: - explicit SstpUiPlugin(QObject *parent = 0, const QVariantList& = QVariantList()); - virtual ~SstpUiPlugin(); - virtual SettingWidget * widget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0); - virtual SettingWidget * askUser(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0); - virtual QString suggestedFileName(const NetworkManager::ConnectionSettings::Ptr &connection) const; - virtual QString supportedFileExtensions() const; - - virtual NMVariantMapMap importConnectionSettings(const QString &fileName); - virtual bool exportConnectionSettings(const NetworkManager::ConnectionSettings::Ptr &connection, const QString &fileName); + explicit SstpUiPlugin(QObject *parent = nullptr, const QVariantList& = QVariantList()); + ~SstpUiPlugin() override; + SettingWidget * widget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr) override; + SettingWidget * askUser(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr) override; + QString suggestedFileName(const NetworkManager::ConnectionSettings::Ptr &connection) const override; + QString supportedFileExtensions() const override; + + NMVariantMapMap importConnectionSettings(const QString &fileName) override; + bool exportConnectionSettings(const NetworkManager::ConnectionSettings::Ptr &connection, const QString &fileName) override; }; #endif // PLASMA_NM_SSTP_H diff --git a/vpn/sstp/sstpauth.h b/vpn/sstp/sstpauth.h index 8cf4056d..bfff6e25 100644 --- a/vpn/sstp/sstpauth.h +++ b/vpn/sstp/sstpauth.h @@ -1,45 +1,45 @@ /* Copyright 2015 Jan Grulich 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef SSTP_AUTH_H #define SSTP_AUTH_H #include "settingwidget.h" #include class SstpAuthWidgetPrivate; class SstpAuthWidget : public SettingWidget { Q_OBJECT Q_DECLARE_PRIVATE(SstpAuthWidget) public: - explicit SstpAuthWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0); - ~SstpAuthWidget(); + explicit SstpAuthWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr); + ~SstpAuthWidget() override; - virtual QVariantMap setting() const; + QVariantMap setting() const override; private: SstpAuthWidgetPrivate *const d_ptr; void acceptDialog(); }; #endif // SSTP_AUTH_H diff --git a/vpn/sstp/sstpwidget.cpp b/vpn/sstp/sstpwidget.cpp index b5d4a14b..208dca6d 100644 --- a/vpn/sstp/sstpwidget.cpp +++ b/vpn/sstp/sstpwidget.cpp @@ -1,388 +1,388 @@ /* Copyright 2015 Jan Grulich 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include "sstpwidget.h" #include "ui_sstpwidget.h" #include "ui_sstpadvanced.h" #include #include #include #include "nm-sstp-service.h" class SstpSettingWidgetPrivate { public: Ui_SstpWidget ui; Ui_SstpAdvanced advUi; NetworkManager::VpnSetting::Ptr setting; QDialog *advancedDlg; QWidget *advancedWid; }; SstpSettingWidget::SstpSettingWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent) : SettingWidget(setting, parent) , d_ptr(new SstpSettingWidgetPrivate) { Q_D(SstpSettingWidget); d->ui.setupUi(this); d->setting = setting; d->ui.le_password->setPasswordOptionsEnabled(true); connect(d->ui.btn_advancedOption, &QPushButton::clicked, this, &SstpSettingWidget::doAdvancedDialog); d->advancedDlg = new QDialog(this); d->advancedDlg->setModal(true); d->advancedWid = new QWidget(this); d->advUi.setupUi(d->advancedWid); QVBoxLayout *layout = new QVBoxLayout(d->advancedDlg); layout->addWidget(d->advancedWid); d->advancedDlg->setLayout(layout); QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel, d->advancedDlg); connect(buttons, &QDialogButtonBox::accepted, d->advancedDlg, &QDialog::accept); connect(buttons, &QDialogButtonBox::rejected, d->advancedDlg, &QDialog::reject); layout->addWidget(buttons); // Connect for setting check watchChangedSetting(); // Connect for validity check connect(d->ui.le_gateway, &QLineEdit::textChanged, this, &SstpSettingWidget::slotWidgetChanged); connect(d->ui.le_username, &QLineEdit::textChanged, this, &SstpSettingWidget::slotWidgetChanged); connect(d->ui.le_password, &PasswordField::textChanged, this, &SstpSettingWidget::slotWidgetChanged); KAcceleratorManager::manage(this); if (d->setting && !d->setting->isNull()) { loadConfig(d->setting); } } SstpSettingWidget::~SstpSettingWidget() { delete d_ptr; } void SstpSettingWidget::loadConfig(const NetworkManager::Setting::Ptr &setting) { Q_D(SstpSettingWidget); Q_UNUSED(setting) const QString yesString = QLatin1String("yes"); const NMStringMap dataMap = d->setting->data(); // General const QString gateway = dataMap[QLatin1String(NM_SSTP_KEY_GATEWAY)]; if (!gateway.isEmpty()) { d->ui.le_gateway->setText(gateway); } // Optional setting const QString username = dataMap[QLatin1String(NM_SSTP_KEY_USER)]; if (!username.isEmpty()) { d->ui.le_username->setText(username); } // Authentication const NetworkManager::Setting::SecretFlags type = (NetworkManager::Setting::SecretFlags)dataMap[NM_SSTP_KEY_PASSWORD_FLAGS].toInt(); fillOnePasswordCombo(d->ui.le_password, type); const QString ntDomain = dataMap[QLatin1String(NM_SSTP_KEY_DOMAIN)]; if (!ntDomain.isEmpty()) { d->ui.le_ntDomain->setText(ntDomain); } const QString caCert = dataMap[QLatin1String(NM_SSTP_KEY_CA_CERT)]; if (!caCert.isEmpty()) { d->ui.kurl_caCert->setUrl(QUrl::fromLocalFile(caCert)); } const bool ignoreCertWarnings = (dataMap[QLatin1String(NM_SSTP_KEY_IGN_CERT_WARN)] == yesString); d->ui.chk_ignoreCertWarnings->setChecked(ignoreCertWarnings); // Advanced options - Point-to-Point bool refuse_pap = (dataMap[QLatin1String(NM_SSTP_KEY_REFUSE_PAP)] == yesString); bool refuse_chap = (dataMap[QLatin1String(NM_SSTP_KEY_REFUSE_CHAP)] == yesString); bool refuse_mschap = (dataMap[QLatin1String(NM_SSTP_KEY_REFUSE_MSCHAP)] == yesString); bool refuse_mschapv2 = (dataMap[QLatin1String(NM_SSTP_KEY_REFUSE_MSCHAPV2)] == yesString); bool refuse_eap = (dataMap[QLatin1String(NM_SSTP_KEY_REFUSE_EAP)] == yesString); - QListWidgetItem *item = 0; + QListWidgetItem *item = nullptr; item = d->advUi.listWidget->item(0); // PAP item->setCheckState(refuse_pap ? Qt::Unchecked : Qt::Checked); item = d->advUi.listWidget->item(1); // CHAP item->setCheckState(refuse_chap ? Qt::Unchecked : Qt::Checked); item = d->advUi.listWidget->item(2); // MSCHAP item->setCheckState(refuse_mschap ? Qt::Unchecked : Qt::Checked); item = d->advUi.listWidget->item(3); // MSCHAPv2 item->setCheckState(refuse_mschapv2 ? Qt::Unchecked : Qt::Checked); item = d->advUi.listWidget->item(4); // EAP item->setCheckState(refuse_eap ? Qt::Unchecked : Qt::Checked); // Cryptography and compression const bool mppe = (dataMap[QLatin1String(NM_SSTP_KEY_REQUIRE_MPPE)] == yesString); const bool mppe40 = (dataMap[QLatin1String(NM_SSTP_KEY_REQUIRE_MPPE_40)] == yesString); const bool mppe128 = (dataMap[QLatin1String(NM_SSTP_KEY_REQUIRE_MPPE_128)] == yesString); const bool mppe_stateful = (dataMap[QLatin1String(NM_SSTP_KEY_MPPE_STATEFUL)] == yesString); if (mppe || mppe40 || mppe128) { // If MPPE is use d->advUi.gb_MPPE->setChecked(mppe || mppe40 || mppe128); if (mppe128) { d->advUi.cb_MPPECrypto->setCurrentIndex(1); // 128 bit } else if (mppe40) { d->advUi.cb_MPPECrypto->setCurrentIndex(2); // 40 bit } else { d->advUi.cb_MPPECrypto->setCurrentIndex(0); // Any } d->advUi.cb_statefulEncryption->setChecked(mppe_stateful); } const bool nobsd = (dataMap[QLatin1String(NM_SSTP_KEY_NOBSDCOMP)] == yesString); d->advUi.cb_BSD->setChecked(!nobsd); const bool nodeflate = (dataMap[QLatin1String(NM_SSTP_KEY_NODEFLATE)] == yesString); d->advUi.cb_deflate->setChecked(!nodeflate); const bool novjcomp = (dataMap[QLatin1String(NM_SSTP_KEY_NO_VJ_COMP)] == yesString); d->advUi.cb_TCPheaders->setChecked(!novjcomp); // Echo const int lcp_echo_interval = QString(dataMap[QLatin1String(NM_SSTP_KEY_LCP_ECHO_INTERVAL)]).toInt(); d->advUi.cb_sendEcho->setChecked(lcp_echo_interval > 0); if (dataMap.contains(QLatin1String(NM_SSTP_KEY_UNIT_NUM))) { d->advUi.chk_useCustomUnitNumber->setChecked(true); d->advUi.sb_customUnitNumber->setValue(dataMap[QLatin1String(NM_SSTP_KEY_UNIT_NUM)].toInt()); } // Advanced options - Proxy const QString address = dataMap[QLatin1String(NM_SSTP_KEY_PROXY_SERVER)]; if (!address.isEmpty()) { d->advUi.le_address->setText(address); } const int port = dataMap[QLatin1String(NM_SSTP_KEY_PROXY_PORT)].toInt(); if (port >= 0) { d->advUi.sb_port->setValue(port); } const QString proxyUsername = dataMap[QLatin1String(NM_SSTP_KEY_PROXY_USER)]; if (!proxyUsername.isEmpty()) { d->advUi.le_username->setText(proxyUsername); } const QString proxyPassword = dataMap[QLatin1String(NM_SSTP_KEY_PROXY_PASSWORD)]; if (!proxyPassword.isEmpty()) { d->advUi.le_password->setText(proxyPassword); } loadSecrets(setting); } void SstpSettingWidget::loadSecrets(const NetworkManager::Setting::Ptr &setting) { Q_D(SstpSettingWidget); NetworkManager::VpnSetting::Ptr vpnSetting = setting.staticCast(); if (vpnSetting) { const NMStringMap secrets = vpnSetting->secrets(); const QString keyPassword = secrets.value(NM_SSTP_KEY_PASSWORD); if (!keyPassword.isEmpty()) { d->ui.le_password->setText(keyPassword); } } } QVariantMap SstpSettingWidget::setting() const { Q_D(const SstpSettingWidget); NetworkManager::VpnSetting setting; setting.setServiceType(QLatin1String(NM_DBUS_SERVICE_SSTP)); const QString yesString = QLatin1String("yes"); NMStringMap data; NMStringMap secretData; data.insert(QLatin1String(NM_SSTP_KEY_GATEWAY), d->ui.le_gateway->text()); if (!d->ui.le_username->text().isEmpty()) { data.insert(QLatin1String(NM_SSTP_KEY_USER), d->ui.le_username->text()); } if (!d->ui.le_password->text().isEmpty()) { secretData.insert(QLatin1String(NM_SSTP_KEY_PASSWORD), d->ui.le_password->text()); } handleOnePasswordType(d->ui.le_password, NM_SSTP_KEY_PASSWORD_FLAGS, data); if (!d->ui.le_ntDomain->text().isEmpty()) { data.insert(QLatin1String(NM_SSTP_KEY_DOMAIN), d->ui.le_ntDomain->text()); } if (!d->ui.kurl_caCert->url().isEmpty()) { data.insert(QLatin1String(NM_SSTP_KEY_CA_CERT), d->ui.kurl_caCert->url().toLocalFile()); } if (d->ui.chk_ignoreCertWarnings->isChecked()) { data.insert(QLatin1String(NM_SSTP_KEY_IGN_CERT_WARN), yesString); } // Advanced configuration - QListWidgetItem *item = 0; + QListWidgetItem *item = nullptr; item = d->advUi.listWidget->item(0); // PAP if (item->checkState() == Qt::Unchecked) { data.insert(QLatin1String(NM_SSTP_KEY_REFUSE_PAP), yesString); } item = d->advUi.listWidget->item(1); // CHAP if (item->checkState() == Qt::Unchecked) { data.insert(QLatin1String(NM_SSTP_KEY_REFUSE_CHAP), yesString); } item = d->advUi.listWidget->item(2); // MSCHAP if (item->checkState() == Qt::Unchecked) { data.insert(QLatin1String(NM_SSTP_KEY_REFUSE_MSCHAP), yesString); } item = d->advUi.listWidget->item(3); // MSCHAPv2 if (item->checkState() == Qt::Unchecked) { data.insert(QLatin1String(NM_SSTP_KEY_REFUSE_MSCHAPV2), yesString); } item = d->advUi.listWidget->item(4); // EAP if (item->checkState() == Qt::Unchecked) { data.insert(QLatin1String(NM_SSTP_KEY_REFUSE_EAP), yesString); } // Cryptography and compression if (d->advUi.gb_MPPE->isChecked()) { int index = d->advUi.cb_MPPECrypto->currentIndex(); switch (index) { case 0: data.insert(QLatin1String(NM_SSTP_KEY_REQUIRE_MPPE), yesString); break; case 1: data.insert(QLatin1String(NM_SSTP_KEY_REQUIRE_MPPE_128), yesString); break; case 2: data.insert(QLatin1String(NM_SSTP_KEY_REQUIRE_MPPE_40), yesString); break; } if (d->advUi.cb_statefulEncryption->isChecked()) { data.insert(NM_SSTP_KEY_MPPE_STATEFUL, yesString); } } if (!d->advUi.cb_BSD->isChecked()) { data.insert(QLatin1String(NM_SSTP_KEY_NOBSDCOMP), yesString); } if (!d->advUi.cb_deflate->isChecked()) { data.insert(QLatin1String(NM_SSTP_KEY_NODEFLATE), yesString); } if (!d->advUi.cb_TCPheaders->isChecked()) { data.insert(QLatin1String(NM_SSTP_KEY_NO_VJ_COMP), yesString); } // Echo if (d->advUi.cb_sendEcho->isChecked()) { data.insert(QLatin1String(NM_SSTP_KEY_LCP_ECHO_FAILURE), "5"); data.insert(QLatin1String(NM_SSTP_KEY_LCP_ECHO_INTERVAL), "30"); } if (d->advUi.chk_useCustomUnitNumber->isChecked()) { data.insert(QLatin1String(NM_SSTP_KEY_UNIT_NUM), QString::number(d->advUi.sb_customUnitNumber->value())); } if (!d->advUi.le_address->text().isEmpty()) { data.insert(QLatin1String(NM_SSTP_KEY_PROXY_SERVER), d->advUi.le_address->text()); } if (d->advUi.sb_port->value() >= 0) { data.insert(QLatin1String(NM_SSTP_KEY_PROXY_PORT), QString::number(d->advUi.sb_port->value())); } if (!d->advUi.le_username->text().isEmpty()) { data.insert(QLatin1String(NM_SSTP_KEY_PROXY_USER), d->advUi.le_username->text()); } if (!d->advUi.le_password->text().isEmpty()) { data.insert(QLatin1String(NM_SSTP_KEY_PROXY_PASSWORD), d->advUi.le_password->text()); } handleOnePasswordType(d->advUi.le_password, NM_SSTP_KEY_PROXY_PASSWORD_FLAGS, data); // save it all setting.setData(data); setting.setSecrets(secretData); return setting.toMap(); } void SstpSettingWidget::doAdvancedDialog() { Q_D(SstpSettingWidget); d->advancedDlg->show(); } void SstpSettingWidget::fillOnePasswordCombo(PasswordField *passwordField, NetworkManager::Setting::SecretFlags type) { if (type.testFlag(NetworkManager::Setting::None)) { passwordField->setPasswordOption(PasswordField::StoreForAllUsers); } else if (type.testFlag(NetworkManager::Setting::AgentOwned)) { passwordField->setPasswordOption(PasswordField::StoreForUser); } else if (type.testFlag(NetworkManager::Setting::NotSaved)) { passwordField->setPasswordOption(PasswordField::AlwaysAsk); } else { passwordField->setPasswordOption(PasswordField::PasswordField::NotRequired); } } void SstpSettingWidget::handleOnePasswordType(const PasswordField *passwordField, const QString &key, NMStringMap &data) const { const PasswordField::PasswordOption option = passwordField->passwordOption(); switch (option) { case PasswordField::StoreForAllUsers: data.insert(key, QString::number(NetworkManager::Setting::None)); break; case PasswordField::StoreForUser: data.insert(key, QString::number(NetworkManager::Setting::AgentOwned)); break; case PasswordField::AlwaysAsk: data.insert(key, QString::number(NetworkManager::Setting::NotSaved)); break; case PasswordField::NotRequired: data.insert(key, QString::number(NetworkManager::Setting::NotRequired)); break; } } bool SstpSettingWidget::isValid() const { Q_D(const SstpSettingWidget); return !d->ui.le_gateway->text().isEmpty(); } diff --git a/vpn/sstp/sstpwidget.h b/vpn/sstp/sstpwidget.h index a6bfe925..b61d325b 100644 --- a/vpn/sstp/sstpwidget.h +++ b/vpn/sstp/sstpwidget.h @@ -1,55 +1,55 @@ /* Copyright 2015 Jan Grulich 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef SSTP_WIDGET_H #define SSTP_WIDGET_H #include "passwordfield.h" #include "settingwidget.h" #include class QComboBox; class SstpSettingWidgetPrivate; class SstpSettingWidget : public SettingWidget { Q_OBJECT Q_DECLARE_PRIVATE(SstpSettingWidget) public: - explicit SstpSettingWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0); - ~SstpSettingWidget(); + explicit SstpSettingWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr); + ~SstpSettingWidget() override; - void loadConfig(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; - void loadSecrets(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; + void loadSecrets(const NetworkManager::Setting::Ptr &setting) override; - virtual QVariantMap setting() const; - virtual bool isValid() const; + QVariantMap setting() const override; + bool isValid() const override; private Q_SLOTS: void doAdvancedDialog(); private: SstpSettingWidgetPrivate * const d_ptr; void fillOnePasswordCombo(PasswordField *, NetworkManager::Setting::SecretFlags); void handleOnePasswordType(const PasswordField *, const QString &, NMStringMap &) const; }; #endif // SSTP_WIDGET_H diff --git a/vpn/strongswan/CMakeLists.txt b/vpn/strongswan/CMakeLists.txt index 71c99394..6943da17 100644 --- a/vpn/strongswan/CMakeLists.txt +++ b/vpn/strongswan/CMakeLists.txt @@ -1,27 +1,25 @@ add_definitions(-DTRANSLATION_DOMAIN=\"plasmanetworkmanagement_strongswanui\") set(strongswan_SRCS strongswan.cpp strongswanwidget.cpp strongswanauth.cpp ) ki18n_wrap_ui(strongswan_SRCS strongswanprop.ui strongswanauth.ui) add_library(plasmanetworkmanagement_strongswanui ${strongswan_SRCS}) kcoreaddons_desktop_to_json(plasmanetworkmanagement_strongswanui plasmanetworkmanagement_strongswanui.desktop) target_link_libraries(plasmanetworkmanagement_strongswanui plasmanm_internal plasmanm_editor - Qt5::Widgets - KF5::Service KF5::I18n KF5::KIOWidgets - KF5::NetworkManagerQt + KF5::CoreAddons ) -install(TARGETS plasmanetworkmanagement_strongswanui DESTINATION ${PLUGIN_INSTALL_DIR}) +install(TARGETS plasmanetworkmanagement_strongswanui DESTINATION ${KDE_INSTALL_PLUGINDIR}) -install(FILES plasmanetworkmanagement_strongswanui.desktop DESTINATION ${SERVICES_INSTALL_DIR}) +install(FILES plasmanetworkmanagement_strongswanui.desktop DESTINATION ${KDE_INSTALL_KSERVICES5DIR}) diff --git a/vpn/strongswan/plasmanetworkmanagement_strongswanui.desktop b/vpn/strongswan/plasmanetworkmanagement_strongswanui.desktop index fcb2bec7..de9a0f04 100644 --- a/vpn/strongswan/plasmanetworkmanagement_strongswanui.desktop +++ b/vpn/strongswan/plasmanetworkmanagement_strongswanui.desktop @@ -1,87 +1,89 @@ [Desktop Entry] Type=Service Icon= ServiceTypes=PlasmaNetworkManagement/VpnUiPlugin X-KDE-Library=plasmanetworkmanagement_strongswanui X-NetworkManager-Services=org.freedesktop.NetworkManager.strongswan X-KDE-PluginInfo-Author=Lukáš Tinkl X-KDE-PluginInfo-Email=ltinkl@redhat.com X-KDE-PluginInfo-Name=plasmanetworkmanagement_strongswanui X-KDE-PluginInfo-Version=0.1 X-KDE-PluginInfo-Website= X-KDE-PluginInfo-Category=VPNService X-KDE-PluginInfo-Depends= X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=false Name=IPsec based VPN (strongswan) Name[ca]=VPN basada en IPsec (strongswan) Name[ca@valencia]=VPN basada en IPsec (strongswan) Name[da]=IPsec-baseret VPN (strongswan) Name[de]=VPN basierend auf IPsec (strongswan) Name[el]=VPN βασισμένο σε IPsec (strongswan) Name[en_GB]=IPsec based VPN (strongswan) Name[es]=VPN basada en IPsec (strongswan) Name[et]=IPseci põhine VPN (strongswan) Name[eu]=IPsec oinarridun VPN (strongswan) Name[fi]=IPsec-pohjainen VPN (strongswan) Name[fr]=VPN utilisant IPsec (strongswan) Name[gl]=VPN baseada en IPsec (strongswan) Name[he]=‏ VPN מבוסס IPsec‏ (strongswan) Name[hu]=IPsec-alapú VPN (strongswan) +Name[id]=IPsec based VPN (strongswan) Name[it]=VPN basata su IPsec (strongswan) Name[ko]=IPSec 기반 VPN(strongswan) Name[lt]=IPsec su VPN (strongswan) pagrindu Name[nl]=Op IPsec gebaseerde VPN (strongswan) Name[nn]=IPsec-basert VPN (strongswan) Name[pa]=IPsec ਅਧਾਰਿਤ VPN (strongswan) Name[pl]=VPN oparty na IPsec (strongswan) Name[pt]=VPN baseada em IPsec (strongswan) Name[pt_BR]=VPN baseada em IPsec (strongswan) Name[ru]=VPN на основе IPsec (strongswan) Name[sk]=IPsec založené VPN (strongswan) Name[sl]=Na IPsec temelječ VPN (strongswan) Name[sr]=ВПН на основу ИПсека (Стронгсвон) Name[sr@ijekavian]=ВПН на основу ИПсека (Стронгсвон) Name[sr@ijekavianlatin]=VPN na osnovu IPseca (strongSwan) Name[sr@latin]=VPN na osnovu IPseca (strongSwan) Name[sv]=IPsec-baserad VPN (strongswan) Name[tr]=IPsec tabanlı VPN (strongswan) Name[uk]=VPN на основі IPsec (strongswan) Name[x-test]=xxIPsec based VPN (strongswan)xx Name[zh_CN]=基于 IPsec 的 VPN (strongswan) Name[zh_TW]=以 IPsec 為底的 VPN (strongswan) Comment=IPsec, IKEv1, IKEv2 based VPN Comment[ca]=VPN basada en IKEv1, IKEv2 sobre IPsec Comment[ca@valencia]=VPN basada en IKEv1, IKEv2 sobre IPsec Comment[da]=IPsec, IKEv1, IKEv2 baseret VPN Comment[de]=VPN basierend auf IPsec, IKEv1, IKEv2 Comment[el]=VPN βασισμένο σε IPsec, IKEv1, IKEv2 Comment[en_GB]=IPsec, IKEv1, IKEv2 based VPN Comment[es]=VPN basada en IPsec, IKEv1 e IKEv2 Comment[et]=IPsec, IKEv1, IKEv2 põhine VPN Comment[eu]=IPsec, IKEv1, IKEv2 oinarridun VPN Comment[fi]=IPsec-, IKEv1-, IKEv2-pohjainen VPN Comment[fr]=VPN utilisant IPsec, IKEv1, IKEv2 Comment[gl]=VPN baseada en IPsec, IKEv1 e IKEv2. Comment[hu]=IPsec-, IKEv1-, IKEv2-alapú VPN +Comment[id]=IPsec, IKEv1, IKEv2 berbasiskan VPN Comment[it]=VPN basata su IPsec, IKEv1, IKEv2 Comment[ko]=IPSec, IKEv1, IKEv2 기반 VPN Comment[nl]=Op IPsec, IKEv1, IKEv2 gebaseerde VPN Comment[nn]=IPsec-/IKEv1-/IKEv2-basert VPN Comment[pa]=IPsec, IKEv1, IKEv2 ਅਧਾਰਿਤ VPN Comment[pl]=VPN oparty na IPsec, IKEv1, IKEv2 Comment[pt]=VPN baseada em IPsec, IKEv1, IKEv2 Comment[pt_BR]=VPN baseada em IPsec, IKEv1, IKEv2 Comment[ru]=VPN на основе IPsec, IKEv1, IKEv2 Comment[sk]=IPsec, IKEv1, IKEv2 založené VPN Comment[sl]=Na IPsec, IKEv1, IKEv2 temelječ VPN Comment[sr]=ВПН на основу ИПсека, ИКЕ‑а в1, ИКЕ в2 Comment[sr@ijekavian]=ВПН на основу ИПсека, ИКЕ‑а в1, ИКЕ в2 Comment[sr@ijekavianlatin]=VPN na osnovu IPseca, IKE‑a v1, IKE v2 Comment[sr@latin]=VPN na osnovu IPseca, IKE‑a v1, IKE v2 Comment[sv]=IPsec, IKEv1, IKEv2-baserad VPN Comment[tr]=IPsec, IKEv1, IKEv2 tabanlı VPN Comment[uk]=VPN на основі IPsec, IKEv1, IKEv2 Comment[x-test]=xxIPsec, IKEv1, IKEv2 based VPNxx Comment[zh_CN]=基于 IPsec,IKEv1,IKEv2 的 VPN Comment[zh_TW]=以 IPsec, IKEv1, IKEv2 為基底的 VPN diff --git a/vpn/strongswan/strongswan.h b/vpn/strongswan/strongswan.h index 8a08bd23..3ed24d62 100644 --- a/vpn/strongswan/strongswan.h +++ b/vpn/strongswan/strongswan.h @@ -1,45 +1,45 @@ /* Copyright 2009 Will Stephenson Copyright 2010 Maurus Rohrer Copyright 2013 Lukas Tinkl 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef PLASMANM_STRONGSWAN_H #define PLASMANM_STRONGSWAN_H #include "vpnuiplugin.h" #include class Q_DECL_EXPORT StrongswanUiPlugin : public VpnUiPlugin { Q_OBJECT public: - explicit StrongswanUiPlugin(QObject * parent = 0, const QVariantList& = QVariantList()); - virtual ~StrongswanUiPlugin(); - virtual SettingWidget * widget(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = 0); - virtual SettingWidget * askUser(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = 0); - virtual QString suggestedFileName(const NetworkManager::ConnectionSettings::Ptr &connection) const; - virtual QString supportedFileExtensions() const; - - virtual NMVariantMapMap importConnectionSettings(const QString &fileName); - virtual bool exportConnectionSettings(const NetworkManager::ConnectionSettings::Ptr &connection, const QString &fileName); + explicit StrongswanUiPlugin(QObject * parent = nullptr, const QVariantList& = QVariantList()); + ~StrongswanUiPlugin() override; + SettingWidget * widget(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = nullptr) override; + SettingWidget * askUser(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = nullptr) override; + QString suggestedFileName(const NetworkManager::ConnectionSettings::Ptr &connection) const override; + QString supportedFileExtensions() const override; + + NMVariantMapMap importConnectionSettings(const QString &fileName) override; + bool exportConnectionSettings(const NetworkManager::ConnectionSettings::Ptr &connection, const QString &fileName) override; }; #endif // PLASMANM_STRONGSWAN_H diff --git a/vpn/strongswan/strongswanauth.cpp b/vpn/strongswan/strongswanauth.cpp index af327b84..a064351e 100644 --- a/vpn/strongswan/strongswanauth.cpp +++ b/vpn/strongswan/strongswanauth.cpp @@ -1,126 +1,126 @@ /* Copyright 2011 Ilia Kats Copyright 2013 Lukas Tinkl 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include "strongswanauth.h" #include "ui_strongswanauth.h" #include "nm-strongswan-service.h" #include #include #include #include #include class StrongswanAuthWidgetPrivate { public: Ui_StrongswanAuth ui; bool acceptOnShow; NetworkManager::VpnSetting::Ptr setting; }; StrongswanAuthWidget::StrongswanAuthWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent) : SettingWidget(setting, parent) , d_ptr(new StrongswanAuthWidgetPrivate) { Q_D(StrongswanAuthWidget); d->setting = setting; d->ui.setupUi(this); d->acceptOnShow = false; readSecrets(); KAcceleratorManager::manage(this); } StrongswanAuthWidget::~StrongswanAuthWidget() { delete d_ptr; } void StrongswanAuthWidget::readSecrets() { Q_D(StrongswanAuthWidget); const NMStringMap dataMap = d->setting->data(); const QString method = dataMap[NM_STRONGSWAN_METHOD]; if (method == QLatin1String(NM_STRONGSWAN_AUTH_AGENT) || dataMap[NM_STRONGSWAN_SECRET_TYPE] == QLatin1String(NM_STRONGSWAN_PW_TYPE_UNUSED)) { if (isVisible()) { acceptDialog(); } else { d->acceptOnShow = true; } } else if (method == QLatin1String(NM_STRONGSWAN_AUTH_KEY)) { d->ui.passwordLabel->setText(i18nc("@label:textbox password label for private key password", "Private Key Password:")); } else if (method == QLatin1String(NM_STRONGSWAN_AUTH_SMARTCARD)) { d->ui.passwordLabel->setText(i18nc("@label:textbox password label for smartcard pin", "PIN:")); } else if (method == QLatin1String(NM_STRONGSWAN_AUTH_EAP)) { d->ui.passwordLabel->setText(i18nc("@label:textbox password label for EAP password", "Password:")); } } void StrongswanAuthWidget::setVisible(bool visible) { Q_D(StrongswanAuthWidget); SettingWidget::setVisible(visible); if (visible) { if (d->acceptOnShow) { acceptDialog(); } else { SettingWidget::setVisible(visible); } } else { SettingWidget::setVisible(visible); } } void StrongswanAuthWidget::acceptDialog() { QDialog *dialog = qobject_cast(parentWidget()); if (dialog) { dialog->accept(); } } QVariantMap StrongswanAuthWidget::setting() const { Q_D(const StrongswanAuthWidget); NMStringMap secrets; QVariantMap secretData; if (d->setting->data()[NM_STRONGSWAN_METHOD] == QLatin1String(NM_STRONGSWAN_AUTH_AGENT)) { const QString agent = QProcessEnvironment::systemEnvironment().value(QLatin1String("SSH_AUTH_SOCK")); if (!agent.isEmpty()) { secrets.insert(NM_STRONGSWAN_AUTH_AGENT, agent); } else { - KMessageBox::error(0, i18nc("@label:textbox error message while saving configuration", "Configuration uses ssh-agent for authentication, but no ssh-agent found running.")); + KMessageBox::error(nullptr, i18nc("@label:textbox error message while saving configuration", "Configuration uses ssh-agent for authentication, but no ssh-agent found running.")); } } else { secrets.insert(NM_STRONGSWAN_SECRET, d->ui.password->text()); } secretData.insert("secrets", QVariant::fromValue(secrets)); return secretData; } diff --git a/vpn/strongswan/strongswanauth.h b/vpn/strongswan/strongswanauth.h index 0591666a..2bdfbe66 100644 --- a/vpn/strongswan/strongswanauth.h +++ b/vpn/strongswan/strongswanauth.h @@ -1,51 +1,51 @@ /* Copyright 2011 Ilia Kats Copyright 2013 Lukas Tinkl 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef STRONGSWANAUTH_H #define STRONGSWANAUTH_H #include "settingwidget.h" #include class StrongswanAuthWidgetPrivate; class StrongswanAuthWidget : public SettingWidget { Q_OBJECT Q_DECLARE_PRIVATE(StrongswanAuthWidget) public: - explicit StrongswanAuthWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = 0); - ~StrongswanAuthWidget(); + explicit StrongswanAuthWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = nullptr); + ~StrongswanAuthWidget() override; virtual void readSecrets(); - virtual QVariantMap setting() const; + QVariantMap setting() const override; public Q_SLOTS: - void setVisible(bool); + void setVisible(bool) override; private: StrongswanAuthWidgetPrivate * const d_ptr; void acceptDialog(); }; #endif // STRONGSWANAUTH_H diff --git a/vpn/strongswan/strongswanwidget.h b/vpn/strongswan/strongswanwidget.h index 92d13a28..c8322d54 100644 --- a/vpn/strongswan/strongswanwidget.h +++ b/vpn/strongswan/strongswanwidget.h @@ -1,53 +1,53 @@ /* Copyright 2009 Will Stephenson Copyright 2010 Maurus Rohrer Copyright 2013 Lukas Tinkl 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef STRONGSWANWIDGET_H #define STRONGSWANWIDGET_H #include "passwordfield.h" #include "settingwidget.h" #include class QComboBox; class StrongswanSettingWidgetPrivate; class StrongswanSettingWidget : public SettingWidget { Q_OBJECT Q_DECLARE_PRIVATE(StrongswanSettingWidget) public: - explicit StrongswanSettingWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0); - ~StrongswanSettingWidget(); + explicit StrongswanSettingWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr); + ~StrongswanSettingWidget() override; - void loadConfig(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; - void loadSecrets(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; + void loadSecrets(const NetworkManager::Setting::Ptr &setting) override; - virtual QVariantMap setting() const; + QVariantMap setting() const override; - virtual bool isValid() const; + bool isValid() const override; private: StrongswanSettingWidgetPrivate *const d_ptr; }; #endif // STRONGSWANWIDGET_H diff --git a/vpn/vpnc/CMakeLists.txt b/vpn/vpnc/CMakeLists.txt index 02e07c07..1cd5644f 100644 --- a/vpn/vpnc/CMakeLists.txt +++ b/vpn/vpnc/CMakeLists.txt @@ -1,34 +1,29 @@ add_definitions(-DTRANSLATION_DOMAIN=\"plasmanetworkmanagement_vpncui\") set(vpnc_SRCS ../../libs/debug.cpp vpnc.cpp vpncwidget.cpp vpncadvancedwidget.cpp vpncauth.cpp ) ki18n_wrap_ui(vpnc_SRCS vpnc.ui vpncadvanced.ui vpncauth.ui) add_library(plasmanetworkmanagement_vpncui ${vpnc_SRCS}) kcoreaddons_desktop_to_json(plasmanetworkmanagement_vpncui plasmanetworkmanagement_vpncui.desktop) target_link_libraries(plasmanetworkmanagement_vpncui plasmanm_internal plasmanm_editor - Qt5::Widgets - Qt5::Network - Qt5::DBus - KF5::NetworkManagerQt - KF5::Service - KF5::Completion + KF5::ConfigCore KF5::I18n KF5::WidgetsAddons KF5::KIOWidgets KF5::CoreAddons ) -install(TARGETS plasmanetworkmanagement_vpncui DESTINATION ${PLUGIN_INSTALL_DIR}) +install(TARGETS plasmanetworkmanagement_vpncui DESTINATION ${KDE_INSTALL_PLUGINDIR}) -install(FILES plasmanetworkmanagement_vpncui.desktop DESTINATION ${SERVICES_INSTALL_DIR}) +install(FILES plasmanetworkmanagement_vpncui.desktop DESTINATION ${KDE_INSTALL_KSERVICES5DIR}) diff --git a/vpn/vpnc/plasmanetworkmanagement_vpncui.desktop b/vpn/vpnc/plasmanetworkmanagement_vpncui.desktop index 1a950ada..cb201b72 100644 --- a/vpn/vpnc/plasmanetworkmanagement_vpncui.desktop +++ b/vpn/vpnc/plasmanetworkmanagement_vpncui.desktop @@ -1,88 +1,90 @@ [Desktop Entry] Type=Service Icon= ServiceTypes=PlasmaNetworkManagement/VpnUiPlugin X-KDE-Library=plasmanetworkmanagement_vpncui X-NetworkManager-Services=org.freedesktop.NetworkManager.vpnc X-KDE-PluginInfo-Author=Lukáš Tinkl X-KDE-PluginInfo-Email=ltinkl@redhat.com X-KDE-PluginInfo-Name=plasmanetworkmanagement_vpncui X-KDE-PluginInfo-Version=0.1 X-KDE-PluginInfo-Website= X-KDE-PluginInfo-Category=VPNService X-KDE-PluginInfo-Depends= X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=false Name=Cisco Compatible VPN (vpnc) Name[ca]=VPN compatible amb Cisco (vpnc) Name[ca@valencia]=VPN compatible amb Cisco (vpnc) Name[da]=Cisco-kompatibelt VPN (vpnc) Name[de]=VPN kompatibel mit Cisco (vpnc) Name[el]=Συμβατό με Cisco VPN (vpnc) Name[en_GB]=Cisco Compatible VPN (vpnc) Name[es]=VPN compatible con Cisco (vpnc) Name[et]=Ciscoga ühilduv VPN (vpnc) Name[eu]=Ciscorekin bateragarria den VPN (vpnc) Name[fi]=Cisco-yhteensopiva VPN (vpnc) Name[fr]=VPN compatible Cisco (vpnc) Name[gl]=VPN compatíbel con Cisco (vpnc) Name[he]=Cisco Compatible VPN (vpnc) Name[hu]=Cisco kompatibilis VPN (vpnc) +Name[id]=Cisco Compatible VPN (vpnc) Name[it]=VPN compatibile Cisco (vpnc) Name[ko]=Cisco 호환 VPN(vpnc) Name[lt]=VPN suderinamas su Cisco (vpnc) Name[nl]=Cisco Compatible VPN (vpnc) Name[nn]=Cisco-kompatibel VPN (vpnc) Name[pa]=Cisco ਅਨੁਕੂਲ VPN (vpnc) Name[pl]=Zgodny VPN Cisco (vpnc) Name[pt]=VPN Compatível com a Cisco (vpnc) Name[pt_BR]=VPN Compatível com a Cisco (vpnc) Name[ru]=Совместимая с Cisco VPN (vpnc) Name[sk]=Cisco kompatibilné VPN (vpnc) Name[sl]=S Ciscom združljiv VPN (vpnc) Name[sr]=ВПН сагласан са Сисковим (ВПНЦ) Name[sr@ijekavian]=ВПН сагласан са Сисковим (ВПНЦ) Name[sr@ijekavianlatin]=VPN saglasan sa Ciscovim (VPNC) Name[sr@latin]=VPN saglasan sa Ciscovim (VPNC) Name[sv]=Cisco-kompatibel VPN (vpnc) Name[tr]=Cisco Uyumlu VPN (vpnc) Name[uk]=Сумісний із Cisco VPN (vpnc) Name[x-test]=xxCisco Compatible VPN (vpnc)xx Name[zh_CN]=Cisco 兼容 VPN (vpnc) Name[zh_TW]=Cisco 相容 VPN (vpnc) Comment=Compatible with various Cisco, Juniper, Netscreen and Sonicwall IPsec-based VPN gateways Comment[ca]=Compatible amb diverses passarel·les VPN basades en IPsec de Cisco, Juniper, Netscreen i Sonicwall Comment[ca@valencia]=Compatible amb diverses passarel·les VPN basades en IPsec de Cisco, Juniper, Netscreen i Sonicwall Comment[da]=Kompatibel med diverse Cisco, Juniper, Netscreen, og Sonicwall IPsec-baserede VPN-gateways Comment[de]=Mit verschiedenen auf IPsec basierenden VPN-Gateways von Cisco, Juniper, Netscreen und Sonicwall kompatibel Comment[el]=Συμβατό με διάφορες δικτυακές πύλες (gateways) Cisco, Juniper, Netscreen και πύλες VPN βασισμένων σε Sonicwall IPsec Comment[en_GB]=Compatible with various Cisco, Juniper, Netscreen and Sonicwall IPsec-based VPN gateways Comment[es]=Compatible con diversas puertas de enlace VPN de Cisco, Juniper, Netscreen y Sonicwall basadas en IPsec Comment[et]=Ühildub erinevate Cisco, Juniperi, Netscreeni ja Sonicwalli IPseci põhiste VPN-lüüsidega Comment[eu]=Cisco, Juniper, Netscreen eta Sonicwall IPsec-oinarridun VPN atebideekin bateragarria Comment[fi]=Yhteensopiva Ciscon, Juniperin, Netscreenin ja Sonicwallin eri IPsec-pohjaisten VPN-yhdyskäytävien kanssa Comment[fr]=Compatible avec diverses passerelles VPN Cisco, Juniper, Netscreen et Sonicwall utilisant IPsec Comment[gl]=Compatíbel coas seguintes pasarelas de VPN baseadas en IPsec: Cisco, Juniper, Netscreen e Sonicwall. Comment[hu]=Kompatibilis különböző Cisco, Juniper, Netscreen és Sonicwall IPsec-alapú VPN átjárókkal +Comment[id]=Kompatibel dengan beberapa gateway-gateway VPN IPsec-based Sonicwall, Cisco, Juniper dan Netscreen Comment[it]=Compatibile con diversi gateway VPN Cisco, Juniper, Netscreen e Sonicwall basati su IPsec Comment[ko]=Cisco, Juniper, Netscreen, Sonicwall IPSec 기반 VPN 게이트웨이와 호환됨 Comment[lt]=Suderinamas su Cisco, Juniper, Netscreen ir Sonicwall IPsec paremtais VPN tinklų sietuvais Comment[nl]=Compatibel met verschillende op IPsec gebaseerde VPN-gateways van Cisco, Juniper, Netscreen en Sonicwall Comment[nn]=Kompatibel med ymse Cisco-, Juniper-, Netscreen- og Sonicwall IPsec-baserte VPN-portnarar Comment[pa]=ਕਈ ਸਿਸਕੋ, ਜੁਨੀਪੀਅਰ, ਨੈਟਸਕਰੀਨ ਅਤੇ ਸੋਨਿਕਵਾਲ IPsec-ਅਧਾਰਿਤ VPN ਗੇਟਵੇ ਲਈ ਢੁਕਵਾਂ ਹੈ। Comment[pl]=Zgodny z różnymi bramami VPN opartymi na Cisco, Juniper, Netscreen, oraz IPsec Sonicwall Comment[pt]=Compatível com diversas 'gateways' de VPN baseadas em IPsec, como a Cisco, Juniper, Netscreen e Sonicwall Comment[pt_BR]=Compatível com diversos gateways de VPN baseadas em IPsec, como Cisco, Juniper, Netscreen e Sonicwall Comment[ru]=Совместимая с различными VPN-шлюзами на основе IPsec от Cisco, Juniper, Netscreen и Sonicwall Comment[sk]=Kompatibilné s rôznymi Cisco, Juniper, Netscreen a Sonicwall IPsec VPN bránami Comment[sl]=Združljiv z različnimi prehodi VPN, temelječimi na IPsec: Cisco, Juniper, Netscreen in Sonicwall Comment[sr]=Сагласно са разним Сисковим, Џуниперовим, Нетскриновим и Соникволовим ВПН мрежним излазима на основу ИПсека Comment[sr@ijekavian]=Сагласно са разним Сисковим, Џуниперовим, Нетскриновим и Соникволовим ВПН мрежним излазима на основу ИПсека Comment[sr@ijekavianlatin]=Saglasno sa raznim Ciscovim, Juniperovim, NetScreenovim i SonicWallovim VPN mrežnim izlazima na osnovu IPseca Comment[sr@latin]=Saglasno sa raznim Ciscovim, Juniperovim, NetScreenovim i SonicWallovim VPN mrežnim izlazima na osnovu IPseca Comment[sv]=Kompatibel med olika Cisco, Juniper, Netscreen och Sonicwall IPsec-baserade VPN-förmedlingsnoder Comment[tr]=Çeşitli Cisco, Juniper, Netscreen ve Sonicwall IPsec tabanlı VPN ağ geçitleri ile uyumlu Comment[uk]=Сумісний із різноманітними шлюзами VPN Cisco, Juniper, Netscreen та Sonicwall на основі IPsec Comment[x-test]=xxCompatible with various Cisco, Juniper, Netscreen and Sonicwall IPsec-based VPN gatewaysxx Comment[zh_CN]=兼容多种 Cisco,Juniper,Netscreen 和 Sonicwall 基于 IPsec 的 VPN 网关 Comment[zh_TW]=與多種 Cisco, Juniper, Netscreen 與 Sonicwall IPsec 為基底的 VPN 閘道器相容 diff --git a/vpn/vpnc/vpnc.cpp b/vpn/vpnc/vpnc.cpp index 840a1323..ba09996a 100644 --- a/vpn/vpnc/vpnc.cpp +++ b/vpn/vpnc/vpnc.cpp @@ -1,418 +1,418 @@ /* Copyright 2008 Will Stephenson Copyright 2011-2012 Rajeesh K Nambiar Copyright 2011-2012 Lamarque V. Souza Copyright 2013 Lukas Tinkl 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include "debug.h" #include "vpnc.h" #include #include #include #include #include #include #include #include "nm-vpnc-service.h" #include #include #include #include #include "vpncwidget.h" #include "vpncauth.h" VpncUiPluginPrivate::VpncUiPluginPrivate() { decryptedPasswd.clear(); - ciscoDecrypt = 0; + ciscoDecrypt = nullptr; } VpncUiPluginPrivate::~VpncUiPluginPrivate() { } QString VpncUiPluginPrivate::readStringKeyValue(const KConfigGroup & configGroup, const QString & key) { const QString retValue = configGroup.readEntry(key); if (retValue.isEmpty()) { // String key can also start with "!" in CISCO pcf file. return configGroup.readEntry('!' + key); } else { return retValue; } } void VpncUiPluginPrivate::gotCiscoDecryptOutput() { QByteArray output = ciscoDecrypt->readAll(); if (!output.isEmpty()) { QList lines = output.split('\n'); if (!lines.isEmpty()) { decryptedPasswd = QString::fromUtf8(lines.first()); } } } void VpncUiPluginPrivate::ciscoDecryptFinished(int exitCode, QProcess::ExitStatus exitStatus) { if (exitCode || exitStatus != QProcess::NormalExit) { decryptedPasswd.clear(); } } void VpncUiPluginPrivate::ciscoDecryptError(QProcess::ProcessError pError) { if (!pError) { qCWarning(PLASMA_NM) << "Error in executing cisco-decrypt"; - KMessageBox::error(0, i18n("Error decrypting the obfuscated password"), i18n("Error"), KMessageBox::Notify); + KMessageBox::error(nullptr, i18n("Error decrypting the obfuscated password"), i18n("Error"), KMessageBox::Notify); } decryptedPasswd.clear(); } #define NM_VPNC_LOCAL_PORT_DEFAULT 500 K_PLUGIN_FACTORY_WITH_JSON(VpncUiPluginFactory, "plasmanetworkmanagement_vpncui.json", registerPlugin();) VpncUiPlugin::VpncUiPlugin(QObject * parent, const QVariantList &) : VpnUiPlugin(parent) { } VpncUiPlugin::~VpncUiPlugin() { } SettingWidget * VpncUiPlugin::widget(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent) { return new VpncWidget(setting, parent); } SettingWidget *VpncUiPlugin::askUser(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent) { return new VpncAuthDialog(setting, parent); } QString VpncUiPlugin::suggestedFileName(const NetworkManager::ConnectionSettings::Ptr &connection) const { return connection->id() + ".pcf"; } QString VpncUiPlugin::supportedFileExtensions() const { return "*.pcf"; } NMVariantMapMap VpncUiPlugin::importConnectionSettings(const QString &fileName) { // qCDebug(PLASMA_NM) << "Importing Cisco VPN connection from " << fileName; - VpncUiPluginPrivate * decrPlugin = 0; + VpncUiPluginPrivate * decrPlugin = nullptr; NMVariantMapMap result; if (!fileName.endsWith(QLatin1String(".pcf"), Qt::CaseInsensitive)) { return result; } mError = VpnUiPlugin::Error; // NOTE: Cisco VPN pcf files follow ini style matching KConfig files // http://www.cisco.com/en/US/docs/security/vpn_client/cisco_vpn_client/vpn_client46/administration/guide/vcAch2.html#wp1155033 KSharedConfig::Ptr config = KSharedConfig::openConfig(fileName); if (!config) { mErrorMessage = i18n("File %1 could not be opened.", fileName); return result; } KConfigGroup cg(config, "main"); // Keys&Values are stored under [main] if (cg.exists()) { // Setup cisco-decrypt binary to decrypt the passwords const QString ciscoDecryptBinary = QStandardPaths::findExecutable("cisco-decrypt"); if (ciscoDecryptBinary.isEmpty()) { mErrorMessage = i18n("Needed executable cisco-decrypt could not be found."); return result; } decrPlugin = new VpncUiPluginPrivate(); decrPlugin->ciscoDecrypt = new KProcess(decrPlugin); decrPlugin->ciscoDecrypt->setOutputChannelMode(KProcess::OnlyStdoutChannel); decrPlugin->ciscoDecrypt->setReadChannel(QProcess::StandardOutput); - connect(decrPlugin->ciscoDecrypt, static_cast(&KProcess::error), decrPlugin, &VpncUiPluginPrivate::ciscoDecryptError); - connect(decrPlugin->ciscoDecrypt, static_cast(&KProcess::finished), decrPlugin, &VpncUiPluginPrivate::ciscoDecryptFinished); + connect(decrPlugin->ciscoDecrypt, QOverload::of(&KProcess::error), decrPlugin, &VpncUiPluginPrivate::ciscoDecryptError); + connect(decrPlugin->ciscoDecrypt, QOverload::of(&KProcess::finished), decrPlugin, &VpncUiPluginPrivate::ciscoDecryptFinished); connect(decrPlugin->ciscoDecrypt, &KProcess::readyReadStandardOutput, decrPlugin, &VpncUiPluginPrivate::gotCiscoDecryptOutput); NMStringMap data; NMStringMap secretData; QVariantMap ipv4Data; // gateway data.insert(NM_VPNC_KEY_GATEWAY, decrPlugin->readStringKeyValue(cg,"Host")); // group name data.insert(NM_VPNC_KEY_ID, decrPlugin->readStringKeyValue(cg,"GroupName")); // user password if (!decrPlugin->readStringKeyValue(cg,"UserPassword").isEmpty()) { secretData.insert(NM_VPNC_KEY_XAUTH_PASSWORD, decrPlugin->readStringKeyValue(cg,"UserPassword")); } else if (!decrPlugin->readStringKeyValue(cg,"enc_UserPassword").isEmpty() && !ciscoDecryptBinary.isEmpty()) { // Decrypt the password and insert into map decrPlugin->ciscoDecrypt->setProgram(ciscoDecryptBinary); decrPlugin->ciscoDecrypt->start(); decrPlugin->ciscoDecrypt->waitForStarted(); decrPlugin->ciscoDecrypt->write(decrPlugin->readStringKeyValue(cg,"enc_UserPassword").toUtf8()); if (decrPlugin->ciscoDecrypt->waitForFinished()) { secretData.insert(NM_VPNC_KEY_XAUTH_PASSWORD, decrPlugin->decryptedPasswd); } } // Save user password switch (cg.readEntry("SaveUserPassword").toInt()) { case 0: data.insert(NM_VPNC_KEY_XAUTH_PASSWORD"-flags", QString::number(NetworkManager::Setting::NotSaved)); break; case 1: data.insert(NM_VPNC_KEY_XAUTH_PASSWORD"-flags", QString::number(NetworkManager::Setting::AgentOwned)); break; case 2: data.insert(NM_VPNC_KEY_XAUTH_PASSWORD"-flags", QString::number(NetworkManager::Setting::NotRequired)); break; } // group password if (!decrPlugin->readStringKeyValue(cg,"GroupPwd").isEmpty()) { secretData.insert(NM_VPNC_KEY_SECRET, decrPlugin->readStringKeyValue(cg,"GroupPwd")); data.insert(NM_VPNC_KEY_SECRET"-flags", QString::number(NetworkManager::Setting::AgentOwned)); } else if (!decrPlugin->readStringKeyValue(cg,"enc_GroupPwd").isEmpty() && !ciscoDecryptBinary.isEmpty()) { //Decrypt the password and insert into map decrPlugin->ciscoDecrypt->setProgram(ciscoDecryptBinary); decrPlugin->ciscoDecrypt->start(); decrPlugin->ciscoDecrypt->waitForStarted(); decrPlugin->ciscoDecrypt->write(decrPlugin->readStringKeyValue(cg,"enc_GroupPwd").toUtf8()); if (decrPlugin->ciscoDecrypt->waitForFinished()) { secretData.insert(NM_VPNC_KEY_SECRET, decrPlugin->decryptedPasswd); data.insert(NM_VPNC_KEY_SECRET"-flags", QString::number(NetworkManager::Setting::AgentOwned)); } } // Auth Type if (!cg.readEntry("AuthType").isEmpty() && cg.readEntry("AuthType").toInt() == 5) { data.insert(NM_VPNC_KEY_AUTHMODE, QLatin1String("hybrid")); } // Optional settings // username if (!decrPlugin->readStringKeyValue(cg,"Username").isEmpty()) { data.insert(NM_VPNC_KEY_XAUTH_USER, decrPlugin->readStringKeyValue(cg,"Username")); } // domain if (!decrPlugin->readStringKeyValue(cg,"NTDomain").isEmpty()) { data.insert(NM_VPNC_KEY_DOMAIN, decrPlugin->readStringKeyValue(cg,"NTDomain")); } // encryption if (!cg.readEntry("SingleDES").isEmpty() && cg.readEntry("SingleDES").toInt() != 0) { data.insert(NM_VPNC_KEY_SINGLE_DES, QLatin1String("yes")); } /* Disable all NAT Traversal if explicit EnableNat=0 exists, otherwise * default to NAT-T which is newer and standardized. If EnableNat=1, then * use Cisco-UDP like always; but if the key "X-NM-Use-NAT-T" is set, then * use NAT-T. If the key "X-NM-Force-NAT-T" is set then force NAT-T always * on. See vpnc documentation for more information on what the different * NAT modes are. */ // enable NAT if (cg.readEntry("EnableNat").toInt() == 1) { data.insert(NM_VPNC_KEY_NAT_TRAVERSAL_MODE, QLatin1String(NM_VPNC_NATT_MODE_CISCO)); // NAT traversal if (!cg.readEntry("X-NM-Use-NAT-T").isEmpty()) { if (cg.readEntry("X-NM-Use-NAT-T").toInt() == 1) { data.insert(NM_VPNC_KEY_NAT_TRAVERSAL_MODE, QLatin1String(NM_VPNC_NATT_MODE_NATT)); } if (cg.readEntry("X-NM-Force-NAT-T").toInt() == 1) { data.insert(NM_VPNC_KEY_NAT_TRAVERSAL_MODE, QLatin1String(NM_VPNC_NATT_MODE_NATT_ALWAYS)); } } } else { data.insert(NM_VPNC_KEY_NAT_TRAVERSAL_MODE, QLatin1String(NM_VPNC_NATT_MODE_NONE)); } // dead peer detection data.insert(NM_VPNC_KEY_DPD_IDLE_TIMEOUT, cg.readEntry("PeerTimeout")); // UseLegacyIKEPort=0 uses dynamic source IKE port instead of 500. if (cg.readEntry("UseLegacyIKEPort").isEmpty() || cg.readEntry("UseLegacyIKEPort").toInt() != 0) { data.insert(NM_VPNC_KEY_LOCAL_PORT, QString::number(NM_VPNC_LOCAL_PORT_DEFAULT)); } // DH Group data.insert(NM_VPNC_KEY_DHGROUP, decrPlugin->readStringKeyValue(cg,"DHGroup")); // Tunneling Mode - not supported by vpnc if (cg.readEntry("TunnelingMode").toInt() == 1) { - KMessageBox::error(0, i18n("The VPN settings file '%1' specifies that VPN traffic should be tunneled through TCP which is currently not supported in the vpnc software.\n\nThe connection can still be created, with TCP tunneling disabled, however it may not work as expected.", fileName), i18n("Not supported"), KMessageBox::Notify); + KMessageBox::error(nullptr, i18n("The VPN settings file '%1' specifies that VPN traffic should be tunneled through TCP which is currently not supported in the vpnc software.\n\nThe connection can still be created, with TCP tunneling disabled, however it may not work as expected.", fileName), i18n("Not supported"), KMessageBox::Notify); } // EnableLocalLAN and X-NM-Routes are to be added to IPv4Setting if (!cg.readEntry("EnableLocalLAN").isEmpty()) { ipv4Data.insert("never-default", cg.readEntry("EnableLocalLAN")); } if (!decrPlugin->readStringKeyValue(cg,"X-NM-Routes").isEmpty()) { QList list; Q_FOREACH (const QString &route, decrPlugin->readStringKeyValue(cg,"X-NM-Routes").split(' ')) { NetworkManager::IpRoute ipRoute; ipRoute.setIp(QHostAddress(route.split('/').first())); ipRoute.setPrefixLength(route.split('/').at(1).toInt()); list << ipRoute; } QList > dbusRoutes; Q_FOREACH (const NetworkManager::IpRoute &route, list) { QList dbusRoute; dbusRoute << htonl(route.ip().toIPv4Address()) << route.prefixLength() << htonl(route.nextHop().toIPv4Address()) << route.metric(); dbusRoutes << dbusRoute; } ipv4Data.insert("routes", QVariant::fromValue(dbusRoutes)); } // Set the '...-type' and '...-flags' value also NetworkManager::VpnSetting setting; setting.setServiceType("org.freedesktop.NetworkManager.vpnc"); setting.setData(data); setting.setSecrets(secretData); QVariantMap conn; if (decrPlugin->readStringKeyValue(cg,"Description").isEmpty()) { QFileInfo fileInfo(fileName); conn.insert("id", fileInfo.fileName().remove(QLatin1String(".pcf"), Qt::CaseInsensitive)); } else { conn.insert("id", decrPlugin->readStringKeyValue(cg,"Description")); } conn.insert("type", "vpn"); result.insert("connection", conn); result.insert("vpn", setting.toMap()); if (!ipv4Data.isEmpty()) { result.insert("ipv4", ipv4Data); } delete decrPlugin; } else { mErrorMessage = i18n("%1: file format error.", fileName); return result; } mError = VpncUiPlugin::NoError; return result; } bool VpncUiPlugin::exportConnectionSettings(const NetworkManager::ConnectionSettings::Ptr &connection, const QString &fileName) { NMStringMap data; NMStringMap secretData; NetworkManager::VpnSetting::Ptr vpnSetting = connection->setting(NetworkManager::Setting::Vpn).dynamicCast(); data = vpnSetting->data(); secretData = vpnSetting->secrets(); KSharedConfig::Ptr config = KSharedConfig::openConfig(fileName); if (!config) { mErrorMessage = i18n("%1: file could not be created", fileName); return false; } KConfigGroup cg(config,"main"); cg.writeEntry("Description", connection->id()); cg.writeEntry("Host", data.value(NM_VPNC_KEY_GATEWAY)); if (data.value(NM_VPNC_KEY_AUTHMODE) == QLatin1String("hybrid")) { cg.writeEntry("AuthType", "5"); } else { cg.writeEntry("AuthType", "1"); } cg.writeEntry("GroupName", data.value(NM_VPNC_KEY_ID)); cg.writeEntry("GroupPwd", secretData.value(NM_VPNC_KEY_SECRET)); cg.writeEntry("UserPassword", secretData.value(NM_VPNC_KEY_XAUTH_PASSWORD)); cg.writeEntry("enc_GroupPwd", ""); cg.writeEntry("enc_UserPassword", ""); if ((NetworkManager::Setting::SecretFlags)data.value(NM_VPNC_KEY_XAUTH_PASSWORD"-flags").toInt() & NetworkManager::Setting::NotSaved) { cg.writeEntry("SaveUserPassword", "0"); } if ((NetworkManager::Setting::SecretFlags)data.value(NM_VPNC_KEY_XAUTH_PASSWORD"-flags").toInt() & NetworkManager::Setting::AgentOwned) { cg.writeEntry("SaveUserPassword", "1"); } if ((NetworkManager::Setting::SecretFlags)data.value(NM_VPNC_KEY_XAUTH_PASSWORD"-flags").toInt() & NetworkManager::Setting::NotRequired) { cg.writeEntry("SaveUserPassword", "2"); } cg.writeEntry("Username", data.value(NM_VPNC_KEY_XAUTH_USER)); cg.writeEntry("EnableISPConnect", "0"); cg.writeEntry("ISPConnectType", "0"); cg.writeEntry("ISPConnect", ""); cg.writeEntry("ISPCommand", ""); cg.writeEntry("EnableBackup", "0"); cg.writeEntry("BackupServer", ""); cg.writeEntry("CertStore", "0"); cg.writeEntry("CertName", ""); cg.writeEntry("CertPath", ""); cg.writeEntry("CertSubjectName", ""); cg.writeEntry("CertSerialHash", ""); cg.writeEntry("DHGroup", data.value(NM_VPNC_KEY_DHGROUP)); cg.writeEntry("ForceKeepAlives", "0"); cg.writeEntry("NTDomain", data.value(NM_VPNC_KEY_DOMAIN)); cg.writeEntry("EnableMSLogon", "0"); cg.writeEntry("MSLogonType", "0"); cg.writeEntry("TunnelingMode", "0"); cg.writeEntry("TcpTunnelingPort", "10000"); cg.writeEntry("PeerTimeout", data.value(NM_VPNC_KEY_DPD_IDLE_TIMEOUT)); cg.writeEntry("EnableLocalLAN", "1"); cg.writeEntry("SendCertChain", "0"); cg.writeEntry("VerifyCertDN", ""); cg.writeEntry("EnableSplitDNS", "1"); cg.writeEntry("SPPhonebook", ""); if (data.value(NM_VPNC_KEY_SINGLE_DES) == "yes") { cg.writeEntry("SingleDES", "1"); } if (data.value(NM_VPNC_KEY_NAT_TRAVERSAL_MODE) == NM_VPNC_NATT_MODE_CISCO) { cg.writeEntry("EnableNat", "1"); } if (data.value(NM_VPNC_KEY_NAT_TRAVERSAL_MODE) == NM_VPNC_NATT_MODE_NATT) { cg.writeEntry("EnableNat", "1"); cg.writeEntry("X-NM-Use-NAT-T", "1"); } if (data.value(NM_VPNC_KEY_NAT_TRAVERSAL_MODE) == NM_VPNC_NATT_MODE_NATT_ALWAYS) { cg.writeEntry("EnableNat", "1"); cg.writeEntry("X-NM-Force-NAT-T", "1"); } // Export X-NM-Routes NetworkManager::Ipv4Setting::Ptr ipv4Setting = connection->setting(NetworkManager::Setting::Ipv4).dynamicCast(); if (!ipv4Setting->routes().isEmpty()) { QString routes; Q_FOREACH (const NetworkManager::IpRoute &route, ipv4Setting->routes()) { routes += route.ip().toString() + QLatin1Char('/') + QString::number(route.prefixLength()) + QLatin1Char(' '); } cg.writeEntry("X-NM-Routes", routes.trimmed()); } cg.sync(); mError = VpncUiPlugin::NoError; return true; } #include "vpnc.moc" diff --git a/vpn/vpnc/vpnc.h b/vpn/vpnc/vpnc.h index 3dd2fa87..0c3891bd 100644 --- a/vpn/vpnc/vpnc.h +++ b/vpn/vpnc/vpnc.h @@ -1,66 +1,66 @@ /* Copyright 2008 Will Stephenson Copyright 2011-2012 Rajeesh K Nambiar Copyright 2011-2012 Lamarque V. Souza Copyright 2013 Lukas Tinkl 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef PLASMA_NM_VPNC_H #define PLASMA_NM_VPNC_H #include "vpnuiplugin.h" #include #include #include class VpncUiPluginPrivate: public QObject { Q_OBJECT public: VpncUiPluginPrivate(); - ~VpncUiPluginPrivate(); + ~VpncUiPluginPrivate() override; QString readStringKeyValue(const KConfigGroup & configGroup, const QString & key); KProcess * ciscoDecrypt; QString decryptedPasswd; public Q_SLOTS: void gotCiscoDecryptOutput(); void ciscoDecryptError(QProcess::ProcessError pError); void ciscoDecryptFinished(int exitCode, QProcess::ExitStatus exitStatus); }; class Q_DECL_EXPORT VpncUiPlugin : public VpnUiPlugin { Q_OBJECT public: - explicit VpncUiPlugin(QObject * parent = 0, const QVariantList& = QVariantList()); - virtual ~VpncUiPlugin(); - virtual SettingWidget * widget(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = 0); - virtual SettingWidget * askUser(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = 0); + explicit VpncUiPlugin(QObject * parent = nullptr, const QVariantList& = QVariantList()); + ~VpncUiPlugin() override; + SettingWidget * widget(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = nullptr) override; + SettingWidget * askUser(const NetworkManager::VpnSetting::Ptr &setting, QWidget * parent = nullptr) override; - QString suggestedFileName(const NetworkManager::ConnectionSettings::Ptr &connection) const; - QString supportedFileExtensions() const; - NMVariantMapMap importConnectionSettings(const QString &fileName); - bool exportConnectionSettings(const NetworkManager::ConnectionSettings::Ptr &connection, const QString &fileName); + QString suggestedFileName(const NetworkManager::ConnectionSettings::Ptr &connection) const override; + QString supportedFileExtensions() const override; + NMVariantMapMap importConnectionSettings(const QString &fileName) override; + bool exportConnectionSettings(const NetworkManager::ConnectionSettings::Ptr &connection, const QString &fileName) override; }; #endif // PLASMA_NM_VPNC_H diff --git a/vpn/vpnc/vpncadvancedwidget.h b/vpn/vpnc/vpncadvancedwidget.h index 10188037..31372506 100644 --- a/vpn/vpnc/vpncadvancedwidget.h +++ b/vpn/vpnc/vpncadvancedwidget.h @@ -1,47 +1,47 @@ /* Copyright 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_VPNC_ADVANCED_WIDGET_H #define PLASMA_NM_VPNC_ADVANCED_WIDGET_H #include #include namespace Ui { class VpncAdvancedWidget; } class VpncAdvancedWidget : public QDialog { Q_OBJECT public: - explicit VpncAdvancedWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0); - ~VpncAdvancedWidget(); + explicit VpncAdvancedWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr); + ~VpncAdvancedWidget() override; NMStringMap setting() const; void loadConfig(const NetworkManager::VpnSetting::Ptr &setting); private: Ui::VpncAdvancedWidget * m_ui; }; #endif // PLASMA_NM_VPNC_ADVANCED_WIDGET_H diff --git a/vpn/vpnc/vpncauth.h b/vpn/vpnc/vpncauth.h index 4b3723a8..6b66bd48 100644 --- a/vpn/vpnc/vpncauth.h +++ b/vpn/vpnc/vpncauth.h @@ -1,46 +1,46 @@ /* Copyright 2008 Will Stephenson Copyright 2013 Lukas Tinkl 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 . */ #ifndef PLASMA_NM_VPNC_AUTH_H #define PLASMA_NM_VPNC_AUTH_H #include #include "settingwidget.h" class VpncAuthDialogPrivate; class VpncAuthDialog : public SettingWidget { Q_OBJECT Q_DECLARE_PRIVATE(VpncAuthDialog) public: - explicit VpncAuthDialog(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0); - ~VpncAuthDialog(); + explicit VpncAuthDialog(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr); + ~VpncAuthDialog() override; virtual void readSecrets(); - virtual QVariantMap setting() const; + QVariantMap setting() const override; private: VpncAuthDialogPrivate *const d_ptr; }; #endif // PLASMA_NM_VPNC_AUTH_H diff --git a/vpn/vpnc/vpncwidget.h b/vpn/vpnc/vpncwidget.h index 91dc601e..ce15b8fd 100644 --- a/vpn/vpnc/vpncwidget.h +++ b/vpn/vpnc/vpncwidget.h @@ -1,62 +1,62 @@ /* Copyright 2013 Lukas Tinkl This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef PLASMA_NM_VPNC_WIDGET_H #define PLASMA_NM_VPNC_WIDGET_H #include #include #include "settingwidget.h" #include "vpncadvancedwidget.h" namespace Ui { class VpncWidget; } class VpncWidget : public SettingWidget { Q_OBJECT public: - explicit VpncWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = 0, Qt::WindowFlags f = 0); - virtual ~VpncWidget(); + explicit VpncWidget(const NetworkManager::VpnSetting::Ptr &setting, QWidget *parent = nullptr, Qt::WindowFlags f = {}); + ~VpncWidget() override; - void loadConfig(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; - void loadSecrets(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; + void loadConfig(const NetworkManager::Setting::Ptr &setting) override; + void loadSecrets(const NetworkManager::Setting::Ptr &setting) override; - QVariantMap setting() const; + QVariantMap setting() const override; - virtual bool isValid() const; + bool isValid() const override; private Q_SLOTS: void userPasswordTypeChanged(int index); void groupPasswordTypeChanged(int index); void showAdvanced(); private: Ui::VpncWidget *m_ui; NetworkManager::VpnSetting::Ptr m_setting; NetworkManager::VpnSetting::Ptr m_tmpSetting; QPointer m_advancedWidget; }; #endif // PLASMA_NM_VPNC_WIDGET_H