Example #1
0
class Login(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self)
        self.parent = parent
        self.resize(270, 160)
        self.verticalLayout = QVBoxLayout(self)
        self.label_username = QLabel(self)
        self.verticalLayout.addWidget(self.label_username)
        self.username = QLineEdit(self)
        self.verticalLayout.addWidget(self.username)
        self.label_password = QLabel(self)
        self.verticalLayout.addWidget(self.label_password)
        self.password = QLineEdit(self)
        self.password.setEchoMode(QLineEdit.Password)
        self.verticalLayout.addWidget(self.password)
        self.save_password = QCheckBox(self)
        self.verticalLayout.addWidget(self.save_password)
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        self.verticalLayout.addWidget(self.buttonBox)
        self.label_username.setBuddy(self.username)
        self.label_password.setBuddy(self.password)
        self.setWindowIcon(get_icon(MAIL_IMAGE))
        self.setWindowTitle("Gmail Login")
        self.label_username.setText("Username")
        self.label_password.setText("Password")
        self.save_password.setText("Save password")
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
Example #2
0
    def __createLayout( self ):
        " Creates the dialog layout "

        self.resize( 300, 50 )
        self.setSizeGripEnabled( True )

        # Top level layout
        layout = QVBoxLayout( self )

        gridLayout = QGridLayout()
        nameLabel = QLabel( "Name" )
        gridLayout.addWidget( nameLabel, 0, 0 )
        valueLabel = QLabel( "Value" )
        gridLayout.addWidget( valueLabel, 1, 0 )
        self.__nameEdit = QLineEdit()
        self.__nameEdit.textChanged.connect( self.__nameChanged )
        gridLayout.addWidget( self.__nameEdit, 0, 1 )
        self.__valueEdit = QLineEdit()
        self.__valueEdit.textChanged.connect( self.__valueChanged )
        gridLayout.addWidget( self.__valueEdit, 1, 1 )
        layout.addLayout( gridLayout )

        buttonBox = QDialogButtonBox( self )
        buttonBox.setOrientation( Qt.Horizontal )
        buttonBox.setStandardButtons( QDialogButtonBox.Ok |
                                      QDialogButtonBox.Cancel )
        self.__OKButton = buttonBox.button( QDialogButtonBox.Ok )
        self.__OKButton.setDefault( True )
        buttonBox.accepted.connect( self.accept )
        buttonBox.rejected.connect( self.close )
        layout.addWidget( buttonBox )
        return
Example #3
0
    def __createLayout(self):
        " Creates the dialog layout "

        self.resize(300, 50)
        self.setSizeGripEnabled(True)

        # Top level layout
        layout = QVBoxLayout(self)

        gridLayout = QGridLayout()
        nameLabel = QLabel("Name")
        gridLayout.addWidget(nameLabel, 0, 0)
        valueLabel = QLabel("Value")
        gridLayout.addWidget(valueLabel, 1, 0)
        self.__nameEdit = QLineEdit()
        self.__nameEdit.textChanged.connect(self.__nameChanged)
        gridLayout.addWidget(self.__nameEdit, 0, 1)
        self.__valueEdit = QLineEdit()
        self.__valueEdit.textChanged.connect(self.__valueChanged)
        gridLayout.addWidget(self.__valueEdit, 1, 1)
        layout.addLayout(gridLayout)

        buttonBox = QDialogButtonBox(self)
        buttonBox.setOrientation(Qt.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.Ok
                                     | QDialogButtonBox.Cancel)
        self.__OKButton = buttonBox.button(QDialogButtonBox.Ok)
        self.__OKButton.setDefault(True)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.close)
        layout.addWidget(buttonBox)
        return
Example #4
0
class Login(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self)
        self.parent = parent
        self.resize(270, 160)
        self.verticalLayout = QVBoxLayout(self)
        self.label_username = QLabel(self)
        self.verticalLayout.addWidget(self.label_username)
        self.username = QLineEdit(self)
        self.verticalLayout.addWidget(self.username)
        self.label_password = QLabel(self)
        self.verticalLayout.addWidget(self.label_password)
        self.password = QLineEdit(self)
        self.password.setEchoMode(QLineEdit.Password)
        self.verticalLayout.addWidget(self.password)
        self.save_password = QCheckBox(self)
        self.verticalLayout.addWidget(self.save_password)
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(
                QDialogButtonBox.Cancel|QDialogButtonBox.Ok)
        self.verticalLayout.addWidget(self.buttonBox)
        self.label_username.setBuddy(self.username)
        self.label_password.setBuddy(self.password)
        self.setWindowIcon(get_icon(MAIL_IMAGE))
        self.setWindowTitle("Gmail Login")
        self.label_username.setText("Username")
        self.label_password.setText("Password")
        self.save_password.setText("Save password")
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
Example #5
0
    def __createLayout( self ):
        """ Creates the dialog layout """

        self.resize( 450, 20 )
        self.setSizeGripEnabled( True )

        verticalLayout = QVBoxLayout( self )

        # Info label
        self.infoLabel = QLabel( self )
        self.infoLabel.setTextFormat( 1 )
        self.infoLabel.setText( "Profiling of the " + self.__scriptName + \
                                 " script is in progress...<br>" \
                                 "<b>Note:</b> cancelling will try to " \
                                 "kill the profiler session." )
        verticalLayout.addWidget( self.infoLabel )

        # Buttons
        buttonBox = QDialogButtonBox( self )
        buttonBox.setOrientation( Qt.Horizontal )
        buttonBox.setStandardButtons( QDialogButtonBox.Cancel )
        self.__cancelButton = buttonBox.button( QDialogButtonBox.Cancel )
        verticalLayout.addWidget( buttonBox )

        buttonBox.rejected.connect( self.__onClose )
        return
Example #6
0
    def __createLayout( self ):
        """ Creates the dialog layout """

        self.resize( 450, 20 )
        self.setSizeGripEnabled( True )

        verticalLayout = QVBoxLayout( self )

        # Info label
        self.infoLabel = QLabel( self )
        verticalLayout.addWidget( self.infoLabel )

        # Progress bar
        self.progressBar = QProgressBar( self )
        self.progressBar.setValue( 0 )
        self.progressBar.setOrientation( Qt.Horizontal )
        verticalLayout.addWidget( self.progressBar )

        # Buttons
        buttonBox = QDialogButtonBox( self )
        buttonBox.setOrientation( Qt.Horizontal )
        buttonBox.setStandardButtons( QDialogButtonBox.Close )
        verticalLayout.addWidget( buttonBox )

        buttonBox.rejected.connect( self.__onClose )
        return
Example #7
0
    def __init__(self, password, parent=None):
        super(AuthenDlg, self).__init__(parent)
        self.setWindowTitle('Authentication')
        self.password = password
        layout = QGridLayout(self)

        desc = QLabel()
        if self.password != "":#authentication is required only once Once it is correct
            desc.setText("Caution! your action will be recorded on the logbook\n \
Click OK if you want to continue, otherwise click Cancel")
        else: 
            desc.setText("Your action will be recorded on the logbook\n \
Please enter your password if you want to continue\n \
Otherwise Click Cancel \n")       
            self.passWdLineEdit = QLineEdit()
            self.passWdLineEdit.setEchoMode(QLineEdit.Password)
            vbox = QVBoxLayout()
            vbox.addWidget(self.passWdLineEdit)
            vbox.addStretch(1)    
            QObject.connect(self.passWdLineEdit, SIGNAL(_fromUtf8("textChanged(QString)")), 
                        self.getPassWd)
            layout.addWidget(self.passWdLineEdit,1,0,1,1)
        
        buttonBox = QDialogButtonBox()
        buttonBox.setOrientation(Qt.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        QObject.connect(buttonBox, SIGNAL("rejected()"), self.reject)
        QObject.connect(buttonBox, SIGNAL("accepted()"), self.accept)
        
        layout.addWidget(desc,0,0,1,1)
        layout.addWidget(buttonBox,2,0,1,1)
        self.setLayout(layout)
Example #8
0
    def __createLayout( self, pathsToAdd ):
        " Creates the dialog layout "

        self.resize( 640, 480 )
        self.setSizeGripEnabled( True )

        vboxLayout = QVBoxLayout( self )

        # Paths to add part
        vboxLayout.addWidget( QLabel( "Paths to add (total: " +
                                              str( len( pathsToAdd ) ) + ")" ) )

        self.__pathToAddView = QTreeWidget()
        self.__configTable( self.__pathToAddView )

        self.__pathToAddHeader = QTreeWidgetItem( [ "", "Path" ] )
        self.__pathToAddView.setHeaderItem( self.__pathToAddHeader )
        self.__pathToAddView.header().setSortIndicator( PATH_COL,
                                                        Qt.AscendingOrder )
        self.__pathToAddView.itemChanged.connect( self.__onAddPathChanged )
        vboxLayout.addWidget( self.__pathToAddView )

        # Buttons at the bottom
        buttonBox = QDialogButtonBox( self )
        buttonBox.setOrientation( Qt.Horizontal )
        buttonBox.setStandardButtons( QDialogButtonBox.Ok |
                                      QDialogButtonBox.Cancel )
        self.__OKButton = buttonBox.button( QDialogButtonBox.Ok )
        self.__OKButton.setText( "Add" )
        buttonBox.button( QDialogButtonBox.Cancel ).setDefault( True )
        buttonBox.accepted.connect( self.userAccept )
        buttonBox.rejected.connect( self.close )
        vboxLayout.addWidget( buttonBox )
        return
Example #9
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"))
Example #10
0
class SimpleRichTypesDialog(QDialog):
    """Simple dialog to display and change RichTypes"""

    def __init__(self, parent=None, windowTitle='', scrolling=True, text=''):
        QDialog.__init__(self, parent)
        self.mainLayout = QVBoxLayout(self)
        self.textLabel = QLabel(self)
        self.textLabel.setText(text)
        self.mainLayout.addWidget(self.textLabel)
        if scrolling:
            self.scrollArea = QScrollArea(self)
            self.mainLayout.addWidget(self.scrollArea)
            self.richTypesWidget = RichTypesWidget(self.scrollArea)
            self.scrollArea.setWidget(self.richTypesWidget)
            self.scrollArea.setWidgetResizable(False)
        else:
            self.richTypesWidget = RichTypesWidget(self)
            self.mainLayout.addWidget(self.richTypesWidget)
        self.buttonBox =  QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.NoButton | QDialogButtonBox.Ok)
        self.mainLayout.addWidget(self.buttonBox)
        QObject.connect(self.buttonBox, SIGNAL('accepted()'), self.accept)
        QObject.connect(self.buttonBox, SIGNAL('rejected()'), self.reject)
        self.setWindowTitle(windowTitle)
        self.result = None

    def addRichTypes(self, l):
        """set the list of richtypes"""
        self.richTypesWidget.addRichTypes(l)

    def accept(self):
        """after dialog closes, RichType list is available as self.result"""
        self.result = self.richTypesWidget.applyChanges()
        QDialog.accept(self)
Example #11
0
    def __createLayout(self, pathsToAdd):
        " Creates the dialog layout "

        self.resize(640, 480)
        self.setSizeGripEnabled(True)

        vboxLayout = QVBoxLayout(self)

        # Paths to add part
        vboxLayout.addWidget(
            QLabel("Paths to add (total: " + str(len(pathsToAdd)) + ")"))

        self.__pathToAddView = QTreeWidget()
        self.__configTable(self.__pathToAddView)

        self.__pathToAddHeader = QTreeWidgetItem(["", "Path"])
        self.__pathToAddView.setHeaderItem(self.__pathToAddHeader)
        self.__pathToAddView.header().setSortIndicator(PATH_COL,
                                                       Qt.AscendingOrder)
        self.__pathToAddView.itemChanged.connect(self.__onAddPathChanged)
        vboxLayout.addWidget(self.__pathToAddView)

        # Buttons at the bottom
        buttonBox = QDialogButtonBox(self)
        buttonBox.setOrientation(Qt.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.Ok
                                     | QDialogButtonBox.Cancel)
        self.__OKButton = buttonBox.button(QDialogButtonBox.Ok)
        self.__OKButton.setText("Add")
        buttonBox.button(QDialogButtonBox.Cancel).setDefault(True)
        buttonBox.accepted.connect(self.userAccept)
        buttonBox.rejected.connect(self.close)
        vboxLayout.addWidget(buttonBox)
        return
Example #12
0
    def __createLayout(self):
        """ Creates the dialog layout """

        self.resize(450, 20)
        self.setSizeGripEnabled(True)

        verticalLayout = QVBoxLayout(self)

        # Info label
        self.infoLabel = QLabel(self)
        self.infoLabel.setTextFormat(1)
        self.infoLabel.setText( "Profiling of the " + self.__scriptName + \
                                 " script is in progress...<br>" \
                                 "<b>Note:</b> cancelling will try to " \
                                 "kill the profiler session." )
        verticalLayout.addWidget(self.infoLabel)

        # Buttons
        buttonBox = QDialogButtonBox(self)
        buttonBox.setOrientation(Qt.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.Cancel)
        self.__cancelButton = buttonBox.button(QDialogButtonBox.Cancel)
        verticalLayout.addWidget(buttonBox)

        buttonBox.rejected.connect(self.__onClose)
        return
Example #13
0
class NewProjectDirDialog( QDialog, object ):
    " New project directory dialog "

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

        self.__dirnameEdit = None
        self.__buttonBox = None
        self.__createLayout()

        self.okButton = self.__buttonBox.button( QDialogButtonBox.Ok )
        self.okButton.setEnabled( False )
        return

    def __createLayout( self ):
        " Creates the dialog layout "

        self.resize( 400, 100 )
        self.setWindowTitle( "Create subdirectory" )
        vboxlayout = QVBoxLayout( self )

        inputLabel = QLabel( self )
        inputLabel.setText( "Type new subdirectory name" )
        vboxlayout.addWidget( inputLabel )

        self.__dirnameEdit = QLineEdit( self )
        self.__dirnameEdit.setToolTip( "Subdirectory name without "
                                       "path separators" )
        self.__dirnameEdit.installEventFilter( self )
        self.__dirnameEdit.textEdited.connect( self.__onTextChanged )
        vboxlayout.addWidget( self.__dirnameEdit )

        self.__buttonBox = QDialogButtonBox( self )
        self.__buttonBox.setOrientation( Qt.Horizontal )
        self.__buttonBox.setStandardButtons( QDialogButtonBox.Cancel |
                                             QDialogButtonBox.Ok )
        vboxlayout.addWidget( self.__buttonBox )

        self.__buttonBox.accepted.connect( self.accept )
        self.__buttonBox.rejected.connect( self.reject )
        return

    def __onTextChanged( self, text ):
        " Triggered when the input text has been changed "
        self.okButton.setEnabled( text != "" )
        return

    def getDirName( self ):
        " Provides the user input "
        return self.__dirnameEdit.text()

    def eventFilter( self, obj, event ):
        " Event filter for the project name field "

        # Do not allow path separators
        if event.type() == QEvent.KeyPress:
            if event.key() == ord( os.path.sep ):
                return True
        return QObject.eventFilter( self, obj, event )
Example #14
0
class NewProjectDirDialog(QDialog, object):
    " New project directory dialog "

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

        self.__dirnameEdit = None
        self.__buttonBox = None
        self.__createLayout()

        self.okButton = self.__buttonBox.button(QDialogButtonBox.Ok)
        self.okButton.setEnabled(False)
        return

    def __createLayout(self):
        " Creates the dialog layout "

        self.resize(400, 100)
        self.setWindowTitle("Create subdirectory")
        vboxlayout = QVBoxLayout(self)

        inputLabel = QLabel(self)
        inputLabel.setText("Type new subdirectory name")
        vboxlayout.addWidget(inputLabel)

        self.__dirnameEdit = QLineEdit(self)
        self.__dirnameEdit.setToolTip("Subdirectory name without "
                                      "path separators")
        self.__dirnameEdit.installEventFilter(self)
        self.__dirnameEdit.textEdited.connect(self.__onTextChanged)
        vboxlayout.addWidget(self.__dirnameEdit)

        self.__buttonBox = QDialogButtonBox(self)
        self.__buttonBox.setOrientation(Qt.Horizontal)
        self.__buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                            | QDialogButtonBox.Ok)
        vboxlayout.addWidget(self.__buttonBox)

        self.__buttonBox.accepted.connect(self.accept)
        self.__buttonBox.rejected.connect(self.reject)
        return

    def __onTextChanged(self, text):
        " Triggered when the input text has been changed "
        self.okButton.setEnabled(text != "")
        return

    def getDirName(self):
        " Provides the user input "
        return self.__dirnameEdit.text()

    def eventFilter(self, obj, event):
        " Event filter for the project name field "

        # Do not allow path separators
        if event.type() == QEvent.KeyPress:
            if event.key() == ord(os.path.sep):
                return True
        return QObject.eventFilter(self, obj, event)
Example #15
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)
Example #16
0
    def __createLayout( self, bpoint ):
        """ Creates the dialog layout """

        self.resize( 400, 150 )
        self.setSizeGripEnabled( True )

        # Top level layout
        layout = QVBoxLayout( self )

        gridLayout = QGridLayout()
        fileLabel = QLabel( "File name:" )
        gridLayout.addWidget( fileLabel, 0, 0 )
        fileValue = QLabel( bpoint.getAbsoluteFileName() )
        gridLayout.addWidget( fileValue, 0, 1 )
        lineLabel = QLabel( "Line:" )
        gridLayout.addWidget( lineLabel, 1, 0 )
        lineValue = QLabel( str( bpoint.getLineNumber() ) )
        gridLayout.addWidget( lineValue, 1, 1 )
        conditionLabel = QLabel( "Condition:" )
        gridLayout.addWidget( conditionLabel, 2, 0 )
        self.__conditionValue = CDMComboBox( True )
        self.__conditionValue.lineEdit().setText( bpoint.getCondition() )
        gridLayout.addWidget( self.__conditionValue, 2, 1 )
        ignoreLabel = QLabel( "Ignore count:" )
        gridLayout.addWidget( ignoreLabel, 3, 0 )
        self.__ignoreValue = QSpinBox()
        self.__ignoreValue.setMinimum( 0 )
        self.__ignoreValue.setValue( bpoint.getIgnoreCount() )
        gridLayout.addWidget( self.__ignoreValue, 3, 1 )
        layout.addLayout( gridLayout )

        # Checkboxes part
        self.__tempCheckbox = QCheckBox( "&Temporary" )
        self.__tempCheckbox.setChecked( bpoint.isTemporary() )
        layout.addWidget( self.__tempCheckbox )
        self.__enabled = QCheckBox( "&Enabled" )
        self.__enabled.setChecked( bpoint.isEnabled() )
        layout.addWidget( self.__enabled )

        # Buttons at the bottom
        buttonBox = QDialogButtonBox( self )
        buttonBox.setOrientation( Qt.Horizontal )
        buttonBox.setStandardButtons( QDialogButtonBox.Ok |
                                      QDialogButtonBox.Cancel )
        self.__OKButton = buttonBox.button( QDialogButtonBox.Ok )
        self.__OKButton.setDefault( True )
        buttonBox.accepted.connect( self.accept )
        buttonBox.rejected.connect( self.close )
        layout.addWidget( buttonBox )

        self.__conditionValue.setFocus()
        return
