Example #1
0
    def __init__(self, *args, **kwargs):
        # Initialize the base class...
        super(DvidDataSelectionBrowser, self).__init__(*args, **kwargs)

        self._subvol_widget = SubregionRoiWidget(parent=self)

        subvol_layout = QVBoxLayout()
        subvol_layout.addWidget(self._subvol_widget)
        group_title = (
            "Restrict to subvolume (Right-click a volume name above to auto-initialize these subvolume parameters.)"
        )
        subvol_groupbox = QGroupBox(group_title, parent=self)
        subvol_groupbox.setCheckable(True)
        subvol_groupbox.setChecked(False)
        subvol_groupbox.setEnabled(False)
        subvol_groupbox.toggled.connect(self._update_status)
        subvol_groupbox.setLayout(subvol_layout)
        subvol_groupbox.setFixedHeight(200)
        subvol_groupbox.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum)
        self._subvol_groupbox = subvol_groupbox

        # Add to the layout
        layout = self.layout()
        layout.insertWidget(3, subvol_groupbox)

        # Special right-click behavior.
        self._repo_treewidget.viewport().installEventFilter(self)
Example #2
0
    def __init__(self, *args, **kwargs):
        # Initialize the base class...
        super( DvidDataSelectionBrowser, self ).__init__(*args, **kwargs)

        self._subvol_widget = SubregionRoiWidget( parent=self )

        subvol_layout = QVBoxLayout()
        subvol_layout.addWidget( self._subvol_widget )
        group_title = "Restrict to subvolume (Right-click a volume name above to auto-initialize these subvolume parameters.)"
        subvol_groupbox = QGroupBox(group_title, parent=self)
        subvol_groupbox.setCheckable(True)
        subvol_groupbox.setChecked(False)
        subvol_groupbox.setEnabled(False)
        subvol_groupbox.toggled.connect( self._update_status )
        subvol_groupbox.setLayout( subvol_layout )
        subvol_groupbox.setFixedHeight( 200 )
        subvol_groupbox.setSizePolicy( QSizePolicy.Preferred, QSizePolicy.Minimum )
        self._subvol_groupbox = subvol_groupbox

        # Add to the layout
        layout = self.layout()
        layout.insertWidget( 3, subvol_groupbox )

        # Special right-click behavior.
        self._repo_treewidget.viewport().installEventFilter(self)
    def buildPostProcessorForm(self, theParams):
        """Build Post Processor Tab

        Args:
           * theParams - dictionary containing element of form
        Returns:
           not applicable
        """

        # create postprocessors tab
        myTab = QWidget()
        myFormLayout = QFormLayout(myTab)
        myFormLayout.setLabelAlignment(Qt.AlignLeft)
        self.tabWidget.addTab(myTab, self.tr('Postprocessors'))
        self.tabWidget.tabBar().setVisible(True)

        # create element for the tab
        myValues = {}
        for myLabel, myOptions in theParams.items():
            myInputValues = {}

            # NOTE (gigih) : 'params' is assumed as dictionary
            if 'params' in myOptions:
                myGroupBox = QGroupBox()
                myGroupBox.setCheckable(True)
                myGroupBox.setTitle(get_postprocessor_human_name(myLabel))

                # NOTE (gigih): is 'on' always exist??
                myGroupBox.setChecked(myOptions.get('on'))
                myInputValues['on'] = self.bind(myGroupBox, 'checked', bool)

                myLayout = QFormLayout(myGroupBox)
                myGroupBox.setLayout(myLayout)

                # create widget element from 'params'
                myInputValues['params'] = {}
                for myKey, myValue in myOptions['params'].items():
                    myHumanName = get_postprocessor_human_name(myKey)
                    myInputValues['params'][myKey] = self.buildWidget(
                        myLayout, myHumanName, myValue)

                myFormLayout.addRow(myGroupBox, None)

            elif 'on' in myOptions:
                myCheckBox = QCheckBox()
                myCheckBox.setText(get_postprocessor_human_name(myLabel))
                myCheckBox.setChecked(myOptions['on'])

                myInputValues['on'] = self.bind(myCheckBox, 'checked', bool)
                myFormLayout.addRow(myCheckBox, None)
            else:
                raise NotImplementedError('This case is not handled for now')

            myValues[myLabel] = myInputValues

        self.values['postprocessors'] = myValues
    def buildPostProcessorForm(self, theParams):
        """Build Post Processor Tab

        Args:
           * theParams - dictionary containing element of form
        Returns:
           not applicable
        """

        # create postprocessors tab
        myTab = QWidget()
        myFormLayout = QFormLayout(myTab)
        myFormLayout.setLabelAlignment(Qt.AlignLeft)
        self.tabWidget.addTab(myTab, self.tr('Postprocessors'))
        self.tabWidget.tabBar().setVisible(True)

        # create element for the tab
        myValues = {}
        for myLabel, myOptions in theParams.items():
            myInputValues = {}

            # NOTE (gigih) : 'params' is assumed as dictionary
            if 'params' in myOptions:
                myGroupBox = QGroupBox()
                myGroupBox.setCheckable(True)
                myGroupBox.setTitle(get_postprocessor_human_name(myLabel))

                # NOTE (gigih): is 'on' always exist??
                myGroupBox.setChecked(myOptions.get('on'))
                myInputValues['on'] = self.bind(myGroupBox, 'checked', bool)

                myLayout = QFormLayout(myGroupBox)
                myGroupBox.setLayout(myLayout)

                # create widget element from 'params'
                myInputValues['params'] = {}
                for myKey, myValue in myOptions['params'].items():
                    myHumanName = get_postprocessor_human_name(myKey)
                    myInputValues['params'][myKey] = self.buildWidget(
                        myLayout, myHumanName, myValue)

                myFormLayout.addRow(myGroupBox, None)

            elif 'on' in myOptions:
                myCheckBox = QCheckBox()
                myCheckBox.setText(get_postprocessor_human_name(myLabel))
                myCheckBox.setChecked(myOptions['on'])

                myInputValues['on'] = self.bind(myCheckBox, 'checked', bool)
                myFormLayout.addRow(myCheckBox, None)
            else:
                raise NotImplementedError('This case is not handled for now')

            myValues[myLabel] = myInputValues

        self.values['postprocessors'] = myValues
    def build_post_processor_form(self, parameters):
        """Build Post Processor Tab.

        :param parameters: A Dictionary containing element of form
        :type parameters: dict
        """
        # create postprocessors tab
        tab = QWidget()
        form_layout = QFormLayout(tab)
        form_layout.setLabelAlignment(Qt.AlignLeft)
        self.tabWidget.addTab(tab, self.tr('Postprocessors'))
        self.tabWidget.tabBar().setVisible(True)

        # create element for the tab
        values = OrderedDict()
        for label, options in parameters.items():
            input_values = OrderedDict()

            # NOTE (gigih) : 'params' is assumed as dictionary
            if 'params' in options:
                group_box = QGroupBox()
                group_box.setCheckable(True)
                group_box.setTitle(get_postprocessor_human_name(label))

                # NOTE (gigih): is 'on' always exist??
                # (MB) should always be there
                group_box.setChecked(options.get('on'))
                input_values['on'] = self.bind(group_box, 'checked', bool)

                layout = QFormLayout(group_box)
                group_box.setLayout(layout)

                # create widget element from 'params'
                input_values['params'] = OrderedDict()
                for key, value in options['params'].items():
                    input_values['params'][key] = self.build_widget(
                        layout, key, value)

                form_layout.addRow(group_box, None)

            elif 'on' in options:
                checkbox = QCheckBox()
                checkbox.setText(get_postprocessor_human_name(label))
                checkbox.setChecked(options['on'])

                input_values['on'] = self.bind(checkbox, 'checked', bool)
                form_layout.addRow(checkbox, None)
            else:
                raise NotImplementedError('This case is not handled for now')

            values[label] = input_values

        self.values['postprocessors'] = values
    def build_post_processor_form(self, parameters):
        """Build Post Processor Tab.

        :param parameters: A Dictionary containing element of form
        :type parameters: dict
        """
        # create postprocessors tab
        tab = QWidget()
        form_layout = QFormLayout(tab)
        form_layout.setLabelAlignment(Qt.AlignLeft)
        self.tabWidget.addTab(tab, self.tr('Postprocessors'))
        self.tabWidget.tabBar().setVisible(True)

        # create element for the tab
        values = OrderedDict()
        for label, options in parameters.items():
            input_values = OrderedDict()

            # NOTE (gigih) : 'params' is assumed as dictionary
            if 'params' in options:
                group_box = QGroupBox()
                group_box.setCheckable(True)
                group_box.setTitle(get_postprocessor_human_name(label))

                # NOTE (gigih): is 'on' always exist??
                # (MB) should always be there
                group_box.setChecked(options.get('on'))
                input_values['on'] = self.bind(group_box, 'checked', bool)

                layout = QFormLayout(group_box)
                group_box.setLayout(layout)

                # create widget element from 'params'
                input_values['params'] = OrderedDict()
                for key, value in options['params'].items():
                    input_values['params'][key] = self.build_widget(
                        layout, key, value)

                form_layout.addRow(group_box, None)

            elif 'on' in options:
                checkbox = QCheckBox()
                checkbox.setText(get_postprocessor_human_name(label))
                checkbox.setChecked(options['on'])

                input_values['on'] = self.bind(checkbox, 'checked', bool)
                form_layout.addRow(checkbox, None)
            else:
                raise NotImplementedError('This case is not handled for now')

            values[label] = input_values

        self.values['postprocessors'] = values
