Beispiel #1
0
class TaskTreeDialogUi(object):

    def setupUi(self, dialog, hiddenTask=None):
        
        dialog.setObjectName("dialog")
        dialog.resize(300, 300)
        self.gridlayout = QGridLayout(dialog)
        self.gridlayout.setMargin(9)
        self.gridlayout.setSpacing(6)
        self.gridlayout.setObjectName("gridlayout")

        self.taskTreeWidget = TaskTree(mainWindow=dialog.parent(), makeActions=False, hiddenTask=hiddenTask)
        self.gridlayout.addWidget(self.taskTreeWidget, 0, 0, 1, 1)
      
        self.buttonBox = QDialogButtonBox(dialog)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.NoButton | QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        self.gridlayout.addWidget(self.buttonBox, 1, 0, 1, 1)

        self.retranslateUi(dialog)
        self.buttonBox.accepted.connect(dialog.accept)
        self.buttonBox.rejected.connect(dialog.reject)
        QMetaObject.connectSlotsByName(dialog)
        
    def retranslateUi(self, dialog):
        dialog.setWindowTitle(i18n("Task Selection"))
Beispiel #2
0
class TypeChooserDialog(QDialog):
    def __init__(self, parent=None, mainWindow=None, typesUris=None):

        super(TypeChooserDialog, self).__init__(parent)
        self.mainWindow = mainWindow
        if self.mainWindow:
            self.mainWindow.setCursor(Qt.WaitCursor)
        self.typesUris = typesUris
        self.setupUi(self)
        self.validate()
        if self.mainWindow:
            self.mainWindow.unsetCursor()

    def validate(self):
        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True)

    def selectedResources(self):
        if len(self.table.selectedObjects()) > 0:
            return self.table.selectedObjects()
        return None

    def chosenTypes(self):
        return self.table.model.resources

    def accept(self):

        QDialog.accept(self)

    def sizeHint(self):
        return QSize(600, 300)

    def setupUi(self, dialog):
        dialog.setObjectName("dialog")
        self.gridlayout = QGridLayout(dialog)
        self.gridlayout.setMargin(9)
        self.gridlayout.setSpacing(6)
        self.gridlayout.setObjectName("gridlayout")

        self.table = TypesTable(mainWindow=dialog.mainWindow,
                                typesUris=self.typesUris,
                                dialog=self)

        self.gridlayout.addWidget(self.table, 0, 0, 1, 1)

        self.buttonBox = QDialogButtonBox(dialog)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.NoButton
                                          | QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        self.gridlayout.addWidget(self.buttonBox, 1, 0, 1, 1)

        self.buttonBox.accepted.connect(dialog.accept)
        self.buttonBox.rejected.connect(dialog.reject)

        self.setWindowTitle(i18n("Types"))
        QMetaObject.connectSlotsByName(dialog)
class DlgGeoBorderDataEdit(QDialog):
    def __init__(self, parent, title, valueList=None):
        QDialog.__init__(self, parent)

        self.resize(100, 70)
        self.setWindowTitle(title)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        verticalLayoutDlg = QVBoxLayout(self)
        verticalLayoutDlg.setObjectName(("verticalLayoutDlg"))

        self.frameBasic = Frame(self)
        verticalLayoutDlg.addWidget(self.frameBasic)

        self.pnlName = TextBoxPanel(self.frameBasic)
        self.pnlName.Caption = "Name"
        self.pnlName.LabelWidth = 120
        self.frameBasic.Add = self.pnlName

        self.pnlType = ComboBoxPanel(self.frameBasic)
        self.pnlType.Caption = "Type"
        self.pnlType.LabelWidth = 120
        self.frameBasic.Add = self.pnlType

        self.btnBoxOkCancel = QDialogButtonBox(self)
        self.btnBoxOkCancel.setObjectName(("btnBoxOkCancel"))
        self.btnBoxOkCancel.setStandardButtons(QDialogButtonBox.Cancel
                                               | QDialogButtonBox.Ok)
        self.connect(self.btnBoxOkCancel, SIGNAL("accepted()"), self.acceptDlg)
        self.connect(self.btnBoxOkCancel, SIGNAL("rejected()"), self.reject)

        verticalLayoutDlg.addWidget(self.btnBoxOkCancel)

        self.name = ""
        self.type = ""
        self.pnlType.Items = ["ST", "TW", "CS", "RW", "RB", "OTHER"]
        if valueList != None:
            self.pnlName.Value = valueList[0]
            self.pnlType.Value = valueList[1]

    def acceptDlg(self):
        self.name = self.pnlName.Value
        self.type = self.pnlType.SelectedItem
        self.accept()
class DlgQaComment(QDialog):
    def __init__(self, parent=None, string_0=None):
        QDialog.__init__(self, parent)

        self.resize(100, 70)
        self.setWindowTitle("Edit Comment")
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        verticalLayoutDlg = QVBoxLayout(self)
        verticalLayoutDlg.setObjectName(("verticalLayoutDlg"))

        self.txtComment = TextBoxPanel(self)
        self.txtComment.Caption = ""
        self.txtComment.LabelWidth = 0
        verticalLayoutDlg.addWidget(self.txtComment)

        self.btnBoxOkCancel = QDialogButtonBox(self)
        self.btnBoxOkCancel.setObjectName(("btnBoxOkCancel"))
        self.btnBoxOkCancel.setStandardButtons(QDialogButtonBox.Cancel
                                               | QDialogButtonBox.Ok)
        self.btnOK = self.btnBoxOkCancel.button(QDialogButtonBox.Ok)
        # btnOK.setText("Create")
        self.connect(self.btnBoxOkCancel, SIGNAL("accepted()"), self.acceptDlg)
        self.connect(self.btnBoxOkCancel, SIGNAL("rejected()"), self.reject)
        self.connect(self.txtComment, SIGNAL("Event_0"),
                     self.txtComment_TextChanged)

        self.txtComment.Value = string_0
        self.btnOK.setEnabled(False)

    def chbLimit_Event_0(self):
        self.txtLimit.Enabled = self.chbLimit.Checked

    def acceptDlg(self):
        self.accept()

    def txtComment_TextChanged(self):
        self.btnOK.setEnabled(self.txtComment.Value.trimmed() != "")

    def getComment(self):
        return self.txtComment.Value

    Comment = property(getComment, None, None, None)
Beispiel #5
0
class ResourceChooserDialogUi(object):
    def setupUi(self, dialog, nepomukType=None, excludeList=None):

        self.dialog = dialog
        dialog.setObjectName("dialog")
        dialog.resize(500, 300)
        self.gridlayout = QGridLayout(dialog)
        self.gridlayout.setMargin(9)
        self.gridlayout.setSpacing(6)
        self.gridlayout.setObjectName("gridlayout")

        self.table = ResourcesByTypeTable(mainWindow=dialog.parent(),
                                          nepomukType=nepomukType,
                                          excludeList=excludeList,
                                          dialog=self)
        self.table.table.setColumnWidth(0, 250)

        self.gridlayout.addWidget(self.table, 0, 0, 1, 1)

        self.buttonBox = QDialogButtonBox(dialog)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.NoButton
                                          | QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        self.gridlayout.addWidget(self.buttonBox, 1, 0, 1, 1)

        self.retranslateUi(dialog)

        self.table.table.activated.connect(self.activated)

        self.buttonBox.accepted.connect(dialog.accept)
        self.buttonBox.rejected.connect(dialog.reject)
        QMetaObject.connectSlotsByName(dialog)

        #dialog.setTabOrder(self.firstname, self.yearSpinBox)
        #dialog.setTabOrder(self.yearSpinBox, self.minutesSpinBox)

    def activated(self, index):
        if index.isValid():
            self.dialog.accept()

    def retranslateUi(self, dialog):
        dialog.setWindowTitle(i18n("Link to..."))
Beispiel #6
0
class ResourceChooserDialogUi(object):

    def setupUi(self, dialog, nepomukType=None, excludeList=None):
        
        self.dialog = dialog
        dialog.setObjectName("dialog")
        dialog.resize(500, 300)
        self.gridlayout = QGridLayout(dialog)
        self.gridlayout.setMargin(9)
        self.gridlayout.setSpacing(6)
        self.gridlayout.setObjectName("gridlayout")

        self.table = ResourcesByTypeTable(mainWindow=dialog.parent(), nepomukType=nepomukType, excludeList=excludeList, dialog=self)
        self.table.table.setColumnWidth(0,250)
        
        self.gridlayout.addWidget(self.table, 0, 0, 1, 1)
      
        self.buttonBox = QDialogButtonBox(dialog)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.NoButton | QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        self.gridlayout.addWidget(self.buttonBox, 1, 0, 1, 1)

        self.retranslateUi(dialog)
      
        self.table.table.activated.connect(self.activated)
        
        self.buttonBox.accepted.connect(dialog.accept)
        self.buttonBox.rejected.connect(dialog.reject)
        QMetaObject.connectSlotsByName(dialog)
        
        #dialog.setTabOrder(self.firstname, self.yearSpinBox)
        #dialog.setTabOrder(self.yearSpinBox, self.minutesSpinBox)
        
    def activated(self, index):
        if index.isValid():
            self.dialog.accept()

    def retranslateUi(self, dialog):
        dialog.setWindowTitle(i18n("Link to..."))
Beispiel #7
0
    def setupUi( self ):
        self.setObjectName( "frmAnulaciones" )
        self.setWindowTitle( "Seleccione la factura a anular" )
        self.resize( 485, 300 )
        gridLayout = QGridLayout( self )
        gridLayout.setObjectName( "gridLayout" )
        lblnfactura = QLabel( self )
        lblnfactura.setObjectName( "lblnfactura" )
        lblnfactura.setText( "# Factura" )
        gridLayout.addWidget( lblnfactura, 0, 0, 1, 1 )
        self.lblnfactura2 = QLabel( self )
        self.lblnfactura2.setFrameShape( QFrame.Box )
        self.lblnfactura2.setText( "" )
        self.lblnfactura2.setObjectName( "lblnfactura2" )
        gridLayout.addWidget( self.lblnfactura2, 0, 1, 1, 1 )
        lblconcepto = QLabel( self )
        lblconcepto.setObjectName( "lblconcepto" )
        lblconcepto.setText( "Concepto" )
        gridLayout.addWidget( lblconcepto, 1, 0, 1, 1 )


        gridLayout.addWidget( self.cboConceptos, 1, 1, 1, 1 )
        lblobservaciones = QLabel( self )
        lblobservaciones.setObjectName( "lblobservaciones" )
        lblobservaciones.setText( "Observaciones" )
        gridLayout.addWidget( lblobservaciones, 2, 0, 1, 1 )


        gridLayout.addWidget( self.txtObservaciones, 3, 1, 1, 1 )
        buttonBox = QDialogButtonBox( self )
        buttonBox.setOrientation( Qt.Horizontal )
        buttonBox.setStandardButtons( QDialogButtonBox.Cancel |
                                      QDialogButtonBox.Ok )
        buttonBox.setObjectName( "buttonBox" )
        gridLayout.addWidget( buttonBox, 4, 0, 1, 2 )

        buttonBox.accepted.connect( self.accept )
        buttonBox.rejected.connect( self.reject )
Beispiel #8
0
class DlgChartingTemplate(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)

        self.resize(100, 70)
        self.setWindowTitle("Template Properties")
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        verticalLayoutDlg = QVBoxLayout(self)
        verticalLayoutDlg.setObjectName(("verticalLayoutDlg"))

        self.groupBox1 = GroupBox(self)
        self.groupBox1.Caption = ""
        verticalLayoutDlg.addWidget(self.groupBox1)

        self.pnlSpace = ComboBoxPanel(self.groupBox1)
        self.pnlSpace.Caption = "Target Space"
        self.pnlSpace.LabelWidth = 120
        self.groupBox1.Add = self.pnlSpace

        self.pnlDwg = TextBoxPanel(self.groupBox1)
        self.pnlDwg.Caption = "Drawing File"
        self.pnlDwg.LabelWidth = 120
        self.groupBox1.Add = self.pnlDwg

        self.pnlTitle = TextBoxPanel(self.groupBox1)
        self.pnlTitle.Caption = "Titlee"
        self.pnlTitle.LabelWidth = 120
        self.groupBox1.Add = self.pnlTitle

        self.btnBoxOkCancel = QDialogButtonBox(self)
        self.btnBoxOkCancel.setObjectName(("btnBoxOkCancel"))
        self.btnBoxOkCancel.setStandardButtons(QDialogButtonBox.Cancel
                                               | QDialogButtonBox.Ok)
        # btnOK = self.btnBoxOkCancel.button(QDialogButtonBox.Ok)
        # btnOK.setText("Create")
        self.connect(self.btnBoxOkCancel, SIGNAL("accepted()"), self.acceptDlg)
        self.connect(self.btnBoxOkCancel, SIGNAL("rejected()"), self.reject)

        verticalLayoutDlg.addWidget(self.btnBoxOkCancel)

        self.pnlSpace.Add(DrawingSpace.ModelSpace)
        self.pnlSpace.Add(DrawingSpace.PaperSpace)
        self.pnlSpace.SelectedIndex = 1

        # if (String.IsNullOrEmpty(self.pnlDwg.Value)):
        #     # DlgChartingTemplate height = self
        #     # height.Height = height.Height - self.pnlDwg.Height
        #     self.pnlDwg.Visible = False

        # self.pnlCodeType.Items = CodeTypeDesigPtAixm.Items

    def acceptDlg(self):

        self.accept()

    def get_TemplateDrawing(self):
        return self.pnlDwg.Value

    def set_TemplateDrawing(self, val):
        self.pnlDwg.Value = val

    TemplateDrawing = property(get_TemplateDrawing, set_TemplateDrawing, None,
                               None)

    def get_TemplateSpace(self):
        if (self.pnlSpace.SelectedIndex == 0):
            return DrawingSpace.ModelSpace
        return DrawingSpace.PaperSpace

    def set_TemplateSpace(self, val):
        if (val == DrawingSpace.ModelSpace):
            self.pnlSpace.SelectedIndex = 0
            return
        self.pnlSpace.SelectedIndex = 1

    TemplateSpace = property(get_TemplateSpace, set_TemplateSpace, None, None)

    def get_TemplateTitle(self):
        return self.pnlTitle.Value

    def set_TemplateTitle(self, val):
        self.pnlTitle.Value = val

    TemplateTitle = property(get_TemplateTitle, set_TemplateTitle, None, None)

    @staticmethod
    def smethod_0(parent, string_0, drawingSpace_0, string_1):
        flag = False
        dlgChartingTemplate = DlgChartingTemplate(parent)
        dlgChartingTemplate.TemplateTitle = string_0
        dlgChartingTemplate.TemplateDrawing = string_1
        dlgChartingTemplate.TemplateSpace = drawingSpace_0
        result = dlgChartingTemplate.exec_()
        if (not result):
            flag = False
        else:
            string_0 = dlgChartingTemplate.TemplateTitle
            drawingSpace_0 = dlgChartingTemplate.TemplateSpace
            flag = True
        return flag, string_0, drawingSpace_0

    @staticmethod
    def smethod_1(parent, string_0, drawingSpace_0):
        flag = False
        dlgChartingTemplate = DlgChartingTemplate(parent)
        dlgChartingTemplate.TemplateTitle = string_0
        dlgChartingTemplate.TemplateSpace = drawingSpace_0
        result = dlgChartingTemplate.exec_()
        if (not result):
            flag = False
        else:
            string_0 = dlgChartingTemplate.TemplateTitle
            drawingSpace_0 = dlgChartingTemplate.TemplateSpace
            flag = True
        return flag, string_0, drawingSpace_0
class DlgAixmIap(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)

        self.resize(290, 136)
        self.setWindowTitle("Instrument Approach Procedure (IAP)")
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        verticalLayoutDlg = QVBoxLayout(self)
        verticalLayoutDlg.setObjectName(("verticalLayoutDlg"))

        self.groupBox = GroupBox(self)
        verticalLayoutDlg.addWidget(self.groupBox)

        self.pnlAerodrome = ComboBoxPanel(self.groupBox)
        self.pnlAerodrome.Caption = "Aerodrome"
        self.groupBox.Add = self.pnlAerodrome

        self.pnlDesignator = TextBoxPanel(self.groupBox)
        self.pnlDesignator.Caption = "Designator"
        self.groupBox.Add = self.pnlDesignator

        self.pnlAcCategory = ComboBoxPanel(self.groupBox)
        self.pnlAcCategory.Caption = "Ac. Category"
        self.groupBox.Add = self.pnlAcCategory

        self.pnlTransID = TextBoxPanel(self.groupBox)
        self.pnlTransID.Caption = "ransitional Identifier"
        self.groupBox.Add = self.pnlTransID

        self.pnlType = ComboBoxPanel(self.groupBox)
        self.pnlType.Caption = "Type"
        self.groupBox.Add = self.pnlType

        self.pnlRunway = ComboBoxPanel(self.groupBox)
        self.pnlRunway.Caption = "Runway Direction"
        self.groupBox.Add = self.pnlRunway

        self.pnlMSA = ComboBoxPanel(self.groupBox)
        self.pnlMSA.Caption = "MSA Group"
        self.groupBox.Add = self.pnlMSA

        self.pnlRNP = NumberBoxPanel(self.groupBox)
        self.pnlRNP.Caption = "RNP"
        self.groupBox.Add = self.pnlRNP

        self.tableLayoutPanel = Frame(self.groupBox)
        self.groupBox.Add = self.tableLayoutPanel

        self.txtDescription = TextBoxPanel(self.tableLayoutPanel, True)
        self.txtDescription.Caption = "Description"
        self.tableLayoutPanel.Add = self.txtDescription

        self.txtDescrComFail = TextBoxPanel(self.tableLayoutPanel, True)
        self.txtDescrComFail.Caption = "Communication Failure"
        self.tableLayoutPanel.Add = self.txtDescrComFail

        self.txtRemarks = TextBoxPanel(self.tableLayoutPanel, True)
        self.txtRemarks.Caption = "Remarks"
        self.tableLayoutPanel.Add = self.txtRemarks

        self.gbOcaOch = GroupBox(self.groupBox, "HL")
        self.gbOcaOch.Caption = "Minimum OCA/OCH"
        self.groupBox.Add = self.gbOcaOch

        self.gridOcah = QTableView(self.gbOcaOch)
        self.gridOcahModel = StandardItemModel(None, [
            "Ac. Category", "Approach Type", "OCA", "OCH", "OCH Ref.",
            "Remarks"
        ])
        self.gridOcah.setModel(self.gridOcahModel)
        self.gbOcaOch.Add = self.gridOcah

        self.pnlProcButtons = Frame(self.gbOcaOch)
        self.gbOcaOch.Add = self.pnlProcButtons

        self.btnAdd = QPushButton(self.pnlProcButtons)
        icon = QIcon()
        icon.addPixmap(QPixmap("Resource/add.png"), QIcon.Normal, QIcon.Off)
        self.btnAdd.setIcon(icon)
        self.pnlProcButtons.Add = self.btnAdd

        self.btnEdit = QPushButton(self.pnlProcButtons)
        icon = QIcon()
        icon.addPixmap(QPixmap("Resource/mIconEditableEdits.png"),
                       QIcon.Normal, QIcon.Off)
        self.btnEdit.setIcon(icon)
        self.pnlProcButtons.Add = self.btnEdit

        self.btnRemove = QPushButton(self.pnlProcButtons)
        icon = QIcon()
        icon.addPixmap(QPixmap("Resource/remove.png"), QIcon.Normal, QIcon.Off)
        self.btnRemove.setIcon(icon)
        self.pnlProcButtons.Add = self.btnRemove

        self.btnBoxOkCancel = QDialogButtonBox(self)
        self.btnBoxOkCancel.setObjectName(("btnBoxOkCancel"))
        self.btnBoxOkCancel.setStandardButtons(QDialogButtonBox.Cancel
                                               | QDialogButtonBox.Ok)
        self.connect(self.btnBoxOkCancel, SIGNAL("accepted()"), self.acceptDlg)
        self.connect(self.btnBoxOkCancel, SIGNAL("rejected()"), self.reject)

        verticalLayoutDlg.addWidget(self.btnBoxOkCancel)

        self.btnAdd.clicked.connect(self.btnAdd_Click)
        self.btnEdit.clicked.connect(self.btnEdit_Click)
        self.btnRemove.clicked.connect(self.btnRemove_Click)

        self.gridOcah.pressed.connect(self.gridOcah_pressed)

        self.data = None
        self.table = None
        self.selected = None
        self.minimums = None

    def gridOcah_pressed(self):
        self.method_7()

    def btnAdd_Click(self):
        dataBaseIapOcaOch = DataBaseIapOcaOch()
        if (not DlgAixmOcaOch.smethod_0(dataBaseIapOcaOch)):
            return
        self.minimums.Add(dataBaseIapOcaOch)
        self.gridOcahModel.Refresh(self.minimums)
        self.method_7()

    def btnEdit_Click(self):
        selectedIndexes = self.gridOcah.selectedIndexes()
        selectedRow = selectedIndexes[0].row()
        if (DlgAixmOcaOch.smethod_0(self.minimums[selectedRow])):
            self.gridOcahModel.Refresh(self.minimums)
            self.method_7()

    def btnRemove_Click(self):
        selectedIndexes = self.gridOcah.selectedIndexes()
        selectedRow = selectedIndexes[0].row()
        self.minimums.pop(selectedRow)
        self.gridOcahModel.Refresh(self.minimums)
        self.method_7()

    def acceptDlg(self):
        strS = None
        selectedItem = self.pnlAerodrome.SelectedItem
        num = (self.pnlAcCategory.SelectedIndex >=
               0) and self.pnlAcCategory.SelectedIndex or -1
        for row in self.table:
            flag = True
            if (self.selected != None and row == self.selected):
                flag = False
            if (row["ahpEnt"] != selectedItem):
                flag = False
            if (not self.pnlDesignator.Value == row["txtDesig"]):
                flag = False
            if (num != (row["codeCatAcft"] == None) and -1
                    or int(row["codeCatAcft"])):
                flag = False
            strS = (row["codeTransId"] == None) and "" or row["codeTransId"]
            if (not self.pnlTransID.Value == strS):
                flag = False
            if (not flag):
                continue
            str1 = "Cannot create a duplicate procedure entry.\n\nAerodrome = {0}\nDesignator = {1}".format(
                self.pnlAerodrome.SelectedItem, self.pnlDesignator.Value)
            if (self.pnlAcCategory.SelectedIndex >= 0):
                str1 = String.Concat([
                    str1, "\nAc. Category = {0}".format(
                        self.pnlAcCategory.SelectedItem)
                ])
            if (not String.IsNullOrEmpty(self.pnlTransID.Value)):
                str1 = String.Concat([
                    str1, "\nTransition Identifier = {0}".format(
                        self.pnlTransID.Value)
                ])
            QMessageBox.warning(self, "Error", str1)
            return
        self.accept()

    def method_5(self):
        self.data.method_35(self.pnlRunway.Items,
                            self.pnlAerodrome.SelectedItem)
        # self.pnlRunway.comboBox.insertItem(0, "");

    def method_6(self):
        self.btnEdit_Click()

    def method_7(self):
        self.btnEdit.setEnabled(len(self.gridOcah.selectedIndexes()) == 1)
        self.btnRemove.setEnabled(len(self.gridOcah.selectedIndexes()) == 1)

    @staticmethod
    def smethod_0(dataBaseIAPs_0, dataBaseProcedureData_0, dataRow_0):
        flag = False
        dlgAixmIap = DlgAixmIap()
        dlgAixmIap.data = dataBaseProcedureData_0
        dlgAixmIap.table = dataBaseIAPs_0
        dlgAixmIap.selected = dataRow_0
        dataBaseProcedureData_0.method_51(dlgAixmIap.pnlAerodrome)
        dataBaseProcedureData_0.method_47(dlgAixmIap.pnlMSA)
        dlgAixmIap.pnlAcCategory.Items = CodeCatAcftAixm.Items
        dlgAixmIap.pnlType.Items = CodeTypeIapAixm.Items
        # dlgAixmIap.pnlAcCategory.Insert(0, "");
        # dlgAixmIap.pnlMSA.Items.Insert(0, "");
        if (dataRow_0 != None and len(dataRow_0) != 0):
            dlgAixmIap.pnlAerodrome.SelectedIndex = dlgAixmIap.pnlAerodrome.IndexOf(
                dataRow_0["ahpEnt"])
            if (dlgAixmIap.pnlAerodrome.SelectedIndex >= 0):
                dataBaseProcedureData_0.method_35(
                    dlgAixmIap.pnlRunway, dlgAixmIap.pnlAerodrome.SelectedItem)
                # dlgAixmIap.pnlRunway.Insert(0, "");
            dlgAixmIap.pnlDesignator.Value = dataRow_0["txtDesig"]
            if (dataRow_0["codeCatAcft"] != None):
                dlgAixmIap.pnlAcCategory.SelectedIndex = dlgAixmIap.pnlAcCategory.method_3(
                    dataRow_0["codeCatAcft"])
            if (dataRow_0["codeTransId"] != None):
                dlgAixmIap.pnlTransID.Value = dataRow_0["codeTransId"]
            if (dataRow_0["rdnEnt"] != None):
                dlgAixmIap.pnlRunway.SelectedIndex = dlgAixmIap.pnlRunway.IndexOf(
                    dataRow_0["rdnEnt"])
            if (dataRow_0["mgpEnt"] != None):
                dlgAixmIap.pnlMSA.SelectedIndex = dlgAixmIap.pnlMSA.IndexOf(
                    dataRow_0["mgpEnt"])
            if (dataRow_0["codeRnp"] != None):
                dlgAixmIap.pnlRNP.Value = dataRow_0["codeRnp"]
            if (dataRow_0["txtDescrComFail"] != None):
                dlgAixmIap.txtDescrComFail.Value = dataRow_0["txtDescrComFail"]
            dlgAixmIap.pnlType.SelectedIndex = dlgAixmIap.pnlType.method_3(
                dataRow_0["codeTypeRte"])
            if (dataRow_0["txtDescrMiss"] != None):
                dlgAixmIap.txtDescription.Value = dataRow_0["txtDescrMiss"]
            if (dataRow_0["txtRmk"] != None):
                dlgAixmIap.txtRemarks.Value = dataRow_0["txtRmk"]
            dlgAixmIap.minimums = dataRow_0["ocah"]
        if (dlgAixmIap.minimums == None):
            dlgAixmIap.minimums = DataBaseIapOcaOchs()
        dlgAixmIap.gridOcahModel.DataSource = dlgAixmIap.minimums
        resultDlg = dlgAixmIap.exec_()
        if resultDlg == 1:
            dataRow0 = dataRow_0 == None or len(dataRow_0) == 0
            strS = []
            if (not dataRow0):
                for i in range(len(dataBaseIAPs_0.nameList)):
                    strS.append(None)
                # strS = new string[dataBaseIAPs_0.Columns.Count];
                i = 0
                for name in dataBaseIAPs_0.nameList:
                    strS[i] = dataRow_0[name]
                    i += 1
            else:
                dataRow_0 = dataBaseIAPs_0.NewRow()
            dataRow_0["ahpEnt"] = dlgAixmIap.pnlAerodrome.SelectedItem
            if (dataRow0):
                dataRow_0["oldAhpEnt"] = dataRow_0["ahpEnt"]
            dataRow_0["txtDesig"] = dlgAixmIap.pnlDesignator.Value
            if (dataRow0):
                dataRow_0["oldTxtDesig"] = dataRow_0["txtDesig"]
            if (dlgAixmIap.pnlAcCategory.SelectedIndex >= 0):
                dataRow_0[
                    "codeCatAcft"] = dlgAixmIap.pnlAcCategory.SelectedItem
            else:
                dataRow_0["codeCatAcft"] = None
            if (dataRow0):
                dataRow_0["oldCodeCatAcft"] = dataRow_0["codeCatAcft"]
            if (not String.IsNullOrEmpty(dlgAixmIap.pnlTransID.Value)):
                dataRow_0["codeTransId"] = dlgAixmIap.pnlTransID.Value
            else:
                dataRow_0["codeTransId"] = None
            if (dataRow0):
                dataRow_0["oldCodeTransId"] = dataRow_0["codeTransId"]
            if (dlgAixmIap.pnlRunway.SelectedIndex >= 0):
                dataRow_0["rdnEnt"] = dlgAixmIap.pnlRunway.SelectedItem
            else:
                dataRow_0["rdnEnt"] = None
            if (dlgAixmIap.pnlMSA.SelectedIndex >= 0):
                dataRow_0["mgpEnt"] = dlgAixmIap.pnlMSA.SelectedItem
            else:
                dataRow_0["mgpEnt"] = None
            if (not math.isnan(dlgAixmIap.pnlRNP.Value)
                    and not math.isinf(dlgAixmIap.pnlRNP.Value)):
                dataRow_0["codeRnp"] = dlgAixmIap.pnlRNP.Value
            else:
                dataRow_0["codeRnp"] = None
            dataRow_0["codeTypeRte"] = dlgAixmIap.pnlType.SelectedItem
            if (not String.IsNullOrEmpty(dlgAixmIap.txtDescrComFail.Value)):
                dataRow_0["txtDescrComFail"] = dlgAixmIap.txtDescrComFail.Value
            else:
                dataRow_0["txtDescrComFail"] = None
            if (not String.IsNullOrEmpty(dlgAixmIap.txtDescription.Value)):
                dataRow_0["txtDescrMiss"] = dlgAixmIap.txtDescription.Value
            else:
                dataRow_0["txtDescrMiss"] = None
            if (not String.IsNullOrEmpty(dlgAixmIap.txtRemarks.Value)):
                dataRow_0["txtRmk"] = dlgAixmIap.txtRemarks.Value
            else:
                dataRow_0["txtRmk"] = None
            dataRow_0["ocah"] = dlgAixmIap.minimums
            if (dataRow0):
                dataRow_0["procLegs"] = DataBaseProcedureLegs()
                dataRow_0["procLegsEx"] = DataBaseProcedureLegsEx()
            if (not dataRow0):
                num = 1
                while (num < len(strS)):
                    if (not strS[num] == dataRow_0[dataRow_0.nameList[num]]):
                        dataRow_0["changed"] = "True"
                        if (dataRow0):
                            dataBaseIAPs_0.RowsAdd(dataRow_0)
                        flag = True
                        return flag
                    else:
                        num += 1
            else:
                dataRow_0["new"] = "True"
            if (dataRow0):
                dataBaseIAPs_0.RowsAdd(dataRow_0)
            flag = True
            return flag
        return flag
Beispiel #10
0
class DlgQaHeading(QDialog):
    rowLimit = 0
    ignoreNAcolumns = False

    def __init__(self, parent=None, bool_0=None):
        QDialog.__init__(self, parent)

        self.resize(100, 70)
        self.setWindowTitle("QA Entry")
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        verticalLayoutDlg = QVBoxLayout(self)
        verticalLayoutDlg.setObjectName(("verticalLayoutDlg"))

        self.groupBox = GroupBox(self)
        self.groupBox.Caption = ""
        verticalLayoutDlg.addWidget(self.groupBox)

        # self.lblHeading = TextBoxPanel(self.groupBox)
        # self.lblHeading.Enabled = False
        # self.lblHeading.Caption = "Title"
        # self.lblHeading.LabelWidth = 120
        # self.groupBox.Add = self.lblHeading

        self.txtHeading = TextBoxPanel(self.groupBox)
        self.txtHeading.Caption = "Title"
        self.txtHeading.LabelWidth = 120
        self.txtHeading.Width = 200
        self.groupBox.Add = self.txtHeading

        self.chbLimit = CheckBox(self.groupBox)
        self.chbLimit.Caption = "Limit # of table entries to"
        self.groupBox.Add = self.chbLimit

        self.gbColumns = GroupBox(self.groupBox)
        self.groupBox.Add = self.gbColumns

        self.lstColumns = CheckedListBox(self.gbColumns)
        self.gbColumns.Add = self.lstColumns

        self.txtLimit = TextBoxPanel(self.groupBox)
        self.txtLimit.Caption = ""
        self.txtLimit.LabelWidth = 0
        self.txtLimit.Width = 200
        # self.txtLimit.LabelWidth = 120
        self.chbLimit.hLayout.addWidget(self.txtLimit)

        self.chbIgnoreNA = CheckBox(self.groupBox)
        self.chbIgnoreNA.Caption = "Ignore columns containing \"N/A\" values"
        self.groupBox.Add = self.chbIgnoreNA

        self.btnBoxOkCancel = QDialogButtonBox(self)
        self.btnBoxOkCancel.setObjectName(("btnBoxOkCancel"))
        self.btnBoxOkCancel.setStandardButtons(QDialogButtonBox.Cancel
                                               | QDialogButtonBox.Ok)
        # btnOK = self.btnBoxOkCancel.button(QDialogButtonBox.Ok)
        # btnOK.setText("Create")
        self.connect(self.btnBoxOkCancel, SIGNAL("accepted()"), self.acceptDlg)
        self.connect(self.btnBoxOkCancel, SIGNAL("rejected()"), self.reject)

        verticalLayoutDlg.addWidget(self.btnBoxOkCancel)

        if bool_0 != None:
            if (bool_0):
                # int width = base.ClientSize.Width
                # System.Drawing.Size clientSize = base.ClientSize
                # base.ClientSize = new System.Drawing.Size(width, clientSize.Height - (this.gbColumns.Bottom - this.txtHeading.Bottom))
                self.chbLimit.Visible = False
                self.txtLimit.Visible = False
                self.chbIgnoreNA.Visible = False
                self.gbColumns.Visible = False
            self.connect(self.chbLimit, SIGNAL("Event_0"),
                         self.chbLimit_Event_0)
        else:
            DlgQaHeading.rowLimit = 10
            DlgQaHeading.ignoreNAcolumns = True

    def chbLimit_Event_0(self):
        self.txtLimit.Enabled = self.chbLimit.Checked

    def acceptDlg(self):
        flag = False
        if self.txtHeading.Value == None and self.txtHeading.Value == "":
            QMessageBox.information(self, "Information",
                                    "Please input the title.")
            return
        if (self.gbColumns.Visible):
            if self.txtLimit.Value == "":
                QMessageBox.information(self, "Information",
                                        "Please input the limit.")
                return
            try:
                num = int(self.txtLimit.Value)
                if num < 0:
                    QMessageBox.information(
                        self, "Information",
                        "Limit must be positive. \n Please try again.")
                    return
            except:
                QMessageBox.information(
                    self, "Information",
                    "Limit must be number. \n Please try again.")
                return

            if (len(self.lstColumns.CheckedItems) == 0):
                QMessageBox.warning(
                    self, "Information",
                    Validations.PLEASE_SELECT_AT_LEAST_1_COLUMN)
                return
        self.accept()

    def getColumns(self):
        qaHeadingColumn = QaHeadingColumns()
        for item in self.lstColumns.Items:
            qaHeadingColumn.Add(item)
        return qaHeadingColumn

    def setColumns(self, columns):
        self.lstColumns.Clear()
        for qaHeadingColumn in columns:
            self.lstColumns.Add(qaHeadingColumn, qaHeadingColumn.Selected)

    Columns = property(getColumns, setColumns, None, None)

    def getHeading(self):
        return self.txtHeading.Value

    def setHeading(self, val):
        self.txtHeading.Value = val

    Heading = property(getHeading, setHeading, None, None)

    def getIgnoreNAcolumns(self):
        return DlgQaHeading.ignoreNAcolumns

    def setIgnoreNAcolumns(self, val):
        DlgQaHeading.ignoreNAcolumns = val

    IgnoreNAcolumns = property(getIgnoreNAcolumns, setIgnoreNAcolumns, None,
                               None)

    def getRowLimit(self):
        return DlgQaHeading.rowLimit

    def setRowLimit(self, val):
        if val > 0:
            DlgQaHeading.rowLimit = val

    RowLimit = property(getRowLimit, setRowLimit, None, None)

    def getLimit(self):
        num = None
        if (self.txtLimit.Enabled):
            try:
                return int(self.txtLimit.Value)
            except:
                pass
        return -1

    def setLimit(self, val):
        if (val <= 0):
            self.txtLimit.Value = ""
            return
        self.txtLimit.Value = str(val)

    Limit = property(getLimit, setLimit, None, None)

    @staticmethod
    def smethod_0(iwin32Window_0, string_0):
        flag = False
        dlgQaHeading = DlgQaHeading(iwin32Window_0, True)
        dlgQaHeading.Heading = string_0
        resultDlg = dlgQaHeading.exec_()
        if (not resultDlg == QDialog.Accepted):
            return False, None
        else:
            string_0 = dlgQaHeading.Heading
            flag = True
        return flag, string_0

    @staticmethod
    def smethod_1(iwin32Window_0, string_0, int_0, qaHeadingColumns_0):
        flag = False
        dlgQaHeading = DlgQaHeading(iwin32Window_0, False)
        dlgQaHeading.Heading = string_0
        if (int_0 >= DlgQaHeading.rowLimit):
            dlgQaHeading.Limit = DlgQaHeading.rowLimit
        else:
            dlgQaHeading.Limit = int_0
        dlgQaHeading.Columns = qaHeadingColumns_0
        dlgQaHeading.chbIgnoreNA.Checked = DlgQaHeading.IgnoreNAcolumns
        resultDlg = dlgQaHeading.exec_()
        limit = None
        if (not resultDlg == QDialog.Accepted):
            return False, string_0, int_0, qaHeadingColumns_0
        else:
            string_0 = dlgQaHeading.Heading
            limit = dlgQaHeading.Limit
            if (limit >= 0 and limit < int_0):
                int_0 = limit
            DlgQaHeading.IgnoreNAcolumns = dlgQaHeading.chbIgnoreNA.Checked
            flag = True
        return flag, string_0, int_0, qaHeadingColumns_0