Example #17
0
class AboutBox(QDialog):
    def __init__(self, parent, app):
        flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint | Qt.MSWindowsFixedSizeDialogHint
        QDialog.__init__(self, parent, flags)
        self.app = app
        self._setupUi()

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

    def _setupUi(self):
        self.setWindowTitle(
            tr("About {}").format(
                QCoreApplication.instance().applicationName()))
        self.resize(400, 190)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        self.horizontalLayout = QHBoxLayout(self)
        self.logoLabel = QLabel(self)
        self.logoLabel.setPixmap(QPixmap(':/%s_big' % self.app.LOGO_NAME))
        self.horizontalLayout.addWidget(self.logoLabel)
        self.verticalLayout = QVBoxLayout()
        self.nameLabel = QLabel(self)
        font = QFont()
        font.setWeight(75)
        font.setBold(True)
        self.nameLabel.setFont(font)
        self.nameLabel.setText(QCoreApplication.instance().applicationName())
        self.verticalLayout.addWidget(self.nameLabel)
        self.versionLabel = QLabel(self)
        self.versionLabel.setText(
            tr("Version {}").format(
                QCoreApplication.instance().applicationVersion()))
        self.verticalLayout.addWidget(self.versionLabel)
        self.label_3 = QLabel(self)
        self.verticalLayout.addWidget(self.label_3)
        self.label_3.setText(tr("Copyright Hardcoded Software 2014"))
        self.label = QLabel(self)
        font = QFont()
        font.setWeight(75)
        font.setBold(True)
        self.label.setFont(font)
        self.verticalLayout.addWidget(self.label)
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Ok)
        self.verticalLayout.addWidget(self.buttonBox)
        self.horizontalLayout.addLayout(self.verticalLayout)
Example #18
0
    def __createLayout( self, paths, ignoredPaths ):
        " Creates the dialog layout "

        self.resize( 640, 420 )
        self.setSizeGripEnabled( True )

        vboxLayout = QVBoxLayout( self )

        # Paths to commit part
        vboxLayout.addWidget( QLabel( "Paths (total: " +
                              str( len( paths ) ) + ")" ) )

        self.__pathView = QTreeWidget()
        self.__pathView.setAlternatingRowColors( True )
        self.__pathView.setRootIsDecorated( False )
        self.__pathView.setItemsExpandable( False )
        self.__pathView.setSortingEnabled( True )
        self.__pathView.setItemDelegate( NoOutlineHeightDelegate( 4 ) )
        self.__pathView.setUniformRowHeights( True )

        self.__pathHeader = QTreeWidgetItem( [ "", "Path", "Status", "Message" ] )
        self.__pathView.setHeaderItem( self.__pathHeader )
        self.__pathView.header().setSortIndicator( 1, Qt.AscendingOrder )
        vboxLayout.addWidget( self.__pathView )

        # Paths to ignore part
        vboxLayout.addWidget( QLabel( "Ignored paths (total: " +
                              str( len( ignoredPaths ) ) + ")" ) )

        self.__ignoredPathView = QTreeWidget()
        self.__ignoredPathView.setAlternatingRowColors( True )
        self.__ignoredPathView.setRootIsDecorated( False )
        self.__ignoredPathView.setItemsExpandable( False )
        self.__ignoredPathView.setSortingEnabled( True )
        self.__ignoredPathView.setItemDelegate( NoOutlineHeightDelegate( 4 ) )
        self.__ignoredPathView.setUniformRowHeights( True )

        pathToIgnoreHeader = QTreeWidgetItem( [ "Path", "Status" ] )
        self.__ignoredPathView.setHeaderItem( pathToIgnoreHeader )
        self.__ignoredPathView.header().setSortIndicator( 0, Qt.AscendingOrder )
        vboxLayout.addWidget( self.__ignoredPathView )

        # Buttons at the bottom
        buttonBox = QDialogButtonBox( self )
        buttonBox.setOrientation( Qt.Horizontal )
        buttonBox.setStandardButtons( QDialogButtonBox.Ok )
        buttonBox.button( QDialogButtonBox.Ok ).setDefault( True )
        buttonBox.accepted.connect( self.accept )
        vboxLayout.addWidget( buttonBox )
        return
Example #19
0
    def __createLayout(self, paths, ignoredPaths):
        " Creates the dialog layout "

        self.resize(640, 420)
        self.setSizeGripEnabled(True)

        vboxLayout = QVBoxLayout(self)

        # Paths to commit part
        vboxLayout.addWidget(QLabel("Paths (total: " + str(len(paths)) + ")"))

        self.__pathView = QTreeWidget()
        self.__pathView.setAlternatingRowColors(True)
        self.__pathView.setRootIsDecorated(False)
        self.__pathView.setItemsExpandable(False)
        self.__pathView.setSortingEnabled(True)
        self.__pathView.setItemDelegate(NoOutlineHeightDelegate(4))
        self.__pathView.setUniformRowHeights(True)

        self.__pathHeader = QTreeWidgetItem(["", "Path", "Status", "Message"])
        self.__pathView.setHeaderItem(self.__pathHeader)
        self.__pathView.header().setSortIndicator(1, Qt.AscendingOrder)
        vboxLayout.addWidget(self.__pathView)

        # Paths to ignore part
        vboxLayout.addWidget(
            QLabel("Ignored paths (total: " + str(len(ignoredPaths)) + ")"))

        self.__ignoredPathView = QTreeWidget()
        self.__ignoredPathView.setAlternatingRowColors(True)
        self.__ignoredPathView.setRootIsDecorated(False)
        self.__ignoredPathView.setItemsExpandable(False)
        self.__ignoredPathView.setSortingEnabled(True)
        self.__ignoredPathView.setItemDelegate(NoOutlineHeightDelegate(4))
        self.__ignoredPathView.setUniformRowHeights(True)

        pathToIgnoreHeader = QTreeWidgetItem(["Path", "Status"])
        self.__ignoredPathView.setHeaderItem(pathToIgnoreHeader)
        self.__ignoredPathView.header().setSortIndicator(0, Qt.AscendingOrder)
        vboxLayout.addWidget(self.__ignoredPathView)

        # Buttons at the bottom
        buttonBox = QDialogButtonBox(self)
        buttonBox.setOrientation(Qt.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.Ok)
        buttonBox.button(QDialogButtonBox.Ok).setDefault(True)
        buttonBox.accepted.connect(self.accept)
        vboxLayout.addWidget(buttonBox)
        return
Example #20
0
    def __createLayout( self ):
        """ Creates the dialog layout """

        self.resize( 400, 100 )
        self.setSizeGripEnabled( True )

        verticalLayout = QVBoxLayout( self )

        # Check boxes
        self.includeClassesBox = QCheckBox( self )
        self.includeClassesBox.setText( "Show &classes in modules" )
        self.includeClassesBox.setChecked( self.options.includeClasses )
        self.includeClassesBox.stateChanged.connect( self.__updateOptions )
        self.includeFuncsBox = QCheckBox( self )
        self.includeFuncsBox.setText( "Show &functions in modules" )
        self.includeFuncsBox.setChecked( self.options.includeFuncs )
        self.includeFuncsBox.stateChanged.connect( self.__updateOptions )
        self.includeGlobsBox = QCheckBox( self )
        self.includeGlobsBox.setText( "Show &global variables in modules" )
        self.includeGlobsBox.setChecked( self.options.includeGlobs )
        self.includeGlobsBox.stateChanged.connect( self.__updateOptions )
        self.includeDocsBox = QCheckBox( self )
        self.includeDocsBox.setText( "Show modules &docstrings" )
        self.includeDocsBox.setChecked( self.options.includeDocs )
        self.includeDocsBox.stateChanged.connect( self.__updateOptions )
        self.includeConnTextBox = QCheckBox( self )
        self.includeConnTextBox.setText( "Show connection &labels" )
        self.includeConnTextBox.setChecked( self.options.includeConnText )
        self.includeConnTextBox.stateChanged.connect( self.__updateOptions )

        verticalLayout.addWidget( self.includeClassesBox )
        verticalLayout.addWidget( self.includeFuncsBox )
        verticalLayout.addWidget( self.includeGlobsBox )
        verticalLayout.addWidget( self.includeDocsBox )
        verticalLayout.addWidget( self.includeConnTextBox )

        # Buttons at the bottom
        buttonBox = QDialogButtonBox( self )
        buttonBox.setOrientation( Qt.Horizontal )
        buttonBox.setStandardButtons( QDialogButtonBox.Cancel )
        generateButton = buttonBox.addButton( "Generate",
                                              QDialogButtonBox.ActionRole )
        generateButton.setDefault( True )
        generateButton.clicked.connect( self.accept )
        verticalLayout.addWidget( buttonBox )

        buttonBox.rejected.connect( self.close )
        return
Example #21
0
    def __createLayout(self):
        " Creates the dialog layout "
        self.resize(450, 20)
        self.setSizeGripEnabled(True)

        verticalLayout = QVBoxLayout(self)
        self.__infoLabel = QLabel("Getting status of '" + self.__path + "'...")
        verticalLayout.addWidget(self.__infoLabel)

        buttonBox = QDialogButtonBox(self)
        buttonBox.setOrientation(Qt.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.Close)
        verticalLayout.addWidget(buttonBox)

        buttonBox.rejected.connect(self.__onClose)
        return
Example #22
0
    def __createLayout( self ):
        " Creates the dialog layout "
        self.resize( 450, 20 )
        self.setSizeGripEnabled( True )

        verticalLayout = QVBoxLayout( self )
        self.__infoLabel = QLabel( "Annotating '" + self.__path + "'..." )
        verticalLayout.addWidget( self.__infoLabel )

        buttonBox = QDialogButtonBox( self )
        buttonBox.setOrientation( Qt.Horizontal )
        buttonBox.setStandardButtons( QDialogButtonBox.Close )
        verticalLayout.addWidget( buttonBox )

        buttonBox.rejected.connect( self.__onClose )
        return
Example #23
0
class AboutBox(QDialog):
    def __init__(self, parent, app):
        flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint | Qt.MSWindowsFixedSizeDialogHint
        QDialog.__init__(self, parent, flags)
        self.app = app
        self._setupUi()
        
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
    
    def _setupUi(self):
        self.setWindowTitle(tr("About {}").format(QCoreApplication.instance().applicationName()))
        self.resize(400, 190)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        self.horizontalLayout = QHBoxLayout(self)
        self.logoLabel = QLabel(self)
        self.logoLabel.setPixmap(QPixmap(':/%s_big' % self.app.LOGO_NAME))
        self.horizontalLayout.addWidget(self.logoLabel)
        self.verticalLayout = QVBoxLayout()
        self.nameLabel = QLabel(self)
        font = QFont()
        font.setWeight(75)
        font.setBold(True)
        self.nameLabel.setFont(font)
        self.nameLabel.setText(QCoreApplication.instance().applicationName())
        self.verticalLayout.addWidget(self.nameLabel)
        self.versionLabel = QLabel(self)
        self.versionLabel.setText(tr("Version {}").format(QCoreApplication.instance().applicationVersion()))
        self.verticalLayout.addWidget(self.versionLabel)
        self.label_3 = QLabel(self)
        self.verticalLayout.addWidget(self.label_3)
        self.label_3.setText(tr("Copyright Hardcoded Software 2014"))
        self.label = QLabel(self)
        font = QFont()
        font.setWeight(75)
        font.setBold(True)
        self.label.setFont(font)
        self.verticalLayout.addWidget(self.label)
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Ok)
        self.verticalLayout.addWidget(self.buttonBox)
        self.horizontalLayout.addLayout(self.verticalLayout)
Example #24
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..."))
Example #25
0
    def __createLayout( self, fileName, info ):
        """ Creates the dialog layout """

        self.resize( 600, 220 )
        self.setSizeGripEnabled( True )

        verticalLayout = QVBoxLayout( self )

        # Info label
        infoLabel = FitLabel( self )
        sizePolicy = QSizePolicy( QSizePolicy.Minimum, QSizePolicy.Preferred )
        sizePolicy.setHorizontalStretch( 0 )
        sizePolicy.setVerticalStretch( 0 )
        sizePolicy.setHeightForWidth(infoLabel.sizePolicy().hasHeightForWidth())
        infoLabel.setSizePolicy( sizePolicy )
        infoLabel.setText( "Lexer/parser errors for " + fileName )
        verticalLayout.addWidget( infoLabel )

        # Result window
        resultEdit = QTextEdit( self )
        resultEdit.setTabChangesFocus( False )
        resultEdit.setAcceptRichText( False )
        resultEdit.setReadOnly( True )
        resultEdit.setFontFamily( GlobalData().skin.baseMonoFontFace )
        if info is not None:
            modInfo = info
        else:
            modInfo = GlobalData().briefModinfoCache.get( fileName )
        if modInfo.isOK:
            resultEdit.setText( "No errors found" )
        else:
            resultEdit.setText( "\n".join( modInfo.lexerErrors +
                                           modInfo.errors ) )
        verticalLayout.addWidget( resultEdit )

        # Buttons
        buttonBox = QDialogButtonBox( self )
        buttonBox.setOrientation( Qt.Horizontal )
        buttonBox.setStandardButtons( QDialogButtonBox.Close )
        verticalLayout.addWidget( buttonBox )

        buttonBox.rejected.connect( self.close )
        return
Example #26
0
    def __createLayout(self, fileName, info):
        """ Creates the dialog layout """

        self.resize(600, 220)
        self.setSizeGripEnabled(True)

        verticalLayout = QVBoxLayout(self)

        # Info label
        infoLabel = FitLabel(self)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            infoLabel.sizePolicy().hasHeightForWidth())
        infoLabel.setSizePolicy(sizePolicy)
        infoLabel.setText("Lexer/parser errors for " + fileName)
        verticalLayout.addWidget(infoLabel)

        # Result window
        resultEdit = QTextEdit(self)
        resultEdit.setTabChangesFocus(False)
        resultEdit.setAcceptRichText(False)
        resultEdit.setReadOnly(True)
        resultEdit.setFontFamily(GlobalData().skin.baseMonoFontFace)
        if info is not None:
            modInfo = info
        else:
            modInfo = GlobalData().briefModinfoCache.get(fileName)
        if modInfo.isOK:
            resultEdit.setText("No errors found")
        else:
            resultEdit.setText("\n".join(modInfo.lexerErrors + modInfo.errors))
        verticalLayout.addWidget(resultEdit)

        # Buttons
        buttonBox = QDialogButtonBox(self)
        buttonBox.setOrientation(Qt.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.Close)
        verticalLayout.addWidget(buttonBox)

        buttonBox.rejected.connect(self.close)
        return
Example #27
0
    def __createLayout( self ):
        " Creates the dialog layout "
        self.resize( 640, 480 )
        self.setSizeGripEnabled( True )

        vboxLayout = QVBoxLayout( self )
        hboxLayout = QHBoxLayout()
        iconLabel = QLabel()
        iconLabel.setPixmap( PixmapCache().getPixmap( "logo-48x48.png" ) )
        iconLabel.setScaledContents( False )
        hboxLayout.addWidget( iconLabel )
        versionLabel = QLabel( "<b>Codimension IDE version " +
                               str( GlobalData().version ) + "<br>"
                               "CML version " +
                               str( CMLVersion.VERSION ) +
                               "</b><p>Copyright (c) Sergey Satskiy 2010-2016</p>" )
        versionLabel.setSizePolicy( QSizePolicy.Expanding,
                                    QSizePolicy.Expanding )
        versionLabel.setFixedHeight( versionLabel.minimumSizeHint().height() )
        versionLabel.setAlignment( Qt.AlignCenter )
        hboxLayout.addWidget( versionLabel )
        vboxLayout.addLayout( hboxLayout )

        tabWidget = QTabWidget( self )
        tabWidget.setFocusPolicy( Qt.NoFocus )

        description = self.__createDescription()
        tabWidget.addTab( description, "About" )
        versioning = self.__createVersioning()
        tabWidget.addTab( versioning, "Versions and licenses" )
        authors = self.__createAuthors()
        tabWidget.addTab( authors, "Contributors" )
        vboxLayout.addWidget( tabWidget )

        # Button at the bottom
        buttonBox = QDialogButtonBox( self )
        buttonBox.setOrientation( Qt.Horizontal )
        buttonBox.setStandardButtons( QDialogButtonBox.Ok )
        buttonBox.accepted.connect( self.close )
        buttonBox.rejected.connect( self.close )
        vboxLayout.addWidget( buttonBox )
        return
    def __init__(self, eventIDs, parent=None):
        super(ShowSelectRefDlg, self).__init__(parent)
        self.setWindowTitle('Select reference snapshot')
        self.eventIDs = eventIDs
        self.refSnapshot = ""
        #print(self.eventIDs)

        desc = QLabel()
        desc.setText("%d snapshots with IDs %s to be compared.\n\n\
Please select one as the reference snapshot\n\n" % (len(eventIDs), eventIDs))
        gBox = QGroupBox("Reference Snapshot Selection")

        self.radio = [0] * len(eventIDs)
        vbox = QVBoxLayout()
        for i in range(len(eventIDs)):
            self.radio[i] = QRadioButton("Snapshot ID: %s" % eventIDs[i])
            self.radio[i].setChecked(False)
            vbox.addWidget(self.radio[i])
            self.radio[i].clicked.connect(self.reorderEventIDs)
        vbox.addStretch(1)
        gBox.setLayout(vbox)

        #okButton = QPushButton("OK")
        #cancelButton = QPushButton("Cancle")
        #okButton.clicked.connect(self.returnOrderedIDs)
        #okButton.clicked.connect(self.ignore)

        buttonBox = QDialogButtonBox()
        buttonBox.setOrientation(Qt.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.Ok
                                     | QDialogButtonBox.Cancel)
        QObject.connect(buttonBox, SIGNAL("rejected()"), self.reject)
        QObject.connect(buttonBox, SIGNAL("accepted()"), self.accept)

        layout = QGridLayout(self)
        layout.addWidget(desc, 0, 0, 1, 1)
        layout.addWidget(gBox, 1, 0, 1, 1)
        #layout.addWidget(okButton,2,0,1,1)
        #layout.addWidget(cancelButton,2,1,1,1)
        layout.addWidget(buttonBox, 2, 0, 1, 1)
        self.setLayout(layout)
Example #29
0
    def __createLayout(self):
        " Creates the dialog layout "
        self.resize(640, 480)
        self.setSizeGripEnabled(True)

        vboxLayout = QVBoxLayout(self)
        hboxLayout = QHBoxLayout()
        iconLabel = QLabel()
        iconLabel.setPixmap(PixmapCache().getPixmap("logo-48x48.png"))
        iconLabel.setScaledContents(False)
        hboxLayout.addWidget(iconLabel)
        versionLabel = QLabel(
            "<b>Codimension IDE version " + str(GlobalData().version) + "<br>"
            "CML version " + str(CMLVersion.VERSION) +
            "</b><p>Copyright (c) Sergey Satskiy 2010-2016</p>")
        versionLabel.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        versionLabel.setFixedHeight(versionLabel.minimumSizeHint().height())
        versionLabel.setAlignment(Qt.AlignCenter)
        hboxLayout.addWidget(versionLabel)
        vboxLayout.addLayout(hboxLayout)

        tabWidget = QTabWidget(self)
        tabWidget.setFocusPolicy(Qt.NoFocus)

        description = self.__createDescription()
        tabWidget.addTab(description, "About")
        versioning = self.__createVersioning()
        tabWidget.addTab(versioning, "Versions and licenses")
        authors = self.__createAuthors()
        tabWidget.addTab(authors, "Contributors")
        vboxLayout.addWidget(tabWidget)

        # Button at the bottom
        buttonBox = QDialogButtonBox(self)
        buttonBox.setOrientation(Qt.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.Ok)
        buttonBox.accepted.connect(self.close)
        buttonBox.rejected.connect(self.close)
        vboxLayout.addWidget(buttonBox)
        return