Example #7
0
    def __changeDirectory(self, path):
        for c in self.filesview:
            c.setParent(None)
            c.deleteLater()
        self.filesview = []
        self.checkBox_2.setChecked(False)

        self.progressBars = {}
        for f in self.__getFiles(path):
            try:
                group = QGroupBox(f, self)
                group.setGeometry(QRect(20, 20, 100, 150))
                group.setCheckable(True)
                group.setChecked(False)
                group.setFixedSize(100, 150)
                group.setFlat(True)
                group.setToolTip(f)

                label = QLabel(group)
                label.setScaledContents(True)
                label.setGeometry(QRect(5, 25, 90, 90))
                label.setToolTip(f)

                progressBar = QProgressBar(group)
                progressBar.setGeometry(QRect(0, 70, 111, 10))
                progressBar.setProperty("value", 0)
                progressBar.setTextVisible(False)
                progressBar.setToolTip('0%')
                progressBar.setVisible(False)
                self.progressBars[f] = progressBar

                self.filesview.append(group)
                from os.path import isfile
                if isfile(path + '/' + f):
                    ext = f.split('.')[-1]
                    if isfile('icons/' + ext.lower() + '.png'):
                        label.setPixmap(
                            QPixmap('icons/' + ext.lower() + '.png'))
                    else:
                        label.setPixmap(QPixmap('icons/default.png'))
                else:
                    label.setPixmap(QPixmap('icons/folder.png'))
                self.connect(group, SIGNAL("clicked()"), self.__deselectFile)
            except ValueError:
                pass

        i = 0
        for x in list(range(len(self.filesview))):
            if (x % 4) == 0:
                i = i + 1
            self.rowsview[i].addWidget(self.filesview[x])
    def __init__(self, *args, **kwargs):
        # Initialize the base class...
        super( DvidDataSelectionBrowser, self ).__init__(*args, **kwargs)

        self._roi_widget = SubregionRoiWidget( parent=self )

        roi_layout = QVBoxLayout()
        roi_layout.addWidget( self._roi_widget )
        roi_groupbox = QGroupBox("Specify Region of Interest", parent=self)
        roi_groupbox.setCheckable(True)
        roi_groupbox.setChecked(False)
        roi_groupbox.setEnabled(False)
        roi_groupbox.toggled.connect( self._update_display )
        roi_groupbox.setLayout( roi_layout )
        roi_groupbox.setFixedHeight( 200 )
        roi_groupbox.setSizePolicy( QSizePolicy.Preferred, QSizePolicy.Minimum )
        self._roi_groupbox = roi_groupbox

        # Add to the layout
        layout = self.layout()
        layout.insertWidget( 3, roi_groupbox )
Example #9
0
    def __init__(self, *args, **kwargs):
        # Initialize the base class...
        super( DvidDataSelectionBrowser, self ).__init__(*args, **kwargs)

        self._roi_widget = SubregionRoiWidget( parent=self )

        roi_layout = QVBoxLayout()
        roi_layout.addWidget( self._roi_widget )
        roi_groupbox = QGroupBox("Specify Region of Interest", parent=self)
        roi_groupbox.setCheckable(True)
        roi_groupbox.setChecked(False)
        roi_groupbox.setEnabled(False)
        roi_groupbox.toggled.connect( self._update_display )
        roi_groupbox.setLayout( roi_layout )
        roi_groupbox.setFixedHeight( 200 )
        roi_groupbox.setSizePolicy( QSizePolicy.Preferred, QSizePolicy.Minimum )
        self._roi_groupbox = roi_groupbox

        # Add to the layout
        layout = self.layout()
        layout.insertWidget( 3, roi_groupbox )
Example #10
0
class SphereWidget(QWidget):
    """
    Widget for editing sphere's parameters
    """

    signalObjetChanged = pyqtSignal(SphereParam, name='signal_objet_changed')

    def __init__(self, parent=None, param=None):
        super(SphereWidget, self).__init__(parent)

        if param is None:
            self.param = SphereParam()
        else:
            self.param = param

        gbC_lay = QVBoxLayout()

        l_cmap = QLabel("Cmap ")
        self.cmap = list(get_colormaps().keys())
        self.combo = QComboBox(self)
        self.combo.addItems(self.cmap)
        self.combo.currentIndexChanged.connect(self.updateParam)
        self.param.dict["colormap"] = self.cmap[0]
        hbox = QHBoxLayout()
        hbox.addWidget(l_cmap)
        hbox.addWidget(self.combo)
        gbC_lay.addLayout(hbox)

        self.sp = []
        # subdiv
        lL = QLabel("subdiv")
        self.sp.append(QSpinBox())
        self.sp[-1].setMinimum(0)
        self.sp[-1].setMaximum(6)
        self.sp[-1].setValue(self.param.dict["subdiv"])
        # Layout
        hbox = QHBoxLayout()
        hbox.addWidget(lL)
        hbox.addWidget(self.sp[-1])
        gbC_lay.addLayout(hbox)
        # signal's
        self.sp[-1].valueChanged.connect(self.updateParam)
        # Banded
        self.gbBand = QGroupBox(u"Banded")
        self.gbBand.setCheckable(True)
        hbox = QGridLayout()
        lL = QLabel("nbr band", self.gbBand)
        self.sp.append(QSpinBox(self.gbBand))
        self.sp[-1].setMinimum(0)
        self.sp[-1].setMaximum(100)
        # Layout
        hbox = QHBoxLayout()
        hbox.addWidget(lL)
        hbox.addWidget(self.sp[-1])
        self.gbBand.setLayout(hbox)
        gbC_lay.addWidget(self.gbBand)
        # signal's
        self.sp[-1].valueChanged.connect(self.updateParam)
        self.gbBand.toggled.connect(self.updateParam)

        gbC_lay.addStretch(1.0)

        hbox = QHBoxLayout()
        hbox.addLayout(gbC_lay)

        self.setLayout(hbox)
        self.updateMenu()

    def updateParam(self, option):
        """
        update param and emit a signal
        """

        tab = ["subdiv", "nbr_band"]
        for pos, name in enumerate(tab):
            self.param.dict[name] = self.sp[pos].value()
        self.param.dict["banded"] = self.gbBand.isChecked()
        self.param.dict["colormap"] = self.combo.currentText()
        # emit signal
        self.signalObjetChanged.emit(self.param)

    def updateMenu(self, param=None):
        """
        Update menus
        """
        if param is not None:
            self.param = param
        # Lock signals
        self.blockSignals(True)
        for wid in self.sp:
            wid.blockSignals(True)
        tab = ["subdiv", "nbr_band"]
        for pos, name in enumerate(tab):
            self.sp[pos].setValue(self.param.dict[name])
        self.gbBand.setChecked(self.param.dict["banded"])
        # unlock signals
        self.blockSignals(False)
        for wid in self.sp:
            wid.blockSignals(False)
        self.signalObjetChanged.emit(self.param)