Beispiel #11
0
class DlgAixmSid(QDialog):
    def __init__(self, parent = None):
        QDialog.__init__(self, parent)
        
        self.resize(290, 136);
        self.setWindowTitle("Standard Instrument Departure (SID)")
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed);
        sizePolicy.setHorizontalStretch(0);
        sizePolicy.setVerticalStretch(0);
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth());
        self.setSizePolicy(sizePolicy);
        verticalLayoutDlg = QVBoxLayout(self)
        verticalLayoutDlg.setObjectName(("verticalLayoutDlg"));

        self.groupBox = GroupBox(self)
        verticalLayoutDlg.addWidget(self.groupBox)

        self.pnlAerodrome = ComboBoxPanel(self.groupBox)
        self.pnlAerodrome.Caption = "Aerodrome"
        self.groupBox.Add = self.pnlAerodrome

        self.pnlDesignator = TextBoxPanel(self.groupBox)
        self.pnlDesignator.Caption = "Designator"
        self.groupBox.Add = self.pnlDesignator

        self.pnlAcCategory = ComboBoxPanel(self.groupBox)
        self.pnlAcCategory.Caption = "Ac. Category"
        self.groupBox.Add = self.pnlAcCategory

        self.pnlTransID = TextBoxPanel(self.groupBox)
        self.pnlTransID.Caption = "ransitional Identifier"
        self.groupBox.Add = self.pnlTransID

        self.pnlType = ComboBoxPanel(self.groupBox)
        self.pnlType.Caption = "Type"
        self.groupBox.Add = self.pnlType

        self.pnlRunway = ComboBoxPanel(self.groupBox)
        self.pnlRunway.Caption = "Runway Direction"
        self.groupBox.Add = self.pnlRunway

        self.pnlMSA = ComboBoxPanel(self.groupBox)
        self.pnlMSA.Caption = "MSA Group"
        self.groupBox.Add = self.pnlMSA

        self.pnlRNP = NumberBoxPanel(self.groupBox)
        self.pnlRNP.Caption = "RNP"
        self.groupBox.Add = self.pnlRNP

        self.tableLayoutPanel = Frame(self.groupBox)
        self.groupBox.Add = self.tableLayoutPanel

        self.txtDescription = TextBoxPanel(self.tableLayoutPanel, True)
        self.txtDescription.Caption = "Description"
        self.tableLayoutPanel.Add = self.txtDescription

        self.txtDescrComFail = TextBoxPanel(self.tableLayoutPanel, True)
        self.txtDescrComFail.Caption = "Communication Failure"
        self.tableLayoutPanel.Add = self.txtDescrComFail

        self.txtRemarks = TextBoxPanel(self.tableLayoutPanel, True)
        self.txtRemarks.Caption = "Remarks"
        self.tableLayoutPanel.Add = self.txtRemarks

        self.btnBoxOkCancel = QDialogButtonBox(self)
        self.btnBoxOkCancel.setObjectName(("btnBoxOkCancel"));
        self.btnBoxOkCancel.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok);
        self.connect(self.btnBoxOkCancel, SIGNAL("accepted()"), self.acceptDlg)
        self.connect(self.btnBoxOkCancel, SIGNAL("rejected()"), self.reject)

        verticalLayoutDlg.addWidget(self.btnBoxOkCancel)

        self.data = None
        self.table = None
        self.selected = None;
    def acceptDlg(self):
        strS = None;
        # self.errorProvider.method_1();
        # self.pnlAerodrome.method_0();
        # self.pnlDesignator.method_0();
        # self.pnlType.method_0();
        # self.pnlRNP.method_1(new Validator(ValidationFlags.AllowEmpty | ValidationFlags.Positive));
        # if (self.errorProvider.HasErrors)
        # {
        #     return;
        # }
        selectedItem = self.pnlAerodrome.SelectedItem;
        num = (self.pnlAcCategory.SelectedIndex >= 0) and self.pnlAcCategory.SelectedIndex or -1;
        for row in self.table:
            flag = True;
            if (self.selected != None and row == self.selected):
                flag = False;
            if (row["ahpEnt"] != selectedItem):
                flag = False;
            if (not self.pnlDesignator.Value == row["txtDesig"]):
                flag = False;
            if (num != (row["codeCatAcft"] == None) and -1 or row["codeCatAcft"]):
                flag = False;
            str = (row["codeTransId"] == None) and "" or row["codeTransId"];
            if (not self.pnlTransID.Value == str):
                flag = False;
            if (not flag):
                continue;
            str1 = "Cannot create a duplicate procedure entry.\n\nAerodrome = {0}\nDesignator = {1}".format(self.pnlAerodrome.SelectedItem, self.pnlDesignator.Value);
            if (self.pnlAcCategory.SelectedIndex >= 0):
                str1 = String.Concat([str1, "\nAc. Category = {0}".format(self.pnlAcCategory.SelectedItem)]);
            if (not String.IsNullOrEmpty(self.pnlTransID.Value)):
                str1 = String.Concat([str1, "\nTransition Identifier = {0}".format(self.pnlTransID.Value)]);
            QMessageBox.warning(self, "Error", str1);
            return;
        self.accept()
    
    def method_5(self):
        self.data.method_35(self.pnlRunway, self.pnlAerodrome.SelectedItem);
        # self.pnlRunway.comboBox.insertItem(0, "");
    
    @staticmethod
    def smethod_0(dataBaseSIDs_0, dataBaseProcedureData_0, dataRow_0):
        flag = False;
        dlgAixmSid = DlgAixmSid()
        dlgAixmSid.data = dataBaseProcedureData_0;
        dlgAixmSid.table = dataBaseSIDs_0;
        dlgAixmSid.selected = dataRow_0;
        dataBaseProcedureData_0.method_51(dlgAixmSid.pnlAerodrome);
        dataBaseProcedureData_0.method_47(dlgAixmSid.pnlMSA);

        dlgAixmSid.pnlAcCategory.Items = CodeCatAcftAixm.Items;
        dlgAixmSid.pnlType.Items = CodeTypeSidAixm.Items;
        # dlgAixmSid.pnlAcCategory.comboBox.insertItem(0, "");
        # dlgAixmSid.pnlMSA.comboBox.insertItem(0, "");
        if (dataRow_0 != None):
            dlgAixmSid.pnlAerodrome.SelectedIndex = dlgAixmSid.pnlAerodrome.comboBox.findText(dataRow_0["ahpEnt"].ToString());
            if (dlgAixmSid.pnlAerodrome.SelectedIndex >= 0):
                dataBaseProcedureData_0.method_35(dlgAixmSid.pnlRunway, dlgAixmSid.pnlAerodrome.SelectedItem);
                # dlgAixmSid.pnlRunway.comboBox.insertItem(0, "");
            dlgAixmSid.pnlDesignator.Value = dataRow_0["txtDesig"];
            if (dataRow_0["codeCatAcft"] != None):
                dlgAixmSid.pnlAcCategory.SelectedIndex = dlgAixmSid.pnlAcCategory.method_3(dataRow_0["codeCatAcft"]);
            if (dataRow_0["codeTransId"] != None):
                dlgAixmSid.pnlTransID.Value = dataRow_0["codeTransId"];
            if (dataRow_0["rdnEnt"] != None):
                dlgAixmSid.pnlRunway.SelectedIndex = dlgAixmSid.pnlRunway.comboBox.findText(dataRow_0["rdnEnt"].ToString());
            if (dataRow_0["mgpEnt"] != None):
                dlgAixmSid.pnlMSA.SelectedIndex = dlgAixmSid.pnlMSA.comboBox.findText(dataRow_0["mgpEnt"].ToString());
            if (dataRow_0["codeRnp"] != None):
                dlgAixmSid.pnlRNP.Value = dataRow_0["codeRnp"]
            if (dataRow_0["txtDescrComFail"] != None):
                dlgAixmSid.txtDescrComFail.Text = dataRow_0["txtDescrComFail"];
            dlgAixmSid.pnlType.SelectedIndex = dlgAixmSid.pnlType.method_3(dataRow_0["codeTypeRte"]);
            if (dataRow_0["txtDescr"] != None):
                dlgAixmSid.txtDescription.Value = dataRow_0["txtDescr"];
            if (dataRow_0["txtRmk"] != None):
                dlgAixmSid.txtRemarks.Value = dataRow_0["txtRmk"];
        dlgResult = dlgAixmSid.exec_()
        if (dlgResult == 1):
            dataRow0 = dataRow_0 == None;
            strS = [];
            if (not dataRow0):
                for i in range(dataBaseSIDs_0.ColumnsCount()):
                    strS.append(None)
                # str = new string[dataBaseSIDs_0.Columns.Count];
                i = 0
                for name in dataBaseSIDs_0.nameList:
                    strS[i] = dataRow_0[name];
                    i += 1
            else:
                dataRow_0 = dataBaseSIDs_0.NewRow();
            dataRow_0["ahpEnt"] = dlgAixmSid.pnlAerodrome.SelectedItem;
            if (dataRow0):
                dataRow_0["oldAhpEnt"] = dataRow_0["ahpEnt"];
            dataRow_0["txtDesig"] = dlgAixmSid.pnlDesignator.Value;
            if (dataRow0):
                dataRow_0["oldTxtDesig"] = dataRow_0["txtDesig"];
            if (dlgAixmSid.pnlAcCategory.SelectedIndex >= 0):
                dataRow_0["codeCatAcft"] = dlgAixmSid.pnlAcCategory.SelectedItem;
            else:
                dataRow_0["codeCatAcft"] = None;
            if (dataRow0):
                dataRow_0["oldCodeCatAcft"] = dataRow_0["codeCatAcft"];
            if (not String.IsNullOrEmpty(dlgAixmSid.pnlTransID.Value)):
                dataRow_0["codeTransId"] = dlgAixmSid.pnlTransID.Value;
            else:
                dataRow_0["codeTransId"] = None;
            if (dataRow0):
                dataRow_0["oldCodeTransId"] = dataRow_0["codeTransId"];
            if (dlgAixmSid.pnlRunway.SelectedIndex >= 0):
                dataRow_0["rdnEnt"] = dlgAixmSid.pnlRunway.SelectedItem;
            else:
                dataRow_0["rdnEnt"] = None;
            if (dlgAixmSid.pnlMSA.SelectedIndex >= 0):
                dataRow_0["mgpEnt"] = dlgAixmSid.pnlMSA.SelectedItem;
            else:
                dataRow_0["mgpEnt"] = None;
            if (not math.isinf(dlgAixmSid.pnlRNP.Value) and not math.isnan(dlgAixmSid.pnlRNP.Value)):
                dataRow_0["codeRnp"] = dlgAixmSid.pnlRNP.Value;
            else:
                dataRow_0["codeRnp"] = None;
            dataRow_0["codeTypeRte"] = dlgAixmSid.pnlType.SelectedItem;
            if (not String.IsNullOrEmpty(dlgAixmSid.txtDescrComFail.Value)):
                dataRow_0["txtDescrComFail"] = dlgAixmSid.txtDescrComFail.Value;
            else:
                dataRow_0["txtDescrComFail"] = None;
            if (not String.IsNullOrEmpty(dlgAixmSid.txtDescription.Value)):
                dataRow_0["txtDescr"] = dlgAixmSid.txtDescription.Value;
            else:
                dataRow_0["txtDescr"] = None;
            if (not String.IsNullOrEmpty(dlgAixmSid.txtRemarks.Value)):
                dataRow_0["txtRmk"] = dlgAixmSid.txtRemarks.Value;
            else:
                dataRow_0["txtRmk"] = None;
            if (dataRow0):
                dataRow_0["procLegs"] = DataBaseProcedureLegs();
                dataRow_0["procLegsEx"] = DataBaseProcedureLegsEx();
            if (not dataRow0):
                num = 1;
                while (num < int(len(strS))):
                    if (not strS[num] == dataRow_0[dataRow_0.nameList[num]]):
                        dataRow_0["changed"] = "True";
                        if (dataRow0):
                            dataBaseSIDs_0.RowsAdd(dataRow_0);
                        flag = True;
                        return flag;
                    else:
                        num += 1;
            else:
                dataRow_0["new"] = "True";
            if (dataRow0):
                dataBaseSIDs_0.RowsAdd(dataRow_0);
            flag = True;
            return flag;
        return False;