Example #30
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..."))
Example #31
0
    def __createLayout(self):
        """ Creates the dialog layout """

        self.resize(450, 150)
        self.setSizeGripEnabled(True)

        verticalLayout = QVBoxLayout(self)

        whereGroupbox = QGroupBox(self)
        whereGroupbox.setTitle("Garbage collector message destination")
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            whereGroupbox.sizePolicy().hasHeightForWidth())
        whereGroupbox.setSizePolicy(sizePolicy)

        layoutWhere = QVBoxLayout(whereGroupbox)
        self.__silentRButton = QRadioButton(whereGroupbox)
        self.__silentRButton.setText("Silent")
        layoutWhere.addWidget(self.__silentRButton)
        self.__statusbarRButton = QRadioButton(whereGroupbox)
        self.__statusbarRButton.setText("Status bar")
        layoutWhere.addWidget(self.__statusbarRButton)
        self.__logtabRButton = QRadioButton(whereGroupbox)
        self.__logtabRButton.setText("Log tab")
        layoutWhere.addWidget(self.__logtabRButton)

        verticalLayout.addWidget(whereGroupbox)

        buttonBox = QDialogButtonBox(self)
        buttonBox.setOrientation(Qt.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.Ok
                                     | QDialogButtonBox.Cancel)
        self.__OKButton = buttonBox.button(QDialogButtonBox.Ok)
        self.__OKButton.setDefault(True)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.close)
        verticalLayout.addWidget(buttonBox)
        return
    def __init__(self, eventIDs, parent=None):
        super(ShowSelectRefDlg, self).__init__(parent)
        self.setWindowTitle('Select reference snapshot')
        self.eventIDs=eventIDs
        self.refSnapshot = ""
        #print(self.eventIDs)
        
        desc = QLabel()
        desc.setText("%d snapshots with IDs %s to be compared.\n\n\
Please select one as the reference snapshot\n\n"%(len(eventIDs),eventIDs))
        gBox = QGroupBox("Reference Snapshot Selection") 
        
        self.radio = [0]*len(eventIDs)
        vbox = QVBoxLayout()
        for i in range(len(eventIDs)):
            self.radio[i] = QRadioButton("Snapshot ID: %s"%eventIDs[i])   
            self.radio[i].setChecked(False)    
            vbox.addWidget(self.radio[i])
            self.radio[i].clicked.connect(self.reorderEventIDs)
        vbox.addStretch(1)
        gBox.setLayout(vbox)
        
        #okButton = QPushButton("OK")
        #cancelButton = QPushButton("Cancle")
        #okButton.clicked.connect(self.returnOrderedIDs)
        #okButton.clicked.connect(self.ignore)

        buttonBox = QDialogButtonBox()
        buttonBox.setOrientation(Qt.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        QObject.connect(buttonBox, SIGNAL("rejected()"), self.reject)
        QObject.connect(buttonBox, SIGNAL("accepted()"), self.accept)
        
        layout = QGridLayout(self)
        layout.addWidget(desc,0,0,1,1)
        layout.addWidget(gBox,1,0,1,1)
        #layout.addWidget(okButton,2,0,1,1)
        #layout.addWidget(cancelButton,2,1,1,1)
        layout.addWidget(buttonBox,2,0,1,1)
        self.setLayout(layout)
Example #33
0
    def __createLayout( self ):
        """ Creates the dialog layout """

        self.resize( 450, 150 )
        self.setSizeGripEnabled( True )

        verticalLayout = QVBoxLayout( self )

        whereGroupbox = QGroupBox( self )
        whereGroupbox.setTitle( "Garbage collector message destination" )
        sizePolicy = QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Preferred )
        sizePolicy.setHorizontalStretch( 0 )
        sizePolicy.setVerticalStretch( 0 )
        sizePolicy.setHeightForWidth(
                        whereGroupbox.sizePolicy().hasHeightForWidth() )
        whereGroupbox.setSizePolicy( sizePolicy )

        layoutWhere = QVBoxLayout( whereGroupbox )
        self.__silentRButton = QRadioButton( whereGroupbox )
        self.__silentRButton.setText( "Silent" )
        layoutWhere.addWidget( self.__silentRButton )
        self.__statusbarRButton = QRadioButton( whereGroupbox )
        self.__statusbarRButton.setText( "Status bar" )
        layoutWhere.addWidget( self.__statusbarRButton )
        self.__logtabRButton = QRadioButton( whereGroupbox )
        self.__logtabRButton.setText( "Log tab" )
        layoutWhere.addWidget( self.__logtabRButton )

        verticalLayout.addWidget( whereGroupbox )

        buttonBox = QDialogButtonBox( self )
        buttonBox.setOrientation( Qt.Horizontal )
        buttonBox.setStandardButtons( QDialogButtonBox.Ok |
                                      QDialogButtonBox.Cancel )
        self.__OKButton = buttonBox.button( QDialogButtonBox.Ok )
        self.__OKButton.setDefault( True )
        buttonBox.accepted.connect( self.accept )
        buttonBox.rejected.connect( self.close )
        verticalLayout.addWidget( buttonBox )
        return
Example #34
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 )
Example #35
0
    def __createLayout( self ):
        """ Creates the dialog layout """

        self.resize( 450, 20 )
        self.setSizeGripEnabled( True )

        verticalLayout = QVBoxLayout( self )

        # Note label
        noteLabel = QLabel( "<b>Note</b>: the analysis is " \
                            "suggestive and not precise. " \
                            "Use the results with caution.\n", self )
        verticalLayout.addWidget( noteLabel )

        # Info label
        self.__infoLabel = QLabel( self )
        verticalLayout.addWidget( self.__infoLabel )

        # Progress bar
        self.__progressBar = QProgressBar( self )
        self.__progressBar.setValue( 0 )
        self.__progressBar.setOrientation( Qt.Horizontal )
        verticalLayout.addWidget( self.__progressBar )

        # Found label
        self.__foundLabel = QLabel( self )
        verticalLayout.addWidget( self.__foundLabel )

        # Buttons
        buttonBox = QDialogButtonBox( self )
        buttonBox.setOrientation( Qt.Horizontal )
        buttonBox.setStandardButtons( QDialogButtonBox.Close )
        verticalLayout.addWidget( buttonBox )

        buttonBox.rejected.connect( self.__onClose )
        return
Example #36
0
    def __createLayout(self):
        """ Creates the dialog layout """

        self.resize(450, 20)
        self.setSizeGripEnabled(True)

        verticalLayout = QVBoxLayout(self)

        # Note label
        noteLabel = QLabel( "<b>Note</b>: the analysis is " \
                            "suggestive and not precise. " \
                            "Use the results with caution.\n", self )
        verticalLayout.addWidget(noteLabel)

        # Info label
        self.__infoLabel = QLabel(self)
        verticalLayout.addWidget(self.__infoLabel)

        # Progress bar
        self.__progressBar = QProgressBar(self)
        self.__progressBar.setValue(0)
        self.__progressBar.setOrientation(Qt.Horizontal)
        verticalLayout.addWidget(self.__progressBar)

        # Found label
        self.__foundLabel = QLabel(self)
        verticalLayout.addWidget(self.__foundLabel)

        # Buttons
        buttonBox = QDialogButtonBox(self)
        buttonBox.setOrientation(Qt.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.Close)
        verticalLayout.addWidget(buttonBox)

        buttonBox.rejected.connect(self.__onClose)
        return
Example #37
0
class MyMainWindow(QMainWindow):
    ' Main Window '
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self.statusBar().showMessage(__doc__)
        self.setWindowTitle(__doc__)
        self.setMinimumSize(250, 280)
        self.setMaximumSize(300, 300)
        self.resize(250, 290)
        self.setWindowIcon(QIcon.fromTheme("face-monkey"))
        self.setStyleSheet('''QWidget { color: rgba( 0, 255, 255, 255 );
            background-color: #323232; font-family: 'Ubuntu Light';
            font-size: 14px;
            }

            QToolTip {
                border: 1px solid black;
                background-color: #ffa02f;
                background-image: None;
                padding: 1px;
                border-radius: 3px;
                opacity: 100;
            }

            QWidget:item:hover {
                background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #ffa02f,
                    stop: 1 #ca0619
                );
                color: #000000;
            }

            QWidget:item:selected {
                background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #ffa02f,
                    stop: 1 #d7801a
                );
            }

            QWidget:disabled {
                color: #404040;
                background-color: #323232;
            }

            QWidget:focus {
                background-image: None;
                border: 2px solid QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #ffa02f,
                    stop: 1 #d7801a
                );
            }

            QPushButton {
                background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #565656,
                    stop: 0.1 #525252,
                    stop: 0.5 #4e4e4e,
                    stop: 0.9 #4a4a4a,
                    stop: 1 #464646
                );
                border-width: 1px;
                border-color: #1e1e1e;
                border-style: solid;
                border-radius: 6;
                padding: 3px;
                font-size: 12px;
                padding-left: 5px;
                padding-right: 5px;
                background-image: None;
            }

            QPushButton:pressed {
                background-image: None;
                background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #2d2d2d,
                    stop: 0.1 #2b2b2b,
                    stop: 0.5 #292929,
                    stop: 0.9 #282828,
                    stop: 1 #252525
                );
            }

            QComboBox {
                background-image: None;
                selection-background-color: #ffaa00;
                background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #565656,
                    stop: 0.1 #525252,
                    stop: 0.5 #4e4e4e,
                    stop: 0.9 #4a4a4a,
                    stop: 1 #464646
                );
                border-style: solid;
                border: 1px solid #1e1e1e;
                border-radius: 5;
            }

            QComboBox:hover, QPushButton:hover {
                background-image: url(.bg.png);
                border: 2px solid QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #ffa02f,
                    stop: 1 #d7801a
                );
            }

            QComboBox:on {
                padding-top: 3px;
                padding-left: 4px;
                background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #2d2d2d,
                    stop: 0.1 #2b2b2b,
                    stop: 0.5 #292929,
                    stop: 0.9 #282828,
                    stop: 1 #252525
                );
                selection-background-color: #ffaa00;
                background-image: None;
            }

            QComboBox QAbstractItemView {
                background-image: None;
                border: 2px solid darkgray;
                selection-background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #ffa02f,
                    stop: 1 #d7801a
                );
            }

            QComboBox::drop-down {
                 subcontrol-origin: padding;
                 subcontrol-position: top right;
                 width: 15px;
                 border-left-width: 0px;
                 border-left-color: darkgray;
                 border-left-style: solid;
                 border-top-right-radius: 3px;
                 border-bottom-right-radius: 3px;
                 background-image: None;
             }

            QComboBox::down-arrow { background-image: None; }

            QSlider {
                border-width: 2px;
                border-color: #1e1e1e;
                border-style: solid;
                padding: 3px;
                font-size: 8px;
                padding-left: 5px;
                padding-right: 5px;
                width: 25px;
                border-radius: 5px;
            }

            QSlider::sub-page:vertical {
                background: red;
                border: none;
                width: 25px;
            }

            QSlider::add-page:vertical {
                background: green;
                border: none;
                width: 25px;
            }

            QSlider::handle:vertical {
                background-color: QLinearGradient(spread:pad, x1:0, y1:0, x2:1,
                    y2:0.273, stop:0 rgba(0, 0, 0, 255),
                    stop:1 rgba(150, 255, 255, 255)
                    );
                width: 10px;
                height: 25px;
                border: 1px solid grey;
                text-align: center;
                border-top-left-radius: 2px;
                border-bottom-left-radius: 2px;
                border-top-right-radius: 2px;
                border-bottom-right-radius 2px;
                margin-left: 2px;
                margin-right: 2px;
            }

            QSlider::handle:vertical:hover {
                border: 2px solid #ffaa00;
                margin-left: 2px;
                margin-right: 2px;
            }

            QSlider::sub-page:vertical:disabled {
                background: #bbb;
                border-color: #999;
            }

            QSlider::add-page:vertical:disabled {
                background: #eee;
                border-color: #999;
            }

            QSlider::handle:vertical:disabled {
                background: #eee;
                border: 1px solid #aaa;
                border-radius: 4px;
            } ''')

        self.label1 = QLabel(self)
        self.label1.setText('Use Debug')
        self.label1.setGeometry(QtCore.QRect(25, 25, 125, 25))

        self.slider1 = QSlider(self)
        self.slider1.setGeometry(QtCore.QRect(150, 25, 25, 25))
        self.slider1.setTickInterval(1)
        self.slider1.setCursor(QCursor(QtCore.Qt.OpenHandCursor))
        self.slider1.TickPosition(QSlider.TicksBothSides)
        self.slider1.setRange(0, 1)
        self.slider1.setValue(1)
        self.sli1lbl = QLabel(str(self.slider1.value()), self.slider1)
        self.sli1lbl.move(9, 5)
        self.sli1lbl.setAutoFillBackground(False)
        self.slider1.valueChanged.connect(
            lambda: self.sli1lbl.setText(str(self.slider1.value())))
        self.slider1.sliderPressed.connect(
            lambda: self.slider1.setCursor(QCursor(QtCore.Qt.ClosedHandCursor)))
        self.slider1.sliderReleased.connect(
            lambda: self.slider1.setCursor(QCursor(QtCore.Qt.OpenHandCursor)))

        self.label2 = QLabel(self)
        self.label2.setText('Make Executable')
        self.label2.setGeometry(QtCore.QRect(25, 75, 125, 25))

        self.slider2 = QSlider(self)
        self.slider2.setGeometry(QtCore.QRect(150, 75, 25, 25))
        self.slider2.setTickInterval(1)
        self.slider2.setCursor(QCursor(QtCore.Qt.OpenHandCursor))
        self.slider2.TickPosition(QSlider.TicksBothSides)
        self.slider2.setRange(0, 1)
        self.slider2.setValue(1)
        self.sli2lbl = QLabel(str(self.slider2.value()), self.slider2)
        self.sli2lbl.move(9, 5)
        self.sli2lbl.setAutoFillBackground(False)
        self.slider2.valueChanged.connect(
            lambda: self.sli2lbl.setText(str(self.slider2.value())))
        self.slider2.sliderPressed.connect(
            lambda: self.slider2.setCursor(QCursor(QtCore.Qt.ClosedHandCursor)))
        self.slider2.sliderReleased.connect(
            lambda: self.slider2.setCursor(QCursor(QtCore.Qt.OpenHandCursor)))

        self.label3 = QLabel(self)
        self.label3.setText('Relative Imports')
        self.label3.setGeometry(QtCore.QRect(25, 125, 125, 25))

        self.slider3 = QSlider(self)
        self.slider3.setGeometry(QtCore.QRect(150, 125, 25, 25))
        self.slider3.setTickInterval(1)
        self.slider3.setCursor(QCursor(QtCore.Qt.OpenHandCursor))
        self.slider3.TickPosition(QSlider.TicksBothSides)
        self.slider3.setRange(0, 1)
        self.slider3.setValue(0)
        self.sli3lbl = QLabel(str(self.slider3.value()), self.slider3)
        self.sli3lbl.move(9, 5)
        self.sli3lbl.setAutoFillBackground(False)
        self.slider3.valueChanged.connect(
            lambda: self.sli3lbl.setText(str(self.slider3.value())))
        self.slider3.sliderPressed.connect(
            lambda: self.slider3.setCursor(QCursor(QtCore.Qt.ClosedHandCursor)))
        self.slider3.sliderReleased.connect(
            lambda: self.slider3.setCursor(QCursor(QtCore.Qt.OpenHandCursor)))

        self.label4 = QLabel(self)
        self.label4.setText('Indent Spaces')
        self.label4.setGeometry(QtCore.QRect(25, 175, 125, 25))

        self.combo1 = QComboBox(self)
        self.combo1.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
        self.combo1.addItems(['4', '0', '2', '6', '8'])
        self.combo1.setGeometry(QtCore.QRect(150, 175, 50, 25))

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setGeometry(QtCore.QRect(25, 225, 200, 32))
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel |
            QDialogButtonBox.Close | QDialogButtonBox.Help)
        self.buttonBox.setCenterButtons(False)
        self.buttonBox.helpRequested.connect(lambda: QMessageBox.about(
            self, __doc__, str(__doc__ + ', ' + ',\nversion ' + __version__ +
                               '(' + __license__ + '),\nby ' + __author__ + ', '
                               + __email__)))
        self.buttonBox.accepted.connect(self.run)
        self.buttonBox.rejected.connect(self.close)
        palette = self.palette()
        palette.setBrush(QPalette.Base, Qt.transparent)
        self.setPalette(palette)
        self.setAttribute(Qt.WA_OpaquePaintEvent, False)

    def run(self):
        'Run the actual conversion.'
        # Ask the User for the source .ui file as input
        filein = str(QFileDialog.getOpenFileName(
            self, __doc__, path.expanduser("~"), 'UI(*.ui)')).strip()
        # Parse Value of Slider1 as the Debug flag parameter
        if self.slider1.value() == 0:
            arg1 = ''
        else:
            arg1 = '--debug '
        # Parse Value of Slider2 as the Execute flag parameter
        if self.slider2.value() == 0:
            arg2 = ''
        else:
            arg2 = '--execute '
        # Parse Value of Slider3 as the relative imports flag parameter
        if self.slider3.value() == 0:
            arg3 = ''
        else:
            arg3 = '--from-imports '
        # debug
        #print(arg1, arg2, arg3, str(self.combo1.currentText()))
        # run the subprocesses
        subprocess.Popen(
            'nice --adjustment=19 pyuic4 ' + arg1 + arg2 + arg3 +
            '--indent=' + str(self.combo1.currentText()) +
            ' --output=' + str(filein).lower().replace('.ui', '.py') +
            ' ' + filein +
            ' && chmod -v +x ' + str(filein).lower().replace('.ui', '.py'),
            shell=True)

    def paintEvent(self, event):
        ' Paint semi-transparent background '
        painter = QPainter(self)
        painter.fillRect(event.rect(), Qt.transparent)
        painter.setPen(Qt.NoPen)
        painter.setBrush(QColor(0, 0, 0))
        painter.setOpacity(0.75)
        painter.drawRoundedRect(self.rect(), 75, 50)
        painter.end()