class NetWorkSettingWidget(QWidget):

    def __init__(self, app, parent = None):
        super(NetWorkSettingWidget,self).__init__(parent)
        self.setStyleSheet("font-size : 16px;")
        self.app = app
        CDLL("../lib/libjson-c.so", mode=RTLD_GLOBAL)
        self.jytcapi = cdll.LoadLibrary('../lib/libjytcapi.so')
        self.jytcapi.jyinittcapi()
        self.initLayout()

        self.initCheckBoxStatus()

        self.restartNetworkTD = RestartNetworkThread()
        self.waitingDlg = InfoHintDialog(None)

        #绑定信号
        self.connect(self.autoGetIpCheckbox, SIGNAL("stateChanged(int)"),self.slotSettingDHCPType)

        self.connect(self.staticIpGroupbox, SIGNAL("clicked(bool)"),self.slotSettingStaticType)

        self.connect(self.autoGetDNSCheckBox, SIGNAL("stateChanged(int)"),self.slotSettingDNSType)

        self.connect(self.dnsServerAddressGroupbox, SIGNAL("clicked(bool)"),self.slotSettingCustomDNSType)

        self.connect(self.saveBtn, SIGNAL("clicked()"),self.slotSave)

        self.connect(self.restartNetworkTD, SIGNAL("restartNetwork"),self.slotShowRestartNetworkInfo)

    def initLayout(self):
        #IP设置
        self.autoGetIpCheckbox = QCheckBox(self.tr("Auto get IP"))

        self.staticIpGroupbox = QGroupBox(self.tr("Use this IP"))
        self.staticIpGroupbox.setCheckable(True)

        self.ipLabel = QLabel(self.tr("IP address"))
        self.netmastLabel = QLabel(self.tr("Net mask"))
        self.defaultGatewayLabel = QLabel(self.tr("Default gateway"))

        topSpaceWidget = QLabel()
        topSpaceWidget.setFixedHeight(1)

        self.ip = QLineEdit()
        self.ip.setContextMenuPolicy(Qt.NoContextMenu)
        self.ip.setFixedSize(400, 30)
        self.netmast = QLineEdit()
        self.netmast.setContextMenuPolicy(Qt.NoContextMenu)
        self.defaultGateway = QLineEdit()
        self.defaultGateway.setContextMenuPolicy(Qt.NoContextMenu)

        topGridLayout = QGridLayout()
        topGridLayout.setSpacing(15)
        topGridLayout.setMargin(20)
        topGridLayout.addWidget(self.ipLabel, 0, 0, 1, 1)
        topGridLayout.addWidget(self.ip, 0, 1, 1, 1)
        topGridLayout.addWidget(self.netmastLabel, 1, 0, 1, 1)
        topGridLayout.addWidget(self.netmast, 1, 1, 1, 1)
        topGridLayout.addWidget(self.defaultGatewayLabel, 2, 0, 1, 1)
        topGridLayout.addWidget(self.defaultGateway, 2, 1, 1, 1)
        topGridLayout.addWidget(topSpaceWidget, 3, 0, 1, 1)

        self.staticIpGroupbox.setLayout(topGridLayout)

        #DNS设置
        self.autoGetDNSCheckBox = QCheckBox(self.tr("Auto Get DNS"))

        self.dnsServerAddressGroupbox = QGroupBox(self.tr("Use This DNS"))
        self.dnsServerAddressGroupbox.setCheckable(True)

        self.dnsLabel = QLabel(self.tr("DNS"))
        self.backupDnsLabel = QLabel(self.tr("Backup DNS"))

        bottomSpaceWidget = QLabel()
        bottomSpaceWidget.setFixedHeight(1)

        self.dns = QLineEdit()
        self.dns.setContextMenuPolicy(Qt.NoContextMenu)
        self.backupDns = QLineEdit()
        self.backupDns.setContextMenuPolicy(Qt.NoContextMenu)

        self.saveBtn = QPushButton(self.tr("Save"))
        self.saveBtn.setStyleSheet("background: rgb(7,87,198); color: white; width: 90px; height: 30px;font-size : 16px;")

        bottomGridLayout = QGridLayout()
        bottomGridLayout.setSpacing(15)
        bottomGridLayout.setMargin(20)
        bottomGridLayout.addWidget(self.dnsLabel, 0, 0, 1, 1)
        bottomGridLayout.addWidget(self.dns, 0, 1, 1, 1)
        bottomGridLayout.addWidget(self.backupDnsLabel, 1, 0, 1, 1)
        bottomGridLayout.addWidget(self.backupDns, 1, 1, 1, 1)
        bottomGridLayout.addWidget(bottomSpaceWidget, 2, 0, 1, 1)

        self.dnsServerAddressGroupbox.setLayout(bottomGridLayout)

        #布局调整
        vLayout = QVBoxLayout()
        vLayout.setSpacing(10)
        vLayout.setMargin(10)

        vLayout.addWidget(self.autoGetIpCheckbox)
        vLayout.addWidget(self.staticIpGroupbox)
        vLayout.addSpacing(15)
        vLayout.addWidget(self.autoGetDNSCheckBox)
        vLayout.addWidget(self.dnsServerAddressGroupbox)
        vLayout.addStretch()

        topMainLayout = QHBoxLayout()
        topMainLayout.addStretch()
        topMainLayout.addSpacing(50)
        topMainLayout.addLayout(vLayout)
        topMainLayout.addStretch(2)

        bottomHLayout = QHBoxLayout()
        bottomHLayout.addStretch()
        bottomHLayout.addWidget(self.saveBtn)
        bottomHLayout.addStretch()

        mainVLayout = QVBoxLayout()
        mainVLayout.addLayout(topMainLayout)
        mainVLayout.addSpacing(10)
        mainVLayout.addLayout(bottomHLayout)

        self.setLayout(mainVLayout)
        
    def updateWindow(self):
        self.autoGetDNSCheckBox.setText(self.tr("Auto Get DNS"))
        self.autoGetIpCheckbox.setText(self.tr("Auto get IP"))
        self.dnsServerAddressGroupbox.setTitle(self.tr("Use This DNS"))
        self.staticIpGroupbox.setTitle(self.tr("Use this IP"))
        self.ipLabel.setText(self.tr("IP address"))
        self.netmastLabel.setText(self.tr("Net mask"))
        self.defaultGatewayLabel.setText(self.tr("Gate way"))
        self.dnsLabel.setText(self.tr("DNS"))
        self.backupDnsLabel.setText(self.tr("Backup DNS"))
        self.saveBtn.setText(self.tr("Save"))

    def slotShowRestartNetworkInfo(self, status):
        """显示重启网络的状态信息"""
            
        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
        else:
            QmName = "en_US.qm"
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
        """显示重启网络的状态信息"""
        
        if status == "Start":
            self.waitingDlg.setHintInfo(self.tr("network is restarting, waiting..."))
        elif status == "Success":
            self.waitingDlg.setHintInfo(self.tr("network start success!"))
            vmtype = StoreInfoParser.instance().getVmType()
            if vmtype == "offline":
                pass 
        elif status == "Failed":
            self.waitingDlg.setHintInfo(self.tr("network restart failed!"))
        else:
            return
        
        if self.waitingDlg.isHidden():
            self.waitingDlg.exec_()

    def slotSave(self):
        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
        else:
            QmName = "en_US.qm"
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
            
            
        if not self.checkInputValid():
            return

        if self.autoGetIpCheckbox.isChecked():
            netconf = self.setDynamicNetwork()
        elif self.staticIpGroupbox.isChecked():
            netconf = self.setStaticNetwork()

        #重新启动网络
        self.restartNetworkTD.setNetConf(netconf)
        self.restartNetworkTD.start()

        return

    def getCmdExecValueT(self, cmd):
        """得到命令执行的结果"""
        statusOutput = commands.getstatusoutput(cmd)
        monitorList = statusOutput[1].split("\n")
        return monitorList

    def getNetDnsType(self):
        typeList = ["dhcp","dhcp"]
        networkInfo = self.getCmdExecValueT("../lib/ccr_jytcapi network")
        for item in networkInfo:
            if len(item.split(":")) == 2:
                if item.split(":")[0] == "conf":
                    if item.split(":")[1] == "0":
                        typeList[0] = "dhcp"
                    else:
                        typeList[0] = "static"
                else:
                    pass
        DNSStatus = StoreInfoParser.instance().getDNSStatus()
        if DNSStatus == None:
            pass
        else:
            typeList[1] = DNSStatus
        return typeList

    def getNetStatic(self):
        netList = ["0.0.0.0","255.255.255.0","1.1.1.1"]
        networkInfo = self.getCmdExecValueT("../lib/ccr_jytcapi network")
        for item in networkInfo:
            if len(item.split(":")) == 2:
                if item.split(":")[0] == "ip":
                    netList[0] = item.split(":")[1] 
                elif item.split(":")[0] == "mask":
                    netList[1] = item.split(":")[1] 
                elif item.split(":")[0] == "gateway":
                    netList[2] = item.split(":")[1] 
        return netList

    def getDnsStatic(self):
        dnsList = ["0.0.0.0","2.5.5.0"]
        networkInfo = self.getCmdExecValueT("../lib/ccr_jytcapi network")
        for item in networkInfo:
            if len(item.split(":")) == 2:
                if item.split(":")[0] == "dns1":
                    dnsList[0] = item.split(":")[1] 
                elif item.split(":")[0] == "dns2":
                    dnsList[1] = item.split(":")[1] 
        return dnsList


    def initCheckBoxStatus(self):
        """读取网络配置文件,初始化相应的checkbox的状态"""
        [netType, DNSType] = self.getNetDnsType()
        if netType == "dhcp":
            self.autoGetIpCheckbox.setChecked(True)
            self.staticIpGroupbox.setChecked(False)
            self.autoGetDNSCheckBox.setEnabled(False)
            self.dnsServerAddressGroupbox.setEnabled(False)
        else:
            self.autoGetIpCheckbox.setChecked(False)
            self.staticIpGroupbox.setChecked(True)
            self.autoGetDNSCheckBox.setEnabled(True)
            self.dnsServerAddressGroupbox.setEnabled(True)
            [ip, netmask, gateway] = self.getNetStatic()
            if ip:
                self.ip.setText(ip)

            if netmask:
                self.netmast.setText(netmask)

            if gateway:
                self.defaultGateway.setText(gateway)


        if DNSType == "dhcp":
            self.autoGetDNSCheckBox.setChecked(True)
            self.dnsServerAddressGroupbox.setChecked(False)
        else:
            self.autoGetDNSCheckBox.setChecked(False)
            self.dnsServerAddressGroupbox.setChecked(True)
            [DNS_first, DNS_second] = self.getDnsStatic()
            if DNS_first:
                self.dns.setText(DNS_first)

            if DNS_second:
                self.backupDns.setText(DNS_second)


    def getCustomDNSInfo(self):
        """得到自定义DNS的内容"""
        DNS_first = None
        DNS_second = None
        statusOutput = commands.getstatusoutput("cat %s" % common.NETWORK_CONFIG_UBUNTU)
        if statusOutput[0] == 0:
            outputList = QString(statusOutput[1]).split("\n")
            for value in outputList:
                if value.split(" ")[0] == "dns-nameservers":
                    DNS_first = value.split(" ")[1]
                    if len(value.split(" ")) > 2:
                        DNS_second = value.split(" ")[2]

        return [DNS_first, DNS_second]


    def getStaticNetworkInfo(self):
        """得到静态网络的信息"""
        ip = netmask = gateway = None
        statusOutput = commands.getstatusoutput("cat %s" % common.NETWORK_CONFIG_UBUNTU)
        if statusOutput[0] == 0:
            outputList = QString(statusOutput[1]).split("\n")
            for value in outputList:
                if value.split(" ")[0] == "address":
                    ip = value.split(" ")[1]
                elif value.split(" ")[0] == "netmask":
                    netmask = value.split(" ")[1]
                elif value.split(" ")[0] == "gateway":
                    gateway = value.split(" ")[1]

        return [ip, netmask, gateway]

    def getNetworkType(self):
        """得到网络是静态还是动态类型"""
        netType = None
        DNSType = None
        statusOutput = commands.getstatusoutput("cat %s" % common.NETWORK_CONFIG_UBUNTU)
        if statusOutput[0] == 0:
            output = QString(statusOutput[1])
            if output.contains("dhcp"):
                netType = "dhcp"
            else:
                netType = "static"

            if output.contains("dns-nameservers"):
                DNSType = "customDNS"
            else:
                DNSType = "AUTODNS"

        return [netType, DNSType]

    def checkInputValid(self):
        """检测输入的有效性"""
        if self.checkStaticIPInputValid() and self.checkDnsInputValid():
            return True
        return False

    def checkStaticIPInputValid(self):
        """检查静态IP输入内容的有效性"""
        ip = self.ip.text().trimmed()
        netmask = self.netmast.text().trimmed()
        gateway = self.defaultGateway.text().trimmed()

        if not self.autoGetIpCheckbox.isChecked():
            if ip.isEmpty() or ip.isNull() or netmask.isEmpty() or netmask.isNull():
                InfoHintDialog(u'IP地址或子网掩码不能为空').exec_()
                return False

            pattern = '^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$'
            matchObj = re.match(pattern, ip)
            if matchObj is None:
                InfoHintDialog(u'IP地址格式有误,请重新填入').exec_()
                self.ip.setFocus()
                return False

            matchObj = re.match(pattern, str(netmask))
            if matchObj is None:
                InfoHintDialog(u'子网掩码地址格式有误,请重新填入').exec_()
                self.netmast.setFocus()
                return False

            if gateway:
                matchObj = re.match(pattern, str(gateway))
                if matchObj is None:
                    InfoHintDialog(u'网关地址格式有误,请重新填入').exec_()
                    self.netmast.setFocus()
                    return False

        return True

    def checkDnsInputValid(self):
        """检查DNS输入的内容的有效性"""
        if not self.autoGetDNSCheckBox.isChecked():
            dns = self.dns.text().trimmed()
            backupDns = self.backupDns.text().trimmed()
            if dns.isEmpty() or dns.isNull():
                InfoHintDialog(u'DNS不能为空').exec_()
                return False

            pattern = '^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$'
            matchObj = re.match(pattern, str(dns))
            if matchObj is None:
                InfoHintDialog(u'DNS地址格式有误,请重新填入').exec_()
                self.dns.setFocus()
                return False

            if backupDns:
                matchObj = re.match(pattern, str(backupDns))
                if matchObj is None:
                    InfoHintDialog(u'备用DNS地址格式有误,请重新填入').exec_()
                    self.backupDns.setFocus()
                    return False
            return True
        else:
            return True

    def slotSettingDNSType(self, status):
        if status == Qt.Checked:
            self.dnsServerAddressGroupbox.setChecked(False)
        elif status == Qt.Unchecked:
            self.dnsServerAddressGroupbox.setChecked(True)

    def slotSettingCustomDNSType(self, status):
        if status:
            self.autoGetDNSCheckBox.setChecked(False)
        else:
            self.autoGetDNSCheckBox.setChecked(True)

    def slotSettingDHCPType(self, status):
        if status == Qt.Checked:
            self.staticIpGroupbox.setChecked(False)
            self.dnsServerAddressGroupbox.setChecked(False)
            self.autoGetDNSCheckBox.setChecked(True)
            self.autoGetDNSCheckBox.setEnabled(False)
            self.dnsServerAddressGroupbox.setEnabled(False)
        elif status == Qt.Unchecked:
            self.staticIpGroupbox.setChecked(True)
            self.dnsServerAddressGroupbox.setChecked(True)
            self.autoGetDNSCheckBox.setEnabled(True)
            self.autoGetDNSCheckBox.setChecked(False)
            self.dnsServerAddressGroupbox.setEnabled(True)



    def slotSettingStaticType(self, status):
        if status:
            self.autoGetIpCheckbox.setChecked(False)
            self.dnsServerAddressGroupbox.setChecked(True)
            self.autoGetDNSCheckBox.setEnabled(True)
            self.autoGetDNSCheckBox.setChecked(False)
            self.dnsServerAddressGroupbox.setEnabled(True)
        else:
            self.autoGetIpCheckbox.setChecked(True)
            self.dnsServerAddressGroupbox.setChecked(False)
            self.autoGetDNSCheckBox.setEnabled(False)
            self.autoGetDNSCheckBox.setChecked(True)
            self.dnsServerAddressGroupbox.setEnabled(False)
 

    def setDynamicNetwork(self):
        """设置动态网络的信息到配置文件"""
        netconf="conf=0&ip=&mask=&gateway="
        #如果是指定DNS地址
        if self.dnsServerAddressGroupbox.isChecked():
            dns = str(self.dns.text().trimmed())
            backupDns = str(self.backupDns.text().trimmed())
            if not backupDns:
                netconf = netconf + "&dns1=" + dns 
            else:
                netconf = netconf + "&dns1=" + dns + "&dns2=" + backupDns 
            StoreInfoParser.instance().setDNSStatus("static")
        else:
            netconf = netconf + "&dns1=&dns2=" 
            StoreInfoParser.instance().setDNSStatus("dhcp")
        return netconf 
    def setStaticNetwork(self):
        """设置静态网络的信息到配置文件"""

        IPADDR = str(self.ip.text().trimmed())
        NETMASK = str(self.netmast.text().trimmed())
        GATEWAY = str(self.defaultGateway.text().trimmed())
        content = None
        if not GATEWAY:
            content = "conf=1&ip=%s&mask=%s&gateway=" % (IPADDR, NETMASK)
        else:
            content = "conf=1&ip=%s&mask=%s&gateway=%s" % (IPADDR, NETMASK, GATEWAY)

        #如果是指定DNS地址
        if self.dnsServerAddressGroupbox.isChecked():
            dns = str(self.dns.text().trimmed())
            backupDns = str(self.backupDns.text().trimmed())
            if not backupDns:
                content = content + "&dns1=" + dns 
            else:
                content = content + "&dns1=" + dns + "&dns2=" + backupDns 
            StoreInfoParser.instance().setDNSStatus("static")
        else:
            content = content + "&dns1=&dns2="
            StoreInfoParser.instance().setDNSStatus("dhcp")
        return content 