Beispiel #12
0
class GenericVerticalUI(object):
    """Generic class of user interface"""
    def addGuiItem(self, ParentClass, parameters, width):
        """Defines a new set of Label and a box that can be a
        ComboBox, RComboBox, LineEdit, TextEdit or DoubleSpinBox."""
        widgetType=parameters[1]
        #check if there are default values:
        if len(parameters)>2:
            default=parameters[2]
        else:
            default=""
        skip = False
        notnull=parameters[3]
        #setting the right type of widget
        if widgetType=="comboBox":
            widget = QComboBox(ParentClass)
            widget.addItems(default.split(';'))
            widget.setFixedHeight(26)
        elif widgetType=="RComboBox":
            widget = RComboBox(ParentClass, default.split(';'))
            widget.setFixedHeight(26)
            self.hasRComboBox = True
            widget.setEditable(True)
        elif widgetType=="RListWidget":
            widget = RListWidget(ParentClass,
            default.split(';'), notnull)
            widget.setMinimumHeight(116)
            self.hasRComboBox = True
            widget.setSelectionMode(
            QAbstractItemView.ExtendedSelection)
        elif widgetType=="doubleSpinBox":
            widget = QDoubleSpinBox(ParentClass)
            widget.setValue(float(default))
            widget.setFixedHeight(26)
            widget.setMaximum(999999.9999)
            widget.setDecimals(4)
        elif widgetType=="textEdit":
            widget = QTextEdit(ParentClass)
            widget.setPlainText(default)
            widget.setMinimumHeight(116)
        elif widgetType=="helpString":
            self.helpString = default
            skip = True
        else:
            #if unknown assumes lineEdit
            widget = QLineEdit(ParentClass)
            widget.setText(default)
            widget.setFixedHeight(26)
        if not skip:
            hbox = QHBoxLayout()
            name="widget"+unicode(self.widgetCounter)
            widget.setObjectName(name)
            widget.setMinimumWidth(250)
            self.widgets.append(widget)
            name="label"+unicode(self.widgetCounter)
            self.widgetCounter += 1
            label = QLabel(ParentClass)
            label.setObjectName(name)
            label.setFixedWidth(width*8)
            label.setText(parameters[0])
            hbox.addWidget(label)
            hbox.addWidget(widget)
            self.vbox.addLayout(hbox)

    def isSpatial(self):
        return self.hasRComboBox

    def updateRObjects(self):
        layers = browseEnv()
        for widget in self.widgets:
            if isinstance(widget, RComboBox) or isinstance(widget, RListWidget):
                types = widget.types()
                for type in types:
                    for layer in layers:
                        if layer.className() == type.strip() or type.strip() == "all":
                            value = layer.name()
                            widget.addItem(value)
                        if layer in VECTORTYPES \
                        and (sptype.strip() == "data.frame" \
                        or sptype.strip() == "all"):
                            value = layer+"@data"
                            widget.addItem(value)
                        if splayers[layer] in VECTORTYPES \
                        or splayers[layer] == "data.frame":
                            names =  robjects.r('names(%s)' % (layer))
                            if not unicode(names) == 'NULL':
                                for item in list(names):
                                    if splayers[layer] == "data.frame":
                                        value = layer+"$"+item
                                    else:
                                        value = layer+"@data$"+item
                                    try:
                                        if unicode(robjects.r('class(%s)' % (value))[0]) == sptype.strip() \
                                        or sptype.strip() == "all":
                                             widget.addItem(value)
                                    except:
                                        pass



    def setupUi(self, ParentClass, itemlist):
        self.ParentClass = ParentClass
        self.ParentClass.setObjectName("ParentClass")
        self.exists={"RComboBox":0, "comboBox":0, "textEdit":0,
                     "doubleSpinBox":0, "lineEdit":0,  "label":0}
        self.helpString = "There is no help available for this plugin"
        self.widgetCounter = 0
        self.widgets = []
        width = 0
        self.hasRComboBox = False
        self.vbox = QVBoxLayout(self.ParentClass)
        for item in itemlist:
            if len(item[0]) > width:
                width = len(item[0])
        # Draw a label/widget pair for every item in the list
        for item in itemlist:
            self.addGuiItem(self.ParentClass, item, width)
        self.showCommands = QCheckBox("Append commands to console",self.ParentClass)
        self.buttonBox = QDialogButtonBox(self.ParentClass)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(
        QDialogButtonBox.Help|QDialogButtonBox.Close|QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        self.vbox.addWidget(self.showCommands)
        self.vbox.addWidget(self.buttonBox)
        # accept gets connected in the plugin manager
        QObject.connect(self.buttonBox, SIGNAL("rejected()"), self.ParentClass.reject)
        QObject.connect(self.buttonBox, SIGNAL("helpRequested()"), self.help)
        #QMetaObject.connectSlotsByName(self.ParentClass)

    def help(self):
        if QString(self.helpString).startsWith("topic:"):
            topic = QString(self.helpString).remove("topic:")
            self.ParentClass.parent().editor.moveToEnd()
            self.ParentClass.parent().editor.cursor.movePosition(
            QTextCursor.StartOfBlock, QTextCursor.KeepAnchor)
            self.ParentClass.parent().editor.cursor.removeSelectedText()
            self.ParentClass.parent().editor.cursor.insertText(
            "%shelp(%s)" % (
            self.ParentClass.parent().editor.currentPrompt,
            unicode(topic)))
            self.ParentClass.parent().editor.execute(
            QString("help('%s')" % (unicode(topic))))
        else:
            HelpForm(self.ParentClass, self.helpString).show()
Beispiel #13
0
class DlgAerodromeSurfaces(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)

        self.resize(290, 136)
        self.setWindowTitle("Surfaces")
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        verticalLayoutDlg = QVBoxLayout(self)
        verticalLayoutDlg.setObjectName(("verticalLayoutDlg"))

        self.lstSurfaces = CheckedListBox(self)
        verticalLayoutDlg.addWidget(self.lstSurfaces)

        self.btnBoxOkCancel = QDialogButtonBox(self)
        self.btnBoxOkCancel.setObjectName(("btnBoxOkCancel"))
        self.btnBoxOkCancel.setStandardButtons(QDialogButtonBox.Cancel
                                               | QDialogButtonBox.Ok)

        self.btnOK = self.btnBoxOkCancel.button(QDialogButtonBox.Ok)

        self.connect(self.btnBoxOkCancel, SIGNAL("accepted()"), self.acceptDlg)
        self.connect(self.btnBoxOkCancel, SIGNAL("rejected()"), self.reject)

        verticalLayoutDlg.addWidget(self.btnBoxOkCancel)

        # self.btnOK.setEnabled(len(self.lstSurfaces.CheckedItems) > 0)
        # self.connect(self.lstSurfaces, SIGNAL("ItemCheck"), self.lstSurfaces_ItemCheck)

    def acceptDlg(self):
        if len(self.lstSurfaces.CheckedItems) == 0:
            self.reject()
        else:
            self.accept()

    def lstSurfaces_ItemCheck(self, standardItem):
        # if checkBoxObj == None:
        #     return
        count = len(self.lstSurfaces.CheckedItems)
        if (count == 0):
            self.btnOK.setEnabled(standardItem.checkState() == Qt.Checked)
            return
        if (count != 1):
            self.btnOK.setEnabled(True)
            return
        self.btnOK.setEnabled(standardItem.checkState() == Qt.Checked)

    def method_5(self, bool_0):
        for i in range(len(bool_0)):
            bool_0[i] = self.lstSurfaces.GetItemChecked(i)
        return bool_0

    def method_6(self):
        self.btnOK.setEnabled(len(self.lstSurfaces.CheckedItems) > 0)

    def set_Surfaces(self, strList):
        self.lstSurfaces.Clear()
        strArrays = strList
        for i in range(len(strArrays)):
            str0 = strArrays[i]
            self.lstSurfaces.Add(str0, True)

    Surfaces = property(None, set_Surfaces, None, None)

    @staticmethod
    def smethod_0(parent, string_0, bool_0):
        flag = False
        dlgAerodromeSurface = DlgAerodromeSurfaces(parent)
        dlgAerodromeSurface.Surfaces = string_0
        resultDlg = dlgAerodromeSurface.exec_()
        if (not resultDlg == 1):
            flag = False
        else:
            dlgAerodromeSurface.method_5(bool_0)
            flag = True
        return flag
class DlgDetailDataEdit(QDialog):
    def __init__(self, parent, title, valueList=None):
        QDialog.__init__(self, parent)

        self.resize(100, 70)
        self.setWindowTitle(title)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        verticalLayoutDlg = QVBoxLayout(self)
        verticalLayoutDlg.setObjectName(("verticalLayoutDlg"))

        self.frameBasic = Frame(self)
        verticalLayoutDlg.addWidget(self.frameBasic)

        self.pnlDetail = PositionPanel(self.frameBasic, None, None, "Degree")
        self.pnlDetail.btnCalculater.setVisible(False)
        self.pnlDetail.Caption = "Position"
        self.frameBasic.Add = self.pnlDetail

        self.pnlType = ComboBoxPanel(self.frameBasic)
        self.pnlType.Caption = "Type"
        self.pnlType.LabelWidth = 120
        self.frameBasic.Add = self.pnlType

        self.pnlCenter = PositionPanel(self.frameBasic, None, None, "Degree")
        self.pnlCenter.btnCalculater.setVisible(False)
        self.pnlCenter.Caption = "Center Position"
        self.pnlCenter.hideframe_Altitude()
        self.frameBasic.Add = self.pnlCenter

        self.pnlMagVariation = TextBoxPanel(self.frameBasic)
        self.pnlMagVariation.Caption = "Mag. Variation"
        self.pnlMagVariation.LabelWidth = 120
        self.frameBasic.Add = self.pnlMagVariation

        self.btnBoxOkCancel = QDialogButtonBox(self)
        self.btnBoxOkCancel.setObjectName(("btnBoxOkCancel"))
        self.btnBoxOkCancel.setStandardButtons(QDialogButtonBox.Cancel
                                               | QDialogButtonBox.Ok)
        self.connect(self.btnBoxOkCancel, SIGNAL("accepted()"), self.acceptDlg)
        self.connect(self.btnBoxOkCancel, SIGNAL("rejected()"), self.reject)

        verticalLayoutDlg.addWidget(self.btnBoxOkCancel)

        self.x = ""
        self.y = ""
        self.latitude = ""
        self.longitude = ""
        self.altitude = ""
        self.cenLatitude = ""
        self.cenLongitude = ""
        self.type = ""
        self.magVariation = ""

        self.pnlMagVariation.Visible = False
        self.pnlCenter.Visible = False
        self.pnlType.Items = [
            DataBaseCoordinateType.ArcPoint, DataBaseCoordinateType.CCA,
            DataBaseCoordinateType.CenPoint, DataBaseCoordinateType.CWA,
            DataBaseCoordinateType.FNT, DataBaseCoordinateType.GRC,
            DataBaseCoordinateType.MidPoint, DataBaseCoordinateType.Point
        ]

        if valueList != None:
            self.pnlDetail.Point3d = Point3D(
                float(valueList[1]), float(valueList[0]),
                float(valueList[2]) if
                (valueList[2] != None and valueList[2] != "") else 0.0)
            self.pnlType.Value = valueList[3]
            if title == "Modify Detail Airspace":
                if valueList[5] != None and valueList[5] != "":
                    self.pnlCenter.Point3d = Point3D(float(valueList[5]),
                                                     float(valueList[4]))
            elif title == "Modify Detail Routes":
                self.pnlMagVariation.Value = valueList[4]
        if title == "Modify Detail Airspace" or title == "Add Detail Airspace":
            self.pnlCenter.Visible = True
        elif title == "Modify Detail Routes" or title == "Add Detail Routes":
            self.pnlMagVariation.Visible = True

    def acceptDlg(self):
        if self.pnlDetail.Point3d != None and isinstance(
                self.pnlDetail.Point3d, Point3D):
            xyPoint = QgisHelper.CrsTransformPoint(
                self.pnlDetail.Point3d.get_X(), self.pnlDetail.Point3d.get_Y(),
                define._latLonCrs, define._xyCrs,
                self.pnlDetail.Point3d.get_Z())
            self.x = QString(str(xyPoint.get_X()))
            self.y = QString(str(xyPoint.get_Y()))
            self.latitude = QString(str(self.pnlDetail.Point3d.get_Y()))
            self.longitude = QString(str(self.pnlDetail.Point3d.get_X()))
            self.altitude = QString(str(self.pnlDetail.Altitude().Metres))
        if self.pnlCenter.Point3d != None and isinstance(
                self.pnlCenter.Point3d, Point3D):
            self.cenLatitude = QString(str(self.pnlCenter.Point3d.get_Y()))
            self.cenLongitude = QString(str(self.pnlCenter.Point3d.get_X()))
        self.magVariation = self.pnlMagVariation.Value
        self.type = self.pnlType.SelectedItem
        self.accept()
class DlgRunway(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)

        self.resize(290, 136)
        self.setWindowTitle("Runway Setup")
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        verticalLayoutDlg = QVBoxLayout(self)
        verticalLayoutDlg.setObjectName(("verticalLayoutDlg"))

        self.basicFrame = Frame(self)
        verticalLayoutDlg.addWidget(self.basicFrame)

        self.groupBox = GroupBox(self.basicFrame)
        self.basicFrame.Add = self.groupBox

        self.pnlName = TextBoxPanel(self.groupBox)
        self.pnlName.Caption = "Name"
        self.pnlName.LabelWidth = 70
        self.groupBox.Add = self.pnlName

        self.pnlDesignatorFrame = Frame(self.groupBox, "HL")
        self.groupBox.Add = self.pnlDesignatorFrame

        self.pnlDesignator = TextBoxPanel(self.groupBox)
        self.pnlDesignator.Caption = "Designator"
        self.pnlDesignator.LabelWidth = 70
        self.pnlDesignator.Button = "Calculator.bmp"
        self.pnlDesignatorFrame.Add = self.pnlDesignator

        self.cmbDesignator = ComboBoxPanel(self.groupBox)
        self.cmbDesignator.Caption = ""
        self.cmbDesignator.LabelWidth = 0
        self.cmbDesignator.Items = ["", "L", "C", "R"]
        self.pnlDesignatorFrame.Add = self.cmbDesignator

        self.gbPositions = GroupBox(self.groupBox)
        self.gbPositions.Caption = "Positions"
        self.groupBox.Add = self.gbPositions

        self.pnlPosition = PositionPanel(self.gbPositions)
        # self.pnlPosition.hideframe_Altitude()
        self.pnlPosition.btnCalculater.setVisible(False)
        self.gbPositions.Add = self.pnlPosition

        self.pnlTree = Frame(self.gbPositions)
        self.gbPositions.Add = self.pnlTree

        self.trvPositions = TreeView(self.pnlTree)
        self.pnlTree.Add = self.trvPositions

        self.pnlButtons = Frame(self.pnlTree, "HL")
        self.pnlTree.Add = self.pnlButtons

        self.btnPrevious = QPushButton(self.pnlButtons)
        self.btnPrevious.setObjectName("btnPrevious")
        self.btnPrevious.setText("")
        icon = QIcon()
        icon.addPixmap(QPixmap("Resource/btnImage/Prev_32x32.png"),
                       QIcon.Normal, QIcon.Off)
        self.btnPrevious.setIcon(icon)
        self.pnlButtons.Add = self.btnPrevious

        self.btnInsert = QPushButton(self.pnlButtons)
        self.btnInsert.setObjectName("btnInsert")
        self.btnInsert.setText("")
        icon = QIcon()
        icon.addPixmap(QPixmap("Resource/add.png"), QIcon.Normal, QIcon.Off)
        self.btnInsert.setIcon(icon)
        self.pnlButtons.Add = self.btnInsert

        self.btnRemove = QPushButton(self.pnlButtons)
        self.btnRemove.setObjectName("btnRemove")
        self.btnRemove.setText("")
        icon = QIcon()
        icon.addPixmap(QPixmap("Resource/remove.png"), QIcon.Normal, QIcon.Off)
        self.btnRemove.setIcon(icon)
        self.pnlButtons.Add = self.btnRemove

        self.btnNext = QPushButton(self.pnlButtons)
        self.btnNext.setObjectName("btnNext")
        self.btnNext.setText("")
        icon = QIcon()
        icon.addPixmap(QPixmap("Resource/btnImage/Next_32x32.png"),
                       QIcon.Normal, QIcon.Off)
        self.btnNext.setIcon(icon)
        self.pnlButtons.Add = self.btnNext

        self.btnBoxOkCancel = QDialogButtonBox(self)
        self.btnBoxOkCancel.setObjectName(("btnBoxOkCancel"))
        self.btnBoxOkCancel.setStandardButtons(QDialogButtonBox.Cancel
                                               | QDialogButtonBox.Ok)

        self.btnOK = self.btnBoxOkCancel.button(QDialogButtonBox.Ok)

        self.connect(self.btnBoxOkCancel, SIGNAL("accepted()"), self.acceptDlg)
        self.connect(self.btnBoxOkCancel, SIGNAL("rejected()"), self.reject)

        verticalLayoutDlg.addWidget(self.btnBoxOkCancel)

        self.btnOK.setText("Save")
        self.connect(self.pnlDesignator, SIGNAL("Event_1"), self.method_14)

        self.connect(self.pnlPosition, SIGNAL("captureFinished"),
                     self.method_13)
        self.btnInsert.clicked.connect(self.btnInsert_Click)
        self.btnNext.clicked.connect(self.btnNext_Click)
        self.btnPrevious.clicked.connect(self.btnPrevious_Click)
        self.btnRemove.clicked.connect(self.btnRemove_Click)

        self.trvPositions.clicked.connect(self.trvPositions_clicked)

        # item = self.trvPositions.Add("Parent")
        # item.appendRow(TreeNode("Child0"))
        #
        # item00 = item0.appendRow(TreeNode("Child00"))

    def trvPositions_clicked(self):
        selectedNode = self.trvPositions.SelectedNode
        if (selectedNode == None):
            return
        tag = selectedNode.Tag
        if (tag == None):
            return
        if not tag.IsEmpty and tag.IsValid:
            self.pnlPosition.Point3d = tag.Point3d
        else:
            self.pnlPosition.Point3d = None

    def get_Runway(self):
        return self.method_6()

    def set_Runway(self, runway):
        if (runway != None):
            self.pnlName.Value = runway.Name
            self.pnlDesignator.Value = runway.DesignatorHeading
            self.cmbDesignator.SelectedIndex = self.cmbDesignator.comboBox.findText(
                (runway.DesignatorCode))
        self.method_5(runway)

    RunwayValue = property(get_Runway, set_Runway, None, None)

    def acceptDlg(self):
        current = None
        # self.errorProvider.method_1()
        # self.pnlName.method_0()
        for current in self.trvPositions.Nodes:
            # IEnumerator enumerator = self.trvPositions.Nodes.GetEnumerator()
            # try
            # {
            #     while (true)
            #     {
            #         if (enumerator.MoveNext())
            #         {
            #     current = (TreeNode)enumerator.Current
            tag = current.Tag
            if (not tag.IsValidIncludingAltitude):
                if (tag.Type == PositionType.THR):
                    break
                if (tag.Type == PositionType.END):
                    break
                elif (not tag.IsEmpty):
                    self.trvPositions.SelectedNode = current
                    self.emit(SIGNAL("DlgRunway_accept"), self.method_6())
                    # self.pnlPosition.method_6()
                    return
            for treeNode in current.Nodes:
                # IEnumerator enumerator1 = current.Nodes.GetEnumerator()
                # try
                # {
                #     while (enumerator1.MoveNext())
                #     {
                #         TreeNode treeNode = (TreeNode)enumerator1.Current
                position = current.Tag
                if (position.IsValidIncludingAltitude or position.IsEmpty):
                    continue
                self.trvPositions.SelectedNode = treeNode
                self.pnlPosition.method_6()
                self.emit(SIGNAL("DlgRunway_accept"), self.method_6())
                return
            #     }
            # }
            # finally
            # {
            #     IDisposable disposable = enumerator1 as IDisposable
            #     if (disposable != null)
            #     {
            #         disposable.Dispose()
            #     }
            # }
            #     }
            #     else
            #     {
            #         goto Label0
            #     }
            # }
        self.trvPositions.SelectedNode = current
        # self.pnlPosition.method_6()
        self.emit(SIGNAL("DlgRunway_accept"), self.method_6())
        # }
        # finally
        # {
        #     IDisposable disposable1 = enumerator as IDisposable
        #     if (disposable1 != null)
        #     {
        #         disposable1.Dispose()
        #     }
        # }
        # return
        # Label0:
        #     if (!self.errorProvider.HasErrors)
        #     {
        #         if (self.method_6().method_7(self))
        #         {
        #             base.DialogResult = System.Windows.Forms.DialogResult.OK
        #         }
        #         return
        #     }
        #     else
        #     {
        #         return
        #     }
        self.accept()

    def btnInsert_Click(self):
        selectedNode = self.trvPositions.SelectedNode
        if (selectedNode == None):
            return
        tag = selectedNode.Tag
        if (tag == None):
            return
        if (tag.Type == PositionType.THR):
            selectedNode = selectedNode.Insert(
                0, PositionType.VariableNames[PositionType.Position - 1])
            selectedNode.Tag = Position(PositionType.Position)
        elif (tag.Type != PositionType.END):
            if (tag.Type != PositionType.Position):
                return
            if selectedNode.Parent == None:
                selectedNode = self.trvPositions.Insert(
                    selectedNode.Index,
                    PositionType.VariableNames[PositionType.Position - 1])
            else:
                selectedNode = selectedNode.Parent.Insert(
                    selectedNode.Index,
                    PositionType.VariableNames[PositionType.Position - 1])
            selectedNode.Tag = Position(PositionType.Position)
        else:
            selectedNode = selectedNode.PrevNode.Add(
                PositionType.VariableNames[PositionType.Position - 1])
            selectedNode.Tag = Position(PositionType.Position)
        self.trvPositions.SelectedNode = selectedNode

    def btnNext_Click(self):
        selectedNode = self.trvPositions.SelectedNode
        if (selectedNode == None):
            return
        if (selectedNode.Parent != None):
            if (selectedNode.NextNode == None):
                self.trvPositions.SelectedNode = selectedNode.Parent.NextNode
                return
            self.trvPositions.SelectedNode = selectedNode.NextNode
        else:
            if (len(selectedNode.Nodes) > 0):
                self.trvPositions.SelectedNode = selectedNode.Nodes[0]
                return
            if (selectedNode.NextNode != None):
                self.trvPositions.SelectedNode = selectedNode.NextNode
                return

    def btnPrevious_Click(self):
        selectedNode = self.trvPositions.SelectedNode
        if (selectedNode == None):
            return
        if (selectedNode.Parent != None):
            if (selectedNode.Index == 0):
                self.trvPositions.SelectedNode = selectedNode.Parent
                return
            self.trvPositions.SelectedNode = selectedNode.PrevNode
        else:
            selectedNode = selectedNode.PrevNode
            if (selectedNode != None):
                if (len(selectedNode.Nodes) <= 0):
                    self.trvPositions.SelectedNode = selectedNode
                    return
                self.trvPositions.SelectedNode = selectedNode.LastNode
                return

    def btnRemove_Click(self):
        selectedNode = self.trvPositions.SelectedNode
        if (selectedNode == None):
            return
        if (selectedNode.Parent != None):
            if (selectedNode.NextNode != None):
                self.trvPositions.SelectedNode = selectedNode.NextNode
            elif (selectedNode.Parent.NextNode != None):
                self.trvPositions.SelectedNode = selectedNode.Parent.NextNode
            else:
                self.trvPositions.SelectedNode = selectedNode.Parent
            parentNode = selectedNode.Parent
            if parentNode == None:
                self.trvPositions.Remove(selectedNode)
            else:
                parentNode.Remove(selectedNode)
        else:
            self.trvPositions.Remove(selectedNode)

    def method_5(self, runway_0):
        self.trvPositions.treeNodeList = []
        if (runway_0 != None):
            position = runway_0.method_1(PositionType.START)
            self.trvPositions.Add(PositionType.VariableNames[position.Type -
                                                             1]).Tag = position
            position = runway_0.method_1(PositionType.THR)
            self.trvPositions.Add(PositionType.VariableNames[position.Type -
                                                             1]).Tag = position
            position = runway_0.method_1(PositionType.END)
            self.trvPositions.Add(PositionType.VariableNames[position.Type -
                                                             1]).Tag = position
            position = runway_0.method_1(PositionType.SWY)
            self.trvPositions.Add(PositionType.VariableNames[position.Type -
                                                             1]).Tag = position
            position = runway_0.method_1(PositionType.CWY)
            self.trvPositions.Add(PositionType.VariableNames[position.Type -
                                                             1]).Tag = position
            item = self.trvPositions.Nodes[1]
            for position0 in runway_0:
                if (position0.Type != PositionType.Position):
                    continue
                item.Add(PositionType.VariableNames[position0.Type -
                                                    1]).Tag = position0
            # item.Expand()
        else:
            self.trvPositions.Add("START").Tag = Position(PositionType.START)
            self.trvPositions.Add("THR").Tag = Position(PositionType.THR)
            self.trvPositions.Add("END").Tag = Position(PositionType.END)
            self.trvPositions.Add("SWY").Tag = Position(PositionType.SWY)
            self.trvPositions.Add("CWY").Tag = Position(PositionType.CWY)
        self.trvPositions.SelectedNode = self.trvPositions.Nodes[0]
        self.method_10()

    def method_6(self):
        runway = Runway()
        runway.Name = self.pnlName.Value
        runway.DesignatorHeading = self.pnlDesignator.Value
        if (self.cmbDesignator.SelectedIndex > 0):
            runway.DesignatorCode = self.cmbDesignator.SelectedItem  #.ToString()
        for node in self.trvPositions.Nodes:
            tag = node.Tag
            runway[node.Index] = tag
            if (tag.Type != PositionType.THR):
                continue
            for treeNode in node.Nodes:
                position = treeNode.Tag
                if position == None:
                    continue
                if (not position.IsValidIncludingAltitude):
                    continue
                runway.Add(position)
        return runway

    def method_7(self):
        selectedNode = self.trvPositions.SelectedNode
        flag = False
        if (selectedNode != None):
            flag = True if (
                selectedNode.PrevNode != None) else selectedNode.Parent != None
        self.btnPrevious.setEnabled(flag)
        nextNode = False
        if (selectedNode != None):
            if (selectedNode.NextNode != None):
                nextNode = True
            elif (selectedNode.Parent != None):
                nextNode = selectedNode.Parent.NextNode != None
        self.btnNext.setEnabled(nextNode)
        flag1 = False
        if (selectedNode != None):
            tag = selectedNode.Tag
            if (tag != None):
                flag1 = True if (tag.Type == PositionType.THR
                                 or tag.Type == PositionType.Position
                                 ) else tag.Type == PositionType.END
        self.btnInsert.setEnabled(flag1)
        type = False
        if (selectedNode != None):
            position = selectedNode.Tag
            if (position != None):
                type = position.Type == PositionType.Position
        self.btnRemove.setEnabled(type)

    def method_8(self, treeNode_0, bool_0):
        if (treeNode_0 != None):
            text = treeNode_0.Text
            treeNode_0.Text = " "
            if (not bool_0):
                treeNode_0.NodeFont = QFont()
            else:
                font = QFont()
                font.setBold(True)
                treeNode_0.NodeFont = font
            treeNode_0.Text = text

    def method_9(self, treeNode_0):
        position = treeNode_0.Tag
        if not isinstance(position, Position):
            return
        num = 0
        if (not position.IsValidIncludingAltitude):
            if (position.Type != PositionType.THR):
                if (position.Type == PositionType.END):
                    num = 2
                else:
                    if (not position.IsEmpty):
                        num = 2
                        # treeNode_0.ImageIndex = num
                        # treeNode_0.SelectedImageIndex = num
                        for node in treeNode_0.Nodes:
                            self.method_9(node)
                        return
                    else:
                        # treeNode_0.ImageIndex = num
                        # treeNode_0.SelectedImageIndex = num
                        for treeNode in treeNode_0.Nodes:
                            self.method_9(treeNode)
                        return
            num = 2
        else:
            num = 1
        # treeNode_0.ImageIndex = num
        # treeNode_0.SelectedImageIndex = num
        for node1 in treeNode_0.Nodes:
            self.method_9(node1)

    def method_10(self):
        for node in self.trvPositions.Nodes:
            self.method_9(node)

    def method_11(self):
        point3d_0 = Point3D.get_Origin()
        selectedNode = self.trvPositions.SelectedNode
        if (selectedNode != None):
            selectedNode = selectedNode.PrevNode
            if (selectedNode != None):
                if (len(selectedNode.Nodes) > 0):
                    selectedNode = selectedNode.LastNode
                point3d_0 = selectedNode.Tag.Point3d
                return True, point3d_0
        return False, None

    def method_12(self):
        # Point3d point3d
        # Point3d point3d1
        # if (AcadHelper.Ready)
        # {
        #     AcadHelper.smethod_27(DrawingSpace.ModelSpace, true)
        #     Position tag = self.trvPositions.SelectedNode.Tag as Position
        #     string rUNWAYPOSITION = Captions.RUNWAY_POSITION
        #     if (tag.Type != PositionType.Position)
        #     {
        #         rUNWAYPOSITION = string.Format(Captions.RUNWAY_X_POSITION, EnumHelper.smethod_0(tag.Type))
        #     }
        #     if (self.method_11(out point3d1))
        #     {
        #         if (!AcadHelper.smethod_82(this, rUNWAYPOSITION, point3d1, out point3d))
        #         {
        #             return
        #         }
        #     }
        #     else if (!AcadHelper.smethod_80(this, rUNWAYPOSITION, out point3d))
        #     {
        #         return
        #     }
        #     self.pnlPosition.Point3d = point3d
        self.method_13()

    def method_13(self):
        if self.trvPositions.SelectedNode == None:
            return
        self.pnlPosition.posType = self.trvPositions.SelectedNode.Tag.Type
        self.trvPositions.SelectedNode.Tag = self.pnlPosition.PositionValue
        self.method_10()

    def method_14(self):
        runway = self.method_6()
        self.pnlDesignator.Value = runway.method_0()

    @staticmethod
    def smethod_0(iwin32Window_0, runway_0):
        flag = False
        dlgRunway = DlgRunway(iwin32Window_0)
        dlgRunway.RunwayValue = runway_0
        dlgRunway.show()
        # if (dlgRunway.method_2(iwin32Window_0) != System.Windows.Forms.DialogResult.OK)
        # {
        #     flag = false
        # }
        # else
        # {
        #     runway_0 = dlgRunway.Runway
        #     flag = true
        # }
        # }
        return dlgRunway
Beispiel #16
0
class EntityEditorDialog(QDialog, MapperMixin):
    """
    Dialog for editing entity attributes.
    """
    addedModel = pyqtSignal(object)

    def __init__(
            self,
            entity,
            model=None,
            parent=None,
            manage_documents=True,
            collect_model=False
    ):
        """
        Class constructor.
        :param entity: Entity object corresponding to a table object.
        :type entity: Entity
        :param model: Data object for loading data into the form widgets.
        If the model is set, then the editor dialog is assumed to be in edit
        mode.
        :type model: object
        :param parent: Parent widget that the form belongs to.
        :type parent: QWidget
        :param manage_documents: True if the dialog should provide controls
        for managing supporting documents. Only applicable if the entity
        allows for supporting documents to be attached.
        :type manage_documents: bool
        :param collect_model: If set to True only returns
        the filled form model without saving it to the database.
        :type collect_model: Boolean
        :return: If collect_model, returns SQLAlchemy Model
        """
        QDialog.__init__(self, parent)

        self.collection_suffix = self.tr('Collection')

        #Set minimum width
        self.setMinimumWidth(350)

        #Flag for mandatory columns
        self.has_mandatory = False

        self._entity = entity
        self._fk_browsers = OrderedDict()

        #Set notification layout bar
        self.vlNotification = QVBoxLayout()
        self.vlNotification.setObjectName('vlNotification')
        self._notifBar = NotificationBar(self.vlNotification)

        # Set manage documents only if the entity supports documents
        if self._entity.supports_documents:
            self._manage_documents = manage_documents

        else:
            self._manage_documents = False

        #Setup entity model
        self._ent_document_model = None
        if self._entity.supports_documents:
                ent_model, self._ent_document_model = entity_model(
                    self._entity,
                    with_supporting_document=True
                )
        else:
            ent_model = entity_model(self._entity)

        if not model is None:
            ent_model = model

        MapperMixin.__init__(self, ent_model)

        self.collect_model = collect_model
        #Initialize UI setup
        self._init_gui()

        #Set title
        editor_trans = self.tr('Editor')
        title = u'{0} {1}'.format(
            format_name(self._entity.short_name),
            editor_trans
        )
        self.setWindowTitle(title)


    def _init_gui(self):
        #Setup base elements
        self.gridLayout = QGridLayout(self)
        self.gridLayout.setObjectName('glMain')
        self.gridLayout.addLayout(
            self.vlNotification, 0, 0, 1, 1
        )

        #Set column widget area
        column_widget_area = self._setup_columns_content_area()
        self.gridLayout.addWidget(
            column_widget_area, 1, 0, 1, 1
        )

        #Add notification for mandatory columns if applicable
        next_row = 2
        if self.has_mandatory:
            self.required_fields_lbl = QLabel(self)
            msg = self.tr(
                'Please fill out all required (*) fields.'
            )
            msg = self._highlight_asterisk(msg)
            self.required_fields_lbl.setText(msg)
            self.gridLayout.addWidget(
                self.required_fields_lbl, next_row, 0, 1, 2
            )

            #Bump up row reference
            next_row += 1

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(
            QDialogButtonBox.Cancel|QDialogButtonBox.Save
        )
        self.buttonBox.setObjectName('buttonBox')
        self.gridLayout.addWidget(
            self.buttonBox, next_row, 0, 1, 1
        )

        if self.collect_model:
            self.buttonBox.accepted.connect(
                self.on_model_added
            )
            self.buttonBox.rejected.connect(
                self.cancel
            )
        else:
            #Connect to MapperMixin slots
            self.buttonBox.accepted.connect(
                self.submit
            )
            self.buttonBox.rejected.connect(
                self.cancel
            )

    def on_model_added(self):
        model = self.submit(True)
        self.addedModel.emit(model)

    def _setup_columns_content_area(self):
        #Only use this if entity supports documents
        self.entity_tab_widget = None
        self.doc_widget = None

        self.entity_scroll_area = QScrollArea(self)
        self.entity_scroll_area.setFrameShape(QFrame.NoFrame)
        self.entity_scroll_area.setWidgetResizable(True)
        self.entity_scroll_area.setObjectName('scrollArea')
        self.scroll_widget_contents = QWidget()
        self.scroll_widget_contents.setObjectName(
            'scrollAreaWidgetContents'
        )
    
        #Grid layout for controls
        self.gl = QGridLayout(self.scroll_widget_contents)
        self.gl.setObjectName('gl_widget_contents')
    
        #Append column labels and widgets
        table_name = self._entity.name
        columns = table_column_names(table_name)
        #Iterate entity column and assert if they exist
        row_id = 0
        for c in self._entity.columns.values():
            if not c.name in columns and not isinstance(c, VirtualColumn):
                continue
    
            #Get widget factory
            column_widget = ColumnWidgetRegistry.create(
                c,
                self.scroll_widget_contents
            )
            if not column_widget is None:
                header = c.header()
                self.c_label = QLabel(self.scroll_widget_contents)

                #Format label text if it is a mandatory field
                if c.mandatory:
                    header = '{0} *'.format(c.header())
                    #Highlight asterisk
                    header = self._highlight_asterisk(header)

                self.c_label.setText(header)
                self.gl.addWidget(self.c_label, row_id, 0, 1, 1)

                self.column_widget = column_widget
                self.gl.addWidget(self.column_widget, row_id, 1, 1, 1)

                #Add user tip if specified for the column configuration
                if c.user_tip:
                    self.tip_lbl = UserTipLabel(user_tip=c.user_tip)
                    self.gl.addWidget(self.tip_lbl, row_id, 2, 1, 1)

                if c.mandatory and not self.has_mandatory:
                    self.has_mandatory = True

                col_name = c.name
                #Replace name accordingly based on column type
                if isinstance(c, MultipleSelectColumn):
                    col_name = c.model_attribute_name
    
                #Add widget to MapperMixin collection
                self.addMapping(
                    col_name,
                    self.column_widget,
                    c.mandatory,
                    pseudoname=c.header()
                )

                #Bump up row_id
                row_id += 1
    
        self.entity_scroll_area.setWidget(
            self.scroll_widget_contents
        )

        #Check if there are children and add foreign key browsers
        ch_entities = self.children_entities()
        if len(ch_entities) > 0:
            if self.entity_tab_widget is None:
                self.entity_tab_widget = QTabWidget(self)

            #Add primary tab if necessary
            self._add_primary_attr_widget()

            for ch in ch_entities:
                self._add_fk_browser(ch)

        #Add tab widget if entity supports documents
        if self._entity.supports_documents:
            self.doc_widget = SupportingDocumentsWidget(
                self._entity.supporting_doc,
                self._ent_document_model,
                self
            )

            #Map the source document manager object
            self.addMapping(
                'documents',
                self.doc_widget.source_document_manager
            )

            if self.entity_tab_widget is None:
                self.entity_tab_widget = QTabWidget(self)

            #Add attribute tab
            self._add_primary_attr_widget()

            #Add supporting documents tab
            self.entity_tab_widget.addTab(
                self.doc_widget,
                self.tr('Supporting Documents')
            )

        #Return the correct widget
        if not self.entity_tab_widget is None:
            return self.entity_tab_widget
    
        return self.entity_scroll_area

    def _add_primary_attr_widget(self):
        # Check if the primary entity
        # exists and add if it does not
        pr_txt = self.tr('Primary')
        if not self.entity_tab_widget is None:
            tab_txt = self.entity_tab_widget.tabText(0)
            if not tab_txt == pr_txt:
                self.entity_tab_widget.addTab(
                self.entity_scroll_area,
                pr_txt
            )

    def _add_fk_browser(self, child_entity):
        # Create and add foreign key
        # browser to the collection
        attr = u'{0}_collection'.format(
            child_entity.name
        )

        #Return if the attribute does not exist
        if not hasattr(self._model, attr):
            return

        fkb = ForeignKeyMapper(
            child_entity,
            self,
            notification_bar=self._notifBar,
            can_filter=True
        )

        #Add to mapped collection
        self.addMapping(
            attr,
            fkb
        )

        self.entity_tab_widget.addTab(
            fkb,
            u'{0} {1}'.format(
                child_entity.short_name,
                self.collection_suffix
            )
        )

        #Add to the collection
        self._fk_browsers[child_entity.name] = fkb

    def children_entities(self):
        """
        :return: Returns a list of children entities
        that refer to the main entity as the parent.
        :rtype: list
        """
        return [ch for ch in self._entity.children()
                if ch.TYPE_INFO == Entity.TYPE_INFO]

    def document_widget(self):
        """
        :return: Returns the widget for managing
        the supporting documents for an entity if enabled.
        :rtype: SupportingDocumentsWidget
        """
        return self.doc_widget

    def source_document_manager(self):
        """
        :return: Returns an instance of the
        SourceDocumentManager only if supporting
        documents are enabled for the given entity. Otherwise,
        None if supporting documents are not enabled.
        :rtype: SourceDocumentManager
        """
        if self.doc_widget is None:
            return None

        return self.doc_widget.source_document_manager

    def _highlight_asterisk(self, text):
        #Highlight asterisk in red
        c = '*'

        #Do not format if there is no asterisk
        if text.find(c) == -1:
            return text

        asterisk_highlight = '<span style=\" color:#ff0000;\">*</span>'
        text = text.replace(c, asterisk_highlight)

        return u'<html><head/><body><p>{0}</p></body></html>'.format(text)
    def __init__(self, parent, layer):
        '''
        Constructor
        '''
        QDialog.__init__(self, parent)
        self.resize(200, 200)

        self.rasterLayer = layer

        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)

        verticalLayout = QVBoxLayout(self)
        verticalLayout.setObjectName("verticalLayout")
        stackedWidget = QStackedWidget(self)
        stackedWidget.setObjectName("stackedWidget")
        pageRender = QWidget(stackedWidget)
        pageRender.setObjectName("pageRender")
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(pageRender.sizePolicy().hasHeightForWidth())
        pageRender.setSizePolicy(sizePolicy)

        horizontalLayout = QHBoxLayout(pageRender)
        horizontalLayout.setObjectName("horizontalLayout")
        frameRender = QFrame(pageRender)
        frameRender.setObjectName("frameRender")
        frameRender.setFrameShape(QFrame.StyledPanel)
        frameRender.setFrameShadow(QFrame.Raised)

        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(frameRender.sizePolicy().hasHeightForWidth())
        frameRender.setSizePolicy(sizePolicy)
        self.vLayoutFrameRender = QVBoxLayout(frameRender)
        self.vLayoutFrameRender.setObjectName("vLayoutFrameRender")

        horizontalLayout.addWidget(frameRender)
        self.cmbRendererType = ComboBoxPanel(frameRender)
        self.cmbRendererType.Caption = "Render Type"
        self.cmbRendererType.LabelWidth = 70
        self.cmbRendererType.Items = ["Mutiband color", "Paletted", "Singleband gray", "Singleband pseudocolor"]
        self.connect(self.cmbRendererType, SIGNAL("Event_0"), self.cmbRendererType_currentIndexChanged)

        self.vLayoutFrameRender.addWidget(self.cmbRendererType)
        self.gbRenderer = GroupBox(frameRender)
        self.gbRenderer.Caption = self.cmbRendererType.SelectedItem
        self.vLayoutFrameRender.addWidget(self.gbRenderer)

        self.qgsMultiBandColorRendererWidget = QgsMultiBandColorRendererWidget(self.rasterLayer)
        self.qgsPalettedRendererWidget = QgsPalettedRendererWidget(self.rasterLayer)
        self.qgsSingleBandGrayRendererWidget = QgsSingleBandGrayRendererWidget(self.rasterLayer)
        self.qgsSingleBandPseudoColorRendererWidget = QgsSingleBandPseudoColorRendererWidget(self.rasterLayer)


        self.gbRenderer.Add = self.qgsMultiBandColorRendererWidget
        self.gbRenderer.Add = self.qgsPalettedRendererWidget
        self.gbRenderer.Add = self.qgsSingleBandGrayRendererWidget
        self.gbRenderer.Add = self.qgsSingleBandPseudoColorRendererWidget

        self.qgsPalettedRendererWidget.setVisible(False)
        self.qgsSingleBandGrayRendererWidget.setVisible(False)
        self.qgsSingleBandPseudoColorRendererWidget.setVisible(False)

        stackedWidget.addWidget(pageRender)
        # page_2 = QWidget()
        # page_2.setObjectName("page_2")
        # stackedWidget.addWidget(page_2)

        verticalLayout.addWidget(stackedWidget)

        buttonBox = QDialogButtonBox(self)
        buttonBox.setObjectName("buttonBox")
        buttonBox.setOrientation(Qt.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok | QDialogButtonBox.Apply)
        btnApply = buttonBox.button(QDialogButtonBox.Apply)
        btnApply.clicked.connect(self.btnApply_clicked)
        verticalLayout.addWidget(buttonBox)


        # retranslateUi(Dialog)
        buttonBox.accepted.connect(self.OK)
        buttonBox.rejected.connect(self.reject)

        if self.rasterLayer.renderer().bandCount() == 1:
            self.cmbRendererType.SelectedIndex = 2
        elif self.rasterLayer.renderer().bandCount() > 1:
            self.cmbRendererType.SelectedIndex = 0
Beispiel #18
0
class DlgPointDataEdit(QDialog):
    def __init__(self, parent, title, valueList=None):
        QDialog.__init__(self, parent)

        self.resize(100, 70)
        self.setWindowTitle(title)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        verticalLayoutDlg = QVBoxLayout(self)
        verticalLayoutDlg.setObjectName(("verticalLayoutDlg"))

        self.frameBasic = Frame(self)
        verticalLayoutDlg.addWidget(self.frameBasic)

        self.pnlName = TextBoxPanel(self.frameBasic)
        self.pnlName.Caption = "Name"
        self.pnlName.LabelWidth = 120
        self.frameBasic.Add = self.pnlName

        self.pnlObstacle = PositionPanel(self.frameBasic, None, None, "Degree")
        self.pnlObstacle.btnCalculater.setVisible(False)
        self.frameBasic.Add = self.pnlObstacle

        self.pnlType = ComboBoxPanel(self.frameBasic)
        self.pnlType.Caption = "Type"
        self.pnlType.LabelWidth = 120
        self.frameBasic.Add = self.pnlType

        self.pnlRemarks = TextBoxPanel(self.frameBasic, True)
        self.pnlRemarks.Caption = "Remarks"
        self.pnlRemarks.LabelWidth = 120
        self.frameBasic.Add = self.pnlRemarks

        self.btnBoxOkCancel = QDialogButtonBox(self)
        self.btnBoxOkCancel.setObjectName(("btnBoxOkCancel"))
        self.btnBoxOkCancel.setStandardButtons(QDialogButtonBox.Cancel
                                               | QDialogButtonBox.Ok)
        self.connect(self.btnBoxOkCancel, SIGNAL("accepted()"), self.acceptDlg)
        self.connect(self.btnBoxOkCancel, SIGNAL("rejected()"), self.reject)

        verticalLayoutDlg.addWidget(self.btnBoxOkCancel)

        self.name = ""
        self.latitude = ""
        self.longitude = ""
        self.altitude = ""
        self.type = ""
        self.remarks = ""

        if title == "Add Symbol" or title == "Modify Symbol":
            self.pnlType.Items = [
                SymbolType.Default, SymbolType.Arp, SymbolType.Be1,
                SymbolType.Dme, SymbolType.Faf, SymbolType.Gp, SymbolType.Ndb,
                SymbolType.Repnc, SymbolType.Tacan, SymbolType.Vor,
                SymbolType.Vord
            ]
        elif title == "Add Obstacle" or title == "Modify Obstacle":
            self.pnlType.Items = [
                SymbolType.Obst1, SymbolType.Obst2, SymbolType.Obst3,
                SymbolType.Obst4
            ]

        self.editingFlag = False
        if valueList != None:
            self.pnlName.Value = valueList[0]
            self.pnlObstacle.Point3d = Point3D(float(valueList[2]),
                                               float(valueList[1]),
                                               float(valueList[3]))
            self.pnlType.Value = valueList[4]
            self.pnlRemarks.Value = valueList[5]

            self.editingFlag = True

    def acceptDlg(self):
        self.name = self.pnlName.Value
        self.latitude = QString(str(self.pnlObstacle.Point3d.get_Y()))
        self.longitude = QString(str(self.pnlObstacle.Point3d.get_X()))
        self.altitude = QString(str(self.pnlObstacle.Altitude().Metres))
        self.type = self.pnlType.SelectedItem
        self.remarks = self.pnlRemarks.Value
        self.accept()
class DlgAixmHolding(QDialog):
    def __init__(self, parent = None):
        QDialog.__init__(self, parent)
        
        self.resize(290, 136);
        self.setWindowTitle("Instrument Approach Procedure (IAP)")
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed);
        sizePolicy.setHorizontalStretch(0);
        sizePolicy.setVerticalStretch(0);
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth());
        self.setSizePolicy(sizePolicy);
        verticalLayoutDlg = QVBoxLayout(self)
        verticalLayoutDlg.setObjectName(("verticalLayoutDlg"));

        self.groupBox = GroupBox(self)
        verticalLayoutDlg.addWidget(self.groupBox)

        self.pnlBasedOn = ComboBoxPanel(self.groupBox)
        self.pnlBasedOn.Caption = "Based On"
        self.pnlBasedOn.Button = "coordinate_capture.png"
        self.groupBox.Add = self.pnlBasedOn

        self.pnlType = ComboBoxPanel(self.groupBox)
        self.pnlType.Caption = "Type"
        self.groupBox.Add = self.pnlType

        self.txtDescription = TextBoxPanel(self.groupBox, True)
        self.txtDescription.Caption = "Description"
        self.groupBox.Add = self.txtDescription

        self.txtRemarks = TextBoxPanel(self.groupBox, True)
        self.txtRemarks.Caption = "Remarks"
        self.groupBox.Add = self.txtRemarks

        self.btnBoxOkCancel = QDialogButtonBox(self)
        self.btnBoxOkCancel.setObjectName(("btnBoxOkCancel"));
        self.btnBoxOkCancel.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok);
        self.connect(self.btnBoxOkCancel, SIGNAL("accepted()"), self.acceptDlg)
        self.connect(self.btnBoxOkCancel, SIGNAL("rejected()"), self.reject)

        self.connect(self.pnlBasedOn, SIGNAL("Event_3"), self.pnlBasedOn_Event_3)

        verticalLayoutDlg.addWidget(self.btnBoxOkCancel)


        self.data = None
        self.table = None
        self.selected = None;

        self.CaptureCoordTool = CaptureCoordinateToolUpdate(define._canvas)
        self.connect(self.CaptureCoordTool, SIGNAL("resultPointValueList"), self.resultPointValueListMethod)

    def pnlBasedOn_Event_3(self):
        CaptureCoordTool = CaptureCoordinateToolUpdate(define._canvas)
        self.connect(CaptureCoordTool, SIGNAL("resultPointValueList"), self.resultPointValueListMethod)

        define._canvas.setMapTool(self.CaptureCoordTool)

    def resultPointValueListMethod(self, resultValueList):
        if len(resultValueList) > 0:
            point3d = Point3D(float(resultValueList[1]), float(resultValueList[2]), float(resultValueList[3]))
            resultDlg, procEntityBase = DlgAixmSelectPosition.smethod_0(self, self.data, point3d, ProcEntityListType.Holding)
            if (resultDlg and procEntityBase != None):
                if (not self.pnlBasedOn.Contains(procEntityBase)):
                    self.pnlBasedOn.Add(procEntityBase);
                self.pnlBasedOn.SelectedIndex = self.pnlBasedOn.IndexOf(procEntityBase);
    def acceptDlg(self):
        selectedItem = self.pnlBasedOn.SelectedItem;
        codeTypeHoldProcAixm = self.pnlType.SelectedItem
        for row in self.table:
            flag = True;
            if (self.selected != None and row == self.selected):
                flag = False;
            if (row["basedOnEnt"] != selectedItem):
                flag = False;
            if (row["codeType"] != codeTypeHoldProcAixm):
                flag = False;
            if (not flag):
                continue;
            strS = "Cannot create a duplicate procedure entry.\n\nBased on = {0}\nType = {1}".format(self.pnlBasedOn.SelectedItem, self.pnlType.SelectedItem);
            QMessageBox.warning(self, "Error", strS);
            return;
        self.accept()
    

    def method_6(self):
        pass

    @staticmethod
    def smethod_0(dataBaseHoldings_0, dataBaseProcedureData_0, dataRow_0):
        flag = False;
        dlgAixmHolding = DlgAixmHolding()
        dlgAixmHolding.data = dataBaseProcedureData_0;
        dlgAixmHolding.table = dataBaseHoldings_0;
        dlgAixmHolding.selected = dataRow_0;
        dataBaseProcedureData_0.method_59(dlgAixmHolding.pnlBasedOn, ProcEntityListType.Holding);
        dlgAixmHolding.pnlType.Items = CodeTypeHoldProcAixm.Items;
        if (dataRow_0 != None and len(dataRow_0) > 0):
            dlgAixmHolding.pnlBasedOn.SelectedIndex = dlgAixmHolding.pnlBasedOn.IndexOf(dataRow_0["basedOnEnt"]);
            dlgAixmHolding.pnlType.SelectedIndex = dlgAixmHolding.pnlType.method_3(dataRow_0["codeType"]);
            if (dataRow_0["txtDescr"] != None):
                dlgAixmHolding.txtDescription.Value = dataRow_0["txtDescr"];
            if (dataRow_0["txtRmk"] != None):
                dlgAixmHolding.txtRemarks.Value = dataRow_0["txtRmk"];
        resultDlg = dlgAixmHolding.exec_()
        if (resultDlg == 1):
            dataRow0 = dataRow_0 == None or len(dataRow_0) == 0;
            strS = [];
            if (not dataRow0):
                for a in dataBaseHoldings_0.nameList:
                    strS.append(None)
                # str = new string[dataBaseHoldings_0.Columns.Count];
                i = 0
                for name in dataBaseHoldings_0.nameList:
                    strS[i] = dataRow_0[name]
                    i += 1
            else:
                dataRow_0 = dataBaseHoldings_0.NewRow();
            dataRow_0["basedOnEnt"] = dlgAixmHolding.pnlBasedOn.SelectedItem;
            if (dataRow0):
                dataRow_0["oldBasedOnEnt"] = dataRow_0["basedOnEnt"];
            dataRow_0["codeType"] = dlgAixmHolding.pnlType.SelectedItem;
            if (dataRow0):
                dataRow_0["oldCodeType"] = dataRow_0["codeType"];
            if (not String.IsNullOrEmpty(dlgAixmHolding.txtDescription.Value)):
                dataRow_0["txtDescr"] = dlgAixmHolding.txtDescription.Value;
            else:
                dataRow_0["txtDescr"] = None;
            if (not String.IsNullOrEmpty(dlgAixmHolding.txtRemarks.Value)):
                dataRow_0["txtRmk"] = dlgAixmHolding.txtRemarks.Value;
            else:
                dataRow_0["txtRmk"] = None;
            if (dataRow0):
                dataRow_0["procLegs"] = DataBaseProcedureLegs();
                dataRow_0["procLegsEx"] = DataBaseProcedureLegsEx();
            if (not dataRow0):
                num = 1;
                while (num < len(strS)):
                    if (not strS[num] == dataRow_0[dataRow_0.nameList[num]]):
                        dataRow_0["changed"] = "True";
                        if (dataRow0):
                            dataBaseHoldings_0.RowsAdd(dataRow_0);
                        flag = True;
                        return flag;
                    else:
                        num += 1;
            else:
                dataRow_0["new"] = "True";
            if (dataRow0):
                dataBaseHoldings_0.RowsAdd(dataRow_0);
            flag = True;
            return flag;
        return flag