Example #38
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 CalculatorModelerParametersDialog(ModelerParametersDialog):

    def setupUi(self):
        self.valueItems = {}
        self.dependentItems = {}
        self.resize(650, 450)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        self.infoText = QTextEdit()
        numbers = self.getAvailableValuesOfType(ParameterNumber, OutputNumber)
        text = self.tr('You can refer to model values in your formula, using '
                       'single-letter variables, as follows:\n', 'CalculatorModelerParametersDialog')
        ichar = 97
        if numbers:
            for number in numbers:
                text += chr(ichar) + '->' + self.resolveValueDescription(number) + '\n'
                ichar += 1
        else:
            text += self.tr('\n - No numerical variables are available.', 'CalculatorModelerParametersDialog')
        self.infoText.setText(text)
        self.infoText.setEnabled(False)
        self.formulaText = QLineEdit()
        if hasattr(self.formulaText, 'setPlaceholderText'):
            self.formulaText.setPlaceholderText(self.tr('[Enter your formula here]', 'CalculatorModelerParametersDialog'))
        self.setWindowTitle(self.tr('Calculator', 'CalculatorModelerParametersDialog'))
        self.verticalLayout = QVBoxLayout()
        self.verticalLayout.setSpacing(2)
        self.verticalLayout.setMargin(0)
        self.verticalLayout.addWidget(self.infoText)
        self.verticalLayout.addWidget(self.formulaText)
        self.verticalLayout.addWidget(self.buttonBox)
        self.setLayout(self.verticalLayout)
        QObject.connect(self.buttonBox, SIGNAL('accepted()'), self.okPressed)
        QObject.connect(self.buttonBox, SIGNAL('rejected()'), self.cancelPressed)
        QMetaObject.connectSlotsByName(self)

    def createAlgorithm(self):
        alg = Algorithm('modelertools:calculator')
        alg.setName(self.model)
        alg.description = self.tr('Calculator', 'CalculatorModelerParametersDialog')

        formula = self.formulaText.text()
        alg.params[FORMULA] = formula

        for i in xrange(AVAILABLE_VARIABLES):
            paramname = NUMBER + unicode(i)
            alg.params[paramname] = None

        numbers = self.getAvailableValuesOfType(ParameterNumber, OutputNumber)
        used = []
        for i in range(len(numbers)):
            if unicode(chr(i + 97)) in formula:
                used.append(numbers[i])

        for i, variable in enumerate(used):
            paramname = NUMBER + unicode(i)
            alg.params[paramname] = variable

        # TODO check formula is correct
        return alg
Example #40
0
class MainWindow(QDialog, SetupTabStopsMixin, CenterOnScreenMixin):
    WINDOW_TITLE_TEXT = 'BAON'
    OPTIONS_BOX_TEXT = 'Options'
    SCAN_RECURSIVE_CHECKBOX_TEXT = 'Recursively scan subfolders'
    USE_PATH_CHECKBOX_TEXT = 'Use path'
    USE_EXTENSION_CHECKBOX_TEXT = 'Use extension'
    RULES_BOX_TEXT = 'Rename Rules'
    FILES_BOX_TEXT = 'Renamed Files'

    RENAME_WARNINGS_DIALOG_CAPTION = 'Please Confirm'
    RENAME_WARNINGS_DIALOG_TEXT = 'There are warnings for some of the files. Proceed with the rename operation anyway?'

    RENAME_COMPLETE_DIALOG_CAPTION = 'Rename Complete'
    RENAME_COMPLETE_DIALOG_TEXT =\
        'The files have been renamed successfully. Do you wish to perform another rename operation?'

    DEFAULT_WINDOW_WIDTH = 800
    DEFAULT_WINDOW_HEIGHT = 600
    RULES_BOX_HEIGHT = 112

    base_path_edited = pyqtSignal(str)
    scan_recursive_changed = pyqtSignal(bool)
    rules_text_changed = pyqtSignal(str)
    use_path_changed = pyqtSignal(bool)
    use_extension_changed = pyqtSignal(bool)

    request_add_override = pyqtSignal(BAONPath, BAONPath)
    request_remove_override = pyqtSignal(BAONPath)

    request_do_rename = pyqtSignal()

    request_rescan = pyqtSignal()

    _base_path_panel = None
    _scan_recursive_checkbox = None
    _use_path_checkbox = None
    _use_extension_checkbox = None
    _rules_editor = None
    _files_display = None
    _files_display_summary_panel = None
    _status_box = None
    _dialog_button_box = None

    def __init__(self, args):
        super().__init__()

        self._init_ui()
        self._fill_in_controls(args)
        self._center_on_screen()

    def _init_ui(self):
        self.setWindowTitle(self.WINDOW_TITLE_TEXT)
        self.resize(self.DEFAULT_WINDOW_WIDTH, self.DEFAULT_WINDOW_HEIGHT)

        main_layout = QVBoxLayout(self)
        main_layout.addWidget(self._create_base_path_panel())
        main_layout.addWidget(self._create_options_box())
        main_layout.addWidget(self._create_rules_box())
        main_layout.addWidget(self._create_files_box())
        main_layout.addWidget(self._create_status_box())
        main_layout.addWidget(self._create_dialog_buttons())

        self._setup_tab_stops(
            self._base_path_panel,
            self._scan_recursive_checkbox,
            self._use_path_checkbox,
            self._use_extension_checkbox,
            self._rules_editor,
            self._files_display,
            self._files_display_summary,
            self._dialog_button_box,
        )

    def _create_base_path_panel(self):
        self._base_path_panel = BasePathPanel(self)
        self._base_path_panel.path_edited.connect(self.base_path_edited)

        return self._base_path_panel

    def _create_options_box(self):
        box = QGroupBox(self.OPTIONS_BOX_TEXT, self)

        self._scan_recursive_checkbox = QCheckBox(self.SCAN_RECURSIVE_CHECKBOX_TEXT, box)
        self._scan_recursive_checkbox.toggled.connect(self.scan_recursive_changed)

        self._use_path_checkbox = QCheckBox(self.USE_PATH_CHECKBOX_TEXT, box)
        self._use_path_checkbox.toggled.connect(self.use_path_changed)

        self._use_extension_checkbox = QCheckBox(self.USE_EXTENSION_CHECKBOX_TEXT, box)
        self._use_extension_checkbox.toggled.connect(self.use_extension_changed)

        layout = QHBoxLayout(box)
        layout.addWidget(self._scan_recursive_checkbox)
        layout.addWidget(self._use_path_checkbox)
        layout.addWidget(self._use_extension_checkbox)
        layout.addStretch()

        return box

    def _create_rules_box(self):
        box = QGroupBox(self.RULES_BOX_TEXT, self)
        box.setMaximumHeight(self.RULES_BOX_HEIGHT)

        self._rules_editor = RulesEditor(box)
        self._rules_editor.rules_edited.connect(self.rules_text_changed)

        layout = QHBoxLayout(box)
        layout.addWidget(self._rules_editor)

        return box

    def _create_files_box(self):
        box = QGroupBox(self.FILES_BOX_TEXT, self)
        box.setSizePolicy(QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding))

        self._files_display = FilesDisplay(box)
        self._files_display_summary = FilesDisplaySummaryPanel(box)

        self._files_display.request_add_override.connect(self.request_add_override)
        self._files_display.request_remove_override.connect(self.request_remove_override)

        self._files_display.counts_changed.connect(self._files_display_summary.set_counts)
        self._files_display.is_browsing_category_changed.connect(self._files_display_summary.set_is_browsing_category)
        self._files_display.has_next_in_category_changed.connect(self._files_display_summary.set_has_next_in_category)
        self._files_display.has_prev_in_category_changed.connect(self._files_display_summary.set_has_prev_in_category)

        self._files_display_summary.start_browsing_category.connect(self._files_display.start_browsing_category)
        self._files_display_summary.next_in_category.connect(self._files_display.next_in_category)
        self._files_display_summary.prev_in_category.connect(self._files_display.prev_in_category)

        layout = QVBoxLayout(box)
        layout.addWidget(self._files_display)
        layout.addWidget(self._files_display_summary)

        return box

    def _create_status_box(self):
        self._status_box = StatusBox(self)

        return self._status_box

    def _create_dialog_buttons(self):
        self._dialog_button_box = QDialogButtonBox(self)
        self._dialog_button_box.setOrientation(Qt.Horizontal)
        self._dialog_button_box.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok)
        self._dialog_button_box.setCenterButtons(True)

        self._dialog_button_box.accepted.connect(self._confirm_rename)
        self._dialog_button_box.rejected.connect(self.reject)

        return self._dialog_button_box

    def _fill_in_controls(self, args):
        if args.base_path is not None:
            self._base_path_panel.set_base_path(args.base_path)
        if args.scan_recursive is not None:
            self._scan_recursive_checkbox.setChecked(args.scan_recursive)
        if args.use_extension is not None:
            self._use_extension_checkbox.setChecked(args.use_extension)
        if args.use_path is not None:
            self._use_path_checkbox.setChecked(args.use_path)
        if args.rules_text is not None:
            self._rules_editor.set_rules(args.rules_text)

    @pyqtSlot()
    def show_first_time(self):
        self.show()
        self.raise_()

        # We need to do this here as otherwise the operation may fail on some platforms
        self.setWindowIcon(QIcon(':/app_icon.png'))

    @pyqtSlot(str)
    def set_base_path(self, base_path):
        self._base_path_panel.set_base_path(base_path)

    @pyqtSlot(BAONStatus)
    def report_status(self, status):
        files_busy = \
            status.scan_status in [BAONStatus.IN_PROGRESS, BAONStatus.PENDING] or \
            status.rename_status in [BAONStatus.IN_PROGRESS, BAONStatus.PENDING]

        self._files_display.setEnabled(not files_busy)

        if status.rules_status == BAONStatus.ERROR:
            self._rules_editor.show_error(status.rules_status_extra.source_span)
        else:
            self._rules_editor.clear_error()

        self._status_box.show_status(status)

        self._dialog_button_box.button(QDialogButtonBox.Ok).setEnabled(
            status.execute_status in [BAONStatus.WAITING_FOR_USER, BAONStatus.ERROR]
        )

        if status.execute_status == BAONStatus.AVAILABLE:
            self._on_rename_completed()

    @pyqtSlot(list)
    def update_scanned_files(self, files):
        self._files_display.set_original_files(files)

    @pyqtSlot(list)
    def update_renamed_files(self, files):
        self._files_display.set_renamed_files(files)

    @pyqtSlot()
    def _confirm_rename(self):
        if self._files_display.has_rename_warnings():
            if not self._ask_user(self.RENAME_WARNINGS_DIALOG_CAPTION, self.RENAME_WARNINGS_DIALOG_TEXT):
                return

        self.request_do_rename.emit()

    def _on_rename_completed(self):
        self._rules_editor.clear()
        self.request_rescan.emit()

        if self._ask_user(self.RENAME_COMPLETE_DIALOG_CAPTION, self.RENAME_COMPLETE_DIALOG_TEXT):
            pass
        else:
            self.reject()

    def _ask_user(self, caption, text):
        on_mac = platform.system() == 'Darwin'

        dialog = QMessageBox(
            QMessageBox.Question,
            caption,
            text,
            QMessageBox.Yes | QMessageBox.No,
            self,
            Qt.Sheet if on_mac else Qt.Dialog | Qt.MSWindowsFixedSizeDialogHint,
        )
        dialog.setDefaultButton(QMessageBox.No)
        dialog.setWindowModality(Qt.WindowModal)

        return dialog.exec_() == QMessageBox.Yes