Example #12
0
class EthernetEditor(QFrame):
    def __init__(self, ethernet, parent=None):
        QFrame.__init__(self, parent)

        self.ethernet = ethernet

        self.buildGUI()
        self.fillValues()

    def buildGUI(self):
        #general setup
        form = QFormLayout(self)

        self.label = OptionnalLine(hint="Optional interface name")
        form.addRow(self.tr("Interface name"), self.label)

        self.speed_group = QButtonGroup()
        self.speed_box = QGroupBox(tr("Force an ethernet speed"))
        speed_layout = QVBoxLayout(self.speed_box)

        self.speed_GFull = QRadioButton(tr("Gigabit full duplex"))
        self.speed_GHalf = QRadioButton(tr("Gigabit half duplex"))
        self.speed_100Full = QRadioButton(tr("100 Mb Full duplex"))
        self.speed_100Half = QRadioButton(tr("100 Mb Half duplex"))
        self.speed_10Full = QRadioButton(tr("10 Mb Full duplex"))
        self.speed_10Half = QRadioButton(tr("10 Mb Half duplex"))

        def toggle(value):
            if value:
                self.speed_GFull.click()

        self.speed_box.setCheckable(True)
        self.speed_box.setChecked(Qt.Unchecked)
        self.connect(self.speed_box, SIGNAL('toggled(bool)'), toggle)

        for item in (
            self.speed_GFull,
            self.speed_GHalf,
            self.speed_100Full,
            self.speed_100Half,
            self.speed_10Full,
            self.speed_10Half,
            ):
            self.speed_group.addButton(item)
            speed_layout.addWidget(item)

        form.addRow(self.speed_box)

    def fillValues(self):
        name = self.ethernet.user_label
        if name != "":
            self.label.setText(name)
            self.label.checkEmpty()
            self.label.setStyleSheet('')

        if self.ethernet.eth_auto:
            self.speed_box.setChecked(Qt.Unchecked)
            return

        self.speed_box.setChecked(Qt.Checked)
        if self.ethernet.eth_duplex == Ethernet.FULL:
            if self.ethernet.eth_speed == 10:
                button = self.speed_10Full
            elif self.ethernet.eth_speed == 100:
                button = self.speed_100Full
            else:
                button = self.speed_GFull
        else:
            if self.ethernet.eth_speed == 10:
                button = self.speed_10Half
            elif self.ethernet.eth_speed == 100:
                button = self.speed_100Half
            else:
                button = self.speed_GHalf


        button.setChecked(Qt.Checked)

    def getConfig(self):
        auto = not self.speed_box.isChecked()
        if auto:
            return True, None, None
        selection = self.speed_group.checkedButton()
        if selection is self.speed_GFull:
            return False, 1000, Ethernet.FULL
        elif self.speed_GHalf:
            return False, 1000, Ethernet.HALF
        elif self.speed_100Full:
            return False, 100, Ethernet.FULL
        elif self.speed_100Half:
            return False, 100, Ethernet.HALF
        elif self.speed_10Full:
            return False, 10, Ethernet.FULL
        elif self.speed_10Half:
            return False, 10, Ethernet.HALF

        assert False, "this selection is unknown"

    def setName(self):
        new_name = self.label.value()
        if new_name != self.ethernet.user_label:
            self.ethernet.user_label = new_name
            #message = tr("renamed ethernet interface to: %s'") % new_name
        return True

    def accept(self, *args, **kwargs):
        ok = True
        ok &= self.setName()
        self.ethernet.setEthernetMode(*self.getConfig())
        if ok:
            self.emit(SIGNAL('edited'), "edited ethernet interface '%s'" \
            % self.ethernet.fullName())
        return ok
