diff --git a/applet/contents/ui/ConnectionItem.qml b/applet/contents/ui/ConnectionItem.qml index 3fba0374..36419826 100644 --- a/applet/contents/ui/ConnectionItem.qml +++ b/applet/contents/ui/ConnectionItem.qml @@ -1,416 +1,415 @@ /* 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 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 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 && - (Type == PlasmaNM.Enums.Wimax || - Type == PlasmaNM.Enums.Wired || + (Type == PlasmaNM.Enums.Wired || Type == PlasmaNM.Enums.Wireless || Type == PlasmaNM.Enums.Gsm || Type == PlasmaNM.Enums.Cdma) property bool visibleDetails: false property bool visiblePasswordDialog: false 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 } } PlasmaComponents.Label { id: connectionNameLabel anchors { bottom: connectionSvgIcon.verticalCenter left: connectionSvgIcon.right leftMargin: Math.round(units.gridUnit / 2) right: stateChangeButton.visible ? stateChangeButton.left : parent.right } 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 } height: paintedHeight elide: Text.ElideRight font.pointSize: theme.smallestFont.pointSize opacity: 0.6 text: itemText() } PlasmaComponents.BusyIndicator { id: connectingIndicator 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 anchors { right: parent.right rightMargin: Math.round(units.gridUnit / 2) verticalCenter: connectionSvgIcon.verticalCenter } 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 anchors { left: parent.left right: parent.right top: connectionItemBase.bottom } } Component { id: detailsComponent Item { height: childrenRect.height Separator { id: detailsSeparator anchors { left: parent.left right: parent.right top: parent.top } } PlasmaComponents.TabBar { id: detailsTabBar; anchors { left: parent.left right: parent.right top: detailsSeparator.bottom topMargin: Math.round(units.gridUnit / 3) } height: visible ? implicitHeight : 0 visible: showSpeed && dataSource.data && dataSource.data[dataSource.downloadSource] && dataSource.data[dataSource.uploadSource] PlasmaComponents.TabButton { id: speedTabButton; text: i18n("Speed"); } PlasmaComponents.TabButton { id: detailsTabButton; text: i18n("Details"); } Component.onCompleted: { if (!speedTabButton.visible) { currentTab = detailsTabButton; } } } DetailsText { anchors { left: parent.left leftMargin: units.iconSizes.medium right: parent.right top: detailsTabBar.visible ? detailsTabBar.bottom : detailsSeparator.bottom 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 topMargin: Math.round(units.gridUnit / 3) } dataEngine: dataSource deviceName: DeviceName visible: detailsTabBar.currentTab == speedTabButton } } } Component { id: passwordDialogComponent Item { property alias password: passwordField.text property alias passwordInput: passwordField height: childrenRect.height Separator { id: passwordSeparator 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 } } } } 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); } else if (visiblePasswordDialog) { if (expandableComponentLoader.item.password != "") { handler.addAndActivateConnection(DevicePath, SpecificPath, expandableComponentLoader.item.password); visiblePasswordDialog = false; } else { connectionItem.clicked(); } } else { handler.activateConnection(ConnectionPath, DevicePath, SpecificPath); } } else { handler.deactivateConnection(ConnectionPath, DevicePath); } } else if (predictableWirelessPassword) { appletProxyModel.dynamicSortFilter = false; visiblePasswordDialog = true; } } function itemText() { if (ConnectionState == PlasmaNM.Enums.Activating) { if (Type == PlasmaNM.Enums.Vpn) return VpnState; else return DeviceState; } else if (ConnectionState == PlasmaNM.Enums.Deactivating) { if (Type == PlasmaNM.Enums.Vpn) return VpnState; else return DeviceState; } else if (ConnectionState == PlasmaNM.Enums.Deactivated) { var result = LastUsed; if (SecurityType > PlasmaNM.Enums.NoneSecurity) result += ", " + SecurityTypeString; return result; } else if (ConnectionState == PlasmaNM.Enums.Activated) { if (showSpeed && dataSource.data && dataSource.data[dataSource.downloadSource] && dataSource.data[dataSource.uploadSource]) { return i18n("Connected, %2/s, %4/s", theme.highlightColor, KCoreAddons.Format.formatByteSize(dataSource.data[dataSource.downloadSource].value * 1024 || 0), cycle(theme.highlightColor, -180), KCoreAddons.Format.formatByteSize(dataSource.data[dataSource.uploadSource].value * 1024 || 0)); } else { return i18n("Connected"); } } } /* * Stolen from the system monitor applet * from plasma-workspace/applets/systemmonitor/common/contents/ui/DoublePlotter.qml */ function cycle(color, degrees) { var min = Math.min(color.r, Math.min(color.g, color.b)); var max = Math.max(color.r, Math.max(color.g, color.b)); var c = max - min; var h; if (c == 0) { h = 0 } else if (max == color.r) { h = ((color.g - color.b) / c) % 6; } else if (max == color.g) { h = ((color.b - color.r) / c) + 2; } else if (max == color.b) { h = ((color.r - color.g) / c) + 4; } var hue = (1/6) * h + (degrees/360); var saturation = c / (1 - Math.abs(2 * ((max+min)/2) - 1)); var lightness = (max + min)/3; return Qt.hsla(hue, saturation, lightness, 1.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/DetailsText.qml b/applet/contents/ui/DetailsText.qml index 27be5d73..6554679e 100644 --- a/applet/contents/ui/DetailsText.qml +++ b/applet/contents/ui/DetailsText.qml @@ -1,121 +1,121 @@ /* 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.kquickcontrolsaddons 2.0 as KQuickControlsAddons import org.kde.plasma.components 2.0 as PlasmaComponents Item { property var details: [] height: repeater.contentHeight KQuickControlsAddons.Clipboard { id: clipboard } PlasmaComponents.ContextMenu { id: contextMenu property string text function show(item, text, x, y) { contextMenu.text = text visualParent = item open(x, y) } PlasmaComponents.MenuItem { text: i18n("Copy") icon: "edit-copy" enabled: contextMenu.text !== "" onClicked: clipboard.content = contextMenu.text } } Column { anchors.fill: parent Repeater { id: repeater property int contentHeight: 0 property int longestString: 0 model: details.length / 2 Item { anchors { left: parent.left right: parent.right topMargin: Math.round(units.gridUnit / 3) } height: Math.max(detailNameLabel.height, detailValueLabel.height) PlasmaComponents.Label { id: detailNameLabel anchors { left: parent.left leftMargin: repeater.longestString - paintedWidth + Math.round(units.gridUnit / 2) verticalCenter: parent.verticalCenter } height: paintedHeight font.pointSize: theme.smallestFont.pointSize horizontalAlignment: Text.AlignRight opacity: 0.6 text: "" + details[index*2] + ":  " Component.onCompleted: { if (paintedWidth > repeater.longestString) { repeater.longestString = paintedWidth } } } PlasmaComponents.Label { id: detailValueLabel anchors { left: detailNameLabel.right right: parent.right verticalCenter: parent.verticalCenter } height: paintedHeight elide: Text.ElideRight font.pointSize: theme.smallestFont.pointSize opacity: 0.6 text: details[(index*2)+1] textFormat: Text.PlainText MouseArea { anchors.fill: parent acceptedButtons: Qt.RightButton - onClicked: contextMenu.show(this, detailValueLabel.text, mouse.x, mouse.y) + onPressed: contextMenu.show(this, detailValueLabel.text, mouse.x, mouse.y) } } } // Count total height from added items, somehow contentRect.height doesn't work onItemAdded: { contentHeight = contentHeight + item.height } } } } diff --git a/kcm/kcm.cpp b/kcm/kcm.cpp index be490b1a..88e9b244 100755 --- a/kcm/kcm.cpp +++ b/kcm/kcm.cpp @@ -1,498 +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); 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)) { - loadConnectionSettings(activeConnection->connection()->settings()); 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)) { - loadConnectionSettings(connection->settings()); 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()) { - Q_EMIT changed(true); + kcmChanged(true); } }); connect(m_tabWidget, &ConnectionEditorTabWidget::validityChanged, [this] (bool valid) { if (m_tabWidget->isInitialized()) { - Q_EMIT changed(valid); + kcmChanged(valid); } }); QVBoxLayout *layout = new QVBoxLayout(m_ui->connectionConfiguration); layout->addWidget(m_tabWidget); } - Q_EMIT changed(false); -} -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); + 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 adb924ca..462c99c0 100755 --- a/kcm/kcm.h +++ b/kcm/kcm.h @@ -1,65 +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(); 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(); - void importVpn(); 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/qml/ConnectionItem.qml b/kcm/qml/ConnectionItem.qml index 3fad2252..53d20eec 100644 --- a/kcm/qml/ConnectionItem.qml +++ b/kcm/qml/ConnectionItem.qml @@ -1,167 +1,166 @@ /* 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 org.kde.kquickcontrolsaddons 2.0 as KQuickControlsAddons import org.kde.plasma.core 2.0 as PlasmaCore import org.kde.plasma.components 2.0 as PlasmaComponents import org.kde.plasma.networkmanagement 0.2 as PlasmaNM ListItem { id: connectionItem checked: mouseArea.containsMouse || ConnectionPath === connectionView.currentConnectionPath height: connectionItemBase.height + signal aboutToChangeConnection(bool exportable, string name, string path) signal aboutToExportConnection(string path) signal aboutToRemoveConnection(string name, string path) Item { id: connectionItemBase anchors { left: parent.left right: parent.right top: parent.top topMargin: -Math.round(units.gridUnit / 3) } height: Math.max(units.iconSizes.medium, connectionNameLabel.height + connectionStatusLabel.height) + Math.round(units.gridUnit / 2) KQuickControlsAddons.QIconItem { id: connectionIcon anchors { left: parent.left verticalCenter: parent.verticalCenter } height: units.iconSizes.medium; width: height icon: KcmConnectionIcon } Text { id: connectionNameLabel anchors { bottom: connectionIcon.verticalCenter left: connectionIcon.right leftMargin: Math.round(units.gridUnit / 2) right: connectingIndicator.visible ? connectingIndicator.left : parent.right } color: textColor height: paintedHeight elide: Text.ElideRight font.weight: ConnectionState == PlasmaNM.Enums.Activated ? Font.DemiBold : Font.Normal font.italic: ConnectionState == PlasmaNM.Enums.Activating ? true : false text: Name textFormat: Text.PlainText } Text { id: connectionStatusLabel anchors { left: connectionIcon.right leftMargin: Math.round(units.gridUnit / 2) right: connectingIndicator.visible ? connectingIndicator.left : parent.right top: connectionNameLabel.bottom } color: textColor height: paintedHeight elide: Text.ElideRight font.pointSize: theme.smallestFont.pointSize opacity: 0.6 text: itemText() } PlasmaComponents.BusyIndicator { id: connectingIndicator anchors { right: parent.right rightMargin: Math.round(units.gridUnit / 2) verticalCenter: connectionIcon.verticalCenter } height: units.iconSizes.medium; width: height running: ConnectionState == PlasmaNM.Enums.Activating visible: running } } PlasmaComponents.Menu { id: connectionItemMenu visualParent: mouseArea PlasmaComponents.MenuItem { text: ConnectionState == PlasmaNM.Enums.Deactivated ? i18n("Connect") : i18n("Disconnect") visible: ItemType == 1 onClicked: { if (ConnectionState == PlasmaNM.Enums.Deactivated) { handler.activateConnection(ConnectionPath, DevicePath, SpecificPath); } else { handler.deactivateConnection(ConnectionPath, DevicePath); } } } PlasmaComponents.MenuItem { icon: "list-remove" text: i18n("Delete"); onClicked: { aboutToRemoveConnection(Name, ConnectionPath) } } PlasmaComponents.MenuItem { icon: "document-export" visible: KcmVpnConnectionExportable text: i18n("Export"); onClicked: aboutToExportConnection(ConnectionPath) } } MouseArea { id: mouseArea anchors.fill: parent acceptedButtons: Qt.AllButtons; hoverEnabled: true onClicked: { if (mouse.button === Qt.LeftButton) { - connectionView.currentConnectionExportable = KcmVpnConnectionExportable - connectionView.currentConnectionName = Name - connectionView.currentConnectionPath = ConnectionPath + aboutToChangeConnection(KcmVpnConnectionExportable, Name, ConnectionPath) } else if (mouse.button == Qt.RightButton) { connectionItemMenu.open(mouse.x, mouse.y) } } } function itemText() { if (ConnectionState == PlasmaNM.Enums.Activated) { return i18n("Connected") } else if (ConnectionState == PlasmaNM.Enums.Activating) { return i18n("Connecting") } else { return LastUsed } } } diff --git a/kcm/qml/Dialog.qml b/kcm/qml/Dialog.qml index 0075830e..425282f2 100644 --- a/kcm/qml/Dialog.qml +++ b/kcm/qml/Dialog.qml @@ -1,192 +1,192 @@ /* 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.3 import QtQuick.Dialogs 1.2 import QtQuick.Controls 1.2 as QtControls import org.kde.kquickcontrolsaddons 2.0 as KQuickControlsAddons 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 Dialog { id: dialog - title: i18n("Choose a connection type") + title: i18nc("@title:window", "Choose a Connection Type") signal requestCreateConnection(int type, string vpnType, string specificType, bool shared) contentItem: Item { implicitHeight: 600 implicitWidth: 500 PlasmaNM.CreatableConnectionsModel { id: connectionModel } Rectangle { id: background anchors.fill: parent focus: true color: baseColor } PlasmaExtras.ScrollArea { id: scrollView anchors { bottom: buttonRow.top bottomMargin: Math.round(units.gridUnit / 2) left: parent.left right: parent.right top: parent.top } ListView { id: view property int currentlySelectedIndex: -1 property bool connectionShared property string connectionSpecificType property int connectionType property string connectionVpnType anchors.fill: parent clip: true model: connectionModel currentIndex: -1 boundsBehavior: Flickable.StopAtBounds section.property: "ConnectionTypeSection" section.delegate: Header { text: section } delegate: ListItem { checked: mouseArea.containsMouse || view.currentlySelectedIndex == index height: connectionTypeBase.height Item { id: connectionTypeBase 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 + connectionDescriptionLabel.height) + Math.round(units.gridUnit / 2) KQuickControlsAddons.QIconItem { id: connectionIcon anchors { left: parent.left verticalCenter: parent.verticalCenter } height: units.iconSizes.medium; width: height icon: ConnectionIcon } Text { id: connectionNameLabel anchors { bottom: ConnectionType == 11 ? connectionIcon.verticalCenter : undefined left: connectionIcon.right leftMargin: Math.round(units.gridUnit / 2) right: parent.right verticalCenter: ConnectionType == 11 ? undefined : parent.verticalCenter } color: textColor height: paintedHeight elide: Text.ElideRight text: ConnectionTypeName textFormat: Text.PlainText } Text { id: connectionDescriptionLabel anchors { left: connectionIcon.right leftMargin: Math.round(units.gridUnit / 2) right: parent.right top: connectionNameLabel.bottom } color: textColor height: visible ? paintedHeight : 0 elide: Text.ElideRight font.pointSize: theme.smallestFont.pointSize opacity: 0.6 text: ConnectionDescription visible: ConnectionType == 11 // VPN } } MouseArea { id: mouseArea anchors.fill: parent hoverEnabled: true onClicked: { createButton.enabled = true view.currentlySelectedIndex = index view.connectionSpecificType = ConnectionSpecificType view.connectionShared = ConnectionShared view.connectionType = ConnectionType view.connectionVpnType = ConnectionVpnType } onDoubleClicked: { dialog.close() dialog.requestCreateConnection(view.connectionType, view.connectionVpnType, view.connectionSpecificType, view.connectionShared) } } } } } Row { id: buttonRow anchors { bottom: parent.bottom right: parent.right margins: Math.round(units.gridUnit / 2) } spacing: Math.round(units.gridUnit / 2) QtControls.Button { id: createButton enabled: false text: i18n("Create") onClicked: { dialog.close() dialog.requestCreateConnection(view.connectionType, view.connectionVpnType, view.connectionSpecificType, view.connectionShared) } } QtControls.Button { - id: closeButton - text: i18n("Close") + id: cancelButton + text: i18n("Cancel") onClicked: { dialog.close() } } } } } diff --git a/kcm/qml/main.qml b/kcm/qml/main.qml index ba8a311d..e8c4b2eb 100755 --- a/kcm/qml/main.qml +++ b/kcm/qml/main.qml @@ -1,202 +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 { 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 { - onAboutToRemoveConnection: { - deleteConfirmationDialog.connectionName = name - deleteConfirmationDialog.connectionPath = path - deleteConfirmationDialog.open() + 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.Close - title: i18n("Remove connection") - text: i18n("Do you want to remove the connection '%1'", connectionName) + 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/networkmanagement.notifyrc b/kded/networkmanagement.notifyrc index 15d0b7db..35b36d7a 100644 --- a/kded/networkmanagement.notifyrc +++ b/kded/networkmanagement.notifyrc @@ -1,779 +1,780 @@ [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[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[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[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[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[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[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[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 fallo Name[he]=ההתקן נכשל Name[hu]=Az eszköz meghiúsult Name[ia]=Dispositivo falleva 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 foi posíbel activar a conexión +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[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 foi posíbel engadir a conexión +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[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 foi posíbel desactivar a conexión +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[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 foi posíbel retirar a conexión +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[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 foi posíbel obter os segredos +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[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 foi posíbel actualizar a conexión +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[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[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[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[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/passworddialog.ui b/kded/passworddialog.ui index 1f0a2a93..c2322a75 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 + 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/libs/declarative/availabledevices.cpp b/libs/declarative/availabledevices.cpp index 86126bb7..0e312c6f 100644 --- a/libs/declarative/availabledevices.cpp +++ b/libs/declarative/availabledevices.cpp @@ -1,164 +1,131 @@ /* 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 "availabledevices.h" #include AvailableDevices::AvailableDevices(QObject* parent) : QObject(parent) , m_wiredDeviceAvailable(false) , m_wirelessDeviceAvailable(false) -#if !NM_CHECK_VERSION(1, 2, 0) - , m_wimaxDeviceAvailable(false) -#endif , m_modemDeviceAvailable(false) , m_bluetoothDeviceAvailable(false) { Q_FOREACH (const NetworkManager::Device::Ptr& device, NetworkManager::networkInterfaces()) { if (device->type() == NetworkManager::Device::Modem) { m_modemDeviceAvailable = true; } else if (device->type() == NetworkManager::Device::Wifi) { m_wirelessDeviceAvailable = true; -#if !NM_CHECK_VERSION(1, 2, 0) - } else if (device->type() == NetworkManager::Device::Wimax) { - m_wimaxDeviceAvailable = true; -#endif } else if (device->type() == NetworkManager::Device::Ethernet) { m_wiredDeviceAvailable = true; } else if (device->type() == NetworkManager::Device::Bluetooth) { m_bluetoothDeviceAvailable = true; } } connect(NetworkManager::notifier(), &NetworkManager::Notifier::deviceAdded, this, &AvailableDevices::deviceAdded); connect(NetworkManager::notifier(), &NetworkManager::Notifier::deviceRemoved, this, &AvailableDevices::deviceRemoved); } AvailableDevices::~AvailableDevices() { } bool AvailableDevices::isWiredDeviceAvailable() const { return m_wiredDeviceAvailable; } bool AvailableDevices::isWirelessDeviceAvailable() const { return m_wirelessDeviceAvailable; } -#if !NM_CHECK_VERSION(1, 2, 0) -bool AvailableDevices::isWimaxDeviceAvailable() const -{ - return m_wimaxDeviceAvailable; -} -#endif - bool AvailableDevices::isModemDeviceAvailable() const { return m_modemDeviceAvailable; } bool AvailableDevices::isBluetoothDeviceAvailable() const { return m_bluetoothDeviceAvailable; } void AvailableDevices::deviceAdded(const QString& dev) { NetworkManager::Device::Ptr device = NetworkManager::findNetworkInterface(dev); if (device) { if (device->type() == NetworkManager::Device::Modem && !m_modemDeviceAvailable) { m_modemDeviceAvailable = true; Q_EMIT modemDeviceAvailableChanged(true); } else if (device->type() == NetworkManager::Device::Wifi && !m_wirelessDeviceAvailable) { m_wirelessDeviceAvailable = true; Q_EMIT wirelessDeviceAvailableChanged(true); -#if !NM_CHECK_VERSION(1, 2, 0) - } else if (device->type() == NetworkManager::Device::Wimax && !m_wimaxDeviceAvailable) { - m_wimaxDeviceAvailable = true; - Q_EMIT wimaxDeviceAvailableChanged(true); -#endif } else if (device->type() == NetworkManager::Device::Ethernet && !m_wiredDeviceAvailable) { m_wiredDeviceAvailable = true; Q_EMIT wiredDeviceAvailableChanged(true); } else if (device->type() == NetworkManager::Device::Bluetooth && !m_bluetoothDeviceAvailable) { m_bluetoothDeviceAvailable = true; Q_EMIT bluetoothDeviceAvailableChanged(true); } } } void AvailableDevices::deviceRemoved() { bool wired = false; bool wireless = false; -#if !NM_CHECK_VERSION(1, 2, 0) - bool wimax = false; -#endif bool modem = false; bool bluetooth = false; Q_FOREACH (const NetworkManager::Device::Ptr& device, NetworkManager::networkInterfaces()) { if (device->type() == NetworkManager::Device::Modem) { modem = true; } else if (device->type() == NetworkManager::Device::Wifi) { wireless = true; -#if !NM_CHECK_VERSION(1, 2, 0) - } else if (device->type() == NetworkManager::Device::Wimax) { - wimax = true; -#endif } else if (device->type() == NetworkManager::Device::Ethernet) { wired = true; } else if (device->type() == NetworkManager::Device::Bluetooth) { bluetooth = true; } } if (!wired && m_wiredDeviceAvailable) { m_wiredDeviceAvailable = false; Q_EMIT wiredDeviceAvailableChanged(false); } if (!wireless && m_wirelessDeviceAvailable) { m_wirelessDeviceAvailable = false; Q_EMIT wirelessDeviceAvailableChanged(false); } -#if !NM_CHECK_VERSION(1, 2, 0) - if (!wimax && m_wimaxDeviceAvailable) { - m_wimaxDeviceAvailable = false; - Q_EMIT wimaxDeviceAvailableChanged(false); - } -#endif - if (!modem && m_modemDeviceAvailable) { m_modemDeviceAvailable = false; Q_EMIT modemDeviceAvailableChanged(false); } if (!bluetooth && m_bluetoothDeviceAvailable) { m_bluetoothDeviceAvailable = false; Q_EMIT bluetoothDeviceAvailableChanged(false); } } diff --git a/libs/declarative/availabledevices.h b/libs/declarative/availabledevices.h index 72ef392f..99aa1063 100644 --- a/libs/declarative/availabledevices.h +++ b/libs/declarative/availabledevices.h @@ -1,92 +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) -#if !NM_CHECK_VERSION(1, 2, 0) -/** - * Return true when there is present wimax device - */ -Q_PROPERTY(bool wimaxDeviceAvailable READ isWimaxDeviceAvailable NOTIFY wimaxDeviceAvailableChanged) -#endif - /** * 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(); public Q_SLOTS: bool isWiredDeviceAvailable() const; bool isWirelessDeviceAvailable() const; -#if !NM_CHECK_VERSION(1, 2, 0) - bool isWimaxDeviceAvailable() const; -#endif 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); -#if !NM_CHECK_VERSION(1, 2, 0) - void wimaxDeviceAvailableChanged(bool available); -#endif void modemDeviceAvailableChanged(bool available); void bluetoothDeviceAvailableChanged(bool available); private: bool m_wiredDeviceAvailable; bool m_wirelessDeviceAvailable; -#if !NM_CHECK_VERSION(1, 2, 0) - bool m_wimaxDeviceAvailable; -#endif bool m_modemDeviceAvailable; bool m_bluetoothDeviceAvailable; }; #endif // PLASMA_NM_AVAILABLE_DEVICES_H diff --git a/libs/declarative/enabledconnections.cpp b/libs/declarative/enabledconnections.cpp index dc10215b..adec8fde 100644 --- a/libs/declarative/enabledconnections.cpp +++ b/libs/declarative/enabledconnections.cpp @@ -1,130 +1,96 @@ /* 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 "enabledconnections.h" EnabledConnections::EnabledConnections(QObject* parent) : QObject(parent) , m_networkingEnabled(NetworkManager::isNetworkingEnabled()) , m_wirelessEnabled(NetworkManager::isWirelessEnabled()) , m_wirelessHwEnabled(NetworkManager::isWirelessHardwareEnabled()) -#if !NM_CHECK_VERSION(1, 2, 0) - , m_wimaxEnabled(NetworkManager::isWimaxEnabled()) - , m_wimaxHwEnabled(NetworkManager::isWimaxHardwareEnabled()) -#endif , m_wwanEnabled(NetworkManager::isWwanEnabled()) , m_wwanHwEnabled(NetworkManager::isWwanHardwareEnabled()) { connect(NetworkManager::notifier(), &NetworkManager::Notifier::networkingEnabledChanged, this, &EnabledConnections::onNetworkingEnabled); connect(NetworkManager::notifier(), &NetworkManager::Notifier::wirelessEnabledChanged, this, &EnabledConnections::onWirelessEnabled); connect(NetworkManager::notifier(), &NetworkManager::Notifier::wirelessHardwareEnabledChanged, this, &EnabledConnections::onWirelessHwEnabled); -#if !NM_CHECK_VERSION(1, 2, 0) - connect(NetworkManager::notifier(), &NetworkManager::Notifier::wimaxEnabledChanged, this, &EnabledConnections::onWimaxEnabled); - connect(NetworkManager::notifier(), &NetworkManager::Notifier::wimaxHardwareEnabledChanged, this, &EnabledConnections::onWimaxHwEnabled); -#endif connect(NetworkManager::notifier(), &NetworkManager::Notifier::wwanEnabledChanged, this, &EnabledConnections::onWwanEnabled); connect(NetworkManager::notifier(), &NetworkManager::Notifier::wwanHardwareEnabledChanged, this, &EnabledConnections::onWwanHwEnabled); } EnabledConnections::~EnabledConnections() { } bool EnabledConnections::isNetworkingEnabled() const { return m_networkingEnabled; } bool EnabledConnections::isWirelessEnabled() const { return m_wirelessEnabled; } bool EnabledConnections::isWirelessHwEnabled() const { return m_wirelessHwEnabled; } -#if !NM_CHECK_VERSION(1, 2, 0) -bool EnabledConnections::isWimaxEnabled() const -{ - return m_wimaxEnabled; -} - -bool EnabledConnections::isWimaxHwEnabled() const -{ - return m_wimaxHwEnabled; -} -#endif - bool EnabledConnections::isWwanEnabled() const { return m_wwanEnabled; } bool EnabledConnections::isWwanHwEnabled() const { return m_wwanHwEnabled; } void EnabledConnections::onNetworkingEnabled(bool enabled) { m_networkingEnabled = enabled; Q_EMIT networkingEnabled(enabled); } void EnabledConnections::onWirelessEnabled(bool enabled) { m_wirelessEnabled = enabled; Q_EMIT wirelessEnabled(enabled); } void EnabledConnections::onWirelessHwEnabled(bool enabled) { m_wirelessHwEnabled = enabled; Q_EMIT wirelessHwEnabled(enabled); } -#if !NM_CHECK_VERSION(1, 2, 0) -void EnabledConnections::onWimaxEnabled(bool enabled) -{ - m_wimaxEnabled = enabled; - Q_EMIT wimaxEnabled(enabled); -} - -void EnabledConnections::onWimaxHwEnabled(bool enabled) -{ - m_wimaxHwEnabled = enabled; - Q_EMIT wimaxHwEnabled(enabled); -} -#endif - void EnabledConnections::onWwanEnabled(bool enabled) { m_wwanEnabled = enabled; Q_EMIT wwanEnabled(enabled); } void EnabledConnections::onWwanHwEnabled(bool enabled) { m_wwanHwEnabled = enabled; Q_EMIT wwanHwEnabled(enabled); } diff --git a/libs/declarative/enabledconnections.h b/libs/declarative/enabledconnections.h index e8bf3be3..bcb7dfb8 100644 --- a/libs/declarative/enabledconnections.h +++ b/libs/declarative/enabledconnections.h @@ -1,111 +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) - -#if !NM_CHECK_VERSION(1, 2, 0) -/** - * Indicates if WiMAX devices are currently enabled or not - */ -Q_PROPERTY(bool wimaxEnabled READ isWimaxEnabled NOTIFY wimaxEnabled) -/** - * Indicates if the WiMAX hardware is currently enabled, i.e. the state of the RF kill switch. - */ -Q_PROPERTY(bool wimaxHwEnabled READ isWimaxHwEnabled NOTIFY wimaxHwEnabled) -#endif - /** * 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(); bool isNetworkingEnabled() const; bool isWirelessEnabled() const; bool isWirelessHwEnabled() const; -#if !NM_CHECK_VERSION(1, 2, 0) - bool isWimaxEnabled() const; - bool isWimaxHwEnabled() const; -#endif bool isWwanEnabled() const; bool isWwanHwEnabled() const; public Q_SLOTS: void onNetworkingEnabled(bool enabled); void onWirelessEnabled(bool enabled); void onWirelessHwEnabled(bool enabled); -#if !NM_CHECK_VERSION(1, 2, 0) - void onWimaxEnabled(bool enabled); - void onWimaxHwEnabled(bool enabled); -#endif void onWwanEnabled(bool enabled); void onWwanHwEnabled(bool enabled); Q_SIGNALS: void networkingEnabled(bool enabled); void wirelessEnabled(bool enabled); void wirelessHwEnabled(bool enabled); -#if !NM_CHECK_VERSION(1, 2, 0) - void wimaxEnabled(bool enabled); - void wimaxHwEnabled(bool enabled); -#endif void wwanEnabled(bool enabled); void wwanHwEnabled(bool enabled); private: bool m_networkingEnabled; bool m_wirelessEnabled; bool m_wirelessHwEnabled; -#if !NM_CHECK_VERSION(1, 2, 0) - bool m_wimaxEnabled; - bool m_wimaxHwEnabled; -#endif bool m_wwanEnabled; bool m_wwanHwEnabled; }; #endif // PLASMA_NM_ENABLED_CONNECTIONS_H diff --git a/libs/declarative/networkstatus.cpp b/libs/declarative/networkstatus.cpp index ec3e0956..75df4a77 100644 --- a/libs/declarative/networkstatus.cpp +++ b/libs/declarative/networkstatus.cpp @@ -1,243 +1,240 @@ /* 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::Wimax: - return NetworkStatus::Wimax; - 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)); 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); } else if (connected) { status = i18n("Connected to %1", connectionName); } 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 9d63110b..750f5775 100644 --- a/libs/declarative/networkstatus.h +++ b/libs/declarative/networkstatus.h @@ -1,79 +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, - Wimax, Gsm, Cdma, Pppoe, Adsl, Infiniband, OLPCMesh, Bluetooth, Vpn, Other }; static SortedConnectionType connectionTypeToSortedType(NetworkManager::ConnectionSettings::ConnectionType type); explicit NetworkStatus(QObject* parent = 0); virtual ~NetworkStatus(); 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/editor/CMakeLists.txt b/libs/editor/CMakeLists.txt index e7272e53..dd63248c 100644 --- a/libs/editor/CMakeLists.txt +++ b/libs/editor/CMakeLists.txt @@ -1,116 +1,114 @@ 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/wimaxwidget.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 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/wimax.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 Qt5::Widgets 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) endif() install(TARGETS plasmanm_editor ${INSTALL_TARGETS_DEFAULT_ARGS}) install(FILES plasma-networkmanagement-vpnuiplugin.desktop DESTINATION ${SERVICETYPES_INSTALL_DIR}) diff --git a/libs/editor/connectioneditorbase.cpp b/libs/editor/connectioneditorbase.cpp index f9251456..6e423a53 100644 --- a/libs/editor/connectioneditorbase.cpp +++ b/libs/editor/connectioneditorbase.cpp @@ -1,481 +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 "settings/wimaxwidget.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); } 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; 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 - || type == NetworkManager::ConnectionSettings::Wimax #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) { + 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/settings/ipv4widget.cpp b/libs/editor/settings/ipv4widget.cpp index 971db67b..65951d39 100644 --- a/libs/editor/settings/ipv4widget.cpp +++ b/libs/editor/settings/ipv4widget.cpp @@ -1,498 +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); 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(&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/ipv6widget.cpp b/libs/editor/settings/ipv6widget.cpp index 5f427925..c871374d 100644 --- a/libs/editor/settings/ipv6widget.cpp +++ b/libs/editor/settings/ipv6widget.cpp @@ -1,489 +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); 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(&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/security802-1x.cpp b/libs/editor/settings/security802-1x.cpp index 7f9897a1..d6405bf1 100644 --- a/libs/editor/settings/security802-1x.cpp +++ b/libs/editor/settings/security802-1x.cpp @@ -1,586 +1,601 @@ /* 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->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::EapMethodFast); m_ui->auth->setItemData(3, NetworkManager::Security8021xSetting::EapMethodTtls); m_ui->auth->setItemData(4, 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::EapMethodFast); m_ui->auth->setItemData(3, NetworkManager::Security8021xSetting::EapMethodTtls); m_ui->auth->setItemData(4, 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->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->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::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::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::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::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/ui/802-1x.ui b/libs/editor/settings/ui/802-1x.ui index 8aab1b5e..aaa46fa4 100644 --- a/libs/editor/settings/ui/802-1x.ui +++ b/libs/editor/settings/ui/802-1x.ui @@ -1,770 +1,803 @@ Lukáš Tinkl <ltinkl@redhat.com> Security8021x 0 0 563 471 Authentication: auth 0 0 0 MD5 TLS LEAP FAST Tunneled TLS (TTLS) Protected EAP (PEAP) 0 Username: md5UserName Password: md5Password true Identity: tlsIdentity + + + Domain: + + + + + + + User certificate: tlsUserCert - + *.der *.pem *.crt *.cer - + CA certificate: tlsCACert - + *.der *.pem *.crt *.cer - + Subject match: leTlsSubjectMatch - + - + Alternative subject matches: leTlsAlternativeSubjectMatches - + ... - + Connect to these servers: leTlsConnectToServers - + ... - + Private key: tlsPrivateKey - + *.der *.pem *.p12 *.key - + Private key password: tlsPrivateKeyPassword - + true Username: leapUsername Password: leapPassword true Anonymous identity: fastAnonIdentity Automatic PAC provisioning false 0 0 Anonymous Authenticated Both PAC file: pacFile *.pac Inner authentication: fastInnerAuth 0 0 GTC MSCHAPv2 Username: fastUsername Password: fastPassword true Anonymous identity: fastAnonIdentity - + CA certificate: tlsCACert - + *.der *.pem *.crt *.cer - + Inner authentication: fastInnerAuth - + 0 0 PAP MSCHAP MSCHAPv2 CHAP - + Username: fastUsername - + - + Password: fastPassword - + true + + + + Domain: + + + + + + - + Anonymous identity: fastAnonIdentity - + - + CA certificate: tlsCACert - + *.der *.pem *.crt *.cer - + PEAP version: peapVersion - + 0 0 Automatic Version 0 Version 1 - + Inner authentication: fastInnerAuth - + 0 0 MSCHAPv2 MD5 GTC - + Username: fastUsername - + - + Password: fastPassword - + true + + + + Domain: + + + + + + KComboBox QComboBox
kcombobox.h
KUrlRequester QWidget
kurlrequester.h
KLineEdit QLineEdit
klineedit.h
PasswordField QLineEdit
passwordfield.h
auth md5UserName md5Password tlsIdentity + tlsDomain tlsUserCert tlsCACert leTlsSubjectMatch leTlsAlternativeSubjectMatches btnTlsAltSubjectMatches leTlsConnectToServers btnTlsConnectToServers tlsPrivateKey tlsPrivateKeyPassword leapUsername leapPassword fastAnonIdentity fastAllowPacProvisioning pacMethod pacFile fastInnerAuth fastUsername fastPassword ttlsAnonIdentity + ttlsDomain ttlsCACert ttlsInnerAuth ttlsUsername ttlsPassword peapAnonIdentity + peapDomain peapCACert peapVersion peapInnerAuth peapUsername peapPassword auth currentIndexChanged(int) stackedWidget setCurrentIndex(int) 156 16 149 72 stackedWidget currentChanged(int) auth setCurrentIndex(int) 376 114 355 14 fastAllowPacProvisioning toggled(bool) pacMethod setEnabled(bool) 95 73 285 77
diff --git a/libs/editor/settings/ui/ipv6.ui b/libs/editor/settings/ui/ipv6.ui index 6853eed2..e20f43af 100644 --- a/libs/editor/settings/ui/ipv6.ui +++ b/libs/editor/settings/ui/ipv6.ui @@ -1,407 +1,408 @@ IPv6Widget 0 0 418 427 0 0 Qt::LeftToRight When connecting to IPv4-capable networks, allows the connection to complete if IPv6 configuration fails but IPv4 configuration succeeds IPv6 is required for this connection true 0 0 Method: Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter method 0 0 250 0 Use this field to specify the IP address(es) of one or more DNS servers. Use ',' to separate entries. Edit the list of DNS servers .. Remove .. Add .. 0 0 IP addresses identify your computer on the network. Click the "Add" button to add an IP address QAbstractItemView::SingleSelection QAbstractItemView::SelectRows true false Qt::Vertical QSizePolicy::MinimumExpanding 20 40 0 0 DNS Servers: Qt::AutoText Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter dns 0 0 Configure IPv6 Privacy Extensions for SLAAC, described in RFC4941. If enabled, it makes the kernel generate a temporary IPv6 address in addition to the public one generated from MAC address via modified EUI-64. Default Disabled Enabled (prefer public address) Enabled (prefer temporary addresses) 0 0 Automatic Automatic (Only addresses) Automatic (Only DHCP) Link-Local Manual Ignored 250 0 Use this field to specify one or more DNS domains to search. Use ',' to separate entries. Edit the list of DNS domains being searched .. Qt::Horizontal 40 20 0 0 16777215 16777215 Routes... 0 0 Privacy: Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter privacyCombo 0 0 Search Domains: Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter dnsSearch Qt::Vertical 20 40 labelPrivacy ipv6RequiredCB method dnsLabel dnsSearchLabel privacyCombo label verticalSpacer KComboBox QComboBox
kcombobox.h
KLineEdit QLineEdit
klineedit.h
method dns dnsMorePushButton dnsSearch + dnsSearchMorePushButton privacyCombo tableViewAddresses btnAdd btnRemove btnRoutes
diff --git a/libs/editor/settings/ui/wimax.ui b/libs/editor/settings/ui/wimax.ui deleted file mode 100644 index 28e71431..00000000 --- a/libs/editor/settings/ui/wimax.ui +++ /dev/null @@ -1,71 +0,0 @@ - - - Lukáš Tinkl <ltinkl@redhat.com> - WimaxWidget - - - - 0 - 0 - 369 - 70 - - - - - 0 - - - - - Network name: - - - networkName - - - - - - - - - - Restrict to device: - - - macAddress - - - - - - - - 0 - 0 - - - - - - - - - KLineEdit - QLineEdit -
klineedit.h
-
- - HwAddrComboBox - QComboBox -
hwaddrcombobox.h
-
-
- - networkName - macAddress - - - -
diff --git a/libs/editor/settings/ui/wiredconnectionwidget.ui b/libs/editor/settings/ui/wiredconnectionwidget.ui index 36c1e534..810c4eaf 100644 --- a/libs/editor/settings/ui/wiredconnectionwidget.ui +++ b/libs/editor/settings/ui/wiredconnectionwidget.ui @@ -1,306 +1,312 @@ WiredConnectionWidget 0 0 401 217 QFormLayout::ExpandingFieldsGrow 6 Restrict to device: macAddress Cloned MAC address: clonedMacAddress 0 0 This option locks this connection to the network device specified by its permanent MAC address entered here. Example: 00:11:22:33:44:55 0 0 The MAC address entered here will be used as hardware address for the network device this connection is activated on. This feature is known as MAC cloning or spoofing. Example 11:22:33:44:55 HH:HH:HH:HH:HH:HH;_ Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter Random MTU: mtu 0 0 Only transmit packets of the specified size or smaller, breaking larger packets up into multiple Ethernet frames Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter Automatic bytes 10000 Speed: speed 0 0 Request that the device use only the specified speed. In MBit/s, example 100 == 100Mbit/s Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - Automatic + Mbit/s + + 1 + 9999 + + 100 + Duplex: duplex 0 0 Request that the device use the specified duplex mode. Either "half" or "full" Full Half 0 0 Allow auto-negotiation of port speed and duplex mode Allow auto-negotiation true false KComboBox QComboBox
kcombobox.h
KLineEdit QLineEdit
klineedit.h
HwAddrComboBox QComboBox
hwaddrcombobox.h
macAddress clonedMacAddress btnRandomMacAddr mtu speed duplex autonegotiate toggled(bool) speedLabel setHidden(bool) 80 290 81 117 autonegotiate toggled(bool) speed setHidden(bool) 80 290 245 118 autonegotiate toggled(bool) duplexLabel setHidden(bool) 80 290 81 147 autonegotiate toggled(bool) duplex setHidden(bool) 80 290 298 143
diff --git a/libs/editor/settings/wimaxwidget.cpp b/libs/editor/settings/wimaxwidget.cpp deleted file mode 100644 index c76054f6..00000000 --- a/libs/editor/settings/wimaxwidget.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/* - 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 "wimaxwidget.h" -#include "ui_wimax.h" -#include "uiutils.h" - -#include -#include - -#include - -WimaxWidget::WimaxWidget(const NetworkManager::Setting::Ptr &setting, QWidget* parent, Qt::WindowFlags f): - SettingWidget(setting, parent, f), - m_ui(new Ui::WimaxWidget) -{ - m_ui->setupUi(this); - - connect(m_ui->networkName, &KLineEdit::textChanged, this, &WimaxWidget::slotWidgetChanged); - connect(m_ui->macAddress, &HwAddrComboBox::hwAddressChanged, this, &WimaxWidget::slotWidgetChanged); - - // Connect for setting check - watchChangedSetting(); - - KAcceleratorManager::manage(this); - - if (setting) { - loadConfig(setting); - } -} - -WimaxWidget::~WimaxWidget() -{ - delete m_ui; -} - -void WimaxWidget::loadConfig(const NetworkManager::Setting::Ptr &setting) -{ - NetworkManager::WimaxSetting::Ptr wimaxSetting = setting.staticCast(); - - m_ui->networkName->setText(wimaxSetting->networkName()); - m_ui->macAddress->init(NetworkManager::Device::Wimax, NetworkManager::macAddressAsString(wimaxSetting->macAddress())); -} - -QVariantMap WimaxWidget::setting() const -{ - NetworkManager::WimaxSetting wimaxSetting; - - wimaxSetting.setNetworkName(m_ui->networkName->text()); - wimaxSetting.setMacAddress(NetworkManager::macAddressFromString(m_ui->macAddress->hwAddress())); - - return wimaxSetting.toMap(); -} - -bool WimaxWidget::isValid() const -{ - return !m_ui->networkName->text().isEmpty() && m_ui->macAddress->isValid(); -} diff --git a/libs/editor/settings/wimaxwidget.h b/libs/editor/settings/wimaxwidget.h deleted file mode 100644 index 2def0289..00000000 --- a/libs/editor/settings/wimaxwidget.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - 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_WIMAX_WIDGET_H -#define PLASMA_NM_WIMAX_WIDGET_H - -#include - -#include "settingwidget.h" - -namespace Ui -{ -class WimaxWidget; -} - -class Q_DECL_EXPORT WimaxWidget : public SettingWidget -{ - Q_OBJECT -public: - explicit WimaxWidget(const NetworkManager::Setting::Ptr &setting = NetworkManager::Setting::Ptr(), QWidget* parent = 0, Qt::WindowFlags f = 0); - virtual ~WimaxWidget(); - - void loadConfig(const NetworkManager::Setting::Ptr &setting) Q_DECL_OVERRIDE; - - QVariantMap setting() const Q_DECL_OVERRIDE; - - virtual bool isValid() const Q_DECL_OVERRIDE; - -private: - Ui::WimaxWidget * m_ui; -}; - -#endif // PLASMA_NM_WIMAX_WIDGET_H diff --git a/libs/editor/widgets/hwaddrcombobox.cpp b/libs/editor/widgets/hwaddrcombobox.cpp index 11924ec6..e0d78e4a 100644 --- a/libs/editor/widgets/hwaddrcombobox.cpp +++ b/libs/editor/widgets/hwaddrcombobox.cpp @@ -1,168 +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 -#if !NM_CHECK_VERSION(1, 2, 0) -#include -#endif #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); } 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(); -#if !NM_CHECK_VERSION(1, 2, 0) - } else if (type == NetworkManager::Device::Wimax) { - data = device->as()->hardwareAddress(); -#endif } 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/passwordfield.cpp b/libs/editor/widgets/passwordfield.cpp index e5e5aa52..3e3b6741 100644 --- a/libs/editor/widgets/passwordfield.cpp +++ b/libs/editor/widgets/passwordfield.cpp @@ -1,165 +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 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); // 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->setReadOnly(true); + m_passwordField->setDisabled(true); } else { - m_passwordField->setReadOnly(false); + m_passwordField->setEnabled(true); } Q_EMIT passwordOptionChanged(m_currentPasswordOption); } diff --git a/libs/handler.cpp b/libs/handler.cpp index 9f8d3702..2ae3ec6f 100644 --- a/libs/handler.cpp +++ b/libs/handler.cpp @@ -1,541 +1,520 @@ /* 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 #if WITH_MODEMMANAGER_SUPPORT #include #include #endif #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) -#if !NM_CHECK_VERSION(1, 2, 0) - , m_tmpWimaxEnabled(NetworkManager::isWimaxEnabled()) -#endif , 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) { -#if !NM_CHECK_VERSION(1, 2, 0) - m_tmpWimaxEnabled = NetworkManager::isWimaxEnabled(); -#endif m_tmpWirelessEnabled = NetworkManager::isWirelessEnabled(); m_tmpWwanEnabled = NetworkManager::isWwanEnabled(); enableBluetooth(false); -#if !NM_CHECK_VERSION(1, 2, 0) - enableWimax(false); -#endif enableWireless(false); enableWwan(false); } else { enableBluetooth(true); -#if !NM_CHECK_VERSION(1, 2, 0) - if (m_tmpWimaxEnabled) { - enableWimax(true); - } -#endif 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); } -#if !NM_CHECK_VERSION(1, 2, 0) -void Handler::enableWimax(bool enable) -{ - NetworkManager::setWimaxEnabled(enable); -} -#endif - 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; 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; 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 c3a0b863..163ea603 100644 --- a/libs/handler.h +++ b/libs/handler.h @@ -1,131 +1,125 @@ /* 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 #if WITH_MODEMMANAGER_SUPPORT #include #endif #include 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(); 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); -#if !NM_CHECK_VERSION(1, 2, 0) - void enableWimax(bool enable); -#endif 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: -#if !NM_CHECK_VERSION(1, 2, 0) - bool m_tmpWimaxEnabled; -#endif 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 47b6ee06..5a57574b 100644 --- a/libs/models/appletproxymodel.cpp +++ b/libs/models/appletproxymodel.cpp @@ -1,129 +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) : QSortFilterProxyModel(parent) { setDynamicSortFilter(true); sort(0, Qt::DescendingOrder); } AppletProxyModel::~AppletProxyModel() { } 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 || - itemType == NetworkModelItem::AvailableNsp) { + itemType == NetworkModelItem::AvailableAccessPoint) { return true; } return false; } 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/editorproxymodel.cpp b/libs/models/editorproxymodel.cpp index 0144538f..258c3e5a 100644 --- a/libs/models/editorproxymodel.cpp +++ b/libs/models/editorproxymodel.cpp @@ -1,116 +1,116 @@ /* 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 "editorproxymodel.h" #include "uiutils.h" 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 { 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 || itemType == NetworkModelItem::AvailableNsp) { + 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/networkitemslist.cpp b/libs/models/networkitemslist.cpp index 84434545..852ba5ed 100644 --- a/libs/models/networkitemslist.cpp +++ b/libs/models/networkitemslist.cpp @@ -1,191 +1,175 @@ /* 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 "networkitemslist.h" #include "networkmodelitem.h" NetworkItemsList::NetworkItemsList(QObject* parent) : QObject(parent) { } NetworkItemsList::~NetworkItemsList() { qDeleteAll(m_items); } bool NetworkItemsList::contains(const NetworkItemsList::FilterType type, const QString& parameter) const { Q_FOREACH (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::Nsp: - if (item->nsp() == 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 { return m_items.indexOf(item); } void NetworkItemsList::insertItem(NetworkModelItem* item) { m_items << item; } NetworkModelItem* NetworkItemsList::itemAt(int index) const { return m_items.at(index); } QList< NetworkModelItem* > NetworkItemsList::items() const { return m_items; } 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 result; Q_FOREACH (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::Nsp: - if (item->nsp() == parameter) { - if (additionalParameter.isEmpty()) { - result << item; - } else { - if (item->devicePath() == additionalParameter) { - 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 result; Q_FOREACH (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 579c872d..7a506375 100644 --- a/libs/models/networkitemslist.h +++ b/libs/models/networkitemslist.h @@ -1,62 +1,61 @@ /* 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_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, - Nsp, Ssid, Uuid, Type }; explicit NetworkItemsList(QObject* parent = 0); virtual ~NetworkItemsList(); bool contains(const FilterType type, const QString& parameter) const; int count() 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, NetworkManager::ConnectionSettings::ConnectionType typeParameter) const; 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 f0f13a79..82c3af74 100644 --- a/libs/models/networkmodel.cpp +++ b/libs/models/networkmodel.cpp @@ -1,1146 +1,1007 @@ /* 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 "networkmodel.h" #include "networkmodelitem.h" #include "debug.h" #include "uiutils.h" #if WITH_MODEMMANAGER_SUPPORT #include #include #endif #include -#include +#include 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 { const int row = index.row(); if (row >= 0 && row < m_list.count()) { 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 NspRole: - return item->nsp(); 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(); default: break; } } return QVariant(); } int NetworkModel::rowCount(const QModelIndex& parent) const { Q_UNUSED(parent); - return m_list.count(); + return parent.isValid() ? 0 : m_list.count(); } QHash< int, QByteArray > 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[NspRole] = "Nsp"; 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"; return roles; } void NetworkModel::initialize() { // Initialize existing connections Q_FOREACH (const NetworkManager::Connection::Ptr& connection, NetworkManager::listConnections()) { addConnection(connection); } // Initialize existing devices Q_FOREACH (const NetworkManager::Device::Ptr& dev, NetworkManager::networkInterfaces()) { addDevice(dev); } // Initialize existing active connections Q_FOREACH (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) { 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) { connect(connection.data(), &NetworkManager::Connection::updated, this, &NetworkModel::connectionUpdated, Qt::UniqueConnection); } 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); 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 !NM_CHECK_VERSION(1, 2, 0) - else if (device->type() == NetworkManager::Device::Wimax) { - NetworkManager::WimaxDevice::Ptr wimaxDev = device.objectCast(); - connect(wimaxDev.data(), &NetworkManager::WimaxDevice::nspAppeared, this, &NetworkModel::wimaxNspAppeared); - connect(wimaxDev.data(), &NetworkManager::WimaxDevice::nspDisappeared, this, &NetworkModel::wimaxNspDisappeared); - } -#endif #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 } -#if !NM_CHECK_VERSION(1, 2, 0) -void NetworkModel::initializeSignals(const NetworkManager::WimaxNsp::Ptr& nsp) -{ - connect(nsp.data(), &NetworkManager::WimaxNsp::signalQualityChanged, this, &NetworkModel::wimaxNspSignalChanged); -} -#endif - 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) { 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())) { 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(); qCDebug(PLASMA_NM) << "Item " << item->name() << ": active connection state changed to " << item->connectionState(); } } endResetModel(); } void NetworkModel::addAvailableConnection(const QString& connection, const NetworkManager::Device::Ptr& device) { checkAndCreateDuplicate(connection, device); Q_FOREACH (NetworkModelItem * item, m_list.returnItems(NetworkItemsList::Connection, connection)) { // The item is already associated with another device if (!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())) { 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); } } } -#if !NM_CHECK_VERSION(1, 2, 0) - else if (item->type() == NetworkManager::ConnectionSettings::Wimax) { - // Find a nsp which could be removed, because it will be merged with a connection - Q_FOREACH (NetworkModelItem * secondItem, m_list.returnItems(NetworkItemsList::Nsp, item->nsp())) { - if (secondItem->itemType() == NetworkModelItem::AvailableNsp && secondItem->devicePath() == item->devicePath()) { - const int row = m_list.indexOf(secondItem); - qCDebug(PLASMA_NM) << "Nsp " << secondItem->name() << ": merged to " << item->name() << " connection"; - if (row >= 0) { - beginRemoveRows(QModelIndex(), row, row); - m_list.removeItem(secondItem); - secondItem->deleteLater(); - endRemoveRows(); - } - break; - } - } - NetworkManager::WimaxDevice::Ptr wimaxDevice = device.objectCast(); - NetworkManager::WimaxNsp::Ptr nsp = wimaxDevice->findNsp(item->specificPath()); - if (nsp) { - updateFromWimaxNsp(item, nsp); - } - } -#endif updateItem(item); break; } } 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::WimaxSetting::Ptr wimaxSetting; 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(); - } else if (settings->connectionType() == NetworkManager::ConnectionSettings::Wimax) { - wimaxSetting = settings->setting(NetworkManager::Setting::Wimax).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(); 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())); - } else if (item->type() == NetworkManager::ConnectionSettings::Wimax) { - item->setNsp(wimaxSetting->networkName()); } item->updateDetails(); 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) { initializeSignals(device); if (device->type() == NetworkManager::Device::Wifi) { NetworkManager::WirelessDevice::Ptr wifiDev = device.objectCast(); Q_FOREACH (const NetworkManager::WirelessNetwork::Ptr& wifiNetwork, wifiDev->networks()) { addWirelessNetwork(wifiNetwork, wifiDev); } } -#if !NM_CHECK_VERSION(1, 2, 0) - else if (device->type() == NetworkManager::Device::Wimax) { - NetworkManager::WimaxDevice::Ptr wimaxDev = device.objectCast(); - Q_FOREACH (const QString & nsp, wimaxDev->nsps()) { - NetworkManager::WimaxNsp::Ptr wimaxNsp = wimaxDev->findNsp(nsp); - if (wimaxNsp) { - addWimaxNsp(wimaxNsp, wimaxDev); - } - } - } -#endif Q_FOREACH (const NetworkManager::Connection::Ptr & connection, device->availableConnections()) { addAvailableConnection(connection->path(), device); } } -#if !NM_CHECK_VERSION(1, 2, 0) -void NetworkModel::addWimaxNsp(const NetworkManager::WimaxNsp::Ptr& nsp, const NetworkManager::WimaxDevice::Ptr& device) -{ - initializeSignals(nsp); - - NetworkModelItem * item = new NetworkModelItem(); - if (device->ipInterfaceName().isEmpty()) { - item->setDeviceName(device->interfaceName()); - } else { - item->setDeviceName(device->ipInterfaceName()); - } - item->setDevicePath(device->uni()); - item->setName(nsp->name()); - item->setSignal(nsp->signalQuality()); - item->setSpecificPath(nsp->uni()); - item->setType(NetworkManager::ConnectionSettings::Wimax); - item->updateDetails(); - - const int index = m_list.count(); - beginInsertRows(QModelIndex(), index, index); - m_list.insertItem(item); - endInsertRows(); - qCDebug(PLASMA_NM) << "New wireless network " << item->name() << " added"; -} -#endif - 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)) { + 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()); 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(); 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(); 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) { bool createDuplicate = false; NetworkModelItem * originalItem = 0; Q_FOREACH (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())) { createDuplicate = true; } } if (createDuplicate) { NetworkModelItem * duplicatedItem = new NetworkModelItem(originalItem); duplicatedItem->updateDetails(); const int index = m_list.count(); beginInsertRows(QModelIndex(), index, index); m_list.insertItem(duplicatedItem); endInsertRows(); } } void NetworkModel::onItemUpdated() { NetworkModelItem * item = static_cast(sender()); if (item) { updateItem(item); } } void NetworkModel::updateItem(NetworkModelItem * item) { const int row = m_list.indexOf(item); if (row >= 0) { item->updateDetails(); QModelIndex index = createIndex(row, 0); Q_EMIT dataChanged(index, index); } } void NetworkModel::accessPointSignalStrengthChanged(int signal) { NetworkManager::AccessPoint * apPtr = qobject_cast(sender()); if (apPtr) { Q_FOREACH (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) { NetworkManager::ActiveConnection::Ptr activeCon = NetworkManager::findActiveConnection(activeConnection); if (activeCon) { addActiveConnection(activeCon); } } void NetworkModel::activeConnectionRemoved(const QString& activeConnection) { Q_FOREACH (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()); if (activePtr) { beginResetModel(); Q_FOREACH (NetworkModelItem * item, m_list.returnItems(NetworkItemsList::ActiveConnection, activePtr->path())) { item->setConnectionState(state); item->updateDetails(); 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())) { 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) { NetworkManager::Device::Ptr device = NetworkManager::findNetworkInterface(qobject_cast(sender())->uni()); addAvailableConnection(connection, device); } void NetworkModel::availableConnectionDisappeared(const QString& connection) { Q_FOREACH (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()) { 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 !NM_CHECK_VERSION(1, 2, 0) - else if (item->type() == NetworkManager::ConnectionSettings::Wimax && !specificPath.isEmpty()) { // Same for Wimax - if (device && device->type() == NetworkManager::Device::Wimax) { - NetworkManager::WimaxDevice::Ptr wimaxDevice = device.objectCast(); - if (wimaxDevice) { - NetworkManager::WimaxNsp::Ptr nsp = wimaxDevice->findNsp(specificPath); - if (nsp) { - addWimaxNsp(nsp, wimaxDevice); - } - } - } - } -#endif 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) { NetworkManager::Connection::Ptr newConnection = NetworkManager::findConnection(connection); if (newConnection) { addConnection(newConnection); } } void NetworkModel::connectionRemoved(const QString& connection) { bool remove = false; Q_FOREACH (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()) { // 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()); if (connectionPtr) { NetworkManager::ConnectionSettings::Ptr settings = connectionPtr->settings(); Q_FOREACH (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 - } else if (item->type() == NetworkManager::ConnectionSettings::Wimax) { - NetworkManager::WimaxSetting::Ptr wimaxSetting; - wimaxSetting = settings->setting(NetworkManager::Setting::Wimax).dynamicCast(); - item->setNsp(wimaxSetting->networkName()); } updateItem(item); qCDebug(PLASMA_NM) << "Item " << item->name() << ": connection updated"; } } } void NetworkModel::deviceAdded(const QString& device) { NetworkManager::Device::Ptr dev = NetworkManager::findNetworkInterface(device); if (dev) { addDevice(dev); } } void NetworkModel::deviceRemoved(const QString& device) { // Make all items unavailable Q_FOREACH (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())) { item->setDeviceState(state); item->updateDetails(); // 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()); if (gsmNetwork) { Q_FOREACH (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())) { updateItem(item); } } } } } } } } void NetworkModel::gsmNetworkCurrentModesChanged() { ModemManager::Modem * gsmNetwork = qobject_cast(sender()); if (gsmNetwork) { Q_FOREACH (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())) { updateItem(item); } } } } } } } } void NetworkModel::gsmNetworkSignalQualityChanged(const ModemManager::SignalQualityPair &signalQuality) { ModemManager::Modem * gsmNetwork = qobject_cast(sender()); if (gsmNetwork) { Q_FOREACH (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())) { 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())) { updateItem(item); // qCDebug(PLASMA_NM) << "Item " << item->name() << ": device ipconfig changed"; } } } void NetworkModel::ipInterfaceChanged() { NetworkManager::Device * device = qobject_cast(sender()); if (device) { Q_FOREACH (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)) { updateItem(item); } } -#if !NM_CHECK_VERSION(1, 2, 0) -void NetworkModel::wimaxNspAppeared(const QString& nsp) -{ - NetworkManager::Device::Ptr device = NetworkManager::findNetworkInterface(qobject_cast(sender())->uni()); - if (device && device->type() == NetworkManager::Device::Wimax) { - NetworkManager::WimaxDevice::Ptr wimaxDevice = device.objectCast(); - NetworkManager::WimaxNsp::Ptr wimaxNsp = wimaxDevice->findNsp(nsp); - if (wimaxNsp) { - addWimaxNsp(wimaxNsp, wimaxDevice); - } - } -} - -void NetworkModel::wimaxNspDisappeared(const QString& nsp) -{ - NetworkManager::Device::Ptr device = NetworkManager::findNetworkInterface(qobject_cast(sender())->uni()); - if (device) { - Q_FOREACH (NetworkModelItem * item, m_list.returnItems(NetworkItemsList::Nsp, nsp, device->uni())) { - // Remove the entire item, because it's only NSP or it's a duplicated available connection - if (item->itemType() == NetworkModelItem::AvailableNsp || item->duplicate()) { - const int row = m_list.indexOf(item); - if (row >= 0) { - qCDebug(PLASMA_NM) << "Wimax Nsp " << item->name() << " removed completely"; - beginRemoveRows(QModelIndex(), row, row); - m_list.removeItem(item); - item->deleteLater(); - endRemoveRows(); - } - // Remove only NSP and device from the item and leave it as an unavailable connection - } else { - item->setDeviceName(QString()); - item->setDevicePath(QString()); - item->setSpecificPath(QString()); - item->setSignal(0); - updateItem(item); - qCDebug(PLASMA_NM) << "Item " << item->name() << ": wimax Nsp removed"; - } - } - } -} - -void NetworkModel::wimaxNspSignalChanged(uint signal) -{ - NetworkManager::WimaxNsp * nspPtr = qobject_cast(sender()); - if (nspPtr) { - Q_FOREACH (NetworkModelItem * item, m_list.returnItems(NetworkItemsList::Nsp, nspPtr->name())) { - if (item->specificPath() == nspPtr->uni()) { - item->setSignal(signal); - updateItem(item); -// qCDebug(PLASMA_NM) << "Wimax Nsp " << item->name() << ": signal changed to " << item->signal(); - } - } - } -} -#endif - 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) { NetworkManager::Device::Ptr device = NetworkManager::findNetworkInterface(qobject_cast(sender())->uni()); if (device) { Q_FOREACH (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) { NetworkManager::WirelessNetwork * networkPtr = qobject_cast(sender()); if (networkPtr) { Q_FOREACH (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()); if (networkPtr) { Q_FOREACH (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; } -#if !NM_CHECK_VERSION(1, 2, 0) -void NetworkModel::updateFromWimaxNsp(NetworkModelItem* item, const NetworkManager::WimaxNsp::Ptr& nsp) -{ - item->setSignal(nsp->signalQuality()); - item->setSpecificPath(nsp->uni()); -} -#endif - 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()) { 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 85e8cb7d..8b911f58 100644 --- a/libs/models/networkmodel.h +++ b/libs/models/networkmodel.h @@ -1,147 +1,129 @@ /* 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_NETWORK_MODEL_H #define PLASMA_NM_NETWORK_MODEL_H #include #include #include "networkitemslist.h" #include #include #include -#if !NM_CHECK_VERSION(1, 2, 0) -#include -#endif #include #if WITH_MODEMMANAGER_SUPPORT #include #endif class Q_DECL_EXPORT NetworkModel : public QAbstractListModel { Q_OBJECT public: explicit NetworkModel(QObject* parent = 0); virtual ~NetworkModel(); enum ItemRole { ConnectionDetailsRole = Qt::UserRole + 1, ConnectionIconRole, ConnectionPathRole, ConnectionStateRole, DeviceName, DevicePathRole, DeviceStateRole, DuplicateRole, ItemUniqueNameRole, ItemTypeRole, LastUsedRole, LastUsedDateOnlyRole, NameRole, - NspRole, SecurityTypeRole, SecurityTypeStringRole, SectionRole, SignalRole, SlaveRole, SsidRole, SpecificPathRole, TimeStampRole, TypeRole, UniRole, UuidRole, VpnState, VpnType }; 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; public Q_SLOTS: void onItemUpdated(); private Q_SLOTS: void accessPointSignalStrengthChanged(int signal); 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 connectionUpdated(); 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); -#if !NM_CHECK_VERSION(1, 2, 0) - void wimaxNspAppeared(const QString& nsp); - void wimaxNspDisappeared(const QString& nsp); - void wimaxNspSignalChanged(uint signal); -#endif void wirelessNetworkAppeared(const QString& ssid); void wirelessNetworkDisappeared(const QString& ssid); void wirelessNetworkSignalChanged(int signal); 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); -#if !NM_CHECK_VERSION(1, 2, 0) - void addWimaxNsp(const NetworkManager::WimaxNsp::Ptr& nsp, const NetworkManager::WimaxDevice::Ptr& device); -#endif void addWirelessNetwork(const NetworkManager::WirelessNetwork::Ptr& network, const NetworkManager::WirelessDevice::Ptr& device); void checkAndCreateDuplicate(const QString& connection, const NetworkManager::Device::Ptr& device); void initializeSignals(); void initializeSignals(const NetworkManager::ActiveConnection::Ptr& activeConnection); void initializeSignals(const NetworkManager::Connection::Ptr& connection); void initializeSignals(const NetworkManager::Device::Ptr& device); -#if !NM_CHECK_VERSION(1, 2, 0) - void initializeSignals(const NetworkManager::WimaxNsp::Ptr& nsp); -#endif void initializeSignals(const NetworkManager::WirelessNetwork::Ptr& network); void updateItem(NetworkModelItem * item); -#if !NM_CHECK_VERSION(1, 2, 0) - void updateFromWimaxNsp(NetworkModelItem * item, const NetworkManager::WimaxNsp::Ptr& nsp); -#endif 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 c834d465..c3e91244 100644 --- a/libs/models/networkmodelitem.cpp +++ b/libs/models/networkmodelitem.cpp @@ -1,610 +1,560 @@ /* 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 "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 -#if !NM_CHECK_VERSION(1, 2, 0) -#include -#endif #include #include #include #include #if WITH_MODEMMANAGER_SUPPORT #include #include #include #include #include #endif NetworkModelItem::NetworkModelItem(QObject* parent) : QObject(parent) , m_connectionState(NetworkManager::ActiveConnection::Deactivated) , m_deviceState(NetworkManager::Device::UnknownState) , 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) { } NetworkModelItem::NetworkModelItem(const NetworkModelItem* item, QObject* parent) : QObject(parent) , m_connectionPath(item->connectionPath()) , m_connectionState(NetworkManager::ActiveConnection::Deactivated) , 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) { } NetworkModelItem::~NetworkModelItem() { } QString NetworkModelItem::activeConnectionPath() const { return m_activeConnectionPath; } void NetworkModelItem::setActiveConnectionPath(const QString& path) { m_activeConnectionPath = path; } QString NetworkModelItem::connectionPath() const { return m_connectionPath; } 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 { return m_details; } QString NetworkModelItem::devicePath() const { return m_devicePath; } QString NetworkModelItem::deviceName() const { return m_deviceName; } void NetworkModelItem::setDeviceName(const QString& name) { m_deviceName = name; } 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::Wimax: - if (m_signal == 0 ) { - return QStringLiteral("network-wireless-0"); - } else if (m_signal < 20) { - return QStringLiteral("network-wireless-20"); - } else if (m_signal < 40) { - return QStringLiteral("network-wireless-40"); - } else if (m_signal < 60) { - return QStringLiteral("network-wireless-60"); - } else if (m_signal < 80) { - return QStringLiteral("network-wireless-80"); - } else { - return QStringLiteral("network-wireless-100"); - } - 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 && m_type == NetworkManager::ConnectionSettings::Vpn)) { if (m_connectionPath.isEmpty() && m_type == NetworkManager::ConnectionSettings::Wireless) { return NetworkModelItem::AvailableAccessPoint; - } else if (m_connectionPath.isEmpty() && m_type == NetworkManager::ConnectionSettings::Wimax) { - return NetworkModelItem::AvailableNsp; } 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) { m_name = name; } -QString NetworkModelItem::nsp() const -{ - return m_nsp; -} - -void NetworkModelItem::setNsp(const QString& nsp) -{ - m_nsp = nsp; -} - 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) { m_specificPath = path; } QString NetworkModelItem::ssid() const { return m_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) { 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 if (m_type == NetworkManager::ConnectionSettings::Wimax && m_uuid.isEmpty()) { - return m_nsp + '%' + m_devicePath; } else { return m_connectionPath + '%' + m_devicePath; } } QString NetworkModelItem::uuid() const { return m_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 { 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; } - } else if (item->type() == NetworkManager::ConnectionSettings::Wimax && type() == NetworkManager::ConnectionSettings::Wimax) { - if (item->nsp() == nsp() && item->devicePath() == devicePath()) { - return true; - } } return false; } void NetworkModelItem::updateDetails() { 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(); } -#if !NM_CHECK_VERSION(1, 2, 0) - } else if (m_type == NetworkManager::ConnectionSettings::Wimax) { - NetworkManager::WimaxDevice::Ptr wimaxDevice = device.objectCast(); - if (wimaxDevice) { - NetworkManager::WimaxNsp::Ptr wimaxNsp = wimaxDevice->findNsp(m_specificPath); - m_details << i18n("NSP Name") << m_nsp; - m_details << i18n("Signal Strength") << QString("%1%").arg(m_signal); - if (wimaxNsp) { - m_details << i18n("Network Type"); - } - m_details << i18n("Bsid") << wimaxDevice->bsid(); - m_details << i18n("MAC Address") << wimaxDevice->hardwareAddress(); - } -#endif } 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 e2d706d2..44714085 100644 --- a/libs/models/networkmodelitem.h +++ b/libs/models/networkmodelitem.h @@ -1,143 +1,139 @@ /* 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_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, AvailableNsp }; + enum ItemType { UnavailableConnection, AvailableConnection, AvailableAccessPoint }; explicit NetworkModelItem(QObject * parent = 0); explicit NetworkModelItem(const NetworkModelItem * item, QObject* parent = 0); virtual ~NetworkModelItem(); QString activeConnectionPath() const; void setActiveConnectionPath(const QString& path); QString connectionPath() const; 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); QString devicePath() const; 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); - QString nsp() const; - void setNsp(const QString& nsp); - 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); QString ssid() const; void setSsid(const QString& ssid); QDateTime timestamp() const; 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); QString vpnState() const; void setVpnState(NetworkManager::VpnConnection::State state); QString vpnType() const; void setVpnType(const QString &type); bool operator==(const NetworkModelItem * item) const; public Q_SLOTS: void updateDetails(); private: 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; bool m_duplicate; NetworkManager::WirelessSetting::NetworkMode m_mode; QString m_name; - QString m_nsp; 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; }; #endif // PLASMA_NM_MODEL_NETWORK_MODEL_ITEM_H diff --git a/libs/uiutils.cpp b/libs/uiutils.cpp index d8de9dfe..6abeb99d 100644 --- a/libs/uiutils.cpp +++ b/libs/uiutils.cpp @@ -1,703 +1,679 @@ /* Copyright 2008-2010 Sebastian Kügler 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 . */ // Own #include "uiutils.h" #include "configuration.h" #include "debug.h" // KDE #include #include #include #include #include #include #include #include #include #include #if WITH_MODEMMANAGER_SUPPORT #include #include #include #include #include #endif // Qt #include #include #include using namespace NetworkManager; UiUtils::SortedConnectionType UiUtils::connectionTypeToSortedType(NetworkManager::ConnectionSettings::ConnectionType type) { switch (type) { case NetworkManager::ConnectionSettings::Unknown: return UiUtils::Unknown; break; case NetworkManager::ConnectionSettings::Adsl: return UiUtils::Adsl; break; case NetworkManager::ConnectionSettings::Bluetooth: return UiUtils::Bluetooth; break; case NetworkManager::ConnectionSettings::Bond: return UiUtils::Bond; break; case NetworkManager::ConnectionSettings::Bridge: return UiUtils::Bridge; break; case NetworkManager::ConnectionSettings::Cdma: return UiUtils::Cdma; break; case NetworkManager::ConnectionSettings::Gsm: return UiUtils::Gsm; break; case NetworkManager::ConnectionSettings::Infiniband: return UiUtils::Infiniband; break; case NetworkManager::ConnectionSettings::OLPCMesh: return UiUtils::OLPCMesh; break; case NetworkManager::ConnectionSettings::Pppoe: return UiUtils::Pppoe; break; case NetworkManager::ConnectionSettings::Team: return UiUtils::Team; break; case NetworkManager::ConnectionSettings::Vlan: return UiUtils::Vlan; break; case NetworkManager::ConnectionSettings::Vpn: return UiUtils::Vpn; break; - case NetworkManager::ConnectionSettings::Wimax: - return UiUtils::Wimax; - break; case NetworkManager::ConnectionSettings::Wired: return UiUtils::Wired; break; case NetworkManager::ConnectionSettings::Wireless: return UiUtils::Wireless; break; default: return UiUtils::Unknown; break; } } bool UiUtils::isConnectionTypeSupported(NetworkManager::ConnectionSettings::ConnectionType type) { #if NM_CHECK_VERSION(1, 2, 0) if (type == NetworkManager::ConnectionSettings::Generic || type == NetworkManager::ConnectionSettings::Tun) { #else if (type == NetworkManager::ConnectionSettings::Generic) { #endif return false; } bool manageVirtualConnections = Configuration::manageVirtualConnections(); if (type == NetworkManager::ConnectionSettings::Bond || type == NetworkManager::ConnectionSettings::Bridge || type == NetworkManager::ConnectionSettings::Infiniband || type == NetworkManager::ConnectionSettings::Team || type == NetworkManager::ConnectionSettings::Vlan) { return manageVirtualConnections; } return true; } QString UiUtils::interfaceTypeLabel(const NetworkManager::Device::Type type, const NetworkManager::Device::Ptr iface) { QString deviceText; switch (type) { case NetworkManager::Device::Wifi: deviceText = i18nc("title of the interface widget in nm's popup", "Wi-Fi"); break; case NetworkManager::Device::Bluetooth: deviceText = i18nc("title of the interface widget in nm's popup", "Bluetooth"); break; - case NetworkManager::Device::Wimax: - deviceText = i18nc("title of the interface widget in nm's popup", "WiMAX"); - break; case NetworkManager::Device::InfiniBand: deviceText = i18nc("title of the interface widget in nm's popup", "Infiniband"); break; case NetworkManager::Device::Adsl: deviceText = i18nc("title of the interface widget in nm's popup", "ADSL"); break; case NetworkManager::Device::Bond: deviceText = i18nc("title of the interface widget in nm's popup", "Virtual (bond)"); break; case NetworkManager::Device::Bridge: deviceText = i18nc("title of the interface widget in nm's popup", "Virtual (bridge)"); break; case NetworkManager::Device::Vlan: deviceText = i18nc("title of the interface widget in nm's popup", "Virtual (vlan)"); break; #if NM_CHECK_VERSION(0, 9, 10) case NetworkManager::Device::Team: deviceText = i18nc("title of the interface widget in nm's popup", "Virtual (team)"); break; #endif case NetworkManager::Device::Modem: { const NetworkManager::ModemDevice::Ptr nmModemIface = iface.objectCast(); if (nmModemIface) { switch(modemSubType(nmModemIface->currentCapabilities())) { case NetworkManager::ModemDevice::Pots: deviceText = i18nc("title of the interface widget in nm's popup", "Serial Modem"); break; case NetworkManager::ModemDevice::GsmUmts: case NetworkManager::ModemDevice::CdmaEvdo: case NetworkManager::ModemDevice::Lte: deviceText = i18nc("title of the interface widget in nm's popup", "Mobile Broadband"); break; case NetworkManager::ModemDevice::NoCapability: qCWarning(PLASMA_NM) << "Unhandled modem sub type: NetworkManager::ModemDevice::NoCapability"; break; } } } break; case NetworkManager::Device::Ethernet: default: deviceText = i18nc("title of the interface widget in nm's popup", "Wired Ethernet"); break; } return deviceText; } QString UiUtils::iconAndTitleForConnectionSettingsType(NetworkManager::ConnectionSettings::ConnectionType type, QString &title) { QString text; QString icon = QStringLiteral("network-wired"); switch (type) { case ConnectionSettings::Adsl: text = i18n("ADSL"); icon = QStringLiteral("network-modem"); break; case ConnectionSettings::Pppoe: text = i18n("DSL"); icon = QStringLiteral("network-modem"); break; case ConnectionSettings::Bluetooth: text = i18n("Bluetooth"); icon = QStringLiteral("network-bluetooth"); break; case ConnectionSettings::Bond: text = i18n("Bond"); break; case ConnectionSettings::Bridge: text = i18n("Bridge"); break; case ConnectionSettings::Gsm: case ConnectionSettings::Cdma: text = i18n("Mobile broadband"); icon = QStringLiteral("smartphone"); break; case ConnectionSettings::Infiniband: text = i18n("Infiniband"); break; case ConnectionSettings::OLPCMesh: text = i18n("Olpc mesh"); break; case ConnectionSettings::Vlan: text = i18n("VLAN"); break; case ConnectionSettings::Vpn: text = i18n("VPN"); icon = QStringLiteral("network-vpn"); break; - case ConnectionSettings::Wimax: - text = i18n("WiMAX"); - icon = QStringLiteral("network-wireless"); - break; case ConnectionSettings::Wired: text = i18n("Wired Ethernet"); icon = QStringLiteral("network-wired"); break; case ConnectionSettings::Wireless: text = i18n("Wi-Fi"); icon = QStringLiteral("network-wireless"); break; #if NM_CHECK_VERSION(0, 9, 10) case ConnectionSettings::Team: text = i18n("Team"); break; #endif default: text = i18n("Unknown connection type"); break; } title = text; return icon; } QString UiUtils::prettyInterfaceName(NetworkManager::Device::Type type, const QString &interfaceName) { QString ret; switch (type) { case NetworkManager::Device::Wifi: ret = i18n("Wireless Interface (%1)", interfaceName); break; case NetworkManager::Device::Ethernet: ret = i18n("Wired Interface (%1)", interfaceName); break; case NetworkManager::Device::Bluetooth: ret = i18n("Bluetooth (%1)", interfaceName); break; case NetworkManager::Device::Modem: ret = i18n("Modem (%1)", interfaceName); break; case NetworkManager::Device::Adsl: ret = i18n("ADSL (%1)", interfaceName); break; case NetworkManager::Device::Vlan: ret = i18n("VLan (%1)", interfaceName); break; case NetworkManager::Device::Bridge: ret = i18n("Bridge (%1)", interfaceName); break; default: ret = interfaceName; } return ret; } QString UiUtils::connectionStateToString(NetworkManager::Device::State state, const QString &connectionName) { QString stateString; switch (state) { case NetworkManager::Device::UnknownState: stateString = i18nc("description of unknown network interface state", "Unknown"); break; case NetworkManager::Device::Unmanaged: stateString = i18nc("description of unmanaged network interface state", "Unmanaged"); break; case NetworkManager::Device::Unavailable: stateString = i18nc("description of unavailable network interface state", "Unavailable"); break; case NetworkManager::Device::Disconnected: stateString = i18nc("description of unconnected network interface state", "Not connected"); break; case NetworkManager::Device::Preparing: stateString = i18nc("description of preparing to connect network interface state", "Preparing to connect"); break; case NetworkManager::Device::ConfiguringHardware: stateString = i18nc("description of configuring hardware network interface state", "Configuring interface"); break; case NetworkManager::Device::NeedAuth: stateString = i18nc("description of waiting for authentication network interface state", "Waiting for authorization"); break; case NetworkManager::Device::ConfiguringIp: stateString = i18nc("network interface doing dhcp request in most cases", "Setting network address"); break; case NetworkManager::Device::CheckingIp: stateString = i18nc("is other action required to fully connect? captive portals, etc.", "Checking further connectivity"); break; case NetworkManager::Device::WaitingForSecondaries: stateString = i18nc("a secondary connection (e.g. VPN) has to be activated first to continue", "Waiting for a secondary connection"); break; case NetworkManager::Device::Activated: if (connectionName.isEmpty()) { stateString = i18nc("network interface connected state label", "Connected"); } else { stateString = i18nc("network interface connected state label", "Connected to %1", connectionName); } break; case NetworkManager::Device::Deactivating: stateString = i18nc("network interface disconnecting state label", "Deactivating connection"); break; case NetworkManager::Device::Failed: stateString = i18nc("network interface connection failed state label", "Connection Failed"); break; default: stateString = i18nc("interface state", "Error: Invalid state"); } return stateString; } QString UiUtils::vpnConnectionStateToString(VpnConnection::State state) { QString stateString; switch (state) { case VpnConnection::Unknown: stateString = i18nc("The state of the VPN connection is unknown", "Unknown"); break; case VpnConnection::Prepare: stateString = i18nc("The VPN connection is preparing to connect", "Preparing to connect"); break; case VpnConnection::NeedAuth: stateString = i18nc("The VPN connection needs authorization credentials", "Needs authorization"); break; case VpnConnection::Connecting: stateString = i18nc("The VPN connection is being established", "Connecting"); break; case VpnConnection::GettingIpConfig: stateString = i18nc("The VPN connection is getting an IP address", "Setting network address"); break; case VpnConnection::Activated: stateString = i18nc("The VPN connection is active", "Activated"); break; case VpnConnection::Failed: stateString = i18nc("The VPN connection failed", "Failed"); break; case VpnConnection::Disconnected: stateString = i18nc("The VPN connection is disconnected", "Failed"); break; default: stateString = i18nc("interface state", "Error: Invalid state"); } return stateString; } QString UiUtils::operationModeToString(NetworkManager::WirelessDevice::OperationMode mode) { QString modeString; switch (mode) { case NetworkManager::WirelessDevice::WirelessDevice::Unknown: modeString = i18nc("wireless network operation mode", "Unknown"); break; case NetworkManager::WirelessDevice::Adhoc: modeString = i18nc("wireless network operation mode", "Adhoc"); break; case NetworkManager::WirelessDevice::WirelessDevice::Infra: modeString = i18nc("wireless network operation mode", "Infrastructure"); break; case NetworkManager::WirelessDevice::WirelessDevice::ApMode: modeString = i18nc("wireless network operation mode", "Access point"); break; default: modeString = I18N_NOOP("INCORRECT MODE FIX ME"); } return modeString; } QStringList UiUtils::wpaFlagsToStringList(NetworkManager::AccessPoint::WpaFlags flags) { /* for testing purposes flags = NetworkManager::AccessPoint::PairWep40 | NetworkManager::AccessPoint::PairWep104 | NetworkManager::AccessPoint::PairTkip | NetworkManager::AccessPoint::PairCcmp | NetworkManager::AccessPoint::GroupWep40 | NetworkManager::AccessPoint::GroupWep104 | NetworkManager::AccessPoint::GroupTkip | NetworkManager::AccessPoint::GroupCcmp | NetworkManager::AccessPoint::KeyMgmtPsk | NetworkManager::AccessPoint::KeyMgmt8021x; */ QStringList flagList; if (flags.testFlag(NetworkManager::AccessPoint::PairWep40)) flagList.append(i18nc("wireless network cipher", "Pairwise WEP40")); if (flags.testFlag(NetworkManager::AccessPoint::PairWep104)) flagList.append(i18nc("wireless network cipher", "Pairwise WEP104")); if (flags.testFlag(NetworkManager::AccessPoint::PairTkip)) flagList.append(i18nc("wireless network cipher", "Pairwise TKIP")); if (flags.testFlag(NetworkManager::AccessPoint::PairCcmp)) flagList.append(i18nc("wireless network cipher", "Pairwise CCMP")); if (flags.testFlag(NetworkManager::AccessPoint::GroupWep40)) flagList.append(i18nc("wireless network cipher", "Group WEP40")); if (flags.testFlag(NetworkManager::AccessPoint::GroupWep104)) flagList.append(i18nc("wireless network cipher", "Group WEP104")); if (flags.testFlag(NetworkManager::AccessPoint::GroupTkip)) flagList.append(i18nc("wireless network cipher", "Group TKIP")); if (flags.testFlag(NetworkManager::AccessPoint::GroupCcmp)) flagList.append(i18nc("wireless network cipher", "Group CCMP")); if (flags.testFlag(NetworkManager::AccessPoint::KeyMgmtPsk)) flagList.append(i18nc("wireless network cipher", "PSK")); if (flags.testFlag(NetworkManager::AccessPoint::KeyMgmt8021x)) flagList.append(i18nc("wireless network cipher", "802.1x")); return flagList; } QString UiUtils::connectionSpeed(double bitrate) { QString out; if (bitrate < 1000) { out = i18nc("connection speed", "%1 Bit/s", bitrate); } else if (bitrate < 1000000) { out = i18nc("connection speed", "%1 MBit/s", bitrate/1000); } else { out = i18nc("connection speed", "%1 GBit/s", bitrate/1000000); } return out; } QString UiUtils::wirelessBandToString(NetworkManager::WirelessSetting::FrequencyBand band) { switch (band) { case NetworkManager::WirelessSetting::Automatic: return QStringLiteral("automatic"); break; case NetworkManager::WirelessSetting::A: return QStringLiteral("a"); break; case NetworkManager::WirelessSetting::Bg: return QStringLiteral("b/g"); break; } return QString(); } #if WITH_MODEMMANAGER_SUPPORT QString UiUtils::convertAllowedModeToString(ModemManager::Modem::ModemModes modes) { if (modes.testFlag(MM_MODEM_MODE_4G)) { return i18nc("Gsm modes (2G/3G/any)","LTE"); } else if (modes.testFlag(MM_MODEM_MODE_3G)) { return i18nc("Gsm modes (2G/3G/any)","UMTS/HSxPA"); } else if (modes.testFlag(MM_MODEM_MODE_2G)) { return i18nc("Gsm modes (2G/3G/any)","GPRS/EDGE"); } else if (modes.testFlag(MM_MODEM_MODE_CS)) { return i18nc("Gsm modes (2G/3G/any)","GSM"); } else if (modes.testFlag(MM_MODEM_MODE_ANY)) { return i18nc("Gsm modes (2G/3G/any)","Any"); } return i18nc("Gsm modes (2G/3G/any)","Any"); } QString UiUtils::convertAccessTechnologyToString(ModemManager::Modem::AccessTechnologies tech) { if (tech.testFlag(MM_MODEM_ACCESS_TECHNOLOGY_LTE)) { return i18nc("Cellular access technology","LTE"); } else if (tech.testFlag(MM_MODEM_ACCESS_TECHNOLOGY_EVDOB)) { return i18nc("Cellular access technology","CDMA2000 EVDO revision B"); } else if (tech.testFlag(MM_MODEM_ACCESS_TECHNOLOGY_EVDOA)) { return i18nc("Cellular access technology","CDMA2000 EVDO revision A"); } else if (tech.testFlag(MM_MODEM_ACCESS_TECHNOLOGY_EVDO0)) { return i18nc("Cellular access technology","CDMA2000 EVDO revision 0"); } else if (tech.testFlag(MM_MODEM_ACCESS_TECHNOLOGY_1XRTT)) { return i18nc("Cellular access technology","CDMA2000 1xRTT"); } else if (tech.testFlag(MM_MODEM_ACCESS_TECHNOLOGY_HSPA_PLUS)) { return i18nc("Cellular access technology","HSPA+"); } else if (tech.testFlag(MM_MODEM_ACCESS_TECHNOLOGY_HSPA)) { return i18nc("Cellular access technology","HSPA"); } else if (tech.testFlag(MM_MODEM_ACCESS_TECHNOLOGY_HSUPA)) { return i18nc("Cellular access technology","HSUPA"); } else if (tech.testFlag(MM_MODEM_ACCESS_TECHNOLOGY_HSDPA)) { return i18nc("Cellular access technology","HSDPA"); } else if (tech.testFlag(MM_MODEM_ACCESS_TECHNOLOGY_UMTS)) { return i18nc("Cellular access technology","UMTS"); } else if (tech.testFlag(MM_MODEM_ACCESS_TECHNOLOGY_EDGE)) { return i18nc("Cellular access technology","EDGE"); } else if (tech.testFlag(MM_MODEM_ACCESS_TECHNOLOGY_GPRS)) { return i18nc("Cellular access technology","GPRS"); } else if (tech.testFlag(MM_MODEM_ACCESS_TECHNOLOGY_GSM_COMPACT)) { return i18nc("Cellular access technology","Compact GSM"); } else if (tech.testFlag(MM_MODEM_ACCESS_TECHNOLOGY_GSM)) { return i18nc("Cellular access technology","GSM"); } else if (tech.testFlag(MM_MODEM_ACCESS_TECHNOLOGY_POTS)) { return i18nc("Analog wireline modem","Analog"); } else if (tech.testFlag(MM_MODEM_ACCESS_TECHNOLOGY_UNKNOWN)) { return i18nc("Unknown cellular access technology","Unknown"); } else if (tech.testFlag(MM_MODEM_ACCESS_TECHNOLOGY_ANY)) { return i18nc("Any cellular access technology","Any"); } return i18nc("Unknown cellular access technology","Unknown"); } QString UiUtils::convertLockReasonToString(MMModemLock reason) { switch (reason) { case MM_MODEM_LOCK_NONE: return i18nc("possible SIM lock reason", "Modem is unlocked."); case MM_MODEM_LOCK_SIM_PIN: return i18nc("possible SIM lock reason", "SIM requires the PIN code."); case MM_MODEM_LOCK_SIM_PIN2: return i18nc("possible SIM lock reason", "SIM requires the PIN2 code."); case MM_MODEM_LOCK_SIM_PUK: return i18nc("possible SIM lock reason", "SIM requires the PUK code."); case MM_MODEM_LOCK_SIM_PUK2: return i18nc("possible SIM lock reason", "SIM requires the PUK2 code."); case MM_MODEM_LOCK_PH_SP_PIN: return i18nc("possible SIM lock reason", "Modem requires the service provider PIN code."); case MM_MODEM_LOCK_PH_SP_PUK: return i18nc("possible SIM lock reason", "Modem requires the service provider PUK code."); case MM_MODEM_LOCK_PH_NET_PIN: return i18nc("possible SIM lock reason", "Modem requires the network PIN code."); case MM_MODEM_LOCK_PH_NET_PUK: return i18nc("possible SIM lock reason", "Modem requires the network PUK code."); case MM_MODEM_LOCK_PH_SIM_PIN: return i18nc("possible SIM lock reason", "Modem requires the PIN code."); case MM_MODEM_LOCK_PH_CORP_PIN: return i18nc("possible SIM lock reason", "Modem requires the corporate PIN code."); case MM_MODEM_LOCK_PH_CORP_PUK: return i18nc("possible SIM lock reason", "Modem requires the corporate PUK code."); case MM_MODEM_LOCK_PH_FSIM_PIN: return i18nc("possible SIM lock reason", "Modem requires the PH-FSIM PIN code."); case MM_MODEM_LOCK_PH_FSIM_PUK: return i18nc("possible SIM lock reason", "Modem requires the PH-FSIM PUK code."); case MM_MODEM_LOCK_PH_NETSUB_PIN: return i18nc("possible SIM lock reason", "Modem requires the network subset PIN code."); case MM_MODEM_LOCK_PH_NETSUB_PUK: return i18nc("possible SIM lock reason", "Modem requires the network subset PUK code."); case MM_MODEM_LOCK_UNKNOWN: default: return i18nc("possible SIM lock reason", "Lock reason unknown."); } } #endif -#if !NM_CHECK_VERSION(1, 2, 0) -QString UiUtils::convertNspTypeToString(WimaxNsp::NetworkType type) -{ - switch (type) { - case WimaxNsp::Unknown: return i18nc("unknown Wimax NSP type", "Unknown"); - case WimaxNsp::Home: return i18n("Home"); - case WimaxNsp::Partner: return i18n("Partner"); - case WimaxNsp::RoamingPartner: return i18n("Roaming partner"); - } - - return i18nc("Unknown", "Unknown Wimax NSP type"); -} -#endif - NetworkManager::ModemDevice::Capability UiUtils::modemSubType(NetworkManager::ModemDevice::Capabilities modemCaps) { if (modemCaps & NetworkManager::ModemDevice::Lte) { return NetworkManager::ModemDevice::Lte; } else if (modemCaps & NetworkManager::ModemDevice::CdmaEvdo) { return NetworkManager::ModemDevice::CdmaEvdo; } else if (modemCaps & NetworkManager::ModemDevice::GsmUmts) { return NetworkManager::ModemDevice::GsmUmts; } else if (modemCaps & NetworkManager::ModemDevice::Pots) { return NetworkManager::ModemDevice::Pots; } return NetworkManager::ModemDevice::NoCapability; } QString UiUtils::labelFromWirelessSecurity(NetworkManager::WirelessSecurityType type) { QString tip; switch (type) { case NetworkManager::NoneSecurity: tip = i18nc("@label no security", "Insecure"); break; case NetworkManager::StaticWep: tip = i18nc("@label WEP security", "WEP"); break; case NetworkManager::Leap: tip = i18nc("@label LEAP security", "LEAP"); break; case NetworkManager::DynamicWep: tip = i18nc("@label Dynamic WEP security", "Dynamic WEP"); break; case NetworkManager::WpaPsk: tip = i18nc("@label WPA-PSK security", "WPA-PSK"); break; case NetworkManager::WpaEap: tip = i18nc("@label WPA-EAP security", "WPA-EAP"); break; case NetworkManager::Wpa2Psk: tip = i18nc("@label WPA2-PSK security", "WPA2-PSK"); break; case NetworkManager::Wpa2Eap: tip = i18nc("@label WPA2-EAP security", "WPA2-EAP"); break; default: tip = i18nc("@label unknown security", "Unknown security type"); break; } return tip; } QString UiUtils::formatDateRelative(const QDateTime & lastUsed) { QString lastUsedText; if (lastUsed.isValid()) { const QDateTime now = QDateTime::currentDateTime(); if (lastUsed.daysTo(now) == 0 ) { const int secondsAgo = lastUsed.secsTo(now); if (secondsAgo < (60 * 60 )) { const int minutesAgo = secondsAgo / 60; lastUsedText = i18ncp( "Label for last used time for a network connection used in the last hour, as the number of minutes since usage", "One minute ago", "%1 minutes ago", minutesAgo); } else { const int hoursAgo = secondsAgo / (60 * 60); lastUsedText = i18ncp( "Label for last used time for a network connection used in the last day, as the number of hours since usage", "One hour ago", "%1 hours ago", hoursAgo); } } else if (lastUsed.daysTo(now) == 1) { lastUsedText = i18nc("Label for last used time for a network connection used the previous day", "Yesterday"); } else { lastUsedText = QLocale().toString(lastUsed.date(), QLocale::ShortFormat); } } else { lastUsedText = i18nc("Label for last used time for a " "network connection that has never been used", "Never"); } return lastUsedText; } QString UiUtils::formatLastUsedDateRelative(const QDateTime & lastUsed) { QString lastUsedText; if (lastUsed.isValid()) { const QDateTime now = QDateTime::currentDateTime(); if (lastUsed.daysTo(now) == 0 ) { const int secondsAgo = lastUsed.secsTo(now); if (secondsAgo < (60 * 60 )) { const int minutesAgo = secondsAgo / 60; lastUsedText = i18ncp( "Label for last used time for a network connection used in the last hour, as the number of minutes since usage", "Last used one minute ago", "Last used %1 minutes ago", minutesAgo); } else { const int hoursAgo = secondsAgo / (60 * 60); lastUsedText = i18ncp( "Label for last used time for a network connection used in the last day, as the number of hours since usage", "Last used one hour ago", "Last used %1 hours ago", hoursAgo); } } else if (lastUsed.daysTo(now) == 1) { lastUsedText = i18nc("Label for last used time for a network connection used the previous day", "Last used yesterday"); } else { lastUsedText = i18n("Last used on %1", QLocale().toString(lastUsed.date(), QLocale::ShortFormat)); } } else { lastUsedText = i18nc("Label for last used time for a " "network connection that has never been used", "Never used"); } return lastUsedText; } diff --git a/libs/uiutils.h b/libs/uiutils.h index af0f4750..badb702d 100644 --- a/libs/uiutils.h +++ b/libs/uiutils.h @@ -1,141 +1,135 @@ /* Copyright 2008-2010 Sebastian Kügler 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 PLASMA_NM_UIUTILS_H #define PLASMA_NM_UIUTILS_H #include #include #include #include #include -#include #include #include -#include #include #include #include #if WITH_MODEMMANAGER_SUPPORT #include #include #endif #include class Q_DECL_EXPORT UiUtils { public: enum SortedConnectionType { Wired, Wireless, - Wimax, Gsm, Cdma, Pppoe, Adsl, Infiniband, OLPCMesh, Bluetooth, Vpn, Vlan, Bridge, Bond, Team, Unknown }; /* * @return sorted connection type used to prioritize specific connection types */ static SortedConnectionType connectionTypeToSortedType(NetworkManager::ConnectionSettings::ConnectionType type); /* * @return whether given connection type is supported * Currently ignored connection types: Bond, Bridge, Generic, Infiniband, Team, Vlan, Tun */ static bool isConnectionTypeSupported(NetworkManager::ConnectionSettings::ConnectionType type); /** * @return a human-readable description for the network interface type for use as label * @param type the type of the network interface */ static QString interfaceTypeLabel(const NetworkManager::Device::Type type, const NetworkManager::Device::Ptr iface); /** * @return a human-readable name for a given network interface according to the configured * naming style * @param type type of the network interface * @param interfaceName name of the network interface (eg eth0) */ static QString prettyInterfaceName(NetworkManager::Device::Type type, const QString &interfaceName); /** * @return a human-readable description of the connection state of a given network interface * @param state The connection state */ static QString connectionStateToString(NetworkManager::Device::State state, const QString &connectionName = QString()); static QString vpnConnectionStateToString(NetworkManager::VpnConnection::State state); static QString iconAndTitleForConnectionSettingsType(NetworkManager::ConnectionSettings::ConnectionType type, QString &title); /** * @return a human-readable description of operation mode. * @param mode the operation mode */ static QString operationModeToString(NetworkManager::WirelessDevice::OperationMode mode); /** * @return string list with a human-readable description of wpa flags. * @param flags the wpa flags */ static QStringList wpaFlagsToStringList(NetworkManager::AccessPoint::WpaFlags flags); /** * @return localized string showing a human-readable connection speed. 1000 is used as base. * @param bitrate bitrate of the connection per second */ static QString connectionSpeed(double bitrate); /** * @param band The band of a wireless network. The value corresponds to the type enum in Knm::WirelessSetting::EnumBand * @return A string representation */ static QString wirelessBandToString(NetworkManager::WirelessSetting::FrequencyBand band); #if WITH_MODEMMANAGER_SUPPORT static QString convertAllowedModeToString(ModemManager::Modem::ModemModes mode); static QString convertAccessTechnologyToString(ModemManager::Modem::AccessTechnologies tech); static QString convertLockReasonToString(MMModemLock reason); #endif static NetworkManager::ModemDevice::Capability modemSubType(NetworkManager::ModemDevice::Capabilities modemCaps); -#if !NM_CHECK_VERSION(1, 2, 0) - static QString convertNspTypeToString(NetworkManager::WimaxNsp::NetworkType type); -#endif static QString labelFromWirelessSecurity(NetworkManager::WirelessSecurityType type); static QString formatDateRelative(const QDateTime & lastUsed); static QString formatLastUsedDateRelative(const QDateTime & lastUsed); }; #endif // UIUTILS_H diff --git a/vpn/fortisslvpn/plasmanetworkmanagement_fortisslvpnui.desktop b/vpn/fortisslvpn/plasmanetworkmanagement_fortisslvpnui.desktop index 3e6701b6..01b0ce9c 100644 --- a/vpn/fortisslvpn/plasmanetworkmanagement_fortisslvpnui.desktop +++ b/vpn/fortisslvpn/plasmanetworkmanagement_fortisslvpnui.desktop @@ -1,64 +1,72 @@ [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[el]=Fortinet SSLVPN (fortisslvpn) +Name[en_GB]=Fortinet SSLVPN (fortisslvpn) Name[es]=SSLVPN de Fortinet (fortisslvpn) Name[eu]=Fortinet SSLVPN (fortisslvpn) Name[fr]=SSLVPN Fortinet (fortisslvpn) Name[gl]=VPN SSL de Fortinet (fortisslvpn) Name[it]=Fortinet SSLVPN (fortisslvpn) +Name[ko]=Fortinet SSLVPN (fortisslvpn) Name[nl]=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[sk]=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[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[fr]=Réseaux privés virtuels SSLVPN Fortinet -Comment[gl]=Redes privadas virtuais SSL de Fortinet +Comment[gl]=Redes privadas virtuais SSL de Fortinet Comment[it]=Reti private virtuali Fortinet SSLVPN +Comment[ko]=Fortinet SSLVPN 가상 개인 네트워크 Comment[nl]=Fortinet SSLVPN virtuele private netwerken 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[sk]=Virtuálne privátne siete 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/plasmanetworkmanagement_iodineui.desktop b/vpn/iodine/plasmanetworkmanagement_iodineui.desktop index a3349b12..bc3a0dbd 100644 --- a/vpn/iodine/plasmanetworkmanagement_iodineui.desktop +++ b/vpn/iodine/plasmanetworkmanagement_iodineui.desktop @@ -1,82 +1,84 @@ [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[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[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/l2tp.ui b/vpn/l2tp/l2tp.ui index 597ef1b0..6f541997 100644 --- a/vpn/l2tp/l2tp.ui +++ b/vpn/l2tp/l2tp.ui @@ -1,221 +1,221 @@ L2tpWidget 0 0 450 388 6 Gateway: L2TP server IP or name. true User name: Set the name used for authenticating the local system to the peer to <name>. true Password: Password passed to PPPD when prompted for it. true NT Domain: Append the domain name <domain> to the local host name for authentication purposes. true Qt::Horizontal - CA Certificate: + CA Certificate: - Certificate: + Certificate: - Private Key: + Private Key: Qt::Vertical 20 216 Qt::Horizontal 188 22 IPsec Settings... PPP Settings... false false false Use Certificate KUrlRequester QWidget
kurlrequester.h
PasswordField QLineEdit
passwordfield.h
gateway username password domain btnIPSecSettings btnPPPSettings
diff --git a/vpn/l2tp/l2tpppp.ui b/vpn/l2tp/l2tpppp.ui index 12731792..60055b7c 100644 --- a/vpn/l2tp/l2tpppp.ui +++ b/vpn/l2tp/l2tpppp.ui @@ -1,416 +1,416 @@ L2tpPppWidget 0 0 341 702 0 0 6 Authentication 6 Allow following authentication methods: listWidget Allow/disable authentication methods PAP Checked CHAP Checked MSCHAP Checked MSCHAPv2 Checked EAP Checked Compression Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter 6 Allow/disable BSD-Compress compression. Allow BSD compression true Allow/disable Deflate compression. Allow Deflate compression true Allow/disable Van Jacobson style TCP/IP header compression in both the transmit and the receive directions. Allow TCP header compression true Allow protocol field compression negotiation in both the receive and the transmit directions. Use protocol field compression negotiation true false Use Address/Control compression in both directions (send and receive). Use Address/Control compression true Echo 6 Send LCP echo-requests to find out whether peer is alive. - Send PPP echo packets + Send PPP echo packets QDialogButtonBox::Cancel|QDialogButtonBox::Ok 0 0 Other Settings 6 MRU: 1500 MTU: 1500 Note: MPPE encryption is only available with MSCHAP authentication methods. To enable this checkbox, select one or more of the MSCHAP authentication methods: MSCHAP or MSCHAPv2. Use MPPE Encryption true false 6 100 16777215 Crypto: cbMPPECrypto 0 0 Require the use of MPPE, with 40/128-bit encryption or all. Any 128 bit 40 bit Allow MPPE to use stateful mode. Stateless mode is still attempted first. Use stateful encryption grp_authenfication grp_echo grp_cryptoAndCompression gbMPPE buttonBox grp_other listWidget gbMPPE cbMPPECrypto cbstatefulEncryption cbBSD cbdeflate cbTCPheaders cbCompressionNegotiation cbAddressControlCompression cbsendEcho buttonBox accepted() L2tpPppWidget accept() 187 536 187 276 buttonBox rejected() L2tpPppWidget reject() 187 536 187 276 gbMPPE toggled(bool) cbMPPECrypto setEnabled(bool) 187 250 239 248 gbMPPE toggled(bool) cbstatefulEncryption setEnabled(bool) 187 250 187 277 diff --git a/vpn/openvpn/nm-openvpn-service.h b/vpn/openvpn/nm-openvpn-service.h index 409f7829..b63ab5c1 100644 --- a/vpn/openvpn/nm-openvpn-service.h +++ b/vpn/openvpn/nm-openvpn-service.h @@ -1,110 +1,111 @@ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */ /* nm-openvpn-service - openvpn integration with NetworkManager * * Copyright (C) 2005 - 2008 Tim Niemueller * Copyright (C) 2005 - 2008 Dan Williams * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef NM_OPENVPN_SERVICE_H #define NM_OPENVPN_SERVICE_H #define NM_DBUS_SERVICE_OPENVPN "org.freedesktop.NetworkManager.openvpn" #define NM_DBUS_INTERFACE_OPENVPN "org.freedesktop.NetworkManager.openvpn" #define NM_DBUS_PATH_OPENVPN "/org/freedesktop/NetworkManager/openvpn" #define NM_OPENVPN_KEY_AUTH "auth" #define NM_OPENVPN_KEY_CA "ca" #define NM_OPENVPN_KEY_CERT "cert" #define NM_OPENVPN_KEY_CIPHER "cipher" #define NM_OPENVPN_KEY_KEYSIZE "keysize" #define NM_OPENVPN_KEY_COMP_LZO "comp-lzo" #define NM_OPENVPN_KEY_CONNECTION_TYPE "connection-type" #define NM_OPENVPN_KEY_FLOAT "float" #define NM_OPENVPN_KEY_FRAGMENT_SIZE "fragment-size" #define NM_OPENVPN_KEY_KEY "key" #define NM_OPENVPN_KEY_LOCAL_IP "local-ip" /* ??? */ #define NM_OPENVPN_KEY_MSSFIX "mssfix" #define NM_OPENVPN_KEY_NS_CERT_TYPE "ns-cert-type" #define NM_OPENVPN_KEY_PING "ping" #define NM_OPENVPN_KEY_PING_EXIT "ping-exit" #define NM_OPENVPN_KEY_PING_RESTART "ping-restart" #define NM_OPENVPN_KEY_PORT "port" #define NM_OPENVPN_KEY_PROTO_TCP "proto-tcp" #define NM_OPENVPN_KEY_PROXY_TYPE "proxy-type" #define NM_OPENVPN_KEY_PROXY_SERVER "proxy-server" #define NM_OPENVPN_KEY_PROXY_PORT "proxy-port" #define NM_OPENVPN_KEY_PROXY_RETRY "proxy-retry" #define NM_OPENVPN_KEY_HTTP_PROXY_USERNAME "http-proxy-username" #define NM_OPENVPN_KEY_REMOTE "remote" #define NM_OPENVPN_KEY_REMOTE_RANDOM "remote-random" #define NM_OPENVPN_KEY_REMOTE_IP "remote-ip" #define NM_OPENVPN_KEY_STATIC_KEY "static-key" #define NM_OPENVPN_KEY_STATIC_KEY_DIRECTION "static-key-direction" #define NM_OPENVPN_KEY_TA "ta" #define NM_OPENVPN_KEY_TA_DIR "ta-dir" #define NM_OPENVPN_KEY_TUNNEL_MTU "tunnel-mtu" #define NM_OPENVPN_KEY_USERNAME "username" #define NM_OPENVPN_KEY_TAP_DEV "tap-dev" #define NM_OPENVPN_KEY_DEV "dev" #define NM_OPENVPN_KEY_DEV_TYPE "dev-type" #define NM_OPENVPN_KEY_TUN_IPV6 "tun-ipv6" #define NM_OPENVPN_KEY_TLS_CIPHER "tls-cipher" +#define NM_OPENVPN_KEY_TLS_CRYPT "tls-crypt" #define NM_OPENVPN_KEY_TLS_REMOTE "tls-remote" #define NM_OPENVPN_KEY_VERIFY_X509_NAME "verify-x509-name" #define NM_OPENVPN_KEY_REMOTE_CERT_TLS "remote-cert-tls" #define NM_OPENVPN_KEY_MAX_ROUTES "max-routes" #define NM_OPENVPN_KEY_PASSWORD "password" #define NM_OPENVPN_KEY_CERTPASS "cert-pass" #define NM_OPENVPN_KEY_HTTP_PROXY_PASSWORD "http-proxy-password" /* Internal auth-dialog -> service token indicating that no secrets are * required for the connection. */ #define NM_OPENVPN_KEY_NOSECRET "no-secret" #define NM_OPENVPN_KEY_RENEG_SECONDS "reneg-seconds" #define NM_OPENVPN_AUTH_NONE "none" #define NM_OPENVPN_AUTH_RSA_MD4 "RSA-MD4" #define NM_OPENVPN_AUTH_MD5 "MD5" #define NM_OPENVPN_AUTH_SHA1 "SHA1" #define NM_OPENVPN_AUTH_SHA224 "SHA224" #define NM_OPENVPN_AUTH_SHA256 "SHA256" #define NM_OPENVPN_AUTH_SHA384 "SHA384" #define NM_OPENVPN_AUTH_SHA512 "SHA512" #define NM_OPENVPN_AUTH_RIPEMD160 "RIPEMD160" #define NM_OPENVPN_CONTYPE_TLS "tls" #define NM_OPENVPN_CONTYPE_STATIC_KEY "static-key" #define NM_OPENVPN_CONTYPE_PASSWORD "password" #define NM_OPENVPN_CONTYPE_PASSWORD_TLS "password-tls" /* arguments of "--remote-cert-tls" */ #define NM_OPENVPN_REM_CERT_TLS_CLIENT "client" #define NM_OPENVPN_REM_CERT_TLS_SERVER "server" /* arguments of "--ns-cert-type" */ #define NM_OPENVPN_NS_CERT_TYPE_CLIENT "client" #define NM_OPENVPN_NS_CERT_TYPE_SERVER "server" /* possible types for verify-x509-name */ #define NM_OPENVPN_VERIFY_X509_NAME_TYPE_SUBJECT "subject" #define NM_OPENVPN_VERIFY_X509_NAME_TYPE_NAME "name" #define NM_OPENVPN_VERIFY_X509_NAME_TYPE_NAME_PREFIX "name-prefix" #endif /* NM_OPENVPN_SERVICE_H */ diff --git a/vpn/openvpn/openvpnadvanced.ui b/vpn/openvpn/openvpnadvanced.ui index 5e7c36e5..766f0056 100644 --- a/vpn/openvpn/openvpnadvanced.ui +++ b/vpn/openvpn/openvpnadvanced.ui @@ -1,1433 +1,1465 @@ OpenVpnAdvancedWidget 0 0 - 554 - 611 + 626 + 624 QDialogButtonBox::Cancel|QDialogButtonBox::Ok 0 General TCP/UDP port number for peer. (Default value when there is no port for gateway). Use custom gateway port: false TCP/UDP port number for peer. (Default value when there is no port for gateway). Automatic 1 65535 1194 Renegotiate data channel key after the specified number of seconds. - Use custom renegotiation interval + Use custom renegotiation interval: false Renegotiate data channel key after the specified number of seconds. 604800 Use fast LZO compression. Use LZO compression false Use fast LZO compression. No Yes Adaptive Use TCP for communicating with remote host. Use a TCP connection Explicitly set virtual device type (TUN/TAP). Set virtual device type: false Explicitly set virtual device type (TUN/TAP). TUN TAP Use custom name for TUN/TAP virtual device (instead of default "tun" or "tap"). Set virtual device name: false 0 0 Use custom name for TUN/TAP virtual device (instead of default "tun" or "tap"). Automatic Take the TUN device MTU to be specified value and derive the link MTU from it. Use custom tunnel Maximum Transmission Unit (MTU): false Take the TUN device MTU to be specified value and derive the link MTU from it. Automatic 1 65535 1500 Enable internal datagram fragmentation with this maximum size. Use custom UDP fragment size: false Enable internal datagram fragmentation with this maximum size. Automatic 65535 1300 Restrict tunnel TCP maximum segment size. Restrict TCP maximum segment size (MSS) Randomize the order of gateways list (remote) as a kind of basic load- balancing measure. Randomize remote hosts Build a tun link capable of forwarding IPv6 traffic. IPv6 tun link Ping remote over the TCP/UDP control channel if no packets have been sent for at least n seconds. Specify ping interval: false Ping remote over the TCP/UDP control channel if no packets have been sent for at least n seconds. 1 65535 30 Exit or restart after n seconds pass without reception of a ping or other packet from remote. Specify exit or restart ping: false Exit or restart after n seconds pass without reception of a ping or other packet from remote. ping-exit ping-restart false Exit or restart after n seconds pass without reception of a ping or other packet from remote. 1 65535 30 Allow remote peer to change its IP address and/or port number such as due to DHCP (this is the default if --remote is not used). --float when specified with --remote allows an OpenVPN session to initially connect to a peer at a known address, however if packets arrive from a new address and pass all authentication tests, the new address will take control of the session. This is useful when you are connecting to a peer which holds a dynamic address such as a dial-in user or DHCP client. Essentially, --float tells OpenVPN to accept authenticated packets from any address, not only the address which was specified in the --remote option. Accept authenticated packets from any address (Float) Specify the maximum number of routes the server is allowed to specify. Specify max routes: false Specify the maximum number of routes the server is allowed to specify. 100000000 100 Qt::Vertical 303 11 Security Encrypt packets with cipher algorithm. The default is BF-CBC (Blowfish in Cipher Block Chaining mode). Cipher: Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter cboCipher false 0 0 Encrypt packets with cipher algorithm. The default is BF-CBC (Blowfish in Cipher Block Chaining mode). Obtaining available ciphers... Set cipher key size to a custom value. If unspecified, it defaults to cipher-specific size. Qt::LeftToRight Use custom size of cipher key: false Set cipher key size to a custom value. If unspecified, it defaults to cipher-specific size. 1 65535 128 Authenticate packets with HMAC using message digest algorithm. The default is SHA1. HMAC Authentication: Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter cboHmac 0 0 Authenticate packets with HMAC using message digest algorithm. The default is SHA1. Default None MD-4 MD-5 SHA-1 SHA-224 SHA-256 SHA-384 SHA-512 RIPEMD-160 Qt::Vertical 20 0 TLS Settings Verify server certificate identification. When enabled, connection will only succeed if the server certificate matches some expected properties. Matching can either apply to the whole certificate subject (all the fields), or just the Common Name (CN field). Server Certificate Check: Verify server certificate identification. When enabled, connection will only succeed if the server certificate matches some expected properties. Matching can either apply to the whole certificate subject (all the fields), or just the Common Name (CN field). Don't verify certificate identification Verify whole subject exactly Verify name exactly Verify name by prefix Verify subject partially (legacy mode, strongly discouraged) false Subject or Common Name to verify server certificate information against. Subject Match: subjectMatch false Subject or Common Name to verify server certificate information against. Connect only to servers whose certificate matches the given subject. Example: /CN=myvpn.company.com true Require that peer certificate was signed with an explicit key usage and extended key usage based on RFC3280 TLS rules. Verify peer (server) certificate usage signature false Require that peer certificate was signed with an explicit key usage and extended key usage based on RFC3280 TLS rules. Remote peer certificate TLS type: false Require that peer certificate was signed with an explicit key usage and extended key usage based on RFC3280 TLS rules. Server Client Require that peer certificate was signed with an explicit nsCertType designation. Verify peer (server) certificate nsCertType designation false Require that peer certificate was signed with an explicit nsCertType designation. Remote peer certificate nsCert designation: false Require that peer certificate was signed with an explicit nsCertType designation. Server Client Add an additional layer of HMAC authentication. - Use additional TLS authentication + - true + false false + + + Mode: + + + + + + + + None + + + + + TLS-Auth + + + + + TLS-Crypt + + + + + Add an additional layer of HMAC authentication on top of the TLS control channel to protect against DoS attacks. Key File: false kurlTlsAuthKey - + + + false + Add an additional layer of HMAC authentication on top of the TLS control channel to protect against DoS attacks. - + Direction parameter for static key mode. Key Direction: false cboDirection - + + + false + Direction parameter for static key mode. None Server (0) Client (1) - + Qt::Vertical 20 137 Proxies QFormLayout::ExpandingFieldsGrow 6 - Proxy type: HTTP or Socks + Proxy type: HTTP or SOCKS Proxy Type: cmbProxyType 0 0 0 0 - Proxy type: HTTP or Socks + Proxy type: HTTP or SOCKS Not Required HTTP SOCKS 0 0 true Select this option if your organization requires the use of a proxy server to access the Internet. true Connect to remote host through a proxy with this address. Server Address: proxyServerAddress Connect to remote host through a proxy with this address. true Connect to remote host through a proxy with this port. Port: sbProxyPort 0 0 Connect to remote host through a proxy with this port. 65535 - HTTP/Socks proxy username passed to OpenVPN when prompted for it. + HTTP/SOCKS proxy username passed to OpenVPN when prompted for it. Proxy Username: proxyUsername - HTTP/Socks proxy username passed to OpenVPN when prompted for it. + HTTP/SOCKS proxy username passed to OpenVPN when prompted for it. true - HTTP/Socks proxy password passed to OpenVPN when prompted for it. + HTTP/SOCKS proxy password passed to OpenVPN when prompted for it. Proxy Password: proxyPassword - HTTP/Socks proxy password passed to OpenVPN when prompted for it. + HTTP/SOCKS proxy password passed to OpenVPN when prompted for it. true Retry indefinitely on proxy errors. It simulates a SIGUSR1 reset. Retry indefinitely when errors occur KUrlRequester QWidget
kurlrequester.h
PasswordField QLineEdit
passwordfield.h
sbCustomPort sbMtu sbCustomFragmentSize chkUseCustomReneg sbCustomReneg chkUseVirtualDeviceType cmbDeviceType chkUseVirtualDeviceName leVirtualDeviceName chkUseLZO chkUseTCP chkMssRestrict chkRandRemHosts cboCipher chkUseCustomCipherKey sbCustomCipherKey cboHmac subjectMatch chkRemoteCertTls cmbRemoteCertTls useExtraTlsAuth kurlTlsAuthKey cboDirection cmbProxyType proxyServerAddress sbProxyPort chkProxyRetry proxyUsername proxyPassword chkUseCustomReneg toggled(bool) sbCustomReneg setEnabled(bool) 172 131 392 131 chkRemoteCertTls toggled(bool) cmbRemoteCertTls setEnabled(bool) 281 94 414 127 chkRemoteCertTls toggled(bool) labelRemoteCertTls setEnabled(bool) 281 94 148 127 chkUseVirtualDeviceType toggled(bool) cmbDeviceType setEnabled(bool) 146 208 412 208 chkUseVirtualDeviceName toggled(bool) leVirtualDeviceName setEnabled(bool) 146 245 412 245 chkUseCustomCipherKey toggled(bool) sbCustomCipherKey setEnabled(bool) 146 97 412 97 chkMtu toggled(bool) sbMtu setEnabled(bool) 209 268 472 268 chkPingInterval toggled(bool) sbPingInterval setEnabled(bool) 145 419 408 420 chkSpecifyExitRestartPing toggled(bool) sbSpecifyExitRestartPing setEnabled(bool) 119 456 461 457 chkSpecifyExitRestartPing toggled(bool) cbSpecifyExitRestartPing setEnabled(bool) 119 456 304 457 chkMaxRoutes toggled(bool) sbMaxRoutes setEnabled(bool) 145 519 408 520 chkCustomFragmentSize toggled(bool) sbCustomFragmentSize setEnabled(bool) 145 304 408 305 chkUseLZO toggled(bool) cmbUseLZO setEnabled(bool) 145 131 408 132 chkCustomPort toggled(bool) sbCustomPort setEnabled(bool) 145 57 408 58 chkNsCertType toggled(bool) cmbNsCertType setEnabled(bool) 276 189 422 221 chkNsCertType toggled(bool) lblNsCertType setEnabled(bool) 276 189 159 221
diff --git a/vpn/openvpn/openvpnadvancedwidget.cpp b/vpn/openvpn/openvpnadvancedwidget.cpp index aa3a878d..2689d554 100644 --- a/vpn/openvpn/openvpnadvancedwidget.cpp +++ b/vpn/openvpn/openvpnadvancedwidget.cpp @@ -1,678 +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) { + 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, &KProcess::readyReadStandardOutput, this, &OpenVpnAdvancedWidget::gotOpenVpnCipherOutput); connect(d->openvpnCipherProcess, static_cast(&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, &KProcess::readyReadStandardOutput, this, &OpenVpnAdvancedWidget::gotOpenVpnVersionOutput); connect(d->openvpnVersionProcess, static_cast(&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->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->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); } - m_ui->useExtraTlsAuth->setChecked(!dataMap[QLatin1String(NM_OPENVPN_KEY_TA)].isEmpty()); - m_ui->kurlTlsAuthKey->setUrl(QUrl::fromLocalFile(dataMap[QLatin1String(NM_OPENVPN_KEY_TA)])); - 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); + 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->useExtraTlsAuth->isChecked()) { + 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/strongswan/strongswanprop.ui b/vpn/strongswan/strongswanprop.ui index 52f686fc..a109cb5c 100644 --- a/vpn/strongswan/strongswanprop.ui +++ b/vpn/strongswan/strongswanprop.ui @@ -1,353 +1,353 @@ StrongswanProp 0 0 490 460 Strong Swan VPN Gateway 0 Gateway: false leGateway true Certificate: Authentication 0 0 false Certificate/private key Certificate/ssh-agent Smartcard EAP 0 0 0 QFormLayout::ExpandingFieldsGrow 0 Certificate: Private key: Private Key Password: true 0 Certificate: 0 PIN: true QFormLayout::ExpandingFieldsGrow 0 Username: leUserName true true - User Password + User Password: leUserPassword Options false Request an inner IP address true false Enforce UDP encapsulation Use IP compression Qt::Vertical 20 0 KUrlRequester QWidget
kurlrequester.h
PasswordField QLineEdit
passwordfield.h
leGateway leGatewayCertificate cmbMethod leAuthPrivatekeyCertificate leAuthPrivatekeyKey lePrivateKeyPassword leAuthSshCertificate lePin leUserName leUserPassword innerIP udpEncap ipComp cmbMethod currentIndexChanged(int) swMethods setCurrentIndex(int) 231 129 231 186