Beispiel #20
0
class DlgAixmSelectPosition(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)

        self.resize(290, 136)
        self.setWindowTitle("New DPN DB Entry")
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        verticalLayoutDlg = QVBoxLayout(self)
        verticalLayoutDlg.setObjectName(("verticalLayoutDlg"))

        self.groupBox = GroupBox(self)
        self.groupBox.Caption = "Existing DB Entries"
        verticalLayoutDlg.addWidget(self.groupBox)

        self.lstItems = ListBox(self.groupBox)
        self.groupBox.Add = self.lstItems

        frame = Frame(self, "HL")
        verticalLayoutDlg.addWidget(frame)

        self.btnNewDPN = QPushButton(frame)
        self.btnNewDPN.setObjectName("btnNewDPN")
        self.btnNewDPN.setText("New DPN...")
        frame.Add = self.btnNewDPN

        self.btnNewPCP = QPushButton(frame)
        self.btnNewPCP.setObjectName("btnNewPCP")
        self.btnNewPCP.setText("New PCP...")
        frame.Add = self.btnNewPCP

        self.btnBoxOkCancel = QDialogButtonBox(frame)
        self.btnBoxOkCancel.setObjectName(("btnBoxOkCancel"))
        self.btnBoxOkCancel.setStandardButtons(QDialogButtonBox.Cancel
                                               | QDialogButtonBox.Ok)
        self.connect(self.btnBoxOkCancel, SIGNAL("accepted()"), self.acceptDlg)
        self.connect(self.btnBoxOkCancel, SIGNAL("rejected()"), self.reject)

        self.btnNewDPN.clicked.connect(self.btnNewDPN_Click)
        self.btnNewPCP.clicked.connect(self.btnNewPCP_Click)

        frame.Add = self.btnBoxOkCancel

        self.newTypeSelected = None

    def acceptDlg(self):
        self.accept()

    def btnNewDPN_Click(self):
        self.newTypeSelected = NewDbEntryType.DPN
        self.reject()

    def btnNewPCP_Click(self):
        self.newTypeSelected = NewDbEntryType.PCP
        self.reject()

    @staticmethod
    def resultPointValueListMethod(resultValueList, dataBaseProcedureData_0,
                                   point3d_0, procEntityListType_0, parent):
        if len(resultValueList) > 0:
            lat = None
            lon = None
            if define._units == QGis.Meters:
                point3d = QgisHelper.CrsTransformPoint(
                    float(resultValueList[1]), float(resultValueList[2]),
                    define._xyCrs, define._latLonCrs)

                lat = Degrees(point3d.get_Y(), None, None,
                              DegreesType.Latitude)
                lon = Degrees(point3d.get_X(), None, None,
                              DegreesType.Longitude)
            else:
                lat = Degrees(float(resultValueList[2]), None, None,
                              DegreesType.Latitude)
                lon = Degrees(float(resultValueList[1]), None, None,
                              DegreesType.Longitude)
            str0 = lon.method_1("dddmmss.ssssH")
            textString = lat.method_1("ddmmss.ssssH")
            procEntityBases = DlgAixmSelectPosition.smethod_1(
                dataBaseProcedureData_0, procEntityListType_0, point3d_0,
                textString, str0)
            dlgAixmSelectPosition = DlgAixmSelectPosition()
            naN = None
            degree = None
            result, naN, degree = Geo.smethod_2(point3d_0.get_X(),
                                                point3d_0.get_Y())
            if (result):
                dataBaseProcedureData_0.method_60(procEntityBases,
                                                  procEntityListType_0,
                                                  naN.ToString(),
                                                  degree.ToString())
            dlgAixmSelectPosition.lstItems.Sorted = True
            for procEntityBase in procEntityBases:
                dlgAixmSelectPosition.lstItems.Add(procEntityBase)
            if (procEntityListType_0 != ProcEntityListType.CentersEx
                    and procEntityListType_0 != ProcEntityListType.FixesEx):
                dlgAixmSelectPosition.btnNewPCP.setEnabled(False)
                dlgAixmSelectPosition.btnNewPCP.setVisible(False)
            resultDlg = dlgAixmSelectPosition.exec_()
            procEntityBase_0 = None
            if (resultDlg != 1):
                if dlgAixmSelectPosition.newTypeSelected == NewDbEntryType.DPN:
                    flag, procEntityBase_0 = DlgAixmNewDPN.smethod_0(
                        dataBaseProcedureData_0, naN, degree)
                elif dlgAixmSelectPosition.newTypeSelected == NewDbEntryType.PCP:
                    flag, procEntityBase_0 = DlgAixmNewPCP.smethod_0(
                        dataBaseProcedureData_0, naN, degree)
                else:
                    flag = False
            else:
                procEntityBase_0 = dlgAixmSelectPosition.lstItems.SelectedItem
                flag = True
            QObject.emit(parent,
                         SIGNAL("DlgAixmSelectPosition_Smethod_0_Event"), flag,
                         procEntityBase_0)
            return

    @staticmethod  #### complete
    def smethod_0(dataBaseProcedureData_0, point3d_0, procEntityListType_0):
        flag = False
        procEntityBase_0 = None
        CaptureCoordTool = CaptureCoordinateToolUpdate(
            define._canvas, dataBaseProcedureData_0, point3d_0,
            procEntityListType_0)
        define._canvas.setMapTool(CaptureCoordTool)
        QObject.connect(CaptureCoordTool, SIGNAL("resultPointValueList"),
                        DlgAixmSelectPosition.resultPointValueListMethod)
        return CaptureCoordTool

    @staticmethod
    def smethod_1(dataBaseProcedureData_0, procEntityListType_0, point3d_0,
                  textString, strS):
        procEntityBases = []
        for case in switch(procEntityListType_0):
            if case(ProcEntityListType.Holding) or case(
                    ProcEntityListType.Fixes) or case(
                        ProcEntityListType.FixesEx) or case(
                            ProcEntityListType.Centers) or case(
                                ProcEntityListType.CentersEx):
                if (not String.IsNullOrEmpty(textString)
                        and not String.IsNullOrEmpty(strS)):
                    dataBaseProcedureData_0.method_60(procEntityBases,
                                                      procEntityListType_0,
                                                      textString, strS)
                return procEntityBases
            else:
                return None
        return None
Beispiel #21
0
class DlgCrcReadWrite(QDialog):
    def __init__(self, parent, rwFlag="r"):
        QDialog.__init__(self, parent)
        self.rwFlag = rwFlag
        self.resize(100, 70)
        if self.rwFlag == "r":
            self.setWindowTitle("CRC Reader")
        else:
            self.setWindowTitle("CRC Writer")
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        verticalLayoutDlg = QVBoxLayout(self)
        verticalLayoutDlg.setObjectName(("verticalLayoutDlg"))

        self.groupBox1 = GroupBox(self)
        self.groupBox1.Caption = ""
        verticalLayoutDlg.addWidget(self.groupBox1)

        self.pnlFile = TextBoxPanel(self.groupBox1)
        self.pnlFile.Caption = "File"
        self.pnlFile.LabelWidth = 120
        self.pnlFile.textBox.setMaximumWidth(200)
        self.pnlFile.textBox.setMinimumWidth(200)
        self.pnlFile.Button = "openData.png"
        self.groupBox1.Add = self.pnlFile

        self.pnlSuppliedCrcValue = TextBoxPanel(self.groupBox1)
        self.pnlSuppliedCrcValue.Caption = "Supplied CRC Value"
        self.pnlSuppliedCrcValue.LabelWidth = 120
        self.pnlSuppliedCrcValue.Enabled = False
        self.groupBox1.Add = self.pnlSuppliedCrcValue

        if self.rwFlag == "w":
            self.pnlSuppliedCrcValue.Visible = False

        self.pnlCalculatedCrcValue = TextBoxPanel(self.groupBox1)
        self.pnlCalculatedCrcValue.Caption = "Calculated CRC Value"
        self.pnlCalculatedCrcValue.LabelWidth = 120
        self.pnlCalculatedCrcValue.Enabled = False
        self.groupBox1.Add = self.pnlCalculatedCrcValue

        self.btnBoxOkCancel = QDialogButtonBox(self)
        self.btnBoxOkCancel.setObjectName(("btnBoxOkCancel"))
        self.btnBoxOkCancel.setStandardButtons(QDialogButtonBox.Cancel
                                               | QDialogButtonBox.Ok)
        btnQuit = self.btnBoxOkCancel.button(QDialogButtonBox.Ok)
        btnQuit.setText("Quit")
        btnCancel = self.btnBoxOkCancel.button(QDialogButtonBox.Cancel)
        btnCancel.setVisible(False)

        self.connect(self.btnBoxOkCancel, SIGNAL("accepted()"), self.acceptDlg)

        self.connect(self.pnlFile, SIGNAL("Event_1"), self.pnlFileEvent_1)

        verticalLayoutDlg.addWidget(self.btnBoxOkCancel)

    def pnlFileEvent_1(self):

        inputFilePath = QFileDialog.getOpenFileName(
            self, "Open Xml File", QCoreApplication.applicationDirPath(),
            "Xml Files (*.xml)")
        if inputFilePath == "":
            return
        fileInfo = QFileInfo(inputFilePath)
        self.pnlFile.Value = fileInfo.fileName()
        contents = None
        with open(inputFilePath, 'rb', 0) as tempFile:
            contents = tempFile.read()
            tempFile.close()
        bytes = FasDataBlockFile.CRC_Calculation(contents)

        string_0 = QString(inputFilePath)

        crcFileDir = string_0.left(string_0.length() - 3) + "crc"
        fileInfo = QFileInfo(crcFileDir)
        if self.rwFlag == "r":
            if not fileInfo.exists():
                QMessageBox.warning(self, "Warning",
                                    "CRC file is not existing.")
                return
            crcFileContents = None
            with open(crcFileDir, 'rb', 0) as tempFileCrc:
                crcFileContents = tempFileCrc.read()
                tempFileCrc.close()
            if bytes != crcFileContents:
                self.pnlCalculatedCrcValue.textBox.setStyleSheet(
                    "color: rgb(255, 0, 0);")
            else:
                self.pnlCalculatedCrcValue.textBox.setStyleSheet(
                    "color: rgb(0, 0, 0);")
            self.pnlSuppliedCrcValue.Value = crcFileContents
            self.pnlCalculatedCrcValue.Value = bytes
        else:
            fileStream = open(crcFileDir, 'wb')
            fileStream.write(bytes)
            fileStream.close()
            self.pnlCalculatedCrcValue.Value = bytes

    def acceptDlg(self):

        self.accept()

    @staticmethod
    def smethod_0(parent, inputFilePath, rwFlag="r"):
        flag = False
        dlgCrcReadWrite = DlgCrcReadWrite(parent, rwFlag)

        resultDlg = dlgCrcReadWrite.exec_()
        if (resultDlg == 0):
            flag = False
        else:
            flag = True
        return flag
Beispiel #22
0
class DlgAixmProcLegsEx(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)

        self.resize(290, 136)
        self.setWindowTitle("Procedure Legs (AIXM 4.5+)")
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        verticalLayoutDlg = QVBoxLayout(self)
        verticalLayoutDlg.setObjectName(("verticalLayoutDlg"))

        self.gbAll = GroupBox(self, "HL")
        self.gbAll.Caption = "Legs"
        verticalLayoutDlg.addWidget(self.gbAll)

        self.trvLegs = QTreeView(self.gbAll)
        self.trvLegsStdModel = StandardItemModel()
        self.trvLegs.setModel(self.trvLegsStdModel)
        self.gbAll.Add = self.trvLegs

        self.flowLayoutPanel1 = Frame(self.gbAll)
        self.gbAll.Add = self.flowLayoutPanel1

        self.btnAdd = QPushButton(self.flowLayoutPanel1)
        icon = QIcon()
        icon.addPixmap(QPixmap("Resource/add.png"), QIcon.Normal, QIcon.Off)
        self.btnAdd.setIcon(icon)
        self.flowLayoutPanel1.Add = self.btnAdd

        self.btnRemove = QPushButton(self.flowLayoutPanel1)
        icon = QIcon()
        icon.addPixmap(QPixmap("Resource/remove.png"), QIcon.Normal, QIcon.Off)
        self.btnRemove.setIcon(icon)
        self.flowLayoutPanel1.Add = self.btnRemove

        self.btnMoveUp = QPushButton(self.flowLayoutPanel1)
        icon = QIcon()
        icon.addPixmap(QPixmap("Resource/up.png"), QIcon.Normal, QIcon.Off)
        self.btnMoveUp.setIcon(icon)
        self.flowLayoutPanel1.Add = self.btnMoveUp

        self.btnMoveDown = QPushButton(self.flowLayoutPanel1)
        icon = QIcon()
        icon.addPixmap(QPixmap("Resource/down.png"), QIcon.Normal, QIcon.Off)
        self.btnMoveDown.setIcon(icon)
        self.flowLayoutPanel1.Add = self.btnMoveDown

        self.scrollBox = Frame(self.gbAll)
        self.gbAll.Add = self.scrollBox

        self.gbPosition = GroupBox(self.scrollBox)
        self.gbPosition.Caption = "Fix"
        self.scrollBox.Add = self.gbPosition

        self.cmbPosUid = ComboBoxPanel(self.gbPosition)
        self.cmbPosUid.Caption = "Position"
        self.cmbPosUid.Button = "coordinate_capture.png"
        self.gbPosition.Add = self.cmbPosUid

        self.gbAttributes = GroupBox(self.scrollBox)
        self.gbAttributes.Caption = "Attributes"
        self.scrollBox.Add = self.gbAttributes

        self.pnlPathType = ComboBoxPanel(self.gbAttributes)
        self.pnlPathType.Caption = "Path Type"
        self.gbAttributes.Add = self.pnlPathType

        self.pnlLegType = ComboBoxPanel(self.gbAttributes)
        self.pnlLegType.Caption = "Leg Type"
        self.gbAttributes.Add = self.pnlLegType

        self.cmbCenUid = ComboBoxPanel(self.gbAttributes)
        self.cmbCenUid.Caption = "Center"
        self.cmbCenUid.Button = "coordinate_capture.png"
        self.gbAttributes.Add = self.cmbCenUid

        self.pnlFlyBy = ComboBoxPanel(self.gbAttributes)
        self.pnlFlyBy.Caption = "Fly-By"
        self.gbAttributes.Add = self.pnlFlyBy

        self.pnlMinAlt = AltitudeBoxPanel(self.gbAttributes)
        self.pnlMinAlt.CaptionUnits = "ft"
        self.pnlMinAlt.Caption = "Minimum Altitude"
        self.gbAttributes.Add = self.pnlMinAlt

        self.pnlSegLength = DistanceBoxPanel(self.gbAttributes,
                                             DistanceUnits.NM)
        self.pnlSegLength.Caption = "Segment Length"
        self.gbAttributes.Add = self.pnlSegLength

        self.pnlCourse = TrackRadialBoxPanel(self.gbAttributes)
        self.pnlCourse.Caption = "Course"
        self.gbAttributes.Add = self.pnlCourse

        self.pnlLegVOR = Frame(self.gbAttributes)
        self.gbAttributes.Add = self.pnlLegVOR

        f1 = Frame(self.pnlLegVOR, "HL")
        self.pnlLegVOR.Add = f1

        self.cmbLegVor = ComboBoxPanel(f1)
        self.cmbLegVor.Caption = "VOR / Radial (" + define._degreeStr + ")"
        f1.Add = self.cmbLegVor

        self.txtLegRadial = TrackRadialBoxPanel(f1)
        self.txtLegRadial.Caption = ""
        self.txtLegRadial.LabelWidth = 0
        f1.Add = self.txtLegRadial

        f2 = Frame(self.pnlLegVOR, "HL")
        self.pnlLegVOR.Add = f2

        self.cmbLegBackVor = ComboBoxPanel(f2)
        self.cmbLegBackVor.Caption = "Reverse VOR / Radial (" + define._degreeStr + ")"
        f2.Add = self.cmbLegBackVor

        self.txtLegBackRadial = TrackRadialBoxPanel(f2)
        self.txtLegBackRadial.Caption = ""
        self.txtLegBackRadial.LabelWidth = 0
        f2.Add = self.txtLegBackRadial

        self.pnlPointType = ComboBoxPanel(self.gbAttributes)
        self.pnlPointType.Caption = "Point Type"
        self.gbAttributes.Add = self.pnlPointType

        self.pnlRepPointType = ComboBoxPanel(self.gbAttributes)
        self.pnlRepPointType.Caption = "Reporting Point Type"
        self.gbAttributes.Add = self.pnlRepPointType

        self.pnlPointVor = Frame(self.gbAttributes)
        self.gbAttributes.Add = self.pnlPointVor

        frame1 = Frame(self.pnlPointVor, "HL")
        self.pnlPointVor.Add = frame1

        self.cmbPointVor = ComboBoxPanel(frame1)
        self.cmbPointVor.Caption = "Point VOR / Radial (" + define._degreeStr + ")"
        frame1.Add = self.cmbPointVor

        self.txtPointRadial = TrackRadialBoxPanel(frame1)
        self.txtPointRadial.Caption = ""
        self.txtPointRadial.LabelWidth = 0
        frame1.Add = self.txtPointRadial

        frame2 = Frame(self.pnlPointVor, "HL")
        self.pnlPointVor.Add = frame2

        self.cmbPointDme1 = ComboBoxPanel(frame2)
        self.cmbPointDme1.Caption = "Point 1. DME / Distance (nm)"
        frame2.Add = self.cmbPointDme1

        self.txtPointDme1 = DistanceBoxPanel(frame2, DistanceUnits.NM)
        self.txtPointDme1.Caption = ""
        self.txtPointDme1.LabelWidth = 0
        frame2.Add = self.txtPointDme1

        frame3 = Frame(self.pnlPointVor, "HL")
        self.pnlPointVor.Add = frame3

        self.cmbPointDme2 = ComboBoxPanel(frame3)
        self.cmbPointDme2.Caption = "Point 2. DME / Distance (nm)"
        frame3.Add = self.cmbPointDme2

        self.txtPointDme2 = DistanceBoxPanel(frame3, DistanceUnits.NM)
        self.txtPointDme2.Caption = ""
        self.txtPointDme2.LabelWidth = 0
        frame3.Add = self.txtPointDme2

        self.txtFlyDuration = TextBoxPanel(self.pnlPointVor, True)
        self.txtFlyDuration.Caption = "Flying Time Duration"
        self.pnlPointVor.Add = self.txtFlyDuration

        self.txtRemarks = TextBoxPanel(self.pnlPointVor, True)
        self.txtRemarks.Caption = "Remarks"
        self.pnlPointVor.Add = self.txtRemarks

        self.btnBoxOkCancel = QDialogButtonBox(self)
        self.btnBoxOkCancel.setObjectName(("btnBoxOkCancel"))
        self.btnBoxOkCancel.setStandardButtons(QDialogButtonBox.Cancel
                                               | QDialogButtonBox.Ok)
        self.connect(self.btnBoxOkCancel, SIGNAL("accepted()"), self.acceptDlg)
        self.connect(self.btnBoxOkCancel, SIGNAL("rejected()"), self.reject)

        self.btnAdd.clicked.connect(self.btnAdd_Click)
        self.btnMoveDown.clicked.connect(self.btnMoveDown_Click)
        self.btnMoveUp.clicked.connect(self.btnMoveUp_Click)
        self.btnRemove.clicked.connect(self.btnRemove_Click)

        verticalLayoutDlg.addWidget(self.btnBoxOkCancel)

        self.trvLegs.pressed.connect(self.trvLegs_pressed)

        self.data = None
        self.legs = None
        self.aerodrome = None
        self.magnVar = 0.0

        self.trvLegs.setHeaderHidden(True)

        self.pnlPointType.Items = ["IAF", "IF", "FAF", "FAP", "MAPt", "TP"]

        for value in CodeLegTypeAixm.Items:
            self.pnlLegType.Add(value)

        for value in CodePathTypeAixm.Items:
            self.pnlPathType.Add(value)

        for value in CodeRepAtcAixm.Items:
            self.pnlRepPointType.Add(value)

        for value in CodeTypeFlyByAixm.Items:
            self.pnlFlyBy.Add(value)
        self.method_6()

        self.connect(self.txtRemarks, SIGNAL("Event_0"),
                     self.txtRemarks_Event_0)
        self.connect(self.txtPointDme2, SIGNAL("Event_0"),
                     self.txtPointDme2_Event_0)
        self.connect(self.cmbPointDme2, SIGNAL("Event_0"),
                     self.cmbPointDme2_Event_0)
        self.connect(self.txtPointDme1, SIGNAL("Event_0"),
                     self.txtPointDme1_Event_0)
        self.connect(self.cmbPointDme1, SIGNAL("Event_0"),
                     self.cmbPointDme1_Event_0)
        self.connect(self.cmbPointVor, SIGNAL("Event_0"),
                     self.cmbPointVor_Event_0)
        self.connect(self.txtPointRadial, SIGNAL("Event_0"),
                     self.txtPointRadial_Event_0)
        self.connect(self.txtFlyDuration, SIGNAL("Event_0"),
                     self.txtFlyDuration_Event_0)
        self.connect(self.pnlRepPointType, SIGNAL("Event_0"),
                     self.pnlRepPointType_Event_0)

        self.connect(self.pnlPointType, SIGNAL("Event_0"),
                     self.pnlPointType_Event_0)

        self.connect(self.txtLegBackRadial, SIGNAL("Event_0"),
                     self.txtLegBackRadial_Event_0)

        self.connect(self.cmbLegBackVor, SIGNAL("Event_0"),
                     self.cmbLegBackVor_Event_0)

        self.connect(self.cmbLegVor, SIGNAL("Event_0"), self.cmbLegVor_Event_0)

        self.connect(self.txtLegRadial, SIGNAL("Event_0"),
                     self.txtLegRadial_Event_0)

        self.connect(self.pnlCourse, SIGNAL("Event_0"), self.pnlCourse_Event_0)

        self.connect(self.pnlSegLength, SIGNAL("Event_0"),
                     self.pnlSegLength_Event_0)

        self.connect(self.pnlMinAlt, SIGNAL("Event_0"), self.pnlMinAlt_Event_0)

        self.connect(self.pnlFlyBy, SIGNAL("Event_0"), self.pnlFlyBy_Event_0)

        self.connect(self.cmbCenUid, SIGNAL("Event_0"), self.cmbCenUid_Event_0)

        self.connect(self.pnlLegType, SIGNAL("Event_0"),
                     self.pnlLegType_Event_0)

        self.connect(self.pnlPathType, SIGNAL("Event_0"),
                     self.pnlPathType_Event_0)

        self.connect(self.cmbPosUid, SIGNAL("Event_0"), self.cmbPosUid_Event_0)
        self.connect(self.cmbCenUid, SIGNAL("Event_3"), self.method_14)
        self.connect(self.cmbPosUid, SIGNAL("Event_3"), self.method_13)

        # self.cmbCenter.imageButton.clicked.connect(self.method_14)
        # self.cmbFixPos.imageButton.clicked.connect(self.method_13)
    def btnAdd_Click(self):
        if (len(self.trvLegs.selectedIndexes()) == 0 and not self.method_5()):
            return
        listInsertPosition = ListInsertPosition.Append
        resultDlg, listInsertPosition = DlgAixmInsertLeg.smethod_0(
            listInsertPosition)
        if (self.trvLegsStdModel.rowCount() > 0 and not resultDlg):
            return
        count = self.trvLegsStdModel.rowCount()
        if (listInsertPosition == ListInsertPosition.Before):
            count = self.trvLegs.selectedIndexes()[0].row()
        elif (listInsertPosition == ListInsertPosition.After):
            count = self.trvLegs.selectedIndexes()[0].row() + 1
        self.trvLegsStdModel.setItem(
            self.trvLegsStdModel.rowCount(),
            QStandardItem(str(self.trvLegsStdModel.rowCount() + 1)))
        self.legs.insert(count, DataBaseProcedureLegEx())
        self.trvLegs.setCurrentIndex(self.trvLegsStdModel.index(count, 0))
        self.trvLegs_pressed()

    def btnMoveDown_Click(self):
        if (len(self.trvLegs.selectedIndexes()) == 0):
            return
        index = self.trvLegs.selectedIndexes()[0].row()
        item = self.legs[index]
        self.legs.pop(index)
        self.legs.insert(index + 1, item)
        self.trvLegs.setCurrentIndex(self.trvLegsStdModel.index(index + 1, 0))
        self.trvLegs_pressed()

    def btnMoveUp_Click(self):
        if (len(self.trvLegs.selectedIndexes()) == 0):
            return
        index = self.trvLegs.selectedIndexes()[0].row()
        item = self.legs[index]
        self.legs.pop(index)
        self.legs.insert(index - 1, item)
        self.trvLegs.setCurrentIndex(self.trvLegsStdModel.index(index - 1, 0))
        self.trvLegs_pressed()

    def btnRemove_Click(self):
        item = None
        if (len(self.trvLegs.selectedIndexes()) == 0):
            return
        if (QMessageBox.question(
                self, "Question",
                "Are you sure you want to delete the selected procedure leg?",
                QMessageBox.Yes | QMessageBox.No) == QMessageBox.Yes):
            index = self.trvLegs.selectedIndexes()[0].row()
            self.legs.pop(index)
            self.trvLegsStdModel.takeRow(self.trvLegsStdModel.rowCount() - 1)
            if (index >= self.trvLegsStdModel.rowCount() - 1):
                index -= 1
            # treeView = self.trvLegs;
            # if (index >= 0):
            if self.trvLegsStdModel.rowCount() > 0 and index < 0:
                index = 0
            self.trvLegs.setCurrentIndex(self.trvLegsStdModel.index(index, 0))

            self.trvLegs_pressed()

    def cmbPosUid_Event_0(self):
        self.txtFlyDuration_TextChanged(self.cmbPosUid)

    def txtRemarks_Event_0(self):
        self.txtFlyDuration_TextChanged(self.txtRemarks)

    def txtPointDme2_Event_0(self):
        self.txtFlyDuration_TextChanged(self.txtPointDme2)

    def cmbPointDme2_Event_0(self):
        self.txtFlyDuration_TextChanged(self.cmbPointDme2)

    def txtPointDme1_Event_0(self):
        self.txtFlyDuration_TextChanged(self.txtPointDme1)

    def cmbPointDme1_Event_0(self):
        self.txtFlyDuration_TextChanged(self.cmbPointDme1)

    def cmbPointVor_Event_0(self):
        self.txtFlyDuration_TextChanged(self.cmbPointVor)

    def txtPointRadial_Event_0(self):
        self.txtFlyDuration_TextChanged(self.txtPointRadial)

    def txtFlyDuration_Event_0(self):
        self.txtFlyDuration_TextChanged(self.txtFlyDuration)

    def pnlRepPointType_Event_0(self):
        self.txtFlyDuration_TextChanged(self.pnlRepPointType)

    def pnlPointType_Event_0(self):
        self.txtFlyDuration_TextChanged(self.pnlPointType)

    def txtLegBackRadial_Event_0(self):
        self.txtFlyDuration_TextChanged(self.txtLegBackRadial)

    def cmbLegBackVor_Event_0(self):
        self.txtFlyDuration_TextChanged(self.cmbLegBackVor)

    def cmbLegVor_Event_0(self):
        self.txtFlyDuration_TextChanged(self.cmbLegVor)

    def txtLegRadial_Event_0(self):
        self.txtFlyDuration_TextChanged(self.txtLegRadial)

    def pnlCourse_Event_0(self):
        self.txtFlyDuration_TextChanged(self.pnlCourse)

    def pnlSegLength_Event_0(self):
        self.txtFlyDuration_TextChanged(self.pnlSegLength)

    def pnlMinAlt_Event_0(self):
        self.txtFlyDuration_TextChanged(self.pnlMinAlt)

    def pnlFlyBy_Event_0(self):
        self.txtFlyDuration_TextChanged(self.pnlFlyBy)

    def cmbCenUid_Event_0(self):
        self.txtFlyDuration_TextChanged(self.cmbCenUid)

    def pnlLegType_Event_0(self):
        self.txtFlyDuration_TextChanged(self.pnlLegType)

    def pnlPathType_Event_0(self):
        self.txtFlyDuration_TextChanged(self.pnlPathType)

    def trvLegs_pressed(self):
        self.method_6()
        self.method_8()

    def acceptDlg(self):
        self.legs.refresh()
        QObject.emit(self, SIGNAL("DlgAixmProcLegs_Smethod_0_Event"),
                     self.legs, self.data)
        self.accept()

    def method_6(self):
        self.btnOK = self.btnBoxOkCancel.button(QDialogButtonBox.Ok)
        self.btnOK.setEnabled(len(self.trvLegs.selectedIndexes()) > 0)
        self.btnRemove.setEnabled(len(self.trvLegs.selectedIndexes()) > 0)
        self.btnMoveUp.setEnabled(
            (len(self.trvLegs.selectedIndexes()) > 0
             and self.trvLegs.selectedIndexes()[0].row() != 0) and True
            or False)
        self.btnMoveDown.setEnabled(
            (len(self.trvLegs.selectedIndexes()) <= 0
             or self.trvLegsStdModel.rowCount() <= 0) and False
            or ((len(self.trvLegs.selectedIndexes()) > 0)
                and self.trvLegs.selectedIndexes()[0].row() <
                self.trvLegsStdModel.rowCount() - 1))

    def method_7(self):
        for i in range(self.legs.Count):
            num = i + 1
            self.trvLegsStdModel.setItem(i, QStandardItem(str(num)))
        self.method_6()

    def method_8(self):
        if (self.trvLegs.selectedIndexes() == None
                or len(self.trvLegs.selectedIndexes()) == 0):
            self.scrollBox.Enabled = False
            self.cmbPosUid.SelectedIndex = -1
            self.pnlPathType.SelectedIndex = -1
            self.pnlLegType.SelectedIndex = -1
            self.cmbCenUid.SelectedIndex = -1
            self.pnlFlyBy.SelectedIndex = -1
            self.pnlMinAlt.Value = None
            self.pnlSegLength.Value = None
            self.pnlCourse.Value = None
            self.cmbLegVor.SelectedIndex = -1
            self.txtLegRadial.Value = 0
            self.cmbLegBackVor.SelectedIndex = -1
            self.txtLegBackRadial.Value = 0
            self.pnlPointType.Value = ""
            self.pnlRepPointType.SelectedIndex = -1
            self.cmbPointVor.SelectedIndex = -1
            self.txtPointRadial.Value = 0
            self.cmbPointDme1.SelectedIndex = -1
            self.txtPointDme1.Value = None
            self.cmbPointDme2.SelectedIndex = -1
            self.txtPointDme2.Value = None
            self.txtFlyDuration.Value = ""
            self.txtRemarks.Value = ""
            return
        self.scrollBox.Enabled = True
        item = self.legs[self.trvLegs.selectedIndexes()[0].row()]
        if (item.PointEnt == None):
            self.cmbPosUid.SelectedIndex = -1
        else:
            self.cmbPosUid.SelectedIndex = self.cmbPosUid.IndexOf(
                item.PointEnt)
        self.pnlPathType.SelectedIndex = self.method_10(
            self.pnlPathType.Items, item.CodePathType)
        self.pnlLegType.SelectedIndex = self.method_10(self.pnlLegType.Items,
                                                       item.CodeLegType)
        if (item.CodeLegType != CodeLegTypeAixm.CCA):
            if (item.CodeLegType == CodeLegTypeAixm.CWA):
                if (item.CenterEnt == None):
                    self.cmbCenUid.SelectedIndex = -1
                else:
                    self.cmbCenUid.SelectedIndex = self.cmbCenUid.IndexOf(
                        item.CenterEnt)
                self.cmbCenUid.Visible = True
            else:
                self.cmbCenUid.SelectedIndex = -1
                self.cmbCenUid.Visible = False
                # goto Label0;
        else:
            # Label2:
            if (item.CenterEnt == None):
                self.cmbCenUid.SelectedIndex = -1
            else:
                self.cmbCenUid.SelectedIndex = self.cmbCenUid.IndexOf(
                    item.CenterEnt)
            self.cmbCenUid.Visible = True

    # Label0:
        self.pnlFlyBy.SelectedIndex = self.method_10(self.pnlFlyBy.Items,
                                                     item.CodeFlyBy)
        self.pnlMinAlt.Value = item.ValMinAlt
        self.pnlSegLength.Value = item.ValDist
        self.pnlCourse.Value = item.ValCourse
        if (item.VorUidLeg == None):
            self.cmbLegVor.SelectedIndex = -1
        else:
            self.cmbLegVor.SelectedIndex = self.cmbLegVor.IndexOf(
                item.VorUidLeg)
        self.txtLegRadial.Value = item.ValLegRadial
        if (item.VorUidLegBack == None):
            self.cmbLegBackVor.SelectedIndex = -1
        else:
            self.cmbLegBackVor.SelectedIndex = self.cmbLegBackVor.IndexOf(
                item.VorUidLegBack)
        self.txtLegBackRadial.Value = item.ValLegRadialBack
        self.pnlPointType.Value = item.CodePointType
        self.pnlRepPointType.SelectedIndex = self.method_10(
            self.pnlRepPointType.Items, item.CodeRepAtc)
        if (item.VorUidPoint == None):
            self.cmbPointVor.SelectedIndex = -1
        else:
            self.cmbPointVor.SelectedIndex = self.cmbPointVor.IndexOf(
                item.VorUidPoint)
        self.txtPointRadial.Value = item.ValPointRadial
        if (item.UidPointDist1 == None):
            self.cmbPointDme1.SelectedIndex = -1
        else:
            self.cmbPointDme1.SelectedIndex = self.cmbPointDme1.IndexOf(
                item.UidPointDist1)
        self.txtPointDme1.Value = item.ValPointDist1
        if (item.UidPointDist2 == None):
            self.cmbPointDme2.SelectedIndex = -1
        else:
            self.cmbPointDme2.SelectedIndex = self.cmbPointDme2.IndexOf(
                item.UidPointDist2)
        self.txtPointDme2.Value = item.ValPointDist2
        self.txtFlyDuration.Value = item.ValDur
        self.txtRemarks.Value = item.TxtRmk

    def method_9(self, ilist_0, string_0):
        for i in range(len(ilist_0)):
            if (String.StartsWith(ilist_0[i], string_0)):
                return i
        return -1

    def method_10(self, ilist_0, string_0):
        for i in range(len(ilist_0)):
            if (String.Equals(ilist_0[i], string_0)):
                return i
        return -1

    def txtFlyDuration_TextChanged(self, sender):
        if (self.trvLegs.selectedIndexes() == None
                or len(self.trvLegs.selectedIndexes()) == 0):
            return
        item = self.legs[self.trvLegs.selectedIndexes()[0].row()]
        if (sender == self.cmbPosUid):
            item.PointEnt = self.cmbPosUid.SelectedItem
            return
        if (sender == self.pnlPathType):
            item.CodePathType = self.pnlPathType.SelectedItem
            return
        if (sender == self.pnlLegType):
            item.CodeLegType = self.pnlLegType.SelectedItem
            self.cmbCenUid.Visible = (
                item.CodeLegType == CodeLegTypeAixm.CCA
            ) and True or item.CodeLegType == CodeLegTypeAixm.CWA
            return
        if (sender == self.cmbCenUid):
            item.CenterEnt = self.cmbCenUid.SelectedItem
            return
        if (sender == self.pnlFlyBy):
            item.CodeFlyBy = self.pnlFlyBy.SelectedItem
            return
        if (sender == self.pnlMinAlt):
            item.ValMinAlt = self.pnlMinAlt.Value
            return
        if (sender == self.pnlSegLength):
            item.ValDist = self.pnlSegLength.Value
            return
        if (sender == self.pnlCourse):
            item.ValCourse = self.pnlCourse.Value
            return
        if (sender == self.cmbLegVor):
            item.VorUidLeg = self.cmbLegVor.SelectedItem
            return
        if (sender == self.txtLegRadial):
            item.ValLegRadial = self.txtLegRadial.Value
            return
        if (sender == self.cmbLegBackVor):
            item.VorUidLegBack = self.cmbLegBackVor.SelectedItem
            return
        if (sender == self.txtLegBackRadial):
            item.ValLegRadialBack = self.txtLegBackRadial.Value
            return
        if (sender == self.pnlPointType):
            item.CodePointType = self.pnlPointType.SelectedItem
            return
        if (sender == self.pnlRepPointType):
            item.CodeRepAtc = self.pnlRepPointType.SelectedItem
            return
        if (sender == self.cmbPointVor):
            item.VorUidPoint = self.cmbPointVor.SelectedItem
            return
        if (sender == self.txtPointRadial):
            item.ValPointRadial = self.txtPointRadial.Value
            return
        if (sender == self.cmbPointDme1):
            item.UidPointDist1 = self.cmbPointDme1.SelectedItem
            return
        if (sender == self.txtPointDme1):
            item.ValPointDist1 = self.txtPointDme1.Value
            return
        if (sender == self.cmbPointDme2):
            item.UidPointDist2 = self.cmbPointDme2.SelectedItem
            return
        if (sender == self.txtPointDme2):
            item.ValPointDist2 = self.txtPointDme2.Value
            return
        if (sender == self.txtFlyDuration):
            item.ValDur = self.txtFlyDuration.Value
            return
        if (sender == self.txtRemarks):
            item.TxtRmk = self.txtRemarks.Value

    def method_13(self):
        point3d = None
        procEntityBase = None
        selectTool = DlgAixmSelectPosition.smethod_0(
            self.data, point3d, ProcEntityListType.FixesEx)
        QObject.connect(selectTool,
                        SIGNAL("DlgAixmSelectPosition_Smethod_0_Event"),
                        self.method_13_Event)

    def method_13_Event(self, flag, procEntityBase):
        # flag, procEntityBase = DlgAixmSelectPosition.smethod_0(self.data, point3d, ProcEntityListType.Fixes)
        if (flag and procEntityBase != None):
            if (not self.cmbPosUid.Contains(procEntityBase)):
                self.cmbPosUid.Add(procEntityBase)
            self.cmbPosUid.SelectedIndex = self.cmbPosUid.IndexOf(
                procEntityBase)
            self.txtFlyDuration_TextChanged(self.cmbPosUid)

    def method_14(self):
        point3d = None
        procEntityBase = None
        selectTool = DlgAixmSelectPosition.smethod_0(
            self.data, point3d, ProcEntityListType.CentersEx)
        QObject.connect(selectTool,
                        SIGNAL("DlgAixmSelectPosition_Smethod_0_Event"),
                        self.method_14_Event)

    def method_14_Event(self, flag, procEntityBase):
        # flag, procEntityBase = DlgAixmSelectPosition.smethod_0(self.data, point3d, ProcEntityListType.Centers)
        if (flag and procEntityBase != None):
            if (not self.cmbCenUid.Contains(procEntityBase)):
                self.cmbCenUid.Add(procEntityBase)
            self.cmbCenUid.SelectedIndex = self.cmbCenUid.IndexOf(
                procEntityBase)
            self.txtFlyDuration_TextChanged(self.cmbCenUid)

    @staticmethod
    def smethod_0(parent, dataBaseProcedureLegsEx_0, dataBaseProcedureData_0,
                  procEntityAHP_0):
        flag = False
        dlgAixmProcLegsEx = DlgAixmProcLegsEx(parent)
        dlgAixmProcLegsEx.legs = dataBaseProcedureLegsEx_0
        dlgAixmProcLegsEx.data = dataBaseProcedureData_0
        if (procEntityAHP_0 != None):
            dlgAixmProcLegsEx.aerodrome = procEntityAHP_0
            dlgAixmProcLegsEx.magnVar = procEntityAHP_0.ValMagVar
        dataBaseProcedureData_0.method_59(dlgAixmProcLegsEx.cmbPosUid,
                                          ProcEntityListType.FixesEx)
        dataBaseProcedureData_0.method_59(dlgAixmProcLegsEx.cmbCenUid,
                                          ProcEntityListType.CentersEx)
        dataBaseProcedureData_0.method_59(dlgAixmProcLegsEx.cmbLegVor,
                                          ProcEntityListType.VORs)
        dataBaseProcedureData_0.method_59(dlgAixmProcLegsEx.cmbLegBackVor,
                                          ProcEntityListType.VORs)
        dataBaseProcedureData_0.method_59(dlgAixmProcLegsEx.cmbPointVor,
                                          ProcEntityListType.VORs)
        dataBaseProcedureData_0.method_59(dlgAixmProcLegsEx.cmbPointDme1,
                                          ProcEntityListType.DMEs)
        dataBaseProcedureData_0.method_59(dlgAixmProcLegsEx.cmbPointDme2,
                                          ProcEntityListType.DMEs)
        if (len(dlgAixmProcLegsEx.legs) == 0):
            dlgAixmProcLegsEx.legs.append(DataBaseProcedureLegEx())

        dlgAixmProcLegsEx.method_7()
        if dlgAixmProcLegsEx.trvLegsStdModel.rowCount() > 0:
            dlgAixmProcLegsEx.trvLegs.setCurrentIndex(
                dlgAixmProcLegsEx.trvLegsStdModel.index(0, 0))
            dlgAixmProcLegsEx.method_6()
        dlgAixmProcLegsEx.method_8()
        dlgAixmProcLegsEx.show()
        return dlgAixmProcLegsEx