class NetWorkSettingWidget(QWidget):
        
    def __init__(self, app, parent = None):
        super(NetWorkSettingWidget,self).__init__(parent)
        self.setStyleSheet("font-size : 16px;")
        self.app = app

        self.setNetworkCardFilePath()
        
        self.initLayout()
        
        self.initCheckBoxStatus()
        
        self.restartNetworkTD = RestartNetworkThread()
        self.waitingDlg = InfoHintDialog(None)
        
        #绑定信号
        self.connect(self.autoGetIpCheckbox, SIGNAL("stateChanged(int)"),self.slotSettingDHCPType)
        
        self.connect(self.staticIpGroupbox, SIGNAL("clicked(bool)"),self.slotSettingStaticType)
        
        self.connect(self.autoGetDNSCheckBox, SIGNAL("stateChanged(int)"),self.slotSettingDNSType)
        
        self.connect(self.dnsServerAddressGroupbox, SIGNAL("clicked(bool)"),self.slotSettingCustomDNSType)
        
        self.connect(self.saveBtn, SIGNAL("clicked()"),self.slotSave)
        
        self.connect(self.restartNetworkTD, SIGNAL("restartNetwork"),self.slotShowRestartNetworkInfo)

    def setNetworkCardFilePath(self):
        #self.networkconfigFile = common.NETWORK_CONFIG_CENTOS_7_0 + "br0"
        #self.bridgeNetworkconfigFile = common.NETWORK_CONFIG_CENTOS_7_0 + "br0"
        ethName = common.DEFAULT_NETCARD_NAME
        ethNameList = globalfunc.getEthNameList()
        if not ethNameList:
            LogRecord.instance().logger.info(u"获取网卡名称失败!")
        else:
            ethName = ethNameList[0]

        self.originalNetConfigFile = common.NETWORK_CONFIG_CENTOS_7_0 + ethName
        LogRecord.instance().logger.info(u"获取网卡名称:%s" % self.originalNetConfigFile)
        
        self.originalBridgerNetConfigFile = common.BRIDGER_NETWORK_CONFIG_CENTOS_7_0
        LogRecord.instance().logger.info(u"获取bridge网卡名称:%s" % self.originalNetConfigFile)

        self.networkconfigFile = self.originalNetConfigFile
        self.bridgeNetworkconfigFile = self.originalBridgerNetConfigFile
        if globalvariable.PROGRAM_RUNNING_TYPE == common.OPERATION_ENV_TYPE:#running env
            self.networkconfigFile = globalfunc.convertPathToConfigPath(self.originalNetConfigFile)
            self.bridgeNetworkconfigFile = globalfunc.convertPathToConfigPath(self.originalBridgerNetConfigFile)

        
        #self.networkconfigFile = common.NETWORK_CONFIG_CENTOS_7_0 + "br0"

    def initLayout(self):
        #IP设置
        self.autoGetIpCheckbox = QCheckBox(self.tr("Auto get IP"))
        
        self.staticIpGroupbox = QGroupBox(self.tr("Use this IP"))
        self.staticIpGroupbox.setCheckable(True)
        
        self.ipLabel = QLabel(self.tr("IP address"))
        self.netmastLabel = QLabel(self.tr("Net mask"))
        self.defaultGatewayLabel = QLabel(self.tr("Default gateway"))
        
        topSpaceWidget = QLabel()
        topSpaceWidget.setFixedHeight(1)
        
        self.ip = QLineEdit()
        self.ip.setContextMenuPolicy(Qt.NoContextMenu)
        self.ip.setFixedSize(400, 30)
        self.netmast = QLineEdit()
        self.netmast.setContextMenuPolicy(Qt.NoContextMenu)
        self.defaultGateway = QLineEdit()
        self.defaultGateway.setContextMenuPolicy(Qt.NoContextMenu)
        
        topGridLayout = QGridLayout()
        topGridLayout.setSpacing(15)
        topGridLayout.setMargin(20)
        topGridLayout.addWidget(self.ipLabel, 0, 0, 1, 1)
        topGridLayout.addWidget(self.ip, 0, 1, 1, 1)
        topGridLayout.addWidget(self.netmastLabel, 1, 0, 1, 1)
        topGridLayout.addWidget(self.netmast, 1, 1, 1, 1)
        topGridLayout.addWidget(self.defaultGatewayLabel, 2, 0, 1, 1)
        topGridLayout.addWidget(self.defaultGateway, 2, 1, 1, 1)
        topGridLayout.addWidget(topSpaceWidget, 3, 0, 1, 1)
        
        self.staticIpGroupbox.setLayout(topGridLayout)
        
        #DNS设置
        self.autoGetDNSCheckBox = QCheckBox(self.tr("Auto Get DNS"))
        
        self.dnsServerAddressGroupbox = QGroupBox(self.tr("Use This DNS"))
        self.dnsServerAddressGroupbox.setCheckable(True)
        
        self.dnsLabel = QLabel(self.tr("DNS"))
        self.backupDnsLabel = QLabel(self.tr("Backup DNS"))
        
        bottomSpaceWidget = QLabel()
        bottomSpaceWidget.setFixedHeight(1)
        
        self.dns = QLineEdit()
        self.dns.setContextMenuPolicy(Qt.NoContextMenu)
        self.backupDns = QLineEdit()
        self.backupDns.setContextMenuPolicy(Qt.NoContextMenu)
        
        self.saveBtn = QPushButton(self.tr("Save"))
        self.saveBtn.setStyleSheet("background: rgb(7,87,198); color: white; width: 90px; height: 30px;font-size : 16px;")
        
        bottomGridLayout = QGridLayout()
        bottomGridLayout.setSpacing(15)
        bottomGridLayout.setMargin(20)
        bottomGridLayout.addWidget(self.dnsLabel, 0, 0, 1, 1)
        bottomGridLayout.addWidget(self.dns, 0, 1, 1, 1)
        bottomGridLayout.addWidget(self.backupDnsLabel, 1, 0, 1, 1)
        bottomGridLayout.addWidget(self.backupDns, 1, 1, 1, 1)
        bottomGridLayout.addWidget(bottomSpaceWidget, 2, 0, 1, 1)
        
        self.dnsServerAddressGroupbox.setLayout(bottomGridLayout)
        
        #布局调整
        vLayout = QVBoxLayout()
        vLayout.setSpacing(10)
        vLayout.setMargin(10)
        
        vLayout.addWidget(self.autoGetIpCheckbox)
        vLayout.addWidget(self.staticIpGroupbox)
        vLayout.addSpacing(15)
        vLayout.addWidget(self.autoGetDNSCheckBox)
        vLayout.addWidget(self.dnsServerAddressGroupbox)
        vLayout.addStretch()
        
        topMainLayout = QHBoxLayout()
        topMainLayout.addStretch()
        topMainLayout.addSpacing(50)
        topMainLayout.addLayout(vLayout)
        topMainLayout.addStretch(2)
        
        bottomHLayout = QHBoxLayout()
        bottomHLayout.addStretch()
        bottomHLayout.addWidget(self.saveBtn)
        bottomHLayout.addStretch()
        
        mainVLayout = QVBoxLayout()
        mainVLayout.addLayout(topMainLayout)
        mainVLayout.addSpacing(10)
        mainVLayout.addLayout(bottomHLayout)
        
        self.setLayout(mainVLayout)
    
    def updateWindow(self):
        self.autoGetDNSCheckBox.setText(self.tr("Auto Get DNS"))
        self.autoGetIpCheckbox.setText(self.tr("Auto get IP"))
        self.dnsServerAddressGroupbox.setTitle(self.tr("Use This DNS"))
        self.staticIpGroupbox.setTitle(self.tr("Use this IP"))
        self.ipLabel.setText(self.tr("IP address"))
        self.netmastLabel.setText(self.tr("Net mask"))
        self.defaultGatewayLabel.setText(self.tr("Gate way"))
        self.dnsLabel.setText(self.tr("DNS"))
        self.backupDnsLabel.setText(self.tr("Backup DNS"))
        self.saveBtn.setText(self.tr("Save"))
        
    def slotShowRestartNetworkInfo(self, status):
        
        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
        else:
            QmName = "en_US.qm"
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
        """显示重启网络的状态信息"""
        
        if status == "Start":
            self.waitingDlg.setHintInfo(self.tr("network is restarting, waiting..."))
        elif status == "Success":
            self.waitingDlg.setHintInfo(self.tr("network start success!"))
            vmtype = StoreInfoParser.instance().getVmType()
            if vmtype == "offline":
                pass 
        elif status == "Failed":
            self.waitingDlg.setHintInfo(self.tr("network restart failed!"))
        else:
            return
        
        if self.waitingDlg.isHidden():
            self.waitingDlg.exec_()
        
    def slotSave(self):
        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
        else:
            QmName = "en_US.qm"
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
            
        if not self.checkInputValid():
            return

        if globalvariable.PROGRAM_RUNNING_TYPE == common.OPERATION_ENV_TYPE:#running
            if not os.path.exists(self.networkconfigFile):
                os.system("mkdir -p %s" % os.path.dirname(self.networkconfigFile))#create dir
                os.mknod(self.networkconfigFile)#create empty file
                os.system("echo \"%s\" >> /config/files" % self.originalNetConfigFile)#mark
                
            if not os.path.exists(self.bridgeNetworkconfigFile):
                os.system("mkdir -p %s" % os.path.dirname(self.bridgeNetworkconfigFile))#create dir
                os.mknod(self.bridgeNetworkconfigFile)#create empty file
                os.system("echo \"%s\" >> /config/files" % self.originalBridgerNetConfigFile)#mark


            if not os.path.isfile(self.originalNetConfigFile):
                os.system("mkdir -p %s" % os.path.dirname(self.originalNetConfigFile))
                os.mknod(self.originalNetConfigFile)
                
            if not os.path.isfile(self.originalBridgerNetConfigFile):
                os.system("mkdir -p %s" % os.path.dirname(self.originalBridgerNetConfigFile))
                os.mknod(self.originalBridgerNetConfigFile)
        else:
            if not os.path.exists(self.networkconfigFile):
                os.system("mkdir -p %s" % os.path.dirname(self.networkconfigFile))#create dir
                os.mknod(self.networkconfigFile)#create empty file
                #os.system("echo \"%s\" >> /config/files" % self.originalNetConfigFile)#mark
                
            if not os.path.exists(self.bridgeNetworkconfigFile):
                #os.system("mkdir -p %s" % os.path.dirname(self.networkconfigFile))#create dir
                os.mknod(self.bridgeNetworkconfigFile)#create empty file
                #os.system("echo \"%s\" >> /config/files" % self.originalNetConfigFile)#mark


            if not os.path.isfile(self.originalNetConfigFile):
                os.system("mkdir -p %s" % os.path.dirname(self.originalNetConfigFile))
                os.mknod(self.originalNetConfigFile)
                
            if not os.path.isfile(self.originalBridgerNetConfigFile):
                os.system("mkdir -p %s" % os.path.dirname(self.originalBridgerNetConfigFile))
                os.mknod(self.originalBridgerNetConfigFile)
                

        if globalvariable.PROGRAM_RUNNING_TYPE == common.OPERATION_ENV_TYPE:#running
            globalfunc.umountFile(self.originalNetConfigFile)
            globalfunc.umountFile(self.originalBridgerNetConfigFile)


        if self.autoGetIpCheckbox.isChecked():
            if not self.setDynamicNetwork():
                if globalvariable.PROGRAM_RUNNING_TYPE == common.OPERATION_ENV_TYPE:
                    globalfunc.mountFile(self.originalNetConfigFile)
                    globalfunc.mountFile(self.originalBridgerNetConfigFile)
                return
        elif self.staticIpGroupbox.isChecked():
            if not self.setStaticNetwork():
                if globalvariable.PROGRAM_RUNNING_TYPE == common.OPERATION_ENV_TYPE:
                    globalfunc.mountFile(self.originalNetConfigFile)
                    globalfunc.mountFile(self.originalBridgerNetConfigFile)
                return


        if globalvariable.PROGRAM_RUNNING_TYPE == common.OPERATION_ENV_TYPE:
            globalfunc.mountFile(self.originalNetConfigFile)
            globalfunc.mountFile(self.originalBridgerNetConfigFile)

        #重新启动网络
        self.restartNetworkTD.start()
        
        return
            
    def initCheckBoxStatus(self):
        """读取网络配置文件,初始化相应的checkbox的状态"""
        [netType, DNSType] = self.getNetworkType()
        if netType == "dhcp":
            self.autoGetIpCheckbox.setChecked(True)
            self.staticIpGroupbox.setChecked(False)
        else:
            self.autoGetIpCheckbox.setChecked(False)
            self.staticIpGroupbox.setChecked(True)
            [ip, netmask, gateway] = self.getStaticNetworkInfo()
            if ip:
                self.ip.setText(ip)
                
            if netmask:
                self.netmast.setText(netmask)
                
            if gateway:
                self.defaultGateway.setText(gateway)
                
            
        if DNSType == "AUTODNS":
            self.autoGetDNSCheckBox.setChecked(True)
            self.dnsServerAddressGroupbox.setChecked(False)
        else:
            self.autoGetDNSCheckBox.setChecked(False)
            self.dnsServerAddressGroupbox.setChecked(True)
            [DNS_first, DNS_second] = self.getCustomDNSInfo()
            if DNS_first:
                self.dns.setText(DNS_first)
            
            if DNS_second:
                self.backupDns.setText(DNS_second)
            
            
    def getCustomDNSInfo(self):
        """得到自定义DNS的内容"""
        DNS_first = None
        DNS_second = None
        statusOutput = commands.getstatusoutput("cat %s" % self.bridgeNetworkconfigFile)
        if statusOutput[0] == 0:
            outputList = QString(statusOutput[1]).split("\n")
            for value in outputList:
                if value.split("=")[0] == "DNS1":
                    DNS_first = value.split("=")[1]
                elif value.split("=")[0] == "DNS2":
                    DNS_second = value.split("=")[1]
                    
        return [DNS_first, DNS_second]
        
            
    def getStaticNetworkInfo(self):
        """得到静态网络的信息"""
        ip = netmask = gateway = None
        statusOutput = commands.getstatusoutput("cat %s" % self.bridgeNetworkconfigFile)
        if statusOutput[0] == 0:
            outputList = QString(statusOutput[1]).split("\n")
            for value in outputList:
                if value.split("=")[0] == "IPADDR":
                    ip = value.split("=")[1]
                elif value.split("=")[0] == "NETMASK":
                    netmask = value.split("=")[1]
                elif value.split("=")[0] == "GATEWAY":
                    gateway = value.split("=")[1]
            
        return [ip, netmask, gateway]
            
    def getNetworkType(self):
        """得到网络是静态还是动态类型"""
        netType = None
        DNSType = None
        statusOutput = commands.getstatusoutput("cat %s" % self.bridgeNetworkconfigFile)
        if statusOutput[0] == 0:
            output = QString(statusOutput[1])
            if output.contains("dhcp"):
                netType = "dhcp"
            else:
                netType = "static"
                
            if output.contains("DNS"):
                DNSType = "customDNS"
            else:
                DNSType = "AUTODNS"
                
        return [netType, DNSType]
            
    def checkInputValid(self):
        """检测输入的有效性"""
        if self.checkStaticIPInputValid() and self.checkDnsInputValid():
            return True
        return False
    
    def checkStaticIPInputValid(self):
        """检查静态IP输入内容的有效性"""
        ip = self.ip.text().trimmed()
        netmask = self.netmast.text().trimmed()
        gateway = self.defaultGateway.text().trimmed()
        
        if not self.autoGetIpCheckbox.isChecked():
            if ip.isEmpty() or ip.isNull() or netmask.isEmpty() or netmask.isNull():
                InfoHintDialog(self.tr("IP address or net mask is empty")).exec_()
                return False
            
            pattern = '^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$'
            matchObj = re.match(pattern, ip)
            if matchObj is None:
                InfoHintDialog(self.tr("IP address is wrong, please input again")).exec_()
                self.ip.setFocus()
                return False
            
            matchObj = re.match(pattern, str(netmask))
            if matchObj is None:
                InfoHintDialog(self.tr("Net mask is wrong")).exec_()
                self.netmast.setFocus()
                return False
            
            if gateway:
                matchObj = re.match(pattern, str(gateway))
                if matchObj is None:
                    InfoHintDialog(self.tr("Gate way is wrong")).exec_()
                    self.netmast.setFocus()
                    return False
        
        return True
    
    def checkDnsInputValid(self):
        """检查DNS输入的内容的有效性"""
        if not self.autoGetDNSCheckBox.isChecked():
            dns = self.dns.text().trimmed()
            backupDns = self.backupDns.text().trimmed()
            if dns.isEmpty() or dns.isNull():
                InfoHintDialog(self.tr("DNS is empty")).exec_()
                return False
            
            pattern = '^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$'
            matchObj = re.match(pattern, str(dns))
            if matchObj is None:
                InfoHintDialog(self.tr("DNS is wrong, please input again")).exec_()
                self.dns.setFocus()
                return False
            
            if backupDns:
                matchObj = re.match(pattern, str(backupDns))
                if matchObj is None:
                    InfoHintDialog(self.tr("Backup DNS is wrong, please input again")).exec_()
                    self.backupDns.setFocus()
                    return False
            return True
        else:
            return True
        
    def slotSettingDNSType(self, status):
        if status == Qt.Checked:
            self.dnsServerAddressGroupbox.setChecked(False)
        elif status == Qt.Unchecked:
            self.dnsServerAddressGroupbox.setChecked(True)
            
    def slotSettingCustomDNSType(self, status):
        if status:
            self.autoGetDNSCheckBox.setChecked(False)
        else:
            self.autoGetDNSCheckBox.setChecked(True)
        
    def slotSettingDHCPType(self, status):
        if status == Qt.Checked:
            self.staticIpGroupbox.setChecked(False)
        elif status == Qt.Unchecked:
            self.staticIpGroupbox.setChecked(True)
            
            
    def slotSettingStaticType(self, status):
        if status:
            self.autoGetIpCheckbox.setChecked(False)
        else:
            self.autoGetIpCheckbox.setChecked(True)
        
    def setDynamicNetwork(self):
        """设置动态网络的信息到配置文件"""
        # delCmd = "sed -i '/BOOTPROTO/,$'d %s" % self.networkconfigFile
        delCmd = "echo '' > %s" % self.networkconfigFile
        delBrCmd = "echo '' > %s" % self.bridgeNetworkconfigFile
        delOk = os.system(delCmd)
        delOkB = os.system(delBrCmd)
        #return
        deviceName = self.networkconfigFile.split("/")[-1].split("-")[-1]
        macValue = globalfunc.getMacByEthName(deviceName)
        content = None

        #eth0
        
        contenteth = "BOOTPROTO=none\\nDEVICE=%s\\nHWADDR=%s\\nNM_CONTROLLED=no\\nONBOOT=yes\\nBRIDGE=br0" % (deviceName, macValue)
            
            
        #如果是指定DNS地址
        if self.dnsServerAddressGroupbox.isChecked():
            dns = str(self.dns.text().trimmed())
            backupDns = str(self.backupDns.text().trimmed())
         
            if not backupDns:
                content = "BOOTPROTO=dhcp\\nDEVICE=br0\\nNM_CONTROLLED=no\\nONBOOT=yes\\nTYPE=Bridge\\nPEERNTP=yes\\ncheck_link_down(){\\n    return 1; \\n}\\nDNS1=%s" % (dns)
                                   
            else:
                content = "BOOTPROTO=dhcp\\nDEVICE=br0\\NM_CONTROLLED=no\\nONBOOT=yes\\nTYPE=Bridge\\nPEERNTP=yes\\ncheck_link_down(){\\n    return 1; \\n}\\nDNS1=%s\\nDNS2=%s" % (dns,backupDns) 
                                    
        else:
            content = "BOOTPROTO=dhcp\\nDEVICE=br0\\nNM_CONTROLLED=no\\nONBOOT=yes\\nTYPE=Bridge\\nPEERNTP=yes\\ncheck_link_down(){\\n    return 1; \\n}" 
                                    
        
        addEthCmd = "sed -i '$ a\\%s' %s" % (contenteth, self.networkconfigFile)
        addCmd = "sed -i '$ a\\%s' %s" % (content, self.bridgeNetworkconfigFile)
        
        
        # addCmd = "echo %s > %s" % (content, self.networkconfigFile)
        addOk = os.system(addCmd)
        addE = os.system(addEthCmd)
        if delOk != 0 or addOk != 0 or delOkB != 0 or addE != 0:
            InfoHintDialog(self.tr("Auto get IP failed")).exec_()
            return False
        
        return True
            
    def setStaticNetwork(self):
        """设置静态网络的信息到配置文件"""
        # delCmd = "sed -i '/BOOTPROTO/,$'d %s" % self.networkconfigFile
        delCmd = "echo \"\" > %s" % self.networkconfigFile
        delOk = os.system(delCmd)
        
        delCmdBr = "echo \"\" > %s" % self.bridgeNetworkconfigFile
        delOkBr = os.system(delCmdBr)
        
        IPADDR = str(self.ip.text().trimmed())
        NETMASK = str(self.netmast.text().trimmed())
        GATEWAY = str(self.defaultGateway.text().trimmed())
        
        deviceName = self.networkconfigFile.split("/")[-1].split("-")[-1]
        macValue = globalfunc.getMacByEthName(deviceName)
        
        #eth0
        contenteth = "BOOTPROTO=none\\nDEVICE=%s\\nHWADDR=%s\\nNM_CONTROLLED=no\\nONBOOT=yes\\nBRIDGE=br0" % (deviceName, macValue)
        content = None
        
        if not GATEWAY:
            content = "BOOTPROTO=static\\nDEVICE=br0\\nTYPE=Bridge\\nNM_CONTROLLED=no\\nIPADDR=%s\\nNETMASK=%s" % (IPADDR, NETMASK)
        else:
            content = "BOOTPROTO=static\\nDEVICE=br0\\nTYPE=Bridge\\nNM_CONTROLLED=no\\nIPADDR=%s\\nNETMASK=%s\\nGATEWAY=%s" % (IPADDR, NETMASK, GATEWAY)

        #如果是指定DNS地址
        if self.dnsServerAddressGroupbox.isChecked():
            dns = str(self.dns.text().trimmed())
            backupDns = str(self.backupDns.text().trimmed())
         
            if not backupDns:
                content = "%s\\nDNS1=%s" % (content, dns)
            else:
                content = "%s\\nDNS1=%s\\nDNS2=%s" % (content, dns, backupDns)
        
        addCmdEth = "sed -i '$ a\\%s' %s" % (contenteth, self.networkconfigFile)
        addCmdBr = "sed -i '$ a\\%s' %s" % (content, self.bridgeNetworkconfigFile)
        # addCmd = "echo %s > %s" % (content, self.networkconfigFile)
        addOk = os.system(addCmdEth)
        addOkBr = os.system(addCmdBr)
        if delOk != 0 and addOk != 0 and delOkBr != 0 and addOkBr != 0:
            InfoHintDialog(self.tr("Setting static IP failed")).exec_()
            return False
        
        return True