Example #41
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()
Example #42
0
class ModelerParametersDialog(QDialog):

    ENTER_NAME = '[Enter name if this is a final result]'
    NOT_SELECTED = '[Not selected]'
    USE_MIN_COVERING_EXTENT = '[Use min covering extent]'

    def __init__(self, alg, model, algName=None):
        QDialog.__init__(self)
        self.setModal(True)
        #The algorithm to define in this dialog. It is an instance of GeoAlgorithm
        self._alg = alg
        #The resulting algorithm after the user clicks on OK. it is an instance of the container Algorithm class
        self.alg = None
        #The model this algorithm is going to be added to
        self.model = model
        #The name of the algorithm in the model, in case we are editing it and not defining it for the first time
        self._algName = algName
        self.setupUi()
        self.params = None

    def setupUi(self):
        self.labels = {}
        self.widgets = {}
        self.checkBoxes = {}
        self.showAdvanced = False
        self.valueItems = {}
        self.dependentItems = {}
        self.resize(650, 450)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                | QDialogButtonBox.Ok)
        tooltips = self._alg.getParameterDescriptions()
        self.setSizePolicy(QSizePolicy.Expanding,
                           QSizePolicy.Expanding)
        self.verticalLayout = QVBoxLayout()
        self.verticalLayout.setSpacing(5)
        self.verticalLayout.setMargin(20)

        hLayout = QHBoxLayout()
        hLayout.setSpacing(5)
        hLayout.setMargin(0)
        descriptionLabel = QLabel(self.tr("Description"))
        self.descriptionBox = QLineEdit()
        self.descriptionBox.setText(self._alg.name)
        hLayout.addWidget(descriptionLabel)
        hLayout.addWidget(self.descriptionBox)
        self.verticalLayout.addLayout(hLayout)
        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)
        self.verticalLayout.addWidget(line)

        for param in self._alg.parameters:
            if param.isAdvanced:
                self.advancedButton = QPushButton()
                self.advancedButton.setText(self.tr('Show advanced parameters'))
                self.advancedButton.setMaximumWidth(150)
                self.advancedButton.clicked.connect(
                    self.showAdvancedParametersClicked)
                self.verticalLayout.addWidget(self.advancedButton)
                break
        for param in self._alg.parameters:
            if param.hidden:
                continue
            desc = param.description
            if isinstance(param, ParameterExtent):
                desc += '(xmin, xmax, ymin, ymax)'
            label = QLabel(desc)
            self.labels[param.name] = label
            widget = self.getWidgetFromParameter(param)
            self.valueItems[param.name] = widget
            if param.name in tooltips.keys():
                tooltip = tooltips[param.name]
            else:
                tooltip = param.description
            label.setToolTip(tooltip)
            widget.setToolTip(tooltip)
            if param.isAdvanced:
                label.setVisible(self.showAdvanced)
                widget.setVisible(self.showAdvanced)
                self.widgets[param.name] = widget
            self.verticalLayout.addWidget(label)
            self.verticalLayout.addWidget(widget)

        for output in self._alg.outputs:
            if output.hidden:
                continue
            if isinstance(output, (OutputRaster, OutputVector, OutputTable,
                          OutputHTML, OutputFile, OutputDirectory)):
                label = QLabel(output.description + '<'
                               + output.__class__.__name__ + '>')
                item = QLineEdit()
                if hasattr(item, 'setPlaceholderText'):
                    item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME)
                self.verticalLayout.addWidget(label)
                self.verticalLayout.addWidget(item)
                self.valueItems[output.name] = item

        label = QLabel(' ')
        self.verticalLayout.addWidget(label)
        label = QLabel(self.tr('Parent algorithms'))
        self.dependenciesPanel = self.getDependenciesPanel()
        self.verticalLayout.addWidget(label)
        self.verticalLayout.addWidget(self.dependenciesPanel)

        self.verticalLayout.addStretch(1000)
        self.setLayout(self.verticalLayout)

        self.setPreviousValues()
        self.setWindowTitle(self._alg.name)
        self.verticalLayout2 = QVBoxLayout()
        self.verticalLayout2.setSpacing(2)
        self.verticalLayout2.setMargin(0)
        self.tabWidget = QTabWidget()
        self.tabWidget.setMinimumWidth(300)
        self.paramPanel = QWidget()
        self.paramPanel.setLayout(self.verticalLayout)
        self.scrollArea = QScrollArea()
        self.scrollArea.setWidget(self.paramPanel)
        self.scrollArea.setWidgetResizable(True)
        self.tabWidget.addTab(self.scrollArea, self.tr('Parameters'))
        self.webView = QWebView()

        html = None
        url = None
        isText, help = self._alg.help()
        if help is not None:
            if isText:
                html = help
            else:
                url = QUrl(help)
        else:
            html = self.tr('<h2>Sorry, no help is available for this '
                           'algorithm.</h2>')
        try:
            if html:
                self.webView.setHtml(html)
            elif url:
                self.webView.load(url)
        except:
            self.webView.setHtml(self.tr('<h2>Could not open help file :-( </h2>'))
        self.tabWidget.addTab(self.webView, 'Help')
        self.verticalLayout2.addWidget(self.tabWidget)
        self.verticalLayout2.addWidget(self.buttonBox)
        self.setLayout(self.verticalLayout2)
        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)
        QMetaObject.connectSlotsByName(self)

    def getAvailableDependencies(self):
        if self._algName is None:
            dependent = []
        else:
            dependent = self.model.getDependentAlgorithms(self._algName)
        opts = []
        for alg in self.model.algs.values():
            if alg.name not in dependent:
                opts.append(alg)
        return opts

    def getDependenciesPanel(self):
        return MultipleInputPanel([alg.algorithm.name for alg in self.getAvailableDependencies()])

    def showAdvancedParametersClicked(self):
        self.showAdvanced = not self.showAdvanced
        if self.showAdvanced:
            self.advancedButton.setText(self.tr('Hide advanced parameters'))
        else:
            self.advancedButton.setText(self.tr('Show advanced parameters'))
        for param in self._alg.parameters:
            if param.isAdvanced:
                self.labels[param.name].setVisible(self.showAdvanced)
                self.widgets[param.name].setVisible(self.showAdvanced)

    def getAvailableValuesOfType(self, paramType, outType=None):
        values = []
        inputs = self.model.inputs
        for i in inputs.values():
            param = i.param
            if isinstance(param, paramType):
                values.append(ValueFromInput(param.name))
        if outType is None:
            return values
        if self._algName is None:
            dependent = []
        else:
            dependent = self.model.getDependentAlgorithms(self._algName)
        for alg in self.model.algs.values():
            if alg.name not in dependent:
                for out in alg.algorithm.outputs:
                    if isinstance(out, outType):
                        values.append(ValueFromOutput(alg.name, out.name))

        return values

    def resolveValueDescription(self, value):
        if isinstance(value, ValueFromInput):
            return self.model.inputs[value.name].param.description
        else:
            alg = self.model.algs[value.alg]
            return self.tr("'%s' from algorithm '%s'") % (alg.algorithm.getOutputFromName(value.output).description, alg.description)


    def getWidgetFromParameter(self, param):
        if isinstance(param, ParameterRaster):
            item = QComboBox()
            layers = self.getAvailableValuesOfType(ParameterRaster, OutputRaster)
            if param.optional:
                item.addItem(self.NOT_SELECTED, None)
            for layer in layers:
                item.addItem(self.resolveValueDescription(layer), layer)
        elif isinstance(param, ParameterVector):
            item = QComboBox()
            layers = self.getAvailableValuesOfType(ParameterVector, OutputVector)
            if param.optional:
                item.addItem(self.NOT_SELECTED, None)
            for layer in layers:
                item.addItem(self.resolveValueDescription(layer), layer)
        elif isinstance(param, ParameterTable):
            item = QComboBox()
            tables = self.getAvailableValuesOfType(ParameterTable, OutputTable)
            layers = self.getAvailableValuesOfType(ParameterVector, OutputVector)
            if param.optional:
                item.addItem(self.NOT_SELECTED, None)
            for table in tables:
                item.addItem(self.resolveValueDescription(table), table)
            for layer in layers:
                item.addItem(self.resolveValueDescription(layer), layer)
        elif isinstance(param, ParameterBoolean):
            item = QComboBox()
            item.addItem('Yes')
            item.addItem('No')
            bools = self.getAvailableValuesOfType(ParameterBoolean, None)
            for b in bools:
                item.addItem(self.resolveValueDescription(b), b)
        elif isinstance(param, ParameterSelection):
            item = QComboBox()
            item.addItems(param.options)
        elif isinstance(param, ParameterFixedTable):
            item = FixedTablePanel(param)
        elif isinstance(param, ParameterRange):
            item = RangePanel(param)
        elif isinstance(param, ParameterMultipleInput):
            if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
                options = self.getAvailableValuesOfType(ParameterVector, OutputVector)
            else:
                options = self.getAvailableValuesOfType(ParameterRaster, OutputRaster)
            opts = []
            for opt in options:
                opts.append(self.resolveValueDescription(opt))
            item = MultipleInputPanel(opts)
        elif isinstance(param, ParameterString):
            strings = self.getAvailableValuesOfType(ParameterString, OutputString)
            options = [(self.resolveValueDescription(s), s) for s in strings]
            if param.multiline:
                item = MultilineTextPanel(options)
                item.setText(unicode(param.default))
            else:
                item = QComboBox()
                item.setEditable(True)
                for desc, val in options:
                    item.addItem(desc, val)
                item.setEditText(unicode(param.default))
        elif isinstance(param, ParameterTableField):
            item = QComboBox()
            item.setEditable(True)
            fields = self.getAvailableValuesOfType(ParameterTableField, None)
            for f in fields:
                item.addItem(self.resolveValueDescription(f), f)
        elif isinstance(param, ParameterNumber):
            item = QComboBox()
            item.setEditable(True)
            numbers = self.getAvailableValuesOfType(ParameterNumber, OutputNumber)
            for n in numbers:
                item.addItem(self.resolveValueDescription(n), n)
            item.setEditText(str(param.default))
        elif isinstance(param, ParameterCrs):
            item = CrsSelectionPanel(param.default)
        elif isinstance(param, ParameterExtent):
            item = QComboBox()
            item.setEditable(True)
            extents = self.getAvailableValuesOfType(ParameterExtent, OutputExtent)
            if self.canUseAutoExtent():
                item.addItem(self.USE_MIN_COVERING_EXTENT, None)
            for ex in extents:
                item.addItem(self.resolveValueDescription(ex), ex)
            if not self.canUseAutoExtent():
                item.setEditText(str(param.default))
        elif isinstance(param, ParameterFile):
            item = QComboBox()
            item.setEditable(True)
            files = self.getAvailableValuesOfType(ParameterFile, OutputFile)
            for f in files:
                item.addItem(self.resolveValueDescription(f), f)
        elif isinstance(param, ParameterGeometryPredicate):
            item = GeometryPredicateSelectionPanel(param.enabledPredicates)
        else:
            item = QLineEdit()
            try:
                item.setText(str(param.default))
            except:
                pass
        return item

    def canUseAutoExtent(self):
        for param in self._alg.parameters:
            if isinstance(param, (ParameterRaster, ParameterVector, ParameterMultipleInput)):
                return True
        return False

    def setTableContent(self):
        params = self._alg.parameters
        outputs = self._alg.outputs
        visibleParams = [p for p in params if not p.hidden]
        visibleOutputs = [p for o in outputs if not o.hidden]
        self.tableWidget.setRowCount(len(visibleParams) + len(visibleOutputs))

        for i, param in visibleParams:
            item = QTableWidgetItem(param.description)
            item.setFlags(Qt.ItemIsEnabled)
            self.tableWidget.setItem(i, 0, item)
            item = self.getWidgetFromParameter(param)
            self.valueItems[param.name] = item
            self.tableWidget.setCellWidget(i, 1, item)
            self.tableWidget.setRowHeight(i, 22)

        for i, output in visibleOutputs:
            item = QTableWidgetItem(output.description + '<'
                    + output.__module__.split('.')[-1] + '>')
            item.setFlags(Qt.ItemIsEnabled)
            self.tableWidget.setItem(i, 0, item)
            item = QLineEdit()
            if hasattr(item, 'setPlaceholderText'):
                item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME)
            self.valueItems[output.name] = item
            self.tableWidget.setCellWidget(i, 1, item)
            self.tableWidget.setRowHeight(i, 22)

    def setComboBoxValue(self, combo, value, param):
        if isinstance(value, list):
            value = value[0]
        items = [combo.itemData(i) for i in range(combo.count())]
        try:
            idx = items.index(value)
            combo.setCurrentIndex(idx)
            return
        except ValueError:
            pass
        if combo.isEditable():
            if value is not None:
                combo.setEditText(unicode(value))
        elif isinstance(param, ParameterSelection):
            combo.setCurrentIndex(int(value))
        elif isinstance(param, ParameterBoolean):
            if value:
                combo.setCurrentIndex(0)
            else:
                combo.setCurrentIndex(1)

    def setPreviousValues(self):
        if self._algName is not None:
            alg = self.model.algs[self._algName]
            self.descriptionBox.setText(alg.description)
            for param in alg.algorithm.parameters:
                if param.hidden:
                    continue
                widget = self.valueItems[param.name]
                if param.name in alg.params:
                    value = alg.params[param.name]
                else:
                    value = None
                if isinstance(param, (
                        ParameterRaster,
                        ParameterVector,
                        ParameterTable,
                        ParameterTableField,
                        ParameterSelection,
                        ParameterNumber,
                        ParameterBoolean,
                        ParameterExtent,
                        ParameterFile
                )):
                    self.setComboBoxValue(widget, value, param)
                elif isinstance(param, ParameterString):
                    if param.multiline:
                        widget.setValue(value)
                    else:
                        self.setComboBoxValue(widget, value, param)
                elif isinstance(param, ParameterCrs):
                    widget.setAuthId(value)
                elif isinstance(param, ParameterFixedTable):
                    pass  # TODO!
                elif isinstance(param, ParameterMultipleInput):
                    if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
                        options = self.getAvailableValuesOfType(ParameterVector, OutputVector)
                    else:
                        options = self.getAvailableValuesOfType(ParameterRaster, OutputRaster)
                    selected = []
                    for i, opt in enumerate(options):
                        if opt in value:
                            selected.append(i)
                    widget.setSelectedItems(selected)
                elif isinstance(param, ParameterGeometryPredicate):
                    widget.setValue(value)

            for name, out in alg.outputs.iteritems():
                widget = self.valueItems[name].setText(out.description)

            selected = []
            dependencies = self.getAvailableDependencies()
            for idx, dependency in enumerate(dependencies):
                if dependency in alg.dependencies:
                    selected.append(idx)

            self.dependenciesPanel.setSelectedItems(selected)

    def createAlgorithm(self):
        alg = Algorithm(self._alg.commandLineName())
        alg.setName(self.model)
        alg.description = self.descriptionBox.text()
        params = self._alg.parameters
        outputs = self._alg.outputs
        for param in params:
            if param.hidden:
                continue
            if not self.setParamValue(alg, param, self.valueItems[param.name]):
                return None
        for output in outputs:
            if not output.hidden:
                name = unicode(self.valueItems[output.name].text())
                if name.strip() != '' and name != ModelerParametersDialog.ENTER_NAME:
                    alg.outputs[output.name] = ModelerOutput(name)

        selectedOptions = self.dependenciesPanel.selectedoptions
        availableDependencies = self.getAvailableDependencies()
        for selected in selectedOptions:
            alg.dependencies.append(availableDependencies[selected].name)

        return alg

    def setParamValueLayerOrTable(self, alg, param, widget):
        idx = widget.currentIndex()
        if idx < 0:
            return False
        else:
            value = widget.itemData(widget.currentIndex())
            alg.params[param.name] = value
            return True


    def setParamTableFieldValue(self, alg, param, widget):
        idx = widget.findText(widget.currentText())
        if idx < 0:
            s = str(widget.currentText()).strip()
            if s == '':
                if param.optional:
                    alg.params[param.name] = None
                    return True
                else:
                    return False
            else:
                alg.params[param.name] = s
                return True
        else:
            alg.params[param.name] = widget.itemData(widget.currentIndex())
        return True

    def setParamStringValue(self, alg, param, widget):
        if param.multiline:
            value = widget.getValue()
            option = widget.getOption()
            if option == MultilineTextPanel.USE_TEXT:
                if value == '':
                    if param.optional:
                        alg.params[param.name] = None
                        return True
                    else:
                        return False
                else:
                    alg.params[param.name] = value
            else:
                alg.params[param.name] = value
        else:
            idx = widget.findText(widget.currentText())
            if idx < 0:
                value = widget.currentText().strip()
                if value == '':
                    if param.optional:
                        alg.params[param.name] = None
                        return True
                    else:
                        return False
                else:
                    alg.params[param.name] = value
            else:
                alg.params[param.name] = widget.itemData(widget.currentIndex())
        return True

    def setParamFileValue(self, alg, param, widget):
        idx = widget.findText(widget.currentText())
        if idx < 0:
            value = widget.currentText()
        else:
            value = widget.itemData(widget.currentIndex())
        alg.params[param.name] = value
        return True

    def setParamNumberValue(self, alg, param, widget):
        idx = widget.findText(widget.currentText())
        if idx < 0:
            s = widget.currentText()
            try:
                value = float(s)
            except:
                return False
        else:
            value = widget.itemData(widget.currentIndex())
        alg.params[param.name] = value
        return True

    def setParamExtentValue(self, alg, param, widget):
        idx = widget.findText(widget.currentText())
        if idx < 0:
            s = str(widget.currentText())
            try:
                tokens = s.split(',')
                if len(tokens) != 4:
                    return False
                for token in tokens:
                    float(token)
            except:
                return False
            alg.params[param.name] = [s]
        else:
            value = widget.itemData(widget.currentIndex())
            alg.params[param.name] = value
        return True

    def setParamValue(self, alg, param, widget):
        if isinstance(param, (ParameterRaster, ParameterVector,
                      ParameterTable)):
            return self.setParamValueLayerOrTable(alg, param, widget)
        elif isinstance(param, ParameterBoolean):
            if widget.currentIndex() < 2:
                value = widget.currentIndex() == 0
            else:
                value = widget.itemData(widget.currentIndex())
            alg.params[param.name] = value
            return True
        elif isinstance(param, ParameterString):
            return self.setParamStringValue(alg, param, widget)
        elif isinstance(param, ParameterNumber):
            return self.setParamNumberValue(alg, param, widget)
        elif isinstance(param, ParameterExtent):
            return self.setParamExtentValue(alg, param, widget)
        elif isinstance(param, ParameterFile):
            return self.setParamFileValue(alg, param, widget)
        elif isinstance(param, ParameterSelection):
            alg.params[param.name] = widget.currentIndex()
            return True
        elif isinstance(param, ParameterRange):
            alg.params[param.name] = widget.getValue()
            return True
        elif isinstance(param, ParameterCrs):
            authid = widget.getValue()
            if authid is None:
                alg.params[param.name] = None
            else:
                alg.params[param.name] = authid
            return True
        elif isinstance(param, ParameterFixedTable):
            alg.params[param.name] = ParameterFixedTable.tableToString(widget.table)
            return True
        elif isinstance(param, ParameterTableField):
            return self.setParamTableFieldValue(alg, param, widget)
        elif isinstance(param, ParameterMultipleInput):
            if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
                options = self.getAvailableValuesOfType(ParameterVector, OutputVector)
            else:
                options = self.getAvailableValuesOfType(ParameterRaster, OutputRaster)
            values = [options[i] for i in widget.selectedoptions]
            if len(values) == 0 and not param.optional:
                return False
            alg.params[param.name] = values
            return True
        elif isinstance(param, ParameterGeometryPredicate):
            alg.params[param.name] = widget.value()
            return True
        else:
            alg.params[param.name] = unicode(widget.text())
            return True

    def okPressed(self):
        self.alg = self.createAlgorithm()
        if self.alg is not None:
            self.close()
        else:
            QMessageBox.warning(self, self.tr('Unable to add algorithm'),
                                self.tr('Wrong or missing parameter values'))

    def cancelPressed(self):
        self.alg = None
        self.close()
Example #43
0
    def __createLayout( self ):
        " Creates the dialog layout "
        self.resize( 640, 480 )
        self.setSizeGripEnabled( True )

        vboxLayout = QVBoxLayout( self )

        # Revisions to compare
        compareGroupbox = QGroupBox( self )
        compareGroupbox.setTitle( "Revisions to compare" )
        sizePolicy = QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Preferred )
        sizePolicy.setHorizontalStretch( 0 )
        sizePolicy.setVerticalStretch( 0 )
        sizePolicy.setHeightForWidth(
                        compareGroupbox.sizePolicy().hasHeightForWidth() )
        compareGroupbox.setSizePolicy( sizePolicy )

        revisionLayout = QHBoxLayout( compareGroupbox )

        self.__lhsRevisionLabel = QLabel()
        self.__lhsRevisionLabel.setFrameStyle( QFrame.StyledPanel )
        self.__lhsResetButton = QToolButton()
        self.__lhsResetButton.setIcon( PixmapCache().getIcon( pluginHomeDir + 'svnclearrev.png' ) )
        self.__lhsResetButton.setFocusPolicy( Qt.NoFocus )
        self.__lhsResetButton.setEnabled( False )
        self.__lhsResetButton.setToolTip( "Reset revision to compare" )
        self.__lhsResetButton.clicked.connect( self.__onLHSReset )
        self.__rhsRevisionLabel = QLabel()
        self.__rhsRevisionLabel.setFrameStyle( QFrame.StyledPanel )
        self.__rhsResetButton = QToolButton()
        self.__rhsResetButton.setIcon( PixmapCache().getIcon( pluginHomeDir + 'svnclearrev.png' ) )
        self.__rhsResetButton.setFocusPolicy( Qt.NoFocus )
        self.__rhsResetButton.setEnabled( False )
        self.__rhsResetButton.setToolTip( "Reset revision to compare" )
        self.__rhsResetButton.clicked.connect( self.__onRHSReset )

        lhsLayout = QHBoxLayout()
        lhsLayout.addWidget( self.__lhsRevisionLabel )
        lhsLayout.addWidget( self.__lhsResetButton )
        rhsLayout = QHBoxLayout()
        rhsLayout.addWidget( self.__rhsRevisionLabel )
        rhsLayout.addWidget( self.__rhsResetButton )
        bothLayout = QVBoxLayout()
        bothLayout.addLayout( lhsLayout )
        bothLayout.addLayout( rhsLayout )
        revisionLayout.addLayout( bothLayout )

        self.__diffButton = QToolButton()
        self.__diffButton.setText( "Diff" )
        self.__diffButton.setFocusPolicy( Qt.NoFocus )
        self.__diffButton.setEnabled( False )
        self.__diffButton.clicked.connect( self.__onDiff )
        revisionLayout.addWidget( self.__diffButton )
        vboxLayout.addWidget( compareGroupbox )

        # Log table
        logHeaderFrame = QFrame()
        logHeaderFrame.setFrameStyle( QFrame.StyledPanel )
        logHeaderFrame.setAutoFillBackground( True )
        self.__setLightPalette( logHeaderFrame )
        logHeaderFrame.setFixedHeight( 24 )

        logHeaderLayout = QHBoxLayout()
        logHeaderLayout.setContentsMargins( 3, 0, 0, 0 )
        logHeaderLayout.addWidget( QLabel( "Subversion log of " + self.__path ) )
        logHeaderFrame.setLayout( logHeaderLayout )
        vboxLayout.addWidget( logHeaderFrame )

        self.__logView = QTreeWidget()
        self.__logView.setAlternatingRowColors( True )
        self.__logView.setRootIsDecorated( False )
        self.__logView.setItemsExpandable( False )
        self.__logView.setSortingEnabled( True )
        self.__logView.setItemDelegate( NoOutlineHeightDelegate( 4 ) )

        self.__logViewHeader = QTreeWidgetItem( [ "", "", "Revision", "Date",
                                                  "Author", "Message" ] )
        self.__logView.setHeaderItem( self.__logViewHeader )
        self.__logView.header().setSortIndicator( REVISION_COL, Qt.AscendingOrder )
        self.__logView.itemChanged.connect( self.__onLogViewChanged )
        vboxLayout.addWidget( self.__logView )


        # Diff part
        diffHeaderFrame = QFrame()
        diffHeaderFrame.setFrameStyle( QFrame.StyledPanel )
        diffHeaderFrame.setAutoFillBackground( True )
        self.__setLightPalette( diffHeaderFrame )
        diffHeaderFrame.setFixedHeight( 24 )

        diffLabel = QLabel( "Diff" )
        diffExpandingSpacer = QSpacerItem( 10, 10, QSizePolicy.Expanding )

        self.__showHideDiffButton = QToolButton()
        self.__showHideDiffButton.setAutoRaise( True )
        self.__showHideDiffButton.setIcon( PixmapCache().getIcon( 'less.png' ) )
        self.__showHideDiffButton.setFixedSize( 20, 20 )
        self.__showHideDiffButton.setToolTip( "Show diff" )
        self.__showHideDiffButton.setFocusPolicy( Qt.NoFocus )
        self.__showHideDiffButton.clicked.connect( self.__onShowHideDiff )

        diffLayout = QHBoxLayout()
        diffLayout.setContentsMargins( 3, 0, 0, 0 )
        diffLayout.addWidget( diffLabel )
        diffLayout.addSpacerItem( diffExpandingSpacer )
        diffLayout.addWidget( self.__showHideDiffButton )
        diffHeaderFrame.setLayout( diffLayout )

        self.__diffViewer = DiffTabWidget()
        self.__diffViewer.setHTML( self.NODIFF )
        self.__diffViewer.setVisible( False )

        vboxLayout.addWidget( diffHeaderFrame )
        vboxLayout.addWidget( self.__diffViewer )

        # Buttons at the bottom
        buttonBox = QDialogButtonBox( self )
        buttonBox.setOrientation( Qt.Horizontal )
        buttonBox.setStandardButtons( QDialogButtonBox.Ok )
        buttonBox.button( QDialogButtonBox.Ok ).setDefault( True )
        buttonBox.accepted.connect( self.close )
        vboxLayout.addWidget( buttonBox )
        return
Example #44
0
class ColumnsDialog(QDialog):
    """"""

    #----------------------------------------------------------------------
    def __init__(self,
                 full_column_name_list,
                 init_selected_colum_name_list,
                 permanently_selected_column_name_list,
                 parentWindow=None):
        """Constructor"""

        QDialog.__init__(self, parent=parentWindow)

        self.setWindowFlags(
            QtCore.Qt.Window)  # To add Maximize & Minimize buttons

        self.setWindowTitle('Column Visibility/Order')

        self.verticalLayout = QVBoxLayout(self)

        widget = QWidget(self)
        self.visible_column_order_selector = OrderSelector(
            parentWidget=widget,
            full_string_list=full_column_name_list,
            init_selected_string_list=init_selected_colum_name_list,
            permanently_selected_string_list=
            permanently_selected_column_name_list,
            label_text_NotSelected='NOT Visible Column Names:',
            label_text_Selected='Visible Column Names:')
        self.verticalLayout.addWidget(widget)

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        self.verticalLayout.addWidget(self.buttonBox)

        self.output = None

        self.connect(self.buttonBox, SIGNAL('accepted()'), self.accept)
        self.connect(self.buttonBox, SIGNAL('rejected()'), self.reject)

    #----------------------------------------------------------------------
    def closeEvent(self, event):
        """"""

        self.output = None

        event.accept()

    #----------------------------------------------------------------------
    def accept(self):
        """"""

        selected_listView = self.visible_column_order_selector.view.listView_Selected
        SMod = selected_listView.model()
        self.output = [
            SMod.item(row_ind, 0).text() for row_ind in range(SMod.rowCount())
        ]

        super(ColumnsDialog, self).accept()

    #----------------------------------------------------------------------
    def reject(self):
        """"""

        self.output = None

        super(ColumnsDialog, self).reject()