class ModelerParameterDefinitionDialog(QDialog):

    PARAMETER_NUMBER = 'Number'
    PARAMETER_RASTER = 'Raster layer'
    PARAMETER_TABLE = 'Table'
    PARAMETER_VECTOR = 'Vector layer'
    PARAMETER_STRING = 'String'
    PARAMETER_BOOLEAN = 'Boolean'
    PARAMETER_TABLE_FIELD = 'Table field'
    PARAMETER_EXTENT = 'Extent'
    PARAMETER_FILE = 'File'

    # To add
    PARAMETER_MULTIPLE = 'Multiple input'
    PARAMETER_FIXED_TABLE = 'Fixed table'

    paramTypes = [
        PARAMETER_BOOLEAN,
        PARAMETER_EXTENT,
        PARAMETER_FILE,
        PARAMETER_NUMBER,
        PARAMETER_RASTER,
        PARAMETER_STRING,
        PARAMETER_TABLE,
        PARAMETER_TABLE_FIELD,
        PARAMETER_VECTOR,
    ]

    def __init__(self, alg, paramType=None, param=None):
        self.alg = alg
        self.paramType = paramType
        self.param = param
        QDialog.__init__(self)
        self.setModal(True)
        self.setupUi()

    def setupUi(self):
        self.setWindowTitle(self.tr('Parameter definition'))

        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.setSpacing(40)
        self.verticalLayout.setMargin(20)

        self.horizontalLayout = QHBoxLayout(self)
        self.horizontalLayout.setSpacing(2)
        self.horizontalLayout.setMargin(0)
        self.label = QLabel(self.tr('Parameter name'))
        self.horizontalLayout.addWidget(self.label)
        self.nameTextBox = QLineEdit()
        self.horizontalLayout.addWidget(self.nameTextBox)
        self.verticalLayout.addLayout(self.horizontalLayout)

        self.horizontalLayout2 = QHBoxLayout(self)
        self.horizontalLayout2.setSpacing(2)
        self.horizontalLayout2.setMargin(0)
        self.horizontalLayout3 = QHBoxLayout(self)
        self.horizontalLayout3.setSpacing(2)
        self.horizontalLayout3.setMargin(0)

        if isinstance(self.param, Parameter):
            self.nameTextBox.setText(self.param.description)

        if self.paramType == ModelerParameterDefinitionDialog.PARAMETER_BOOLEAN or \
           isinstance(self.param, ParameterBoolean):
            self.state = QCheckBox()
            self.state.setText(self.tr('Checked'))
            self.state.setChecked(False)
            if self.param is not None:
                self.state.setChecked(True if self.param.value else False)
            self.horizontalLayout2.addWidget(self.state)
            self.verticalLayout.addLayout(self.horizontalLayout2)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD or \
                isinstance(self.param, ParameterTableField):
            self.horizontalLayout2.addWidget(QLabel(self.tr('Parent layer')))
            self.parentCombo = QComboBox()
            idx = 0
            for param in self.alg.inputs.values():
                if isinstance(param.param, (ParameterVector, ParameterTable)):
                    self.parentCombo.addItem(param.param.description,
                                             param.param.name)
                    if self.param is not None:
                        if self.param.parent == param.param.name:
                            self.parentCombo.setCurrentIndex(idx)
                    idx += 1
            self.horizontalLayout2.addWidget(self.parentCombo)
            self.verticalLayout.addLayout(self.horizontalLayout2)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_RASTER or \
                isinstance(self.param, ParameterRaster):
            self.horizontalLayout2.addWidget(QLabel(self.tr('Required')))
            self.yesNoCombo = QComboBox()
            self.yesNoCombo.addItem(self.tr('Yes'))
            self.yesNoCombo.addItem(self.tr('No'))
            if self.param is not None:
                self.yesNoCombo.setCurrentIndex(
                    1 if self.param.optional else 0)
            self.horizontalLayout2.addWidget(self.yesNoCombo)
            self.verticalLayout.addLayout(self.horizontalLayout2)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE or \
                isinstance(self.param, ParameterTable):
            self.horizontalLayout2.addWidget(QLabel(self.tr('Required')))
            self.yesNoCombo = QComboBox()
            self.yesNoCombo.addItem(self.tr('Yes'))
            self.yesNoCombo.addItem(self.tr('No'))
            if self.param is not None:
                self.yesNoCombo.setCurrentIndex(
                    1 if self.param.optional else 0)
            self.horizontalLayout2.addWidget(self.yesNoCombo)
            self.verticalLayout.addLayout(self.horizontalLayout2)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_VECTOR or \
                isinstance(self.param, ParameterVector):
            self.horizontalLayout2.addWidget(QLabel(self.tr('Required')))
            self.yesNoCombo = QComboBox()
            self.yesNoCombo.addItem(self.tr('Yes'))
            self.yesNoCombo.addItem(self.tr('No'))
            self.horizontalLayout2.addWidget(self.yesNoCombo)
            self.horizontalLayout3.addWidget(QLabel(self.tr('Shape type')))
            self.shapetypeCombo = QComboBox()
            self.shapetypeCombo.addItem(self.tr('Any'))
            self.shapetypeCombo.addItem(self.tr('Point'))
            self.shapetypeCombo.addItem(self.tr('Line'))
            self.shapetypeCombo.addItem(self.tr('Polygon'))
            if self.param is not None:
                self.yesNoCombo.setCurrentIndex(
                    1 if self.param.optional else 0)
                self.shapetypeCombo.setCurrentIndex(self.param.shapetype[0] +
                                                    1)
            self.horizontalLayout3.addWidget(self.shapetypeCombo)
            self.verticalLayout.addLayout(self.horizontalLayout3)
            self.verticalLayout.addLayout(self.horizontalLayout2)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_MULTIPLE or \
                isinstance(self.param, ParameterMultipleInput):
            self.horizontalLayout2.addWidget(QLabel(self.tr('Mandatory')))
            self.yesNoCombo = QComboBox()
            self.yesNoCombo.addItem(self.tr('Yes'))
            self.yesNoCombo.addItem(self.tr('No'))
            self.horizontalLayout2.addWidget(self.yesNoCombo)
            self.horizontalLayout3.addWidget(QLabel(self.tr('Data type')))
            self.datatypeCombo = QComboBox()
            self.datatypeCombo.addItem(self.tr('Vector (any)'))
            self.datatypeCombo.addItem(self.tr('Vector (point)'))
            self.datatypeCombo.addItem(self.tr('Vector (line)'))
            self.datatypeCombo.addItem(self.tr('Vector (polygon)'))
            self.datatypeCombo.addItem(self.tr('Raster'))
            self.datatypeCombo.addItem(self.tr('Table'))
            if self.param is not None:
                self.yesNoCombo.setCurrentIndex(
                    1 if self.param.optional else 0)
                self.datatypeCombo.setCurrentIndex(self.param.datatype + 1)
            self.horizontalLayout3.addWidget(self.datatypeCombo)
            self.verticalLayout.addLayout(self.horizontalLayout3)
            self.verticalLayout.addLayout(self.horizontalLayout2)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_NUMBER or \
                isinstance(self.param, ParameterNumber):
            self.horizontalLayout2.addWidget(QLabel(self.tr('Min/Max values')))
            self.minTextBox = QLineEdit()
            self.maxTextBox = QLineEdit()
            if self.param is not None:
                self.minTextBox.setText(unicode(self.param.min))
                self.maxTextBox.setText(unicode(self.param.max))
            self.horizontalLayout2.addWidget(self.minTextBox)
            self.horizontalLayout2.addWidget(self.maxTextBox)
            self.verticalLayout.addLayout(self.horizontalLayout2)
            self.horizontalLayout3.addWidget(QLabel(self.tr('Default value')))
            self.defaultTextBox = QLineEdit()
            self.defaultTextBox.setText(self.tr('0'))
            if self.param is not None:
                default = self.param.default
                if self.param.isInteger:
                    default = int(math.floor(default))
                self.defaultTextBox.setText(unicode(default))
            self.horizontalLayout3.addWidget(self.defaultTextBox)
            self.verticalLayout.addLayout(self.horizontalLayout3)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or \
                isinstance(self.param, ParameterString):
            self.horizontalLayout2.addWidget(QLabel(self.tr('Default value')))
            self.defaultTextBox = QLineEdit()
            if self.param is not None:
                self.defaultTextBox.setText(self.param.default)
            self.horizontalLayout2.addWidget(self.defaultTextBox)
            self.verticalLayout.addLayout(self.horizontalLayout2)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_FILE or \
                isinstance(self.param, ParameterFile):
            self.horizontalLayout2.addWidget(QLabel(self.tr('Type')))
            self.fileFolderCombo = QComboBox()
            self.fileFolderCombo.addItem(self.tr('File'))
            self.fileFolderCombo.addItem(self.tr('Folder'))
            if self.param is not None:
                self.fileFolderCombo.setCurrentIndex(
                    1 if self.param.isFolder else 0)
            self.horizontalLayout2.addWidget(self.fileFolderCombo)
            self.verticalLayout.addLayout(self.horizontalLayout2)

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        self.buttonBox.setObjectName('buttonBox')
        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)

        self.verticalLayout.addWidget(self.buttonBox)

        self.setLayout(self.verticalLayout)

    def okPressed(self):
        description = unicode(self.nameTextBox.text())
        if description.strip() == '':
            QMessageBox.warning(self, self.tr('Unable to define parameter'),
                                self.tr('Invalid parameter name'))
            return
        if self.param is None:
            validChars = \
                'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
            safeName = ''.join(c for c in description if c in validChars)
            name = self.paramType.upper().replace(' ', '') + '_' \
                + safeName.upper()
        else:
            name = self.param.name
        if self.paramType \
                == ModelerParameterDefinitionDialog.PARAMETER_BOOLEAN \
                or isinstance(self.param, ParameterBoolean):
            self.param = ParameterBoolean(name, description,
                                          self.state.isChecked())
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD or \
                isinstance(self.param, ParameterTableField):
            if self.parentCombo.currentIndex() < 0:
                QMessageBox.warning(
                    self, self.tr('Unable to define parameter'),
                    self.tr('Wrong or missing parameter values'))
                return
            parent = self.parentCombo.itemData(self.parentCombo.currentIndex())
            self.param = ParameterTableField(name, description, parent)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_RASTER or \
                isinstance(self.param, ParameterRaster):
            self.param = ParameterRaster(name, description,
                                         self.yesNoCombo.currentIndex() == 1)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE or \
                isinstance(self.param, ParameterTable):
            self.param = ParameterTable(name, description,
                                        self.yesNoCombo.currentIndex() == 1)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_VECTOR or \
                isinstance(self.param, ParameterVector):
            self.param = ParameterVector(
                name, description, [self.shapetypeCombo.currentIndex() - 1],
                self.yesNoCombo.currentIndex() == 1)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_MULTIPLE or \
                isinstance(self.param, ParameterMultipleInput):
            self.param = ParameterMultipleInput(
                name, description,
                self.datatypeCombo.currentIndex() - 1,
                self.yesNoCombo.currentIndex() == 1)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_NUMBER or \
                isinstance(self.param, ParameterNumber):
            try:
                vmin = unicode(self.minTextBox.text()).strip()
                if vmin == '':
                    vmin = None
                else:
                    vmin = float(vmin)
                vmax = unicode(self.maxTextBox.text()).strip()
                if vmax == '':
                    vmax = None
                else:
                    vmax = float(vmax)
                self.param = ParameterNumber(
                    name, description, vmin, vmax,
                    unicode(self.defaultTextBox.text()))
            except:
                QMessageBox.warning(
                    self, self.tr('Unable to define parameter'),
                    self.tr('Wrong or missing parameter values'))
                return
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or \
                isinstance(self.param, ParameterString):
            self.param = ParameterString(name, description,
                                         unicode(self.defaultTextBox.text()))
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_EXTENT or \
                isinstance(self.param, ParameterExtent):
            self.param = ParameterExtent(name, description)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_FILE or \
                isinstance(self.param, ParameterFile):
            isFolder = self.fileFolderCombo.currentIndex() == 1
            self.param = ParameterFile(name, description, isFolder=isFolder)
        self.close()

    def cancelPressed(self):
        self.param = None
        self.close()
class QgsTextAnnotationDialog(QDialog):
    def __init__(self, item):
        QDialog.__init__(self)
        self.gridLayout = QGridLayout(self)
        self.gridLayout.setObjectName(("gridLayout"))
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.setObjectName(("horizontalLayout"))
        self.mFontComboBox = QFontComboBox(self)
        self.mFontComboBox.setObjectName(("mFontComboBox"))
        self.horizontalLayout.addWidget(self.mFontComboBox)
        spacerItem = QSpacerItem(38, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        self.mFontSizeSpinBox = QSpinBox(self)
        self.mFontSizeSpinBox.setObjectName(("mFontSizeSpinBox"))
        self.horizontalLayout.addWidget(self.mFontSizeSpinBox)
        self.mBoldPushButton = QPushButton(self)
        self.mBoldPushButton.setMinimumSize(QSize(50, 0))
        self.mBoldPushButton.setCheckable(True)
        self.mBoldPushButton.setObjectName(("mBoldPushButton"))
        self.horizontalLayout.addWidget(self.mBoldPushButton)
        self.mItalicsPushButton = QPushButton(self)
        self.mItalicsPushButton.setMinimumSize(QSize(50, 0))
        self.mItalicsPushButton.setCheckable(True)
        self.mItalicsPushButton.setObjectName(("mItalicsPushButton"))
        self.horizontalLayout.addWidget(self.mItalicsPushButton)
        self.mFontColorButton = QgsColorButton(self)
        self.mFontColorButton.setText((""))
        self.mFontColorButton.setAutoDefault(False)
        self.mFontColorButton.setObjectName(("mFontColorButton"))
        self.horizontalLayout.addWidget(self.mFontColorButton)
        self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1)
        self.mButtonBox = QDialogButtonBox(self)
        self.mButtonBox.setOrientation(Qt.Horizontal)
        self.mButtonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok)
        self.mButtonBox.setObjectName(("mButtonBox"))
        self.gridLayout.addWidget(self.mButtonBox, 3, 0, 1, 1)
        self.mTextEdit = QTextEdit(self)
        self.mTextEdit.setObjectName(("mTextEdit"))
        self.gridLayout.addWidget(self.mTextEdit, 1, 0, 1, 1)
        self.mStackedWidget = QStackedWidget(self)
        self.mStackedWidget.setObjectName(("mStackedWidget"))
        self.page = QWidget()
        self.page.setObjectName(("page"))
        self.mStackedWidget.addWidget(self.page)
        self.page_2 = QWidget()
        self.page_2.setObjectName(("page_2"))
        self.mStackedWidget.addWidget(self.page_2)
        self.gridLayout.addWidget(self.mStackedWidget, 2, 0, 1, 1)
        self.setLayout(self.gridLayout)
        
        self.mStackedWidget.setCurrentIndex(0)
        QObject.connect(self.mButtonBox, SIGNAL(("accepted()")), self.accept)
        QObject.connect(self.mButtonBox, SIGNAL(("rejected()")), self.reject)
        
        self.setTabOrder(self.mFontComboBox, self.mFontSizeSpinBox)
        self.setTabOrder(self.mFontSizeSpinBox, self.mBoldPushButton)
        self.setTabOrder(self.mBoldPushButton, self.mItalicsPushButton)
        self.setTabOrder(self.mItalicsPushButton, self.mFontColorButton)
        self.setTabOrder(self.mFontColorButton, self.mTextEdit)
        self.setTabOrder(self.mTextEdit, self.mButtonBox)
        
        self.setWindowTitle("Annotation text")
        self.mBoldPushButton.setText("B")
        self.mItalicsPushButton.setText("I")
        
        self.mTextDocument = None
        self.mItem = item
        self.mEmbeddedWidget = QgsAnnotationWidget(self, self.mItem )
        self.mEmbeddedWidget.show()
        self.mStackedWidget.addWidget( self.mEmbeddedWidget )
        self.mStackedWidget.setCurrentWidget( self.mEmbeddedWidget )
        if ( self.mItem != None ):
            self.mTextDocument = self.mItem.document()
            self.mTextEdit.setDocument( self.mTextDocument )
        self.mFontColorButton.setColorDialogTitle(  "Select font color"  )
        self.mFontColorButton.setColorDialogOptions( QColorDialog.ShowAlphaChannel )
        self.setCurrentFontPropertiesToGui()
        QObject.connect( self.mButtonBox, SIGNAL("accepted()"), self.applyTextToItem)
#         QObject.connect( self.mFontComboBox, SIGNAL( "currentFontChanged(QFont())"), self.changeCurrentFormat)
        self.mFontComboBox.currentFontChanged.connect(self.changeCurrentFormat)
        QObject.connect( self.mFontSizeSpinBox, SIGNAL( "valueChanged( int )" ), self.changeCurrentFormat ) 
        QObject.connect( self.mBoldPushButton, SIGNAL( "toggled( bool )" ), self.changeCurrentFormat)
        QObject.connect( self.mItalicsPushButton, SIGNAL( "toggled( bool )" ), self.changeCurrentFormat)
        QObject.connect( self.mTextEdit, SIGNAL( "cursorPositionChanged()" ), self.setCurrentFontPropertiesToGui )
        
#         QObject.connect( self.mButtonBox, SIGNAL( "accepted()" ), self.applySettingsToItem)
        deleteButton = QPushButton( "Delete" )
        QObject.connect( deleteButton, SIGNAL( "clicked()" ), self.deleteItem )
        self.mButtonBox.addButton( deleteButton, QDialogButtonBox.RejectRole )
    def applyTextToItem(self):
        if ( self.mItem  != None and self.mTextDocument !=None ):
            if ( self.mEmbeddedWidget != None):
                self.mEmbeddedWidget.apply()
            self.mItem.setDocument( self.mTextDocument )
            self.mItem.update()
    def changeCurrentFormat(self):
        newFont = QFont()
        newFont.setFamily( self.mFontComboBox.currentFont().family() )
        #bold
        if ( self.mBoldPushButton.isChecked() ):
            newFont.setBold( True )
        else:
            newFont.setBold( False )
        #italic
        if ( self.mItalicsPushButton.isChecked() ):
            newFont.setItalic( True )
        else:
            newFont.setItalic( False )
        #size
        newFont.setPointSize( self.mFontSizeSpinBox.value() )
        self.mTextEdit.setCurrentFont( newFont )
        #color
        self.mTextEdit.setTextColor( self.mFontColorButton.color() )
        
    def on_mFontColorButton_colorChanged(self, color ):
        self.changeCurrentFormat()
    def setCurrentFontPropertiesToGui(self):
        self.blockAllSignals( True )
        currentFont = self.mTextEdit.currentFont()
        self.mFontComboBox.setCurrentFont( currentFont )
        self.mFontSizeSpinBox.setValue( currentFont.pointSize() )
        self.mBoldPushButton.setChecked( currentFont.bold() )
        self.mItalicsPushButton.setChecked( currentFont.italic() )
        self.mFontColorButton.setColor( self.mTextEdit.textColor() )
        self.blockAllSignals( False )
        
    def blockAllSignals(self, block ):
        self.mFontComboBox.blockSignals( block )
        self.mFontSizeSpinBox.blockSignals( block )
        self.mBoldPushButton.blockSignals( block )
        self.mItalicsPushButton.blockSignals( block )
        self.mFontColorButton.blockSignals( block )
    
    def deleteItem(self):
        scene = self.mItem.scene()
        if ( scene != None ):
            scene.removeItem( self.mItem )
        self.mItem = None
class DlgFasDataBlockImport(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)

        self.resize(290, 136)
        self.setWindowTitle("Reference Positions")
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        verticalLayoutDlg = QVBoxLayout(self)
        verticalLayoutDlg.setObjectName(("verticalLayoutDlg"))

        self.groupBox = GroupBox(self)
        self.groupBox.Caption = "Output Data"
        verticalLayoutDlg.addWidget(self.groupBox)

        self.txtDataBlock = TextBoxPanel(self.groupBox, True)
        self.txtDataBlock.Caption = "Data Block"
        self.txtDataBlock.Value = "10 20 10 07 05 8C 20 02 01 36 30 05 54 9D AA 18 7C E8 D5 FC 72 16 A0 F5 00 94 96 02 2C 81 2C 01 64 01 C8 FA 6A E4 AF 51"
        self.groupBox.Add = self.txtDataBlock

        self.pnlSuppliedCRC = TextBoxPanel(self.groupBox)
        self.pnlSuppliedCRC.Caption = "Supplied CRC Value"
        self.pnlSuppliedCRC.ReadOnly = True
        self.groupBox.Add = self.pnlSuppliedCRC

        self.pnlCalculatedCRC = TextBoxPanel(self.groupBox)
        self.pnlCalculatedCRC.Caption = "Calculated CRC Value"
        self.pnlCalculatedCRC.ReadOnly = True
        self.groupBox.Add = self.pnlCalculatedCRC

        self.frameBtn = Frame(self, "HL")
        verticalLayoutDlg.addWidget(self.frameBtn)

        self.btnFile = QPushButton(self.frameBtn)
        self.btnFile.setObjectName(("btnFile"))
        self.btnFile.setText("File...")
        self.frameBtn.Add = self.btnFile

        self.btnBoxOkCancel = QDialogButtonBox(self.frameBtn)
        self.btnBoxOkCancel.setObjectName(("btnBoxOkCancel"))
        self.btnBoxOkCancel.setStandardButtons(QDialogButtonBox.Cancel
                                               | QDialogButtonBox.Ok)
        self.connect(self.btnBoxOkCancel, SIGNAL("accepted()"), self.acceptDlg)
        self.connect(self.btnBoxOkCancel, SIGNAL("rejected()"), self.reject)

        self.btnFile.clicked.connect(self.btnFile_clicked)

        self.frameBtn.Add = self.btnBoxOkCancel

        self.txtDataBlock.textBox.textChanged.connect(
            self.txtDataBlock_TextChanged)

    def acceptDlg(self):
        if self.txtDataBlock.Value == "":
            self.reject()
            return
        self.accept()

    # def reject(self):
    #     self.reject()
    def btnFile_clicked(self):
        filePathDir = QFileDialog.getOpenFileName(
            self, "Open Fas Data", QCoreApplication.applicationDirPath(),
            "FAS Data Block Binary Files (*.bin)")
        if filePathDir == "":
            return
        fasDataBlockFile = FasDataBlockFile()
        fasDataBlockFile.method_1(filePathDir)
        self.txtDataBlock.Value = fasDataBlockFile.HexString

    def method_5(self):
        flag = False
        # self.errorProvider.method_1();
        fasDataBlockFile = FasDataBlockFile()
        fasDataBlockFile.set_HexString(self.txtDataBlock.Value)
        if self.txtDataBlock.Value == "":
            self.pnlCalculatedCRC.set_Value("")
        else:
            self.pnlCalculatedCRC.set_Value(fasDataBlockFile.CRC)
        if self.txtDataBlock.Value == "":
            self.pnlSuppliedCRC.set_Value("")
        else:
            value = fasDataBlockFile.HexString.split(' ')
            str0 = ""
            for i in range(36, 40):
                str0 += value[i]
            self.pnlSuppliedCRC.set_Value(str0)
        flag = True
        # except:
        #     # self.errorProvider.method_0(self.txtDataBlock, exception.Message);
        #     self.pnlCalculatedCRC.Value = "";
        #     self.pnlSuppliedCRC.Value = "";
        #     return False;
        return flag

    @staticmethod
    def smethod_0(parent):
        fasDataBlockFile = None
        dlgFasDataBlockImport = DlgFasDataBlockImport()
        dlgFasDataBlockImport.txtDataBlock.set_Value("")
        dlgFasDataBlockImport.pnlCalculatedCRC.set_Value("")
        dlgResult = dlgFasDataBlockImport.exec_()
        if dlgResult != 1:
            fasDataBlockFile = None
        else:
            fasDataBlockFile = FasDataBlockFile()
            fasDataBlockFile.set_HexString(
                dlgFasDataBlockImport.txtDataBlock.get_Value())
        return fasDataBlockFile

    def txtDataBlock_TextChanged(self):
        self.method_5()
class DlgMagneticVariationParameters(QDialog):
    def __init__(self, parent = None):
        QDialog.__init__(self, parent)
        
        self.resize(290, 136);
        self.setWindowTitle("Reference Positions")
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed);
        sizePolicy.setHorizontalStretch(0);
        sizePolicy.setVerticalStretch(0);
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth());
        self.setSizePolicy(sizePolicy);
        verticalLayoutDlg = QVBoxLayout(self)
        verticalLayoutDlg.setObjectName(("verticalLayoutDlg"));
        frameDate = QFrame(self);
        frameDate.setObjectName(("frameDate"));
        frameDate.setFrameShape(QFrame.StyledPanel);
        frameDate.setFrameShadow(QFrame.Raised);
        horizontalLayoutDate = QHBoxLayout(frameDate);
        horizontalLayoutDate.setObjectName(("horizontalLayoutDate"));
        labelDate = QLabel(frameDate);
        labelDate.setObjectName(("labelDate"));
        labelDate.setMinimumSize(QSize(70, 0));
        labelDate.setMaximumSize(QSize(70, 16777215));
        labelDate.setText("Date:")

        horizontalLayoutDate.addWidget(labelDate);

        self.dtpDate = QDateEdit(frameDate);
        self.dtpDate.setObjectName(("dtpDate"));

        horizontalLayoutDate.addWidget(self.dtpDate);

        self.btnDtpDate =  QToolButton(frameDate);
        self.btnDtpDate.setObjectName(("btnDtpDate"));
        sizePolicy.setHeightForWidth(self.btnDtpDate.sizePolicy().hasHeightForWidth());
        self.btnDtpDate.setSizePolicy(sizePolicy);
        self.btnDtpDate.setMinimumSize(QSize(25, 0));
        self.btnDtpDate.setMaximumSize(QSize(25, 16777215));
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/calender.png")), QIcon.Normal, QIcon.Off)
        self.btnDtpDate.setIcon(icon)

        horizontalLayoutDate.addWidget(self.btnDtpDate);


        verticalLayoutDlg.addWidget(frameDate);

        frameModel = QFrame(self);
        frameModel.setObjectName(("frameModel"));
        frameModel.setFrameShape(QFrame.StyledPanel);
        frameModel.setFrameShadow(QFrame.Raised);
        horizontalLayoutModel = QHBoxLayout(frameModel);
        horizontalLayoutModel.setObjectName(("horizontalLayoutModel"));
        labelModel = QLabel(frameModel);
        labelModel.setObjectName(("labelModel"));
        labelModel.setMinimumSize(QSize(70, 0));
        labelModel.setMaximumSize(QSize(70, 16777215));
        labelModel.setText("Model:")

        horizontalLayoutModel.addWidget(labelModel);

        self.cmbModel = QComboBox(frameModel);
        self.cmbModel.setObjectName(("cmbModel"));

        horizontalLayoutModel.addWidget(self.cmbModel);


        verticalLayoutDlg.addWidget(frameModel);

        self.buttonBox = QDialogButtonBox(self);
        self.buttonBox.setObjectName(("buttonBox"));
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok);
        self.connect(self.buttonBox, SIGNAL("accepted()"), self.accept)
        self.connect(self.buttonBox, SIGNAL("rejected()"), self.reject)


        verticalLayoutDlg.addWidget(self.buttonBox);

        self.calendar = QCalendarWidget()
        self.calendar.clicked.connect(self.calendar_clicked)
        self.menu = QMenu()
        layout = QVBoxLayout(self.menu)
        layout.addWidget(self.calendar)

        self.btnDtpDate.clicked.connect(self.btnDtpDate_clicked)
        self.cmbModel.addItems(["WMM2015", "WMM2010" , "WMM2005", "WMM2000", "WMM95", "WMM90", "WMM85", "IGRF2000", "IGRF95", "IGRF90"])

    def btnDtpDate_clicked(self):
        rcRect = self.btnDtpDate.geometry()
        ptPoint = rcRect.bottomLeft()

        self.menu.exec_( self.mapToGlobal(ptPoint) )

    def calendar_clicked(self, date):
        self.dtpDate.setDate(date)

    def get_Date(self):
        return self.dtpDate.date()
    def setDate(self, date):
        if date != None:
            self.dtpDate.setDate(date)
    Date = property(get_Date, setDate, None, None)

    def get_Model(self):
        return self.cmbModel.currentIndex()
    def set_Model(self, index):
        if index == None:
            self.cmbModel.setCurrentIndex(1)
            return
        self.cmbModel.setCurrentIndex(index)
    Model = property(get_Model, set_Model, None, None)

    @staticmethod
    def smethod_0(date_0, magneticModelIndex_0):

        dlgMagneticVariationParameters = DlgMagneticVariationParameters()
        dlgMagneticVariationParameters.Date = date_0
        dlgMagneticVariationParameters.Model = magneticModelIndex_0
        dialogResult = dlgMagneticVariationParameters.exec_()
        if dialogResult != QDialog.Accepted:
            return (False, None, None)
        else:
            date  = dlgMagneticVariationParameters.Date;
            magneticIndex = dlgMagneticVariationParameters.Model;
            return (True, date, magneticIndex)