Example #14
0
 def buildUp(self):
     for sect in list(self.backend.shared.settings.keys()):
         scroll = QScrollArea(self.tabWidget)
         widget = QWidget(self.tabWidget)
         layout = QVBoxLayout(widget)
         for key, value in list(self.backend.shared.settings[sect].items()):
             if not type(key) is str:
                 continue
             groupbox = QGroupBox(widget)
             loadUi('GUI' + sep + 'settings_element.ui', groupbox)
             if type(value) is str:
                 groupbox.comboBox.lineEdit().setText(value)
                 if key.endswith('directory'):
                     groupbox.toolButton.clicked.connect(
                         lambda y, x=groupbox.comboBox.lineEdit(): x.setText(
                             QFileDialog.getExistingDirectory(
                                 self,
                                 self.tr('Select path'),
                                 options=QFileDialog.DontUseNativeDialog |
                                 QFileDialog.ShowDirsOnly
                                 )
                             )
                         )
                 elif key.endswith('file'):
                     groupbox.toolButton.clicked.connect(
                         lambda y, x=groupbox.comboBox.lineEdit(): x.setText(
                             QFileDialog.getOpenFileName(
                                 self,
                                 self.tr('Select file'),
                                 filter=self.tr('All files(*)'),
                                 options=QFileDialog.DontUseNativeDialog
                                 )
                             )
                         )
                 else:
                     groupbox.toolButton.setShown(False)
                 self.saveButton.clicked.connect(
                     lambda x, y=key, z=groupbox.comboBox, s=sect:
                         self.backend.shared.settings[s].update({y:
                         z.lineEdit().text()}
                         )
                     )
             elif type(value) is int:
                 groupbox.toolButton.setShown(False)
                 groupbox.comboBox.lineEdit().setValidator(
                     QIntValidator(groupbox))
                 groupbox.comboBox.lineEdit().setText(str(value))
                 self.saveButton.clicked.connect(
                     lambda x, y=key, z=groupbox.comboBox.lineEdit(), s=sect:
                         self.backend.shared.settings[s].update(
                             {y: int(z.text())}
                         )
                     )
             elif type(value) is bool:
                 groupbox.comboBox.setShown(False)
                 groupbox.toolButton.setShown(False)
                 groupbox.setCheckable(True)
                 groupbox.setChecked(value)
                 self.saveButton.clicked.connect(
                     lambda x, y=key, z=groupbox.isChecked, s=sect:
                         self.backend.shared.settings[s].update({y:
                         z()}
                         )
                     )
             elif type(value) is list:
                 groupbox.toolButton.setShown(False)
                 for item in self.backend.shared.settings[sect][tuple(key)]:
                     groupbox.comboBox.addItem(str(item))
                 groupbox.comboBox.lineEdit().setText(value[0])
                 self.saveButton.clicked.connect(
                     lambda x, y=key, z=groupbox.comboBox, s=sect:
                         self.backend.shared.settings[s].update({y:
                         [z.lineEdit().text()]}
                         )
                     )
             else:
                 groupbox.toolButton.setShown(False)
                 groupbox.lineEdit.setText(self.tr('Incorrect value'))
                 groupbox.lineEdit.Enable(False)
             groupbox.setTitle(self.tr(key))
             layout.addWidget(groupbox)
         if sect == 'Main':
             self.tabWidget.insertTab(0, scroll, self.tr(sect))
         else:
             self.tabWidget.addTab(scroll, self.tr(sect))
         scroll.setWidget(widget)
     self.tabWidget.setCurrentIndex(0)
     self.saveButton.clicked.connect(
                     lambda: self.backend.shared.save() or
                     self.backend.shared.load()
                     )