Example #45
0
    def __init__(self):
        ' make a diff method with GUI '
        self.dialog = QDialog()
        self.diff_path = None

        # directory auto completer
        self.completer = QCompleter(self.dialog)
        self.dirs = QDirModel(self.dialog)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)
        #self.completer.setCompletionMode(QCompleter.InlineCompletion)

        self.group1 = QGroupBox()
        self.group1.setTitle('Diff')
        self.frmt = QComboBox(self.group1)
        self.frmt.addItems(['Unified', 'Normal', 'Context'])
        self.file1 = QLineEdit()
        self.file1.setPlaceholderText('/full/path/to/one_file.py')
        self.file1.setCompleter(self.completer)
        self.file2 = QLineEdit()
        self.file2.setPlaceholderText('/full/path/to/another_file.py')
        self.file2.setCompleter(self.completer)
        self.fout = QLineEdit()
        self.fout.setText(''.join((path.join(gettempdir(),
                     datetime.now().strftime('%d-%b-%Y_%H:%M:%S.diff')))))
        self.fout.setPlaceholderText('/full/path/to/output_file.diff')
        self.fout.setCompleter(self.completer)
        self.regex = QLineEdit()
        self.regex.setPlaceholderText('DONT use unless you know what are doing')
        self.regex.setToolTip('Do NOT use unless you know what you are doing !')
        self.borig = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.borig.clicked.connect(lambda: self.file1.setText(str(
            QFileDialog.getOpenFileName(self.dialog, 'Open file to compare',
                                           path.expanduser("~"), ';;(*.*)'))))

        self.bmodi = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.bmodi.clicked.connect(lambda: self.file2.setText(str(
            QFileDialog.getOpenFileName(self.dialog, 'Open file to compare',
                                           path.expanduser("~"), ';;(*.*)'))))
        self.bout = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.bout.clicked.connect(lambda: self.fout.setText(str(
            QFileDialog.getSaveFileName(self.dialog, 'Save a Diff file',
                                        path.expanduser("~"), ';;(*.diff)'))))
        vboxg1 = QVBoxLayout(self.group1)
        for each_widget in (QLabel('Original file full path'),
                            self.file1, self.borig,
                            QLabel('Modified file full path'),
                            self.file2, self.bmodi,
                            QLabel('Output file full Path'),
                            self.fout, self.bout,
                            QLabel('Diff Output Format'), self.frmt,
                            QLabel('Diff REGEX to Ignore (ADVANCED)'),
                            self.regex):
            vboxg1.addWidget(each_widget)

        self.group2 = QGroupBox()
        self.group2.setTitle('Options')
        self.nwfl = QCheckBox('Treat new files as Empty')
        self.smll = QCheckBox('Look for smaller changes')
        self.lrgf = QCheckBox('Optimize for large files')
        self.case = QCheckBox('Ignore case changes on content')
        self.cnvt = QCheckBox('Convert Tabs to Spaces')
        self.blnk = QCheckBox('Ignore added or removed Blank lines')
        self.spac = QCheckBox('Ignore changes in amount of Spaces')
        self.whit = QCheckBox('Ignore ALL white Spaces')
        self.tabz = QCheckBox('Ignore changes by Tab expansions')
        self.sprs = QCheckBox('Remove Space or Tab before empty lines')
        self.filn = QCheckBox('Ignore case when comparing file names')
        self.tbs = QComboBox(self.group2)
        self.tbs.addItems(['4', '6', '8', '10', '2'])
        self.nice = QComboBox(self.group2)
        self.nice.addItems(['20', '15', '10', '5', '0'])
        vboxg2 = QVBoxLayout(self.group2)
        for each_widget in (self.nwfl, self.smll, self.lrgf, self.case,
                            self.cnvt, self.blnk, self.spac, self.whit,
                            self.tabz, self.sprs, self.filn,
                            QLabel('Diff Tabs-to-Spaces Size'), self.tbs,
                            QLabel('Diff Backend CPU Priority'), self.nice):
            vboxg2.addWidget(each_widget)
            try:
                each_widget.setToolTip(each_widget.text())
            except:
                each_widget.setToolTip(each_widget.currentText())
            each_widget.setCursor(QCursor(Qt.PointingHandCursor))

        group3 = QGroupBox()
        group3.setTitle('Even More Options')
        self.plai = QCheckBox('Force treat all files as plain text')
        self.nocr = QCheckBox('Force strip trailing carriage return')
        self.ridt = QCheckBox('Report when two files are identical')
        self.nocm = QCheckBox('Do not output common lines')
        self.rdif = QCheckBox('Report only when files differ')
        self.clip = QCheckBox('Copy Diff to Clipboard when done')
        self.noti = QCheckBox('Use system Notification when done')
        self.pret = QCheckBox('Align all Tabs by prepending a Tab')
        self.lolz = QCheckBox('Output Diff in two equal columns')
        self.odif = QCheckBox('Open Diff with Ninja-IDE when done')
        self.plac = QCheckBox('Make an Awesome Diff view when done')
        self.wdth = QComboBox(group3)
        self.wdth.addItems(['80', '100', '120', '130', '250', '500', '999999'])
        self.bcknd = QComboBox(group3)
        self.bcknd.addItems(['diff', 'diff.py'])
        self.bcknd.setDisabled(True)  #TODO this feature needs work
        vboxg3 = QVBoxLayout(group3)
        for each_widget in (self.plai, self.nocr, self.ridt, self.nocm,
                            self.rdif, self.pret, self.clip, self.noti,
                            self.lolz, self.odif, self.plac,
                            QLabel('Diff Maximum Total Width'), self.wdth,
                            QLabel('Diff Backend (EXPERIMENTAL)'), self.bcknd):
            vboxg3.addWidget(each_widget)
            try:
                each_widget.setToolTip(each_widget.text())
            except:
                each_widget.setToolTip(each_widget.currentText())
            each_widget.setCursor(QCursor(Qt.PointingHandCursor))

        for widget_should_be_checked in (self.nwfl, self.smll, self.lrgf,
                                   self.clip, self.cnvt, self.plai, self.noti):
            widget_should_be_checked.setChecked(True)

        container = QWidget()
        hbox = QHBoxLayout(container)
        for each_widget in (self.group2, self.group1, group3):
            hbox.addWidget(each_widget)

        buttons = QDialogButtonBox()
        buttons.resize(self.dialog.size().width(), buttons.size().height() * 2)
        buttons.setOrientation(Qt.Horizontal)
        buttons.setStandardButtons(
            QDialogButtonBox.Ok |
            QDialogButtonBox.Cancel |
            QDialogButtonBox.Close |
            QDialogButtonBox.Help)
        buttons.setCenterButtons(False)
        buttons.helpRequested.connect(lambda: QMessageBox.about(
            self.dialog, __doc__,
            ''.join((__doc__, ' GUI and Visualizer Plugin,', linesep,
            'version ', __version__, ', (', __license__, '), by ', linesep,
            __author__, ', ( ', __email__, ' ).', linesep))))
        buttons.rejected.connect(self.dialog.close)
        buttons.accepted.connect(self.make_diff)

        info = QLabel(''.join(('<b> Current Backend Diff Engine: </b>',
                      getoutput('diff --version').split(linesep)[0])))

        vbox = QVBoxLayout(self.dialog)
        for each_widget in (
                QLabel('<center><h2> Ninja IDE Diff and Patch </h2></center>'),
                container, info, buttons):
            vbox.addWidget(each_widget)

        self.dialog.resize(1024, self.dialog.size().height())
        self.dialog.exec_()
Example #46
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)
Example #47
0
class PreferencesPanel(QDialog):
    def __init__(self, parent, app):
        # The flags we pass are that so we don't get the "What's this" button in the title bar
        QDialog.__init__(self, parent, Qt.WindowTitleHint | Qt.WindowSystemMenuHint)
        self.app = app
        self._setupUi()

        self.dateFormatEdit.editingFinished.connect(self.dateFormatEdited)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

    def _setupUi(self):
        self.setWindowTitle(tr("Preferences"))
        self.resize(332, 170)
        self.verticalLayout = QVBoxLayout(self)
        self.formLayout = QFormLayout()

        self.autoSaveIntervalSpinBox = QSpinBox(self)
        self.autoSaveIntervalSpinBox.setMaximumSize(QSize(70, 0xffffff))
        self.label_5 = QLabel(tr("minute(s) (0 for none)"), self)
        self.formLayout.addRow(
            tr("Auto-save interval:"),
            horizontalWrap([self.autoSaveIntervalSpinBox, self.label_5])
        )

        self.dateFormatEdit = QLineEdit(self)
        self.dateFormatEdit.setMaximumSize(QSize(140, 0xffffff))
        self.formLayout.addRow(tr("Date format:"), self.dateFormatEdit)

        self.fontSizeSpinBox = QSpinBox()
        self.fontSizeSpinBox.setMinimum(5)
        self.fontSizeSpinBox.setMaximumSize(QSize(70, 0xffffff))
        self.formLayout.addRow(tr("Font size:"), self.fontSizeSpinBox)

        self.languageComboBox = QComboBox(self)
        for lang in SUPPORTED_LANGUAGES:
            self.languageComboBox.addItem(LANGNAMES[lang])
        self.languageComboBox.setMaximumSize(QSize(140, 0xffffff))
        self.formLayout.addRow(tr("Language:"), self.languageComboBox)
        self.verticalLayout.addLayout(self.formLayout)

        self.scopeDialogCheckBox = QCheckBox(tr("Show scope dialog when modifying a scheduled transaction"), self)
        self.verticalLayout.addWidget(self.scopeDialogCheckBox)
        self.autoDecimalPlaceCheckBox = QCheckBox(tr("Automatically place decimals when typing"), self)
        self.verticalLayout.addWidget(self.autoDecimalPlaceCheckBox)
        self.debugModeCheckBox = QCheckBox(tr("Debug mode (restart required)"), self)
        self.verticalLayout.addWidget(self.debugModeCheckBox)
        self.verticalLayout.addItem(verticalSpacer())
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok)
        self.verticalLayout.addWidget(self.buttonBox)

    def load(self):
        appm = self.app.model
        self.autoSaveIntervalSpinBox.setValue(appm.autosave_interval)
        self.dateFormatEdit.setText(self.app.prefs.dateFormat)
        self.fontSizeSpinBox.setValue(self.app.prefs.tableFontSize)
        self.scopeDialogCheckBox.setChecked(appm.show_schedule_scope_dialog)
        self.autoDecimalPlaceCheckBox.setChecked(appm.auto_decimal_place)
        self.debugModeCheckBox.setChecked(self.app.prefs.debugMode)
        try:
            langindex = SUPPORTED_LANGUAGES.index(self.app.prefs.language)
        except ValueError:
            langindex = 0
        self.languageComboBox.setCurrentIndex(langindex)

    def save(self):
        restartRequired = False
        appm = self.app.model
        appm.autosave_interval = self.autoSaveIntervalSpinBox.value()
        if self.dateFormatEdit.text() != self.app.prefs.dateFormat:
            restartRequired = True
        self.app.prefs.dateFormat = self.dateFormatEdit.text()
        self.app.prefs.tableFontSize = self.fontSizeSpinBox.value()
        appm.show_schedule_scope_dialog = self.scopeDialogCheckBox.isChecked()
        appm.auto_decimal_place = self.autoDecimalPlaceCheckBox.isChecked()
        self.app.prefs.debugMode = self.debugModeCheckBox.isChecked()
        lang = SUPPORTED_LANGUAGES[self.languageComboBox.currentIndex()]
        oldlang = self.app.prefs.language
        if oldlang not in SUPPORTED_LANGUAGES:
            oldlang = 'en'
        if lang != oldlang:
            restartRequired = True
        self.app.prefs.language = lang
        if restartRequired:
            QMessageBox.information(self, "", tr("moneyGuru has to restart for these changes to take effect"))

    #--- Signals
    def dateFormatEdited(self):
        self.dateFormatEdit.setText(clean_format(self.dateFormatEdit.text()))
class TransactionPanel(Panel):
    FIELDS = [
        ("dateEdit", "date"),
        ("descriptionEdit", "description"),
        ("payeeEdit", "payee"),
        ("checkNoEdit", "checkno"),
        ("notesEdit", "notes"),
    ]

    def __init__(self, mainwindow):
        Panel.__init__(self, mainwindow)
        self.mainwindow = mainwindow
        self.model = mainwindow.model.transaction_panel
        self._setupUi()
        self.model.view = self
        self.splitTable = SplitTable(model=self.model.split_table, view=self.splitTableView)

        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        self.mctButton.clicked.connect(self.model.mct_balance)
        self.addSplitButton.clicked.connect(self.splitTable.model.add)
        self.removeSplitButton.clicked.connect(self.splitTable.model.delete)

    def _setupUi(self):
        self.setWindowTitle(tr("Transaction Info"))
        self.resize(462, 329)
        self.setModal(True)
        self.mainLayout = QVBoxLayout(self)
        self.tabWidget = QTabWidget(self)
        self.infoTab = QWidget()
        self.infoLayout = QVBoxLayout(self.infoTab)
        self.formLayout = QFormLayout()
        self.formLayout.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow)
        self.dateEdit = DateEdit(self.infoTab)
        self.dateEdit.setMaximumSize(QSize(120, 16777215))
        self.formLayout.addRow(tr("Date:"), self.dateEdit)
        self.descriptionEdit = DescriptionEdit(self.model.completable_edit, self.infoTab)
        self.formLayout.addRow(tr("Description:"), self.descriptionEdit)
        self.payeeEdit = PayeeEdit(self.model.completable_edit, self.infoTab)
        self.formLayout.addRow(tr("Payee:"), self.payeeEdit)
        self.checkNoEdit = QLineEdit(self.infoTab)
        self.checkNoEdit.setMaximumSize(QSize(120, 16777215))
        self.formLayout.addRow(tr("Check #:"), self.checkNoEdit)
        self.infoLayout.addLayout(self.formLayout)
        self.amountLabel = QLabel(tr("Transfers:"), self.infoTab)
        self.infoLayout.addWidget(self.amountLabel)
        self.splitTableView = TableView(self.infoTab)
        self.splitTableView.setAcceptDrops(True)
        self.splitTableView.setEditTriggers(QAbstractItemView.DoubleClicked | QAbstractItemView.EditKeyPressed)
        self.splitTableView.setDragEnabled(True)
        self.splitTableView.setDragDropMode(QAbstractItemView.InternalMove)
        self.splitTableView.setSelectionMode(QAbstractItemView.SingleSelection)
        self.splitTableView.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.splitTableView.horizontalHeader().setDefaultSectionSize(40)
        self.splitTableView.verticalHeader().setVisible(False)
        self.splitTableView.verticalHeader().setDefaultSectionSize(18)
        self.infoLayout.addWidget(self.splitTableView)
        self.mctButtonsLayout = QHBoxLayout()
        self.mctButtonsLayout.setMargin(0)
        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.mctButtonsLayout.addItem(spacerItem)
        self.mctButton = QPushButton(tr("Multi-currency balance"), self.infoTab)
        self.mctButtonsLayout.addWidget(self.mctButton)
        self.addSplitButton = QPushButton(self.infoTab)
        icon = QIcon()
        icon.addPixmap(QPixmap(":/plus_8"), QIcon.Normal, QIcon.Off)
        self.addSplitButton.setIcon(icon)
        self.mctButtonsLayout.addWidget(self.addSplitButton)
        self.removeSplitButton = QPushButton(self.infoTab)
        icon1 = QIcon()
        icon1.addPixmap(QPixmap(":/minus_8"), QIcon.Normal, QIcon.Off)
        self.removeSplitButton.setIcon(icon1)
        self.mctButtonsLayout.addWidget(self.removeSplitButton)
        self.infoLayout.addLayout(self.mctButtonsLayout)
        self.tabWidget.addTab(self.infoTab, tr("Info"))
        self.notesTab = QWidget()
        self.notesLayout = QVBoxLayout(self.notesTab)
        self.notesEdit = QPlainTextEdit(self.notesTab)
        self.notesLayout.addWidget(self.notesEdit)
        self.tabWidget.addTab(self.notesTab, tr("Notes"))
        self.tabWidget.setCurrentIndex(0)
        self.mainLayout.addWidget(self.tabWidget)
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Save)
        self.mainLayout.addWidget(self.buttonBox)

    def _loadFields(self):
        Panel._loadFields(self)
        self.tabWidget.setCurrentIndex(0)

    # --- model --> view
    def refresh_for_multi_currency(self):
        self.mctButton.setEnabled(self.model.is_multi_currency)