class ModelerParameterDefinitionDialog(QDialog):

    PARAMETER_NUMBER = 'Number'
    PARAMETER_RASTER = 'Raster layer'
    PARAMETER_TABLE = 'Table'
    PARAMETER_VECTOR = 'Vector layer'
    PARAMETER_STRING = 'String'
    PARAMETER_BOOLEAN = 'Boolean'
    PARAMETER_TABLE_FIELD = 'Table field'
    PARAMETER_EXTENT = 'Extent'
    PARAMETER_FILE = 'File'
    PARAMETER_POINT = 'Point'

    # To add
    PARAMETER_MULTIPLE = 'Multiple input'
    PARAMETER_FIXED_TABLE = 'Fixed table'

    paramTypes = [
        PARAMETER_BOOLEAN,
        PARAMETER_EXTENT,
        PARAMETER_FILE,
        PARAMETER_NUMBER,
        PARAMETER_RASTER,
        PARAMETER_STRING,
        PARAMETER_TABLE,
        PARAMETER_TABLE_FIELD,
        PARAMETER_VECTOR,
        PARAMETER_POINT
    ]

    def __init__(self, alg, paramType=None, param=None):
        self.alg = alg
        self.paramType = paramType
        self.param = param
        QDialog.__init__(self)
        self.setModal(True)
        self.setupUi()

    def setupUi(self):
        self.setWindowTitle(self.tr('Parameter definition'))

        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.setSpacing(40)
        self.verticalLayout.setMargin(20)

        self.horizontalLayout = QHBoxLayout(self)
        self.horizontalLayout.setSpacing(2)
        self.horizontalLayout.setMargin(0)
        self.label = QLabel(self.tr('Parameter name'))
        self.horizontalLayout.addWidget(self.label)
        self.nameTextBox = QLineEdit()
        self.horizontalLayout.addWidget(self.nameTextBox)
        self.verticalLayout.addLayout(self.horizontalLayout)

        self.horizontalLayout2 = QHBoxLayout(self)
        self.horizontalLayout2.setSpacing(2)
        self.horizontalLayout2.setMargin(0)
        self.horizontalLayout3 = QHBoxLayout(self)
        self.horizontalLayout3.setSpacing(2)
        self.horizontalLayout3.setMargin(0)
        self.horizontalLayout4 = QHBoxLayout(self)
        self.horizontalLayout4.setSpacing(2)
        self.horizontalLayout4.setMargin(0)

        if isinstance(self.param, Parameter):
            self.nameTextBox.setText(self.param.description)

        if self.paramType == ModelerParameterDefinitionDialog.PARAMETER_BOOLEAN or \
           isinstance(self.param, ParameterBoolean):
            self.state = QCheckBox()
            self.state.setText(self.tr('Checked'))
            self.state.setChecked(False)
            if self.param is not None:
                self.state.setChecked(True if self.param.value else False)
            self.horizontalLayout3.addWidget(self.state)
            self.verticalLayout.addLayout(self.horizontalLayout3)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD or \
                isinstance(self.param, ParameterTableField):
            self.horizontalLayout3.addWidget(QLabel(self.tr('Parent layer')))
            self.parentCombo = QComboBox()
            idx = 0
            for param in self.alg.inputs.values():
                if isinstance(param.param, (ParameterVector, ParameterTable)):
                    self.parentCombo.addItem(param.param.description, param.param.name)
                    if self.param is not None:
                        if self.param.parent == param.param.name:
                            self.parentCombo.setCurrentIndex(idx)
                    idx += 1
            self.horizontalLayout3.addWidget(self.parentCombo)
            self.verticalLayout.addLayout(self.horizontalLayout3)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_VECTOR or \
                isinstance(self.param, ParameterVector):
            self.horizontalLayout3.addWidget(QLabel(self.tr('Shape type')))
            self.shapetypeCombo = QComboBox()
            self.shapetypeCombo.addItem(self.tr('Any'))
            self.shapetypeCombo.addItem(self.tr('Point'))
            self.shapetypeCombo.addItem(self.tr('Line'))
            self.shapetypeCombo.addItem(self.tr('Polygon'))
            if self.param is not None:
                self.shapetypeCombo.setCurrentIndex(self.param.shapetype[0] + 1)
            self.horizontalLayout3.addWidget(self.shapetypeCombo)
            self.verticalLayout.addLayout(self.horizontalLayout3)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_MULTIPLE or \
                isinstance(self.param, ParameterMultipleInput):
            self.horizontalLayout3.addWidget(QLabel(self.tr('Data type')))
            self.datatypeCombo = QComboBox()
            self.datatypeCombo.addItem(self.tr('Vector (any)'))
            self.datatypeCombo.addItem(self.tr('Vector (point)'))
            self.datatypeCombo.addItem(self.tr('Vector (line)'))
            self.datatypeCombo.addItem(self.tr('Vector (polygon)'))
            self.datatypeCombo.addItem(self.tr('Raster'))
            self.datatypeCombo.addItem(self.tr('Table'))
            if self.param is not None:
                self.datatypeCombo.setCurrentIndex(self.param.datatype + 1)
            self.horizontalLayout3.addWidget(self.datatypeCombo)
            self.verticalLayout.addLayout(self.horizontalLayout3)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_NUMBER or \
                isinstance(self.param, ParameterNumber):
            self.horizontalLayout3.addWidget(QLabel(self.tr('Min/Max values')))
            self.minTextBox = QLineEdit()
            self.maxTextBox = QLineEdit()
            if self.param is not None:
                self.minTextBox.setText(unicode(self.param.min))
                self.maxTextBox.setText(unicode(self.param.max))
            self.horizontalLayout3.addWidget(self.minTextBox)
            self.horizontalLayout3.addWidget(self.maxTextBox)
            self.verticalLayout.addLayout(self.horizontalLayout3)
            self.horizontalLayout4.addWidget(QLabel(self.tr('Default value')))
            self.defaultTextBox = QLineEdit()
            self.defaultTextBox.setText(self.tr('0'))
            if self.param is not None:
                default = self.param.default
                if self.param.isInteger:
                    default = int(math.floor(default))
                self.defaultTextBox.setText(unicode(default))
            self.horizontalLayout4.addWidget(self.defaultTextBox)
            self.verticalLayout.addLayout(self.horizontalLayout4)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or \
                isinstance(self.param, ParameterString):
            self.horizontalLayout3.addWidget(QLabel(self.tr('Default value')))
            self.defaultTextBox = QLineEdit()
            if self.param is not None:
                self.defaultTextBox.setText(self.param.default)
            self.horizontalLayout3.addWidget(self.defaultTextBox)
            self.verticalLayout.addLayout(self.horizontalLayout3)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_FILE or \
                isinstance(self.param, ParameterFile):
            self.horizontalLayout3.addWidget(QLabel(self.tr('Type')))
            self.fileFolderCombo = QComboBox()
            self.fileFolderCombo.addItem(self.tr('File'))
            self.fileFolderCombo.addItem(self.tr('Folder'))
            if self.param is not None:
                self.fileFolderCombo.setCurrentIndex(
                    1 if self.param.isFolder else 0)
            self.horizontalLayout3.addWidget(self.fileFolderCombo)
            self.verticalLayout.addLayout(self.horizontalLayout3)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_POINT or \
                isinstance(self.param, ParameterPoint):
            self.horizontalLayout3.addWidget(QLabel(self.tr('Default value')))
            self.defaultTextBox = QLineEdit()
            if self.param is not None:
                self.defaultTextBox.setText(self.param.default)
            self.horizontalLayout3.addWidget(self.defaultTextBox)
            self.verticalLayout.addLayout(self.horizontalLayout3)

        self.horizontalLayout2.addWidget(QLabel(self.tr('Required')))
        self.yesNoCombo = QComboBox()
        self.yesNoCombo.addItem(self.tr('Yes'))
        self.yesNoCombo.addItem(self.tr('No'))
        self.horizontalLayout2.addWidget(self.yesNoCombo)
        if self.param is not None:
            self.yesNoCombo.setCurrentIndex(
                1 if self.param.optional else 0)
        self.verticalLayout.addLayout(self.horizontalLayout2)

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        self.buttonBox.setObjectName('buttonBox')
        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)

        self.verticalLayout.addWidget(self.buttonBox)

        self.setLayout(self.verticalLayout)

    def okPressed(self):
        description = unicode(self.nameTextBox.text())
        if description.strip() == '':
            QMessageBox.warning(self, self.tr('Unable to define parameter'),
                                self.tr('Invalid parameter name'))
            return
        if self.param is None:
            validChars = \
                'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
            safeName = ''.join(c for c in description if c in validChars)
            name = safeName.lower()
            i = 2
            while name in self.alg.inputs:
                name = safeName.lower() + str(i)
        else:
            name = self.param.name
        if self.paramType \
                == ModelerParameterDefinitionDialog.PARAMETER_BOOLEAN \
                or isinstance(self.param, ParameterBoolean):
            self.param = ParameterBoolean(name, description,
                                          self.state.isChecked())
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD or \
                isinstance(self.param, ParameterTableField):
            if self.parentCombo.currentIndex() < 0:
                QMessageBox.warning(self, self.tr('Unable to define parameter'),
                                    self.tr('Wrong or missing parameter values'))
                return
            parent = self.parentCombo.itemData(self.parentCombo.currentIndex())
            self.param = ParameterTableField(name, description, parent)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_RASTER or \
                isinstance(self.param, ParameterRaster):
            self.param = ParameterRaster(
                name, description,
                self.yesNoCombo.currentIndex() == 1)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE or \
                isinstance(self.param, ParameterTable):
            self.param = ParameterTable(
                name, description,
                self.yesNoCombo.currentIndex() == 1)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_VECTOR or \
                isinstance(self.param, ParameterVector):
            self.param = ParameterVector(
                name, description,
                [self.shapetypeCombo.currentIndex() - 1],
                self.yesNoCombo.currentIndex() == 1)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_MULTIPLE or \
                isinstance(self.param, ParameterMultipleInput):
            self.param = ParameterMultipleInput(
                name, description,
                self.datatypeCombo.currentIndex() - 1,
                self.yesNoCombo.currentIndex() == 1)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_NUMBER or \
                isinstance(self.param, ParameterNumber):
            try:
                vmin = unicode(self.minTextBox.text()).strip()
                if vmin == '':
                    vmin = None
                else:
                    vmin = float(vmin)
                vmax = unicode(self.maxTextBox.text()).strip()
                if vmax == '':
                    vmax = None
                else:
                    vmax = float(vmax)
                self.param = ParameterNumber(name, description, vmin, vmax,
                                             unicode(self.defaultTextBox.text()))
            except:
                QMessageBox.warning(self, self.tr('Unable to define parameter'),
                                    self.tr('Wrong or missing parameter values'))
                return
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or \
                isinstance(self.param, ParameterString):
            self.param = ParameterString(name, description,
                                         unicode(self.defaultTextBox.text()))
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_EXTENT or \
                isinstance(self.param, ParameterExtent):
            self.param = ParameterExtent(name, description)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_FILE or \
                isinstance(self.param, ParameterFile):
            isFolder = self.fileFolderCombo.currentIndex() == 1
            self.param = ParameterFile(name, description, isFolder=isFolder)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_POINT or \
                isinstance(self.param, ParameterPoint):
            self.param = ParameterPoint(name, description,
                                        unicode(self.defaultTextBox.text()))
        self.param.optional = self.yesNoCombo.currentIndex() == 1
        self.close()

    def cancelPressed(self):
        self.param = None
        self.close()
Beispiel #28
0
class DlgNavigationalAid(QDialog):
    def __init__(self, parent):
        QDialog.__init__(self, parent)

        self.resize(100, 70)
        self.setWindowTitle("Navigational Aid")
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        verticalLayoutDlg = QVBoxLayout(self)
        verticalLayoutDlg.setObjectName(("verticalLayoutDlg"))

        self.gbAll = GroupBox(self)
        self.gbAll.Caption = "Properties"
        verticalLayoutDlg.addWidget(self.gbAll)

        self.pnlType = ComboBoxPanel(self.gbAll)
        self.pnlType.Caption = "Type"
        self.pnlType.LabelWidth = 140
        self.gbAll.Add = self.pnlType

        self.pnlName = TextBoxPanel(self.gbAll)
        self.pnlName.Caption = "Name"
        self.pnlName.LabelWidth = 140
        self.pnlType.Items = NavigationalAidType.Items
        self.gbAll.Add = self.pnlName

        self.pnlSlope = AngleGradientBoxPanel(self.gbAll)
        self.pnlSlope.CaptionUnits = AngleGradientSlopeUnits.Degrees
        self.pnlSlope.Caption = "Slope"
        self.pnlSlope.LabelWidth = 140
        self.gbAll.Add = self.pnlSlope

        self.pnlStartingHeight = AltitudeBoxPanel(self.gbAll)
        self.pnlStartingHeight.Caption = "Starting Height"
        self.pnlStartingHeight.CaptionUnits = "m"
        self.pnlStartingHeight.LabelWidth = 140
        self.gbAll.Add = self.pnlStartingHeight

        self.pnlFinishingDistance = DistanceBoxPanel(self.gbAll,
                                                     DistanceUnits.M)
        self.pnlFinishingDistance.Caption = "Finishing Distance"
        self.pnlFinishingDistance.LabelWidth = 140
        self.gbAll.Add = self.pnlFinishingDistance

        self.pnlAlfa = AngleGradientBoxPanel(self.gbAll)
        self.pnlAlfa.CaptionUnits = AngleGradientSlopeUnits.Degrees
        self.pnlAlfa.Caption = "Alpha [" + unicode("α", "utf-8") + " - Cone]"
        self.pnlAlfa.LabelWidth = 140
        self.gbAll.Add = self.pnlAlfa

        self.pnlRadiusCone = DistanceBoxPanel(self.gbAll, DistanceUnits.M)
        self.pnlRadiusCone.Caption = "Radius [R - Cone]"
        self.pnlRadiusCone.LabelWidth = 140
        self.gbAll.Add = self.pnlRadiusCone

        self.pnlRadiusCylinder = DistanceBoxPanel(self.gbAll, DistanceUnits.M)
        self.pnlRadiusCylinder.Caption = "Radius [r - Cylinder]"
        self.pnlRadiusCylinder.LabelWidth = 140
        self.gbAll.Add = self.pnlRadiusCylinder

        self.pnla = DistanceBoxPanel(self.gbAll, DistanceUnits.M)
        self.pnla.Caption = "a"
        self.pnla.LabelWidth = 140
        self.gbAll.Add = self.pnla

        self.pnlb = DistanceBoxPanel(self.gbAll, DistanceUnits.M)
        self.pnlb.Caption = "b"
        self.pnlb.LabelWidth = 140
        self.gbAll.Add = self.pnlb

        self.pnlh = AltitudeBoxPanel(self.gbAll)
        self.pnlh.Caption = "h"
        self.pnlh.CaptionUnits = "m"
        self.pnlh.LabelWidth = 140
        self.gbAll.Add = self.pnlh

        self.pnlr = DistanceBoxPanel(self.gbAll, DistanceUnits.M)
        self.pnlr.Caption = "r"
        self.pnlr.LabelWidth = 140
        self.gbAll.Add = self.pnlr

        self.pnlD = DistanceBoxPanel(self.gbAll, DistanceUnits.M)
        self.pnlD.Caption = "D"
        self.pnlD.LabelWidth = 140
        self.gbAll.Add = self.pnlD

        self.pnlHbig = AltitudeBoxPanel(self.gbAll)
        self.pnlHbig.Caption = "H"
        self.pnlHbig.CaptionUnits = "m"
        self.pnlHbig.LabelWidth = 140
        self.gbAll.Add = self.pnlHbig

        self.pnlL = DistanceBoxPanel(self.gbAll, DistanceUnits.M)
        self.pnlL.Caption = "L"
        self.pnlL.LabelWidth = 140
        self.gbAll.Add = self.pnlL

        self.pnlphi = AngleGradientBoxPanel(self.gbAll)
        self.pnlphi.CaptionUnits = AngleGradientSlopeUnits.Degrees
        self.pnlphi.Caption = unicode("ɸ", "utf-8")
        self.pnlphi.LabelWidth = 140
        self.gbAll.Add = self.pnlphi

        self.btnBoxOkCancel = QDialogButtonBox(self)
        self.btnBoxOkCancel.setObjectName(("btnBoxOkCancel"))
        self.btnBoxOkCancel.setStandardButtons(QDialogButtonBox.Cancel
                                               | QDialogButtonBox.Ok)
        self.connect(self.btnBoxOkCancel, SIGNAL("accepted()"), self.acceptDlg)
        self.connect(self.btnBoxOkCancel, SIGNAL("rejected()"), self.reject)

        verticalLayoutDlg.addWidget(self.btnBoxOkCancel)

        self.connect(self.pnlType, SIGNAL("Event_0"), self.method_5)

        self.shownOnce = False
        self.method_5()

    def get_NavigationalAid(self):
        for case in switch(self.pnlType.SelectedItem):
            if case(NavigationalAidType.Omnidirectional):
                return OmnidirectionalNavigationalAid(
                    self.pnlName.Value, self.pnlAlfa.Value,
                    self.pnlRadiusCone.Value, self.pnlRadiusCylinder.Value,
                    False)
            elif case(NavigationalAidType.Directional):
                return DirectionalNavigationalAid(
                    self.pnlName.Value, self.pnla.Value, self.pnlb.Value,
                    self.pnlh.Value, self.pnlr.Value, self.pnlD.Value,
                    self.pnlHbig.Value, self.pnlL.Value, self.pnlphi.Value,
                    False)
            elif case(NavigationalAidType.LineOfSight):
                return LineOfSight(self.pnlName.Value, self.pnlSlope.Value,
                                   self.pnlStartingHeight.Value,
                                   self.pnlFinishingDistance.Value, False)
            else:
                return None

    def set_NavigationalAid(self, value):
        try:
            if (value != None):
                self.pnlType.SelectedIndex = self.pnlType.FindString(
                    value.Type)
                self.pnlName.Value = value.Name
                if isinstance(value, DirectionalNavigationalAid):
                    directionalNavigationalAid = value
                    self.pnla.Value = directionalNavigationalAid.a
                    self.pnlb.Value = directionalNavigationalAid.b
                    self.pnlh.Value = directionalNavigationalAid.h
                    self.pnlr.Value = directionalNavigationalAid.r
                    self.pnlD.Value = directionalNavigationalAid.D
                    self.pnlHbig.Value = directionalNavigationalAid.H
                    self.pnlL.Value = directionalNavigationalAid.L
                    self.pnlphi.Value = directionalNavigationalAid.phi
                elif isinstance(value, OmnidirectionalNavigationalAid):
                    omnidirectionalNavigationalAid = value
                    self.pnlAlfa.Value = omnidirectionalNavigationalAid.Alfa
                    self.pnlRadiusCone.Value = omnidirectionalNavigationalAid.R
                    self.pnlRadiusCylinder.Value = omnidirectionalNavigationalAid.r
                elif isinstance(value, LineOfSight):
                    lineOfSight = value
                    self.pnlSlope.Value = lineOfSight.Slope
                    self.pnlStartingHeight.Value = lineOfSight.StartingHeight
                    self.pnlFinishingDistance.Value = lineOfSight.FinishingDistance
            self.method_5()
        except:
            pass

    NavigationalAid = property(get_NavigationalAid, set_NavigationalAid, None,
                               None)

    def method_5(self):
        if (self.pnlType.SelectedIndex > -1):
            navigationalAidType = self.pnlType.SelectedItem
            self.pnlName.Enabled = True
            self.pnla.Enabled = navigationalAidType == NavigationalAidType.Directional
            self.pnlb.Enabled = navigationalAidType == NavigationalAidType.Directional
            self.pnlh.Enabled = navigationalAidType == NavigationalAidType.Directional
            self.pnlr.Enabled = navigationalAidType == NavigationalAidType.Directional
            self.pnlD.Enabled = navigationalAidType == NavigationalAidType.Directional
            self.pnlHbig.Enabled = navigationalAidType == NavigationalAidType.Directional
            self.pnlL.Enabled = navigationalAidType == NavigationalAidType.Directional
            self.pnlphi.Enabled = navigationalAidType == NavigationalAidType.Directional
            self.pnlAlfa.Enabled = navigationalAidType == NavigationalAidType.Omnidirectional
            self.pnlRadiusCone.Enabled = navigationalAidType == NavigationalAidType.Omnidirectional
            self.pnlRadiusCylinder.Enabled = navigationalAidType == NavigationalAidType.Omnidirectional
            self.pnlSlope.Enabled = navigationalAidType == NavigationalAidType.LineOfSight
            self.pnlStartingHeight.Enabled = navigationalAidType == NavigationalAidType.LineOfSight
            self.pnlFinishingDistance.Enabled = navigationalAidType == NavigationalAidType.LineOfSight

    def acceptDlg(self):

        self.accept()

    @staticmethod
    def smethod_0(iwin32Window_0, navigationalAid_0):
        flag = False
        dlgNavigationalAid = DlgNavigationalAid(iwin32Window_0)
        dlgNavigationalAid.NavigationalAid = navigationalAid_0
        result = dlgNavigationalAid.exec_()
        if (not result):
            flag = False
        else:
            navigationalAid_0 = dlgNavigationalAid.NavigationalAid
            flag = True
        return flag, navigationalAid_0
class DlgAixmEffectiveDate(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)

        self.resize(290, 136)
        self.setWindowTitle("Effective Date")
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        verticalLayoutDlg = QVBoxLayout(self)
        verticalLayoutDlg.setObjectName(("verticalLayoutDlg"))

        self.groupBox = GroupBox(self)
        verticalLayoutDlg.addWidget(self.groupBox)

        self.dtpDate = QDateTimeEdit(self.groupBox)
        self.dtpDate.setObjectName(("dtpDate"))
        self.dtpDate.setDateTime(QDateTime.currentDateTime())
        self.groupBox.Add = self.dtpDate

        self.calendar = QCalendarWidget(self.groupBox)
        self.groupBox.Add = self.calendar
        self.calendar.clicked.connect(self.calendar_clicked)

        self.btnBoxOkCancel = QDialogButtonBox(self)
        self.btnBoxOkCancel.setObjectName(("btnBoxOkCancel"))
        self.btnBoxOkCancel.setStandardButtons(QDialogButtonBox.Cancel
                                               | QDialogButtonBox.Ok)
        # btnOK = self.btnBoxOkCancel.button(QDialogButtonBox.Ok)
        # btnOK.setText("Create")
        self.connect(self.btnBoxOkCancel, SIGNAL("accepted()"), self.acceptDlg)
        self.connect(self.btnBoxOkCancel, SIGNAL("rejected()"), self.reject)

        verticalLayoutDlg.addWidget(self.btnBoxOkCancel)

    def calendar_clicked(self, date):
        self.dtpDate.setDate(date)

    def get_DateTime(self):
        return self.dtpDate.dateTime()

    def set_DateTime(self, dateTime):
        if dateTime != None:
            self.dtpDate.setDateTime(dateTime)
            self.calendar.setCurrentPage(dateTime.date().year(),
                                         dateTime.date().month())

    DateTime = property(get_DateTime, set_DateTime, None, None)

    def acceptDlg(self):
        self.accept()

    @staticmethod
    def smethod_0(dateTime_0):
        flag = False
        dlgAixmEffectiveDate = DlgAixmEffectiveDate()
        dlgAixmEffectiveDate.dtpDate.setDateTime(dateTime_0)
        resultDlg = dlgAixmEffectiveDate.exec_()
        if (resultDlg != 1):
            return False, dateTime_0
        else:
            dateTime_0 = dlgAixmEffectiveDate.DateTime
            flag = True
        return flag, dateTime_0
Beispiel #30
0
class DlgAirspaceDataEdit(QDialog):
    def __init__(self, parent, title, valueList=None):
        QDialog.__init__(self, parent)

        self.resize(100, 70)
        self.setWindowTitle(title)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        verticalLayoutDlg = QVBoxLayout(self)
        verticalLayoutDlg.setObjectName(("verticalLayoutDlg"))

        self.frameBasic = Frame(self)
        verticalLayoutDlg.addWidget(self.frameBasic)

        self.pnlName = TextBoxPanel(self.frameBasic)
        self.pnlName.Caption = "Name"
        self.pnlName.LabelWidth = 120
        self.frameBasic.Add = self.pnlName

        self.pnlLowerLimit = DistanceBoxPanel(self.frameBasic, DistanceUnits.M)
        self.pnlLowerLimit.Caption = "Lower Limit"
        self.pnlLowerLimit.Button = None
        self.pnlLowerLimit.LabelWidth = 120
        self.frameBasic.Add = self.pnlLowerLimit

        self.pnlUpperLimit = DistanceBoxPanel(self.frameBasic, DistanceUnits.M)
        self.pnlUpperLimit.Caption = "Upper Limit"
        self.pnlUpperLimit.Button = None
        self.pnlUpperLimit.LabelWidth = 120
        self.frameBasic.Add = self.pnlUpperLimit

        self.pnlRadius = DistanceBoxPanel(self.frameBasic, DistanceUnits.M)
        self.pnlRadius.Caption = "Radius"
        self.pnlRadius.Button = None
        self.pnlRadius.LabelWidth = 120
        self.frameBasic.Add = self.pnlRadius

        self.btnBoxOkCancel = QDialogButtonBox(self)
        self.btnBoxOkCancel.setObjectName(("btnBoxOkCancel"))
        self.btnBoxOkCancel.setStandardButtons(QDialogButtonBox.Cancel
                                               | QDialogButtonBox.Ok)
        self.connect(self.btnBoxOkCancel, SIGNAL("accepted()"), self.acceptDlg)
        self.connect(self.btnBoxOkCancel, SIGNAL("rejected()"), self.reject)

        verticalLayoutDlg.addWidget(self.btnBoxOkCancel)

        self.name = ""
        self.lowerLimit = ""
        self.upperLimit = ""
        self.radius = ""

        if valueList != None:
            self.pnlName.Value = valueList[0]
            self.pnlLowerLimit.Value = Distance(float(valueList[1]))
            self.pnlUpperLimit.Value = Distance(float(valueList[2]))
            if valueList[3] != None and valueList[3] != "":
                self.pnlRadius.Value = Distance(float(valueList[3]))

    def acceptDlg(self):
        self.name = self.pnlName.Value
        self.lowerLimit = QString(str(self.pnlLowerLimit.Value.Metres))
        self.upperLimit = QString(str(self.pnlUpperLimit.Value.Metres))
        if self.pnlRadius.Value.Metres == 0:
            self.radius = QString("")
        else:
            self.radius = QString(str(self.pnlRadius.Value.Metres))
        self.accept()
