Exemplo n.º 1
0
class Widget(QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        buttonHelp1 = QPushButton('help')
        buttonHelp1.setEnabled(False)
        buttonHelp1.setToolTip('The table below, with the exception of the last row and column, describe the network\n' +
                               'in terms of the weight coefficient values. The value of a cell in the n-th row and m-th\n' +
                               'column is the weight of the n-th feature for the m-th animal class.\n\n' +
                               'As you can see, each animal class has its own neuron that recognizes it, and each of\n' +
                               'these neurons has inputs that receive individual feature values.\n\n' +
                               'The last column represents the input vector, and the last row contains the network\n' +
                               'output values.')
        buttonHelp2 = QPushButton('help')
        buttonHelp2.setEnabled(False)
        buttonHelp2.setToolTip('If you show the winner, you will see the neuron whose response was the strongest.\n' +
                               'This neuron indicates the animal class the examined object will most probably fall into.\n' +
                               'The table below, with the exception of the last row and column, describe the network\n' +
                               'in terms of the weight coefficient values. The value of a cell in the n-th row and m-th\n' +
                               'column is the weight of the n-th feature for the m-th animal class.\n\n' +
                               'As you can see, each animal class has its own neuron that recognizes it, and each of\n' +
                               'these neurons has inputs that receive individual feature values.\n\n' +
                               'The last column represents the input vector, and the last row contains the network\n' +
                               'output values.')

        hBoxLayout1 = QHBoxLayout()
        hBoxLayout1.addWidget(QLabel('The neural network in this example uses five features to recognize\n' +
                                     'three classes of animals. Its weight coefficients are predefined and shown in the table below.\n\n' +
                                     'To test the network behavior, enter the input signals in the rightmost column and read the output\n' +
                                     'values from the bottom row.'))
        hBoxLayout1.addWidget(buttonHelp1)

        self.checkBoxWinner = QCheckBox()
        self.checkBoxWinner.setText('Show the winner')

        hBoxLayout2 = QHBoxLayout()
        hBoxLayout2.addWidget(self.checkBoxWinner)
        hBoxLayout2.addWidget(buttonHelp2)

        self.tableWidget = QTableWidget()
        self.labelNeuron = QLabel('(There is no winner.)')
        self.labelType = QLabel('This is something strange!')
        self.spinBoxThreshold = QDoubleSpinBox()
        self.spinBoxThreshold.setValue(5.0)

        self.groupBox = QGroupBox('Show the winner')
        gridLayout = QGridLayout()
        gridLayout.addWidget(QLabel('And the winner is...'), 0, 0)
        gridLayout.addWidget(self.labelNeuron, 0, 1)
        gridLayout.addWidget(QLabel('Because of this, the network claims:'), 1, 0)
        gridLayout.addWidget(self.labelType, 1, 1)
        gridLayout.addWidget(QLabel('Threshold:'), 2, 0)
        gridLayout.addWidget(self.spinBoxThreshold, 2, 1)
        self.groupBox.setLayout(gridLayout)
        self.groupBox.setVisible(False)

        vBoxLayout = QVBoxLayout()
        vBoxLayout.addLayout(hBoxLayout1)
        vBoxLayout.addWidget(self.tableWidget)
        vBoxLayout.addLayout(hBoxLayout2)
        vBoxLayout.addWidget(self.groupBox)

        self.setLayout(vBoxLayout)
        self.setWindowTitle('Simple linear neural network (example2)')

        self.classNames = ['mammal', 'bird', 'fish']

        self.tableWidget.setColumnCount(5)
        self.tableWidget.setRowCount(6)
        self.tableWidget.verticalHeader().hide()
        self.tableWidget.setHorizontalHeaderLabels(['Feature'] + self.classNames +  ['Input vector'])
        self.tableWidget.setCellWidget(0, 0, QLabel('number of legs'))
        self.tableWidget.setCellWidget(1, 0, QLabel('lives in water'))
        self.tableWidget.setCellWidget(2, 0, QLabel('can fly'))
        self.tableWidget.setCellWidget(3, 0, QLabel('has feathers'))
        self.tableWidget.setCellWidget(4, 0, QLabel('egg-laying'))
        self.tableWidget.setCellWidget(5, 0, QLabel('Output'))

        weights = [
            [   4,     0.01,   0.01,   -1,     -1.5 ],
            [   2,     -1,     2,      2.5,    2    ],
            [   -1,    3.5,    0.01,   -2,     1.5  ]
        ]

        for i in xrange(len(weights)):
            for j in xrange(len(weights[i])):
                self.tableWidget.setCellWidget(j, i + 1, QLabel('    ' + str(weights[i][j])))
        for i in xrange(len(weights)):
            self.tableWidget.setCellWidget(5, i + 1, QLabel(''))
        for i in xrange(len(weights[0])):
            doubleSpinBox = QDoubleSpinBox()
            doubleSpinBox.setValue(0.0)
            doubleSpinBox.setRange(-15.0, 15.0)
            self.tableWidget.setCellWidget(i, 4, doubleSpinBox)
        self.tableWidget.setCellWidget(5, 4, QPushButton('Calculate'))
        self.linearNetwork = LinearNetwork(initialWeights=weights)
        self.connect(self.checkBoxWinner, SIGNAL('stateChanged(int)'), self.visibleGrid)
        self.connect(self.tableWidget.cellWidget(5, 4), SIGNAL('clicked()'), self.updateResult)
        self.resize(600, 400)

    def visibleGrid(self, state):
        if state == 0:
            self.groupBox.setVisible(False)
        else:
            self.groupBox.setVisible(True)
            self.updateResult()

    def updateResult(self):
        inputColumn0 = self.tableWidget.cellWidget(0, 4).value()  # number of legs
        inputColumn1 = self.tableWidget.cellWidget(1, 4).value()  # lives in water
        inputColumn2 = self.tableWidget.cellWidget(2, 4).value()  # can fly
        inputColumn3 = self.tableWidget.cellWidget(3, 4).value()  # has feathers
        inputColumn4 = self.tableWidget.cellWidget(4, 4).value()  # egg-laying

        outputVector = self.linearNetwork.response([inputColumn0, inputColumn1, inputColumn2, inputColumn3, inputColumn4])

        if self.checkBoxWinner.checkState() == Qt.Checked:
            winner = LinearNetwork.winner(outputVector, self.spinBoxThreshold.value())
            for i in xrange(len(outputVector)):
                self.tableWidget.setCellWidget(5, i + 1, QLabel())
            if winner != -1:
                cellWinner = self.tableWidget.cellWidget(5, winner + 1)
                cellWinner.setStyleSheet('background-color: red;')

                self.labelNeuron.setText('Neuron ' + str(winner + 1))
                self.labelType.setText('This is a ' + self.classNames[winner])
            else:
                self.labelNeuron.setText('(There is no winner.)')
                self.labelType.setText('Thiss is something strange!')

        for i in xrange(len(outputVector)):
            self.tableWidget.cellWidget(5, i + 1).setText(str(outputVector[i]))
Exemplo n.º 2
0
class CalcDlg(QDialog):
    def __init__(self, parent, point3d, startBearing, flagStr):
        QDialog.__init__(self, parent)
        self.parent0 = parent
        self.point = point3d
        self.flagStr = flagStr
        self.calcedPoint = None
        self.startBearing = startBearing
        # self.flagStrName = flagStr
        #         self.resize(326, 310)
        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.setSpacing(6)
        self.verticalLayout.setMargin(3)
        self.verticalLayout.setObjectName(("verticalLayout"))
        self.groupBox = QGroupBox(self)
        self.groupBox.setTitle((""))
        self.groupBox.setObjectName(("groupBox"))
        self.verticalLayout_2 = QVBoxLayout(self.groupBox)
        self.verticalLayout_2.setSpacing(0)
        self.verticalLayout_2.setMargin(3)
        self.verticalLayout_2.setObjectName(("verticalLayout_2"))
        self.groupBox_5 = QGroupBox(self.groupBox)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.groupBox_5.sizePolicy().hasHeightForWidth())
        self.groupBox_5.setSizePolicy(sizePolicy)
        font = QFont()
        font.setFamily(("Arial"))
        self.groupBox_5.setFont(font)
        self.groupBox_5.setObjectName(("groupBox_5"))
        self.horizontalLayout_19 = QHBoxLayout(self.groupBox_5)
        self.horizontalLayout_19.setSpacing(0)
        self.horizontalLayout_19.setMargin(0)
        self.horizontalLayout_19.setObjectName(("horizontalLayout_19"))
        self.groupBox_5.setVisible(False)

        self.frame_18 = QFrame(self.groupBox_5)
        self.frame_18.setFrameShape(QFrame.StyledPanel)
        self.frame_18.setFrameShadow(QFrame.Raised)
        self.frame_18.setObjectName(("frame_18"))
        self.verticalLayout_13 = QVBoxLayout(self.frame_18)
        self.verticalLayout_13.setSpacing(0)
        self.verticalLayout_13.setContentsMargins(-1, -1, 0, -1)
        self.verticalLayout_13.setObjectName(("verticalLayout_13"))
        self.frame_19 = QFrame(self.frame_18)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frame_19.sizePolicy().hasHeightForWidth())
        self.frame_19.setSizePolicy(sizePolicy)
        self.frame_19.setFrameShape(QFrame.StyledPanel)
        self.frame_19.setFrameShadow(QFrame.Raised)
        self.frame_19.setObjectName(("frame_19"))
        self.horizontalLayout_20 = QHBoxLayout(self.frame_19)
        self.horizontalLayout_20.setSpacing(0)
        self.horizontalLayout_20.setMargin(0)
        self.horizontalLayout_20.setObjectName(("horizontalLayout_20"))
        self.label_9 = QLabel(self.frame_19)
        self.label_9.setMaximumSize(QSize(60, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.label_9.setFont(font)
        self.label_9.setObjectName(("label_9"))
        self.horizontalLayout_20.addWidget(self.label_9)
        self.txtTHR_X = QLineEdit(self.frame_19)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.txtTHR_X.sizePolicy().hasHeightForWidth())
        self.txtTHR_X.setSizePolicy(sizePolicy)
        self.txtTHR_X.setMaximumSize(QSize(16777215, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        self.txtTHR_X.setFont(font)
        self.txtTHR_X.setObjectName(("txtTHR_X"))
        self.horizontalLayout_20.addWidget(self.txtTHR_X)
        self.verticalLayout_13.addWidget(self.frame_19)
        self.frame_20 = QFrame(self.frame_18)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frame_20.sizePolicy().hasHeightForWidth())
        self.frame_20.setSizePolicy(sizePolicy)
        self.frame_20.setFrameShape(QFrame.StyledPanel)
        self.frame_20.setFrameShadow(QFrame.Raised)
        self.frame_20.setObjectName(("frame_20"))
        self.horizontalLayout_21 = QHBoxLayout(self.frame_20)
        self.horizontalLayout_21.setSpacing(0)
        self.horizontalLayout_21.setMargin(0)
        self.horizontalLayout_21.setObjectName(("horizontalLayout_21"))
        self.label_10 = QLabel(self.frame_20)
        self.label_10.setMaximumSize(QSize(60, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.label_10.setFont(font)
        self.label_10.setObjectName(("label_10"))
        self.horizontalLayout_21.addWidget(self.label_10)
        self.txtTHR_Y = QLineEdit(self.frame_20)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.txtTHR_Y.sizePolicy().hasHeightForWidth())
        self.txtTHR_Y.setSizePolicy(sizePolicy)
        self.txtTHR_Y.setMaximumSize(QSize(16777215, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        self.txtTHR_Y.setFont(font)
        self.txtTHR_Y.setObjectName(("txtTHR_Y"))
        self.horizontalLayout_21.addWidget(self.txtTHR_Y)
        self.verticalLayout_13.addWidget(self.frame_20)
        self.horizontalLayout_19.addWidget(self.frame_18)
        self.frame_21 = QFrame(self.groupBox_5)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frame_21.sizePolicy().hasHeightForWidth())
        self.frame_21.setSizePolicy(sizePolicy)
        self.frame_21.setMaximumSize(QSize(30, 70))
        self.frame_21.setFrameShape(QFrame.StyledPanel)
        self.frame_21.setFrameShadow(QFrame.Raised)
        self.frame_21.setObjectName(("frame_21"))
        self.verticalLayout_14 = QVBoxLayout(self.frame_21)
        self.verticalLayout_14.setSpacing(0)
        self.verticalLayout_14.setMargin(0)
        self.verticalLayout_14.setObjectName(("verticalLayout_14"))
        self.btnCaptureRunwayTHR = QToolButton(self.frame_21)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.btnCaptureRunwayTHR.sizePolicy().hasHeightForWidth())
        self.btnCaptureRunwayTHR.setSizePolicy(sizePolicy)
        self.btnCaptureRunwayTHR.setMaximumSize(QSize(16777215, 47))
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/coordinate_capture.png")),
                       QIcon.Normal, QIcon.Off)
        self.btnCaptureRunwayTHR.setIcon(icon)
        self.btnCaptureRunwayTHR.setObjectName(("btnCaptureRunwayTHR"))
        self.verticalLayout_14.addWidget(self.btnCaptureRunwayTHR)
        #         self.btnToolTHR = QToolButton(self.frame_21)
        #         sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        #         sizePolicy.setHorizontalStretch(0)
        #         sizePolicy.setVerticalStretch(0)
        #         sizePolicy.setHeightForWidth(self.btnToolTHR.sizePolicy().hasHeightForWidth())
        #         self.btnToolTHR.setSizePolicy(sizePolicy)
        #         self.btnToolTHR.setMaximumSize(QSize(16777215, 20))
        #         icon1 = QIcon()
        #         icon1.addPixmap(QPixmap(("Resource/sort2.png")), QIcon.Normal, QIcon.Off)
        #         self.btnToolTHR.setIcon(icon1)
        #         self.btnToolTHR.setObjectName(("btnToolTHR"))
        #         self.verticalLayout_14.addWidget(self.btnToolTHR)
        self.horizontalLayout_19.addWidget(self.frame_21)
        self.verticalLayout_2.addWidget(self.groupBox_5)
        self.groupBox_4 = QGroupBox(self.groupBox)
        self.groupBox_4.setVisible(False)
        # self.groupBox.setVisible(False)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.groupBox_4.sizePolicy().hasHeightForWidth())
        self.groupBox_4.setSizePolicy(sizePolicy)
        font = QFont()
        font.setFamily(("Arial"))
        self.groupBox_4.setFont(font)
        self.groupBox_4.setObjectName(("groupBox_4"))
        self.horizontalLayout_16 = QHBoxLayout(self.groupBox_4)
        self.horizontalLayout_16.setSpacing(0)
        self.horizontalLayout_16.setMargin(0)
        self.horizontalLayout_16.setObjectName(("horizontalLayout_16"))
        self.frame_14 = QFrame(self.groupBox_4)
        self.frame_14.setFrameShape(QFrame.StyledPanel)
        self.frame_14.setFrameShadow(QFrame.Raised)
        self.frame_14.setObjectName(("frame_14"))
        self.verticalLayout_11 = QVBoxLayout(self.frame_14)
        self.verticalLayout_11.setSpacing(0)
        self.verticalLayout_11.setContentsMargins(-1, -1, 0, -1)
        self.verticalLayout_11.setObjectName(("verticalLayout_11"))
        self.frame_15 = QFrame(self.frame_14)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frame_15.sizePolicy().hasHeightForWidth())
        self.frame_15.setSizePolicy(sizePolicy)
        self.frame_15.setFrameShape(QFrame.StyledPanel)
        self.frame_15.setFrameShadow(QFrame.Raised)
        self.frame_15.setObjectName(("frame_15"))
        self.horizontalLayout_17 = QHBoxLayout(self.frame_15)
        self.horizontalLayout_17.setSpacing(0)
        self.horizontalLayout_17.setMargin(0)
        self.horizontalLayout_17.setObjectName(("horizontalLayout_17"))
        self.label_7 = QLabel(self.frame_15)
        self.label_7.setMaximumSize(QSize(60, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.label_7.setFont(font)
        self.label_7.setObjectName(("label_7"))
        self.horizontalLayout_17.addWidget(self.label_7)
        self.txtEND_X = QLineEdit(self.frame_15)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.txtEND_X.sizePolicy().hasHeightForWidth())
        self.txtEND_X.setSizePolicy(sizePolicy)
        self.txtEND_X.setMaximumSize(QSize(16777215, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        self.txtEND_X.setFont(font)
        self.txtEND_X.setObjectName(("txtEND_X"))
        self.horizontalLayout_17.addWidget(self.txtEND_X)
        self.verticalLayout_11.addWidget(self.frame_15)
        self.frame_16 = QFrame(self.frame_14)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frame_16.sizePolicy().hasHeightForWidth())
        self.frame_16.setSizePolicy(sizePolicy)
        self.frame_16.setFrameShape(QFrame.StyledPanel)
        self.frame_16.setFrameShadow(QFrame.Raised)
        self.frame_16.setObjectName(("frame_16"))
        self.horizontalLayout_18 = QHBoxLayout(self.frame_16)
        self.horizontalLayout_18.setSpacing(0)
        self.horizontalLayout_18.setMargin(0)
        self.horizontalLayout_18.setObjectName(("horizontalLayout_18"))
        self.label_8 = QLabel(self.frame_16)
        self.label_8.setMaximumSize(QSize(60, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.label_8.setFont(font)
        self.label_8.setObjectName(("label_8"))
        self.horizontalLayout_18.addWidget(self.label_8)
        self.txtEND_Y = QLineEdit(self.frame_16)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.txtEND_Y.sizePolicy().hasHeightForWidth())
        self.txtEND_Y.setSizePolicy(sizePolicy)
        self.txtEND_Y.setMaximumSize(QSize(16777215, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        self.txtEND_Y.setFont(font)
        self.txtEND_Y.setObjectName(("txtEND_Y"))
        self.horizontalLayout_18.addWidget(self.txtEND_Y)
        self.verticalLayout_11.addWidget(self.frame_16)
        self.horizontalLayout_16.addWidget(self.frame_14)
        self.frame_17 = QFrame(self.groupBox_4)
        self.frame_17.setMaximumSize(QSize(30, 16777215))
        self.frame_17.setFrameShape(QFrame.StyledPanel)
        self.frame_17.setFrameShadow(QFrame.Raised)
        self.frame_17.setObjectName(("frame_17"))
        self.verticalLayout_12 = QVBoxLayout(self.frame_17)
        self.verticalLayout_12.setSpacing(0)
        self.verticalLayout_12.setMargin(0)
        self.verticalLayout_12.setObjectName(("verticalLayout_12"))
        self.btnCaptureRunwayEND = QToolButton(self.frame_17)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.btnCaptureRunwayEND.sizePolicy().hasHeightForWidth())
        self.btnCaptureRunwayEND.setSizePolicy(sizePolicy)
        self.btnCaptureRunwayEND.setMaximumSize(QSize(16777215, 47))
        self.btnCaptureRunwayEND.setIcon(icon)
        self.btnCaptureRunwayEND.setObjectName(("btnCaptureRunwayEND"))
        self.verticalLayout_12.addWidget(self.btnCaptureRunwayEND)
        #         self.btnToolEND = QToolButton(self.frame_17)
        #         sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        #         sizePolicy.setHorizontalStretch(0)
        #         sizePolicy.setVerticalStretch(0)
        #         sizePolicy.setHeightForWidth(self.btnToolEND.sizePolicy().hasHeightForWidth())
        #         self.btnToolEND.setSizePolicy(sizePolicy)
        #         self.btnToolEND.setMaximumSize(QSize(16777215, 20))
        #         self.btnToolEND.setIcon(icon1)
        #         self.btnToolEND.setObjectName(("btnToolEND"))
        #         self.verticalLayout_12.addWidget(self.btnToolEND)
        self.horizontalLayout_16.addWidget(self.frame_17)
        self.verticalLayout_2.addWidget(self.groupBox_4)
        self.lbl1 = QLabel(self.groupBox)
        font = QFont()
        font.setFamily(("Arial"))
        self.lbl1.setFont(font)
        self.lbl1.setText((""))
        self.lbl1.setAlignment(Qt.AlignCenter)
        self.lbl1.setWordWrap(False)
        self.lbl1.setMargin(0)
        self.lbl1.setObjectName(("lbl1"))
        self.verticalLayout_2.addWidget(self.lbl1)
        self.lbl2 = QLabel(self.groupBox)
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.lbl2.setFont(font)
        self.lbl2.setText((""))
        self.lbl2.setAlignment(Qt.AlignCenter)
        self.lbl2.setObjectName(("lbl2"))
        self.verticalLayout_2.addWidget(self.lbl2)
        self.frame_22 = QFrame(self.groupBox)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frame_22.sizePolicy().hasHeightForWidth())
        self.frame_22.setSizePolicy(sizePolicy)
        self.frame_22.setFrameShape(QFrame.StyledPanel)
        self.frame_22.setFrameShadow(QFrame.Raised)
        self.frame_22.setObjectName(("frame_22"))
        self.horizontalLayout_22 = QHBoxLayout(self.frame_22)
        self.horizontalLayout_22.setSpacing(0)
        self.horizontalLayout_22.setMargin(0)
        self.horizontalLayout_22.setObjectName(("horizontalLayout_22"))
        self.label_11 = QLabel(self.frame_22)
        self.label_11.setMinimumSize(QSize(170, 0))
        self.label_11.setMaximumSize(QSize(180, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.label_11.setFont(font)
        self.label_11.setObjectName(("label_11"))
        self.horizontalLayout_22.addWidget(self.label_11)
        self.txtForm = QLineEdit(self.frame_22)
        self.txtForm.setEnabled(False)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.txtForm.sizePolicy().hasHeightForWidth())
        self.txtForm.setSizePolicy(sizePolicy)
        self.txtForm.setMaximumSize(QSize(16777215, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        self.txtForm.setFont(font)
        self.txtForm.setObjectName(("txtForm"))
        self.horizontalLayout_22.addWidget(self.txtForm)
        self.verticalLayout_2.addWidget(self.frame_22)
        self.frame_23 = QFrame(self.groupBox)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frame_23.sizePolicy().hasHeightForWidth())
        self.frame_23.setSizePolicy(sizePolicy)
        self.frame_23.setFrameShape(QFrame.StyledPanel)
        self.frame_23.setFrameShadow(QFrame.Raised)
        self.frame_23.setObjectName(("frame_23"))
        self.horizontalLayout_23 = QHBoxLayout(self.frame_23)
        self.horizontalLayout_23.setSpacing(0)
        self.horizontalLayout_23.setMargin(0)
        self.horizontalLayout_23.setObjectName(("horizontalLayout_23"))
        self.label_12 = QLabel(self.frame_23)
        self.label_12.setMinimumSize(QSize(170, 0))
        self.label_12.setMaximumSize(QSize(180, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.label_12.setFont(font)
        self.label_12.setObjectName(("label_12"))
        self.horizontalLayout_23.addWidget(self.label_12)
        self.txtBearing = QLineEdit(self.frame_23)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.txtBearing.sizePolicy().hasHeightForWidth())
        self.txtBearing.setSizePolicy(sizePolicy)
        self.txtBearing.setMaximumSize(QSize(16777215, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        self.txtBearing.setFont(font)
        self.txtBearing.setObjectName(("txtBearing"))
        self.horizontalLayout_23.addWidget(self.txtBearing)
        self.btnCaptureBearing = QToolButton(self.frame_23)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.btnCaptureBearing.sizePolicy().hasHeightForWidth())
        self.btnCaptureBearing.setSizePolicy(sizePolicy)
        self.btnCaptureBearing.setMaximumSize(QSize(16777215, 25))
        self.btnCaptureBearing.setStyleSheet((""))
        self.btnCaptureBearing.setIcon(icon)
        self.btnCaptureBearing.setObjectName(("btnCaptureBearing"))
        self.horizontalLayout_23.addWidget(self.btnCaptureBearing)
        self.verticalLayout_2.addWidget(self.frame_23)
        self.frame_24 = QFrame(self.groupBox)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frame_24.sizePolicy().hasHeightForWidth())
        self.frame_24.setSizePolicy(sizePolicy)
        self.frame_24.setFrameShape(QFrame.StyledPanel)
        self.frame_24.setFrameShadow(QFrame.Raised)
        self.frame_24.setObjectName(("frame_24"))
        self.horizontalLayout_24 = QHBoxLayout(self.frame_24)
        self.horizontalLayout_24.setSpacing(0)
        self.horizontalLayout_24.setMargin(0)
        self.horizontalLayout_24.setObjectName(("horizontalLayout_24"))
        self.lblDistance = QLabel(self.frame_24)
        self.lblDistance.setMinimumSize(QSize(170, 0))
        self.lblDistance.setMaximumSize(QSize(180, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.lblDistance.setFont(font)
        self.lblDistance.setObjectName(("lblDistance"))
        self.horizontalLayout_24.addWidget(self.lblDistance)
        self.txtDistance = QLineEdit(self.frame_24)
        self.txtDistance.setEnabled(False)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.txtDistance.sizePolicy().hasHeightForWidth())
        self.txtDistance.setSizePolicy(sizePolicy)
        self.txtDistance.setMaximumSize(QSize(16777215, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        self.txtDistance.setFont(font)
        self.txtDistance.setObjectName(("txtDistance"))
        self.horizontalLayout_24.addWidget(self.txtDistance)
        self.btnCaptureDistance = QToolButton(self.frame_24)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.btnCaptureDistance.sizePolicy().hasHeightForWidth())
        self.btnCaptureDistance.setSizePolicy(sizePolicy)
        self.btnCaptureDistance.setMaximumSize(QSize(16777215, 23))
        self.btnCaptureDistance.setStyleSheet((""))
        self.btnCaptureDistance.setIcon(icon)
        self.btnCaptureDistance.setObjectName(("btnCaptureDistance"))
        self.horizontalLayout_24.addWidget(self.btnCaptureDistance)
        self.verticalLayout_2.addWidget(self.frame_24)
        self.verticalLayout.addWidget(self.groupBox)
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        self.buttonBox.setObjectName(("buttonBox"))
        self.verticalLayout.addWidget(self.buttonBox)
        self.btnCaptureDistance.clicked.connect(self.method_9)
        self.btnCaptureBearing.clicked.connect(self.method_8)
        self.txtEND_X.textChanged.connect(self.method_4)
        self.txtEND_Y.textChanged.connect(self.method_4)
        self.txtTHR_X.textChanged.connect(self.method_4)
        self.txtTHR_Y.textChanged.connect(self.method_4)
        # self.type = rnavType
        # self.category = category
        # self.resultPosionList = position_List
        self.MinBearing2 = 0
        self.MaxBearing2 = 0
        self.waypoint = None
        self.distanceMeasureTool = MeasureTool(define._canvas,
                                               self.txtDistance,
                                               DistanceUnits.NM)
        self.bearingTool = CaptureBearingTool(define._canvas, self.txtBearing)
        self.CaptureTHRCoordTool = CaptureCoordinateTool(
            define._canvas, self.txtTHR_X, self.txtTHR_Y)
        self.CaptureTHRCoordTool.rubberBandClick.setColor(Qt.green)
        self.CaptureENDCoordTool = CaptureCoordinateTool(
            define._canvas, self.txtEND_X, self.txtEND_Y)
        self.CaptureENDCoordTool.rubberBandClick.setColor(Qt.blue)
        #         if rnavType == RnavCommonWaypoint.FAWP or rnavType == RnavCommonWaypoint.MAWP:
        #             self.from1 = position_0
        #
        #             self.resize(326, 310)
        #             if position_List[0] != None:
        #                 self.setThrPosition(position_List[0].x(),position_List[0].y())
        #                 self.CaptureTHRCoordTool.rubberBandClick.addPoint(QgsPoint(position_List[0].x(),position_List[0].y()))
        # #                 self.CaptureTHRCoordTool.rubberBandClick.show()
        #             if position_List[1] != None:
        #                 self.setEndPosition(position_List[1].x(),position_List[1].y())
        #                 self.CaptureENDCoordTool.rubberBandClick.addPoint(QgsPoint(position_List[1].x(),position_List[1].y()))
        # #             self.setWaypoint(position_List[2])
        #         else:
        #             self.from1 = position_1
        #             num = RnavWaypoints.smethod_0(position_0, position_1)
        #             self.MinBearing = RnavWaypoints.smethod_7(rnavType, category, num)
        #             self.MaxBearing= RnavWaypoints.smethod_8(rnavType, category, num)
        #             self.MinDistance = RnavWaypoints.smethod_4(rnavType, category)
        #             if flagStr == "Y-Bar":
        #                 if (rnavType == RnavCommonWaypoint.IAWP1):
        #                     self.setBearing(self.MaxBearing)
        #                 elif (rnavType != RnavCommonWaypoint.IAWP3):
        #                     self.setBearing(num)
        #                 else:
        #                     self.setBearing(self.MinBearing)
        #             else:
        #                 if (rnavType == RnavCommonWaypoint.IAWP1):
        #                     self.setBearing(self.MinBearing)
        #                 elif (rnavType != RnavCommonWaypoint.IAWP3):
        #                     self.setBearing(num)
        #                 else:
        #                     self.setBearing(self.MaxBearing)
        # #             if self.txtDistance.isEnabled():
        # #             self.setDistance(RnavWaypoints.smethod_6(rnavType, category).NauticalMiles)
        # #             self.setWaypoint(position_List.pop(0))
        #         self.method_4()
        self.retranslateUi()
        QObject.connect(self.buttonBox, SIGNAL(("accepted()")),
                        self.btnCalculate_Click)
        QObject.connect(self.buttonBox, SIGNAL(("rejected()")), self.reject)
        #         QMetaObject.connectSlotsByName(Dialog)

        #         self.btnToolEND.clicked.connect(self.removeEnd)
        #         self.btnToolTHR.clicked.connect(self.removeThr)
        self.btnCaptureRunwayTHR.clicked.connect(self.captureTHR)
        self.btnCaptureRunwayEND.clicked.connect(self.captureEND)

        self.txtDistance.setText("10")

    def retranslateUi(self):
        self.setWindowTitle("CaculaterDlg")
        self.groupBox_5.setTitle("Runway THR")
        self.label_9.setText("X:")
        self.label_10.setText("Y:")
        self.btnCaptureRunwayTHR.setText("...")
        #         self.btnToolTHR.setText("...")
        self.groupBox_4.setTitle("Runway END")
        self.label_7.setText("X:")
        self.label_8.setText("Y:")
        self.btnCaptureRunwayEND.setText("...")
        #         self.btnToolEND.setText("...")
        self.label_11.setText("From:")
        self.txtForm.setText("FAWP")
        self.label_12.setText(unicode("Bearing (°) :", "utf-8"))
        #         self.txtBearing.setText("188.25")
        self.btnCaptureBearing.setText("...")
        self.lblDistance.setText("Distance (nm):")
        self.txtDistance.setText("5")
        self.btnCaptureDistance.setText("...")

    def captureTHR(self):
        define._canvas.setMapTool(self.CaptureTHRCoordTool)

    def captureEND(self):
        define._canvas.setMapTool(self.CaptureENDCoordTool)

    def close(self):
        scene = define._canvas.scene()
        scene.removeItem(self.CaptureTHRCoordTool.rubberBandClick)
        scene.removeItem(self.CaptureENDCoordTool.rubberBandClick)
        scene.removeItem(self.bearingTool.rubberBand)
        scene.removeItem(self.distanceMeasureTool.rubberBand)
        #         self.CaptureTHRCoordTool.rubberBand.hide()
        #         self.CaptureENDCoordTool.rubberBand.hide()
        define._canvas.setMapTool(QgsMapToolPan(define._canvas))
#         self.reject()

    def reject(self):
        self.close()
        QDialog.reject(self)

    def getThrPoint3D(self):
        if self.txtTHR_X.text() != "" and self.txtTHR_Y.text() != "":
            try:
                x = float(self.txtTHR_X.text())
            except ValueError:
                x = 0
            try:
                y = float(self.txtTHR_Y.text())
            except ValueError:
                y = 0
            return Point3D(x, y, 0)
        else:
            return None

    def getEndPoint3D(self):
        if self.txtEND_X.text() != "" and self.txtEND_Y.text() != "":
            try:
                x = float(self.txtEND_X.text())
            except ValueError:
                x = 0
            try:
                y = float(self.txtEND_Y.text())
            except ValueError:
                y = 0
            return Point3D(x, y, 0)
        else:
            return None

    def setEndPosition(self, x, y):
        self.txtEND_X.setText(str(x))
        self.txtEND_Y.setText(str(y))

    def setThrPosition(self, x, y):
        self.txtTHR_X.setText(str(x))
        self.txtTHR_Y.setText(str(y))

    def getWaypoint(self):
        if (self.type == RnavCommonWaypoint.FAWP):
            nauticalMiles = float(self.txtDistance.text())
            value = float(self.txtBearing.text())
            num1 = math.fabs(self.rethr - value)
            if (num1 > 180):
                num1 = 360 - num1
            num2 = math.sin(Unit.smethod_0(num1)) * 0.7559395
            num3 = Unit.smethod_1(math.asin(num2 / nauticalMiles))
            num4 = math.cos(Unit.smethod_0(num1)) * 0.755939525
            num5 = math.cos(Unit.smethod_0(num3)) * nauticalMiles
            return RnavWaypoints.smethod_3(
                self.pos1400m, float(self.txtBearing.text()),
                Distance(math.fabs(num5 - num4), DistanceUnits.NM))
        if (self.type != RnavCommonWaypoint.MAWP):
            return RnavWaypoints.smethod_3(
                self.from1, float(self.txtBearing.text()),
                Distance(float(self.txtDistance.text()), DistanceUnits.NM))
        if (float(self.txtBearing.text()) > self.thrre
                or float(self.txtBearing.text()) - self.thrre >= 90):

            angle = 90
            if self.flagStrName == "Y-Bar":
                angle = 70
            num = self.rethr - angle
            if (num < 0):
                num = num + 360
        else:
            num = self.rethr + angle
            if (num > 360):
                num = num - 360
        point3d1 = self.from1
        point3d2 = self.getThrPoint3D()
        point3d = MathHelper.getIntersectionPoint(
            point3d1,
            RnavWaypoints.smethod_3(self.from1, float(self.txtBearing.text()),
                                    Distance(1000)), point3d2,
            RnavWaypoints.smethod_3(self.getThrPoint3D(), num, Distance(1000)))
        if point3d == None:
            raise UserWarning, Messages.ERR_FAILED_TO_CALCULATE_INTERSECTION_POINT
        return RnavWaypoints.smethod_3(
            self.getThrPoint3D(), num,
            Distance(MathHelper.calcDistance(point3d2, point3d)))

    def setWaypoint(self, value):
        self.waypoint = value
        if self.from1 != None and self.waypoint != None:
            #             self.setBearing(RnavWaypoints.smethod_0(self.from1, value))
            #             if self.txtDistance.isEnabled():
            #             print RnavWaypoints.smethod_2(self.from1, value).NauticalMiles
            #             print RnavWaypoints.smethod_2(self.from1, value).NauticalMiles
            self.setDistance(
                RnavWaypoints.smethod_2(self.from1, value).NauticalMiles)

    def setDistance(self, value):
        self.txtDistance.setText("%i" % round(value))

    def setBearing(self, value):
        self.txtBearing.setText(str(value))

    def btnCalculate_Click(self):
        try:
            bearing = Unit.ConvertDegToRad(float(self.txtBearing.text()))
            distance0 = Distance(float(self.txtDistance.text()),
                                 DistanceUnits.NM).Metres
            self.calcedPoint = MathHelper.distanceBearingPoint(
                self.point, bearing, distance0)
            if self.flagStr == "R":
                self.parent0.parametersPanel.pnlIAWP1.Point3d = self.calcedPoint
                self.parent0.parametersPanel.txtRadiusIAWP1.setText(
                    self.txtDistance.text())
            elif self.flagStr == "L":
                self.parent0.parametersPanel.txtRadiusIAWP3.setText(
                    self.txtDistance.text())
                self.parent0.parametersPanel.pnlIAWP3.Point3d = self.calcedPoint
            elif self.flagStr == "C":
                self.parent0.parametersPanel.txtRadiusIAWP2.setText(
                    self.txtDistance.text())
                self.parent0.parametersPanel.pnlIAWP2.Point3d = self.calcedPoint

            self.accept()

        except UserWarning as e:
            QMessageBox.warning(self, "warning", e.message)

    def method_9(self):
        #         self.distanceMeasureTool = MeasureTool(define._canvas, self.txtDistance, DistanceUnits.NM)
        define._canvas.setMapTool(self.distanceMeasureTool)

    def method_8(self):
        #         self.bearingTool = CaptureBearingTool(define._canvas, self.txtBearing)
        define._canvas.setMapTool(self.bearingTool)

    def method_4(self):
        num = None
        num1 = None
        num2 = None
        num3 = None
        num4 = None
        num5 = None
        num6 = None
        num7 = None
        num8 = None
        num9 = None
        self.lbl1.setText(Validations.PLEASE_ENTER_VALID_RUNWAY_POSITIONS)
        self.lbl2.setText(" ")
        if (self.type == RnavCommonWaypoint.FAWP):
            position = self.getThrPoint3D()
            position1 = self.getEndPoint3D()
            if position is None or position1 is None:
                self.txtBearing.setText("")
                #                 self.txtDistance.setText("")
                return
            self.thrre = RnavWaypoints.smethod_0(position, position1)
            self.rethr = RnavWaypoints.smethod_0(position1, position)
            self.pos1400m = RnavWaypoints.smethod_3(position, self.rethr,
                                                    Distance(1400))
            self.MinDistance = RnavWaypoints.smethod_4(self.type,
                                                       self.category)
            #             if self.txtDistance.isEnabled():
            #             self.setDistance(RnavWaypoints.smethod_6(self.type, self.category).NauticalMiles)

            self.setBearing(self.rethr)
            self.MinBearing = RnavWaypoints.smethod_7(self.type, self.category,
                                                      self.rethr)
            self.MaxBearing = RnavWaypoints.smethod_8(self.type, self.category,
                                                      self.rethr)
#             if self.waypoint is not None:
#                 self.setBearing(round(RnavWaypoints.smethod_0(self.pos1400m, self.waypoint), 2))
# #                 if self.txtDistance.isEnabled():
#                 self.setDistance(RnavWaypoints.smethod_2(position, self.waypoint).NauticalMiles)

        elif (self.type == RnavCommonWaypoint.MAWP):
            position2 = self.getThrPoint3D()
            position3 = self.getEndPoint3D()
            if position2 is None or position3 is None:
                self.txtBearing.setText("")
                return
            self.thrre = RnavWaypoints.smethod_0(position2, position3)
            self.rethr = RnavWaypoints.smethod_0(position3, position2)

            self.pos1400m = RnavWaypoints.smethod_3(position2, self.rethr,
                                                    Distance(1400))
            num10 = RnavWaypoints.smethod_1(self.pos1400m, self.from1)
            num = RnavWaypoints.smethod_1(self.from1, self.pos1400m)
            num11 = 15
            position4 = None
            if (self.category == AircraftSpeedCategory.A
                    or self.category == AircraftSpeedCategory.B
                    or self.category == AircraftSpeedCategory.H):
                num11 = 30
            if (num10 > self.rethr or self.rethr - num10 >= 90):
                num1 = self.thrre + num11
                num2 = num
                if (num2 > 360):
                    num2 = num2 - 360
            else:
                num1 = num
                num2 = self.thrre - num11
                if (num2 < 0):
                    num2 = num2 + 360
            if (max(num1, num2) <= 270 or min(num1, num2) >= 90):
                num3 = min(num1, num2)
                num4 = max(num1, num2)
            else:
                num3 = max(num1, num2)
                num4 = min(num1, num2)
            position4 = RnavWaypoints.smethod_3(position2, self.thrre,
                                                Distance(466))
            num12 = RnavWaypoints.smethod_0(position4, self.from1)
            num13 = math.fabs(num12 - self.rethr)
            if (num13 > 180):
                num13 = 360 - num13
            if (num13 > 5):
                num5 = 0
                num6 = 0
                num7 = 0
                num8 = 0
            else:
                if (num12 > self.rethr or self.rethr - num12 >= 90):
                    num9 = self.rethr + 90
                    if (num9 > 360):
                        num9 = num9 - 360
                else:
                    num9 = self.rethr - 90
                    if (num9 < 0):
                        num9 = num9 + 360
                position5 = RnavWaypoints.smethod_3(self.pos1400m, num9,
                                                    Distance(150))
                num5 = RnavWaypoints.smethod_0(self.from1, position5)
                num6 = RnavWaypoints.smethod_0(self.from1, self.pos1400m)
                if (max(num5, num6) <= 270 or min(num5, num6) >= 90):
                    num7 = min(num5, num6)
                    num8 = max(num5, num6)
                else:
                    num7 = max(num5, num6)
                    num8 = min(num5, num6)
            if (MathHelper.smethod_99(num, self.thrre, 1)):
                position6 = RnavWaypoints.smethod_3(self.pos1400m,
                                                    self.rethr - 90,
                                                    Distance(150))
                position7 = RnavWaypoints.smethod_3(self.pos1400m,
                                                    self.rethr + 90,
                                                    Distance(150))
                num1 = RnavWaypoints.smethod_0(self.from1, position6)
                num2 = RnavWaypoints.smethod_0(self.from1, position7)
                num7 = 0
                num8 = 0
                if (max(num1, num2) <= 270 or min(num1, num2) >= 90):
                    num3 = min(num1, num2)
                    num4 = max(num1, num2)
                else:
                    num3 = max(num1, num2)
                    num4 = min(num1, num2)
            if (MathHelper.smethod_96(num7) or MathHelper.smethod_96(num8)):
                self.MinBearing = MathHelper.smethod_3(num3)
                self.MaxBearing = MathHelper.smethod_3(num4)
                self.MinBearing2 = MathHelper.smethod_3(num7)
                self.MaxBearing2 = MathHelper.smethod_3(num8)
            elif (min(num3, num4) >= min(num7, num8)):
                if (MathHelper.smethod_99(num8, num3, 0.3)):
                    num8 = num4
                    num3 = 0
                    num4 = 0
                self.MinBearing = MathHelper.smethod_3(num7)
                self.MaxBearing = MathHelper.smethod_3(num8)
                self.MinBearing2 = MathHelper.smethod_3(num3)
                self.MaxBearing2 = MathHelper.smethod_3(num4)
            else:
                if (MathHelper.smethod_99(num4, num7, 0.3)):
                    num4 = num8
                    num7 = 0
                    num8 = 0
                self.MinBearing = MathHelper.smethod_3(num3)
                self.MaxBearing = MathHelper.smethod_3(num4)
                self.MinBearing2 = MathHelper.smethod_3(num7)
                self.MaxBearing2 = MathHelper.smethod_3(num8)
            self.MinDistance = RnavWaypoints.smethod_4(self.type,
                                                       self.category)
            #             if self.txtDistance.isEnabled():
            #                 self.setDistance(RnavWaypoints.smethod_6(self.type, self.category).NauticalMiles)
            if (self.MinBearing <= self.MaxBearing):
                self.setBearing((self.MinBearing + self.MaxBearing) / 2)
            else:
                self.setBearing(
                    MathHelper.smethod_3(self.MinBearing +
                                         (360 - self.MinBearing +
                                          self.MaxBearing)))
#             if (self.waypoint is not None):
#                 self.setBearing(RnavWaypoints.smethod_0(self.from1, self.waypoint))
        if (MathHelper.smethod_96(self.MinBearing2)
                or MathHelper.smethod_96(self.MaxBearing2)):
            self.lbl1.setText(
                unicode("Acceptable bearings are %.1f° - %.1f°", "utf-8") %
                (self.MinBearing, self.MaxBearing))
        else:
            self.lbl1.setText(Validations.ACCEPTABLE_BEARINGS_ARE_X_Y_AND_X_Y %
                              (self.MinBearing, self.MaxBearing,
                               self.MinBearing2, self.MaxBearing2))
        if self.MinDistance != None and self.type != RnavCommonWaypoint.MAWP:
            self.lbl2.setText(Validations.ACCEPTABLE_MINIMUM_DISTANCE_IS_X %
                              (self.MinDistance.NauticalMiles))


#     def removeEnd(self):
#         self.txtEND_X.setText("")
#         self.txtEND_Y.setText("")
#     def removeThr(self):
#         self.txtTHR_X.setText("")
#         self.txtTHR_Y.setText("")
#     @staticmethod
#     def smethod_0( parent, rnavCommonWaypoint_0, aircraftSpeedCategory_0, position_0, position_1, position_List):
#         flag = None
#         using (DlgCalculateWaypoint dlgCalculateWaypoint = new DlgCalculateWaypoint())
#         {
#             dlgCalculateWaypoint.Text = string.Format("{0} {1}", Captions.CALCULATE, EnumHelper.smethod_0(rnavCommonWaypoint_0))
#             dlgCalculateWaypoint.Type = rnavCommonWaypoint_0
#             dlgCalculateWaypoint.Category = aircraftSpeedCategory_0
#             dlgCalculateWaypoint.From = position_1
#             double num = RnavWaypoints.smethod_0(position_0, position_1)
#             dlgCalculateWaypoint.MinBearing = RnavWaypoints.smethod_7(rnavCommonWaypoint_0, aircraftSpeedCategory_0, num)
#             dlgCalculateWaypoint.MaxBearing = RnavWaypoints.smethod_8(rnavCommonWaypoint_0, aircraftSpeedCategory_0, num)
#             dlgCalculateWaypoint.MinDistance = RnavWaypoints.smethod_4(rnavCommonWaypoint_0, aircraftSpeedCategory_0)
#             if (rnavCommonWaypoint_0 == RnavCommonWaypoint.IAWP1)
#             {
#                 dlgCalculateWaypoint.Bearing = dlgCalculateWaypoint.MinBearing
#             }
#             else if (rnavCommonWaypoint_0 != RnavCommonWaypoint.IAWP3)
#             {
#                 dlgCalculateWaypoint.Bearing = num
#             }
#             else
#             {
#                 dlgCalculateWaypoint.Bearing = dlgCalculateWaypoint.MaxBearing
#             }
#             dlgCalculateWaypoint.Distance = RnavWaypoints.smethod_6(rnavCommonWaypoint_0, aircraftSpeedCategory_0)
#             dlgCalculateWaypoint.Waypoint = position_2
#             if (dlgCalculateWaypoint.method_2(iwin32Window_0) != System.Windows.Forms.DialogResult.OK)
#             {
#                 flag = false
#             }
#             else
#             {
#                 position_2 = dlgCalculateWaypoint.Waypoint
#                 flag = true
#             }
#         }
#         return flag
#     }
#
#     public static bool smethod_1(IWin32Window iwin32Window_0, RnavCommonWaypoint rnavCommonWaypoint_0, AircraftSpeedCategory aircraftSpeedCategory_0, Position position_0, ref Position position_1, ref Position position_2, ref Position position_3)
#     {
#         bool flag
#         using (DlgCalculateWaypoint dlgCalculateWaypoint = new DlgCalculateWaypoint())
#         {
#             dlgCalculateWaypoint.Text = string.Format("{0} {1}", Captions.CALCULATE, EnumHelper.smethod_0(rnavCommonWaypoint_0))
#             dlgCalculateWaypoint.Type = rnavCommonWaypoint_0
#             dlgCalculateWaypoint.Category = aircraftSpeedCategory_0
#             dlgCalculateWaypoint.From = position_0
#             dlgCalculateWaypoint.RwyThr = position_1
#             dlgCalculateWaypoint.RwyEnd = position_2
#             dlgCalculateWaypoint.Waypoint = position_3
#             bool flag1 = dlgCalculateWaypoint.method_2(iwin32Window_0) == System.Windows.Forms.DialogResult.OK
#             position_1 = dlgCalculateWaypoint.RwyThr
#             position_2 = dlgCalculateWaypoint.RwyEnd
#             if (flag1)
#             {
#                 position_3 = dlgCalculateWaypoint.Waypoint
#             }
#             flag = flag1
#         }
#         return flag
#     }
# }
Exemplo n.º 3
0
class ProgressDialog(Ui_ProgressDialog, DialogBase):
    def __init__(self, publisher, plugin, parentWidget=None):
        DialogBase.__init__(self, parentWidget)
        self.setupUi(self)
        self.setObjectName("ProgressDialog")
        self.viewButton_.setEnabled(False)

        self._publisher = publisher
        self._plugin = plugin
	self._parent = parentWidget
        self._cancelled = False
        self._timeline = QTimeLine(1000*60, self)
        self._timeline.setFrameRange(0, 2*60)
        self._timeline.setLoopCount(0)
        self.progressBar_.setRange(0, 60)
        self.connect(self._timeline, QtCore.SIGNAL("frameChanged(int)"),
                     self.updateProgressBar)

        self.outputGroupBox_ = QGroupBox("Script output", None)

        self.outputTextEdit_ = QTextEdit()
        self.outputTextEdit_.setTextInteractionFlags(Qt.TextSelectableByKeyboard
                                                     | Qt.TextSelectableByMouse)
        self.outputTextEdit_.setReadOnly(True)
        self.outputTextEdit_.setTabChangesFocus(True)
        self.outputTextEdit_.setAcceptRichText(False)

        groupBoxLayout = QVBoxLayout()
        groupBoxLayout.setObjectName("groupBoxLayout")
        groupBoxLayout.setMargin(0)
        groupBoxLayout.addWidget(self.outputTextEdit_)
        self.outputGroupBox_.setLayout(groupBoxLayout)

        gridLayout = QGridLayout()
        gridLayout.setSizeConstraint(gridLayout.SetFixedSize)
        gridLayout.addWidget(self.progressLabel_, 0, 0, 1, 4)
        gridLayout.addWidget(self.progressBar_, 1, 0, 1, 4)
        gridLayout.addWidget(self.detailsCheckBox_, 2, 0)
        hSpacer = QSpacerItem(250, 10, QSizePolicy.Expanding)
        gridLayout.addItem(hSpacer, 2, 1)

        gridLayout.addWidget(self.viewButton_, 2, 2)
        gridLayout.addWidget(self.cancelButton_, 2, 3)
        gridLayout.addWidget(self.outputGroupBox_, 3, 0, 1, 4)

        self.setLayout(gridLayout)

        self.outputGroupBox_.setVisible(False)

    def updateProgressBar(self, frame):
        self.progressBar_.setValue(self.progressBar_.value() + 1)

    def on_detailsCheckBox__stateChanged(self, state):
        self.outputGroupBox_.setVisible(Qt.Checked == state)
        gridLayout = self.layout()
        if Qt.Checked == state:
            gridLayout.setSizeConstraint(gridLayout.SetMaximumSize)
            self.setSizeGripEnabled(True)
        else:
            gridLayout.setSizeConstraint(gridLayout.SetFixedSize)
            self.setSizeGripEnabled(False)

    def on_cancelButton__clicked(self, released=True):
        if not released:
            return

        if self._cancelled:
            self.reject()
            return

        self.cancelButton_.setEnabled(False)
        self.progressLabel_.setText("Cancelling...")
        self._publisher.cancel()
        self._cancelled = True
        QTimer.singleShot(5*1000, self, QtCore.SLOT("_kill()"))

    @QtCore.pyqtSignature("_kill()")
    def _cancel(self):
        self._parent.update()
        self._publisher.cancel(True)
        self.reject()

    def updatePublisherOutput(self, data):
        self.outputTextEdit_.append(data)

    def publishComplete(self, exitCode, exitStatus):
        self.progressBar_.setValue(self.progressBar_.maximum())
        self._timeline.stop()
        if self._cancelled:
            self.reject()
        self._cancelled = True
        publishSuccess = (0 == exitCode and QProcess.NormalExit == exitStatus)
        output_exists = self.__findOutput()
        self.viewButton_.setEnabled(publishSuccess and \
                                    output_exists)
        if not publishSuccess:
            self.progressLabel_.setText("Publishing failed, see script output"
                                        " for more details")
        else:
            self.progressLabel_.setText("Publishing completed")

    def __findOutput(self):
        output_exists = os.path.exists(unicode(self._outFile))
        if not output_exists:
            output_exists = self.__findInSubdir()
        if not(output_exists) and ('Dita' in self._publisher.__str__()) :
            output_exists = self.__findInLog()
        if not(output_exists) and ('Docbook' in self._publisher.__str__()) :
            output_exists = self.__findInPI()
        return output_exists

    def __findInLog(self):
        log = self.outputTextEdit_.toPlainText()
        src_filename = os.path.basename(self._publisher.attrs()['srcUri'])
        dst_filename = src_filename.split('.')[0] + "." + self._publisher.attrs()['extension']
        re_str = '\[xslt\] Processing.*?' + src_filename  + ' to (?P<outputFilename>.*?' + dst_filename + ')'
        output_re = re.compile(re_str)
        output_filename = ''
        if None != output_re.search(log):
            output_filename = output_re.search(log).group("outputFilename")
        if not output_filename:
            return False
        real_dst_dir = os.path.dirname(unicode(output_filename))
        dst_filename = os.path.join(real_dst_dir, os.path.basename(self._outFile))
        os.rename(output_filename, dst_filename)
        output_exists = os.path.exists(dst_filename)
        if output_exists:
            self._outFile = dst_filename
            self._parent.setOutputFilePath(self._outFile)
            return True
        return False

    def __findInPI(self):
        src_uri = self._publisher.attrs()['srcUri']
        grove = Grove.buildGroveFromFile(src_uri)
        xpath_value = XpathExpr("//self::processing-instruction('dbhtml')").eval(grove.document())
        dbhtml_pi = xpath_value.getNodeSet().firstNode()
        str_ = unicode(dbhtml_pi.asGrovePi().data())
        filename_re = re.compile('filename="(?P<filename>.*?\n?.*?)"')
        dir_re = re.compile('dir="(?P<dir>.*?\n?.*?)"')
        if None != filename_re.search(str_):
            filename_ = filename_re.search(str_).group("filename")
        if None != dir_re.search(str_):
            dir_ = dir_re.search(str_).group("dir")
        out_dir = os.path.dirname(self._outFile)
        combined_output_filename = os.path.join(out_dir, dir_, filename_)
        output_exists = os.path.exists(combined_output_filename)
        if output_exists:
            self._outFile = combined_output_filename
            self._parent.setOutputFilePath(self._outFile)
            return True
        return False

    def __findInSubdir(self):
        output_filename = unicode(self._outFile)
	filename_ = os.path.basename(output_filename)
        dir_ = os.path.dirname(output_filename)
	folder_name = os.path.basename(dir_)
	output_filename = os.path.join(dir_, folder_name, filename_)
	output_exists = os.path.exists(output_filename)
	if output_exists:
	    self._outFile = output_filename
            self._parent.setOutputFilePath(self._outFile)
            return True
        return False

    def on_viewButton__clicked(self, released=True):
        if not released:
            return
        self._plugin.launchViewer(os.path.abspath(self._outFile))

    def publish(self, dsi, outFile):
        if not self._publisher:
            self.updatePublisherOutput("Script is not found")
            self.publishComplete(1, QProcess.Crashed)
            return self.exec_()
        self._outFile = outFile
        self.show()
        try:
            self.progressBar_.setValue(self.progressBar_.minimum() + 1)
            self._publisher.publish(self, dsi, outFile)
            self._timeline.start()
        except PublishException, pe:
            self.updatePublisherOutput(pe.getErrorString())
        return self.exec_()
Exemplo n.º 4
0
class CommandWindow (QMainWindow):
    
    # Constructs a new CommandWindow
    def __init__(self, parent = None):
        
        QMainWindow.__init__(self, parent)
        self.main_widget = QWidget()
        
        # Builds all groups
        self.build_connection_group()        
        self.build_source_windows()
        self.build_buttons_group()
        self.build_commands_group()
        self.build_log_group()
        
        # Initially the client is disconnected. Consequently, no boards
        # are available
        self.sources_group.setVisible(False)
        
        self.main_layout = QGridLayout()
        self.main_layout.setSpacing(10)
        
        # Groups all components in the main widget
        self.main_layout.addWidget(self.connect_group, 0, 0, 1, 3)
        self.main_layout.addWidget(self.commands_group, 1, 0, 1, 5)
        self.main_layout.addWidget(self.sources_group, 2, 0, 1, 5)
        self.main_layout.addWidget(self.log_group, 3, 0, 1, 5)
        
        self.main_widget.setLayout(self.main_layout)
        
        self.statusBar().showMessage("Client started.")
        self.setCentralWidget(self.main_widget)
        self.setWindowTitle('Commands Window')
        self.setFixedSize(QSize(720, 330))
        
        # Constructs the objects responsible to send and receive packets 
        # from PROSAC
        self.requester_controller = Requester(self)
        
        self.is_closed = 0
    
    # Sets a requester in the case it was not instantiated 
    def setRequester(self, r):
        self.requester_controller = r
        self.requester_controller.window_controller = self
    
    # Builds text boxes, labels and buttons required to establish a connection with PROSAC 
    def build_connection_group (self):
        
        self.connect_group = QGroupBox(parent =  self.main_widget)
        self.connect_group.setTitle('Connection')
        self.connect_group.setStyleSheet("QGroupBox { border: 1px solid gray; border-radius: 3px;  margin-top: 0.5em; } QGroupBox::title {  subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px;}")
        
        self.connect_label = QLabel("IP Address")
        self.connect_line = QLineEdit("10.0.6.65")
        self.connect_line.setFixedWidth(100)
        
        self.connect_button = QPushButton("Connect")
        self.connect_button.clicked.connect(self.connection_handler)
        
        self.port_label = QLabel("Port")
        self.port_line = QLineEdit("4000")
        self.port_line.setFixedWidth(50)
        self.led_connected = QLed(parent = self.main_widget)
        self.led_connected.turnOff()
        
        self.connect_layout = QHBoxLayout()
        
        self.connect_layout.addWidget(self.connect_label)
        self.connect_layout.addWidget(self.connect_line)
        self.connect_layout.addWidget(self.port_label)
        self.connect_layout.addWidget(self.port_line)
        self.connect_layout.addWidget(self.led_connected)
        self.connect_layout.addWidget(self.connect_button)
        
        self.connect_group.setLayout(self.connect_layout)
    
    # Builds components to show last received and sent messages
    def build_log_group (self): 
        
        self.log_group = QGroupBox(parent =  self.main_widget)
        self.log_group.setTitle('Messages')
        self.log_group.setStyleSheet("QGroupBox { border: 1px solid gray; border-radius: 3px;  margin-top: 0.5em; } QGroupBox::title {  subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px;}")
        
        self.label_sent = QLabel("Last packet sent: ")
        self.label_received = QLabel("Last packet received: ")
        
        self.log_layout = QVBoxLayout()
        self.log_layout.addWidget(self.label_received)
        self.log_layout.addWidget(self.label_sent)
        
        self.log_group.setLayout(self.log_layout)
    
    # Adds as many buttons as the number of connected power supplies.
    def build_buttons_group (self):
        
        self.sources_group = QGroupBox(parent =  self.main_widget)
        self.sources_group.setTitle('Power supply')
        self.sources_group.setStyleSheet("QGroupBox { border: 1px solid gray; border-radius: 3px;  margin-top: 0.5em; } QGroupBox::title {  subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px;}")
    
        self.sources_layout = QHBoxLayout()
    
        for button in self.board_buttons_list:
            self.sources_layout.addWidget(button)
            
        self.sources_group.setLayout(self.sources_layout)
        
    # Builds all command buttons.
    # 0x00 stands for a normal reading command, 0x01, a ADJUST command, 0x05, a acknowledge message,
    # 0xE0 is used to ENABLE CYCLE and 0xE1, to abort it.
    def build_commands_group (self):
        
        self.commands_group = QGroupBox(parent =  self.main_widget)
        self.commands_group.setTitle('Commands')
        self.commands_group.setStyleSheet("QGroupBox { border: 1px solid gray; border-radius: 3px;  margin-top: 0.5em; } QGroupBox::title {  subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px;}")
    
        self.commands_layout = QHBoxLayout()
    
        self.button_normal = QPushButton("0x00")
        self.commands_layout.addWidget(self.button_normal)
        self.button_normal.setEnabled(False)
        # Connects clicked signal to the handler
        self.button_normal.clicked.connect(self.normal_handler)
        
        self.button_adjust = QPushButton("0x01")
        self.commands_layout.addWidget(self.button_adjust)
        self.button_adjust.setEnabled(False)
        self.button_adjust.clicked.connect(self.adjust_handler)
        
        self.button_confirm = QPushButton("0x05")
        self.commands_layout.addWidget(self.button_confirm)
        self.button_confirm.setEnabled(False)
        self.button_confirm.clicked.connect(self.confirm_handler)
        
        self.button_cycle_enable = QPushButton("0xE0")
        self.commands_layout.addWidget(self.button_cycle_enable)
        self.button_cycle_enable.setEnabled(False)
        self.button_cycle_enable.clicked.connect(self.cycle_enable_handler)
        
        self.button_cycle_abort = QPushButton("0xE1")
        self.commands_layout.addWidget(self.button_cycle_abort)
        self.button_cycle_abort.setEnabled(False)
        self.button_cycle_abort.clicked.connect(self.cycle_abort_handler)
        
        self.commands_group.setLayout(self.commands_layout)
    
    # Returns how many power suppliers are connected
    def get_boards_count(self):
        
        return len(self.board_source_windows_list)
    
    # Returns how many power suppliers are connected
    def get_boards_list(self):
        
        return self.board_source_windows_list
    
    # Resets lists
    def build_source_windows(self):
        
        # board_source_windows_list is a list object which contains all references
        # to the SourceWindow objects. board_buttons_list contains the references to
        # the buttons which open the respective window 
        
        self.board_source_windows_list = list()
        self.board_buttons_list = list()
        
        # Support for a pre-built configuration (command IDENT not necessary)
        #for i in board_list:
        #    self.board_source_windows_list.append(SourceWindow(parent = self, board = i))
        #    button = QPushButton(i.getTitle())
        #    button.clicked.connect (self.source_handler)
        #    self.board_buttons_list.append(button)

    # Adds a button to the board_buttons_list and associates it to a SourceWindow object
    def add_board_source_group(self, id):
               
        self.board_source_windows_list.append(SourceWindow(parent = self, board = Board(title='Board #%d' % id, color = QColor(randint(0, 255), randint(0, 255), randint(0, 255) ), order = id)))
        button = QPushButton('Board #%d' % id)
        button.clicked.connect (self.source_handler)
        self.board_buttons_list.append(button)
        
        self.sources_layout.addWidget(button)
    
    # Resets and deletes board_source_windows_list and board_buttons_list
    def clear_source_group (self):
        
        # Resets entire source group. Clears buttons and layout
        for b in self.board_buttons_list:
            b.deleteLater()
            #self.sources_layout.removeWidget(b)
            
        self.board_buttons_list = []  # Clears button list
        
        for b in self.board_source_windows_list:
            
            # if useCanvas is True, close canvas. Such operation must be made explicitly,
            # considering that matplotlib does not handle it.
            if b.useCanvas:
                b.canvas.close()
                     
            b.close()
        
        self.board_source_windows_list = []
        
    # Updates buttons in the case of a disconnection
    def set_disconnected_state (self):
               
        self.sources_group.setVisible(False)
        
        self.button_normal.setEnabled(False)
        self.button_adjust.setEnabled(False)
        self.button_cycle_enable.setEnabled(False)
        self.button_cycle_abort.setEnabled(False)
        self.button_confirm.setEnabled(False)
        
        self.led_connected.turnOff()
                
        self.connect_button.setText("Connect")
    
    # Updates buttons in the case of a connection    
    def set_connected_state (self):
        
        self.sources_group.setVisible(True)
        
        self.button_normal.setEnabled(True)
        self.button_adjust.setEnabled(True)
        self.button_cycle_enable.setEnabled(True)
        self.button_cycle_abort.setEnabled(False)
        self.button_confirm.setEnabled(True)
        
        self.led_connected.turnOn()
        
        self.connect_button.setText("Disconnect")
        
    def set_requester_controller(self, requester):
        
        self.requester_controller = requester

    ####### HANDLERS section #######
    
    # Handles a connection / disconnection request
    def connection_handler(self):
        
        if not self.requester_controller.isConnected :
        
            port_n = int(self.port_line.text())
            
            self.led_connected.turnAlmostOn()
            
            self.statusBar().clearMessage()
            
            self.statusBar().showMessage('Trying to connect to %s through port %d' % (self.connect_line.text(), port_n))
            
            self.update()
            
            # Tries to connect to the PROSAC
            connected, message = self.requester_controller.connect(ip_address = self.connect_line.text(), port = port_n)
            
            self.statusBar().showMessage('%s' % message)
                    
            if connected:
                
                self.set_connected_state()
                                            
                # Request information about how many boards are connected (IDENT command)
                self.requester_controller.execute_command(0x02)
                self.requester_controller.execute_command(0x03)
                
                
                self.requester_controller.can_ask = True
            
            # If connection request was not successful, reset all lists 
            # and boards
            else: 
                
                self.requester_controller.isConnected = False
                self.clear_source_group()
                self.set_disconnected_state()
        
        # Disconnection request: reset all lists and updates buttons
        else :
            
            self.requester_controller.disconnect()
            
            self.clear_source_group()
            
            self.set_disconnected_state()
                        
            self.statusBar().showMessage('Client disconnected.')            
            
    # Sends a 0x00 command
    def normal_handler (self):
    
        self.requester_controller.execute_command(0x00)
    
    # Sends a 0x01 command
    def adjust_handler(self):
        
        self.requester_controller.execute_command(0x01)
    
    # Sends a 0x05 command
    def confirm_handler(self):
        
        self.requester_controller.execute_command(0x05)

    # Sends a 0xE0 command and updates states of buttons
    def cycle_enable_handler(self):
        
        self.requester_controller.execute_command(0xE0)
        
        self.button_normal.setEnabled(False)
        self.button_adjust.setEnabled(False)
        self.button_cycle_enable.setEnabled(False)
        self.button_cycle_abort.setEnabled(True)
        self.button_confirm.setEnabled(False)
    
    # Sends a 0xE1 command and updates states of buttons
    def cycle_abort_handler(self):
        
        self.requester_controller.execute_command(0xE1)
        
        self.button_normal.setEnabled(True)
        self.button_adjust.setEnabled(True)
        self.button_cycle_enable.setEnabled(True)
        self.button_cycle_abort.setEnabled(False)
        self.button_confirm.setEnabled(True)
        
    # Handles push-button event and shows the associated SourceWindow object 
    def source_handler(self):
        
        sender = self.sender()
        j = 0
        
        for i in self.board_buttons_list:
            
            if sender == i:
                break
            
            j = j + 1
            
        self.board_source_windows_list[j].show()
        
        self.statusBar().showMessage(sender.text() + ' was pressed')
    
    # Update flag in order to reader thread to acknowledge it 
    def closeEvent(self, *args, **kwargs):
        
        self.is_closed = 1
        
        return QMainWindow.closeEvent(self, *args, **kwargs)
    
    # Updates all SourceWindow objects 
    def paintEvent(self, *args, **kwargs):
        
        for b in self.board_source_windows_list:
            b.update()
        
        return QMainWindow.paintEvent(self, *args, **kwargs)
Exemplo n.º 5
0
class AuthenticationFrontend(ScrollArea):
    COMPONENT = 'auth_cert'
    LABEL = tr('Authentication server')
    REQUIREMENTS = ('auth_cert',)
    ICON = ':/icons/auth_protocol.png'

    def __init__(self, client, parent):
        self.__loading = True
        ScrollArea.__init__(self)
        self.mainwindow = parent
        self.client = client
        self.modified = False

        self.qauthcertobject = QAuthCertObject.getInstance()

        frame = QFrame(self)

        layout = QVBoxLayout(frame)

        layout.addWidget(QLabel('<H1>%s</H1>' % tr('Authentication server') ))

        head_box = QGroupBox(tr("How the authentication server handles certificates"))
        head = QFormLayout(head_box)
        self.strictCheckBox = QCheckBox()
        head.addRow(QLabel(tr("Strict mode (check the client's certificate against the installed CA)")), self.strictCheckBox)
        self.connect(self.strictCheckBox, SIGNAL('toggled(bool)'),
                     self.setStrict)

        self.cl_auth_box = QGroupBox(tr("Client authentication with a certificate is"))
        cl_auth = QVBoxLayout(self.cl_auth_box)
        self.auth_by_cert = QButtonGroup()
        self.auth_by_cert.setExclusive(True)

        self.mainwindow.writeAccessNeeded(self.strictCheckBox)

        labels = [tr('forbidden'), tr('allowed'), tr('mandatory')]
        for index, label_button in enumerate(labels):
            button = QRadioButton(label_button)
            self.auth_by_cert.addButton(button, index)
            cl_auth.addWidget(button)
            self.mainwindow.writeAccessNeeded(button)
        self.auth_by_cert.button(0).setChecked(Qt.Checked)
        self.connect(self.auth_by_cert, SIGNAL('buttonClicked(int)'),
                     self.auth_by_cert_modified)


        # Captive portal
        # --------------
        self.portal_groupbox = QGroupBox(tr("Captive portal"))
        self.portal_groupbox.setLayout(QVBoxLayout())

        # Enabled checkbox:
        self.portal_checkbox = QCheckBox(tr("Enable captive portal"))
        self.connect(self.portal_checkbox, SIGNAL('toggled(bool)'),
                     self.setPortalEnabled)

        # List of networks redirected to the captive portal:
        self.portal_nets_groupbox = QGroupBox(
            tr("Networks handled by the captive portal"))
        self.portal_nets_groupbox.setLayout(QVBoxLayout())
        self.portal_nets_edit = NetworkListEdit()
        self.connect(self.portal_nets_edit, SIGNAL('textChanged()'), self.setPortalNets)
        self.portal_nets_groupbox.layout().addWidget(self.portal_nets_edit)

        # Pack the widgets:
        for widget in (self.portal_checkbox, self.portal_nets_groupbox):
            self.portal_groupbox.layout().addWidget(widget)
        self.mainwindow.writeAccessNeeded(self.portal_checkbox)
        self.mainwindow.writeAccessNeeded(self.portal_nets_edit)

        if not EDENWALL:
            self.portal_groupbox.setVisible(False)


        # authentication server
        self.pki_widget = PkiEmbedWidget(self.client, self, 'auth_cert', PkiEmbedWidget.SHOW_ALL|PkiEmbedWidget.CRL_OPTIONAL, self.setModified)
        self.mainwindow.writeAccessNeeded(self.pki_widget)

        layout.addWidget(head_box)
        layout.addWidget(self.cl_auth_box)
        layout.addWidget(self.portal_groupbox)
        layout.addWidget(self.pki_widget)
        layout.addStretch()
        self.setWidget(frame)
        self.setWidgetResizable(True)

        self.resetConf()
        self.__loading = False

    def setModified(self, isModified=True, message=""):
        if self.__loading:
            return
        if isModified:
            self.modified = True
            self.mainwindow.setModified(self, True)
            if message:
                self.mainwindow.addToInfoArea(message)
        else:
            self.modified = False

    def setModifiedCallback(self, *unused):
        self.setModified()

    def isModified(self):
        return self.modified

    def saveConf(self, message):
        self.qauthcertobject.auth_cert.auth_by_cert = self.auth_by_cert.checkedId()

        conf = self.pki_widget.getConfig()
        self.qauthcertobject.auth_cert.setSSLDict(conf)

        serialized = self.qauthcertobject.auth_cert.serialize(downgrade=True)
        self.client.call('auth_cert', 'setAuthCertConfig', serialized, message)

    def resetConf(self):
        auth_cert_loaded = self._reset_helper(
            'auth_cert',
            'getAuthCertConfig',
            self.qauthcertobject,
            tr("Authentication interface enabled"),
            tr("Authentication disabled: backend not loaded")
        )
        self.setModified(False)

        remote = self.qauthcertobject.auth_cert.getReceivedSerialVersion()
        if remote < 3:
            self.mainwindow.addWarningMessage(tr('Captive portal configuration disabled: this frontend and your appliance software versions are not compatible.'))
        enable_portal = (
            auth_cert_loaded
            and EDENWALL
            and remote >= 3
            )
        self.portal_groupbox.setVisible(enable_portal)

        if not auth_cert_loaded:
            return


        self.strictCheckBox.setChecked(self.qauthcertobject.auth_cert.strict)
        if not self.qauthcertobject.auth_cert.auth_by_cert:
            self.qauthcertobject.auth_cert.auth_by_cert = 0
        self.auth_by_cert.button(
            self.qauthcertobject.auth_cert.auth_by_cert).setChecked(True)

        # Captive portal:
        self.portal_checkbox.setChecked(
            self.qauthcertobject.auth_cert.portal_enabled)
        self.portal_nets_edit.setIpAddrs(
            self.qauthcertobject.auth_cert.portal_nets)

        # Certificate (PKI):
        pki_conf = self.qauthcertobject.auth_cert.getSSLDict()
        self.pki_widget.setConfig(pki_conf)

    def error(self, message):
        self.mainwindow.addToInfoArea(message, category=COLOR_ERROR)

    def auth_by_cert_modified(self, idbox):
        button_name = self.auth_by_cert.button(idbox).text()
        info = tr("Certificates - Authentication with client certificate : '%s'") % button_name
        self.setModified(message=info)

    def setPortalEnabled(self, value):
        if value != self.qauthcertobject.auth_cert.portal_enabled:
            self.qauthcertobject.auth_cert.setPortalEnabled(value)
            self.setModified()

    def setPortalNets(self):
        if self.portal_nets_edit.isValid():
            self.qauthcertobject.auth_cert.setPortalNets(
                self.portal_nets_edit.value())
            self.setModified()

    def setStrict(self, value):
        if value != self.qauthcertobject.auth_cert.strict:
            self.qauthcertobject.auth_cert.setStrict(value)
            self.setModified()
        self.cl_auth_box.setEnabled(value)

    def isValid(self):
        cert_validity = self.pki_widget.validate()
        if cert_validity is not None:
            self.error_message = '<br/>' + cert_validity + '<br/>'
            self.mainwindow.addToInfoArea(cert_validity, category=COLOR_ERROR)
            return False
        return True

    def onApplyFinished(self):
        self.pki_widget.feed()
Exemplo n.º 6
0
class ProgressDialog(Ui_ProgressDialog, DialogBase):
    def __init__(self, publisher, plugin, parentWidget=None):
        DialogBase.__init__(self, parentWidget)
        self.setupUi(self)
        self.setObjectName("ProgressDialog")
        self.viewButton_.setEnabled(False)

        self._publisher = publisher
        self._plugin = plugin
        self._parent = parentWidget
        self._cancelled = False
        self._timeline = QTimeLine(1000 * 60, self)
        self._timeline.setFrameRange(0, 2 * 60)
        self._timeline.setLoopCount(0)
        self.progressBar_.setRange(0, 60)
        self.connect(self._timeline, QtCore.SIGNAL("frameChanged(int)"),
                     self.updateProgressBar)

        self.outputGroupBox_ = QGroupBox("Script output", None)

        self.outputTextEdit_ = QTextEdit()
        self.outputTextEdit_.setTextInteractionFlags(
            Qt.TextSelectableByKeyboard
            | Qt.TextSelectableByMouse)
        self.outputTextEdit_.setReadOnly(True)
        self.outputTextEdit_.setTabChangesFocus(True)
        self.outputTextEdit_.setAcceptRichText(False)

        groupBoxLayout = QVBoxLayout()
        groupBoxLayout.setObjectName("groupBoxLayout")
        groupBoxLayout.setMargin(0)
        groupBoxLayout.addWidget(self.outputTextEdit_)
        self.outputGroupBox_.setLayout(groupBoxLayout)

        gridLayout = QGridLayout()
        gridLayout.setSizeConstraint(gridLayout.SetFixedSize)
        gridLayout.addWidget(self.progressLabel_, 0, 0, 1, 4)
        gridLayout.addWidget(self.progressBar_, 1, 0, 1, 4)
        gridLayout.addWidget(self.detailsCheckBox_, 2, 0)
        hSpacer = QSpacerItem(250, 10, QSizePolicy.Expanding)
        gridLayout.addItem(hSpacer, 2, 1)

        gridLayout.addWidget(self.viewButton_, 2, 2)
        gridLayout.addWidget(self.cancelButton_, 2, 3)
        gridLayout.addWidget(self.outputGroupBox_, 3, 0, 1, 4)

        self.setLayout(gridLayout)

        self.outputGroupBox_.setVisible(False)

    def updateProgressBar(self, frame):
        self.progressBar_.setValue(self.progressBar_.value() + 1)

    def on_detailsCheckBox__stateChanged(self, state):
        self.outputGroupBox_.setVisible(Qt.Checked == state)
        gridLayout = self.layout()
        if Qt.Checked == state:
            gridLayout.setSizeConstraint(gridLayout.SetMaximumSize)
            self.setSizeGripEnabled(True)
        else:
            gridLayout.setSizeConstraint(gridLayout.SetFixedSize)
            self.setSizeGripEnabled(False)

    def on_cancelButton__clicked(self, released=True):
        if not released:
            return

        if self._cancelled:
            self.reject()
            return

        self.cancelButton_.setEnabled(False)
        self.progressLabel_.setText("Cancelling...")
        self._publisher.cancel()
        self._cancelled = True
        QTimer.singleShot(5 * 1000, self, QtCore.SLOT("_kill()"))

    @QtCore.pyqtSignature("_kill()")
    def _cancel(self):
        self._parent.update()
        self._publisher.cancel(True)
        self.reject()

    def updatePublisherOutput(self, data):
        self.outputTextEdit_.append(data)

    def publishComplete(self, exitCode, exitStatus):
        self.progressBar_.setValue(self.progressBar_.maximum())
        self._timeline.stop()
        if self._cancelled:
            self.reject()
        self._cancelled = True
        publishSuccess = (0 == exitCode and QProcess.NormalExit == exitStatus)
        output_exists = self.__findOutput()
        self.viewButton_.setEnabled(publishSuccess and \
                                    output_exists)
        if not publishSuccess:
            self.progressLabel_.setText("Publishing failed, see script output"
                                        " for more details")
        else:
            self.progressLabel_.setText("Publishing completed")

    def __findOutput(self):
        output_exists = os.path.exists(unicode(self._outFile))
        if not output_exists:
            output_exists = self.__findInSubdir()
        if not (output_exists) and ('Dita' in self._publisher.__str__()):
            output_exists = self.__findInLog()
        if not (output_exists) and ('Docbook' in self._publisher.__str__()):
            output_exists = self.__findInPI()
        return output_exists

    def __findInLog(self):
        log = self.outputTextEdit_.toPlainText()
        src_filename = os.path.basename(self._publisher.attrs()['srcUri'])
        dst_filename = src_filename.split(
            '.')[0] + "." + self._publisher.attrs()['extension']
        re_str = '\[xslt\] Processing.*?' + src_filename + ' to (?P<outputFilename>.*?' + dst_filename + ')'
        output_re = re.compile(re_str)
        output_filename = ''
        if None != output_re.search(log):
            output_filename = output_re.search(log).group("outputFilename")
        if not output_filename:
            return False
        real_dst_dir = os.path.dirname(unicode(output_filename))
        dst_filename = os.path.join(real_dst_dir,
                                    os.path.basename(self._outFile))
        os.rename(output_filename, dst_filename)
        output_exists = os.path.exists(dst_filename)
        if output_exists:
            self._outFile = dst_filename
            self._parent.setOutputFilePath(self._outFile)
            return True
        return False

    def __findInPI(self):
        src_uri = self._publisher.attrs()['srcUri']
        grove = Grove.buildGroveFromFile(src_uri)
        xpath_value = XpathExpr(
            "//self::processing-instruction('dbhtml')").eval(grove.document())
        dbhtml_pi = xpath_value.getNodeSet().firstNode()
        str_ = unicode(dbhtml_pi.asGrovePi().data())
        filename_re = re.compile('filename="(?P<filename>.*?\n?.*?)"')
        dir_re = re.compile('dir="(?P<dir>.*?\n?.*?)"')
        if None != filename_re.search(str_):
            filename_ = filename_re.search(str_).group("filename")
        if None != dir_re.search(str_):
            dir_ = dir_re.search(str_).group("dir")
        out_dir = os.path.dirname(self._outFile)
        combined_output_filename = os.path.join(out_dir, dir_, filename_)
        output_exists = os.path.exists(combined_output_filename)
        if output_exists:
            self._outFile = combined_output_filename
            self._parent.setOutputFilePath(self._outFile)
            return True
        return False

    def __findInSubdir(self):
        output_filename = unicode(self._outFile)
        filename_ = os.path.basename(output_filename)
        dir_ = os.path.dirname(output_filename)
        folder_name = os.path.basename(dir_)
        output_filename = os.path.join(dir_, folder_name, filename_)
        output_exists = os.path.exists(output_filename)
        if output_exists:
            self._outFile = output_filename
            self._parent.setOutputFilePath(self._outFile)
            return True
        return False

    def on_viewButton__clicked(self, released=True):
        if not released:
            return
        self._plugin.launchViewer(os.path.abspath(self._outFile))

    def publish(self, dsi, outFile):
        if not self._publisher:
            self.updatePublisherOutput("Script is not found")
            self.publishComplete(1, QProcess.Crashed)
            return self.exec_()
        self._outFile = outFile
        self.show()
        try:
            self.progressBar_.setValue(self.progressBar_.minimum() + 1)
            self._publisher.publish(self, dsi, outFile)
            self._timeline.start()
        except PublishException, pe:
            self.updatePublisherOutput(pe.getErrorString())
        return self.exec_()