Example #49
0
class ModelerParametersDialog(QDialog):

    ENTER_NAME = '[Enter name if this is a final result]'
    NOT_SELECTED = '[Not selected]'
    USE_MIN_COVERING_EXTENT = '[Use min covering extent]'

    def __init__(self, alg, model, algName=None):
        QDialog.__init__(self)
        self.setModal(True)
        #The algorithm to define in this dialog. It is an instance of GeoAlgorithm
        self._alg = alg
        #The resulting algorithm after the user clicks on OK. it is an instance of the container Algorithm class
        self.alg = None
        #The model this algorithm is going to be added to
        self.model = model
        #The name of the algorithm in the model, in case we are editing it and not defining it for the first time
        self._algName = algName
        self.setupUi()
        self.params = None

    def setupUi(self):
        self.labels = {}
        self.widgets = {}
        self.checkBoxes = {}
        self.showAdvanced = False
        self.valueItems = {}
        self.dependentItems = {}
        self.resize(650, 450)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        tooltips = self._alg.getParameterDescriptions()
        self.setSizePolicy(QSizePolicy.Expanding,
                           QSizePolicy.Expanding)
        self.verticalLayout = QVBoxLayout()
        self.verticalLayout.setSpacing(5)
        self.verticalLayout.setMargin(20)

        hLayout = QHBoxLayout()
        hLayout.setSpacing(5)
        hLayout.setMargin(0)
        descriptionLabel = QLabel(self.tr("Description"))
        self.descriptionBox = QLineEdit()
        self.descriptionBox.setText(self._alg.name)
        hLayout.addWidget(descriptionLabel)
        hLayout.addWidget(self.descriptionBox)
        self.verticalLayout.addLayout(hLayout)
        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)
        self.verticalLayout.addWidget(line)

        for param in self._alg.parameters:
            if param.isAdvanced:
                self.advancedButton = QPushButton()
                self.advancedButton.setText(self.tr('Show advanced parameters'))
                self.advancedButton.setMaximumWidth(150)
                self.advancedButton.clicked.connect(
                    self.showAdvancedParametersClicked)
                self.verticalLayout.addWidget(self.advancedButton)
                break
        for param in self._alg.parameters:
            if param.hidden:
                continue
            desc = param.description
            if isinstance(param, ParameterExtent):
                desc += '(xmin, xmax, ymin, ymax)'
            label = QLabel(desc)
            self.labels[param.name] = label
            widget = self.getWidgetFromParameter(param)
            self.valueItems[param.name] = widget
            if param.name in tooltips.keys():
                tooltip = tooltips[param.name]
            else:
                tooltip = param.description
            label.setToolTip(tooltip)
            widget.setToolTip(tooltip)
            if param.isAdvanced:
                label.setVisible(self.showAdvanced)
                widget.setVisible(self.showAdvanced)
                self.widgets[param.name] = widget
            self.verticalLayout.addWidget(label)
            self.verticalLayout.addWidget(widget)

        for output in self._alg.outputs:
            if output.hidden:
                continue
            if isinstance(output, (OutputRaster, OutputVector, OutputTable,
                          OutputHTML, OutputFile, OutputDirectory)):
                label = QLabel(output.description + '<'
                               + output.__class__.__name__ + '>')
                item = QLineEdit()
                if hasattr(item, 'setPlaceholderText'):
                    item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME)
                self.verticalLayout.addWidget(label)
                self.verticalLayout.addWidget(item)
                self.valueItems[output.name] = item

        label = QLabel(' ')
        self.verticalLayout.addWidget(label)
        label = QLabel(self.tr('Parent algorithms'))
        self.dependenciesPanel = self.getDependenciesPanel()
        self.verticalLayout.addWidget(label)
        self.verticalLayout.addWidget(self.dependenciesPanel)

        self.verticalLayout.addStretch(1000)
        self.setLayout(self.verticalLayout)

        self.setPreviousValues()
        self.setWindowTitle(self._alg.name)
        self.verticalLayout2 = QVBoxLayout()
        self.verticalLayout2.setSpacing(2)
        self.verticalLayout2.setMargin(0)
        self.tabWidget = QTabWidget()
        self.tabWidget.setMinimumWidth(300)
        self.paramPanel = QWidget()
        self.paramPanel.setLayout(self.verticalLayout)
        self.scrollArea = QScrollArea()
        self.scrollArea.setWidget(self.paramPanel)
        self.scrollArea.setWidgetResizable(True)
        self.tabWidget.addTab(self.scrollArea, self.tr('Parameters'))
        self.webView = QWebView()

        html = None
        url = None
        isText, help = self._alg.help()
        if help is not None:
            if isText:
                html = help
            else:
                url = QUrl(help)
        else:
            html = self.tr('<h2>Sorry, no help is available for this '
                           'algorithm.</h2>')
        try:
            if html:
                self.webView.setHtml(html)
            elif url:
                self.webView.load(url)
        except:
            self.webView.setHtml(self.tr('<h2>Could not open help file :-( </h2>'))
        self.tabWidget.addTab(self.webView, 'Help')
        self.verticalLayout2.addWidget(self.tabWidget)
        self.verticalLayout2.addWidget(self.buttonBox)
        self.setLayout(self.verticalLayout2)
        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)
        QMetaObject.connectSlotsByName(self)

    def getAvailableDependencies(self):
        if self._algName is None:
            dependent = []
        else:
            dependent = self.model.getDependentAlgorithms(self._algName)
        opts = []
        for alg in self.model.algs.values():
            if alg.name not in dependent:
                opts.append(alg)
        return opts

    def getDependenciesPanel(self):
        return MultipleInputPanel([alg.algorithm.name for alg in self.getAvailableDependencies()])

    def showAdvancedParametersClicked(self):
        self.showAdvanced = not self.showAdvanced
        if self.showAdvanced:
            self.advancedButton.setText(self.tr('Hide advanced parameters'))
        else:
            self.advancedButton.setText(self.tr('Show advanced parameters'))
        for param in self._alg.parameters:
            if param.isAdvanced:
                self.labels[param.name].setVisible(self.showAdvanced)
                self.widgets[param.name].setVisible(self.showAdvanced)

    def getAvailableValuesOfType(self, paramType, outType=None):
        values = []
        inputs = self.model.inputs
        for i in inputs.values():
            param = i.param
            if isinstance(param, paramType):
                values.append(ValueFromInput(param.name))
        if outType is None:
            return values
        if self._algName is None:
            dependent = []
        else:
            dependent = self.model.getDependentAlgorithms(self._algName)
        for alg in self.model.algs.values():
            if alg.name not in dependent:
                for out in alg.algorithm.outputs:
                    if isinstance(out, outType):
                        values.append(ValueFromOutput(alg.name, out.name))

        return values

    def resolveValueDescription(self, value):
        if isinstance(value, ValueFromInput):
            return self.model.inputs[value.name].param.description
        else:
            alg = self.model.algs[value.alg]
            return self.tr("'%s' from algorithm '%s'") % (alg.algorithm.getOutputFromName(value.output).description, alg.description)

    def getWidgetFromParameter(self, param):
        if isinstance(param, ParameterRaster):
            item = QComboBox()
            layers = self.getAvailableValuesOfType(ParameterRaster, OutputRaster)
            if param.optional:
                item.addItem(self.NOT_SELECTED, None)
            for layer in layers:
                item.addItem(self.resolveValueDescription(layer), layer)
        elif isinstance(param, ParameterVector):
            item = QComboBox()
            layers = self.getAvailableValuesOfType(ParameterVector, OutputVector)
            if param.optional:
                item.addItem(self.NOT_SELECTED, None)
            for layer in layers:
                item.addItem(self.resolveValueDescription(layer), layer)
        elif isinstance(param, ParameterTable):
            item = QComboBox()
            tables = self.getAvailableValuesOfType(ParameterTable, OutputTable)
            layers = self.getAvailableValuesOfType(ParameterVector, OutputVector)
            if param.optional:
                item.addItem(self.NOT_SELECTED, None)
            for table in tables:
                item.addItem(self.resolveValueDescription(table), table)
            for layer in layers:
                item.addItem(self.resolveValueDescription(layer), layer)
        elif isinstance(param, ParameterBoolean):
            item = QComboBox()
            item.addItem('Yes')
            item.addItem('No')
            bools = self.getAvailableValuesOfType(ParameterBoolean, None)
            for b in bools:
                item.addItem(self.resolveValueDescription(b), b)
        elif isinstance(param, ParameterSelection):
            item = QComboBox()
            item.addItems(param.options)
            item.setCurrentIndex(param.default)
        elif isinstance(param, ParameterFixedTable):
            item = FixedTablePanel(param)
        elif isinstance(param, ParameterRange):
            item = RangePanel(param)
        elif isinstance(param, ParameterMultipleInput):
            if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
                options = self.getAvailableValuesOfType(ParameterVector, OutputVector)
            else:
                options = self.getAvailableValuesOfType(ParameterRaster, OutputRaster)
            opts = []
            for opt in options:
                opts.append(self.resolveValueDescription(opt))
            item = MultipleInputPanel(opts)
        elif isinstance(param, ParameterString):
            strings = self.getAvailableValuesOfType(ParameterString, OutputString)
            options = [(self.resolveValueDescription(s), s) for s in strings]
            if param.multiline:
                item = MultilineTextPanel(options)
                item.setText(unicode(param.default))
            else:
                item = QComboBox()
                item.setEditable(True)
                for desc, val in options:
                    item.addItem(desc, val)
                item.setEditText(unicode(param.default))
        elif isinstance(param, ParameterTableField):
            item = QComboBox()
            item.setEditable(True)
            fields = self.getAvailableValuesOfType(ParameterTableField, None)
            for f in fields:
                item.addItem(self.resolveValueDescription(f), f)
        elif isinstance(param, ParameterNumber):
            item = QComboBox()
            item.setEditable(True)
            numbers = self.getAvailableValuesOfType(ParameterNumber, OutputNumber)
            for n in numbers:
                item.addItem(self.resolveValueDescription(n), n)
            item.setEditText(unicode(param.default))
        elif isinstance(param, ParameterCrs):
            item = CrsSelectionPanel(param.default)
        elif isinstance(param, ParameterExtent):
            item = QComboBox()
            item.setEditable(True)
            extents = self.getAvailableValuesOfType(ParameterExtent, OutputExtent)
            if self.canUseAutoExtent():
                item.addItem(self.USE_MIN_COVERING_EXTENT, None)
            for ex in extents:
                item.addItem(self.resolveValueDescription(ex), ex)
            if not self.canUseAutoExtent():
                item.setEditText(unicode(param.default))
        elif isinstance(param, ParameterFile):
            item = QComboBox()
            item.setEditable(True)
            files = self.getAvailableValuesOfType(ParameterFile, OutputFile)
            for f in files:
                item.addItem(self.resolveValueDescription(f), f)
        elif isinstance(param, ParameterGeometryPredicate):
            item = GeometryPredicateSelectionPanel(param.enabledPredicates)
        else:
            item = QLineEdit()
            try:
                item.setText(unicode(param.default))
            except:
                pass
        return item

    def canUseAutoExtent(self):
        for param in self._alg.parameters:
            if isinstance(param, (ParameterRaster, ParameterVector, ParameterMultipleInput)):
                return True
        return False

    def setTableContent(self):
        params = self._alg.parameters
        outputs = self._alg.outputs
        visibleParams = [p for p in params if not p.hidden]
        visibleOutputs = [p for o in outputs if not o.hidden]
        self.tableWidget.setRowCount(len(visibleParams) + len(visibleOutputs))

        for i, param in visibleParams:
            item = QTableWidgetItem(param.description)
            item.setFlags(Qt.ItemIsEnabled)
            self.tableWidget.setItem(i, 0, item)
            item = self.getWidgetFromParameter(param)
            self.valueItems[param.name] = item
            self.tableWidget.setCellWidget(i, 1, item)
            self.tableWidget.setRowHeight(i, 22)

        for i, output in visibleOutputs:
            item = QTableWidgetItem(output.description + '<'
                                    + output.__module__.split('.')[-1] + '>')
            item.setFlags(Qt.ItemIsEnabled)
            self.tableWidget.setItem(i, 0, item)
            item = QLineEdit()
            if hasattr(item, 'setPlaceholderText'):
                item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME)
            self.valueItems[output.name] = item
            self.tableWidget.setCellWidget(i, 1, item)
            self.tableWidget.setRowHeight(i, 22)

    def setComboBoxValue(self, combo, value, param):
        if isinstance(value, list):
            value = value[0]
        items = [combo.itemData(i) for i in range(combo.count())]
        try:
            idx = items.index(value)
            combo.setCurrentIndex(idx)
            return
        except ValueError:
            pass
        if combo.isEditable():
            if value is not None:
                combo.setEditText(unicode(value))
        elif isinstance(param, ParameterSelection):
            combo.setCurrentIndex(int(value))
        elif isinstance(param, ParameterBoolean):
            if value:
                combo.setCurrentIndex(0)
            else:
                combo.setCurrentIndex(1)

    def setPreviousValues(self):
        if self._algName is not None:
            alg = self.model.algs[self._algName]
            self.descriptionBox.setText(alg.description)
            for param in alg.algorithm.parameters:
                if param.hidden:
                    continue
                widget = self.valueItems[param.name]
                if param.name in alg.params:
                    value = alg.params[param.name]
                else:
                    value = None
                if isinstance(param, (
                        ParameterRaster,
                        ParameterVector,
                        ParameterTable,
                        ParameterTableField,
                        ParameterSelection,
                        ParameterNumber,
                        ParameterBoolean,
                        ParameterExtent,
                        ParameterFile
                )):
                    self.setComboBoxValue(widget, value, param)
                elif isinstance(param, ParameterString):
                    if param.multiline:
                        widget.setValue(value)
                    else:
                        self.setComboBoxValue(widget, value, param)
                elif isinstance(param, ParameterCrs):
                    widget.setAuthId(value)
                elif isinstance(param, ParameterFixedTable):
                    pass  # TODO!
                elif isinstance(param, ParameterMultipleInput):
                    if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
                        options = self.getAvailableValuesOfType(ParameterVector, OutputVector)
                    else:
                        options = self.getAvailableValuesOfType(ParameterRaster, OutputRaster)
                    selected = []
                    for i, opt in enumerate(options):
                        if opt in value:
                            selected.append(i)
                    widget.setSelectedItems(selected)
                elif isinstance(param, ParameterGeometryPredicate):
                    widget.setValue(value)

            for name, out in alg.outputs.iteritems():
                widget = self.valueItems[name].setText(out.description)

            selected = []
            dependencies = self.getAvailableDependencies()
            for idx, dependency in enumerate(dependencies):
                if dependency.name in alg.dependencies:
                    selected.append(idx)

            self.dependenciesPanel.setSelectedItems(selected)

    def createAlgorithm(self):
        alg = Algorithm(self._alg.commandLineName())
        alg.setName(self.model)
        alg.description = self.descriptionBox.text()
        params = self._alg.parameters
        outputs = self._alg.outputs
        for param in params:
            if param.hidden:
                continue
            if not self.setParamValue(alg, param, self.valueItems[param.name]):
                return None
        for output in outputs:
            if not output.hidden:
                name = unicode(self.valueItems[output.name].text())
                if name.strip() != '' and name != ModelerParametersDialog.ENTER_NAME:
                    alg.outputs[output.name] = ModelerOutput(name)

        selectedOptions = self.dependenciesPanel.selectedoptions
        availableDependencies = self.getAvailableDependencies()
        for selected in selectedOptions:
            alg.dependencies.append(availableDependencies[selected].name)

        return alg

    def setParamValueLayerOrTable(self, alg, param, widget):
        idx = widget.currentIndex()
        if idx < 0:
            return False
        else:
            value = widget.itemData(widget.currentIndex())
            alg.params[param.name] = value
            return True

    def setParamTableFieldValue(self, alg, param, widget):
        idx = widget.findText(widget.currentText())
        if idx < 0:
            s = unicode(widget.currentText()).strip()
            if s == '':
                if param.optional:
                    alg.params[param.name] = None
                    return True
                else:
                    return False
            else:
                alg.params[param.name] = s
                return True
        else:
            alg.params[param.name] = widget.itemData(widget.currentIndex())
        return True

    def setParamStringValue(self, alg, param, widget):
        if param.multiline:
            value = widget.getValue()
            option = widget.getOption()
            if option == MultilineTextPanel.USE_TEXT:
                if value == '':
                    if param.optional:
                        alg.params[param.name] = None
                        return True
                    else:
                        return False
                else:
                    alg.params[param.name] = value
            else:
                alg.params[param.name] = value
        else:
            idx = widget.findText(widget.currentText())
            if idx < 0:
                value = widget.currentText().strip()
                if value == '':
                    if param.optional:
                        alg.params[param.name] = None
                        return True
                    else:
                        return False
                else:
                    alg.params[param.name] = value
            else:
                alg.params[param.name] = widget.itemData(widget.currentIndex())
        return True

    def setParamFileValue(self, alg, param, widget):
        idx = widget.findText(widget.currentText())
        if idx < 0:
            value = widget.currentText()
        else:
            value = widget.itemData(widget.currentIndex())
        alg.params[param.name] = value
        return True

    def setParamNumberValue(self, alg, param, widget):
        idx = widget.findText(widget.currentText())
        if idx < 0:
            s = widget.currentText().strip()
            if s:
                try:
                    value = float(s)
                except:
                    return False
            elif param.optional:
                value = None
            else:
                return False
        else:
            value = widget.itemData(widget.currentIndex())
        alg.params[param.name] = value
        return True

    def setParamExtentValue(self, alg, param, widget):
        idx = widget.findText(widget.currentText())
        if idx < 0:
            s = unicode(widget.currentText()).strip()
            if s:
                try:
                    tokens = s.split(',')
                    if len(tokens) != 4:
                        return False
                    for token in tokens:
                        float(token)
                except:
                    return False
            elif param.optional:
                s = None
            else:
                return False
            alg.params[param.name] = [s]
        else:
            value = widget.itemData(widget.currentIndex())
            alg.params[param.name] = value
        return True

    def setParamValue(self, alg, param, widget):
        if isinstance(param, (ParameterRaster, ParameterVector,
                      ParameterTable)):
            return self.setParamValueLayerOrTable(alg, param, widget)
        elif isinstance(param, ParameterBoolean):
            if widget.currentIndex() < 2:
                value = widget.currentIndex() == 0
            else:
                value = widget.itemData(widget.currentIndex())
            alg.params[param.name] = value
            return True
        elif isinstance(param, ParameterString):
            return self.setParamStringValue(alg, param, widget)
        elif isinstance(param, ParameterNumber):
            return self.setParamNumberValue(alg, param, widget)
        elif isinstance(param, ParameterExtent):
            return self.setParamExtentValue(alg, param, widget)
        elif isinstance(param, ParameterFile):
            return self.setParamFileValue(alg, param, widget)
        elif isinstance(param, ParameterSelection):
            alg.params[param.name] = widget.currentIndex()
            return True
        elif isinstance(param, ParameterRange):
            alg.params[param.name] = widget.getValue()
            return True
        elif isinstance(param, ParameterCrs):
            authid = widget.getValue()
            if authid is None and not param.optional:
                return False
            alg.params[param.name] = authid
            return True
        elif isinstance(param, ParameterFixedTable):
            table = widget.table
            if not bool(table) and not param.optional:
                return False
            alg.params[param.name] = ParameterFixedTable.tableToString(table)
            return True
        elif isinstance(param, ParameterTableField):
            return self.setParamTableFieldValue(alg, param, widget)
        elif isinstance(param, ParameterMultipleInput):
            if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
                options = self.getAvailableValuesOfType(ParameterVector, OutputVector)
            else:
                options = self.getAvailableValuesOfType(ParameterRaster, OutputRaster)
            values = [options[i] for i in widget.selectedoptions]
            if len(values) == 0 and not param.optional:
                return False
            alg.params[param.name] = values
            return True
        elif isinstance(param, ParameterGeometryPredicate):
            alg.params[param.name] = widget.value()
            return True
        else:
            alg.params[param.name] = unicode(widget.text())
            return True

    def okPressed(self):
        self.alg = self.createAlgorithm()
        if self.alg is not None:
            self.close()
        else:
            QMessageBox.warning(self, self.tr('Unable to add algorithm'),
                                self.tr('Wrong or missing parameter values'))

    def cancelPressed(self):
        self.alg = None
        self.close()