Beispiel #31
0
class EntityEditorDialog(QDialog, MapperMixin):
    """
    Dialog for editing entity attributes.
    """
    addedModel = pyqtSignal(object)

    def __init__(self,
                 entity,
                 model=None,
                 parent=None,
                 manage_documents=True,
                 collect_model=False,
                 parent_entity=None,
                 exclude_columns=[],
                 plugin=None):
        """
        Class constructor.
        :param entity: Entity object corresponding to a table object.
        :type entity: Entity
        :param model: Data object for loading data into the form widgets.
        If the model is set, then the editor dialog is assumed to be in edit
        mode.
        :type model: object
        :param parent: Parent widget that the form belongs to.
        :type parent: QWidget
        :param manage_documents: True if the dialog should provide controls
        for managing supporting documents. Only applicable if the entity
        allows for supporting documents to be attached.
        :type manage_documents: bool
        :param collect_model: If set to True only returns
        the filled form model without saving it to the database.
        :type collect_model: Boolean
        :param parent_entity: The parent entity of the editor
        :type parent_entity: Object
        :param exclude_columns: List of columns to be excluded if in a list.
        :type exclude_columns: List
        :return: If collect_model, returns SQLAlchemy Model
        """
        QDialog.__init__(self, parent)

        self.entity_table_model = {}

        self.collection_suffix = self.tr('Collection')

        #Set minimum width
        self.setMinimumWidth(450)

        self.plugin = plugin

        #Flag for mandatory columns
        self.has_mandatory = False
        self.reload_form = False
        self._entity = entity
        self.edit_model = model
        self.column_widgets = OrderedDict()
        self._parent = parent
        self.exclude_columns = exclude_columns
        self.entity_tab_widget = None
        self._disable_collections = False
        self.filter_val = None
        self.parent_entity = parent_entity
        self.child_models = OrderedDict()
        self.entity_scroll_area = None
        self.entity_editor_widgets = OrderedDict()
        # Set notification layout bar
        self.vlNotification = QVBoxLayout()
        self.vlNotification.setObjectName('vlNotification')
        self._notifBar = NotificationBar(self.vlNotification)
        self.do_not_check_dirty = False
        # Set manage documents only if the entity supports documents
        if self._entity.supports_documents:
            self._manage_documents = manage_documents
        else:
            self._manage_documents = False

        # Setup entity model
        self._ent_document_model = None
        if self._entity.supports_documents:
            self.ent_model, self._ent_document_model = entity_model(
                self._entity, with_supporting_document=True)
        else:
            self.ent_model = entity_model(self._entity)
        if not model is None:
            self.ent_model = model

        MapperMixin.__init__(self, self.ent_model, entity)

        self.collect_model = collect_model

        self.register_column_widgets()
        try:
            if isinstance(parent._parent, EntityEditorDialog):
                # hide collections form child editor
                self._disable_collections = True

        except AttributeError:
            self._parent._parent = None
        # Set title
        editor_trans = self.tr('Editor')
        if self._entity.label is not None:
            if self._entity.label != '':
                title_str = self._entity.label
            else:
                title_str = format_name(self._entity.short_name)
        else:
            title_str = format_name(self._entity.short_name)

        self.title = u'{0} {1}'.format(title_str, editor_trans)

        self.setWindowTitle(self.title)

        self._init_gui()
        self.adjustSize()

        self._get_entity_editor_widgets()

        if isinstance(parent._parent, EntityEditorDialog):
            self.parent_entity = parent.parent_entity
            self.set_parent_values()
            # make the size smaller to differentiate from parent and as it
            # only has few tabs.
            self.adjustSize()

        self.attribute_mappers = self._attr_mapper_collection

        # Exception title for editor extension exceptions
        self._ext_exc_msg = self.tr(
            'An error has occured while executing Python code in the editor '
            'extension:')

        # Register custom editor extension if specified
        self._editor_ext = entity_dlg_extension(self)
        if not self._editor_ext is None:
            self._editor_ext.post_init()

            # Initialize CascadingFieldContext objects
            self._editor_ext.connect_cf_contexts()

    def _init_gui(self):
        # Setup base elements
        self.gridLayout = QGridLayout(self)
        self.gridLayout.setObjectName('glMain')
        self.gridLayout.addLayout(self.vlNotification, 0, 0, 1, 1)
        QApplication.processEvents()

        #set widgets values
        column_widget_area = self._setup_columns_content_area()

        self.gridLayout.addWidget(column_widget_area, 1, 0, 1, 1)

        QApplication.processEvents()
        # Add notification for mandatory columns if applicable
        next_row = 2
        if self.has_mandatory:
            self.required_fields_lbl = QLabel(self)
            msg = self.tr('Please fill out all required (*) fields.')
            msg = self._highlight_asterisk(msg)
            self.required_fields_lbl.setText(msg)
            self.gridLayout.addWidget(self.required_fields_lbl, next_row, 0, 1,
                                      2)
            # Bump up row reference
            next_row += 1

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setObjectName('buttonBox')
        self.gridLayout.addWidget(self.buttonBox, next_row, 0, 1, 1)

        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Save)

        if self.edit_model is None:
            if not self.collect_model:
                self.save_new_button = QPushButton(
                    QApplication.translate('EntityEditorDialog',
                                           'Save and New'))
                self.buttonBox.addButton(self.save_new_button,
                                         QDialogButtonBox.ActionRole)

        # edit model, collect model
        # adding new record for child

        # Saving in parent editor
        if not isinstance(self._parent._parent, EntityEditorDialog):
            # adding a new record
            if self.edit_model is None:
                # saving when digitizing.
                if self.collect_model:
                    self.buttonBox.accepted.connect(self.on_model_added)
                # saving parent editor
                else:
                    self.buttonBox.accepted.connect(self.save_parent_editor)
                    self.save_new_button.clicked.connect(self.save_and_new)
            # updating existing record
            else:
                if not self.collect_model:
                    # updating existing record of the parent editor
                    self.buttonBox.accepted.connect(self.save_parent_editor)
                else:
                    self.buttonBox.accepted.connect(self.on_model_added)
        # Saving in child editor
        else:
            # save and new record
            if self.edit_model is None:
                self.buttonBox.accepted.connect(self.on_child_saved)
                self.save_new_button.clicked.connect(
                    lambda: self.on_child_saved(True))

            else:
                # When updating an existing child editor save to the db
                self.buttonBox.accepted.connect(self.on_child_saved)
                #self.buttonBox.accepted.connect(self.submit)

        self.buttonBox.rejected.connect(self.cancel)

    @property
    def notification_bar(self):
        """
        :return: Returns the dialog's notification bar.
        :rtype: NotificationBar
        """
        return self._notifBar

    def save_parent_editor(self):
        """
        Saves the parent editor and its children.
        """
        self.submit()
        self.save_children()

    def set_parent_values(self):
        """
        Sets the parent display column for the child.
        """
        if self.parent_entity is None:
            return
        for col in self._entity.columns.values():
            if col.TYPE_INFO == 'FOREIGN_KEY':
                parent_entity = col.parent
                if parent_entity == self.parent_entity:
                    self.parent_widgets_value_setter(self._parent._parent, col)

    def parent_widgets_value_setter(self, parent, col):
        """
        Finds and sets the value from parent widget and set it to the column
        widget of a child using the child column.
        :param parent: The parent widget
        :type parent: QWidget
        :param col: The child column object
        :type col: Object
        """
        for parent_col, parent_widget in parent.column_widgets.iteritems():
            if parent_col.name == col.name:
                self.single_parent_value_setter(col, parent_widget)
                break
            if parent_col.name in col.entity_relation.display_cols:
                self.single_parent_value_setter(col, parent_widget)
                break

    def single_parent_value_setter(self, col, parent_widget):
        """
        Gets value from parent widget and set it to the column widget of a
        child using the child column.
        :param parent: The parent widget
        :type parent: QWidget
        :param col: The child column object
        :type col: Object
        """
        local_widget = self.column_widgets[col]
        local_widget.show_clear_button()
        self.filter_val = parent_widget.text()
        local_widget.setText(self.filter_val)

    def save_and_new(self):
        """
        A slot raised when Save and New button is click. It saves the form
        without showing a success message. Then it sets reload_form property
        to True so that entity_browser can re-load the form.
        """
        from stdm.ui.entity_browser import (EntityBrowserWithEditor)
        self.submit(False, True)
        self.save_children()

        if self.is_valid:
            self.addedModel.emit(self.model())
            self.setModel(self.ent_model())
            self.clear()
            self.child_models.clear()
            for index in range(0, self.entity_tab_widget.count() - 1):
                if isinstance(self.entity_tab_widget.widget(index),
                              EntityBrowserWithEditor):
                    child_browser = self.entity_tab_widget.widget(index)
                    child_browser.remove_rows()

    def on_model_added(self):
        """
        A slot raised when a form is submitted with collect model set to True.
        There will be no success message and the form does not close.
        """
        self.submit(True)
        self.addedModel.emit(self.model())

    def closeEvent(self, event):
        '''
        Raised when a request to close the window is received.
        Check the dirty state of input controls and prompt user to
        save if dirty.
        '''

        if self.do_not_check_dirty:
            event.accept()
            return
        isDirty, userResponse = self.checkDirty()

        if isDirty:
            if userResponse == QMessageBox.Yes:
                # We need to ignore the event so that validation and
                # saving operations can be executed
                event.ignore()
                self.submit()
            elif userResponse == QMessageBox.No:
                event.accept()
            elif userResponse == QMessageBox.Cancel:
                event.ignore()
        else:
            event.accept()

    def on_child_saved(self, save_and_new=False):
        """
        A slot raised when the save or save and new button is clicked. It sets
        the child_models dictionary of the parent when saved.
        :param save_and_new: A boolean indicating the save and new button is
        clicked to trigger the slot.
        :type save_and_new: Boolean
        """
        if self.parent_entity is None:
            return

        self.submit(True)

        insert_pos = self._parent.tbEntity.model().rowCount() + 1
        # Save to parent editor so that it is persistent.
        self._parent._parent.child_models[insert_pos, self._entity] = \
            self.model()
        self.addedModel.emit(self.model())
        if not save_and_new:
            self.accept()

        else:
            if self.is_valid:
                #self.addedModel.emit(self.model())
                self.setModel(self.ent_model())

                self.clear()
                self.set_parent_values()

    def save_children(self):
        """
        Saves children models into the database by assigning the the id of the
        parent for foreign key column.
        """
        if len(self.child_models) < 1:
            return
        children_obj = []
        for row_entity, model in self.child_models.iteritems():
            row_pos = row_entity[0]
            entity = row_entity[1]
            ent_model = entity_model(entity)
            entity_obj = ent_model()
            for col in entity.columns.values():
                if col.TYPE_INFO == 'FOREIGN_KEY':
                    if col.parent.name == self._entity.name:
                        setattr(model, col.name, self.model().id)
                        children_obj.append(model)
            entity_obj.saveMany(children_obj)

    def register_column_widgets(self):
        """
        Registers the column widgets.
        """
        # Append column labels and widgets
        table_name = self._entity.name
        columns = table_column_names(table_name)
        self.scroll_widget_contents = QWidget()
        self.scroll_widget_contents.setObjectName('scrollAreaWidgetContents')
        for c in self._entity.columns.values():
            if c.name in self.exclude_columns:
                continue
            if not c.name in columns and not isinstance(c, VirtualColumn):
                continue
            # Get widget factory
            column_widget = ColumnWidgetRegistry.create(
                c, self.scroll_widget_contents, host=self)
            self.column_widgets[c] = column_widget

    def _setup_columns_content_area(self):
        # Only use this if entity supports documents
        # self.entity_tab_widget = None
        self.doc_widget = None

        self.entity_scroll_area = QScrollArea(self)
        self.entity_scroll_area.setFrameShape(QFrame.NoFrame)
        self.entity_scroll_area.setWidgetResizable(True)
        self.entity_scroll_area.setObjectName('scrollArea')

        # Grid layout for controls
        self.gl = QGridLayout(self.scroll_widget_contents)
        self.gl.setObjectName('gl_widget_contents')

        # Append column labels and widgets
        table_name = self._entity.name
        columns = table_column_names(table_name)
        # Iterate entity column and assert if they exist
        row_id = 0
        for c, column_widget in self.column_widgets.iteritems():
            if c.name in self.exclude_columns:
                continue
            if not c.name in columns and not isinstance(c, VirtualColumn):
                continue

            if column_widget is not None:
                header = c.ui_display()
                self.c_label = QLabel(self.scroll_widget_contents)

                # Format label text if it is a mandatory field
                if c.mandatory:
                    header = u'{0} *'.format(c.ui_display())
                    #Highlight asterisk
                    header = self._highlight_asterisk(header)

                self.c_label.setText(header)
                self.gl.addWidget(self.c_label, row_id, 0, 1, 1)

                self.column_widget = column_widget
                self.gl.addWidget(self.column_widget, row_id, 1, 1, 1)

                #Add user tip if specified for the column configuration
                if c.user_tip:
                    self.tip_lbl = UserTipLabel(user_tip=c.user_tip)
                    self.gl.addWidget(self.tip_lbl, row_id, 2, 1, 1)

                if c.mandatory and not self.has_mandatory:
                    self.has_mandatory = True

                col_name = c.name
                #Replace name accordingly based on column type
                if isinstance(c, MultipleSelectColumn):
                    col_name = c.model_attribute_name

                # Add widget to MapperMixin collection
                self.addMapping(col_name,
                                self.column_widget,
                                c.mandatory,
                                pseudoname=c.ui_display())

                # Bump up row_id
                row_id += 1

        self.entity_scroll_area.setWidget(self.scroll_widget_contents)

        if self.entity_tab_widget is None:
            self.entity_tab_widget = QTabWidget(self)
        # Check if there are children and add foreign key browsers

        # Add primary tab if necessary
        self._add_primary_attr_widget()

        if not self._disable_collections:
            ch_entities = self.children_entities()

            for col, ch in ch_entities.iteritems():
                if hasattr(col.entity_relation, 'show_in_parent'):
                    if col.entity_relation.show_in_parent != '0':
                        self._add_fk_browser(ch, col)
                else:
                    self._add_fk_browser(ch, col)

        #Add tab widget if entity supports documents
        if self._entity.supports_documents:
            self.doc_widget = SupportingDocumentsWidget(
                self._entity.supporting_doc, self._ent_document_model, self)

            # Map the source document manager object
            self.addMapping('documents',
                            self.doc_widget.source_document_manager)

            #
            # # Add attribute tab
            # self._add_primary_attr_widget()

            # Add supporting documents tab
            self.entity_tab_widget.addTab(self.doc_widget,
                                          self.tr('Supporting Documents'))

        # Return the correct widget
        if not self.entity_tab_widget is None:
            return self.entity_tab_widget

        return self.entity_scroll_area

    def _add_primary_attr_widget(self):
        # Check if the primary entity
        # exists and add if it does not
        pr_txt = self.tr('Primary')
        if not self.entity_tab_widget is None:
            tab_txt = self.entity_tab_widget.tabText(0)
            if not tab_txt == pr_txt:
                self.entity_tab_widget.addTab(self.entity_scroll_area, pr_txt)

    def _add_fk_browser(self, child_entity, column):
        # Create and add foreign key
        # browser to the collection
        from stdm.ui.entity_browser import (EntityBrowserWithEditor)

        attr = u'{0}_collection'.format(child_entity.name)

        # Return if the attribute does not exist
        if not hasattr(self._model, attr):
            return
        entity_browser = EntityBrowserWithEditor(child_entity,
                                                 self,
                                                 MANAGE,
                                                 False,
                                                 plugin=self.plugin)
        entity_browser.buttonBox.setVisible(False)
        entity_browser.record_filter = []

        if len(child_entity.label) > 2:
            column_label = child_entity.label
        else:
            # Split and join  to filter out entity name prefix
            # e.g. 'lo_parcel' to 'parcel'
            column_label = format_name(" ".join(
                child_entity.name.split("_", 1)[1:]))
        self.entity_tab_widget.addTab(entity_browser,
                                      u'{0}'.format(column_label))
        self.set_filter(child_entity, entity_browser)

    def set_filter(self, entity, browser):
        col = self.filter_col(entity)
        child_model = entity_model(entity)
        child_model_obj = child_model()
        col_obj = getattr(child_model, col.name)
        if self.model() is not None:
            if self.model().id is None:
                browser.filtered_records = []
            else:
                browser.filtered_records = child_model_obj.queryObject(
                ).filter(col_obj == self.model().id).all()

        if self.edit_model is not None:
            browser.filtered_records = child_model_obj.queryObject().filter(
                col_obj == self.edit_model.id).all()

        if self.edit_model is None and self.model() is None:
            browser.filtered_records = []

    def filter_col(self, child_entity):
        for col in child_entity.columns.values():
            if col.TYPE_INFO == 'FOREIGN_KEY':
                parent_entity = col.parent
                if parent_entity == self._entity:
                    return col

    def children_entities(self):
        """
        :return: Returns a list of children entities
        that refer to the main entity as the parent.
        :rtype: OrderedDict
        """
        child_columns = OrderedDict()
        for ch in self._entity.children():
            if ch.TYPE_INFO == Entity.TYPE_INFO:
                for col in ch.columns.values():
                    if hasattr(col, 'entity_relation'):

                        if col.parent.name == self._entity.name:
                            child_columns[col] = ch
        return child_columns

    def document_widget(self):
        """
        :return: Returns the widget for managing
        the supporting documents for an entity if enabled.
        :rtype: SupportingDocumentsWidget
        """
        return self.doc_widget

    def source_document_manager(self):
        """
        :return: Returns an instance of the
        SourceDocumentManager only if supporting
        documents are enabled for the given entity. Otherwise,
        None if supporting documents are not enabled.
        :rtype: SourceDocumentManager
        """
        if self.doc_widget is None:
            return None

        return self.doc_widget.source_document_manager

    def _highlight_asterisk(self, text):
        # Highlight asterisk in red
        c = '*'

        # Do not format if there is no asterisk
        if text.find(c) == -1:
            return text

        asterisk_highlight = '<span style=\" color:#ff0000;\">*</span>'
        text = text.replace(c, asterisk_highlight)

        return u'<html><head/><body><p>{0}</p></body></html>'.format(text)

    def _custom_validate(self):
        """
        Override of the MapperMixin which enables custom editor extensions to
        inject additional validation before saving form data.
        :return: Return True if the validation was successful,
        otherwise False.
        :rtype: bool
        """
        if not self._editor_ext is None:
            return self._editor_ext.validate()

        # Return True if there is no custom editor extension specified
        return True

    def _post_save(self, model):
        """
        Include additional post-save logic by custom extensions.
        :param model: SQLAlchemy model
        :type model: object
        """
        if not self._editor_ext is None:
            self._editor_ext.post_save(model)

    def _get_entity_editor_widgets(self):
        """
        Gets entity editor widgets and appends them to a dictionary
        """
        if self.entity_tab_widget:
            tab_count = self.entity_tab_widget.count()
            for i in range(tab_count):
                tab_object = self.entity_tab_widget.widget(i)
                tab_text = self.entity_tab_widget.tabText(i)
                self.entity_editor_widgets[tab_text] = tab_object
        else:
            self.entity_editor_widgets['no_tab'] = self.entity_scroll_area
Beispiel #32
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
#     }
# }
Beispiel #33
0
class ProxyPreferencesWidget(QDialog):
    def __init__(self, parent=None):
        super(ProxyPreferencesWidget, self).__init__(parent, Qt.Dialog)
        self.setObjectName('Dialog')
        self.resize(325, 142)
        self.setMinimumSize(QSize(325, 142))
        self.setMaximumSize(QSize(325, 142))
        self.formLayout = QFormLayout(self)
        self.formLayout.setObjectName('formLayout')
        self.proxyEnable = QCheckBox(self)
        self.proxyEnable.setObjectName('proxyEnable')
        self.proxyEnable.stateChanged.connect(self.enable_edit)
        self.formLayout.setWidget(0, QFormLayout.LabelRole, self.proxyEnable)
        self.proxyServer = QLineEdit(self)
        self.proxyServer.setObjectName('proxyServer')
        self.formLayout.setWidget(1, QFormLayout.FieldRole, self.proxyServer)
        self.proxyLogin = QLineEdit(self)
        self.proxyLogin.setObjectName('proxyLogin')
        self.formLayout.setWidget(2, QFormLayout.FieldRole, self.proxyLogin)
        #self.proxyPass = QLineEdit(self)
        plug_path = os.path.abspath(__file__)
        plug_path = os.path.dirname(plug_path)
        self.proxyPass = ButtonInLineEdit(self, plug_path + '/eye.svg')
        self.proxyPass.setObjectName('proxyPass')
        self.proxyPass.setEchoMode(QLineEdit.Password)
        self.formLayout.setWidget(3, QFormLayout.FieldRole, self.proxyPass)
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok)
        self.buttonBox.setObjectName('buttonBox')
        self.formLayout.setWidget(4, QFormLayout.FieldRole, self.buttonBox)
        self.label = QLabel(self)
        self.label.setObjectName('label')
        self.formLayout.setWidget(1, QFormLayout.LabelRole, self.label)
        self.label_2 = QLabel(self)
        self.label_2.setObjectName('label_2')
        self.formLayout.setWidget(2, QFormLayout.LabelRole, self.label_2)
        self.label_3 = QLabel(self)
        self.label_3.setObjectName('label_3')
        self.formLayout.setWidget(3, QFormLayout.LabelRole, self.label_3)

        self.setWindowTitle('Proxy preferences')
        self.proxyEnable.setText('Enable Proxy')
        self.label.setText('Proxy server:port')
        self.label_2.setText('Login')
        self.label_3.setText('Password')

        QObject.connect(self.buttonBox, SIGNAL('accepted()'), self.save_settings)
        QObject.connect(self.buttonBox, SIGNAL('rejected()'), self.reject)
        QObject.connect(self.proxyPass.Button, SIGNAL('pressed()'), lambda: self.proxyPass.setEchoMode(QLineEdit.Normal))
        QObject.connect(self.proxyPass.Button, SIGNAL('released()'), lambda: self.proxyPass.setEchoMode(QLineEdit.Password))
        QMetaObject.connectSlotsByName(self)

    def show_pass(self):
        self.proxyPass.setEchoMode(QLineEdit.Normal)

    def enable_edit(self):
        if not self.proxyEnable.isChecked():
            self.proxyServer.setEnabled(False)
            self.proxyLogin.setEnabled(False)
            self.proxyPass.setEnabled(False)
        else:
            self.proxyServer.setEnabled(True)
            self.proxyLogin.setEnabled(True)
            self.proxyPass.setEnabled(True)

    def set_values(self, preferences):
        self.proxyEnable.setChecked(preferences['proxy_enabled'])
        self.proxyServer.setText(preferences['proxy_server'])
        self.proxyLogin.setText(preferences['proxy_login'])
        self.proxyPass.setText(preferences['proxy_password'])
        self.enable_edit()

    def save_settings(self):
        qsettings = QSettings(resources.SETTINGS_PATH, QSettings.IniFormat)
        qsettings.beginGroup('proxy')
        qsettings.setValue('enabled', self.proxyEnable.isChecked())
        qsettings.setValue('server', self.proxyServer.text())
        qsettings.setValue('login', self.proxyLogin.text())
        qsettings.setValue('password', base64.b64encode(self.proxyPass.text()))
        qsettings.endGroup()
        self.accept()
class DlgAixmOcaOch(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)

        self.resize(290, 136)
        self.setWindowTitle("Instrument Approach Procedure (IAP)")
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        verticalLayoutDlg = QVBoxLayout(self)
        verticalLayoutDlg.setObjectName(("verticalLayoutDlg"))

        self.groupBox = GroupBox(self)
        verticalLayoutDlg.addWidget(self.groupBox)

        self.pnlCodeCatAcft = ComboBoxPanel(self.groupBox)
        self.pnlCodeCatAcft.Caption = "Ac. Category"
        self.pnlCodeCatAcft.LabelWidth = 100
        self.groupBox.Add = self.pnlCodeCatAcft

        self.pnlCodeTypeApch = ComboBoxPanel(self.groupBox)
        self.pnlCodeTypeApch.Caption = "Approach Type"
        self.pnlCodeTypeApch.LabelWidth = 100
        self.groupBox.Add = self.pnlCodeTypeApch

        self.pnlValOca = AltitudeBoxPanel(self.groupBox)
        self.pnlValOca.CaptionUnits = "ft"
        self.pnlValOca.Caption = "OCA"
        self.pnlValOca.LabelWidth = 100
        self.groupBox.Add = self.pnlValOca

        self.pnlOchBase = Frame(self.groupBox, "HL")
        self.groupBox.Add = self.pnlOchBase

        self.pnlValOch = AltitudeBoxPanel(self.pnlOchBase)
        self.pnlValOch.CaptionUnits = "ft"
        self.pnlValOch.Caption = "OCH"
        self.pnlValOch.LabelWidth = 100
        self.pnlOchBase.Add = self.pnlValOch

        self.pnlCodeRefOch = ComboBoxPanel(self.pnlOchBase)
        self.pnlCodeRefOch.Caption = ""
        self.pnlCodeRefOch.LabelWidth = 0
        self.pnlOchBase.Add = self.pnlCodeRefOch

        self.txtRemarks = TextBoxPanel(self.groupBox, True)
        self.txtRemarks.Caption = "Remarks"
        self.txtRemarks.LabelWidth = 100
        self.groupBox.Add = self.txtRemarks

        self.btnBoxOkCancel = QDialogButtonBox(self)
        self.btnBoxOkCancel.setObjectName(("btnBoxOkCancel"))
        self.btnBoxOkCancel.setStandardButtons(QDialogButtonBox.Cancel
                                               | QDialogButtonBox.Ok)
        self.connect(self.btnBoxOkCancel, SIGNAL("accepted()"), self.acceptDlg)
        self.connect(self.btnBoxOkCancel, SIGNAL("rejected()"), self.reject)

        verticalLayoutDlg.addWidget(self.btnBoxOkCancel)

        self.pnlCodeCatAcft.Items = CodeCatAcftAixm.Items
        self.pnlCodeTypeApch.Items = CodeTypeApchAixm.Items
        self.pnlCodeRefOch.Items = CodeRefOchAixm.Items

    def acceptDlg(self):
        self.accept()

    @staticmethod
    def smethod_0(dataBaseIapOcaOch_0):
        flag = False
        dlgAixmOcaOch = DlgAixmOcaOch()
        dlgAixmOcaOch.pnlCodeCatAcft.SelectedIndex = DlgAixmOcaOch.smethod_1(
            dlgAixmOcaOch.pnlCodeCatAcft.Items,
            dataBaseIapOcaOch_0.CodeCatAcft)
        dlgAixmOcaOch.pnlCodeTypeApch.SelectedIndex = DlgAixmOcaOch.smethod_1(
            dlgAixmOcaOch.pnlCodeTypeApch.Items,
            dataBaseIapOcaOch_0.CodeTypeApch)
        dlgAixmOcaOch.pnlValOca.Value = dataBaseIapOcaOch_0.ValOca
        dlgAixmOcaOch.pnlValOch.Value = dataBaseIapOcaOch_0.ValOch
        dlgAixmOcaOch.pnlCodeRefOch.SelectedIndex = DlgAixmOcaOch.smethod_1(
            dlgAixmOcaOch.pnlCodeRefOch.Items, dataBaseIapOcaOch_0.CodeRefOch)
        dlgAixmOcaOch.txtRemarks.Value = dataBaseIapOcaOch_0.TxtRmk
        resultDlg = dlgAixmOcaOch.exec_()
        if (resultDlg == 0):
            return False
        else:
            dataBaseIapOcaOch_0.CodeCatAcft = dlgAixmOcaOch.pnlCodeCatAcft.SelectedItem
            dataBaseIapOcaOch_0.CodeTypeApch = dlgAixmOcaOch.pnlCodeTypeApch.SelectedItem
            dataBaseIapOcaOch_0.ValOca = dlgAixmOcaOch.pnlValOca.Value
            dataBaseIapOcaOch_0.ValOch = dlgAixmOcaOch.pnlValOch.Value
            if (dataBaseIapOcaOch_0.ValOch.IsValid()):
                dataBaseIapOcaOch_0.CodeRefOch = dlgAixmOcaOch.pnlCodeRefOch.SelectedItem
            dataBaseIapOcaOch_0.TxtRmk = dlgAixmOcaOch.txtRemarks.Value
            dataBaseIapOcaOch_0.refresh()
        flag = True
        return flag

    @staticmethod
    def smethod_1(ilist_0, string_0):
        for i in range(len(ilist_0)):
            if ilist_0[
                    i] == string_0:  # (string.Equals(ilist_0[i].ToString(), string_0, StringComparison.OrdinalIgnoreCase))
                return i
        return -1
Beispiel #35
0
class EntityEditorDialog(QDialog, MapperMixin):
    """
    Dialog for editing entity attributes.
    """
    addedModel = pyqtSignal(object)

    def __init__(
            self,
            entity,
            model=None,
            parent=None,
            manage_documents=True,
            collect_model=False,
            parent_entity=None,
            exclude_columns=[],
            plugin = None
    ):
        """
        Class constructor.
        :param entity: Entity object corresponding to a table object.
        :type entity: Entity
        :param model: Data object for loading data into the form widgets.
        If the model is set, then the editor dialog is assumed to be in edit
        mode.
        :type model: object
        :param parent: Parent widget that the form belongs to.
        :type parent: QWidget
        :param manage_documents: True if the dialog should provide controls
        for managing supporting documents. Only applicable if the entity
        allows for supporting documents to be attached.
        :type manage_documents: bool
        :param collect_model: If set to True only returns
        the filled form model without saving it to the database.
        :type collect_model: Boolean
        :param parent_entity: The parent entity of the editor
        :type parent_entity: Object
        :param exclude_columns: List of columns to be excluded if in a list.
        :type exclude_columns: List
        :return: If collect_model, returns SQLAlchemy Model
        """
        QDialog.__init__(self, parent)

        self.entity_table_model = {}

        self.collection_suffix = self.tr('Collection')

        #Set minimum width
        self.setMinimumWidth(450)

        self.plugin = plugin

        #Flag for mandatory columns
        self.has_mandatory = False
        self.reload_form = False
        self._entity = entity
        self.edit_model = model
        self.column_widgets = OrderedDict()
        self._parent = parent
        self.exclude_columns = exclude_columns
        self.entity_tab_widget = None
        self._disable_collections = False
        self.filter_val = None
        self.parent_entity = parent_entity
        self.child_models = OrderedDict()
        self.entity_scroll_area = None
        self.entity_editor_widgets = OrderedDict()
        # Set notification layout bar
        self.vlNotification = QVBoxLayout()
        self.vlNotification.setObjectName('vlNotification')
        self._notifBar = NotificationBar(self.vlNotification)
        self.do_not_check_dirty = False
        # Set manage documents only if the entity supports documents
        if self._entity.supports_documents:
            self._manage_documents = manage_documents
        else:
            self._manage_documents = False

        # Setup entity model
        self._ent_document_model = None
        if self._entity.supports_documents:
            self.ent_model, self._ent_document_model = entity_model(
                self._entity,
                with_supporting_document=True
            )
        else:
            self.ent_model = entity_model(self._entity)
        if not model is None:
            self.ent_model = model

        MapperMixin.__init__(self, self.ent_model, entity)

        self.collect_model = collect_model

        self.register_column_widgets()
        try:
            if isinstance(parent._parent, EntityEditorDialog):
                # hide collections form child editor
                self._disable_collections = True

        except AttributeError:
            self._parent._parent = None
        # Set title
        editor_trans = self.tr('Editor')
        if self._entity.label is not None:
            if self._entity.label != '':
                title_str = self._entity.label
            else:
                title_str = format_name(self._entity.short_name)
        else:
            title_str = format_name(self._entity.short_name)

        self.title = u'{0} {1}'.format(title_str, editor_trans)

        self.setWindowTitle(self.title)

        self._init_gui()
        self.adjustSize()

        self._get_entity_editor_widgets()

        if isinstance(parent._parent, EntityEditorDialog):
            self.parent_entity = parent.parent_entity
            self.set_parent_values()
            # make the size smaller to differentiate from parent and as it
            # only has few tabs.
            self.adjustSize()

        self.attribute_mappers = self._attr_mapper_collection

        # Exception title for editor extension exceptions
        self._ext_exc_msg = self.tr(
            'An error has occured while executing Python code in the editor '
            'extension:'
        )

        # Register custom editor extension if specified
        self._editor_ext = entity_dlg_extension(self)
        if not self._editor_ext is None:
            self._editor_ext.post_init()

            # Initialize CascadingFieldContext objects
            self._editor_ext.connect_cf_contexts()

    def _init_gui(self):
        # Setup base elements
        self.gridLayout = QGridLayout(self)
        self.gridLayout.setObjectName('glMain')
        self.gridLayout.addLayout(
            self.vlNotification, 0, 0, 1, 1
        )
        QApplication.processEvents()

        #set widgets values
        column_widget_area = self._setup_columns_content_area() 

        self.gridLayout.addWidget(
            column_widget_area, 1, 0, 1, 1
        )

        QApplication.processEvents()
        # Add notification for mandatory columns if applicable
        next_row = 2
        if self.has_mandatory:
            self.required_fields_lbl = QLabel(self)
            msg = self.tr(
                'Please fill out all required (*) fields.'
            )
            msg = self._highlight_asterisk(msg)
            self.required_fields_lbl.setText(msg)
            self.gridLayout.addWidget(
                self.required_fields_lbl, next_row, 0, 1, 2
            )
            # Bump up row reference
            next_row += 1

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setObjectName('buttonBox')
        self.gridLayout.addWidget(
            self.buttonBox, next_row, 0, 1, 1
        )

        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(
            QDialogButtonBox.Cancel|QDialogButtonBox.Save
        )

        if self.edit_model is None:
            if not self.collect_model:
                self.save_new_button = QPushButton(
                    QApplication.translate(
                        'EntityEditorDialog', 'Save and New'
                    )
                )
                self.buttonBox.addButton(
                    self.save_new_button, QDialogButtonBox.ActionRole
                )

        # edit model, collect model
        # adding new record for child

        # Saving in parent editor
        if not isinstance(self._parent._parent, EntityEditorDialog):
            # adding a new record
            if self.edit_model is None:
                # saving when digitizing.
                if self.collect_model:
                    self.buttonBox.accepted.connect(self.on_model_added)
                # saving parent editor
                else:
                    self.buttonBox.accepted.connect(self.save_parent_editor)
                    self.save_new_button.clicked.connect(self.save_and_new)
            # updating existing record
            else:
                if not self.collect_model:
                    # updating existing record of the parent editor
                    self.buttonBox.accepted.connect(self.save_parent_editor)
                else:
                    self.buttonBox.accepted.connect(self.on_model_added)
        # Saving in child editor
        else:
            # save and new record
            if self.edit_model is None:
                self.buttonBox.accepted.connect(self.on_child_saved)
                self.save_new_button.clicked.connect(
                    lambda: self.on_child_saved(True)
                )

            else:
                # When updating an existing child editor save to the db
                self.buttonBox.accepted.connect(
                    self.on_child_saved
                )
                #self.buttonBox.accepted.connect(self.submit)

        self.buttonBox.rejected.connect(self.cancel)

    @property
    def notification_bar(self):
        """
        :return: Returns the dialog's notification bar.
        :rtype: NotificationBar
        """
        return self._notifBar

    def save_parent_editor(self):
        """
        Saves the parent editor and its children.
        """
        self.submit()
        self.save_children()

    def set_parent_values(self):
        """
        Sets the parent display column for the child.
        """
        if self.parent_entity is None:
            return
        for col in self._entity.columns.values():
            if col.TYPE_INFO == 'FOREIGN_KEY':
                parent_entity = col.parent
                if parent_entity == self.parent_entity:
                    self.parent_widgets_value_setter(self._parent._parent, col)

    def parent_widgets_value_setter(self, parent, col):
        """
        Finds and sets the value from parent widget and set it to the column
        widget of a child using the child column.
        :param parent: The parent widget
        :type parent: QWidget
        :param col: The child column object
        :type col: Object
        """
        for parent_col, parent_widget in parent.column_widgets.iteritems():
            if parent_col.name == col.name:
                self.single_parent_value_setter(col, parent_widget)
                break
            if parent_col.name in col.entity_relation.display_cols:
                self.single_parent_value_setter(col, parent_widget)
                break

    def single_parent_value_setter(self, col, parent_widget):
        """
        Gets value from parent widget and set it to the column widget of a
        child using the child column.
        :param parent: The parent widget
        :type parent: QWidget
        :param col: The child column object
        :type col: Object
        """
        local_widget = self.column_widgets[col]
        local_widget.show_clear_button()
        self.filter_val = parent_widget.text()
        local_widget.setText(self.filter_val)

    def save_and_new(self):
        """
        A slot raised when Save and New button is click. It saves the form
        without showing a success message. Then it sets reload_form property
        to True so that entity_browser can re-load the form.
        """
        from stdm.ui.entity_browser import (
            EntityBrowserWithEditor
        )
        self.submit(False, True)
        self.save_children()

        if self.is_valid:
            self.addedModel.emit(self.model())
            self.setModel(self.ent_model())
            self.clear()
            self.child_models.clear()
            for index in range(0, self.entity_tab_widget.count()-1):
                if isinstance(
                        self.entity_tab_widget.widget(index),
                        EntityBrowserWithEditor
                ):
                    child_browser = self.entity_tab_widget.widget(index)
                    child_browser.remove_rows()

    def on_model_added(self):
        """
        A slot raised when a form is submitted with collect model set to True.
        There will be no success message and the form does not close.
        """
        self.submit(True)
        self.addedModel.emit(self.model())

    def closeEvent(self, event):
        '''
        Raised when a request to close the window is received.
        Check the dirty state of input controls and prompt user to
        save if dirty.
        '''

        if self.do_not_check_dirty:
            event.accept()
            return
        isDirty, userResponse = self.checkDirty()

        if isDirty:
            if userResponse == QMessageBox.Yes:
                # We need to ignore the event so that validation and
                # saving operations can be executed
                event.ignore()
                self.submit()
            elif userResponse == QMessageBox.No:
                event.accept()
            elif userResponse == QMessageBox.Cancel:
                event.ignore()
        else:
            event.accept()

    def on_child_saved(self, save_and_new=False):
        """
        A slot raised when the save or save and new button is clicked. It sets
        the child_models dictionary of the parent when saved.
        :param save_and_new: A boolean indicating the save and new button is
        clicked to trigger the slot.
        :type save_and_new: Boolean
        """
        if self.parent_entity is None:
            return

        self.submit(True)

        insert_pos = self._parent.tbEntity.model().rowCount() + 1
        # Save to parent editor so that it is persistent.
        self._parent._parent.child_models[insert_pos, self._entity] = \
            self.model()
        self.addedModel.emit(self.model())
        if not save_and_new:
            self.accept()

        else:
            if self.is_valid:
                #self.addedModel.emit(self.model())
                self.setModel(self.ent_model())

                self.clear()
                self.set_parent_values()

    def save_children(self):
        """
        Saves children models into the database by assigning the the id of the
        parent for foreign key column.
        """
        if len(self.child_models) < 1:
            return
        children_obj = []
        for row_entity, model in self.child_models.iteritems():
            row_pos = row_entity[0]
            entity = row_entity[1]
            ent_model = entity_model(entity)
            entity_obj = ent_model()
            for col in entity.columns.values():
                if col.TYPE_INFO == 'FOREIGN_KEY':
                    if col.parent.name == self._entity.name:
                        setattr(model, col.name, self.model().id)
                        children_obj.append(model)
            entity_obj.saveMany(children_obj)

    def register_column_widgets(self):
        """
        Registers the column widgets.
        """
        # Append column labels and widgets
        table_name = self._entity.name
        columns = table_column_names(table_name)
        self.scroll_widget_contents = QWidget()
        self.scroll_widget_contents.setObjectName(
            'scrollAreaWidgetContents'
        )
        for c in self._entity.columns.values():
            if c.name in self.exclude_columns:
                continue
            if not c.name in columns and not isinstance(c, VirtualColumn):
                continue
            # Get widget factory
            column_widget = ColumnWidgetRegistry.create(
                c,
                self.scroll_widget_contents,
                host=self
            )
            self.column_widgets[c] = column_widget

    def _setup_columns_content_area(self):
        # Only use this if entity supports documents
        # self.entity_tab_widget = None
        self.doc_widget = None

        self.entity_scroll_area = QScrollArea(self)
        self.entity_scroll_area.setFrameShape(QFrame.NoFrame)
        self.entity_scroll_area.setWidgetResizable(True)
        self.entity_scroll_area.setObjectName('scrollArea')

        # Grid layout for controls
        self.gl = QGridLayout(self.scroll_widget_contents)
        self.gl.setObjectName('gl_widget_contents')
    
        # Append column labels and widgets
        table_name = self._entity.name
        columns = table_column_names(table_name)
        # Iterate entity column and assert if they exist
        row_id = 0
        for c, column_widget in self.column_widgets.iteritems():
            if c.name in self.exclude_columns:
                continue
            if not c.name in columns and not isinstance(c, VirtualColumn):
                continue

            if column_widget is not None:
                header = c.ui_display()
                self.c_label = QLabel(self.scroll_widget_contents)

                # Format label text if it is a mandatory field
                if c.mandatory:
                    header = u'{0} *'.format(c.ui_display())
                    #Highlight asterisk
                    header = self._highlight_asterisk(header)

                self.c_label.setText(header)
                self.gl.addWidget(self.c_label, row_id, 0, 1, 1)

                self.column_widget = column_widget
                self.gl.addWidget(self.column_widget, row_id, 1, 1, 1)

                #Add user tip if specified for the column configuration
                if c.user_tip:
                    self.tip_lbl = UserTipLabel(user_tip=c.user_tip)
                    self.gl.addWidget(self.tip_lbl, row_id, 2, 1, 1)

                if c.mandatory and not self.has_mandatory:
                    self.has_mandatory = True

                col_name = c.name
                #Replace name accordingly based on column type
                if isinstance(c, MultipleSelectColumn):
                    col_name = c.model_attribute_name
    
                # Add widget to MapperMixin collection
                self.addMapping(
                    col_name,
                    self.column_widget,
                    c.mandatory,
                    pseudoname=c.ui_display()
                )

                # Bump up row_id
                row_id += 1
    
        self.entity_scroll_area.setWidget(self.scroll_widget_contents)

        if self.entity_tab_widget is None:
            self.entity_tab_widget = QTabWidget(self)
        # Check if there are children and add foreign key browsers

        # Add primary tab if necessary
        self._add_primary_attr_widget()

        if not self._disable_collections:
            ch_entities = self.children_entities()

            for col, ch in ch_entities.iteritems():
                if hasattr(col.entity_relation, 'show_in_parent'):
                    if col.entity_relation.show_in_parent != '0':
                        self._add_fk_browser(ch, col)
                else:
                    self._add_fk_browser(ch, col)

        #Add tab widget if entity supports documents
        if self._entity.supports_documents:
            self.doc_widget = SupportingDocumentsWidget(
                self._entity.supporting_doc,
                self._ent_document_model,
                self
            )

            # Map the source document manager object
            self.addMapping(
                'documents',
                self.doc_widget.source_document_manager
            )

            #
            # # Add attribute tab
            # self._add_primary_attr_widget()

            # Add supporting documents tab
            self.entity_tab_widget.addTab(
                self.doc_widget,
                self.tr('Supporting Documents')
            )

        # Return the correct widget
        if not self.entity_tab_widget is None:
            return self.entity_tab_widget
    
        return self.entity_scroll_area

    def _add_primary_attr_widget(self):
        # Check if the primary entity
        # exists and add if it does not
        pr_txt = self.tr('Primary')
        if not self.entity_tab_widget is None:
            tab_txt = self.entity_tab_widget.tabText(0)
            if not tab_txt == pr_txt:
                self.entity_tab_widget.addTab(
                self.entity_scroll_area,
                pr_txt
            )

    def _add_fk_browser(self, child_entity, column):
        # Create and add foreign key
        # browser to the collection
        from stdm.ui.entity_browser import (
            EntityBrowserWithEditor
        )

        attr = u'{0}_collection'.format(child_entity.name)

        # Return if the attribute does not exist
        if not hasattr(self._model, attr):
            return
        entity_browser = EntityBrowserWithEditor(
            child_entity,
            self,
            MANAGE,
            False,
            plugin=self.plugin
        )
        entity_browser.buttonBox.setVisible(False)
        entity_browser.record_filter = []

        if len(child_entity.label) > 2:
            column_label = child_entity.label
        else:
            # Split and join  to filter out entity name prefix
            # e.g. 'lo_parcel' to 'parcel'
            column_label = format_name(" ".join(child_entity.name.split("_", 1)[1:]))
        self.entity_tab_widget.addTab(
            entity_browser,
            u'{0}'.format(
                column_label
            )
        )
        self.set_filter(child_entity, entity_browser)

    def set_filter(self, entity, browser):
        col = self.filter_col(entity)
        child_model = entity_model(entity)
        child_model_obj = child_model()
        col_obj = getattr(child_model, col.name)
        if self.model() is not None:
            if self.model().id is None:
                browser.filtered_records = []
            else:
                browser.filtered_records = child_model_obj.queryObject().filter(
                    col_obj == self.model().id
                ).all()

        if self.edit_model is not None:
            browser.filtered_records = child_model_obj.queryObject().filter(
                col_obj == self.edit_model.id
            ).all()

        if self.edit_model is None and self.model() is None:
            browser.filtered_records = []

    def filter_col(self, child_entity):
        for col in child_entity.columns.values():
            if col.TYPE_INFO == 'FOREIGN_KEY':
                parent_entity = col.parent
                if parent_entity == self._entity:
                    return col


    def children_entities(self):
        """
        :return: Returns a list of children entities
        that refer to the main entity as the parent.
        :rtype: OrderedDict
        """
        child_columns = OrderedDict()
        for ch in self._entity.children():
            if ch.TYPE_INFO == Entity.TYPE_INFO:
                for col in ch.columns.values():
                    if hasattr(col, 'entity_relation'):

                        if col.parent.name == self._entity.name:
                            child_columns[col] = ch
        return child_columns

    def document_widget(self):
        """
        :return: Returns the widget for managing
        the supporting documents for an entity if enabled.
        :rtype: SupportingDocumentsWidget
        """
        return self.doc_widget

    def source_document_manager(self):
        """
        :return: Returns an instance of the
        SourceDocumentManager only if supporting
        documents are enabled for the given entity. Otherwise,
        None if supporting documents are not enabled.
        :rtype: SourceDocumentManager
        """
        if self.doc_widget is None:
            return None

        return self.doc_widget.source_document_manager

    def _highlight_asterisk(self, text):
        # Highlight asterisk in red
        c = '*'

        # Do not format if there is no asterisk
        if text.find(c) == -1:
            return text

        asterisk_highlight = '<span style=\" color:#ff0000;\">*</span>'
        text = text.replace(c, asterisk_highlight)

        return u'<html><head/><body><p>{0}</p></body></html>'.format(text)

    def _custom_validate(self):
        """
        Override of the MapperMixin which enables custom editor extensions to
        inject additional validation before saving form data.
        :return: Return True if the validation was successful,
        otherwise False.
        :rtype: bool
        """
        if not self._editor_ext is None:
            return self._editor_ext.validate()

        # Return True if there is no custom editor extension specified
        return True

    def _post_save(self, model):
        """
        Include additional post-save logic by custom extensions.
        :param model: SQLAlchemy model
        :type model: object
        """
        if not self._editor_ext is None:
            self._editor_ext.post_save(model)

    def _get_entity_editor_widgets(self):
        """
        Gets entity editor widgets and appends them to a dictionary
        """
        if self.entity_tab_widget:
            tab_count = self.entity_tab_widget.count()
            for i in range(tab_count):
                tab_object = self.entity_tab_widget.widget(i)
                tab_text = self.entity_tab_widget.tabText(i)
                self.entity_editor_widgets[tab_text] = tab_object
        else:
            self.entity_editor_widgets['no_tab'] = self.entity_scroll_area
Beispiel #36
0
class previewDlg(QMainWindow):
    '''
    classdocs
    '''
    def __init__(self, parent, comp, basePMCheck, model):
        '''
        Constructor
        '''

        QMainWindow.__init__(self, parent)

        self.basePMCheck = basePMCheck
        #         self.ui = Ui_Previewself.grbPageProperty()
        #         self.ui.setupUi(self)
        self.resize(1000, 700)
        self.setWindowTitle("Preview Dialog")
        self.view = QgsComposerView(self)
        viewLayout = QGridLayout()
        viewLayout.setSpacing(0)
        viewLayout.setMargin(0)
        mHorizontalRuler = QgsComposerRuler(QgsComposerRuler.Horizontal)
        mVerticalRuler = QgsComposerRuler(QgsComposerRuler.Vertical)
        mRulerLayoutFix = QWidget()
        mRulerLayoutFix.setAttribute(Qt.WA_NoMousePropagation)
        mRulerLayoutFix.setBackgroundRole(QPalette.Window)
        mRulerLayoutFix.setFixedSize(mVerticalRuler.rulerSize(),
                                     mHorizontalRuler.rulerSize())
        viewLayout.addWidget(mRulerLayoutFix, 0, 0)
        viewLayout.addWidget(mHorizontalRuler, 0, 1)
        viewLayout.addWidget(mVerticalRuler, 1, 0)

        self.view.setContentsMargins(0, 0, 0, 0)
        self.view.setHorizontalRuler(mHorizontalRuler)
        self.view.setVerticalRuler(mVerticalRuler)
        viewLayout.addWidget(self.view, 1, 1)

        #         self.scene = comp

        self.view.setZoomLevel(1.0)
        self.view.setComposition(comp)
        self.scene = self.view.composition()
        layout = QVBoxLayout()
        hLayout = QHBoxLayout()
        hLayout.addLayout(viewLayout)

        self.mapItem = self.scene.getComposerMapById(0)

        self.view.scale(2.8, 2.8)
        self.view.setPreviewModeEnabled(True)

        self.toolBarAction = self.addToolBar("composer action")
        self.actionMapRefresh = QAction(self)
        self.actionMapRefresh.setObjectName("actionMapRefresh")
        icon3 = QIcon("Resource/Refresh.png")
        self.actionMapRefresh.setIcon(icon3)
        self.actionMapRefresh.setToolTip("Refresh")
        # self.textItemAction.setCheckable(True)
        self.connect(self.actionMapRefresh, SIGNAL("triggered()"),
                     self.actionMapRefresh_triggered)
        self.toolBarAction.addAction(self.actionMapRefresh)

        # # self.templeteCreateAction = QAction(self)
        # # self.templeteCreateAction.setObjectName("createTempleteAction")
        # # icon4 = QIcon("Resource\\templetepointer.png")
        # # self.templeteCreateAction.setIcon(icon4)
        # # self.templeteCreateAction.setToolTip("Create Templete")
        # # self.templeteCreateAction.setCheckable(True)
        # # self.connect(self.templeteCreateAction, SIGNAL("triggered()"), self.createTempleteAction)
        # # self.toolBar.addAction(self.templeteCreateAction)
        # layout.insertWidget(0, self.toolBar)

        #         self.scene.selectedItemChanged.connect(self.selectedItemDisplay)
        self.view.selectedItemChanged.connect(self.selectedItemDisplay)

        self.view.cursorPosChanged.connect(self.cursorPosChangedEvent)
        #         self.connect(self.view, SIGNAL("selectedItemChanged(QgsComposerItem)"),self, SLOT("selectedItemDisplay(QgsComposerItem)"))
        #         self.scene.composerLabelAdded.connect(self.composerLabelAddedEvent)
        self.view.itemRemoved.connect(self.deleteItem)
        # self.connect( self.view, SIGNAL( "actionFinished()" ), self.setSelectionTool)

        #listen out for position updates from the QgsComposerView
        self.propertyWidget = QWidget(self)
        hLayout.addWidget(self.propertyWidget)
        self.propertyWidget.setObjectName("propertyWidget")
        self.propertyWidget.resize(222, 302)
        self.vLayout_3 = QVBoxLayout(self.propertyWidget)
        self.vLayout_3.setObjectName("vLayout_3")
        self.groupBox = QGroupBox(self.propertyWidget)
        self.groupBox.setObjectName("groupBox")
        self.horizontalLayout_2 = QHBoxLayout(self.groupBox)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.frame = QFrame(self.groupBox)
        self.frame.setFrameShape(QFrame.StyledPanel)
        self.frame.setFrameShadow(QFrame.Raised)
        self.frame.setObjectName("frame")
        self.verticalLayout = QVBoxLayout(self.frame)
        self.verticalLayout.setObjectName("verticalLayout")
        self.label = QLabel(self.frame)
        self.label.setObjectName("label")
        self.verticalLayout.addWidget(self.label)
        self.labelText = QPlainTextEdit(self.frame)
        self.labelText.setObjectName("labelText")
        self.verticalLayout.addWidget(self.labelText)
        self.btnLabelFont = QPushButton(self.frame)
        self.btnLabelFont.setObjectName("btnLabelFont")
        self.verticalLayout.addWidget(self.btnLabelFont)
        self.btnLabelColor = QPushButton(self.frame)
        self.btnLabelColor.setObjectName("btnLabelColor")
        self.verticalLayout.addWidget(self.btnLabelColor)
        self.frame_2 = QFrame(self.frame)
        self.frame_2.setFrameShape(QFrame.StyledPanel)
        self.frame_2.setFrameShadow(QFrame.Raised)
        self.frame_2.setObjectName("frame_2")
        self.horizontalLayout = QHBoxLayout(self.frame_2)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.label_2 = QLabel(self.frame_2)
        self.label_2.setObjectName("label_2")
        self.horizontalLayout.addWidget(self.label_2)
        self.spinLabelRotation = QSpinBox(self.frame_2)
        self.spinLabelRotation.setObjectName("spinLabelRotation")
        self.spinLabelRotation.setMinimum(-360)
        self.spinLabelRotation.setMaximum(360)
        self.horizontalLayout.addWidget(self.spinLabelRotation)
        self.verticalLayout.addWidget(self.frame_2)
        self.chbBackgroundEnable = QCheckBox(self.frame)
        self.chbBackgroundEnable.setChecked(True)
        self.chbBackgroundEnable.setObjectName("chbBackgroundEnable")
        self.verticalLayout.addWidget(self.chbBackgroundEnable)
        self.horizontalLayout_2.addWidget(self.frame)
        self.vLayout_3.addWidget(self.groupBox)

        self.resolutionFrame = QFrame(self.frame)
        self.resolutionFrame.setFrameShape(QFrame.StyledPanel)
        self.resolutionFrame.setFrameShadow(QFrame.Raised)
        self.resolutionFrame.setObjectName("resolutionFrame")
        self.horizontalLayout4 = QHBoxLayout(self.resolutionFrame)
        self.horizontalLayout4.setObjectName("horizontalLayout4")
        self.label_resolution = QLabel(self.resolutionFrame)
        self.label_resolution.setObjectName("label_resolution")
        self.label_resolution.setText("Print Resolution (dpi):")
        self.horizontalLayout4.addWidget(self.label_resolution)
        self.spinResolution = QSpinBox(self.resolutionFrame)
        self.spinResolution.setObjectName("spinResolution")
        self.spinResolution.setMinimum(0)
        self.spinResolution.setMaximum(1000)
        self.spinResolution.setValue(300)
        self.horizontalLayout4.addWidget(self.spinResolution)
        #         self.verticalLayout.addWidget(self.frame_2)
        self.vLayout_3.addWidget(self.resolutionFrame)

        self.gbTable = GroupBox(self.propertyWidget)
        self.gbTable.Caption = "Table"
        self.vLayout_3.addWidget(self.gbTable)

        self.mTableView = QTableView(self.gbTable)
        self.gbTable.Add = self.mTableView
        hHeder = self.mTableView.horizontalHeader()
        hHeder.setVisible(False)
        vHeder = self.mTableView.verticalHeader()
        vHeder.setVisible(False)
        # self.mTableView.setFixedHeight(70)
        # self.mTableView.setFixedWidth(comp.paperWidth() - 40)

        # self.stdItemModel = QStandardItemModel()
        # self.

        self.spaceItem = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                     QSizePolicy.Expanding)
        self.vLayout_3.addItem(self.spaceItem)

        self.groupBox.setTitle("Label Property")
        self.label.setText("Label Text:")
        self.btnLabelFont.setText("Label Font")
        self.btnLabelColor.setText("Label Color")
        self.label_2.setText("Label Rotation:")
        self.chbBackgroundEnable.setText("Background Enable")
        self.groupBox.setEnabled(False)
        self.connect(self.btnLabelFont, SIGNAL("clicked()"),
                     self.btnLabelFontClick)
        self.connect(self.btnLabelColor, SIGNAL("clicked()"),
                     self.btnLabelColorClick)
        self.connect(self.chbBackgroundEnable, SIGNAL("clicked()"),
                     self.chbBackgroundEnableClick)
        self.labelText.textChanged.connect(self.labelTextChanged)
        self.spinLabelRotation.valueChanged.connect(
            self.spinLabelRotationValueChanged)
        layout.addLayout(hLayout)
        #
        self.btnBack = QPushButton()
        self.btnBack.setText("back")
        footerLayout = QHBoxLayout()
        footerLayout.addWidget(self.btnBack)

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        footerLayout.addWidget(self.buttonBox)
        layout.addLayout(footerLayout)
        self.setLayout(layout)

        deleteItemKey = QShortcut(QKeySequence(Qt.Key_Delete), self)
        deleteItemKey.activated.connect(self.deleteItem)

        # self.btnBack.clicked.connect(self.back)
        self.connect(self.buttonBox, SIGNAL("accepted()"), self.acceptMethod)
        self.connect(self.buttonBox, SIGNAL("rejected()"), self.reject)
        self.btnCancel = self.buttonBox.button(QDialogButtonBox.Cancel)
        self.view.setCurrentTool(QgsComposerView.Select)

        self.btnLabelColor.setVisible(False)
        # self.btnBack.setVisible(False)
        self.chbBackgroundEnable.setVisible(False)
        #         self.view.emit(SIGNAL("actionFinished"))

        #         if self.scene.plotStyle() != QgsComposition.Preview:
        #         self.scene.setPlotStyle(QgsComposition.Preview)
        #         self.mapItem.setPreviewMode(QgsComposerMap.Render)
        #         self.mapItem.updateCachedImage()
        #         self.mapItem.setSelected(True)
        self.mComposition = comp
        self.composerMapItem = self.mComposition.composerMapItems()[0]
        self.composerMapItem.setUpdatesEnabled(True)
        self.mStdModel = model

        self.mTableView.setModel(self.mStdModel)
        self.mTableView.setSpan(0, 0, 1, 6)
        self.mTableView.setSpan(1, 0, 1, 2)
        self.mTableView.setSpan(2, 0, 2, 1)
        self.mTableView.setSpan(4, 0, 1, 2)
        self.mTableView.setSpan(5, 0, 1, 2)
        self.mTableView.setSpan(6, 0, 1, 2)

        self.mTableView.setSpan(0, 6, 1, 8)
        self.mTableView.setSpan(1, 7, 1, 4)
        self.mTableView.setSpan(1, 11, 1, 3)
        self.mTableView.setSpan(2, 7, 1, 4)
        self.mTableView.setSpan(2, 11, 1, 3)

    def acceptMethod(self):
        # self.mStdModel.setItem(0, QStandardItem("nnnnnnnn"))
        filePath = QFileDialog.getSaveFileName(
            self, "Save PDF File", QCoreApplication.applicationDirPath(),
            "pdf files(*.pdf )")
        if filePath == "":
            return
        self.mComposition.clearSelection()
        self.mComposition.setPrintResolution(self.spinResolution.value())
        resultPdf = self.mComposition.exportAsPDF(filePath)
        if resultPdf:
            message = QMessageBox.information(self, "Result",
                                              "Successful export PDF")
        else:
            message = QMessageBox.information(self, "Result",
                                              "Don't export PDF")

    def rePresent(self, comp, model):
        self.mComposition = comp
        self.mStdModel = model
        self.view.setComposition(comp)
        self.scene = self.view.composition()

    def back(self):
        self.done(2)

    def spinLabelRotationValueChanged(self, rotationValue):
        self.selectedLabelItem.setItemRotation(rotationValue)

    def cursorPosChangedEvent(self, scenePointF):
        self.scenePoint = scenePointF
#         i = 100

    def labelTextChanged(self):
        self.selectedLabelItem.beginCommand(
            "Label text changed", QgsComposerMergeCommand.ComposerLabelSetText)
        self.selectedLabelItem.blockSignals(True)
        self.selectedLabelItem.setText(self.labelText.toPlainText())
        self.selectedLabelItem.update()
        self.selectedLabelItem.blockSignals(False)
        self.selectedLabelItem.endCommand()

    def chbBackgroundEnableClick(self):
        if self.chbBackgroundEnable.isChecked():
            self.selectedLabelItem.setBackgroundEnabled(True)
            self.mapItem.updateCachedImage()
        else:
            self.selectedLabelItem.setBackgroundEnabled(False)
            self.mapItem.updateCachedImage()

    def btnLabelFontClick(self):
        dlgFont = QFontDialog(self)
        dlgFont.setCurrentFont(self.selectedLabelItem.font())
        result = dlgFont.exec_()
        if result == 1:
            self.labelFont = dlgFont.selectedFont()
        else:
            self.labelFont = QFont()

        self.selectedLabelItem.setFont(self.labelFont)

    def btnLabelColorClick(self):
        dlgColor = QColorDialog(self)
        dlgColor.setCurrentColor(self.selectedLabelItem.fontColor())
        result = dlgColor.exec_()
        if result == 1:
            self.labelColor = dlgColor.selectedColor()
            self.selectedLabelItem.setFontColor(self.labelColor)

    def createTempleteAction(self):
        if self.templeteCreateAction.isChecked() and self.basePMCheck:
            font = QFont("Arial", 13)
            font.setItalic(True)
            self.compLabel1 = QgsComposerLabel(self.scene)
            self.compLabel1.setFont(font)
            self.compLabel1.setText("South China Sea")
            self.compLabel1.setBackgroundEnabled(False)
            self.compLabel1.setItemPosition(156, 100)
            self.compLabel1.adjustSizeToText()
            self.compLabel1.setItemRotation(60)
            #             mapitem = self.scene.composerMapItems()
            #             mapitem[0].addItem(self.compLabel1)
            self.scene.addItem(self.compLabel1)

            self.compLabel2 = QgsComposerLabel(self.scene)
            self.compLabel2.setFont(font)
            self.compLabel2.setText("Straits Of Malacca")
            self.compLabel2.setBackgroundEnabled(False)
            self.compLabel2.setItemPosition(35, 100)
            self.compLabel2.adjustSizeToText()
            self.compLabel2.setItemRotation(60)
            self.scene.addItem(self.compLabel2)

            font.setItalic(False)
            self.compLabel3 = QgsComposerLabel(self.scene)
            self.compLabel3.setFont(font)
            self.compLabel3.setBackgroundEnabled(False)
            self.compLabel3.setText("THAILAND")
            self.compLabel3.setItemPosition(68, 60)
            self.compLabel3.adjustSizeToText()
            #             self.compLabel3.setItemRotation(0.5)
            self.scene.addItem(self.compLabel3)
            #             self.templeteCreateAction.setChecked(False)

            self.compLabel4 = QgsComposerLabel(self.scene)
            self.compLabel4.setFont(font)
            self.compLabel4.setBackgroundEnabled(False)
            self.compLabel4.setText("SINGAPORE")
            self.compLabel4.setItemPosition(141, 218)
            self.compLabel4.adjustSizeToText()
            #             self.compLabel3.setItemRotation(0.5)
            self.scene.addItem(self.compLabel4)
            self.templeteCreateAction.setChecked(False)
            self.compLabel4.setSelected(True)
        elif self.templeteCreateAction.isChecked(
        ) and self.basePMCheck == False:
            font = QFont("Arial", 14)
            font.setItalic(True)
            self.compLabel5 = QgsComposerLabel(self.scene)
            self.compLabel5.setFont(font)
            self.compLabel5.setText("South China Sea")
            self.compLabel5.setBackgroundEnabled(False)
            self.compLabel5.setItemPosition(108, 86)
            self.compLabel5.adjustSizeToText()
            self.compLabel5.setItemRotation(-45)
            #             mapitem = self.scene.composerMapItems()
            #             mapitem[0].addItem(self.compLabel1)
            self.scene.addItem(self.compLabel5)

            self.compLabel6 = QgsComposerLabel(self.scene)
            self.compLabel6.setFont(font)
            self.compLabel6.setText("Sulu Sea")
            self.compLabel6.setBackgroundEnabled(False)
            self.compLabel6.setItemPosition(236, 38)
            self.compLabel6.adjustSizeToText()
            self.compLabel6.setItemRotation(45)
            self.scene.addItem(self.compLabel6)

            font.setItalic(False)
            self.compLabel7 = QgsComposerLabel(self.scene)
            self.compLabel7.setFont(font)
            self.compLabel7.setBackgroundEnabled(False)
            self.compLabel7.setText("Celebes Sea")
            self.compLabel7.setItemPosition(242, 112)
            self.compLabel7.adjustSizeToText()
            self.compLabel7.setItemRotation(-45)
            #             self.compLabel3.setItemRotation(0.5)
            self.scene.addItem(self.compLabel7)
            #             self.templeteCreateAction.setChecked(False)

            self.compLabel8 = QgsComposerLabel(self.scene)
            self.compLabel8.setFont(font)
            self.compLabel8.setBackgroundEnabled(False)
            self.compLabel8.setText("INDONESIA\n(Kalimantan)")
            self.compLabel8.setItemPosition(172, 148, 32, 16)
            #             self.compLabel8.setHAlign(Qt.AlignHCenter)
            #             self.compLabel8.setVAlign(Qt.AlignVCenter)
            #             self.compLabel8.setFrameEnabled(False)
            #             self.compLabel8.setItemPosition()
            #             self.compLabel8.adjustSizeToText()
            #             self.compLabl3.setItemRotation(0.5)
            self.scene.addItem(self.compLabel8)

            self.compLabel9 = QgsComposerLabel(self.scene)
            self.compLabel9.setFont(font)
            self.compLabel9.setBackgroundEnabled(False)
            self.compLabel9.setText("BRUNEI")
            self.compLabel9.setItemPosition(136, 83)
            self.compLabel9.adjustSizeToText()
            #             self.compLabl3.setItemRotation(0.5)
            self.scene.addItem(self.compLabel9)
            self.templeteCreateAction.setChecked(False)

        pass

    def actionMapRefresh_triggered(self):

        self.view.setCurrentTool(QgsComposerView.AddRectangle)

    def setSelectionTool(self):
        self.view.deleteSelectedItems()
        font = QFont("Arial", 14)
        newLabelItem = QgsComposerLabel(self.scene)
        newLabelItem.setText("QGIS")
        newLabelItem.setFont(font)

        newLabelItem.setItemPosition(self.scenePoint.x(), self.scenePoint.y())
        newLabelItem.adjustSizeToText()

        self.scene.addItem(newLabelItem)
        #         selectItemPoint = self.scene.composerItemAt(self.scenePoint)
        newLabelItem.setSelected(True)
        self.groupBox.setEnabled(True)
        self.selectedLabelItem = newLabelItem
        #         txt = self.selectedLabelItem.text()
        #         textDoc = QTextDocument(txt)
        self.labelText.setPlainText(self.selectedLabelItem.text())
        #         self.scene.setSelectedItem(self.newLabelItem)

        self.view.setCurrentTool(QgsComposerView.Select)
        #         self.selectedLabelItem = self.view.currentTool()
        self.textItemAction.setChecked(False)

    def selectedItemDisplay(self, item):

        if self.scene.plotStyle() != QgsComposition.Preview:
            self.scene.setPlotStyle(QgsComposition.Preview)
            self.mapItem.setPreviewMode(QgsComposerMap.Render)
            self.mapItem.updateCachedImage()
        item._class_ = QgsComposerLabel
        #         selectedItems = self.scene.selectedComposerItems(True)
        #         if isinstance(item, QgsComposerItem):
        #             self.selectedLabelItem = item
        #         if isinstance(item, QGraphicsRectItem):
        #             self.selectedLabelItem = item
        if isinstance(item, QgsComposerLabel):
            self.selectedLabelItem = item
            self.groupBox.setEnabled(True)
            self.labelText.setPlainText(self.selectedLabelItem.text())
            self.spinLabelRotation.setValue(self.selectedLabelItem.rotation())
        else:
            self.groupBox.setEnabled(False)
#         print "debug"
        itemName = self.view.currentTool()
        if itemName == 5:
            item.setText("label")
        pass

    def deleteItem(self):
        self.view.deleteSelectedItems()
Beispiel #37
0
class AdvancedSearch(EntityEditorDialog):
    def __init__(self, entity, parent):

        EntityEditorDialog.__init__(self, entity, parent=parent)
        self.parent = parent

    def _init_gui(self):
        # Setup base elements
        self.gridLayout = QGridLayout(self)
        self.gridLayout.setObjectName('glMain')
        self.gridLayout.addLayout(
            self.vlNotification, 0, 0, 1, 1
        )
        QApplication.processEvents()

        column_widget_area = self._setup_columns_content_area()
        self.gridLayout.addWidget(
            column_widget_area, 1, 0, 1, 1
        )
        QApplication.processEvents()
        # Add notification for mandatory columns if applicable
        next_row = 2
        # Set title
        search_trans = self.tr('Advanced Search')
        if self._entity.label is not None:
            if self._entity.label != '':
                title_str = self._entity.label
            else:
                title_str = format_name(self._entity.short_name)
        else:
            title_str = format_name(self._entity.short_name)

        title = u'{0} {1}'.format(title_str, search_trans)
        self.do_not_check_dirty = True
        self.setWindowTitle(title)
        # if self.has_mandatory:
        #     self.required_fields_lbl = QLabel(self)
        #     msg = self.tr(
        #         'Please fill out all required (*) fields.'
        #     )
        #     msg = self._highlight_asterisk(msg)
        #     self.required_fields_lbl.setText(msg)
        #     self.gridLayout.addWidget(
        #         self.required_fields_lbl, next_row, 0, 1, 2
        #     )
        #     # Bump up row reference
        #     next_row += 1

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setObjectName('buttonBox')
        self.gridLayout.addWidget(
            self.buttonBox, next_row, 0, 1, 1
        )

        self.buttonBox.setOrientation(Qt.Horizontal)

        self.search = QPushButton(
            QApplication.translate(
                'EntityEditorDialog', 'Search'
            )
        )
        self.buttonBox.addButton(
            self.search, QDialogButtonBox.ActionRole
        )
        self.buttonBox.setStandardButtons(
            QDialogButtonBox.Cancel
        )
        self.search.clicked.connect(self.on_search)
        #
        #
        # # edit model, collect model
        # # adding new record for child
        #
        # # Saving in parent editor
        # if not isinstance(self._parent._parent, EntityEditorDialog):
        #     # adding a new record
        #     if self.edit_model is None:
        #         # saving when digitizing.
        #         if self.collect_model:
        #             self.buttonBox.accepted.connect(self.on_model_added)
        #         # saving parent editor
        #         else:
        #             self.buttonBox.accepted.connect(self.save_parent_editor)
        #             self.save_new_button.clicked.connect(self.save_and_new)
        #     # updating existing record
        #     else:
        #         if not self.collect_model:
        #             # updating existing record of the parent editor
        #             self.buttonBox.accepted.connect(self.save_parent_editor)
        #         else:
        #             self.buttonBox.accepted.connect(self.on_model_added)
        # # Saving in child editor
        # else:
        #     # save and new record
        #     if self.edit_model is None:
        #         self.buttonBox.accepted.connect(self.on_child_saved)
        #         self.save_new_button.clicked.connect(
        #             lambda: self.on_child_saved(True)
        #         )
        #
        #     else:
        #         # When updating an existing child editor save to the db
        #         self.buttonBox.accepted.connect(
        #             self.on_child_saved
        #         )
        #         #self.buttonBox.accepted.connect(self.submit)
        #
        self.buttonBox.rejected.connect(self.cancel)

    def on_search(self):
        search_data = {}
        for column in self._entity.columns.values():
            if column.name in entity_display_columns(self._entity):
                if column.name == 'id':
                    continue
                handler = self.attribute_mappers[
                    column.name].valueHandler()
                value = handler.value()
                if value != handler.default() and bool(value):
                    search_data[column.name] = value
        # self.search_db(search_data)
        result = self.search_db_raw(search_data)
        self.parent._tableModel.removeRows(0, self.parent._tableModel.rowCount())
        if result is not None:
            found = QApplication.translate('AdvancedSearch', 'records found')
            new_title = '{} - {} {}'.format(self.title, result.rowcount, found)
            if result.rowcount > 3000:
                title = QApplication.translate(
                        'AdvancedSearch',
                        'Advanced Search'
                )
                message = QApplication.translate(
                    'AdvancedSearch',
                    'The search result returned {0} records, which is above the '
                    'search result limit. <br>Would you like to see the first 3000 '
                    'records?'.format("{:,}".format(result.rowcount ))
                )

                res, chk_result = simple_dialog(self, title, message)
                if res:
                    self.setWindowTitle(new_title)
                    self.parent._initializeData(result)
                else:
                    return

            else:
                self.setWindowTitle(new_title)
                self.parent._initializeData(result)

    def search_db(self, search_data):
        ent_model_obj = self.ent_model()
        # query = ent_model_obj.queryObject()
        for attr, value in search_data.iteritems():
            ent_model_obj.queryObject().filter(
                getattr(self.ent_model(), attr) == value)

        # now we can run the query
        # print ent_model_obj.queryObject(), vars(ent_model_obj.queryObject())
        # print str(ent_model_obj.queryObject())
        results = ent_model_obj.queryObject().all()

    def search_db_raw(self, search_data):
        sql = u"SELECT * FROM {} WHERE ".format(self._entity.name)
        # query = ent_model_obj.queryObject()
        param = []
        if len(search_data) == 0:
            return None
        for attr, value in search_data.iteritems():
            if isinstance(value, (int, float)):
                param.append(u'{} = {}'.format(unicode(attr), unicode(value)))
            if isinstance(value, (unicode, str)):
                param.append(u"{} = '{}'".format(unicode(attr), unicode(value)))
        final_sql = u'{} {}'.format(sql, ' AND '.join(param))
        # sql_text = text(final_sql)
        results = fetch_with_filter(final_sql)
        # now we can run the query

        return results

    def _setup_columns_content_area(self):
        # Only use this if entity supports documents
        # self.entity_tab_widget = None
        self.doc_widget = None

        self.entity_scroll_area = QScrollArea(self)
        self.entity_scroll_area.setFrameShape(QFrame.NoFrame)
        self.entity_scroll_area.setWidgetResizable(True)
        self.entity_scroll_area.setObjectName('scrollArea')

        # Grid layout for controls
        self.gl = QGridLayout(self.scroll_widget_contents)
        self.gl.setObjectName('gl_widget_contents')

        # Append column labels and widgets
        table_name = self._entity.name
        columns = table_column_names(table_name)
        # Iterate entity column and assert if they exist
        row_id = 0
        for c, column_widget in self.column_widgets.iteritems():
            if c.name in self.exclude_columns:
                continue
            if isinstance(c, MultipleSelectColumn):
                continue
            if not c.name in columns and not isinstance(c, VirtualColumn):
                continue

            if column_widget is not None:
                header = c.ui_display()
                self.c_label = QLabel(self.scroll_widget_contents)

                self.c_label.setText(header)
                self.gl.addWidget(self.c_label, row_id, 0, 1, 1)


                if c.TYPE_INFO == 'AUTO_GENERATED':
                    column_widget.setReadOnly(False)
                    column_widget.btn_load.hide()
                self.gl.addWidget(column_widget, row_id, 1, 1, 1)

                col_name = c.name

                # Add widget to MapperMixin collection
                self.addMapping(
                    col_name,
                    column_widget,
                    c.mandatory,
                    pseudoname=c.ui_display()
                )

                # Bump up row_id
                row_id += 1

        self.entity_scroll_area.setWidget(self.scroll_widget_contents)
        if self.entity_tab_widget is None:
            self.entity_tab_widget = QTabWidget(self)
        # Check if there are children and add foreign key browsers

        # Add primary tab if necessary
        self._add_primary_attr_widget()
        # self.entity_tab_widget.setTabEnabled(0, False)  # enable/disable the tab
        # set the style sheet
        self.setStyleSheet(
            "QTabBar::tab::selected {width: 0; height: 0; margin: 0; "
            "padding: 0; border: none;} ")
        # Return the correct widget
        if self.entity_tab_widget is not None:
            return self.entity_tab_widget

        return self.entity_scroll_area

    def closeEvent(self, event):
        '''
        Raised when a request to close the window is received.
        Check the dirty state of input controls and prompt user to
        save if dirty.
        '''
        event.accept()

    def cancel(self):
        '''
        Slot for closing the dialog.
        Checks the dirty state first before closing.
        '''
        self.reject()