Example #50
0
class CalculatorModelerParametersDialog(ModelerParametersDialog):
    def setupUi(self):
        self.valueItems = {}
        self.dependentItems = {}
        self.resize(650, 450)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        self.infoText = QTextEdit()
        numbers = self.getAvailableValuesOfType(ParameterNumber, OutputNumber)
        text = self.tr(
            'You can refer to model values in your formula, using '
            'single-letter variables, as follows:\n',
            'CalculatorModelerParametersDialog')
        ichar = 97
        if numbers:
            for number in numbers:
                text += chr(ichar) + '->' + self.resolveValueDescription(
                    number) + '\n'
                ichar += 1
        else:
            text += self.tr('\n - No numerical variables are available.',
                            'CalculatorModelerParametersDialog')
        self.infoText.setText(text)
        self.infoText.setEnabled(False)
        self.formulaText = QLineEdit()
        if hasattr(self.formulaText, 'setPlaceholderText'):
            self.formulaText.setPlaceholderText(
                self.tr('[Enter your formula here]',
                        'CalculatorModelerParametersDialog'))
        if self._algName is not None:
            alg = self.model.algs[self._algName]
            self.formulaText.setText(alg.params[FORMULA])
        self.setWindowTitle(
            self.tr('Calculator', 'CalculatorModelerParametersDialog'))
        self.verticalLayout = QVBoxLayout()
        self.verticalLayout.setSpacing(2)
        self.verticalLayout.setMargin(0)
        self.verticalLayout.addWidget(self.infoText)
        self.verticalLayout.addWidget(self.formulaText)
        self.verticalLayout.addWidget(self.buttonBox)
        self.setLayout(self.verticalLayout)
        QObject.connect(self.buttonBox, SIGNAL('accepted()'), self.okPressed)
        QObject.connect(self.buttonBox, SIGNAL('rejected()'),
                        self.cancelPressed)
        QMetaObject.connectSlotsByName(self)

    def createAlgorithm(self):
        alg = Algorithm('modelertools:calculator')
        alg.setName(self.model)
        alg.description = self.tr('Calculator',
                                  'CalculatorModelerParametersDialog')

        formula = self.formulaText.text()
        alg.params[FORMULA] = formula

        for i in xrange(AVAILABLE_VARIABLES):
            paramname = NUMBER + unicode(i)
            alg.params[paramname] = None

        numbers = self.getAvailableValuesOfType(ParameterNumber, OutputNumber)
        used = []
        for i in range(len(numbers)):
            if unicode(chr(i + 97)) in formula:
                used.append(numbers[i])

        for i, variable in enumerate(used):
            paramname = NUMBER + unicode(i)
            alg.params[paramname] = variable

        # TODO check formula is correct
        return alg
Example #51
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
Example #52
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
#     }
# }
Example #53
0
class LineCounterDialog( QDialog, object ):
    """ line counter dialog implementation """

    def __init__( self, fName = None, editor = None, parent = None ):

        QDialog.__init__( self, parent )

        self.__cancelRequest = False
        self.__inProgress = False
        if fName is not None:
            self.__fName = fName.strip()
        else:
            self.__fName = None
        self.__editor = editor
        self.__createLayout()
        self.setWindowTitle( "Line counter" )
        QTimer.singleShot( 0, self.__process )
        return

    def __createLayout( self ):
        """ Creates the dialog layout """

        self.resize( 450, 220 )
        self.setSizeGripEnabled( True )

        self.verticalLayout = QVBoxLayout( self )

        # Info label
        self.infoLabel = FitPathLabel( self )
        #sizePolicy = QSizePolicy( QSizePolicy.Expanding,
        #                          QSizePolicy.Preferred )
        sizePolicy = QSizePolicy( QSizePolicy.Minimum,
                                  QSizePolicy.Preferred )
        sizePolicy.setHorizontalStretch( 0 )
        sizePolicy.setVerticalStretch( 0 )
        sizePolicy.setHeightForWidth(
                    self.infoLabel.sizePolicy().hasHeightForWidth() )
        self.infoLabel.setSizePolicy( sizePolicy )
        self.verticalLayout.addWidget( self.infoLabel )

        # Progress bar
        self.progressBar = QProgressBar( self )
        self.progressBar.setValue( 0 )
        self.progressBar.setOrientation( Qt.Horizontal )
        self.verticalLayout.addWidget( self.progressBar )

        # Result window
        self.resultEdit = QTextEdit( self )
        self.resultEdit.setTabChangesFocus( False )
        self.resultEdit.setAcceptRichText( False )
        self.resultEdit.setReadOnly( True )
        self.resultEdit.setFontFamily( GlobalData().skin.baseMonoFontFace )
        font = self.resultEdit.font()

        # Calculate the vertical size
        fontMetrics = QFontMetrics( font )
        rect = fontMetrics.boundingRect( "W" )
        # 6 lines, 5 line spacings, 2 frames
        self.resultEdit.setMinimumHeight( rect.height() * 7 + 4 * 5 +
                                          self.resultEdit.frameWidth() * 2 )
        self.verticalLayout.addWidget( self.resultEdit )

        # Buttons
        self.buttonBox = QDialogButtonBox( self )
        self.buttonBox.setOrientation( Qt.Horizontal )
        self.buttonBox.setStandardButtons( QDialogButtonBox.Close )
        self.verticalLayout.addWidget( self.buttonBox )

        self.buttonBox.rejected.connect( self.__onClose )
        return

    def __scanDir( self, path, files ):
        " Recursively builds a list of python files "

        if path in self.__scannedDirs:
            return

        self.__scannedDirs.append( path )
        for item in os.listdir( path ):
            if os.path.isdir( path + item ):
                nestedDir = os.path.realpath( path + item )
                if not nestedDir.endswith( os.path.sep ):
                    nestedDir += os.path.sep
                self.__scanDir( nestedDir, files )
            else:
                candidate = os.path.realpath( path + item )
                if candidate.endswith( ".py" ) or \
                   candidate.endswith( ".py3" ) or \
                   candidate.endswith( ".pyw" ):
                    if not candidate in files:
                        files.append( candidate )
        return

    def __onClose( self ):
        " triggered when the close button is clicked "

        self.__cancelRequest = True
        if not self.__inProgress:
            self.close()
        return

    def __process( self ):
        " Accumulation process "

        self.__inProgress = True
        if self.__fName is not None:
            if os.path.exists( self.__fName ):
                if os.path.isdir( self.__fName ):
                    self.__fName = os.path.realpath( self.__fName )
                    if not self.__fName.endswith( os.path.sep ):
                        self.__fName += os.path.sep
                    files = []
                    self.__scannedDirs = []
                    QApplication.setOverrideCursor( QCursor( Qt.WaitCursor ) )
                    self.__scanDir( self.__fName, files )
                    QApplication.restoreOverrideCursor()
                else:
                    files = [ self.__fName ]
            else:
                files = []
        elif self.__editor is not None:
            files = [ "buffer" ]
        else:
            files = GlobalData().project.filesList
        self.progressBar.setRange( 0, len( files ) )

        accumulator = LinesCounter()
        current = LinesCounter()

        index = 1
        for fileName in files:

            if self.__cancelRequest:
                self.__inProgress = False
                self.close()
                return

            self.infoLabel.setPath( 'Processing: ' + fileName )

            processed = False
            if self.__editor is not None:
                current.getLinesInBuffer( self.__editor )
                processed = True
            else:
                if (fileName.endswith( '.py' ) or \
                    fileName.endswith( '.py3' ) or \
                    fileName.endswith( '.pyw' )) and \
                   os.path.exists( fileName ):
                    current.getLines( fileName )
                    processed = True

            if processed:
                accumulator.files += current.files
                accumulator.filesSize += current.filesSize
                accumulator.codeLines += current.codeLines
                accumulator.emptyLines += current.emptyLines
                accumulator.commentLines += current.commentLines
                accumulator.classes += current.classes

            self.progressBar.setValue( index )
            index += 1

            QApplication.processEvents()

        self.infoLabel.setPath( 'Done' )
        self.__inProgress = False

        # Update text in the text window
        nFiles = splitThousands( str( accumulator.files ) )
        filesSize = splitThousands( str( accumulator.filesSize ) )
        classes = splitThousands( str( accumulator.classes ) )
        codeLines = splitThousands( str( accumulator.codeLines ) )
        emptyLines = splitThousands( str( accumulator.emptyLines ) )
        commentLines = splitThousands( str( accumulator.commentLines ) )
        totalLines = splitThousands( str( accumulator.codeLines +
                                          accumulator.emptyLines +
                                          accumulator.commentLines ) )

        output = "Classes:                 " + classes + "\n" \
                 "Code lines:              " + codeLines + "\n" \
                 "Empty lines:             " + emptyLines + "\n" \
                 "Comment lines:           " + commentLines + "\n" \
                 "Total lines:             " + totalLines

        if self.__editor is None:
            output = "Number of python files:  " + nFiles + "\n" \
                     "Total files size:        " + filesSize + " bytes\n" + \
                     output
        else:
            output = "Number of characters:    " + filesSize + "\n" + \
                     output

        self.resultEdit.setText( output )
        return
Example #54
0
    def __createLayout(self):
        """ Creates the dialog layout """

        self.resize(700, 300)
        self.setSizeGripEnabled(True)

        layout = QVBoxLayout(self)
        gridLayout = QGridLayout()

        # Columns
        colsLabel = QLabel("Columns")
        self.__colsEdit = QLineEdit()
        self.__colsEdit.setText(str(self.__settings.settings["COL_LIMIT"]))
        self.__colsEdit.setToolTip(self.__settings.getDescription("COL_LIMIT"))
        self.__colsEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(colsLabel, 0, 0, 1, 1)
        gridLayout.addWidget(self.__colsEdit, 0, 1, 1, 1)
        font = self.__colsEdit.font()
        font.setFamily(GlobalData().skin.baseMonoFontFace)
        self.__colsEdit.setFont(font)

        # Assignment
        assignmentLabel = QLabel("Assignment")
        self.__assignmentEdit = QLineEdit()
        self.__assignmentEdit.setText(self.__settings.settings["ASSIGNMENT"])
        self.__assignmentEdit.setToolTip(
            self.__settings.getDescription("ASSIGNMENT"))
        self.__assignmentEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(assignmentLabel, 0, 3, 1, 1)
        gridLayout.addWidget(self.__assignmentEdit, 0, 4, 1, 1)
        self.__assignmentEdit.setFont(font)

        # Function parameters assignment
        funcAssignLabel = QLabel("Function params\nassignment")
        self.__funcAssignEdit = QLineEdit()
        self.__funcAssignEdit.setText(
            self.__settings.settings["FUNCTION_PARAM_ASSIGNMENT"])
        self.__funcAssignEdit.setToolTip(
            self.__settings.getDescription("FUNCTION_PARAM_ASSIGNMENT"))
        self.__funcAssignEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(funcAssignLabel, 1, 0, 1, 1)
        gridLayout.addWidget(self.__funcAssignEdit, 1, 1, 1, 1)
        self.__funcAssignEdit.setFont(font)

        # Dictionary separator
        dictSepLabel = QLabel("Dictionary separator")
        self.__dictSepEdit = QLineEdit()
        self.__dictSepEdit.setText(self.__settings.settings["DICT_COLON"])
        self.__dictSepEdit.setToolTip(
            self.__settings.getDescription("DICT_COLON"))
        self.__dictSepEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(dictSepLabel, 1, 3, 1, 1)
        gridLayout.addWidget(self.__dictSepEdit, 1, 4, 1, 1)
        self.__dictSepEdit.setFont(font)

        # Slice separator
        sliceSepLabel = QLabel("Slice separator")
        self.__sliceSepEdit = QLineEdit()
        self.__sliceSepEdit.setText(self.__settings.settings["SLICE_COLON"])
        self.__sliceSepEdit.setToolTip(
            self.__settings.getDescription("SLICE_COLON"))
        self.__sliceSepEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(sliceSepLabel, 2, 0, 1, 1)
        gridLayout.addWidget(self.__sliceSepEdit, 2, 1, 1, 1)
        self.__sliceSepEdit.setFont(font)

        # Interpreter
        inLabel = QLabel("Interpreter")
        self.__inEdit = QLineEdit()
        self.__inEdit.setText(self.__settings.settings["SHEBANG"])
        self.__inEdit.setToolTip(self.__settings.getDescription("SHEBANG"))
        self.__inEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(inLabel, 2, 3, 1, 1)
        gridLayout.addWidget(self.__inEdit, 2, 4, 1, 1)
        self.__inEdit.setFont(font)

        # Coding spec
        codingLabel = QLabel("Output encoding")
        self.__outCodingEdit = QLineEdit()
        self.__outCodingEdit.setText(self.__settings.settings["CODING"])
        self.__outCodingEdit.setToolTip(
            self.__settings.getDescription("CODING"))
        self.__outCodingEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(codingLabel, 3, 0, 1, 1)
        gridLayout.addWidget(self.__outCodingEdit, 3, 1, 1, 1)
        self.__outCodingEdit.setFont(font)

        # Src coding comment
        srcCodingLabel = QLabel("File encoding\ncomment")
        self.__srcCodingEdit = QLineEdit()
        self.__srcCodingEdit.setText(self.__settings.settings["CODING_SPEC"])
        self.__srcCodingEdit.setToolTip(
            self.__settings.getDescription("CODING_SPEC"))
        self.__srcCodingEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(srcCodingLabel, 3, 3, 1, 1)
        gridLayout.addWidget(self.__srcCodingEdit, 3, 4, 1, 1)
        self.__srcCodingEdit.setFont(font)

        layout.addLayout(gridLayout)

        # Boilerplate
        boilLabel = QLabel("Boilerplate  ")
        boilLabel.setAlignment(Qt.AlignTop)
        self.__boilEdit = QTextEdit()
        self.__boilEdit.setPlainText(self.__settings.settings["BOILERPLATE"])
        self.__boilEdit.setToolTip(
            self.__settings.getDescription("BOILERPLATE"))
        self.__boilEdit.setTabChangesFocus(True)
        self.__boilEdit.setAcceptRichText(False)
        self.__boilEdit.setFont(font)
        self.__boilEdit.textChanged.connect(self.__validate)
        boilLayout = QHBoxLayout()
        boilLayout.addWidget(boilLabel)
        boilLayout.addWidget(self.__boilEdit)
        layout.addLayout(boilLayout)

        # Now check boxes and radio buttons
        cbGridLayout = QGridLayout()
        self.__keepBlanks = QCheckBox("Keep blank lines")
        self.__keepBlanks.setChecked(
            self.__settings.settings["KEEP_BLANK_LINES"])
        self.__keepBlanks.setToolTip(
            self.__settings.getDescription("KEEP_BLANK_LINES"))
        cbGridLayout.addWidget(self.__keepBlanks, 0, 0, 1, 1)

        self.__addBlanks = QCheckBox("Add blank lines around comments")
        self.__addBlanks.setChecked(
            self.__settings.settings["ADD_BLANK_LINES_AROUND_COMMENTS"])
        self.__addBlanks.setToolTip(
            self.__settings.getDescription("ADD_BLANK_LINES_AROUND_COMMENTS"))
        cbGridLayout.addWidget(self.__addBlanks, 0, 2, 1, 1)

        self.__justifyDoc = QCheckBox("Left justify doc strings")
        self.__justifyDoc.setChecked(
            self.__settings.settings["LEFTJUST_DOC_STRINGS"])
        self.__justifyDoc.setToolTip(
            self.__settings.getDescription("LEFTJUST_DOC_STRINGS"))
        cbGridLayout.addWidget(self.__justifyDoc, 1, 0, 1, 1)

        self.__wrapDoc = QCheckBox("Wrap long doc strings")
        self.__wrapDoc.setChecked(self.__settings.settings["WRAP_DOC_STRINGS"])
        self.__wrapDoc.setToolTip(
            self.__settings.getDescription("WRAP_DOC_STRINGS"))
        cbGridLayout.addWidget(self.__wrapDoc, 1, 2, 1, 1)

        self.__recodeStrings = QCheckBox("Try to decode strings")
        self.__recodeStrings.setChecked(
            self.__settings.settings["RECODE_STRINGS"])
        self.__recodeStrings.setToolTip(
            self.__settings.getDescription("RECODE_STRINGS"))
        cbGridLayout.addWidget(self.__recodeStrings, 2, 0, 1, 1)

        self.__splitStrings = QCheckBox("Split long strings")
        self.__splitStrings.setChecked(
            self.__settings.settings["CAN_SPLIT_STRINGS"])
        self.__splitStrings.setToolTip(
            self.__settings.getDescription("CAN_SPLIT_STRINGS"))
        cbGridLayout.addWidget(self.__splitStrings, 2, 2, 1, 1)

        self.__keepUnassignedConst = QCheckBox("Keep unassigned constants")
        self.__keepUnassignedConst.setChecked(
            self.__settings.settings["KEEP_UNASSIGNED_CONSTANTS"])
        self.__keepUnassignedConst.setToolTip(
            self.__settings.getDescription("KEEP_UNASSIGNED_CONSTANTS"))
        cbGridLayout.addWidget(self.__keepUnassignedConst, 3, 0, 1, 1)

        self.__parenTuple = QCheckBox("Parenthesize tuple display")
        self.__parenTuple.setChecked(
            self.__settings.settings["PARENTHESIZE_TUPLE_DISPLAY"])
        self.__parenTuple.setToolTip(
            self.__settings.getDescription("PARENTHESIZE_TUPLE_DISPLAY"))
        cbGridLayout.addWidget(self.__parenTuple, 3, 2, 1, 1)

        self.__javaListDedent = QCheckBox("Java style list dedent")
        self.__javaListDedent.setChecked(
            self.__settings.settings["JAVA_STYLE_LIST_DEDENT"])
        self.__javaListDedent.setToolTip(
            self.__settings.getDescription("JAVA_STYLE_LIST_DEDENT"))
        cbGridLayout.addWidget(self.__javaListDedent, 4, 0, 1, 1)

        layout.addLayout(cbGridLayout)

        # Quotes radio buttons
        quotesGroupbox = QGroupBox("Quotes")
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth( \
                        quotesGroupbox.sizePolicy().hasHeightForWidth() )
        quotesGroupbox.setSizePolicy(sizePolicy)

        layoutQG = QVBoxLayout(quotesGroupbox)
        self.__use1RButton = QRadioButton(
            "Use apostrophes instead of quotes for string literals",
            quotesGroupbox)
        layoutQG.addWidget(self.__use1RButton)
        self.__use2RButton = QRadioButton(
            "Use quotes instead of apostrophes for string literals",
            quotesGroupbox)
        layoutQG.addWidget(self.__use2RButton)
        self.__useAsIsRButton = QRadioButton("Do not make changes",
                                             quotesGroupbox)
        layoutQG.addWidget(self.__useAsIsRButton)
        use1 = self.__settings.settings["SINGLE_QUOTED_STRINGS"]
        use2 = self.__settings.settings["DOUBLE_QUOTED_STRINGS"]
        if use1:
            self.__use1RButton.setChecked(True)
        elif use2:
            self.__use2RButton.setChecked(True)
        else:
            self.__useAsIsRButton.setChecked(True)
        layout.addWidget(quotesGroupbox)

        fontMetrics = QFontMetrics(font)
        editWidth = fontMetrics.width("iso8859-10  ") + 20
        self.__colsEdit.setFixedWidth(editWidth)
        self.__funcAssignEdit.setFixedWidth(editWidth)
        self.__sliceSepEdit.setFixedWidth(editWidth)
        self.__outCodingEdit.setFixedWidth(editWidth)

        # Buttons at the bottom
        buttonBox = QDialogButtonBox(self)
        buttonBox.setOrientation(Qt.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.Cancel)
        self.__resetButton = buttonBox.addButton("Reset to Default",
                                                 QDialogButtonBox.ActionRole)
        self.__resetButton.setToolTip(
            "Mostly as recommended by PEP 8 / PEP 308")
        self.__resetButton.clicked.connect(self.__reset)
        self.__tidyButton = buttonBox.addButton("Tidy",
                                                QDialogButtonBox.ActionRole)
        self.__tidyButton.setToolTip("Save settings and run PythonTidy")
        self.__tidyButton.setDefault(True)
        self.__tidyButton.clicked.connect(self.__saveAndAccept)
        layout.addWidget(buttonBox)

        buttonBox.rejected.connect(self.close)
        return
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