Exemple #1
0
    def add_user(self, name):
        radio_button = QRadioButton(name, self)
        if not len(self.radio_buttons):
            radio_button.setChecked(True)

        self.groupBoxLayout.addWidget(radio_button)
        self.radio_buttons.append(radio_button)
        class LabelDistributionOptionsDlg( QDialog ):
            """
            A little dialog to let the user specify how the labels should be
            distributed from the current stages to the other stages.
            """
            def __init__(self, source_stage_index, num_stages, *args, **kwargs):
                super(LabelDistributionOptionsDlg, self).__init__(*args, **kwargs)

                from PyQt4.QtCore import Qt
                from PyQt4.QtGui import QGroupBox, QCheckBox, QRadioButton, QDialogButtonBox
            
                self.setWindowTitle("Distributing from Stage {}".format(source_stage_index+1))

                self.stage_checkboxes = []
                for stage_index in range(1, num_stages+1):
                    self.stage_checkboxes.append( QCheckBox("Stage {}".format( stage_index )) )
                
                # By default, send labels back into the current stage, at least.
                self.stage_checkboxes[source_stage_index].setChecked(True)
                
                stage_selection_layout = QVBoxLayout()
                for checkbox in self.stage_checkboxes:
                    stage_selection_layout.addWidget( checkbox )

                stage_selection_groupbox = QGroupBox("Send labels from Stage {} to:".format( source_stage_index+1 ), self)
                stage_selection_groupbox.setLayout(stage_selection_layout)
                
                self.copy_button = QRadioButton("Copy", self)
                self.partition_button = QRadioButton("Partition", self)
                self.partition_button.setChecked(True)
                distribution_mode_layout = QVBoxLayout()
                distribution_mode_layout.addWidget(self.copy_button)
                distribution_mode_layout.addWidget(self.partition_button)
                
                distribution_mode_group = QGroupBox("Distribution Mode", self)
                distribution_mode_group.setLayout(distribution_mode_layout)
                
                buttonbox = QDialogButtonBox( Qt.Horizontal, parent=self )
                buttonbox.setStandardButtons( QDialogButtonBox.Ok | QDialogButtonBox.Cancel )
                buttonbox.accepted.connect( self.accept )
                buttonbox.rejected.connect( self.reject )
                
                dlg_layout = QVBoxLayout()
                dlg_layout.addWidget(stage_selection_groupbox)
                dlg_layout.addWidget(distribution_mode_group)
                dlg_layout.addWidget(buttonbox)
                self.setLayout(dlg_layout)

            def distribution_mode(self):
                if self.copy_button.isChecked():
                    return "copy"
                if self.partition_button.isChecked():
                    return "partition"
                assert False, "Shouldn't get here."
            
            def destination_stages(self):
                """
                Return the list of stage_indexes (0-based) that the user checked.
                """
                return [ i for i,box in enumerate(self.stage_checkboxes) if box.isChecked() ]
Exemple #3
0
    def choice(self, title, msg, choices):
        vbox = QVBoxLayout()
        self.set_layout(vbox)
        vbox.addWidget(QLabel(title))
        gb2 = QGroupBox(msg)
        vbox.addWidget(gb2)

        vbox2 = QVBoxLayout()
        gb2.setLayout(vbox2)

        group2 = QButtonGroup()
        for i, c in enumerate(choices):
            button = QRadioButton(gb2)
            button.setText(c[1])
            vbox2.addWidget(button)
            group2.addButton(button)
            group2.setId(button, i)
            if i == 0:
                button.setChecked(True)
        vbox.addStretch(1)
        vbox.addLayout(Buttons(CancelButton(self), OkButton(self, _('Next'))))
        if not self.exec_():
            return
        wallet_type = choices[group2.checkedId()][0]
        return wallet_type
Exemple #4
0
class CADOptionsToolbar_Modify(CADOptionsToolbar):
    def __init__(self, layerType):
        super(CADOptionsToolbar_Modify, self).__init__()

        self.add_btn = QRadioButton(
            tr(u"Add"), self.optionsToolBar)
        self.add_btn.setToolTip(
            tr(u"Add extension"))
        self.add_btn.setObjectName("add_rbtn")
        self.modify_btn = QRadioButton(
            tr(u"Modify"), self.optionsToolBar)
        self.modify_btn.setToolTip(
            tr(u"Modify the entity"))
        self.modify_btn.setObjectName("modify_rbtn")
        self.extend_btn = QRadioButton(
            tr(u"Add opposite"), self.optionsToolBar)
        self.extend_btn.setToolTip(
            tr(u"Add an extended line"))
        self.extend_btn.setObjectName("extend_rbtn")
        self.optionsToolBar.addWidget(self.add_btn)
        self.optionsToolBar.addWidget(self.modify_btn)
        self.optionsToolBar.addWidget(self.extend_btn)
        self.add_btn.setChecked(True)

        if layerType == QGis.Polygon:
            self.modify_btn.setChecked(True)
            self.add_btn.setEnabled(False)
            self.extend_btn.setEnabled(False)
        else:
            self.add_btn.setEnabled(True)
            self.extend_btn.setEnabled(True)
Exemple #5
0
class ConnectorPage(QWizardPage):
    def __init__(self, parent=None):
        QWizardPage.__init__(self, parent)
        self.parent = parent
        self.setTitle(self.tr("Add dumps"))

        label = QLabel(
            self.
            tr("What do you want to analyse? "
               "The first step is to choose some dumps for analysis. "
               "You could load a local file, a dump or choose to mount connected devices"
               ))
        label.setWordWrap(True)
        layout = QGridLayout()
        layout.addWidget(label, 0, 0)

        groupBox = QGroupBox(self.tr("Dumps"))
        self.localFilesRadioButton = QRadioButton(self.tr("Add a local file"))
        self.deviceRadioButton = QRadioButton(self.tr("Add a device"))
        self.localFilesRadioButton.setChecked(True)
        groupBoxLayout = QVBoxLayout()
        groupBoxLayout.addWidget(self.localFilesRadioButton)
        groupBoxLayout.addWidget(self.deviceRadioButton)
        groupBox.setLayout(groupBoxLayout)
        layout.addWidget(groupBox, 1, 0)
        self.setLayout(layout)

    def nextId(self):
        if self.localFilesRadioButton.isChecked():
            return AutoWizard.Page_Local
        else:
            return AutoWizard.Page_Device

    def __del__(self):
        pass  #fix pyqt segfault when QGridLayout (layout ) is deleted
Exemple #6
0
class RadioButton(QWidget):
    selected = pyqtSignal()

    def __init__(self, caption, parent, selected=False):
        QWidget.__init__(self)

        self.value = selected
        self.radiobutton = QRadioButton(caption, parent)
        self.radiobutton.clicked.connect(self.__on_change)

        hbox = QHBoxLayout()
        hbox.addWidget(self.radiobutton)
        hbox.setMargin(0)
        self.setLayout(hbox)
        self.setContentsMargins(0, 0, 0, 0)
        self.radiobutton.setChecked(self.value)

    def __on_change(self):
        self.value = True
        self.selected.emit()

    def set_value(self, value):
        self.radiobutton.setChecked(value)

    def get_value(self):
        return self.radiobutton.isChecked()
Exemple #7
0
class RadioButton(QWidget):
    selected = pyqtSignal()

    def __init__(self, caption, parent, selected=False):
        QWidget.__init__(self)

        self.value = selected
        self.radiobutton = QRadioButton(caption, parent)
        self.radiobutton.clicked.connect(self.__on_change)

        hbox = QHBoxLayout()
        hbox.addWidget(self.radiobutton)
        hbox.setMargin(0)
        self.setLayout(hbox)
        self.setContentsMargins(0, 0, 0, 0)
        self.radiobutton.setChecked(self.value)

    def __on_change(self):
        self.value = True
        self.selected.emit()

    def set_value(self, value):
        self.radiobutton.setChecked(value)

    def get_value(self):
        return self.radiobutton.isChecked()
Exemple #8
0
class PostProcessMode(QWizardPage):
    def __init__(self, parent=None):
        QWizardPage.__init__(self, parent)
        self.parent = parent
        self.setTitle(self.tr("Processing mode"))
        label = QLabel(
            self.
            tr("You can choose between a fully automated mode, and semi-automatic mode. "
               "Full mode means all compatible modules will be applied without prompting you. "
               "Semi-auto mode means that for each applied module and for each scan you will be asked to continue or to cancel. "
               "If you don't know what to choose, select Full-automatic"))
        label.setWordWrap(True)
        layout = QGridLayout()
        layout.addWidget(label, 0, 0)
        groupBox = QGroupBox("Mode")
        self.fullBoxRadioButton = QRadioButton("F&ull Auto")
        self.semiBoxRadioButton = QRadioButton("S&emi Auto")
        self.fullBoxRadioButton.setChecked(True)
        groupBoxLayout = QVBoxLayout()
        groupBoxLayout.addWidget(self.fullBoxRadioButton)
        groupBoxLayout.addWidget(self.semiBoxRadioButton)
        groupBox.setLayout(groupBoxLayout)
        layout.addWidget(groupBox, 1, 0)
        self.setLayout(layout)

    def validatePage(self):
        if self.fullBoxRadioButton.isChecked():
            ppsched.fullAutoMode(True)
        else:
            ppsched.fullAutoMode(False)
        return True

    def __del__(self):
        pass  #fix pyqt segfault when QGridLayout (layout ) is deleted
def Build_Tab(group, source_key, default, projector, projectordb, edit=False):
    """
    Create the radio button page for a tab.
    Dictionary will be a 1-key entry where key=tab to setup, val=list of inputs.

    source_key: {"groupkey1": {"key11": "key11-text",
                               "key12": "key12-text",
                               ...
                              },
                 "groupkey2": {"key21": "key21-text",
                               "key22": "key22-text",
                               ....
                              },
                 ...
                }

    :param group: Button group widget to add buttons to
    :param source_key: Dictionary of sources for radio buttons
    :param default: Default radio button to check
    :param projector: Projector instance
    :param projectordb: ProjectorDB instance for session
    :param edit: If we're editing the source text
    """
    buttonchecked = False
    widget = QWidget()
    layout = QFormLayout() if edit else QVBoxLayout()
    layout.setSpacing(10)
    widget.setLayout(layout)
    tempkey = list(source_key.keys())[0]  # Should only be 1 key
    sourcelist = list(source_key[tempkey])
    sourcelist.sort()
    button_count = len(sourcelist)
    if edit:
        for key in sourcelist:
            item = QLineEdit()
            item.setObjectName('source_key_%s' % key)
            source_item = projectordb.get_source_by_code(code=key, projector_id=projector.db_item.id)
            if source_item is None:
                item.setText(PJLINK_DEFAULT_CODES[key])
            else:
                item.setText(source_item.text)
            layout.addRow(PJLINK_DEFAULT_CODES[key], item)
            group.append(item)
    else:
        for key in sourcelist:
            source_item = projectordb.get_source_by_code(code=key, projector_id=projector.db_item.id)
            if source_item is None:
                text = source_key[tempkey][key]
            else:
                text = source_item.text
            itemwidget = QRadioButton(text)
            itemwidget.setAutoExclusive(True)
            if default == key:
                itemwidget.setChecked(True)
                buttonchecked = itemwidget.isChecked() or buttonchecked
            group.addButton(itemwidget, int(key))
            layout.addWidget(itemwidget)
        layout.addStretch()
    return widget, button_count, buttonchecked
 def RadioSet(widget : QtGui.QRadioButton, val : str, id : int) -> bool:
     """If QRadioButton name match 'val' select it and return True."""
     # if widget.accessibleName() != val: return False
     # widget.setChecked(True)
     # return True                
     assert len(self.enum) > id
     if self.enum[id] != val: return False
     widget.setChecked(True)
     return True
Exemple #11
0
 def initUI(self):
     # local variable that records which radio button is clicked
     self.choice = 1
     # welcome message
     welcomeMsg = QLabel(self)
     welcomeMsg.setText("Welcome to the PyQt Interface!")
     welcomeMsg.setAlignment(Qt.AlignCenter)
     menu = QLabel(self)
     menu.setText("Menu")
     # create buttons & connect them with function btnClicked
     btn1 = QRadioButton(self)
     btn1.setText("1. Create montages recursively from given directory and sub-directories")
     btn1.setChecked(True)
     btn1.toggled.connect(lambda:self.btnClicked(1))        
     btn2 = QRadioButton(self)
     btn2.setText("2. Create montages from provided CSV files (split by categories or bins)")
     btn2.toggled.connect(lambda:self.btnClicked(2))
     btn3 = QRadioButton(self)
     btn3.setText("3. Create vertical montage from provided CSV file")
     btn3.toggled.connect(lambda:self.btnClicked(3))
     btn4 = QRadioButton(self)
     btn4.setText("4. Create image histogram from provided CSV file")
     btn4.toggled.connect(lambda:self.btnClicked(4))
     btn5 = QRadioButton(self)
     btn5.setText("5. Create scatter plot from provided CSV file")
     btn5.toggled.connect(lambda:self.btnClicked(5))
     quit = QPushButton(self)
     quit.setText("Quit")
     enter = QPushButton(self)
     enter.setText("Enter")
     instr = QPushButton(self)
     instr.setText("Instruction")
     self.setStyleSheet('QLabel {font-family: cursive, sans-serif; font-weight: 500; font-size: 16px; color: #A0522D;} QRadioButton {font-family: cursive, sans-serif; font-weight: 300; font-size: 16px; color: #8B4513;} QPushButton {font-family: cursive, sans-serif; font-weight: 500; font-size: 16px; color: #CD853F; }')
     welcomeMsg.setStyleSheet('QLabel {font-weight: 900;font-size: 20px;}')        
     # set layout
     mbox = QGridLayout(self)
     mbox.addWidget(welcomeMsg, 1, 1)
     mbox.addWidget(menu,2,1)
     mbox.addWidget(btn1,3,1)
     mbox.addWidget(btn2,4,1)
     mbox.addWidget(btn3,5,1)
     mbox.addWidget(btn4,6,1)
     mbox.addWidget(btn5,7,1)
     mbox.addWidget(quit,8,0)
     mbox.addWidget(enter,8,2)
     mbox.addWidget(instr,8,1)
     self.setLayout(mbox)
     # connect the click event with a function
     enter.clicked.connect(self.nextPage)
     quit.clicked.connect(self.close)
     instr.clicked.connect(self.instruction)
     # set background as transparent
     palette	= QPalette()
     palette.setBrush(QPalette.Background,QBrush(QPixmap()))
     self.setPalette(palette)       
Exemple #12
0
 def _create_radiobutton(self, key, value):
     atomic_widget = QWidget()
     layout = QBoxLayout(self.horizontal)
     for i, rbkey in enumerate(self.radiobuttons[key][0]):
         b1 = QRadioButton("Button1")
         if i == self.radiobuttons[key][1]:
             b1.setChecked(True)
         # b1.toggled.connect(lambda:self.btnstate(self.b1))
         layout.addWidget(b1)
     atomic_widget.setLayout(layout)
     return atomic_widget
Exemple #13
0
    def __init__(self):
        super(IntroductionPage, self).__init__()
        self.setTitle(self.tr("Creación de un nuevo Proyecto"))
        self.setSubTitle(self.tr("Información básica del Proyecto"))
        container = QVBoxLayout(self)
        hbox = QHBoxLayout()
        # Nombre
        hbox.addWidget(QLabel(self.tr("Nombre del Proyecto:")))
        self.line_name = QLineEdit()
        hbox.addWidget(self.line_name)
        container.addLayout(hbox)
        # Ubicación
        group = QGroupBox(self.tr("Ubicación:"))
        box = QVBoxLayout(group)
        button_group = QButtonGroup(self)
        radio_buttons = [
            self.tr("Directorio por defecto"),
            self.tr("Otro")
            ]
        for _id, radiob in enumerate(radio_buttons):
            radio_button = QRadioButton(radiob)
            button_group.addButton(radio_button, _id)
            box.addWidget(radio_button)
            if _id == 0:
                # El primero checked por defecto
                radio_button.setChecked(True)
        container.addWidget(group)

        self.line_location = QLineEdit()
        container.addWidget(self.line_location)

        hbox = QHBoxLayout()
        hbox.addWidget(QLabel(self.tr("Archivo del Proyecto: ")))
        self._project_filename = QLineEdit()
        hbox.addWidget(self._project_filename)
        container.addLayout(hbox)

        hbox = QHBoxLayout()
        hbox.addWidget(QLabel(self.tr("Archivo resultante: ")))
        self._resulting_filename = QLineEdit()
        hbox.addWidget(self._resulting_filename)
        container.addLayout(hbox)

        # Conexiones
        self.connect(button_group, SIGNAL("buttonClicked(int)"),
                     self._update_location)
        self.connect(self.line_name, SIGNAL("textChanged(const QString&)"),
                     self._on_project_name_changed)
        self.connect(self.line_name, SIGNAL("textChanged(const QString&)"),
                     lambda: self.emit(SIGNAL("completeChanged()")))

        self._update_location(0)
Exemple #14
0
    def createExtractionTab(self):
        extractDeckLabel = QLabel('Extracts Deck')
        self.extractDeckComboBox = QComboBox()
        deckNames = sorted([d['name'] for d in mw.col.decks.all()])
        self.extractDeckComboBox.addItem('[Current Deck]')
        self.extractDeckComboBox.addItems(deckNames)

        if self.settings['extractDeck']:
            setComboBoxItem(self.extractDeckComboBox,
                            self.settings['extractDeck'])
        else:
            setComboBoxItem(self.extractDeckComboBox, '[Current Deck]')

        extractDeckLayout = QHBoxLayout()
        extractDeckLayout.addWidget(extractDeckLabel)
        extractDeckLayout.addWidget(self.extractDeckComboBox)

        self.editExtractButton = QRadioButton('Edit Extracted Note')
        enterTitleButton = QRadioButton('Enter Title Only')

        if self.settings['editExtract']:
            self.editExtractButton.setChecked(True)
        else:
            enterTitleButton.setChecked(True)

        radioButtonsLayout = QHBoxLayout()
        radioButtonsLayout.addWidget(self.editExtractButton)
        radioButtonsLayout.addWidget(enterTitleButton)
        radioButtonsLayout.addStretch()

        self.editSourceCheckBox = QCheckBox('Edit Source Note')
        self.plainTextCheckBox = QCheckBox('Extract as Plain Text')

        if self.settings['editSource']:
            self.editSourceCheckBox.setChecked(True)

        if self.settings['plainText']:
            self.plainTextCheckBox.setChecked(True)

        layout = QVBoxLayout()
        layout.addLayout(extractDeckLayout)
        layout.addLayout(radioButtonsLayout)
        layout.addWidget(self.editSourceCheckBox)
        layout.addWidget(self.plainTextCheckBox)
        layout.addStretch()

        tab = QWidget()
        tab.setLayout(layout)

        return tab
Exemple #15
0
    def setup_method_layout(self):
        self.group = QButtonGroup(self, exclusive=True)

        if self.initialize_methods:
            self.methods = [method() for method in self.methods]

        for i, method in enumerate(self.methods):
            rb = QRadioButton(self, text=self.textify(method.name))
            rb.setChecked(i == self.method_index)
            rb.setToolTip(self.get_tooltip(method))
            self.group.addButton(rb, i)
            self.method_layout.addWidget(rb, i, 0)

        self.group.buttonClicked.connect(self.update_value)
Exemple #16
0
    def network_dialog(self):
        # skip this if config already exists
        if self.config.get('server') is not None:
            return

        grid = QGridLayout()
        grid.setSpacing(5)

        label = QLabel(_(
            "Electrum communicates with remote servers to get ",
            'information about your transactions and addresses. ',
            'The servers all fulfil the same purpose only ',
            'differing in hardware. In most cases you simply ',
            'want to let Electrum pick one at random if you ',
            'have a preference though feel free to select a server manually.') + "\n\n" + _(
            "How do you want to connect to a server:") + " ")
        label.setWordWrap(True)
        grid.addWidget(label, 0, 0)

        gb = QGroupBox()

        b1 = QRadioButton(gb)
        b1.setText(_("Auto connect"))
        b1.setChecked(True)

        b2 = QRadioButton(gb)
        b2.setText(_("Select server manually"))

        # b3 = QRadioButton(gb)
        # b3.setText(_("Stay offline"))

        grid.addWidget(b1, 1, 0)
        grid.addWidget(b2, 2, 0)
        # grid.addWidget(b3, 3, 0)

        vbox = QVBoxLayout()
        vbox.addLayout(grid)

        vbox.addStretch(1)
        vbox.addLayout(Buttons(CancelButton(self), OkButton(self, _('Next'))))

        self.set_layout(vbox)
        if not self.exec_():
            return

        if b2.isChecked():
            return NetworkDialog(self.network, self.config, None).do_exec()
        else:
            self.config.set_key('auto_connect', True, True)
            return
Exemple #17
0
class GPSTab(OptionsDialogTab):
    def __init__(self, optionsConfig, parent):
        OptionsDialogTab.__init__(self, optionsConfig, parent)
        self.setFromOptionsConfig(self.getOptionsConfig())

    def getTabName(self):
        return "GPS"

    def setFromOptionsConfig(self, optionsConfig):
        self.useNmea = self.optionsConfig["withNmea"]
        self.useGpsd = self.optionsConfig["withGpsd"]
        self.device = self.optionsConfig["device"]

    def setToOptionsConfig(self):
        self.optionsConfig["withNmea"] = self.nmeaButton.isChecked()
        self.optionsConfig["withGpsd"] = self.gpsdButton.isChecked()
        device = self.deviceText.text()
        if len(device) != 0:
            self.optionsConfig["device"] = device
        else:
            self.optionsConfig["device"] = None

    def addToLayout(self, layout):
        filler = QLabel(self)
        label = QLabel(self)
        label.setText("Changes take affect only after restart.")
        layout.addWidget(label)

        formLayout = QFormLayout()
        formLayout.setAlignment(Qt.AlignTop)
        layout.addLayout(formLayout)

        self.nmeaButton = QRadioButton("nmea", self)
        formLayout.addRow(self.nmeaButton, filler)
        self.nmeaButton.setChecked(self.useNmea)

        label = QLabel(self)
        label.setText("GPS Device:")

        self.deviceText = QLineEdit(self)
        formLayout.addRow(label, self.deviceText)
        self.deviceText.setToolTip('NMEA GPS device path.')
        if self.device != None:
            self.deviceText.setText(self.device)

        self.gpsdButton = QRadioButton("gpsd", self)
        formLayout.addRow(self.gpsdButton, filler)
        self.gpsdButton.setChecked(self.useGpsd)
Exemple #18
0
class InputRadioGroup(QWidget):
    """Create an horizontal radio group"""
    def __init__(self, parent=None, option_list=None, default_select=0):
        super(InputRadioGroup, self).__init__(parent=parent)
        layout = QHBoxLayout(self)
        self.group = QButtonGroup()
        for idx, op in enumerate(option_list):
            self.op = QRadioButton(_(op))
            if idx == default_select:
                self.op.setChecked(True)
            layout.addWidget(self.op)
            self.group.addButton(self.op)
        self.setLayout(layout)

    @pyqtProperty(str)
    def currentItemData(self):
        return str(abs(int(self.group.checkedId())) - 1)
Exemple #19
0
    def createDialog(self):
        """
        Create qt dialog
        """
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setStyleSheet("""QDialogButtonBox { 
            dialogbuttonbox-buttons-have-icons: 1;
            dialog-ok-icon: url(:/ok.png);
            dialog-cancel-icon: url(:/test-close-black.png);
        }""")
        self.buttonBox.setStandardButtons(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Cancel)

        self.stepIdLabel = QLabel("%s" % self.stepId)
        stepTitleLayout = QGridLayout()

        # mandatory args
        self.argsLayout = QGridLayout()
        for i in xrange(len(self.stepData['obj'])):
            self.argsLayout.addWidget(QLabel(self.stepData['obj'][i]['name']),
                                      i, 0)
            typeParam = QRadioButton(self.stepData['obj'][i]['type'])
            typeParam.setEnabled(False)
            self.argsLayout.addWidget(typeParam, i, 1)
            if self.stepData['obj'][i]['type'] == 'string':
                typeParam.setChecked(True)
                self.argsLayout.addWidget(QTextEdit(), i, 2)
            if self.stepData['obj'][i]['type'] == "boolean":
                boolCombo = QComboBox()
                valBool = ["True", "False"]
                boolCombo.addItems(valBool)
                boolCombo.setEnabled(
                    False)  # feature not yet available in abstract mode
                typeParam.setChecked(True)
                self.argsLayout.addWidget(boolCombo, i, 2)

        mainLayout = QVBoxLayout()
        mainLayout.addLayout(stepTitleLayout)
        mainLayout.addLayout(self.argsLayout)
        mainLayout.addWidget(self.buttonBox)
        self.setLayout(mainLayout)

        self.setWindowTitle(self.tr("Step configuration"))
        self.resize(450, 250)
        self.center()
Exemple #20
0
    def rebuild_editor ( self ):
        """ Rebuilds the contents of the editor whenever the original factory
            object's **values** facet changes.
        """
        # Clear any existing content:
        ### self.clear_layout()

        # Get the current facet value:
        cur_name = self.str_value

        # Create a sizer to manage the radio buttons:
        names   = self.names
        mapping = self.mapping
        n       = len( names )
        cols    = self.factory.cols
        rows    = (n + cols - 1) / cols
        incr    = [ n / cols ] * cols
        rem     = n % cols
        for i in range( cols ):
            incr[i] += (rem > i)

        incr[-1] = -( reduce( lambda x, y: x + y, incr[:-1], 0 ) - 1 )

        # Add the set of all possible choices:
        index = 0

        for i in range( rows ):
            for j in range( cols ):
                if n > 0:
                    name = label = names[ index ]
                    label = self.string_value( label, capitalize )
                    rb = QRadioButton( label )
                    rb.value = mapping[ name ]

                    rb.setChecked( name == cur_name )

                    QObject.connect( rb, SIGNAL( 'clicked()' ), self._mapper,
                                     SLOT( 'map()' ) )
                    self._mapper.setMapping( rb, rb )

                    self.set_tooltip( rb )
                    self.control.addWidget( rb, i, j )

                    index += incr[j]
                    n     -= 1
    def _initPolicyWidget(self):
        policyWidget = QWidget(self)
        self._policyGroup = QButtonGroup(self)

        once = QRadioButton("Once", policyWidget)
        once.setChecked(True)
        once.clicked.connect(partial(self._setPolicy, self.POLICY_ONCE))
        self._policyGroup.addButton(once)

        forever = QRadioButton("Forever", policyWidget)
        forever.clicked.connect(partial(self._setPolicy, self.POLICY_FOREVER))
        self._policyGroup.addButton(forever)

        policyLayout = QHBoxLayout(policyWidget)
        policyLayout.setContentsMargins(5, 0, 5, 0)
        policyLayout.addWidget(once, 0)
        policyLayout.addWidget(forever, 1, Qt.AlignLeft)
        return policyWidget
Exemple #22
0
    def __init__(self, parameter, parent=None):
        """Constructor.

        :param parameter: A DefaultValueParameter object.
        :type parameter: DefaultValueParameter

        """
        super(DefaultValueParameterWidget, self).__init__(parameter, parent)

        self.radio_button_layout = QHBoxLayout()

        # Create radio button group
        self.input_button_group = QButtonGroup()

        for i in range(len(self._parameter.labels)):
            if '%s' in self._parameter.labels[i]:
                label = (
                    self._parameter.labels[i] %
                    self._parameter.options[i])
            else:
                label = self._parameter.labels[i]

            radio_button = QRadioButton(label)
            self.radio_button_layout.addWidget(radio_button)
            self.input_button_group.addButton(radio_button, i)
            if self._parameter.value == \
                    self._parameter.options[i]:
                radio_button.setChecked(True)

        # Create double spin box for custom value
        self.custom_value = QDoubleSpinBox()
        self.custom_value.setSingleStep(0.1)
        if self._parameter.options[-1]:
            self.custom_value.setValue(self._parameter.options[-1])
        self.radio_button_layout.addWidget(self.custom_value)

        self.toggle_custom_value()

        self.inner_input_layout.addLayout(self.radio_button_layout)

        # Connect
        # noinspection PyUnresolvedReferences
        self.input_button_group.buttonClicked.connect(
            self.toggle_custom_value)
Exemple #23
0
    def add_radio_btns(self, choicesL, 
                          name='isBell', init_val=3, layout=None,
                          advance_n=True, fulldesc='Nozzle Geometry', 
                          text_font=ARIAL_10, col=0, parent=None):
                       
        # if parent is input, add widget to parent
        if parent is None:
            parent = self
                                            
        if layout is None:
            NRow = parent.get_next_row_number(advance_n)
            # Need to change next row number by length of choicesL
            if advance_n:
                for i in range(1, len(choicesL)):
                    parent.get_next_row_number(advance_n)
        
        radio_btnL = [] # a list of radio buttons in this group
        self.selection_textD[name] = ''
        
        # First build the radio buttons
        groupBox = QGroupBox(fulldesc)
        vbox = QVBoxLayout()
        for i,choice in enumerate( choicesL ):
            radio = QRadioButton(choice, groupBox)
            vbox.addWidget(radio)
            if i == init_val:
                radio.setChecked(True)
                self.selection_textD[name] = str( choice )
                
            radio_btnL.append( radio )
            
            radio.toggled.connect( lambda: self.radio_btn_changed( '%s_radio_group_box'%name ) ) 

            
        #vbox.addStretch(1)
        groupBox.setLayout(vbox)
        
        if layout is None:
            parent.grid.addWidget(groupBox,      NRow, col, len(choicesL), 1)
        else:
            layout.addWidget( groupBox )
        
        self.objectD['%s_radio_group_box'%name] = radio_btnL
        self.input_widget_by_nameD[name] = (radio_btnL , 'radio_btn_list')
    def __init__(self, parameter, parent=None):
        """Constructor.

        :param parameter: A DefaultValueParameter object.
        :type parameter: DefaultValueParameter

        """
        super(DefaultValueParameterWidget, self).__init__(parameter, parent)

        self.radio_button_layout = QHBoxLayout()

        # Create radio button group
        self.input_button_group = QButtonGroup()

        for i in range(len(self._parameter.labels)):
            if '%s' in self._parameter.labels[i]:
                label = (
                    self._parameter.labels[i] %
                    self._parameter.options[i])
            else:
                label = self._parameter.labels[i]

            radio_button = QRadioButton(label)
            self.radio_button_layout.addWidget(radio_button)
            self.input_button_group.addButton(radio_button, i)
            if self._parameter.value == \
                    self._parameter.options[i]:
                radio_button.setChecked(True)

        # Create double spin box for custom value
        self.custom_value = QDoubleSpinBox()
        self.custom_value.setSingleStep(0.1)
        if self._parameter.options[-1]:
            self.custom_value.setValue(self._parameter.options[-1])
        self.radio_button_layout.addWidget(self.custom_value)

        self.toggle_custom_value()

        self.inner_input_layout.addLayout(self.radio_button_layout)

        # Connect
        # noinspection PyUnresolvedReferences
        self.input_button_group.buttonClicked.connect(
            self.toggle_custom_value)
class GuiOptionTriggerMock(GuiOptionMock):

    def __init__(self):
        GuiOptionMock.__init__(self)
        self.w = QWidget()
        self.list_trigger = QComboBox()
        self.list_conn_trigger = QComboBox()
        self.pattern_trigger = QLineEdit()
        self.command_trigger = QLineEdit()
        self.case_trigger = QCheckBox()
        self.delete_trigger = QPushButton()
        self.save_trigger = QPushButton()
        self.radio_command_trigger = QRadioButton(self.w)
        self.radio_command_trigger.setChecked(True)
        self.radio_color_trigger = QRadioButton(self.w)
        self.text_color_trigger_button = QPushButton()
        self.bg_color_trigger_button = QPushButton()
        self.text_color_trigger = QLabel()
        self.bg_color_trigger = QLabel()
Exemple #26
0
    def __init__(self, result):
        QDialog.__init__(self)
        self.layout = QVBoxLayout(self)
        self.result = result
        observation_window = result.observation_window

        group = QButtonGroup(self)
        use_simu_duration = QRadioButton("Use entire simulation.")
        use_simu_duration.setChecked(
            observation_window[0] == 0
            and observation_window[1] == result.model.duration)
        group.addButton(use_simu_duration)
        self.layout.addWidget(use_simu_duration)

        use_custom = QRadioButton("Use a custom observation window:")
        use_custom.setChecked(not use_simu_duration.isChecked())
        group.addButton(use_custom)
        self.layout.addWidget(use_custom)

        self._slider = QxtSpanSliderWidget(
            0,
            result.model.now() // result.model.cycles_per_ms, self)
        self._slider.setSpan(
            observation_window[0] // result.model.cycles_per_ms,
            observation_window[1] // result.model.cycles_per_ms)
        self._slider.setEnabled(use_custom.isChecked())
        group.buttonClicked.connect(
            lambda x: self._slider.setEnabled(x == use_custom))

        self.layout.addWidget(self._slider)

        buttons = QWidget(self)
        buttons_layout = QHBoxLayout()
        buttons.setLayout(buttons_layout)
        buttons_layout.addStretch()
        ok_button = QPushButton("Ok")
        cancel_button = QPushButton("Cancel")
        ok_button.clicked.connect(self.accept)
        cancel_button.clicked.connect(self.reject)
        buttons_layout.addWidget(ok_button)
        buttons_layout.addWidget(cancel_button)
        self.layout.addWidget(buttons)
Exemple #27
0
    def __init__(self, result):
        QDialog.__init__(self)
        self.layout = QVBoxLayout(self)
        self.result = result
        observation_window = result.observation_window

        group = QButtonGroup(self)
        use_simu_duration = QRadioButton("Use entire simulation.")
        use_simu_duration.setChecked(
            observation_window[0] == 0
            and observation_window[1] == result.model.duration)
        group.addButton(use_simu_duration)
        self.layout.addWidget(use_simu_duration)

        use_custom = QRadioButton("Use a custom observation window:")
        use_custom.setChecked(not use_simu_duration.isChecked())
        group.addButton(use_custom)
        self.layout.addWidget(use_custom)

        self._slider = QxtSpanSliderWidget(
            0, result.model.now() // result.model.cycles_per_ms, self)
        self._slider.setSpan(
            observation_window[0] // result.model.cycles_per_ms,
            observation_window[1] // result.model.cycles_per_ms)
        self._slider.setEnabled(use_custom.isChecked())
        group.buttonClicked.connect(
            lambda x: self._slider.setEnabled(x == use_custom))

        self.layout.addWidget(self._slider)

        buttons = QWidget(self)
        buttons_layout = QHBoxLayout()
        buttons.setLayout(buttons_layout)
        buttons_layout.addStretch()
        ok_button = QPushButton("Ok")
        cancel_button = QPushButton("Cancel")
        ok_button.clicked.connect(self.accept)
        cancel_button.clicked.connect(self.reject)
        buttons_layout.addWidget(ok_button)
        buttons_layout.addWidget(cancel_button)
        self.layout.addWidget(buttons)
class CrossModeGroupItem(GroupItem):
    def __init__(self, setup):
        super(CrossModeGroupItem, self).__init__("Cross-Mode Terms", [("Cross-Mode Term", CrossModeItem)], setup)
        self.context_menu.add_action('Add Terms From Matrix', self.add_from_matrix)

        self.array_model = UpperHalfArrayModel()
        array_view = QTableView()
        array_view.setModel(self.array_model)
        type_group = QGroupBox()
        type_layout = QVBoxLayout(type_group)
        self.cross_kerr_type_radio = QRadioButton("Cross-Kerr")
        self.cross_kerr_type_radio.setChecked(True)
        self.xx_type_radio = QRadioButton("X-X")
        type_layout.addWidget(self.cross_kerr_type_radio)
        type_layout.addWidget(self.xx_type_radio)
        self.dialog = OKCancelDialog(QLabel("Mode Array"), array_view, type_group)

    def add_item(self, dialog=True):
        if self.setup.modes_item.rowCount() < 2:
            message_box.setIcon(QMessageBox.Warning)
            message_box.setText("Need more than two modes")
            message_box.exec_()
        else:
            return super(CrossModeGroupItem, self).add_item(dialog=dialog)

    def add_from_matrix(self):
        self.array_model.set_n(self.setup.modes_item.rowCount())
        names = [m.text() for m in self.setup.modes_item.items_list()]
        self.array_model.setHorizontalHeaderLabels(names)
        self.array_model.setVerticalHeaderLabels(names)
        if self.dialog.exec_():
            if self.cross_kerr_type_radio.isChecked():
                type_str = "Cross-Kerr"
            elif self.xx_type_radio.isChecked():
                type_str = "X-X"
            else:
                return
            for i, row in enumerate(self.array_model.array):
                for j, val in enumerate(row):
                    if val:
                        self.appendRow(CrossModeItem(type_str, val, i, j, self.setup.modes_item))
Exemple #29
0
class Target(preferences.Group):
    def __init__(self, page):
        super(Target, self).__init__(page)

        layout = QGridLayout()
        self.setLayout(layout)

        self.targetPDF = QRadioButton(toggled=page.changed)
        self.targetSVG = QRadioButton(toggled=page.changed)
        self.openDefaultView = QCheckBox(clicked=page.changed)

        layout.addWidget(self.targetPDF, 0, 0)
        layout.addWidget(self.targetSVG, 0, 1)
        layout.addWidget(self.openDefaultView, 1, 0, 1, 5)
        app.translateUI(self)

    def translateUI(self):
        self.setTitle(_("Default output format"))
        self.targetPDF.setText(_("PDF"))
        self.targetPDF.setToolTip(
            _("Create PDF (Portable Document Format) documents by default."))
        self.targetSVG.setText(_("SVG"))
        self.targetSVG.setToolTip(
            _("Create SVG (Scalable Vector Graphics) documents by default."))
        self.openDefaultView.setText(
            _("Open default viewer after successful compile"))
        self.openDefaultView.setToolTip(
            _("Shows the PDF or SVG music view when a compile job finishes "
              "successfully."))

    def loadSettings(self):
        s = settings()
        target = s.value("default_output_target", "pdf", type(""))
        if target == "svg":
            self.targetSVG.setChecked(True)
            self.targetPDF.setChecked(False)
        else:
            self.targetSVG.setChecked(False)
            self.targetPDF.setChecked(True)
        self.openDefaultView.setChecked(
            s.value("open_default_view", True, bool))

    def saveSettings(self):
        s = settings()
        if self.targetSVG.isChecked():
            target = "svg"
        else:
            target = "pdf"
        s.setValue("default_output_target", target)
        s.setValue("open_default_view", self.openDefaultView.isChecked())
	def __init__(self, client, parent = None):
		infoWidget.__init__(self, client, parent)
		self.__mainLayout = QHBoxLayout()
		self.__chart = LineChartFrame()

		self.__projectsList = QListWidget()
		self.__projectsList.setFixedWidth(200)

		self.__statisticGroupBox = QGroupBox(self.tr("Statistics type"))
		self.__statisticLayout = QVBoxLayout()
		self.__statisticGroupBox.setLayout(self.__statisticLayout)

		userTotalRadio   = QRadioButton(self.tr("User total"), self.__statisticGroupBox)
		userAverageRadio = QRadioButton(self.tr("User average"), self.__statisticGroupBox)
		hostTotalRadio   = QRadioButton(self.tr("Host total"), self.__statisticGroupBox)
		hostAverageRadio = QRadioButton(self.tr("Host average"), self.__statisticGroupBox)

		self.__statisticLayout.addWidget(userTotalRadio)
		self.__statisticLayout.addWidget(userAverageRadio)
		self.__statisticLayout.addWidget(hostTotalRadio)
		self.__statisticLayout.addWidget(hostAverageRadio)

		self.__buttonsLayout = QVBoxLayout()
		self.__buttonsLayout.addWidget(self.__projectsList)
		self.__buttonsLayout.addWidget(self.__statisticGroupBox)

		self.__mainLayout.addWidget(self.__chart)
		self.__mainLayout.addLayout(self.__buttonsLayout)
		self.setMainLayout(self.__mainLayout)

		userTotalRadio.setChecked(True)
		self.connect(userTotalRadio, SIGNAL("toggled(bool)"), self.__setUserTotalGraph)
		self.connect(userAverageRadio, SIGNAL("toggled(bool)"), self.__setUserAverageGraph)
		self.connect(hostTotalRadio, SIGNAL("toggled(bool)"), self.__setHostTotalGraph)
		self.connect(hostAverageRadio, SIGNAL("toggled(bool)"), self.__setHostAverageGraph)

		self.connect(self.__projectsList, SIGNAL("itemChanged(QListWidgetItem *)"), self.__updateStatisticsGraph)
		self.connect(client, SIGNAL("getStatisticsRecv(PyQt_PyObject)"), self.__updateStatistics)
		client.getStatistics()
Exemple #31
0
class Target(preferences.Group):
    def __init__(self, page):
        super(Target, self).__init__(page)
        
        layout = QGridLayout()
        self.setLayout(layout)
        
        self.targetPDF = QRadioButton(toggled=page.changed)
        self.targetSVG = QRadioButton(toggled=page.changed)
        self.openDefaultView = QCheckBox(clicked=page.changed)
        
        layout.addWidget(self.targetPDF, 0, 0)
        layout.addWidget(self.targetSVG, 0, 1)
        layout.addWidget(self.openDefaultView, 1, 0, 1, 5)
        app.translateUI(self)
        
    def translateUI(self):
        self.setTitle(_("Default output format"))
        self.targetPDF.setText(_("PDF"))
        self.targetPDF.setToolTip(_(
            "Create PDF (Portable Document Format) documents by default."))
        self.targetSVG.setText(_("SVG"))
        self.targetSVG.setToolTip(_(
            "Create SVG (Scalable Vector Graphics) documents by default."))
        self.openDefaultView.setText(_("Open default viewer after successful compile"))
        self.openDefaultView.setToolTip(_(
            "Shows the PDF or SVG music view when a compile job finishes "
            "successfully."))
    
    def loadSettings(self):
        s = settings()
        target = s.value("default_output_target", "pdf", type(""))
        if target == "svg":
            self.targetSVG.setChecked(True)
            self.targetPDF.setChecked(False)
        else:
            self.targetSVG.setChecked(False)
            self.targetPDF.setChecked(True)
        self.openDefaultView.setChecked(s.value("open_default_view", True, bool))
        
    def saveSettings(self):
        s = settings()
        if self.targetSVG.isChecked():
            target = "svg"
        else:
            target = "pdf"
        s.setValue("default_output_target", target)
        s.setValue("open_default_view", self.openDefaultView.isChecked())
Exemple #32
0
class StartSession(preferences.Group):
    def __init__(self, page):
        super(StartSession, self).__init__(page)

        grid = QGridLayout()
        self.setLayout(grid)

        def changed():
            self.changed.emit()
            self.combo.setEnabled(self.custom.isChecked())

        self.none = QRadioButton(toggled=changed)
        self.lastused = QRadioButton(toggled=changed)
        self.custom = QRadioButton(toggled=changed)
        self.combo = QComboBox(currentIndexChanged=changed)

        grid.addWidget(self.none, 0, 0, 1, 2)
        grid.addWidget(self.lastused, 1, 0, 1, 2)
        grid.addWidget(self.custom, 2, 0, 1, 1)
        grid.addWidget(self.combo, 2, 1, 1, 1)

        app.translateUI(self)

    def translateUI(self):
        self.setTitle(
            _("Session to load if Frescobaldi is started without arguments"))
        self.none.setText(_("Start with no session"))
        self.lastused.setText(_("Start with last used session"))
        self.custom.setText(_("Start with session:"))

    def loadSettings(self):
        s = QSettings()
        s.beginGroup("session")
        startup = s.value("startup", "none", type(""))
        if startup == "lastused":
            self.lastused.setChecked(True)
        elif startup == "custom":
            self.custom.setChecked(True)
        else:
            self.none.setChecked(True)
        sessionNames = sessions.sessionNames()
        self.combo.clear()
        self.combo.addItems(sessionNames)
        custom = s.value("custom", "", type(""))
        if custom in sessionNames:
            self.combo.setCurrentIndex(sessionNames.index(custom))

    def saveSettings(self):
        s = QSettings()
        s.beginGroup("session")
        s.setValue("custom", self.combo.currentText())
        if self.custom.isChecked():
            startup = "custom"
        elif self.lastused.isChecked():
            startup = "lastused"
        else:
            startup = "none"
        s.setValue("startup", startup)
Exemple #33
0
class StartSession(preferences.Group):
    def __init__(self, page):
        super(StartSession, self).__init__(page)
        
        grid = QGridLayout()
        self.setLayout(grid)
        
        def changed():
            self.changed.emit()
            self.combo.setEnabled(self.custom.isChecked())
        
        self.none = QRadioButton(toggled=changed)
        self.lastused = QRadioButton(toggled=changed)
        self.custom = QRadioButton(toggled=changed)
        self.combo = QComboBox(currentIndexChanged=changed)
        
        grid.addWidget(self.none, 0, 0, 1, 2)
        grid.addWidget(self.lastused, 1, 0, 1, 2)
        grid.addWidget(self.custom, 2, 0, 1, 1)
        grid.addWidget(self.combo, 2, 1, 1, 1)

        app.translateUI(self)
        
    def translateUI(self):
        self.setTitle(_("Session to load if Frescobaldi is started without arguments"))
        self.none.setText(_("Start with no session"))
        self.lastused.setText(_("Start with last used session"))
        self.custom.setText(_("Start with session:"))
        
    def loadSettings(self):
        s = QSettings()
        s.beginGroup("session")
        startup = s.value("startup", "none", type(""))
        if startup ==  "lastused":
            self.lastused.setChecked(True)
        elif startup == "custom":
            self.custom.setChecked(True)
        else:
            self.none.setChecked(True)
        sessionNames = sessions.sessionNames()
        self.combo.clear()
        self.combo.addItems(sessionNames)
        custom = s.value("custom", "", type(""))
        if custom in sessionNames:
            self.combo.setCurrentIndex(sessionNames.index(custom))

    def saveSettings(self):
        s = QSettings()
        s.beginGroup("session")
        s.setValue("custom", self.combo.currentText())
        if self.custom.isChecked():
            startup = "custom"
        elif self.lastused.isChecked():
            startup = "lastused"
        else:
            startup = "none"
        s.setValue("startup", startup)
Exemple #34
0
class DatabaseTypePage(QWizardPage):
    def __init__(self, parent=None):
        super(DatabaseTypePage, self).__init__(parent)

        self.setTitle(self.tr(u"Typ databáze"))
        self.textRB = QRadioButton(QApplication.translate("DatabaseTypePage", 'Databáze uložená jako textové soubory v adresáři', None, QApplication.UnicodeUTF8), None)
        self.pgRB = QRadioButton(QApplication.translate("DatabaseTypePage", 'Databáze PostGIS', None, QApplication.UnicodeUTF8), None)
        self.setCheckedButton()

        grid = QGridLayout()
        grid.addWidget(self.textRB, 0, 0)
        grid.addWidget(self.pgRB, 1, 0)

        self.setLayout(grid)

        self.connect(self.textRB, SIGNAL("clicked()"), self.updateDatabaseTypeText)
        self.connect(self.pgRB, SIGNAL("clicked()"), self.updateDatabaseTypePG)

    def setCheckedButton(self):
        dbType = config['selectedDatabaseType']
        if dbType == 'textFile_DBHandler':
            return self.textRB.setChecked(True)
        elif dbType == 'postGIS_DBHandler':
            return self.pgRB.setChecked(True)

    def updateDatabaseTypeText(self):
        config['selectedDatabaseType'] = 'textFile_DBHandler'

    def updateDatabaseTypePG(self):
        config['selectedDatabaseType'] = 'postGIS_DBHandler'

    def nextId(self):
        if self.textRB.isChecked():
            return LicenseWizard.PageTextFileDBHandler
        else:
            return LicenseWizard.PagePostGISDBHandler
Exemple #35
0
class CADOptionsToolbar_ModifyOffset(CADOptionsToolbar):
    def __init__(self, layerType):
        super(CADOptionsToolbar_ModifyOffset, self).__init__()

        self.segmentChoice = QRadioButton(
            tr(u"Segment"))
        self.segmentChoice.setChecked(Qt.Checked)
        self.featureChoice = QRadioButton(
            tr(u"Feature"))
        self.optionsToolBar.addWidget(self.segmentChoice)
        self.optionsToolBar.addWidget(self.featureChoice)

        if layerType == QGis.Polygon:
            self.segmentChoice.setChecked(Qt.Unchecked)
            self.featureChoice.setChecked(Qt.Checked)
            self.segmentChoice.setEnabled(False)
            self.featureChoice.setEnabled(False)
        elif layerType == QGis.Line:
            self.segmentChoice.setEnabled(True)
            self.featureChoice.setEnabled(True)
Exemple #36
0
class Preferences(QDialog):
    def __init__(self, parent=None, test=False):
        super(Preferences, self).__init__(parent)
        self.parent = parent
        self.test = test

        saveQL = QLabel('<html><b>' + self.tr('Save files') + '</b></html>')
        existQL = QLabel(self.tr('Existing files:'))
        self.exst_prefixQRB = QRadioButton(self.tr("Add '~' prefix"))
        self.exst_overwriteQRB = QRadioButton(self.tr('Overwrite'))
        exist_layout = utils.add_to_layout('h', self.exst_prefixQRB,
                                           self.exst_overwriteQRB)

        defaultQL = QLabel(self.tr('Default output destination:'))
        self.defaultQLE = QLineEdit()
        self.defaultQTB = QToolButton()
        self.defaultQTB.setText('...')
        deafult_fol_layout = utils.add_to_layout('h', self.defaultQLE,
                                                 self.defaultQTB)
        nameQL = QLabel('<html><b>' + self.tr('Name files') + '</b></html>')
        prefixQL = QLabel(self.tr('Prefix:'))
        suffixQL = QLabel(self.tr('Suffix:'))
        self.prefixQLE = QLineEdit()
        self.suffixQLE = QLineEdit()
        grid = utils.add_to_grid([prefixQL, self.prefixQLE],
                                 [suffixQL, self.suffixQLE])
        prefix_layout = utils.add_to_layout('h', grid, None)

        tabwidget1_layout = utils.add_to_layout('v', saveQL,
                                                QSpacerItem(14, 13), existQL,
                                                exist_layout,
                                                QSpacerItem(14, 13), defaultQL,
                                                deafult_fol_layout,
                                                QSpacerItem(13, 13), nameQL,
                                                QSpacerItem(14, 13),
                                                prefix_layout, None)

        ffmpegQL = QLabel('<html><b>FFmpeg</b></html>')
        default_cmd_ffmpegQL = QLabel(self.tr('Default command:'))
        self.ffmpegcmdQLE = QLineEdit()

        vidcodecsQL = QLabel('<html><b>' + self.tr('Video codecs') +
                             '</b></html>')
        self.vidcodecsQPTE = QPlainTextEdit()
        audcodecsQL = QLabel('<html><b>' + self.tr('Audio codecs') +
                             '</b></html>')
        self.audcodecsQPTE = QPlainTextEdit()
        extraformatsffmpegQL = QLabel('<html><b>' + self.tr('Extra formats') +
                                      '</b></html>')
        self.extraformatsffmpegQPTE = QPlainTextEdit()

        gridlayout = utils.add_to_grid(
            [vidcodecsQL, audcodecsQL, extraformatsffmpegQL], [
                self.vidcodecsQPTE, self.audcodecsQPTE,
                self.extraformatsffmpegQPTE
            ])

        defvidcodecsQPB = QPushButton(self.tr("Default video codecs"))
        defaudcodecsQPB = QPushButton(self.tr("Default audio codecs"))

        hlayout1 = utils.add_to_layout('h', None, defvidcodecsQPB,
                                       defaudcodecsQPB)

        tabwidget2_layout = utils.add_to_layout('v', ffmpegQL,
                                                QSpacerItem(14, 13),
                                                default_cmd_ffmpegQL,
                                                self.ffmpegcmdQLE,
                                                QSpacerItem(20, 20),
                                                gridlayout, hlayout1, None)

        imagemagickQL = QLabel('<html><b>ImageMagick (convert)</b></html>')
        default_cmd_imageQL = QLabel(self.tr('Default options:'))
        self.imagecmdQLE = QLineEdit()

        extraformatsimageQL = QLabel('<html><b>' + self.tr('Extra formats') +
                                     '</b></html>')
        self.extraformatsimageQPTE = QPlainTextEdit()

        hlayout2 = utils.add_to_layout('h', self.extraformatsimageQPTE,
                                       QSpacerItem(220, 20))

        tabwidget3_layout = utils.add_to_layout('v', imagemagickQL,
                                                QSpacerItem(14, 13),
                                                default_cmd_imageQL,
                                                self.imagecmdQLE,
                                                QSpacerItem(20, 20),
                                                extraformatsimageQL, hlayout2,
                                                None)

        widget1 = QWidget()
        widget1.setLayout(tabwidget1_layout)
        widget2 = QWidget()
        widget2.setLayout(tabwidget2_layout)
        widget3 = QWidget()
        widget3.setLayout(tabwidget3_layout)
        tabWidget = QTabWidget()
        tabWidget.addTab(widget1, self.tr('General'))
        tabWidget.addTab(widget2, self.tr('Audio/Video'))
        tabWidget.addTab(widget3, self.tr('Images'))

        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok
                                     | QDialogButtonBox.Cancel)

        final_layout = utils.add_to_layout('v', tabWidget, None, buttonBox)
        self.setLayout(final_layout)

        self.defaultQTB.clicked.connect(self.open_dir)
        buttonBox.accepted.connect(self.save_settings)
        buttonBox.rejected.connect(self.reject)
        defvidcodecsQPB.clicked.connect(self.set_default_videocodecs)
        defaudcodecsQPB.clicked.connect(self.set_default_audiocodecs)

        self.resize(400, 450)
        self.setWindowTitle(self.tr('Preferences'))

        QTimer.singleShot(0, self.load_settings)

    def load_settings(self):
        """Load settings and update graphical widgets with loaded values."""
        settings = QSettings()
        overwrite_existing = utils.str_to_bool(
            settings.value('overwrite_existing'))
        default_output = settings.value('default_output')
        prefix = settings.value('prefix')
        suffix = settings.value('suffix')
        default_command = settings.value('default_command')
        videocodecs = settings.value('videocodecs')
        audiocodecs = settings.value('audiocodecs')
        extraformats_video = settings.value('extraformats')
        default_command_image = settings.value('default_command_image')
        extraformats_image = settings.value('extraformats_image')

        # QSettings.value() returns str() in python3, not QVariant() as in p2
        if overwrite_existing:
            self.exst_overwriteQRB.setChecked(True)
        else:
            self.exst_prefixQRB.setChecked(True)
        if default_output:
            self.defaultQLE.setText(default_output)
        if prefix:
            self.prefixQLE.setText(prefix)
        if suffix:
            self.suffixQLE.setText(suffix)
        if default_command:
            self.ffmpegcmdQLE.setText(default_command)
        else:
            self.ffmpegcmdQLE.setText(config.default_ffmpeg_cmd)

        if not videocodecs:
            self.set_default_videocodecs()
        else:
            self.vidcodecsQPTE.setPlainText(videocodecs)
        if not audiocodecs:
            self.set_default_audiocodecs
        else:
            self.audcodecsQPTE.setPlainText(audiocodecs)
        self.extraformatsffmpegQPTE.setPlainText(extraformats_video)

        if default_command_image:
            self.imagecmdQLE.setText(default_command_image)
        else:
            self.imagecmdQLE.setText(config.default_imagemagick_cmd)
        self.extraformatsimageQPTE.setPlainText(extraformats_image)

    def set_default_videocodecs(self):
        self.vidcodecsQPTE.setPlainText("\n".join(config.video_codecs))

    def set_default_audiocodecs(self):
        self.audcodecsQPTE.setPlainText("\n".join(config.audio_codecs))

    def open_dir(self):
        """Get a directory name using a standard Qt dialog and update
        self.defaultQLE with dir's name."""
        if self.defaultQLE.isEnabled():
            _dir = QFileDialog.getExistingDirectory(
                self, 'FF Multi Converter - ' +
                self.tr('Choose default output destination'), config.home)
            if _dir:
                self.defaultQLE.setText(_dir)

    def save_settings(self):
        """Set settings values, extracting the appropriate information from
        the graphical widgets."""
        # remove empty codecs
        videocodecs = []
        audiocodecs = []
        extraformats_video = []
        extraformats_image = []

        for i in self.vidcodecsQPTE.toPlainText().split("\n"):
            i = i.strip()
            if len(i.split()) == 1 and i not in videocodecs:  # i single word
                videocodecs.append(i)

        for i in self.audcodecsQPTE.toPlainText().split("\n"):
            i = i.strip()
            if len(i.split()) == 1 and i not in audiocodecs:
                audiocodecs.append(i)

        for i in self.extraformatsffmpegQPTE.toPlainText().split("\n"):
            i = i.strip()
            if len(i.split()) == 1 and i not in extraformats_video \
            and i not in config.video_formats:
                extraformats_video.append(i)

        for i in self.extraformatsimageQPTE.toPlainText().split("\n"):
            i = i.strip()
            if len(i.split()) == 1 and i not in extraformats_image \
            and i not in config.image_formats:
                extraformats_image.append(i)

        videocodecs = "\n".join(sorted(videocodecs))
        audiocodecs = "\n".join(sorted(audiocodecs))
        extraformats_video = "\n".join(sorted(extraformats_video))
        extraformats_image = "\n".join(sorted(extraformats_image))

        settings = QSettings()
        settings.setValue('overwrite_existing',
                          self.exst_overwriteQRB.isChecked())
        settings.setValue('default_output', self.defaultQLE.text())
        settings.setValue('prefix', self.prefixQLE.text())
        settings.setValue('suffix', self.suffixQLE.text())
        settings.setValue('default_command', self.ffmpegcmdQLE.text())
        settings.setValue('videocodecs', videocodecs)
        settings.setValue('audiocodecs', audiocodecs)
        settings.setValue('extraformats', extraformats_video)
        settings.setValue('default_command_image', self.imagecmdQLE.text())
        settings.setValue('extraformats_image', extraformats_image)

        self.accept()
class ProxyConfigPage(QWizardPage):
    def __init__(self, parent=None,key=None):
        super(ProxyConfigPage, self).__init__(parent)
        
        self.parent = parent 
        self.key = key
        
        try:
            (pxytype,pxyhost,pxyport,pxyauth,pxyusr,pxypwd) = self.parent.mfr.readProxyConfig()
        except:
            (pxytype,pxyhost,pxyport,pxyauth,pxyusr,pxypwd) = (None,)*6
            
        #if we use enums for pxy types
        #pxytype = [a[0] for a in WFSDataStore.PROXY_TYPE.reverse.items() if a[1]==pxytype][0]

            
        self.setTitle(self.parent.plist.get(self.key)[1]+' Configuration Options')
        self.setSubTitle('Enter the hostname/ip-address, port number and authentication details of your HTTP proxy')

        QToolTip.setFont(QFont('SansSerif', 10))
        
        #labels
        directlabel = QLabel('Direct Connection')
        systemlabel = QLabel('Use System Proxy settings')
        proxylabel = QLabel('Configure Proxy')
        
        hostLabel = QLabel('Proxy Host')
        portLabel = QLabel('Proxy Port')
        authLabel = QLabel('Authentication')
        usrLabel = QLabel('Username')
        pwdLabel = QLabel('Password')
        
        
        #radio buttons
        self.directradio = QRadioButton()
        self.systemradio = QRadioButton()
        self.usrdefradio = QRadioButton()
        
        
        #edit boxes
        self.hostEdit = QLineEdit(pxyhost)
        self.hostEdit.setToolTip('Enter Proxy host (IP Address or hostname)')
        self.portEdit = QLineEdit(pxyport)
        self.portEdit.setToolTip('Enter Proxy port')
        
        #dropdown
        self.authSelect = QComboBox()
        self.authSelect.addItem('')
        self.authSelect.setToolTip('Select appropriate proxy authentication mechanism')
        self.authSelect.addItems(WFSDataStore.PROXY_AUTH)
        self.authSelect.setCurrentIndex(0 if LU.assessNone(pxyauth) is None else WFSDataStore.PROXY_AUTH.index(pxyauth))
        
        self.usrEdit = QLineEdit(pxyusr)
        self.usrEdit.setToolTip('Enter your proxy username (if required)')
        self.pwdEdit = QLineEdit('')#pxypwd
        self.usrEdit.setToolTip('Enter your proxy password (if required)')
        self.pwdEdit.setEchoMode(QLineEdit.Password)
        
        self.portEdit.setValidator(QRegExpValidator(QRegExp("\d{1,5}"), self))
        
        self.registerField(self.key+"host",self.hostEdit)
        self.registerField(self.key+"port",self.portEdit)
        self.registerField(self.key+"auth",self.authSelect,"currentIndex")
        self.registerField(self.key+"usr",self.usrEdit)
        self.registerField(self.key+"pwd",self.pwdEdit)
        
        self.registerField(self.key+WFSDataStore.PROXY_TYPE[0],self.directradio)
        self.registerField(self.key+WFSDataStore.PROXY_TYPE[1],self.systemradio)
        self.registerField(self.key+WFSDataStore.PROXY_TYPE[2],self.usrdefradio)

        #grid
        grid1 = QGridLayout()
        grid1.setSpacing(10)
        
        grid2 = QGridLayout()
        grid2.setSpacing(10)
        
        #layout
        hbox = QHBoxLayout()
        grid1.addWidget(self.directradio,1,0)
        grid1.addWidget(directlabel,1,1)
        grid1.addWidget(self.systemradio,2,0)
        grid1.addWidget(systemlabel,2,1)
        grid1.addWidget(self.usrdefradio,3,0)
        grid1.addWidget(proxylabel,3,1)
        hbox.addLayout(grid1)
        hbox.addStretch(1)
        
        
        self.gbox = QGroupBox('Proxy Configuration')

        #dsu
        subs = False
        if pxytype == WFSDataStore.PROXY_TYPE[1]:
            #system
            self.systemradio.setChecked(True)
        elif pxytype == WFSDataStore.PROXY_TYPE[2]:
            #user_defined
            self.usrdefradio.setChecked(True)
            subs = True
        else:
            #direct (default)
            self.directradio.setChecked(True)
            
        self.setUserDefined(subs)
        
        self.directradio.clicked.connect(self.disableUserDefined)
        self.systemradio.clicked.connect(self.disableUserDefined)
        self.usrdefradio.clicked.connect(self.enableUserDefined)
        
        grid2.addWidget(hostLabel, 1, 0)
        grid2.addWidget(self.hostEdit, 1, 2)
        
        grid2.addWidget(portLabel, 2, 0)
        grid2.addWidget(self.portEdit, 2, 2)
        
        grid2.addWidget(authLabel, 3, 0)
        grid2.addWidget(self.authSelect, 3, 2)
        
        grid2.addWidget(usrLabel, 4, 0)
        grid2.addWidget(self.usrEdit, 4, 2)
        
        grid2.addWidget(pwdLabel, 5, 0)
        grid2.addWidget(self.pwdEdit, 5, 2)
             
        self.gbox.setLayout(grid2)
        
        #layout    
        vbox = QVBoxLayout()
        vbox.addLayout(hbox)
        vbox.insertWidget(1,self.gbox)
        self.setLayout(vbox)  
        
    def selectConfFile(self):
        self.fileEdit.setText(QFileDialog.getOpenFileName())

    def nextId(self):
        #now go to selected dest configger
        #return int(self.field("ldsdest").toString())
    
        if self.testConnection():
            return self.field("ldsdest")
        return self.parent.plist.get('proxy')[0]
    
    def disableUserDefined(self):
        self.setUserDefined(False)
        
    def enableUserDefined(self):
        self.setUserDefined(True)
        
    def setUserDefined(self,udval):
        self.gbox.setEnabled(udval)
        self.hostEdit.setEnabled(udval)
        self.portEdit.setEnabled(udval)
        self.authSelect.setEnabled(udval)
        self.usrEdit.setEnabled(udval)
        self.pwdEdit.setEnabled(udval)
        
    def testConnection(self):
        if not self.usrdefradio.isChecked(): 
            return True
        if not any(f for f in (self.hostEdit.isModified(),self.portEdit.isModified(),
                               self.usrEdit.isModified(),self.pwdEdit.isModified())):
            return False
        proxydata = {'type':'USER','host':str(self.hostEdit.text()),'port':str(self.portEdit.text()),
                     'auth':str(WFSDataStore.PROXY_AUTH[self.authSelect.currentIndex()-1]),
                     'user':str(self.usrEdit.text()),'pass':str(self.pwdEdit.text())}
        wfsdata = {'key':'00112233445566778899aabbccddeeff'}#key not necessary but config tester checks format
        lds = LDSDataStore(None,{'Proxy':proxydata,'WFS':wfsdata}) 
        lds.applyConfigOptions()
        
        try:
            #use website likely to be up (that isn't LDS so error is distinct)
            lds.initDS('http://www.google.com/',False)
        except DatasourceConnectException as dce:
            QMessageBox.warning(self, 'Connection Error', 'Cannot connect to network using proxy parameters provided {}'.format(dce), 'OK')
            return False
        except DatasourceOpenException as dse:
            QMessageBox.info(self, 'Connection Warning', 'Connection parameters confirmed, Datasource initialisation untested. Continuing.\n{}'.format(dse), 'OK')
            return True
        except RuntimeError as rte:
            QMessageBox.warning(self, 'RuntimeError', 'Error connecting to network: '+str(rte), 'OK')
            return False
        return True
Exemple #38
0
class FindInFilesDialog(QDialog):
    def __init__(self, result_widget, parent):
        QDialog.__init__(self, parent)
        self._find_thread = FindInFilesThread()
        self.setWindowTitle("Find in files")
        self.resize(400, 300)
        #MAIN LAYOUT
        main_vbox = QVBoxLayout(self)

        self.pattern_line_edit = QLineEdit()
        self.dir_name_root = None
        self.user_home = os.path.expanduser('~')
        self.dir_combo = QComboBox()
        self.dir_combo.addItem(self.user_home)
        self.dir_combo.setEditable(True)
        self.open_button = QPushButton(QIcon(resources.IMAGES['find']),
                                       self.tr("Open"))
        self.filters_line_edit = QLineEdit("*.py")
        self.replace_line = QLineEdit()
        self.replace_line.setEnabled(False)
        self.check_replace = QCheckBox(self.tr("Replace: "))
        self.case_checkbox = QCheckBox(self.tr("C&ase sensitive"))
        self.type_checkbox = QCheckBox(self.tr("R&egular Expression"))
        self.recursive_checkbox = QCheckBox(self.tr("Rec&ursive"))
        self.recursive_checkbox.setCheckState(Qt.Checked)
        self.phrase_radio = QRadioButton(
            self.tr("Search by Phrase (Exact Match)."))
        self.phrase_radio.setChecked(True)
        self.words_radio = QRadioButton(
            self.tr("Search for all the words "
                    "(anywhere in the document, not together)."))
        self.find_button = QPushButton(self.tr("Find!"))
        self.find_button.setMaximumWidth(150)
        self.cancel_button = QPushButton(self.tr("Cancel"))
        self.cancel_button.setMaximumWidth(150)
        self.result_widget = result_widget

        hbox = QHBoxLayout()
        hbox.addWidget(self.find_button)
        hbox.addWidget(self.cancel_button)

        #main section
        find_group_box = QGroupBox(self.tr("Main"))
        grid = QGridLayout()
        grid.addWidget(QLabel(self.tr("Text: ")), 0, 0)
        grid.addWidget(self.pattern_line_edit, 0, 1)
        grid.addWidget(QLabel(self.tr("Directory: ")), 1, 0)
        grid.addWidget(self.dir_combo, 1, 1)
        grid.addWidget(self.open_button, 1, 2)
        grid.addWidget(QLabel(self.tr("Filter: ")), 2, 0)
        grid.addWidget(self.filters_line_edit, 2, 1)
        grid.addWidget(self.check_replace, 3, 0)
        grid.addWidget(self.replace_line, 3, 1)

        find_group_box.setLayout(grid)
        #add main section to MAIN LAYOUT
        main_vbox.addWidget(find_group_box)

        #options sections
        options_group_box = QGroupBox(self.tr("Options"))
        gridOptions = QGridLayout()
        gridOptions.addWidget(self.case_checkbox, 0, 0)
        gridOptions.addWidget(self.type_checkbox, 1, 0)
        gridOptions.addWidget(self.recursive_checkbox, 2, 0)
        gridOptions.addWidget(self.phrase_radio, 0, 1)
        gridOptions.addWidget(self.words_radio, 1, 1)

        options_group_box.setLayout(gridOptions)
        #add options sections to MAIN LAYOUT
        main_vbox.addWidget(options_group_box)

        #add buttons to MAIN LAYOUT
        main_vbox.addLayout(hbox)

        #Focus
        self.pattern_line_edit.setFocus()
        self.open_button.setFocusPolicy(Qt.NoFocus)

        #signal
        self.connect(self.open_button, SIGNAL("clicked()"), self._select_dir)
        self.connect(self.find_button, SIGNAL("clicked()"),
                     self._find_in_files)
        self.connect(self.cancel_button, SIGNAL("clicked()"),
                     self._kill_thread)
        self.connect(self._find_thread, SIGNAL("found_pattern(PyQt_PyObject)"),
                     self._found_match)
        self.connect(self._find_thread, SIGNAL("finished()"),
                     self._find_thread_finished)
        self.connect(self.type_checkbox, SIGNAL("stateChanged(int)"),
                     self._change_radio_enabled)
        self.connect(self.check_replace, SIGNAL("stateChanged(int)"),
                     self._replace_activated)
        self.connect(self.words_radio, SIGNAL("clicked(bool)"),
                     self._words_radio_pressed)

    def _replace_activated(self):
        self.replace_line.setEnabled(self.check_replace.isChecked())
        self.phrase_radio.setChecked(True)

    def _words_radio_pressed(self, value):
        self.replace_line.setEnabled(not value)
        self.check_replace.setChecked(not value)
        self.words_radio.setChecked(True)

    def _change_radio_enabled(self, val):
        enabled = not self.type_checkbox.isChecked()
        self.phrase_radio.setEnabled(enabled)
        self.words_radio.setEnabled(enabled)

    def show(self, actual_project=None, actual=None):
        self.dir_combo.clear()
        self.dir_name_root = actual_project if \
            actual_project else [self.user_home]
        self.dir_combo.addItems(self.dir_name_root)
        if actual:
            index = self.dir_combo.findText(actual)
            self.dir_combo.setCurrentIndex(index)
        super(FindInFilesDialog, self).show()
        self.pattern_line_edit.setFocus()

    def reject(self):
        self._kill_thread()
        # Crazy hack to avoid circular imports
        self.result_widget.parent().parent().parent().hide()
        super(FindInFilesDialog, self).reject()

    def _find_thread_finished(self):
        self.emit(SIGNAL("finished()"))
        self._find_thread.wait()

    def _select_dir(self):
        dir_name = QFileDialog.getExistingDirectory(
            self, self.tr("Open Directory"), self.dir_combo.currentText(),
            QFileDialog.ShowDirsOnly)
        index = self.dir_combo.findText(dir_name)
        if index >= 0:
            self.dir_combo.setCurrentIndex(index)
        else:
            self.dir_combo.insertItem(0, dir_name)
            self.dir_combo.setCurrentIndex(0)

    def _found_match(self, result):
        file_name = result[0]
        items = result[1]
        self.result_widget.update_result(self.dir_combo.currentText(),
                                         file_name, items)

    def _kill_thread(self):
        if self._find_thread.isRunning():
            self._find_thread.cancel()
        self.accept()

    def _find_in_files(self):
        self.emit(SIGNAL("findStarted()"))
        self._kill_thread()
        self.result_widget.clear()
        pattern = self.pattern_line_edit.text()
        dir_name = self.dir_combo.currentText()

        filters = re.split("[,;]", self.filters_line_edit.text())

        # Version of PyQt API 1
        # filters = self.filters_line_edit.text().split(QRegExp("[,;]"),
        #     QString.SkipEmptyParts)

        #remove the spaces in the words Ex. (" *.foo"--> "*.foo")
        filters = [f.strip() for f in filters]
        case_sensitive = self.case_checkbox.isChecked()
        type_ = QRegExp.RegExp if \
            self.type_checkbox.isChecked() else QRegExp.FixedString
        recursive = self.recursive_checkbox.isChecked()
        by_phrase = True
        if self.phrase_radio.isChecked() or self.type_checkbox.isChecked():
            regExp = QRegExp(pattern, case_sensitive, type_)
        elif self.words_radio.isChecked():
            by_phrase = False
            type_ = QRegExp.RegExp
            pattern = '|'.join([word.strip() for word in pattern.split()])
            regExp = QRegExp(pattern, case_sensitive, type_)
        #save a reference to the root directory where we find
        self.dir_name_root = dir_name
        self._find_thread.find_in_files(dir_name, filters, regExp, recursive,
                                        by_phrase)
class ShortcutEditDialog(QDialog):
    """A modal dialog to view and/or edit keyboard shortcuts."""
    
    def __init__(self, parent=None, conflictCallback=None, *cbArgs):
        """conflictCallback is a optional method called when a shortcut is changed.
        
        cbArgs is optional arguments of the conflictCallback method.
        it should return the name of the potential conflict or a null value """
        
        super(ShortcutEditDialog, self).__init__(parent)
        self.conflictCallback = conflictCallback
        self.cbArgs = cbArgs
        self.setMinimumWidth(400)
        # create gui
        
        layout = QVBoxLayout()
        layout.setSpacing(10)
        self.setLayout(layout)
        
        top = QHBoxLayout()
        top.setSpacing(4)
        p = self.toppixmap = QLabel()
        l = self.toplabel = QLabel()
        top.addWidget(p)
        top.addWidget(l, 1)
        layout.addLayout(top)
        grid = QGridLayout()
        grid.setSpacing(4)
        grid.setColumnStretch(1, 2)
        layout.addLayout(grid)
        
        self.buttonDefault = QRadioButton(self, toggled=self.slotButtonDefaultToggled)
        self.buttonNone = QRadioButton(self)
        self.lconflictDefault = QLabel('test')
        self.lconflictDefault.setStyleSheet("color : red;")
        self.lconflictDefault.setVisible(False)
        self.buttonCustom = QRadioButton(self)
        grid.addWidget(self.buttonDefault, 0, 0, 1, 2)
        grid.addWidget(self.lconflictDefault, 1, 0, 1, 2)
        grid.addWidget(self.buttonNone, 2, 0, 1, 2)
        grid.addWidget(self.buttonCustom, 3, 0, 1, 2)
        
        self.keybuttons = []
        self.keylabels = []
        self.conflictlabels = []
        for num in range(4):
            l = QLabel(self)
            l.setStyleSheet("margin-left: 2em;")
            l.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
            b = KeySequenceWidget(self, num)
            b.keySequenceChanged.connect(self.slotKeySequenceChanged)
            l.setBuddy(b)
            self.keylabels.append(l)
            self.keybuttons.append(b)
            grid.addWidget(l, num+4+num, 0)
            grid.addWidget(b, num+4+num, 1)
            lconflict = QLabel()
            lconflict.setStyleSheet("color : red;")
            self.conflictlabels.append(lconflict)
            lconflict.setVisible(False)
            grid.addWidget(lconflict, num+5+num, 0, 1, 2, Qt.AlignHCenter)
        
        layout.addWidget(Separator(self))
        
        b = QDialogButtonBox(self)
        b.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        layout.addWidget(b)
        b.accepted.connect(self.accept)
        b.rejected.connect(self.reject)
        app.translateUI(self)
    
    def translateUI(self):
        self.setWindowTitle(app.caption(_("window title", "Edit Shortcut")))
        self.buttonNone.setText(_("&No shortcut"))
        self.buttonCustom.setText(_("Use a &custom shortcut:"))
        for num in range(4):
            self.keylabels[num].setText(_("Alternative #{num}:").format(num=num) if num else _("Primary shortcut:"))
    
    def slotKeySequenceChanged(self, num):
        """Called when one of the keysequence buttons has changed."""
        self.checkConflict(num)
        self.buttonCustom.setChecked(True)
    
    def slotButtonDefaultToggled(self, val):
        if self.conflictCallback is not None:
            if not val:
                self.lconflictDefault.setVisible(False)
            else:
                if self._default:
                    conflictList = []
                    for s in self._default:
                        conflictName = self.conflictCallback(s, *self.cbArgs)
                        if conflictName:
                            conflictList.append(conflictName)
                    if conflictList:
                        text = _("Conflict with: {name}").format(
                            name="<b>{0}</b>".format(', '.join(conflictList)))
                        self.lconflictDefault.setText(text)
                        self.lconflictDefault.setVisible(True)
            QTimer.singleShot(0, self.adjustSize)
                    
    def checkConflict(self, num):
        if self.conflictCallback is not None:
            conflictName = self.conflictCallback(self.keybuttons[num].shortcut(), *self.cbArgs)
            if conflictName:
                text = _("Conflict with: {name}").format(
                    name="<b>{0}</b>".format(conflictName))
                self.conflictlabels[num].setText(text)
                self.conflictlabels[num].setVisible(True)
            else:
                self.conflictlabels[num].setVisible(False)
            QTimer.singleShot(0, self.adjustSize)
     
    def editAction(self, action, default=None):
        # load the action
        self._action = action
        self._default = default
        self.toplabel.setText('<p>{0}</p>'.format(
            _("Here you can edit the shortcuts for {name}").format(
                name='<br/><b>{0}</b>:'.format(action.text()))))
        self.toppixmap.setPixmap(action.icon().pixmap(32))
        shortcuts = action.shortcuts()
        self.buttonDefault.setVisible(bool(default))
        if default is not None and shortcuts == default:
            self.buttonDefault.setChecked(True)
        else:
            if shortcuts:
                self.buttonCustom.setChecked(True)
                for num, key in enumerate(shortcuts[:4]):
                    self.keybuttons[num].setShortcut(key)
                    self.checkConflict(num)
            else:
                self.buttonNone.setChecked(True)
            
        if default:
            ds = "; ".join(key.toString(QKeySequence.NativeText) for key in default)
        else:
            ds = _("no keyboard shortcut", "none")
        self.buttonDefault.setText(_("Use &default shortcut ({name})").format(name=ds))
        return self.exec_()
        
    def done(self, result):
        if result:
            shortcuts = []
            if self.buttonDefault.isChecked():
                shortcuts = self._default
            elif self.buttonCustom.isChecked():
                for num in range(4):
                    seq = self.keybuttons[num].shortcut()
                    if not seq.isEmpty():
                        shortcuts.append(seq)
            self._action.setShortcuts(shortcuts)
        super(ShortcutEditDialog, self).done(result)
    def initDownloadTab(self):
        # # # Download Tab# # # 
        download_tab = QWidget()
        download_tab_layout = QVBoxLayout()
        self.tabWidget.addTab(download_tab, "Download HITs")

        # Status
        status_box = QGroupBox()
        status_box.setTitle("Status")
        status_layout = QGridLayout()
        self.table_turk = ContextTable(0, 4, self)
        self.table_turk.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table_turk.setColumnWidth(0, 160)
        self.table_turk.setColumnWidth(1, 50)
        self.table_turk.setColumnWidth(2, 90)
        self.table_turk.setColumnWidth(3, 90)
        # self.table_turk.verticalHeader().setVisible(False)

        # Set Headers
        header_0 = QTableWidgetItem()
        header_0.setText("Turker")
        self.table_turk.setHorizontalHeaderItem(0, header_0)

        header_1 = QTableWidgetItem()
        header_1.setText("HITs")
        self.table_turk.setHorizontalHeaderItem(1, header_1)

        header_2 = QTableWidgetItem()
        header_2.setText("Rejected")
        self.table_turk.setHorizontalHeaderItem(2, header_2)

        header_3 = QTableWidgetItem()
        header_3.setText("Approved")
        self.table_turk.setHorizontalHeaderItem(3, header_3)

        status_layout.addWidget(self.table_turk, 0, 0, 1, 2)

        # Status Button
        status_button = QPushButton('Update Status')
        status_button.clicked.connect(self.getStatus)

        status_layout.addWidget(status_button, 1, 1)
        status_box.setLayout(status_layout)
        download_tab_layout.addWidget(status_box) 

        # Download Button
        download_button = QPushButton("Download Results")
        download_button.clicked.connect(self.download)
        status_layout.addWidget(download_button, 1, 0)

        # Options Box
        options_box = QGroupBox()
        options_box.setTitle("Import results")
        options_box_layout = QGridLayout()
        matching = QRadioButton("Choose best matching Outlines")
        matching.setEnabled(False)
        review = QRadioButton("Review by hand")
        review.setChecked(True)
        review_button = QPushButton("Review Results")
        review_button.clicked.connect(self.review)

        # Import Button
        import_button = QPushButton("Import results")
        import_button.clicked.connect(self.importResults)

        options_box_layout.addWidget(review, 0, 0)
        options_box_layout.addWidget(review_button, 0, 1)
        options_box_layout.addWidget(matching, 1, 0)
        options_box_layout.addWidget(import_button, 2, 0, 1, 2)

        options_box.setLayout(options_box_layout)
        download_tab_layout.addWidget(options_box)
        download_tab.setLayout(download_tab_layout)
    def initManageTab(self):
        ###Manage Tab###
        manage_tab = QWidget()
        manage_tab_layout = QVBoxLayout()
        self.tabWidget.addTab(manage_tab, "Manage HITs")

        # Send Box
        send_box_layout = QVBoxLayout()
        subject = QLineEdit()
        subject_label = QLabel("Subject:")

        send_text = QTextEdit()
        send_button = QPushButton("Send Message")
        send_button.setMinimumWidth(135)

        send_button.clicked.connect(self.sendMessage)

        allTurkers = QRadioButton("Send message to all Turkers")
        allTurkers.setChecked(True)
        singleTurker = QRadioButton("Send message to single Turker")

        workerIDLabel = QLabel('Worker-ID:')
        workerID = QLineEdit()

        def checkState():
            # Set enabled if checked
            if allTurkers.isChecked():
                workerIDLabel.setEnabled(False)
                workerID.setEnabled(False)
            else:
                workerIDLabel.setEnabled(True)
                workerID.setEnabled(True)

        # Connect to check state
        allTurkers.clicked.connect(checkState)
        singleTurker.clicked.connect(checkState)
        checkState()

        # Choose if single or all turkers receive message
        chooseSendLayout = QHBoxLayout()
        chooseSendLayout.addWidget(singleTurker)
        chooseSendLayout.addWidget(workerIDLabel)
        chooseSendLayout.addWidget(workerID)

        # Send box layout
        send_box = QGroupBox()
        send_box_layout.addWidget(allTurkers)
        send_box_layout.addLayout(chooseSendLayout)
        send_box_layout.addWidget(subject_label)
        send_box_layout.addWidget(subject)
        send_box_layout.addWidget(send_text)
        send_box_layout.addWidget(send_button)
        send_box_layout.setAlignment(send_button, Qt.AlignRight)
        send_box.setTitle("Notify Workers")
        send_box.setLayout(send_box_layout)
        manage_tab_layout.addWidget(send_box)

        # Pay box
        payBox = QGroupBox()
        payBox.setTitle("Pay Workers")
        payBox_layout = QGridLayout()

        approveFeedbackLabel = QLabel("Approve Feedback:")
        approveFeedback = QTextEdit()
        approveFeedback.setText("Thank you for your work.")

        rejectFeedback = QTextEdit()
        rejectFeedback.setText("We are sorry, but we cannot accept your work because you did not follow the instructions or submitted careless work.")

        payBox_layout.addWidget(approveFeedbackLabel, 0, 0)
        payBox_layout.addWidget(approveFeedback , 1, 0, 1, 0)
        reject_label = QLabel("{0} HITs will be rejected".format(0))
        approve_label = QLabel("{0} HITs will be approved".format(0))
        pay_button = QPushButton("Pay Turkers")
        pay_button.clicked.connect(self.pay)

        payBox_layout.addWidget(reject_label, 2, 0)
        payBox_layout.addWidget(approve_label, 3, 0)
        payBox_layout.addWidget(pay_button, 4, 0)
        payBox.setLayout(payBox_layout)
        manage_tab_layout.addWidget(payBox)

        # Delete Box
        deleteBox = QGroupBox()
        deleteBox.setTitle("Clean up finished HITs")
        deleteBox_layout = QHBoxLayout()
        delete_label = QLabel("{0} HITs are finished and can be deleted".format(0))
        delete_button = QPushButton("Delete HITs")
        delete_button.clicked.connect(self.delete)
        deleteBox_layout.addWidget(delete_label)
        deleteBox_layout.addWidget(delete_button)
        deleteBox.setLayout(deleteBox_layout)
        manage_tab_layout.addWidget(deleteBox)

        # Evaluation Button
        evalButton = QPushButton("Evaluate")
        evalButton.clicked.connect(self.evaluate)
        manage_tab_layout.addWidget(evalButton)

        # Add layouts to tab
        manage_tab.setLayout(manage_tab_layout)
Exemple #42
0
    def __init__(self, parameter, parent=None):
        """Constructor

        :param parameter: A DefaultSelectParameter object.
        :type parameter: DefaultSelectParameter
        """
        super(DefaultSelectParameterWidget, self).__init__(parameter, parent)

        self.default_layout = QHBoxLayout()
        self.radio_button_layout = QHBoxLayout()
        self.radio_button_widget = QWidget()

        self.default_label = QLabel(tr('Default'))

        # Create radio button group
        self.default_input_button_group = QButtonGroup()

        # Define string enabler for radio button
        self.radio_button_enabler = self.input.itemData(0, Qt.UserRole)

        for i in range(len(self._parameter.default_labels)):
            if '%s' in self._parameter.default_labels[i]:
                label = (self._parameter.default_labels[i] %
                         self._parameter.default_values[i])
            else:
                label = self._parameter.default_labels[i]

            radio_button = QRadioButton(label)
            self.radio_button_layout.addWidget(radio_button)
            self.default_input_button_group.addButton(radio_button, i)
            if self._parameter.default_value == \
                    self._parameter.default_values[i]:
                radio_button.setChecked(True)

        # Create double spin box for custom value
        self.custom_value = QDoubleSpinBox()
        if self._parameter.default_values[-1]:
            self.custom_value.setValue(self._parameter.default_values[-1])
        has_min = False
        if self._parameter.minimum is not None:
            has_min = True
            self.custom_value.setMinimum(self._parameter.minimum)
        has_max = False
        if self._parameter.maximum is not None:
            has_max = True
            self.custom_value.setMaximum(self._parameter.maximum)
        if has_min and has_max:
            step = (self._parameter.maximum - self._parameter.minimum) / 100.0
            self.custom_value.setSingleStep(step)
        self.radio_button_layout.addWidget(self.custom_value)

        self.toggle_custom_value()

        # Reset the layout
        self.input_layout.setParent(None)
        self.help_layout.setParent(None)

        self.label.setParent(None)
        self.inner_input_layout.setParent(None)

        self.input_layout = QGridLayout()
        self.input_layout.setSpacing(0)

        self.input_layout.addWidget(self.label, 0, 0)
        self.input_layout.addLayout(self.inner_input_layout, 0, 1)
        self.input_layout.addWidget(self.default_label, 1, 0)
        self.input_layout.addLayout(self.radio_button_layout, 1, 1)

        self.main_layout.addLayout(self.input_layout)
        self.main_layout.addLayout(self.help_layout)

        # check every added combobox, it could have been toggled by
        # the existing keyword
        self.toggle_input()

        # Connect
        # noinspection PyUnresolvedReferences
        self.input.currentIndexChanged.connect(self.toggle_input)
        self.default_input_button_group.buttonClicked.connect(
            self.toggle_custom_value)
    def initSettingTab(self):
        # ##Setting Tab###
        setting_tab = QWidget()
        setting_tab_layout = QVBoxLayout()
        self.tabWidget.addTab(setting_tab, "Settings")

        # Task Box
        task_box = QGroupBox()
        task_box.setTitle(QString("Task properties"))
        task_layout = QGridLayout()

        # Name
        name = QLabel("Name:")
        name_value = QLineEdit() 
        name_value.setText(self.task.hittypename)
        name_value.setEnabled(False)
        clickable(name_value).connect(self.enable)
        task_layout.addWidget(name, 0, 1)
        task_layout.addWidget(name_value, 0, 2, 1, 3)

        # Description
        description = QLabel("Description:")
        description_value = QLineEdit() 
        description_value.setText(self.task.description)
        description_value.setEnabled(False)
        clickable(description_value).connect(self.enable)
        task_layout.addWidget(description, 1, 1)
        task_layout.addWidget(description_value, 1, 2, 1, 3)

        # Keywords
        keywords = QLabel("Keywords:")
        keywords_value = QLineEdit()
        keywords_value.setText(','.join(self.task.keywords))
        keywords_value.setEnabled(False)
        clickable(keywords_value).connect(self.enable)
        task_layout.addWidget(keywords, 2, 1)
        task_layout.addWidget(keywords_value, 2, 2, 1, 3)

        # Qualification
        qualification = QLabel("Qualification [%]:")
        qualification_value = QSpinBox()
        qualification_value.setSuffix('%')
        qualification_value.setValue(int(self.task.qualification))
        qualification_value.setEnabled(False)
        clickable(qualification_value).connect(self.enable)
        task_layout.addWidget(qualification, 3, 1)
        task_layout.addWidget(qualification_value, 3, 4)

        # Assignments
        assignments = QLabel("Assignments:")
        assignments_value = QSpinBox()
        assignments_value.setSuffix('')
        assignments_value.setValue(int(self.task.assignments))
        assignments_value.setEnabled(False)
        clickable(assignments_value).connect(self.enable)
        task_layout.addWidget(assignments, 4, 1)
        task_layout.addWidget(assignments_value, 4, 4)

        # Duration
        duration = QLabel("Duration [min]:") 
        duration_value = QSpinBox()
        duration_value.setSuffix('min')
        duration_value.setValue(int(self.task.duration))
        duration_value.setEnabled(False)
        clickable(duration_value).connect(self.enable)
        task_layout.addWidget(duration, 5, 1)
        task_layout.addWidget(duration_value, 5, 4)

        # Reward
        reward = QLabel("Reward [0.01$]:")
        reward_value = QDoubleSpinBox()
        reward_value.setRange(0.01, 0.5)
        reward_value.setSingleStep(0.01)
        reward_value.setSuffix('$')
        reward_value.setValue(self.task.reward)
        reward_value.setEnabled(False)
        clickable(reward_value).connect(self.enable)
        task_layout.addWidget(reward, 6, 1)
        task_layout.addWidget(reward_value, 6, 4)

        # Lifetime
        lifetime = QLabel("Lifetime [d]:")
        lifetime_value = QSpinBox()
        lifetime_value.setSuffix('d')
        lifetime_value.setValue(self.task.lifetime)
        lifetime_value.setEnabled(False)
        clickable(lifetime_value).connect(self.enable)
        task_layout.addWidget(lifetime, 7, 1)
        task_layout.addWidget(lifetime_value, 7, 4)

        # sandbox
        sandbox = QCheckBox("Sandbox")
        sandbox.setChecked(self.task.sandbox)
        task_layout.addWidget(sandbox, 8, 1)
        task_box.setLayout(task_layout)
        task_layout.setColumnMinimumWidth(1, 120)

        # Image Storage Box
        storage_box = QGroupBox()
        storage_box.setTitle(QString("Image Storage"))
        storage_layout = QGridLayout()

        # Host URL
        host_url = QLabel("Host-URL:")
        host_url_value = QLineEdit()
        host_url_value.setText(self.task.host_url)
        host_url_value.setEnabled(False)
        clickable(host_url_value).connect(self.enable)

        # Dropbox Path
        dropbox_path = QLabel("Dropbox-Path:")
        dropbox_path_value = QLineEdit()
        dropbox_path_value.setText(self.task.dropbox_path)
        dropbox_path_value.setEnabled(False)
        clickable(dropbox_path_value).connect(self.enable)

        # Dropbox or S3
        usingS3 = QRadioButton("S3")
        usingS3.setChecked(self.task.usingS3)
        usingS3.setEnabled(False)
        usingDropbox = QRadioButton("Dropbox")
        usingDropbox.setChecked(self.task.usingDropbox)

        storage_layout.addWidget(host_url, 0, 1)
        storage_layout.addWidget(host_url_value, 0, 2, 1, 3)
        storage_layout.addWidget(dropbox_path, 1, 1)
        storage_layout.addWidget(dropbox_path_value, 1, 2, 1, 3)

        # Add Layouts
        save_button = QPushButton("Save Settings")
        setting_tab_layout.addWidget(task_box)
        setting_tab_layout.addWidget(storage_box)
        setting_tab.setLayout(setting_tab_layout)
        save_button.clicked.connect(self.SaveSettings)

        storage_layout.addWidget(usingS3, 2, 1)
        storage_layout.addWidget(usingDropbox, 3, 1)
        storage_layout.addWidget(save_button, 3, 4)

        # storage_layout.addStretch(1)
        storage_box.setLayout(storage_layout)
Exemple #44
0
class FindInFilesDialog(QDialog):

    def __init__(self, result_widget, parent):
        QDialog.__init__(self, parent)
        self._find_thread = FindInFilesThread()
        self.setWindowTitle("Find in files")
        self.resize(400, 300)
        #MAIN LAYOUT
        main_vbox = QVBoxLayout(self)

        self.pattern_line_edit = QLineEdit()
        self.dir_name_root = None
        self.user_home = os.path.expanduser('~')
        self.dir_combo = QComboBox()
        self.dir_combo.addItem(self.user_home)
        self.dir_combo.setEditable(True)
        self.open_button = QPushButton(QIcon(resources.IMAGES['find']),
            self.tr("Open"))
        self.filters_line_edit = QLineEdit("*.py")
        self.replace_line = QLineEdit()
        self.replace_line.setEnabled(False)
        self.check_replace = QCheckBox(self.tr("Replace: "))
        self.case_checkbox = QCheckBox(self.tr("C&ase sensitive"))
        self.type_checkbox = QCheckBox(self.tr("R&egular Expression"))
        self.recursive_checkbox = QCheckBox(self.tr("Rec&ursive"))
        self.recursive_checkbox.setCheckState(Qt.Checked)
        self.phrase_radio = QRadioButton(
            self.tr("Search by Phrase (Exact Match)."))
        self.phrase_radio.setChecked(True)
        self.words_radio = QRadioButton(
            self.tr("Search for all the words "
                    "(anywhere in the document, not together)."))
        self.find_button = QPushButton(self.tr("Find!"))
        self.find_button.setMaximumWidth(150)
        self.cancel_button = QPushButton(self.tr("Cancel"))
        self.cancel_button.setMaximumWidth(150)
        self.result_widget = result_widget

        hbox = QHBoxLayout()
        hbox.addWidget(self.find_button)
        hbox.addWidget(self.cancel_button)

        #main section
        find_group_box = QGroupBox(self.tr("Main"))
        grid = QGridLayout()
        grid.addWidget(QLabel(self.tr("Text: ")), 0, 0)
        grid.addWidget(self.pattern_line_edit, 0, 1)
        grid.addWidget(QLabel(self.tr("Directory: ")), 1, 0)
        grid.addWidget(self.dir_combo, 1, 1)
        grid.addWidget(self.open_button, 1, 2)
        grid.addWidget(QLabel(self.tr("Filter: ")), 2, 0)
        grid.addWidget(self.filters_line_edit, 2, 1)
        grid.addWidget(self.check_replace, 3, 0)
        grid.addWidget(self.replace_line, 3, 1)

        find_group_box.setLayout(grid)
        #add main section to MAIN LAYOUT
        main_vbox.addWidget(find_group_box)

        #options sections
        options_group_box = QGroupBox(self.tr("Options"))
        gridOptions = QGridLayout()
        gridOptions.addWidget(self.case_checkbox, 0, 0)
        gridOptions.addWidget(self.type_checkbox, 1, 0)
        gridOptions.addWidget(self.recursive_checkbox, 2, 0)
        gridOptions.addWidget(self.phrase_radio, 0, 1)
        gridOptions.addWidget(self.words_radio, 1, 1)

        options_group_box.setLayout(gridOptions)
        #add options sections to MAIN LAYOUT
        main_vbox.addWidget(options_group_box)

        #add buttons to MAIN LAYOUT
        main_vbox.addLayout(hbox)

        #Focus
        self.pattern_line_edit.setFocus()
        self.open_button.setFocusPolicy(Qt.NoFocus)

        #signal
        self.connect(self.open_button, SIGNAL("clicked()"), self._select_dir)
        self.connect(self.find_button, SIGNAL("clicked()"),
            self._find_in_files)
        self.connect(self.cancel_button, SIGNAL("clicked()"),
            self._kill_thread)
        self.connect(self._find_thread, SIGNAL("found_pattern(PyQt_PyObject)"),
            self._found_match)
        self.connect(self._find_thread, SIGNAL("finished()"),
            self._find_thread_finished)
        self.connect(self.type_checkbox, SIGNAL("stateChanged(int)"),
            self._change_radio_enabled)
        self.connect(self.check_replace, SIGNAL("stateChanged(int)"),
            self._replace_activated)
        self.connect(self.words_radio, SIGNAL("clicked(bool)"),
            self._words_radio_pressed)

    def _replace_activated(self):
        self.replace_line.setEnabled(self.check_replace.isChecked())
        self.phrase_radio.setChecked(True)

    def _words_radio_pressed(self, value):
        self.replace_line.setEnabled(not value)
        self.check_replace.setChecked(not value)
        self.words_radio.setChecked(True)

    def _change_radio_enabled(self, val):
        enabled = not self.type_checkbox.isChecked()
        self.phrase_radio.setEnabled(enabled)
        self.words_radio.setEnabled(enabled)

    def show(self, actual_project=None, actual=None):
        self.dir_combo.clear()
        self.dir_name_root = actual_project if \
            actual_project else [self.user_home]
        self.dir_combo.addItems(self.dir_name_root)
        if actual:
            index = self.dir_combo.findText(actual)
            self.dir_combo.setCurrentIndex(index)
        super(FindInFilesDialog, self).show()
        self.pattern_line_edit.setFocus()

    def reject(self):
        self._kill_thread()
        # Crazy hack to avoid circular imports
        self.result_widget.parent().parent().parent().hide()
        super(FindInFilesDialog, self).reject()

    def _find_thread_finished(self):
        self.emit(SIGNAL("finished()"))
        self._find_thread.wait()

    def _select_dir(self):
        dir_name = QFileDialog.getExistingDirectory(self,
            self.tr("Open Directory"),
            self.dir_combo.currentText(),
            QFileDialog.ShowDirsOnly)
        index = self.dir_combo.findText(dir_name)
        if index >= 0:
            self.dir_combo.setCurrentIndex(index)
        else:
            self.dir_combo.insertItem(0, dir_name)
            self.dir_combo.setCurrentIndex(0)

    def _found_match(self, result):
        file_name = result[0]
        items = result[1]
        self.result_widget.update_result(
            self.dir_combo.currentText(), file_name, items)

    def _kill_thread(self):
        if self._find_thread.isRunning():
            self._find_thread.cancel()
        self.accept()

    def _find_in_files(self):
        self.emit(SIGNAL("findStarted()"))
        self._kill_thread()
        self.result_widget.clear()
        pattern = self.pattern_line_edit.text()
        dir_name = self.dir_combo.currentText()

        filters = re.split("[,;]", self.filters_line_edit.text())

        # Version of PyQt API 1
        # filters = self.filters_line_edit.text().split(QRegExp("[,;]"),
        #     QString.SkipEmptyParts)

        #remove the spaces in the words Ex. (" *.foo"--> "*.foo")
        filters = [f.strip() for f in filters]
        case_sensitive = self.case_checkbox.isChecked()
        type_ = QRegExp.RegExp if \
            self.type_checkbox.isChecked() else QRegExp.FixedString
        recursive = self.recursive_checkbox.isChecked()
        by_phrase = True
        if self.phrase_radio.isChecked() or self.type_checkbox.isChecked():
            regExp = QRegExp(pattern, case_sensitive, type_)
        elif self.words_radio.isChecked():
            by_phrase = False
            type_ = QRegExp.RegExp
            pattern = '|'.join(
                [word.strip() for word in pattern.split()])
            regExp = QRegExp(pattern, case_sensitive, type_)
        #save a reference to the root directory where we find
        self.dir_name_root = dir_name
        self._find_thread.find_in_files(dir_name, filters, regExp, recursive,
            by_phrase)
Exemple #45
0
class SettingsPage(QWidget):
    """
    """
    ReloadSettings = pyqtSignal()
    TestSettings = pyqtSignal(dict) 
    def __init__(self, parent):
        """
        """
        super(SettingsPage, self).__init__()
        self.__core = parent
        self.config = None

        self.createWidgets()
        self.createConnections()
        
        self.loadCfg()
        
    def core(self):
        """
        """
        return self.__core

    def createConnections(self):
        """
        """
        self.saveButton.clicked.connect( self.__saveCfg )
        self.testButton.clicked.connect( self.testConnection )
        
    def createWidgets(self):
        """
        """
        qcCredGroup = QGroupBox(self.tr("HP ALM server credentials"))
        self.hpCredLogin = QLineEdit()
        self.hpCredPwd = QLineEdit()
        self.hpCredPwd.setEchoMode(QLineEdit.Password)
        qcCredLayout = QGridLayout()
        qcCredLayout.addWidget( QLabel("Login"), 0, 0)
        qcCredLayout.addWidget( self.hpCredLogin, 0, 1)
        qcCredLayout.addWidget( QLabel("Password"), 1, 0)
        qcCredLayout.addWidget( self.hpCredPwd, 1, 1)
        qcCredGroup.setLayout(qcCredLayout)
        
        qcSvrGroup = QGroupBox(self.tr("HP ALM server informations"))
        self.hpSvrURL = QLineEdit()
        self.hpSvrDomain = QLineEdit()
        self.hpSvrProject = QLineEdit()

        self.comAPI = QRadioButton("COM")
        self.comAPI.setChecked(False)
        self.comAPI.setEnabled(False)
        
        self.restAPI = QRadioButton("REST")
        self.restAPI.setChecked(True)
        
        layoutApi = QHBoxLayout()
        layoutApi.addWidget(self.comAPI)
        layoutApi.addWidget(self.restAPI)
        
        qcSvrLayout = QGridLayout()
        qcSvrLayout.addWidget( QLabel("URL"), 0, 0)
        qcSvrLayout.addWidget( self.hpSvrURL, 0, 1)
        qcSvrLayout.addWidget( QLabel("Domain"), 1, 0)
        qcSvrLayout.addWidget( self.hpSvrDomain, 1, 1)
        qcSvrLayout.addWidget( QLabel("Project"), 2, 0)
        qcSvrLayout.addWidget( self.hpSvrProject, 2, 1)
        qcSvrLayout.addWidget( QLabel("API"), 3, 0)
        qcSvrLayout.addLayout( layoutApi, 3, 1)
        
        qcSvrGroup.setLayout(qcSvrLayout)

        # begin export result settings
        qcExportResultGroup = QGroupBox(self.tr("Export results"))
        self.ignoreTcCheckBox = QCheckBox(self.tr("Ignore testcase(s)"))
        self.ignoreUncompleteCheckBox = QCheckBox(self.tr("Ignore uncomplete test(s)"))
        self.addFoldersTlCheckBox = QCheckBox(self.tr("Create missing folders in test lab"))
        self.addTestsetCheckBox = QCheckBox(self.tr("Create testset if missing in test lab"))
        self.addTestinstanceCheckBox = QCheckBox(self.tr("Create test instance in test set"))
        self.cfgsTestsetTable = DesignPage.ConfigsTableView(self, core=self.core())
        qcExportResultLayout = QVBoxLayout()
        qcExportResultLayout.addWidget( self.ignoreTcCheckBox )
        qcExportResultLayout.addWidget( self.ignoreUncompleteCheckBox )
        qcExportResultLayout.addWidget( self.addFoldersTlCheckBox )
        qcExportResultLayout.addWidget( self.addTestsetCheckBox )
        qcExportResultLayout.addWidget( self.addTestinstanceCheckBox )
        qcExportResultLayout.addWidget( QLabel("Custom TestSet Fields"))
        qcExportResultLayout.addWidget( self.cfgsTestsetTable )
        qcExportResultLayout.addStretch(1)
        qcExportResultGroup.setLayout(qcExportResultLayout)
        # end 
        
        # begin export test settings
        qcExportGroup = QGroupBox(self.tr("Export tests"))
        
        self.mergeCheckBox = QCheckBox(self.tr("Merge all tests in one"))
        self.mergeStepsCheckBox = QCheckBox(self.tr("Merge all steps in one"))
        self.showTcNameCheckBox = QCheckBox(self.tr("Load with original test name"))
        self.replaceTcCheckBox = QCheckBox(self.tr("Replace testcase with testname"))
        self.addFoldersTpCheckBox = QCheckBox(self.tr("Create missing folders in test plan"))
        self.overwriteTcCheckBox = QCheckBox(self.tr("Overwrite testcases in test plan"))
        self.cfgsTable = DesignPage.ConfigsTableView(self, core=self.core())

        qcExportLayout = QGridLayout()
        qcExportLayout.addWidget( self.mergeCheckBox, 0, 0)
        qcExportLayout.addWidget( self.mergeStepsCheckBox, 1, 0)
        qcExportLayout.addWidget( self.showTcNameCheckBox, 2, 0)
        qcExportLayout.addWidget( self.replaceTcCheckBox, 3, 0)
        qcExportLayout.addWidget( self.addFoldersTpCheckBox, 4, 0)
        qcExportLayout.addWidget( self.overwriteTcCheckBox, 5, 0)
        qcExportLayout.addWidget( QLabel("Custom Test Fields"), 6, 0)
        qcExportLayout.addWidget( self.cfgsTable, 7, 0)
        qcExportGroup.setLayout(qcExportLayout)
        # end 
        
        layoutCtrls = QHBoxLayout()
        self.saveButton = QPushButton(self.tr("Save Settings"), self)
        self.testButton = QPushButton(self.tr("Test Connection"), self)
        layoutCtrls.addWidget(self.saveButton)
        layoutCtrls.addWidget(self.testButton)
        
        mainLayout = QGridLayout()
        mainLayout.addWidget(qcSvrGroup, 0, 0)
        mainLayout.addWidget(qcCredGroup, 0, 1)
        mainLayout.addWidget(qcExportGroup, 2, 0)
        mainLayout.addWidget(qcExportResultGroup, 2, 1)
        mainLayout.addLayout(layoutCtrls, 3, 1)
        self.setLayout(mainLayout)
        
    def loadCfg(self):
        """
        """
        with open( "%s/config.json" % (QtHelper.dirExec()) ) as f:
            CONFIG_RAW = f.read()
        self.config = json.loads(CONFIG_RAW)

        self.hpCredLogin.setText(self.config["credentials"]["login"])
        self.hpSvrURL.setText(self.config["qc-server"]["url"])
        self.hpSvrDomain.setText(self.config["qc-server"]["domain"])
        self.hpSvrProject.setText(self.config["qc-server"]["project"])

        self.restAPI.setChecked(True) 
        
        if self.config["export-tests"]["merge-all-tests"]: 
            self.mergeCheckBox.setCheckState(Qt.Checked) 
        if self.config["export-tests"]["merge-all-steps"]: 
            self.mergeStepsCheckBox.setCheckState(Qt.Checked) 
        if self.config["export-tests"]["original-test"]: 
            self.showTcNameCheckBox.setCheckState(Qt.Checked) 
        if self.config["export-tests"]["replace-testcase"]: 
            self.replaceTcCheckBox.setCheckState(Qt.Checked) 
        if self.config["export-tests"]["add-folders"]: 
            self.addFoldersTpCheckBox.setCheckState(Qt.Checked) 
        if self.config["export-tests"]["overwrite-tests"]: 
            self.overwriteTcCheckBox.setCheckState(Qt.Checked) 
        self.cfgsTable.loadTable(data=self.config["custom-test-fields"])
        
        if self.config["export-results"]["ignore-testcase"]: 
            self.ignoreTcCheckBox.setCheckState(Qt.Checked) 
        if self.config["export-results"]["ignore-uncomplete"]: 
            self.ignoreUncompleteCheckBox.setCheckState(Qt.Checked) 
        if self.config["export-results"]["add-folders"]: 
            self.addFoldersTlCheckBox.setCheckState(Qt.Checked) 
        if self.config["export-results"]["add-testset"]: 
            self.addTestsetCheckBox.setCheckState(Qt.Checked) 
        if self.config["export-results"]["add-testinstance"]: 
            self.addTestinstanceCheckBox.setCheckState(Qt.Checked) 
        self.cfgsTestsetTable.loadTable(data=self.config["custom-testset-fields"])
        
        # decrypt password
        if len(self.config["credentials"]["password"]):
            decrypted = self.decryptPwd(
                                        key=bytes(self.config["credentials"]["login"], "utf8" ),
                                        ciphertext=bytes(self.config["credentials"]["password"], "utf8" )
                                        )
            self.config["credentials"]["password"] = decrypted
            self.hpCredPwd.setText(decrypted)

    def __saveCfg(self):
        """
        """
        self.saveCfg(successMsg=True)
        
    def saveCfg(self, successMsg=True):
        """
        """
        # if successMsg:
        if not len(self.hpSvrURL.text()):
            QMessageBox.warning(self, self.tr("Save Settings") , self.tr("Please to set the server url") )
            return
        if not len(self.hpSvrDomain.text()):
            QMessageBox.warning(self, self.tr("Save Settings") , self.tr("Please to set the server domain") )
            return
        if not len(self.hpSvrProject.text()):
            QMessageBox.warning(self, self.tr("Save Settings") , self.tr("Please to set the server project") )
            return

        if not len(self.hpCredLogin.text()):
            QMessageBox.warning(self, self.tr("Save Settings") , self.tr("Please to set a login") )
            return
        if not len(self.hpCredPwd.text()):
            QMessageBox.warning(self, self.tr("Save Settings") , self.tr("Please to set a password") )
            return
            
        self.config["credentials"]["login"] = self.hpCredLogin.text()
        # encrypt password
        encryptPwd = self.encryptPwd(
                                    key=self.hpCredLogin.text(),
                                    plaintext=self.hpCredPwd.text()
                                   )
        self.config["credentials"]["password"] = str(encryptPwd, "utf8")
        
        self.config["qc-server"]["url"] = self.hpSvrURL.text()
        self.config["qc-server"]["domain"] = self.hpSvrDomain.text()
        self.config["qc-server"]["project"] = self.hpSvrProject.text()
        self.config["qc-server"]["use-rest"] = False
        if self.restAPI.isChecked(): self.config["qc-server"]["use-rest"] = True
        
        self.config["export-tests"]["merge-all-tests"] = False
        self.config["export-tests"]["merge-all-steps"] = False
        self.config["export-tests"]["original-test"] = False
        self.config["export-tests"]["replace-testcase"] = False
        self.config["export-tests"]["add-folders"] = False
        self.config["export-tests"]["overwrite-tests"] = False
        if self.mergeCheckBox.isChecked(): self.config["export-tests"]["merge-all-tests"] = True
        if self.mergeStepsCheckBox.isChecked(): self.config["export-tests"]["merge-all-steps"] = True
        if self.showTcNameCheckBox.isChecked(): self.config["export-tests"]["original-test"] = True
        if self.replaceTcCheckBox.isChecked(): self.config["export-tests"]["replace-testcase"] = True
        if self.addFoldersTpCheckBox.isChecked(): self.config["export-tests"]["add-folders"] = True
        if self.overwriteTcCheckBox.isChecked(): self.config["export-tests"]["overwrite-tests"] = True
        self.config["custom-test-fields"] = self.cfgsTable.model.getData()
        
        self.config["export-results"]["add-folders"] = False
        self.config["export-results"]["ignore-testcase"] = False
        self.config["export-results"]["ignore-uncomplete"] = False
        self.config["export-results"]["add-testset"] = False
        self.config["export-results"]["add-testinstance"] = False
        if self.ignoreTcCheckBox.isChecked(): self.config["export-results"]["ignore-testcase"] = True
        if self.ignoreUncompleteCheckBox.isChecked(): self.config["export-results"]["ignore-uncomplete"] = True
        if self.addFoldersTlCheckBox.isChecked(): self.config["export-results"]["add-folders"] = True
        if self.addTestsetCheckBox.isChecked(): self.config["export-results"]["add-testset"] = True
        if self.addTestinstanceCheckBox.isChecked(): self.config["export-results"]["add-testinstance"] = True
        self.config["custom-testset-fields"] = self.cfgsTestsetTable.model.getData()
        
        with open( "%s/config.json" % (QtHelper.dirExec()), "w" ) as f:
            f.write( json.dumps(self.config) )
            
        if len(self.config["credentials"]["password"]):
            self.config["credentials"]["password"] = self.decryptPwd(
                                            key=bytes(self.config["credentials"]["login"], "utf8" ),
                                            ciphertext=bytes(self.config["credentials"]["password"], "utf8" )
                                  )
                
        self.ReloadSettings.emit()
        
        if successMsg: QMessageBox.information(self, self.tr("Save Settings") ,  self.tr("Settings saved.") )
                                
    def cfg(self):
        """
        """
        return self.config
        
    def encryptPwd(self, key, plaintext):
        """
        """
        return base64.b64encode( bytes( plaintext, "utf8" ) )

    def decryptPwd(self, key, ciphertext):
        """
        """
        return str( base64.b64decode(ciphertext) , "utf8")
    
    def testConnection(self):
        """
        """
        self.TestSettings.emit(self.config)
Exemple #46
0
class NewDocument(preferences.Group):
    def __init__(self, page):
        super(NewDocument, self).__init__(page)
        
        grid = QGridLayout()
        self.setLayout(grid)
        
        def changed():
            self.changed.emit()
            self.combo.setEnabled(self.template.isChecked())
        
        self.emptyDocument = QRadioButton(toggled=changed)
        self.lilyVersion = QRadioButton(toggled=changed)
        self.template = QRadioButton(toggled=changed)
        self.combo = QComboBox(currentIndexChanged=changed)
        
        grid.addWidget(self.emptyDocument, 0, 0, 1, 2)
        grid.addWidget(self.lilyVersion, 1, 0, 1, 2)
        grid.addWidget(self.template, 2, 0, 1, 1)
        grid.addWidget(self.combo, 2, 1, 1, 1)
        self.loadCombo()
        app.translateUI(self)
        
    def translateUI(self):
        self.setTitle(_("When creating new documents"))
        self.emptyDocument.setText(_("Create an empty document"))
        self.lilyVersion.setText(_("Create a document that contains the LilyPond version statement"))
        self.template.setText(_("Create a document from a template:"))
        from snippet import snippets
        for i, name in enumerate(self._names):
            self.combo.setItemText(i, snippets.title(name))
    
    def loadCombo(self):
        from snippet import snippets
        self._names = [name for name in snippets.names()
                        if snippets.get(name).variables.get('template')]
        self.combo.clear()
        self.combo.addItems([''] * len(self._names))
        
    def loadSettings(self):
        s = QSettings()
        ndoc = s.value("new_document", "empty", type(""))
        template = s.value("new_document_template", "", type(""))
        if template in self._names:
            self.combo.setCurrentIndex(self._names.index(template))
        if ndoc == "template":
            self.template.setChecked(True)
        elif ndoc == "version":
            self.lilyVersion.setChecked(True)
        else:
            self.emptyDocument.setChecked(True)

    def saveSettings(self):
        s = QSettings()
        if self._names and self.template.isChecked():
            s.setValue("new_document", "template")
            s.setValue("new_document_template", self._names[self.combo.currentIndex()])
        elif self.lilyVersion.isChecked():
            s.setValue("new_document", "version")
        else:
            s.setValue("new_document", "empty")
Exemple #47
0
class DUdpReplay(QtHelper.EnhancedQDialog, Logger.ClassLogger):
    """
    Http replay dialog
    """
    def __init__(self, parent=None, offlineMode=False):
        """
        Constructor

        @param parent: 
        @type parent:
        """
        super(DUdpReplay, self).__init__(parent)
        self.offlineMode = offlineMode
        self.defaultIp = "127.0.0.1"
        self.defaultPort = "80"
        self.newTest = ''
        self.newTestExec = ''
        self.newInputs = []
        self.requests = []
        self.responses = []
        self.defaultTemplates = DefaultTemplates.Templates()
        self.testType = None

        self.createDialog()
        self.createConnections()
        self.createActions()
        self.createToolbar()

    def createActions(self):
        """
        Create qt actions
        """
        self.openAction = QtHelper.createAction(self,
                                                "&Open",
                                                self.importTrace,
                                                icon=QIcon(":/folder_add.png"),
                                                tip='Open network trace.')
        self.exportTUAction = QtHelper.createAction(
            self,
            "&Test Unit",
            self.exportToTU,
            icon=QIcon(":/%s.png" % WWorkspace.TestUnit.TYPE),
            tip='Export to Test Unit')
        self.exportTSAction = QtHelper.createAction(
            self,
            "&Test Suite",
            self.exportToTS,
            icon=QIcon(":/%s.png" % WWorkspace.TestSuite.TYPE),
            tip='Export to Test Suite')
        self.cancelAction = QtHelper.createAction(self,
                                                  "&Cancel",
                                                  self.reject,
                                                  tip='Cancel')

        menu = QMenu(self)
        menu.addAction(self.exportTUAction)
        menu.addAction(self.exportTSAction)

        self.exportToAction = QtHelper.createAction(
            self,
            "&Export to",
            self.exportToTU,
            icon=QIcon(":/%s.png" % WWorkspace.TestUnit.TYPE),
            tip='Export to tests')
        self.exportToAction.setMenu(menu)
        self.exportToAction.setEnabled(False)

    def createDialog(self):
        """
        Create dialog
        """

        self.dockToolbar = QToolBar(self)
        self.dockToolbar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)

        self.setWindowTitle(WINDOW_TITLE)
        self.resize(500, 400)

        self.ipEdit = QLineEdit(self.defaultIp)
        ipRegExpVal = QRegExpValidator(self)
        ipRegExp = QRegExp("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")
        ipRegExpVal.setRegExp(ipRegExp)
        self.ipEdit.setValidator(ipRegExpVal)

        self.portEdit = QLineEdit(self.defaultPort)
        self.portEdit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        validatorPort = QIntValidator(self)
        self.portEdit.setValidator(validatorPort)

        self.progressBar = QProgressBar(self)
        self.progressBar.setMaximum(100)
        self.progressBar.setProperty("value", 0)
        self.progressBar.setAlignment(Qt.AlignCenter)
        self.progressBar.setObjectName("progressBar")

        self.guiSikuliGroupBox = QGroupBox("")
        self.guiSikuliGroupBox.setFlat(True)
        self.automaticAdp = QRadioButton("Automatic")
        self.automaticAdp.setChecked(True)
        self.defaultAdp = QRadioButton("Default")
        self.genericAdp = QRadioButton("Generic")
        vbox = QHBoxLayout()
        vbox.addWidget(self.automaticAdp)
        vbox.addWidget(self.defaultAdp)
        vbox.addWidget(self.genericAdp)
        vbox.addStretch(1)
        self.guiSikuliGroupBox.setLayout(vbox)

        layout = QVBoxLayout()
        layout.addWidget(self.dockToolbar)
        layout.addSpacing(12)
        paramLayout = QGridLayout()
        paramLayout.addWidget(QLabel("Destination IP:"), 0, 0, Qt.AlignRight)
        paramLayout.addWidget(self.ipEdit, 0, 1)
        paramLayout.addWidget(QLabel("Destination Port:"), 1, 0, Qt.AlignRight)
        paramLayout.addWidget(self.portEdit, 1, 1)
        paramLayout.addWidget(QLabel(self.tr("Gui adapter selector:")), 2, 0,
                              Qt.AlignRight)
        paramLayout.addWidget(self.guiSikuliGroupBox, 2, 1)
        layout.addLayout(paramLayout)

        self.logsEdit = QTextEdit()
        self.logsEdit.setReadOnly(True)
        self.logsEdit.setTextInteractionFlags(Qt.NoTextInteraction)

        layout.addSpacing(12)
        layout.addWidget(self.logsEdit)
        layout.addSpacing(12)
        layout.addWidget(self.progressBar)

        self.setLayout(layout)

    def createToolbar(self):
        """
        Create toolbar
        """
        self.dockToolbar.setObjectName("File toolbar")
        self.dockToolbar.addAction(self.openAction)
        self.dockToolbar.addSeparator()
        self.dockToolbar.addAction(self.exportToAction)
        self.dockToolbar.addSeparator()
        self.dockToolbar.setIconSize(QSize(16, 16))

    def createConnections(self):
        """
        Create qt connections
        """
        pass

    def autoScrollOnTextEdit(self):
        """
        Automatic scroll on text edit
        """
        cursor = self.logsEdit.textCursor()
        cursor.movePosition(QTextCursor.End)
        self.logsEdit.setTextCursor(cursor)

    def strip_html(self, txt):
        """
        Strip html
        """
        if "<" in txt:
            txt = txt.replace('<', '&lt;')
        if ">" in txt:
            txt = txt.replace('>', '&gt;')
        return txt

    def addLogSuccess(self, txt):
        """
        Add log success in the text edit
        """
        self.logsEdit.insertHtml(
            "<span style='color:darkgreen'>%s</span><br />" %
            unicode(self.strip_html(txt)))
        self.autoScrollOnTextEdit()

    def addLogWarning(self, txt):
        """
        Add log warning in the text edit
        """
        self.logsEdit.insertHtml(
            "<span style='color:darkorange'>%s</span><br />" %
            unicode(self.strip_html(txt)))
        self.autoScrollOnTextEdit()

    def addLogError(self, txt):
        """
        Add log error in the text edit
        """
        self.logsEdit.insertHtml("<span style='color:red'>%s</span><br />" %
                                 unicode(self.strip_html(txt)))
        self.autoScrollOnTextEdit()

    def addLog(self, txt):
        """
        Append log to the logsEdit widget
        """
        self.logsEdit.insertHtml("%s<br />" % unicode(self.strip_html(txt)))
        self.autoScrollOnTextEdit()

    def importTrace(self):
        """
        Import network trace
        """
        self.logsEdit.clear()
        self.testType = None

        if not self.offlineMode:
            if not RCI.instance().isAuthenticated():
                self.addLogWarning(
                    txt="<< Connect to the test center in first!")
                QMessageBox.warning(self, "Import",
                                    "Connect to the test center in first!")
                return

        self.exportToAction.setEnabled(False)
        self.newTest = ''
        self.progressBar.setMaximum(100)
        self.progressBar.setValue(0)

        if sys.version_info > (3, ):
            fileName = QFileDialog.getOpenFileName(
                self, self.tr("Open File"), "",
                "Network dump (*.cap;*.pcap;*.pcapng)")
        else:
            fileName = QFileDialog.getOpenFileName(self, self.tr("Open File"),
                                                   "", "Network dump (*.cap)")
        # new in v18 to support qt5
        if QtHelper.IS_QT5:
            _fileName, _type = fileName
        else:
            _fileName = fileName
        # end of new

        if not _fileName:
            return

        if sys.version_info < (3, ):
            extension = str(_fileName).rsplit(".", 1)[1]
            if not (extension == "cap"):
                self.addLogError(txt="<< File not supported %s" % _fileName)
                QMessageBox.critical(self, "Open", "File not supported")
                return

        _fileName = str(_fileName)
        capName = _fileName.rsplit("/", 1)[1]

        self.addLogSuccess(txt=">> Reading the file %s" % _fileName)
        self.readFileV2(fileName=_fileName)

    def exportToTS(self):
        """
        Export to test suite
        """
        self.testType = TS
        self.exportToTest(TS=True, TU=False)

    def exportToTU(self):
        """
        Export to test unit
        """
        self.testType = TU
        self.exportToTest(TS=False, TU=True)

    def searchUDP(self):
        """
        Search UDP module in assistant
        """
        # modules accessor
        ret = "SutAdapters"
        if self.automaticAdp.isChecked():
            isGeneric = WWorkspace.Helper.instance().isGuiGeneric(name="GUI")
            if isGeneric:
                ret = "SutAdapters.Generic"
        elif self.defaultAdp.isChecked():
            return ret
        elif self.genericAdp.isChecked():
            ret = "SutAdapters.Generic"
        else:
            pass
        return ret

    def exportToTest(self, TS=True, TU=False):
        """
        Export to test
        """
        if not RCI.instance().isAuthenticated():
            self.addLogWarning(txt="<< Connect to the test center in first!")
            QMessageBox.warning(self, "Import",
                                "Connect to the test center in first!")
            return

        if TS:
            self.newTest = self.defaultTemplates.getTestDefinitionAuto()
            self.newTestExec = self.defaultTemplates.getTestExecutionAuto()
        if TU:
            self.newTest = self.defaultTemplates.getTestUnitDefinitionAuto()

        destIp = str(self.ipEdit.text())
        destPort = str(self.portEdit.text())

        self.newInputs = []
        self.newInputs.append({
            'type': 'self-ip',
            'name': 'BIND_IP',
            'description': '',
            'value': '0.0.0.0',
            'color': ''
        })
        self.newInputs.append({
            'type': 'int',
            'name': 'BIND_PORT',
            'description': '',
            'value': '0',
            'color': ''
        })
        self.newInputs.append({
            'type': 'str',
            'name': 'DEST_IP',
            'description': '',
            'value': '%s' % destIp,
            'color': ''
        })
        self.newInputs.append({
            'type': 'int',
            'name': 'DEST_PORT',
            'description': '',
            'value': '%s' % destPort,
            'color': ''
        })
        self.newInputs.append({
            'type': 'bool',
            'name': 'DEBUG',
            'description': '',
            'value': 'False',
            'color': ''
        })
        self.newInputs.append({
            'type': 'float',
            'name': 'TIMEOUT',
            'description': '',
            'value': '5.0',
            'color': ''
        })

        adps = """self.ADP_UDP = %s.UDP.Client(parent=self, bindIp=input('BIND_IP'), bindPort=input('BIND_PORT'), destinationIp=input('DEST_IP'), destinationPort=input('DEST_PORT'), debug=input('DEBUG'), separatorDisabled=True)""" % self.searchUDP(
        )

        # prepare steps
        steps = []
        j = 0
        for i in xrange(len(self.requests)):
            j = i + 1
            sentrecv, req = self.requests[i]
            if sentrecv == 'sent':
                steps.append(
                    'self.step%s = self.addStep(expected="udp data sent", description="send udp data", summary="send udp data")'
                    % j)
            else:
                steps.append(
                    'self.step%s = self.addStep(expected="udp data received", description="received udp data", summary="received udp data")'
                    % j)

        tests = []
        for i in xrange(len(self.requests)):
            j = i + 1
            sentrecv, req = self.requests[i]
            (source, dest, source_port, dest_port, data) = req

            if sentrecv == 'sent':
                tests.append("# data to sent %s" % j)
                tests.append('self.step%s.start()' % j)
                if sys.version_info > (3, ):
                    tests.append('rawSent = %s' % data.replace(b"'", b"\\'"))
                else:
                    tests.append('rawSent = """%s"""' % data)
                tests.append('SentMsg = self.ADP_UDP.sendData(data=rawSent)')
                tests.append('if not SentMsg:')
                tests.append(
                    '\tself.step%s.setFailed(actual="unable to send data")' %
                    j)
                tests.append('else:')
                tests.append(
                    '\tself.step%s.setPassed(actual="udp data sent succesfully")'
                    % j)
                tests.append('')

            if sentrecv == 'recv':
                tests.append("# data to received %s" % j)
                tests.append('self.step%s.start()' % j)
                if sys.version_info > (3, ):
                    tests.append('rawRecv = %s' % data.replace(b'"', b'\\"'))
                else:
                    tests.append('rawRecv = """%s"""' % data)
                tests.append(
                    'RecvMsg = self.ADP_UDP.hasReceivedData(data=rawRecv, timeout=input("TIMEOUT"))'
                )
                tests.append('if RecvMsg is None:')
                tests.append(
                    '\tself.step%s.setFailed(actual="unable to received data")'
                    % j)
                tests.append('else:')
                tests.append(
                    '\tself.step%s.setPassed(actual="udp data received succesfully")'
                    % j)
                tests.append('')
        if TS:
            init = """self.ADP_UDP.startListening()
		udpListening = self.ADP_UDP.isListening( timeout=input('TIMEOUT') )
		if not udpListening:
			self.abort( 'unable to listing to the udp port %s'  )
""" % str(self.portEdit.text())

        if TU:
            init = """self.ADP_UDP.startListening()
	udpListening = self.ADP_UDP.isListening( timeout=input('TIMEOUT') )
	if not udpListening:
		self.abort( 'unable to connect to the udp port %s'  )
""" % str(self.portEdit.text())

        if TS:
            cleanup = """self.ADP_UDP.stopListening()
		udpStopped = self.ADP_UDP.isStopped( timeout=input('TIMEOUT') )
		if not udpStopped:
			self.error( 'unable to no more listen from the udp port %s' )
""" % str(self.portEdit.text())

        if TU:
            cleanup = """self.ADP_UDP.stopListening()
	udpStopped = self.ADP_UDP.isStopped( timeout=input('TIMEOUT') )
	if not udpStopped:
		self.error( 'unable to no more listen  from the udp port %s' )
""" % str(self.portEdit.text())

        self.newTest = self.newTest.replace(
            "<<PURPOSE>>", 'self.setPurpose(purpose="Replay UDP")')
        self.newTest = self.newTest.replace("<<ADPS>>", adps)
        if TS:
            self.newTest = self.newTest.replace("<<STEPS>>",
                                                '\n\t\t'.join(steps))
        if TU:
            self.newTest = self.newTest.replace("<<STEPS>>",
                                                '\n\t'.join(steps))
        self.newTest = self.newTest.replace("<<INIT>>", init)
        self.newTest = self.newTest.replace("<<CLEANUP>>", cleanup)
        if TS:
            self.newTest = self.newTest.replace("<<TESTS>>",
                                                '\n\t\t'.join(tests))
        if TU:
            self.newTest = self.newTest.replace("<<TESTS>>",
                                                '\n\t'.join(tests))

        self.accept()

    def readFileV2(self, fileName):
        """
        Read pcap file 
        Support pcap-ng too
        """
        fd = open(fileName, 'rb')
        fileFormat, fileHead = PcapParse.extractFormat(fd)
        if fileFormat == PcapParse.FileFormat.PCAP:
            self.trace("pcap file detected")
            pcapFile = PcapReader.PcapFile(fd, fileHead).read_packet
            self.readFilePacket(pcapFile=pcapFile)
        elif fileFormat == PcapParse.FileFormat.PCAP_NG:
            self.trace("pcap-png file detected")
            pcapFile = PcapngReader.PcapngFile(fd, fileHead).read_packet
            self.readFilePacket(pcapFile=pcapFile)
        else:
            self.addLogError(txt="<< Error to open the network trace")
            self.error('unable to open the network trace: file format = %s' %
                       fileFormat)
            QMessageBox.critical(self, "Import", "File not supported")

    def readFilePacket(self, pcapFile):
        """
        Read file packet by packet
        """
        ip_expected = str(self.ipEdit.text())
        port_expected = int(self.portEdit.text())

        # read packet)
        packets = pcapFile()
        ethernetPackets = list(packets)
        self.addLogSuccess(txt="<< Total packets detected: %s " %
                           len(ethernetPackets))

        # extract udp packet according to the expected ip and port
        self.requests = []
        i = 1
        self.progressBar.setMaximum(len(ethernetPackets))
        self.progressBar.setValue(0)
        for pkt in ethernetPackets:
            self.progressBar.setValue(i)
            i += 1
            pktDecoded = PcapParse.decodePacket(pkt, getTcp=False, getUdp=True)
            if pktDecoded is not None:
                (source, dest, source_port, dest_port, data) = pktDecoded
                # skip when no data exists
                if dest == ip_expected and int(dest_port) == int(
                        port_expected) and len(data) > 0:
                    self.requests.append(('sent', pktDecoded))
                if source == ip_expected and int(source_port) == int(
                        port_expected) and len(data) > 0:
                    self.requests.append(('recv', pktDecoded))
        self.addLogSuccess(txt="<< Number of UDP packets detected: %s" %
                           len(self.requests))

        if self.requests:
            self.addLogSuccess("<< File decoded with success!")
            self.addLogWarning(
                "<< Click on the export button to generate the test!")
            self.exportToAction.setEnabled(True)
        else:
            self.addLogWarning("<< No udp extracted!")
Exemple #48
0
class LegendPropertiesWindow(PyDialog):
    """
    +-------------------+
    | Legend Properties |
    +-----------------------+
    | Title  ______ Default |
    | Min    ______ Default |
    | Max    ______ Default |
    | Format ______ Default |
    | Scale  ______ Default |
    | Number of Colors ____ |
    | Number of Labels ____ |
    | Label Size       ____ | (TODO)
    | ColorMap         ____ | (TODO)
    |                       |
    | x Min/Max (Blue->Red) |
    | o Max/Min (Red->Blue) |
    |                       |
    | x Vertical/Horizontal |
    | x Show/Hide           |
    |                       |
    |    Apply OK Cancel    |
    +-----------------------+
    """

    def __init__(self, data, win_parent=None):
        PyDialog.__init__(self, data, win_parent)

        #Init the base class
        self._updated_legend = False
        self._icase = data['icase']
        self._default_icase = self._icase

        self._default_name = data['name']
        self._default_min = data['min']
        self._default_max = data['max']

        self._default_scale = data['default_scale']
        self._scale = data['scale']

        self._default_format = data['default_format']
        self._format = data['format']

        self._default_labelsize = data['default_labelsize']
        self._labelsize = data['labelsize']

        self._default_nlabels = data['default_nlabels']
        self._nlabels = data['nlabels']

        self._default_ncolors = data['default_ncolors']
        self._ncolors = data['ncolors']

        self._default_colormap = data['default_colormap']
        self._colormap = data['colormap']

        self._default_is_low_to_high = data['is_low_to_high']

        self._default_is_discrete = data['is_discrete']
        self._default_is_horizontal = data['is_horizontal']
        self._default_is_shown = data['is_shown']

        self._update_defaults_to_blank()

        #self.setupUi(self)
        self.setWindowTitle('Legend Properties')
        self.create_widgets()
        self.create_layout()
        self.set_connections()
        #self.show()

    def _update_defaults_to_blank(self):
        """Changes the default (None) to a blank string"""
        if self._default_colormap is None:
            self._default_colormap = 'jet'
        if self._default_labelsize is None:
            self._default_labelsize = ''
        if self._default_ncolors is None:
            self._default_ncolors = ''
        if self._default_nlabels is None:
            self._default_nlabels = ''

        if self._colormap is None:
            self._colormap = 'jet'
        if self._labelsize is None:
            self._labelsize = ''
        if self._ncolors is None:
            self._ncolors = ''
        if self._nlabels is None:
            self._nlabels = ''

    def update_legend(self, icase, name,
                      min_value, max_value, data_format, scale,
                      nlabels, labelsize,
                      ncolors, colormap,

                      default_title, default_min_value, default_max_value,
                      default_data_format, default_scale,
                      default_nlabels, default_labelsize,
                      default_ncolors, default_colormap,
                      is_low_to_high, is_horizontal_scalar_bar):
        """
        We need to update the legend if there's been a result change request
        """
        if icase != self._default_icase:
            self._default_icase = icase
            self._default_name = default_title
            self._default_min = default_min_value
            self._default_max = default_max_value
            self._default_format = default_data_format
            self._default_is_low_to_high = is_low_to_high
            self._default_is_discrete = True
            self._default_is_horizontal = is_horizontal_scalar_bar
            self._default_scale = default_scale
            self._default_nlabels = default_nlabels
            self._default_labelsize = default_labelsize
            self._default_ncolors = default_ncolors
            self._default_colormap = default_colormap


            if colormap is None:
                colormap = 'jet'
            if labelsize is None:
                labelsize = ''
            if ncolors is None:
                ncolors = ''
            if nlabels is None:
                nlabels = ''

            self._update_defaults_to_blank()

            assert isinstance(scale, float), 'scale=%r' % scale
            assert isinstance(default_scale, float), 'default_scale=%r' % default_scale
            if self._default_scale == 0.0:
                self.scale_edit.setEnabled(False)
                self.scale_button.setEnabled(False)
            else:
                self.scale_edit.setEnabled(True)
                self.scale_button.setEnabled(True)

            #self.on_default_name()
            #self.on_default_min()
            #self.on_default_max()
            #self.on_default_format()
            #self.on_default_scale()
            # reset defaults
            self.name_edit.setText(name)
            self.name_edit.setStyleSheet("QLineEdit{background: white;}")

            self.min_edit.setText(str(min_value))
            self.min_edit.setStyleSheet("QLineEdit{background: white;}")

            self.max_edit.setText(str(max_value))
            self.max_edit.setStyleSheet("QLineEdit{background: white;}")

            self.format_edit.setText(str(data_format))
            self.format_edit.setStyleSheet("QLineEdit{background: white;}")

            self.scale_edit.setText(str(scale))
            self.scale_edit.setStyleSheet("QLineEdit{background: white;}")

            self.nlabels_edit.setText(str(nlabels))
            self.nlabels_edit.setStyleSheet("QLineEdit{background: white;}")

            self.labelsize_edit.setText(str(labelsize))
            self.labelsize_edit.setStyleSheet("QLineEdit{background: white;}")

            self.ncolors_edit.setText(str(ncolors))
            self.ncolors_edit.setStyleSheet("QLineEdit{background: white;}")

            self.colormap_edit.setCurrentIndex(colormap_keys.index(str(colormap)))
            self.on_apply()

    def create_widgets(self):
        # Name
        self.name = QLabel("Title:")
        self.name_edit = QLineEdit(str(self._default_name))
        self.name_button = QPushButton("Default")

        # Min
        self.min = QLabel("Min:")
        self.min_edit = QLineEdit(str(self._default_min))
        self.min_button = QPushButton("Default")

        # Max
        self.max = QLabel("Max:")
        self.max_edit = QLineEdit(str(self._default_max))
        self.max_button = QPushButton("Default")

        # Format
        self.format = QLabel("Format (e.g. %.3f, %g, %.6e):")
        self.format_edit = QLineEdit(str(self._format))
        self.format_button = QPushButton("Default")

        # Scale
        self.scale = QLabel("Scale:")
        self.scale_edit = QLineEdit(str(self._scale))
        self.scale_button = QPushButton("Default")
        if self._default_scale == 0.0:
            self.scale_edit.setEnabled(False)
            self.scale_button.setEnabled(False)
        #tip = QtGui.QToolTip()
        #tip.setTe
        #self.format_edit.toolTip(tip)

        #---------------------------------------
        # nlabels
        self.nlabels = QLabel("Number of Labels:")
        self.nlabels_edit = QLineEdit(str(self._nlabels))
        self.nlabels_button = QPushButton("Default")

        self.labelsize = QLabel("Label Size:")
        self.labelsize_edit = QLineEdit(str(self._labelsize))
        self.labelsize_button = QPushButton("Default")

        self.ncolors = QLabel("Number of Colors:")
        self.ncolors_edit = QLineEdit(str(self._ncolors))
        self.ncolors_button = QPushButton("Default")

        self.colormap = QLabel("Color Map:")
        self.colormap_edit = QComboBox(self)
        self.colormap_button = QPushButton("Default")
        for key in colormap_keys:
            self.colormap_edit.addItem(key)
        self.colormap_edit.setCurrentIndex(colormap_keys.index(self._colormap))


        # red/blue or blue/red
        self.low_to_high_radio = QRadioButton('Low -> High')
        self.high_to_low_radio = QRadioButton('High -> Low')
        widget = QWidget(self)
        low_to_high_group = QButtonGroup(widget)
        low_to_high_group.addButton(self.low_to_high_radio)
        low_to_high_group.addButton(self.high_to_low_radio)
        self.low_to_high_radio.setChecked(self._default_is_low_to_high)
        self.high_to_low_radio.setChecked(not self._default_is_low_to_high)

        # horizontal / vertical
        self.horizontal_radio = QRadioButton("Horizontal")
        self.vertical_radio = QRadioButton("Vertical")
        widget = QWidget(self)
        horizontal_vertical_group = QButtonGroup(widget)
        horizontal_vertical_group.addButton(self.horizontal_radio)
        horizontal_vertical_group.addButton(self.vertical_radio)
        self.horizontal_radio.setChecked(self._default_is_horizontal)
        self.vertical_radio.setChecked(not self._default_is_horizontal)

        # on / off
        self.show_radio = QRadioButton("Show")
        self.hide_radio = QRadioButton("Hide")
        widget = QWidget(self)
        show_hide_group = QButtonGroup(widget)
        show_hide_group.addButton(self.show_radio)
        show_hide_group.addButton(self.hide_radio)
        self.show_radio.setChecked(self._default_is_shown)
        self.hide_radio.setChecked(not self._default_is_shown)

        # closing
        self.apply_button = QPushButton("Apply")
        self.ok_button = QPushButton("OK")
        self.cancel_button = QPushButton("Cancel")

    def create_layout(self):
        grid = QGridLayout()
        grid.addWidget(self.name, 0, 0)
        grid.addWidget(self.name_edit, 0, 1)
        grid.addWidget(self.name_button, 0, 2)

        grid.addWidget(self.min, 1, 0)
        grid.addWidget(self.min_edit, 1, 1)
        grid.addWidget(self.min_button, 1, 2)

        grid.addWidget(self.max, 2, 0)
        grid.addWidget(self.max_edit, 2, 1)
        grid.addWidget(self.max_button, 2, 2)

        grid.addWidget(self.format, 3, 0)
        grid.addWidget(self.format_edit, 3, 1)
        grid.addWidget(self.format_button, 3, 2)

        grid.addWidget(self.scale, 4, 0)
        grid.addWidget(self.scale_edit, 4, 1)
        grid.addWidget(self.scale_button, 4, 2)

        grid.addWidget(self.nlabels, 5, 0)
        grid.addWidget(self.nlabels_edit, 5, 1)
        grid.addWidget(self.nlabels_button, 5, 2)

        #grid.addWidget(self.labelsize, 6, 0)
        #grid.addWidget(self.labelsize_edit, 6, 1)
        #grid.addWidget(self.labelsize_button, 6, 2)

        grid.addWidget(self.ncolors, 6, 0)
        grid.addWidget(self.ncolors_edit, 6, 1)
        grid.addWidget(self.ncolors_button, 6, 2)

        grid.addWidget(self.colormap, 7, 0)
        grid.addWidget(self.colormap_edit, 7, 1)
        grid.addWidget(self.colormap_button, 7, 2)

        ok_cancel_box = QHBoxLayout()
        ok_cancel_box.addWidget(self.apply_button)
        ok_cancel_box.addWidget(self.ok_button)
        ok_cancel_box.addWidget(self.cancel_button)


        grid2 = QGridLayout()
        title = QLabel("Color Scale:")
        grid2.addWidget(title, 0, 0)
        grid2.addWidget(self.low_to_high_radio, 1, 0)
        grid2.addWidget(self.high_to_low_radio, 2, 0)

        grid2.addWidget(self.vertical_radio, 1, 1)
        grid2.addWidget(self.horizontal_radio, 2, 1)

        grid2.addWidget(self.show_radio, 1, 2)
        grid2.addWidget(self.hide_radio, 2, 2)

        #grid2.setSpacing(0)

        vbox = QVBoxLayout()
        vbox.addLayout(grid)
        #vbox.addLayout(checkboxes)
        vbox.addLayout(grid2)
        vbox.addStretch()
        vbox.addLayout(ok_cancel_box)

        #Create central widget, add layout and set
        #central_widget = QtGui.QWidget()
        #central_widget.setLayout(vbox)
        #self.setCentralWidget(central_widget)
        self.setLayout(vbox)

    def set_connections(self):
        if qt_version == 4:
            self.connect(self.name_button, QtCore.SIGNAL('clicked()'), self.on_default_name)
            self.connect(self.min_button, QtCore.SIGNAL('clicked()'), self.on_default_min)
            self.connect(self.max_button, QtCore.SIGNAL('clicked()'), self.on_default_max)
            self.connect(self.format_button, QtCore.SIGNAL('clicked()'), self.on_default_format)
            self.connect(self.scale_button, QtCore.SIGNAL('clicked()'), self.on_default_scale)

            self.connect(self.nlabels_button, QtCore.SIGNAL('clicked()'), self.on_default_nlabels)
            self.connect(self.labelsize_button, QtCore.SIGNAL('clicked()'), self.on_default_labelsize)
            self.connect(self.ncolors_button, QtCore.SIGNAL('clicked()'), self.on_default_ncolors)
            self.connect(self.colormap_button, QtCore.SIGNAL('clicked()'), self.on_default_colormap)

            self.connect(self.apply_button, QtCore.SIGNAL('clicked()'), self.on_apply)
            self.connect(self.ok_button, QtCore.SIGNAL('clicked()'), self.on_ok)
            self.connect(self.cancel_button, QtCore.SIGNAL('clicked()'), self.on_cancel)
            self.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent)
            #self.colormap_edit.activated[str].connect(self.onActivated)
        else:
            self.name_button.clicked.connect(self.on_default_name)
            self.min_button.clicked.connect(self.on_default_min)
            self.max_button.clicked.connect(self.on_default_max)
            self.format_button.clicked.connect(self.on_default_format)
            self.scale_button.clicked.connect(self.on_default_scale)

            self.nlabels_button.clicked.connect(self.on_default_nlabels)
            self.labelsize_button.clicked.connect(self.on_default_labelsize)
            self.ncolors_button.clicked.connect(self.on_default_ncolors)
            self.colormap_button.clicked.connect(self.on_default_colormap)

            self.apply_button.clicked.connect(self.on_apply)
            self.ok_button.clicked.connect(self.on_ok)
            self.cancel_button.clicked.connect(self.on_cancel)
            # closeEvent???


    def on_default_name(self):
        name = str(self._default_name)
        self.name_edit.setText(name)
        self.name_edit.setStyleSheet("QLineEdit{background: white;}")

    def on_default_min(self):
        self.min_edit.setText(str(self._default_min))
        self.min_edit.setStyleSheet("QLineEdit{background: white;}")

    def on_default_max(self):
        self.max_edit.setText(str(self._default_max))
        self.max_edit.setStyleSheet("QLineEdit{background: white;}")

    def on_default_format(self):
        self.format_edit.setText(str(self._default_format))
        self.format_edit.setStyleSheet("QLineEdit{background: white;}")

    def on_default_scale(self):
        self.scale_edit.setText(str(self._default_scale))
        self.scale_edit.setStyleSheet("QLineEdit{background: white;}")

    def on_default_ncolors(self):
        self.ncolors_edit.setText(str(self._default_ncolors))
        self.ncolors_edit.setStyleSheet("QLineEdit{background: white;}")

    def on_default_colormap(self):
        self.colormap_edit.setCurrentIndex(colormap_keys.index(self._default_colormap))

    def on_default_nlabels(self):
        self.nlabels_edit.setStyleSheet("QLineEdit{background: white;}")
        self.nlabels_edit.setText(str(self._default_nlabels))

    def on_default_labelsize(self):
        self.labelsize_edit.setText(str(self._default_labelsize))
        self.labelsize_edit.setStyleSheet("QLineEdit{background: white;}")


    @staticmethod
    def check_name(cell):
        cell_value = cell.text()
        try:
            text = str(cell_value).strip()
        except UnicodeEncodeError:
            cell.setStyleSheet("QLineEdit{background: red;}")
            return None, False

        if len(text):
            cell.setStyleSheet("QLineEdit{background: white;}")
            return text, True
        else:
            cell.setStyleSheet("QLineEdit{background: red;}")
            return None, False

    @staticmethod
    def check_colormap(cell):
        text = str(cell.text()).strip()
        if text in colormap_keys:
            cell.setStyleSheet("QLineEdit{background: white;}")
            return text, True
        else:
            cell.setStyleSheet("QLineEdit{background: red;}")
            return None, False

    def on_validate(self):
        name_value, flag0 = self.check_name(self.name_edit)
        min_value, flag1 = self.check_float(self.min_edit)
        max_value, flag2 = self.check_float(self.max_edit)
        format_value, flag3 = self.check_format(self.format_edit)
        scale_value, flag4 = self.check_float(self.scale_edit)

        nlabels, flag5 = self.check_positive_int_or_blank(self.nlabels_edit)
        ncolors, flag6 = self.check_positive_int_or_blank(self.ncolors_edit)
        labelsize, flag7 = self.check_positive_int_or_blank(self.labelsize_edit)
        colormap = str(self.colormap_edit.currentText())

        if all([flag0, flag1, flag2, flag3, flag4, flag5, flag6, flag7]):
            if 'i' in format_value:
                format_value = '%i'

            assert isinstance(scale_value, float), scale_value
            self.out_data['name'] = name_value
            self.out_data['min'] = min_value
            self.out_data['max'] = max_value
            self.out_data['format'] = format_value
            self.out_data['scale'] = scale_value

            self.out_data['nlabels'] = nlabels
            self.out_data['ncolors'] = ncolors
            self.out_data['labelsize'] = labelsize
            self.out_data['colormap'] = colormap

            self.out_data['is_low_to_high'] = self.low_to_high_radio.isChecked()
            self.out_data['is_horizontal'] = self.horizontal_radio.isChecked()
            self.out_data['is_shown'] = self.show_radio.isChecked()

            self.out_data['clicked_ok'] = True
            self.out_data['close'] = True
            #print('self.out_data = ', self.out_data)
            #print("name = %r" % self.name_edit.text())
            #print("min = %r" % self.min_edit.text())
            #print("max = %r" % self.max_edit.text())
            #print("format = %r" % self.format_edit.text())
            return True
        return False

    def on_apply(self):
        passed = self.on_validate()
        if passed:
            self.win_parent._apply_legend(self.out_data)
        return passed

    def on_ok(self):
        passed = self.on_apply()
        if passed:
            self.close()
            #self.destroy()

    def on_cancel(self):
        self.out_data['close'] = True
        self.close()
class PsychomotoCaDialog(QDialog):
    pagetitle = 'Skill-Assessment'
    holdc = {}
    hold = []

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

        ko = 0
        self.subjects = self.pullSubjects()

        self.frame1 = QGroupBox('Skills')
        self.frame2 = QGroupBox('Categories')

        hc1_box = QVBoxLayout()
        hc2_box = QVBoxLayout()
        self.li = []
        self.liID = []
        for subject in self.subjects:
            num = subject['id']
            self.liID.append(num)
            self.c = QRadioButton('cb' + str(num))
            self.c.setText(str(subject['name']).upper())
            self.c.setObjectName("chk" + str(num))
            self.c.setChecked(False)
            self.c.toggled.connect(
                lambda state, x=num, y=self.c: self.catItems(x, y))
            hc1_box.addWidget(self.c)
            self.li.append(self.c)

            ko += 1

        self.li1 = []
        self.li1ID = []
        self.hc2_box = QVBoxLayout()

        self.frame1.setLayout(hc1_box)
        #frame1.setFrameShape(QFrame.StyledPanel)
        self.frame2.setLayout(self.hc2_box)
        #frame2.setFrameShape(QFrame.StyledPanel)

        h_box = QHBoxLayout()
        h_box.addWidget(self.frame1)
        h_box.addWidget(self.frame2)

        self.pb = QPushButton()
        self.pb.setObjectName("MakeEntries")
        self.pb.setText("Edit View")

        self.pb1 = QPushButton()
        self.pb1.setObjectName("View Report")
        self.pb1.setText("Report View")

        self.pb2 = QPushButton()
        self.pb2.setObjectName("Cancel")
        self.pb2.setText("Cancel")

        but_box = QHBoxLayout()
        but_box.addWidget(self.pb2)
        but_box.addWidget(self.pb1)
        but_box.addWidget(self.pb)

        main_box = QVBoxLayout()
        main_box.addLayout(h_box)
        main_box.addLayout(but_box)

        self.setLayout(main_box)
        self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click())
        self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click())
        self.connect(self.pb2, SIGNAL("clicked()"),
                     lambda: self.button_close())
        self.setWindowTitle(self.pagetitle)

    def catItems(self, a, b):
        _a = a
        self.cas = self.pullCas(_a)
        print(self.hold)
        self.li1 = []
        self.li1ID = []
        for rp in self.hold:
            self.hc2_box.removeWidget(rp)
            sip.delete(rp)

        self.hold = []
        ko = 0
        for ca in self.cas:
            num = ca['id']
            self.li1ID.append(num)
            self.c1 = QCheckBox('cbx' + str(num))
            self.c1.setText(str(ca['name']).upper())
            self.c1.setObjectName("chkx" + str(num))
            self.c1.setChecked(True)
            self.hc2_box.addWidget(self.c1)
            self.hold.append(self.c1)
            self.li1.append(self.c1)
            ko += 1

        #self.hc2_box.show()

    def pullSubjects(self):
        cn = Db()
        arr = cn.selectn('datas', '', '', {'pubID': 9})
        return arr

    def pullCas(self, a):
        _a = a
        cn = Db()
        arr = cn.selectn('datas', '', '', {'subID': _a})
        return arr

    def button_close(self):
        self.reject()

    def button_click(self):
        self.accept()

    def getValue(self):

        k1 = []
        k2 = []
        for s in range(0, len(self.li)):
            if self.li[s].isChecked():
                k1.append(self.liID[s])
            else:
                k2.append(self.liID[s])

        k11 = []
        k21 = []
        for s in range(0, len(self.li1)):
            if self.li1[s].isChecked():
                k11.append(self.li1ID[s])
            else:
                k21.append(self.li1ID[s])

        return [k1, k11]
class RunsDialog(QtHelper.EnhancedQDialog):
    """
    Runs several dialog
    """
    RefreshRepository = pyqtSignal(str)
    def __init__(self, dialogName, parent = None, iRepo=None, lRepo=None, rRepo=None):
        """
        Constructor
        """
        QtHelper.EnhancedQDialog.__init__(self, parent)

        self.name = self.tr("Prepare a group of runs")
        self.projectReady = False
        self.iRepo = iRepo
        self.lRepo = lRepo
        self.rRepo = rRepo

        self.createDialog()
        self.createConnections()

    def createDialog(self):
        """
        Create qt dialog
        """
        self.setWindowTitle( self.name )

        mainLayout = QHBoxLayout()
        layoutTests = QHBoxLayout()
        layoutRepoTest = QVBoxLayout()

        self.prjCombo = QComboBox(self)
        self.prjCombo.setEnabled(False)

        self.repoTests = QTreeWidget(self)
        self.repoTests.setFrameShape(QFrame.NoFrame)
        if USE_PYQT5:
            self.repoTests.header().setSectionResizeMode(QHeaderView.Stretch)
        else:
            self.repoTests.header().setResizeMode(QHeaderView.Stretch)
        self.repoTests.setHeaderHidden(True)
        self.repoTests.setContextMenuPolicy(Qt.CustomContextMenu)
        self.repoTests.setIndentation(10)

        layoutRepoTest.addWidget(self.prjCombo)
        layoutRepoTest.addWidget(self.repoTests)

        self.testsList = QListWidget(self)

        layoutTests.addLayout( layoutRepoTest )
        layoutTests.addWidget( self.testsList )
        mainLayout.addLayout( layoutTests )

        buttonLayout = QVBoxLayout()

        self.okButton = QPushButton(self.tr("Execute All"), self)
        self.okButton.setEnabled(False)
        self.cancelButton = QPushButton(self.tr("Cancel"), self)
        self.upButton = QPushButton(self.tr("UP"), self)
        self.upButton.setEnabled(False)
        self.downButton = QPushButton(self.tr("DOWN"), self)
        self.downButton.setEnabled(False)
        self.clearButton = QPushButton(self.tr("Remove All"), self)
        self.delButton = QPushButton(self.tr("Remove"), self)
        self.delButton.setEnabled(False)

        self.runSimultaneous = QCheckBox(self.tr("Simultaneous Run"))
        
        self.schedImmed = QRadioButton(self.tr("Run Immediately"))
        self.schedImmed.setChecked(True)
        self.schedAt = QRadioButton(self.tr("Run At:"))
        self.schedAtDateTimeEdit = QDateTimeEdit(QDateTime.currentDateTime())
        self.schedAtDateTimeEdit.setEnabled(False)

        buttonLayout.addWidget(self.okButton)
        buttonLayout.addWidget(self.runSimultaneous)
        buttonLayout.addWidget(self.schedImmed)
        buttonLayout.addWidget(self.schedAt)
        buttonLayout.addWidget(self.schedAtDateTimeEdit)

        
        buttonLayout.addWidget( self.upButton )
        buttonLayout.addWidget( self.downButton )
        buttonLayout.addWidget( self.delButton )
        buttonLayout.addWidget( self.clearButton )

        buttonLayout.addWidget(self.cancelButton)

        mainLayout.addLayout(buttonLayout)

        self.setMinimumHeight(400)
        self.setMinimumWidth(750)
        self.setLayout(mainLayout)

    def initProjects(self, projects=[], defaultProject=1):
        """
        Initialize projects
        """
        # init date and time
        self.schedAtDateTimeEdit.setDateTime(QDateTime.currentDateTime()) 

        self.projectReady = False

        self.repoTests.clear()
        self.prjCombo.clear()
        self.testsList.clear()

        self.prjCombo.setEnabled(True)
        
        # insert data
        pname = ''
        for p in projects:
            self.prjCombo.addItem ( p['name']  )
            if defaultProject == p['project_id']:
                pname = p['name']
        
        for i in xrange(self.prjCombo.count()):
            item_text = self.prjCombo.itemText(i)
            if str(pname) == str(item_text):
                self.prjCombo.setCurrentIndex(i)

        self.projectReady = True
        self.RefreshRepository.emit(pname)

    def initializeTests(self, listing):
        """
        Initialize tests
        """
        self.repoTests.clear()
        self.testRoot = self.rRepo.Item(repo = self.iRepo.remote(), 
                                        parent = self.repoTests, txt = "Root", 
                                        type = QTreeWidgetItem.UserType+10, 
                                        isRoot = True )
        self.testRoot.setSelected(True)
        self.createRepository(listing=listing, parent=self.testRoot,fileincluded=True)
        self.repoTests.sortItems(0, Qt.AscendingOrder)

        self.hideItems(hideTsx=False, hideTpx=False, hideTcx=True, hideTdx=True, hideTxt=True, hidePy=True,
                                hideTux=False, hidePng=True, hideTgx=False, hideTax=False)

    def createRepository(self, listing, parent, fileincluded=True):
        """
        Create repository

        @param listing: 
        @type listing: list

        @param parent: 
        @type parent:

        @param fileincluded: 
        @type fileincluded: boolean
        """
        try:
            for dct in  listing:
                if dct["type"] == "folder":
                    item = self.rRepo.Item(repo = self.iRepo.remote(), parent = parent, 
                                           txt = dct["name"], propertiesFile=dct )
                    self.createRepository(  dct["content"] , item, fileincluded )
                else:
                    if fileincluded:
                        if dct["type"] == "file":
                            pname = self.iRepo.remote().getProjectName(dct["project"])
                            # {'modification': 1342259500, 'type': 'file', 'name': '__init__.py', 'size': '562 }
                            item = self.rRepo.Item(repo = self.iRepo.remote(), parent = parent, txt = dct["name"] ,
                                                   propertiesFile=dct, type = QTreeWidgetItem.UserType+0, 
                                                   projectId=dct["project"], projectName=pname )

        except Exception as e:
            self.error( "unable to create tree for runs: %s" % e )

    def onProjectChanged(self, projectItem):
        """
        Called when the project changed on the combo box
        """
        if self.projectReady:
            item_text = self.prjCombo.itemText(projectItem)
            self.RefreshRepository.emit(item_text)

    def createConnections (self):
        """
        create qt connections
         * ok
         * cancel
        """
        self.prjCombo.currentIndexChanged.connect(self.onProjectChanged)
        self.okButton.clicked.connect( self.acceptClicked )
        self.cancelButton.clicked.connect( self.reject )
        self.upButton.clicked.connect(self.upTest)
        self.downButton.clicked.connect(self.downTest)
        self.clearButton.clicked.connect(self.clearList)
        self.delButton.clicked.connect(self.delTest)

        self.testsList.itemClicked.connect(self.onItemSelected)
        self.testsList.itemSelectionChanged.connect(self.onItemSelectionChanged)

        self.schedAt.toggled.connect(self.onSchedAtActivated)

        self.repoTests.itemDoubleClicked.connect( self.onTestDoucleClicked )

    def onSchedAtActivated(self, toggled):
        """
        On sched at button activated
        """
        if toggled:
            self.schedAtDateTimeEdit.setEnabled(True)
        else:
            self.schedAtDateTimeEdit.setEnabled(False)

    def onItemSelectionChanged(self):
        """
        Called on item selection changed
        """
        self.onItemSelected(itm=None)

    def onItemSelected(self, itm):
        """
        Call on item selected
        """
        selectedItems = self.testsList.selectedItems()
        if len(selectedItems):
            self.delButton.setEnabled(True)
            self.upButton.setEnabled(True)
            self.downButton.setEnabled(True)
        else:
            self.delButton.setEnabled(False)
            self.upButton.setEnabled(False)
            self.downButton.setEnabled(False)

        if not self.testsList.count():
            self.okButton.setEnabled(False)

    def upTest(self):
        """
        Up test
        """
        currentRow = self.testsList.currentRow()
        currentItem = self.testsList.takeItem(currentRow)
        self.testsList.insertItem(currentRow - 1, currentItem)

    def downTest(self):
        """
        Down test
        """
        currentRow = self.testsList.currentRow()
        currentItem = self.testsList.takeItem(currentRow)
        self.testsList.insertItem(currentRow + 1, currentItem)


    def delTest(self):
        """
        Del test
        """
        currentRow = self.testsList.currentRow()
        currentItem = self.testsList.takeItem(currentRow)

    def clearList(self):
        """
        Clear test
        """
        self.testsList.clear()
        self.delButton.setEnabled(False)
        self.upButton.setEnabled(False)
        self.downButton.setEnabled(False)

        self.okButton.setEnabled(False)

    def iterateTree(self, item, hideTsx, hideTpx, hideTcx, hideTdx, hideTxt, 
                          hidePy, hideTux, hidePng, hideTgx, hideTax):
        """
        Iterate tree
        """
        child_count = item.childCount()
        for i in range(child_count):
            subitem = item.child(i)
            subchild_count = subitem.childCount()
            if subchild_count > 0:
                self.iterateTree(item=subitem, hideTsx=hideTsx, 
                                 hideTpx=hideTpx, hideTcx=hideTcx, 
                                 hideTdx=hideTdx, hideTxt=hideTxt,
                                 hidePy=hidePy, hideTux=hideTux, 
                                 hidePng=hidePng, hideTgx=hideTgx, hideTax=hideTax)
            else:
                if hideTux and subitem.getExtension() == self.rRepo.EXTENSION_TUX:
                    subitem.setHidden (True)
                elif hideTpx and subitem.getExtension() == self.rRepo.EXTENSION_TPX:
                    subitem.setHidden (True)
                elif hideTgx and subitem.getExtension() == self.rRepo.EXTENSION_TGX:
                    subitem.setHidden (True)
                elif hideTcx and subitem.getExtension() == self.rRepo.EXTENSION_TCX:
                    subitem.setHidden (True)
                elif hideTsx and  subitem.getExtension() == self.rRepo.EXTENSION_TSX:
                    subitem.setHidden (True)
                elif hideTdx and  subitem.getExtension() == self.rRepo.EXTENSION_TDX:
                    subitem.setHidden (True)
                elif hideTxt and  subitem.getExtension() == self.rRepo.EXTENSION_TXT:
                    subitem.setHidden (True)
                elif hidePy and  subitem.getExtension() == self.rRepo.EXTENSION_PY:
                    subitem.setHidden (True)
                elif hidePng and  subitem.getExtension() == self.rRepo.EXTENSION_PNG:
                    subitem.setHidden (True)
                elif hideTax and  subitem.getExtension() == self.rRepo.EXTENSION_TAx:
                    subitem.setHidden (True)
                else:
                    subitem.setHidden(False)

    def hideItems(self, hideTsx=False, hideTpx=False, hideTcx=False, hideTdx=False, hideTxt=False, hidePy=False, 
                        hideTux=False, hidePng=False, hideTgx=False, hideTax=False):
        """
        Hide items
        """
        root = self.repoTests.invisibleRootItem()
        self.iterateTree(item=root, hideTsx=hideTsx, hideTpx=hideTpx, hideTcx=hideTcx, 
                         hideTdx=hideTdx, hideTxt=hideTxt, hidePy=hidePy,
                         hideTux=hideTux, hidePng=hidePng, hideTgx=hideTgx, hideTax=hideTax)

    def onTestDoucleClicked(self, testItem):
        """
        On tests double clicked
        """
        if testItem.type() != QTreeWidgetItem.UserType+0:
            return

        self.okButton.setEnabled(True)

        currentProject = self.prjCombo.currentText()

        testName = "%s:%s" % (str(currentProject),testItem.getPath(withFileName = True))
        testItem = QListWidgetItem(testName )

        if testName.endswith(self.rRepo.EXTENSION_TUX):
            testItem.setIcon(QIcon(":/tux.png"))
        if testName.endswith(self.rRepo.EXTENSION_TSX):
            testItem.setIcon(QIcon(":/tsx.png"))
        if testName.endswith(self.rRepo.EXTENSION_TPX):
            testItem.setIcon(QIcon(":/tpx.png"))
        if testName.endswith(self.rRepo.EXTENSION_TGX):
            testItem.setIcon(QIcon(":/tgx.png"))
        if testName.endswith(self.rRepo.EXTENSION_TAX):
            testItem.setIcon(QIcon(":/tax.png"))
            
        self.testsList.addItem( testItem )

    def acceptClicked (self):
        """
        Called on accept button
        """
        self.accept()
    
    def getTests(self):
        """
        Returns all tests in the list
        """
        tests = []
        for i in xrange(self.testsList.count()):
            testItem = self.testsList.item(i)
            tests.append( str(testItem.text()) )

        runSimultaneous = False
        if self.runSimultaneous.isChecked(): runSimultaneous = True
        
        if self.schedImmed.isChecked():
            runAt = (0,0,0,0,0,0)
            return (tests, False, runAt, runSimultaneous)
        else:
            pydt = self.schedAtDateTimeEdit.dateTime().toPyDateTime()
            runAt = (pydt.year, pydt.month, pydt.day, pydt.hour, pydt.minute, pydt.second)
            return (tests, True, runAt, runSimultaneous)
Exemple #51
0
class DHttpReplay(QtHelper.EnhancedQDialog, Logger.ClassLogger):
    """
    Http replay dialog
    """
    def __init__(self, parent=None, offlineMode=False):
        """
        Constructor

        @param parent: 
        @type parent:
        """
        super(DHttpReplay, self).__init__(parent)
        self.offlineMode = offlineMode
        self.defaultIp = "127.0.0.1"
        self.defaultPort = "80"
        self.newTest = ''
        self.newTestExec = ''
        self.newInputs = []
        self.requests = []
        self.responses = []
        self.defaultTemplates = DefaultTemplates.Templates()
        self.testType = None

        self.createDialog()
        self.createConnections()
        self.createActions()
        self.createToolbar()

    def createActions(self):
        """
        Create qt actions
        """
        self.openAction = QtHelper.createAction(self,
                                                "&Open",
                                                self.importTrace,
                                                icon=QIcon(":/folder_add.png"),
                                                tip='Open network trace.')
        self.exportTUAction = QtHelper.createAction(
            self,
            "&Test Unit",
            self.exportToTU,
            icon=QIcon(":/%s.png" % WWorkspace.TestUnit.TYPE),
            tip='Export to Test Unit')
        self.exportTSAction = QtHelper.createAction(
            self,
            "&Test Suite",
            self.exportToTS,
            icon=QIcon(":/%s.png" % WWorkspace.TestSuite.TYPE),
            tip='Export to Test Suite')
        self.cancelAction = QtHelper.createAction(self,
                                                  "&Cancel",
                                                  self.reject,
                                                  tip='Cancel')

        menu = QMenu(self)
        menu.addAction(self.exportTUAction)
        menu.addAction(self.exportTSAction)

        self.exportToAction = QtHelper.createAction(
            self,
            "&Export to",
            self.exportToTU,
            icon=QIcon(":/%s.png" % WWorkspace.TestUnit.TYPE),
            tip='Export to tests')
        self.exportToAction.setMenu(menu)
        self.exportToAction.setEnabled(False)

    def createDialog(self):
        """
        Create dialog
        """

        self.dockToolbar = QToolBar(self)
        self.dockToolbar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)

        self.setWindowTitle(WINDOW_TITLE)
        self.resize(500, 400)

        self.ipEdit = QLineEdit(self.defaultIp)
        ipRegExpVal = QRegExpValidator(self)
        ipRegExp = QRegExp("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")
        ipRegExpVal.setRegExp(ipRegExp)
        self.ipEdit.setValidator(ipRegExpVal)

        self.portEdit = QLineEdit(self.defaultPort)
        self.portEdit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        validatorPort = QIntValidator(self)
        self.portEdit.setValidator(validatorPort)

        self.progressBar = QProgressBar(self)
        self.progressBar.setMaximum(100)
        self.progressBar.setProperty("value", 0)
        self.progressBar.setAlignment(Qt.AlignCenter)
        self.progressBar.setObjectName("progressBar")

        self.guiSikuliGroupBox = QGroupBox("")
        self.guiSikuliGroupBox.setFlat(True)
        self.automaticAdp = QRadioButton("Automatic")
        self.automaticAdp.setChecked(True)
        self.defaultAdp = QRadioButton("Default")
        self.genericAdp = QRadioButton("Generic")
        vbox = QHBoxLayout()
        vbox.addWidget(self.automaticAdp)
        vbox.addWidget(self.defaultAdp)
        vbox.addWidget(self.genericAdp)
        vbox.addStretch(1)
        self.guiSikuliGroupBox.setLayout(vbox)

        layout = QVBoxLayout()
        layout.addWidget(self.dockToolbar)
        layout.addSpacing(12)
        paramLayout = QGridLayout()
        paramLayout.addWidget(QLabel("Destination IP:"), 0, 0, Qt.AlignRight)
        paramLayout.addWidget(self.ipEdit, 0, 1)
        paramLayout.addWidget(QLabel("Destination Port:"), 1, 0, Qt.AlignRight)
        paramLayout.addWidget(self.portEdit, 1, 1)
        paramLayout.addWidget(QLabel(self.tr("Gui adapter selector:")), 2, 0,
                              Qt.AlignRight)
        paramLayout.addWidget(self.guiSikuliGroupBox, 2, 1)
        layout.addLayout(paramLayout)

        self.logsEdit = QTextEdit()
        self.logsEdit.setReadOnly(True)
        self.logsEdit.setTextInteractionFlags(Qt.NoTextInteraction)

        layout.addSpacing(12)
        layout.addWidget(self.logsEdit)
        layout.addSpacing(12)
        layout.addWidget(self.progressBar)

        self.setLayout(layout)

    def createToolbar(self):
        """
        Create toolbar
        """
        self.dockToolbar.setObjectName("File toolbar")
        self.dockToolbar.addAction(self.openAction)
        self.dockToolbar.addSeparator()
        self.dockToolbar.addAction(self.exportToAction)
        self.dockToolbar.addSeparator()
        self.dockToolbar.setIconSize(QSize(16, 16))

    def createConnections(self):
        """
        Create qt connections
        """
        pass

    def autoScrollOnTextEdit(self):
        """
        Automatic scroll on text edit
        """
        cursor = self.logsEdit.textCursor()
        cursor.movePosition(QTextCursor.End)
        self.logsEdit.setTextCursor(cursor)

    def strip_html(self, txt):
        """
        Strip html
        """
        if "<" in txt:
            txt = txt.replace('<', '&lt;')
        if ">" in txt:
            txt = txt.replace('>', '&gt;')
        return txt

    def addLogSuccess(self, txt):
        """
        Add log success in the text edit
        """
        self.logsEdit.insertHtml(
            "<span style='color:darkgreen'>%s</span><br />" %
            unicode(self.strip_html(txt)))
        self.autoScrollOnTextEdit()

    def addLogWarning(self, txt):
        """
        Add log warning in the text edit
        """
        self.logsEdit.insertHtml(
            "<span style='color:darkorange'>%s</span><br />" %
            unicode(self.strip_html(txt)))
        self.autoScrollOnTextEdit()

    def addLogError(self, txt):
        """
        Add log error in the text edit
        """
        self.logsEdit.insertHtml("<span style='color:red'>%s</span><br />" %
                                 unicode(self.strip_html(txt)))
        self.autoScrollOnTextEdit()

    def addLog(self, txt):
        """
        Append log to the logsEdit widget
        """
        self.logsEdit.insertHtml("%s<br />" % unicode(self.strip_html(txt)))
        self.autoScrollOnTextEdit()

    def importTrace(self):
        """
        Import network trace
        """
        self.logsEdit.clear()
        self.testType = None

        if not self.offlineMode:
            if not RCI.instance().isAuthenticated():
                self.addLogWarning(
                    txt="<< Connect to the test center in first!")
                QMessageBox.warning(self, "Import",
                                    "Connect to the test center in first!")
                return

        self.exportToAction.setEnabled(False)
        self.newTest = ''
        self.progressBar.setMaximum(100)
        self.progressBar.setValue(0)

        if sys.version_info > (3, ):
            fileName = QFileDialog.getOpenFileName(
                self, self.tr("Open File"), "",
                "Network dump (*.cap;*.pcap;*.pcapng)")
        else:
            fileName = QFileDialog.getOpenFileName(self, self.tr("Open File"),
                                                   "", "Network dump (*.cap)")
        # new in v18 to support qt5
        if QtHelper.IS_QT5:
            _fileName, _type = fileName
        else:
            _fileName = fileName
        # end of new

        if not _fileName:
            return

        if sys.version_info < (3, ):
            extension = str(_fileName).rsplit(".", 1)[1]
            if not (extension == "cap"):
                self.addLogError(txt="<< File not supported %s" % _fileName)
                QMessageBox.critical(self, "Open", "File not supported")
                return

        _fileName = str(_fileName)
        capName = _fileName.rsplit("/", 1)[1]

        self.addLogSuccess(txt=">> Reading the file %s" % _fileName)
        if sys.version_info > (3, ):
            self.readFileV2(fileName=_fileName)
        else:
            self.readFile(fileName=_fileName)

    def exportToTS(self):
        """
        Export to test suite
        """
        self.testType = TS
        self.exportToTest(TS=True, TU=False)

    def exportToTU(self):
        """
        Export to test unit
        """
        self.testType = TU
        self.exportToTest(TS=False, TU=True)

    def searchHTTP(self):
        """
        Search HTTP module in assistant
        """
        # modules accessor
        ret = "SutAdapters"
        if self.automaticAdp.isChecked():
            isGeneric = WWorkspace.Helper.instance().isGuiGeneric(name="GUI")
            if isGeneric:
                ret = "SutAdapters.Generic"
        elif self.defaultAdp.isChecked():
            return ret
        elif self.genericAdp.isChecked():
            ret = "SutAdapters.Generic"
        else:
            pass
        return ret

    def exportToTest(self, TS=True, TU=False):
        """
        Export to test
        """
        if not RCI.instance().isAuthenticated():
            self.addLogWarning(txt="<< Connect to the test center in first!")
            QMessageBox.warning(self, "Import",
                                "Connect to the test center in first!")
            return

        if TS:
            self.newTest = self.defaultTemplates.getTestDefinitionAuto()
            self.newTestExec = self.defaultTemplates.getTestExecutionAuto()
        if TU:
            self.newTest = self.defaultTemplates.getTestUnitDefinitionAuto()

        destIp = str(self.ipEdit.text())
        destPort = str(self.portEdit.text())

        self.newInputs = []
        self.newInputs.append({
            'type': 'self-ip',
            'name': 'BIND_IP',
            'description': '',
            'value': '0.0.0.0',
            'color': ''
        })
        self.newInputs.append({
            'type': 'int',
            'name': 'BIND_PORT',
            'description': '',
            'value': '0',
            'color': ''
        })
        self.newInputs.append({
            'type': 'str',
            'name': 'DEST_IP',
            'description': '',
            'value': '%s' % destIp,
            'color': ''
        })
        self.newInputs.append({
            'type': 'int',
            'name': 'DEST_PORT',
            'description': '',
            'value': '%s' % destPort,
            'color': ''
        })
        self.newInputs.append({
            'type': 'bool',
            'name': 'DEBUG',
            'description': '',
            'value': 'False',
            'color': ''
        })
        self.newInputs.append({
            'type': 'float',
            'name': 'TIMEOUT',
            'description': '',
            'value': '5.0',
            'color': ''
        })

        adps = """self.ADP_HTTP = %s.HTTP.Client(parent=self, bindIp=input('BIND_IP'), bindPort=input('BIND_PORT'), destinationIp=input('DEST_IP'), destinationPort=input('DEST_PORT'), debug=input('DEBUG'))""" % self.searchHTTP(
        )

        # prepare steps
        steps = []
        j = 0
        for i in xrange(len(self.requests)):
            j = i + 1
            if sys.version_info > (3, ):  # python3 support
                (source, dest, source_port, dest_port, buf_req,
                 reqDecoded) = self.requests[i]
                http_method = str(reqDecoded['method'], 'utf8')
                http_status = 'no'
                http_reason = ''
            else:
                http_method = self.requests[i]['tcp-object'].method
                http_status = 'no'
                http_reason = ''
            try:
                if sys.version_info > (3, ):  # python3 support
                    (sourceRsp, destRsp, sourcePortRsp, destPortRsp, bufReqRsp,
                     reqDecodedRsp) = self.responses[i]
                    http_status = str(reqDecodedRsp['code'])
                    http_reason = str(reqDecodedRsp['phrase'], 'utf8')
                else:
                    http_status = self.responses[i]['tcp-object'].status
                    http_reason = self.responses[i]['tcp-object'].reason
            except Exception as e:
                print(e)
            steps.append(
                'self.step%s = self.addStep(expected="%s %s response", description="send %s request", summary="send %s request")'
                % (j, http_status, http_reason, http_method, http_method))

        tests = []
        for i in xrange(len(self.requests)):
            j = i + 1
            if sys.version_info > (3, ):  # python3 support
                (source, dest, source_port, dest_port, buf_req,
                 reqDecoded) = self.requests[i]
            tests.append("# request %s" % j)
            tests.append('self.step%s.start()' % j)

            if sys.version_info > (3, ):  # python3 support
                lines_req = buf_req.splitlines()
            else:
                lines_req = self.requests[i]['tcp-data'].splitlines()

            if sys.version_info > (3, ):  # python3 support
                tests.append('rawHttp = [%s]' %
                             lines_req[0].replace(b'"', b'\\"'))
            else:
                tests.append('rawHttp = ["%s"]' %
                             lines_req[0].replace(b'"', b'\\"'))
            for lreq in lines_req[1:]:
                if sys.version_info > (3, ):  # python3 support
                    tests.append('rawHttp.append(%s)' %
                                 lreq.replace(b'"', b'\\"'))
                else:
                    tests.append('rawHttp.append("%s")' %
                                 lreq.replace(b'"', b'\\"'))

            tests.append('')
            tests.append(
                'req_tpl = self.ADP_HTTP.constructTemplateRequest(rawHttp=rawHttp)'
            )
            tests.append('req = self.ADP_HTTP.sendRequest(tpl=req_tpl)')

            try:
                tests.append('')
                if sys.version_info > (3, ):  # python3 support
                    (sourceRsp, destRsp, sourcePortRsp, destPortRsp, bufReqRsp,
                     reqDecodedRsp) = self.responses[i]
                    lines_res = bufReqRsp.splitlines()
                else:
                    lines_res = self.responses[i]['tcp-data'].splitlines()
                if sys.version_info > (3, ):  # python3 support
                    tests.append('rawHttpRsp = [%s]' %
                                 lines_res[0].replace(b"'", b"\\'"))
                else:
                    tests.append('rawHttpRsp = ["%s"]' %
                                 lines_res[0].replace(b'"', b'\\"'))
                for lres in lines_res[1:]:
                    if sys.version_info > (3, ):  # python3 support
                        tests.append('rawHttpRsp.append(%s)' %
                                     lres.replace(b"'", b"\\'"))
                    else:
                        tests.append('rawHttpRsp.append("%s")' %
                                     lres.replace(b'"', b'\\"'))
            except Exception as e:
                self.error("unable to append response: %s" % e)
            tests.append(
                'rsp_tpl = self.ADP_HTTP.constructTemplateResponse(rawHttp=rawHttpRsp)'
            )
            tests.append(
                "rsp = self.ADP_HTTP.hasReceivedResponse(expected=rsp_tpl, timeout=input('TIMEOUT'))"
            )
            tests.append('if rsp is None:')
            tests.append(
                '\tself.step%s.setFailed(actual="incorrect response")' % j)
            tests.append('else:')
            tests.append('\tself.step%s.setPassed(actual="ok")' % j)
            tests.append('')
        if TS:
            init = """self.ADP_HTTP.connect()
		connected = self.ADP_HTTP.isConnected( timeout=input('TIMEOUT') )
		if not connected:
			self.abort( 'unable to connect to the tcp port %s'  )
""" % str(self.portEdit.text())

        if TU:
            init = """self.ADP_HTTP.connect()
	connected = self.ADP_HTTP.isConnected( timeout=input('TIMEOUT') )
	if not connected:
		self.abort( 'unable to connect to the tcp port %s'  )
""" % str(self.portEdit.text())

        if TS:
            cleanup = """self.ADP_HTTP.disconnect()
		disconnected = self.ADP_HTTP.isDisconnected( timeout=input('TIMEOUT') )
		if not disconnected:
			self.error( 'unable to disconnect from the tcp port %s' )
""" % str(self.portEdit.text())

        if TU:
            cleanup = """self.ADP_HTTP.disconnect()
	disconnected = self.ADP_HTTP.isDisconnected( timeout=input('TIMEOUT') )
	if not disconnected:
		self.error( 'unable to disconnect from the tcp port %s' )
""" % str(self.portEdit.text())

        self.newTest = self.newTest.replace(
            "<<PURPOSE>>", 'self.setPurpose(purpose="Replay HTTP")')
        self.newTest = self.newTest.replace("<<ADPS>>", adps)
        if TS:
            self.newTest = self.newTest.replace("<<STEPS>>",
                                                '\n\t\t'.join(steps))
        if TU:
            self.newTest = self.newTest.replace("<<STEPS>>",
                                                '\n\t'.join(steps))
        self.newTest = self.newTest.replace("<<INIT>>", init)
        self.newTest = self.newTest.replace("<<CLEANUP>>", cleanup)
        if TS:
            self.newTest = self.newTest.replace("<<TESTS>>",
                                                '\n\t\t'.join(tests))
        if TU:
            self.newTest = self.newTest.replace("<<TESTS>>",
                                                '\n\t'.join(tests))

        self.accept()

    def decodeHttpRequest(self, data):
        """
        Decode http request
        Content chunked not yet implemented
        """
        http = {"type": "request"}
        lines = data.splitlines()
        try:
            request_line = lines[0]
        except Exception:
            self.error("unable to decode http request: %s" % lines)
            return None

        try:
            http["method"] = request_line.split(b" ", 2)[0]
            http["uri"] = request_line.split(b" ", 2)[1]
            http["version"] = request_line.split(b" ", )[2]
        except Exception:
            self.error(
                "unable to decode status code in the http response: %s" %
                request_line)
            return None

        http["body"] = data.split(b"\r\n\r\n")[1]

        headers = []
        contentLenght = 0
        contentChunked = False
        for hdr in data.split(b"\r\n\r\n")[0].splitlines()[1:]:
            if len(hdr):
                k, v = hdr.split(b":", 1)
                if k.lower() == b"content-length":
                    contentLenght = int(v)
                if k.lower() == b"transfer-encoding":
                    if v.lowert() == b"chunked":
                        contentChunked = True

                headers.append(hdr)

        http["headers"] = headers

        if len(http["body"]) != contentLenght:
            return None  # need more data
        return http

    def decodeHttpResponse(self, data):
        """
        Decode http response without body
        """
        http = {"type": "response"}
        lines = data.splitlines()
        try:
            status_line = lines[0]
        except Exception:
            self.error("unable to decode http response: %s" % lines)
            return None

        try:
            http["code"] = int(status_line.split(b" ")[1])
            http["phrase"] = status_line.split(b" ", 2)[2]
        except Exception:
            self.error(
                "unable to decode status code in the http response: %s" %
                status_line)
            return None

        http["headers"] = lines[1:]
        return http

    def readFileV2(self, fileName):
        """
        Read pcap file 
        Support pcap-ng too
        """
        fd = open(fileName, 'rb')
        fileFormat, fileHead = PcapParse.extractFormat(fd)
        if fileFormat == PcapParse.FileFormat.PCAP:
            self.trace("pcap file detected")
            pcapFile = PcapReader.PcapFile(fd, fileHead).read_packet
            self.readFilePacket(pcapFile=pcapFile)
        elif fileFormat == PcapParse.FileFormat.PCAP_NG:
            self.trace("pcap-png file detected")
            pcapFile = PcapngReader.PcapngFile(fd, fileHead).read_packet
            self.readFilePacket(pcapFile=pcapFile)
        else:
            self.addLogError(txt="<< Error to open the network trace")
            self.error('unable to open the network trace: file format = %s' %
                       fileFormat)
            QMessageBox.critical(self, "Import", "File not supported")

    def __readRequest(self, buffer, data, request, output):
        """
        Read request
        """
        buffer += data
        if b'\r\n\r\n' in data:
            reqDecoded = self.decodeHttpRequest(data=buffer)
            if reqDecoded is not None:
                output.append(request + (reqDecoded, ))
                buffer = b''
            else:
                print("need more data: decode request failed")
        else:
            print("need more data, no body separator detected on request")

    def readFilePacket(self, pcapFile):
        """
        Read file packet by packet
        """
        ip_expected = str(self.ipEdit.text())
        port_expected = int(self.portEdit.text())

        # read packet)
        packets = pcapFile()
        ethernetPackets = list(packets)
        self.addLogSuccess(txt="<< Number of packets detected: %s " %
                           len(ethernetPackets))

        # extract tcp packet according to the expected ip and port
        tcpPacketsSent = []
        tcpPacketsRecv = []
        i = 1
        self.progressBar.setMaximum(len(ethernetPackets))
        self.progressBar.setValue(0)
        for pkt in ethernetPackets:
            self.progressBar.setValue(i)
            i += 1
            pktDecoded = PcapParse.decodePacket(pkt, getTcp=True, getUdp=False)
            if pktDecoded is not None:
                (source, dest, source_port, dest_port, data) = pktDecoded
                # skip when no data exists
                if dest == ip_expected and int(dest_port) == int(
                        port_expected) and len(data) > 0:
                    tcpPacketsSent.append(pktDecoded)
                if source == ip_expected and int(source_port) == int(
                        port_expected) and len(data) > 0:
                    tcpPacketsRecv.append(pktDecoded)
        self.addLogSuccess(txt="<< Number of TCP packets sent: %s " %
                           len(tcpPacketsSent))
        self.addLogSuccess(txt="<< Number of TCP packets received: %s " %
                           len(tcpPacketsRecv))

        # decode https requests
        self.requests = []
        buf_req = b''
        i = 1
        self.progressBar.setMaximum(len(tcpPacketsSent))
        self.progressBar.setValue(0)
        # decode the complete packet
        for req in tcpPacketsSent:
            self.progressBar.setValue(i)
            i += 1
            (source, dest, source_port, dest_port, data) = req
            if buf_req:
                buf_req += data
                if b'\r\n\r\n' in data:
                    reqDecoded = self.decodeHttpRequest(data=buf_req)
                    if reqDecoded is not None:
                        self.requests.append((source, dest, source_port,
                                              dest_port, buf_req, reqDecoded))
                        buf_req = b''
            else:
                if isRequest(data):
                    buf_req += data
                    if b'\r\n\r\n' in data:
                        reqDecoded = self.decodeHttpRequest(data=buf_req)
                        if reqDecoded is not None:
                            self.requests.append(
                                (source, dest, source_port, dest_port, buf_req,
                                 reqDecoded))
                            buf_req = b''

        self.addLogSuccess(txt="<< Number of HTTP requests extracted: %s " %
                           len(self.requests))

        # decode https response
        self.responses = []
        buf_rsp = b''
        i = 1
        self.progressBar.setMaximum(len(tcpPacketsRecv))
        self.progressBar.setValue(0)
        # decode just headers for response
        for req in tcpPacketsRecv:
            self.progressBar.setValue(i)
            i += 1
            (source, dest, source_port, dest_port, data) = req
            if buf_rsp:
                buf_rsp += data
                # try to decode response without body
                if b'\r\n\r\n' in data:
                    rspDecoded = self.decodeHttpResponse(data=buf_rsp)
                    if rspDecoded is not None:
                        self.responses.append((source, dest, source_port,
                                               dest_port, buf_rsp, rspDecoded))
                        buf_rsp = b''
            else:
                # is http response ?
                if data.startswith(b'HTTP/'):
                    buf_rsp += data
                    if b'\r\n\r\n' in data:
                        rspDecoded = self.decodeHttpResponse(data=buf_rsp)
                        if rspDecoded is not None:
                            self.responses.append(
                                (source, dest, source_port, dest_port, buf_rsp,
                                 rspDecoded))
                            buf_rsp = b''
        self.addLogSuccess(txt="<< Number of HTTP responses extracted: %s " %
                           len(self.responses))

        if self.requests:
            self.addLogSuccess("<< Read the file finished with success!")
            self.addLogWarning(
                "<< Click on the export button to generate the test!")
            self.exportToAction.setEnabled(True)
        else:
            self.addLogWarning("<< No http extracted!")

    def readFile(self, fileName):
        """
        Read the file passed as argument
        Old function with dtpkt and python2.7
        """
        self.requests = []
        self.responses = []

        ip_expected = socket.inet_aton(str(self.ipEdit.text()))
        port_expected = str(self.portEdit.text())

        try:
            f = open(fileName, 'rb')
            pcap = dpkt.pcap.Reader(f)
            tot_pkts = len(list(pcap))
        except Exception as e:
            self.addLogError(txt="<< Error to open the network trace")
            self.error('unable to open the network trace: %s' % str(e))
            QMessageBox.critical(self, "Import", "File not supported")
            return
        else:
            self.addLogSuccess(txt="<< Total packets detected: %s " % tot_pkts)
            self.progressBar.setMaximum(tot_pkts)

            # decode http request
            i = 1
            buf_req = ''
            for ts, buf in pcap:
                self.progressBar.setValue(i)
                i += 1

                # read ethernet layer
                eth = dpkt.ethernet.Ethernet(buf)
                if eth.type == dpkt.ethernet.ETH_TYPE_IP:
                    # continue with ip decoding layer
                    ip = eth.data
                    if ip.dst == ip_expected:
                        ip_layer = (ip.src, ip.dst)
                        if ip.p == dpkt.ip.IP_PROTO_TCP:
                            tcp = ip.data
                            if tcp.dport == int(port_expected) and len(
                                    tcp.data) > 0:
                                tcp_layer = (tcp.sport, tcp.dport)
                                buf_req += tcp.data
                                try:
                                    http_req = dpkt.http.Request(buf_req)
                                except dpkt.dpkt.NeedData as e:
                                    pass
                                except dpkt.UnpackError as e:
                                    pass
                                else:
                                    self.requests.append({
                                        'ip-src': ip.src,
                                        'ip-dst': ip.dst,
                                        'port-src': tcp.sport,
                                        'port-dst': tcp.dport,
                                        'tcp-data': buf_req,
                                        'tcp-object': http_req
                                    })
                                    self.addLogWarning(
                                        txt="<< %s http request(s) extracted" %
                                        len(self.requests))
                                    buf_req = ''

            # decode http responses
            i = 1
            self.progressBar.setValue(0)
            for ts, buf in pcap:
                self.progressBar.setValue(i)
                i += 1

                # read ethernet layer
                eth = dpkt.ethernet.Ethernet(buf)
                if eth.type == dpkt.ethernet.ETH_TYPE_IP:
                    # continue with ip decoding layer
                    ip = eth.data
                    if ip.src == ip_expected:
                        ip_layer = (ip.src, ip.dst)
                        if ip.p == dpkt.ip.IP_PROTO_TCP:
                            tcp = ip.data
                            if tcp.sport == int(port_expected) and len(
                                    tcp.data) > 0:
                                tcp_layer = (tcp.sport, tcp.dport)
                                if (tcp.data).startswith('HTTP/'):
                                    try:
                                        new_res = "%s\r\n\r\n" % (
                                            tcp.data).splitlines()[0]
                                        http_res = dpkt.http.Response(new_res)
                                    except dpkt.dpkt.NeedData as e:
                                        pass
                                    except dpkt.UnpackError as e:
                                        pass
                                    else:
                                        self.responses.append({
                                            'ip-src':
                                            ip.src,
                                            'ip-dst':
                                            ip.dst,
                                            'port-src':
                                            tcp.sport,
                                            'port-dst':
                                            tcp.dport,
                                            'tcp-data':
                                            new_res,
                                            'tcp-object':
                                            http_res
                                        })
                                        self.addLogWarning(
                                            txt=
                                            "<< %s http response(s) extracted"
                                            % len(self.responses))
            if self.requests:
                self.addLogSuccess("<< File decoded with success!")
                self.addLogWarning(
                    "<< Click on the export button to generate the test!")
                self.exportToAction.setEnabled(True)
            else:
                self.addLogWarning("<< No http extracted!")
Exemple #52
0
class ProprietesAffichage(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self, parent)
        self.parent = parent
        self.panel = self.parent.parent.panel
        self.canvas = self.panel.canvas
        self.islabel = self.parent.parent.islabel
        self.objets = parent.objets
        self.sizer = QVBoxLayout()

        self.changements = {} # ce dictionnaire contiendra tous les styles modifiés
        encadre = QHBoxLayout()

        if not self.islabel:
            proprietes = {'fixe': u'Objet fixe', 'visible': u'Objet visible', 'trace': u'Laisser une trace'}
            for propriete, titre in proprietes.items():
                self.add_checkbox(encadre, propriete, titre)


        encadre1 = QVBoxLayout()
        if not self.islabel:
            ligne = QHBoxLayout()
            if len(self.objets) == 1:
                self.etiquette = etiquette = QLineEdit()
                etiquette.setText(self.objets[0].style("label"))
                etiquette.setMinimumWidth(200)
                etiquette.editingFinished.connect(self.EvtEtiquette)
                ligne.addWidget(etiquette)
            if [objet for objet in self.objets if objet.etiquette is not None]:
                editer = QPushButton(u"Style")
                editer.clicked.connect(self.EvtLabelStyle)
                ligne.addWidget(editer)
            encadre1.addLayout(ligne)

            objets = [objet for objet in self.objets if objet.style("legende") is not None]
            if objets:
                leg = objets[0].style("legende")
                legende = QHBoxLayout()
                self.radio_nom = QRadioButton("Nom")
                ##self.radio_nom.SetValue(0)
                self.radio_etiquette = QRadioButton(u"Texte")
                ##self.radio_etiquette.SetValue(0)
                self.radio_formule = QRadioButton(u"Formule")
                ##self.radio_formule.SetValue(0)
                self.radio_aucun = QRadioButton(u"Aucun")
                ##self.radio_aucun.SetValue(0)
                if all(objet.style("legende") == leg for objet in objets):
                    if leg == NOM:
                        self.radio_nom.setChecked(True)
                    elif leg == TEXTE:
                        self.radio_etiquette.setChecked(True)
                    elif leg == FORMULE:
                        self.radio_formule.setChecked(True)
                    elif leg == RIEN:
                        self.radio_aucun.setChecked(True)

                self.radio_nom.toggled.connect(partial(self.EvtLegende, NOM))
                self.radio_etiquette.toggled.connect(partial(self.EvtLegende, TEXTE))
                self.radio_formule.toggled.connect(partial(self.EvtLegende, FORMULE))
                self.radio_aucun.toggled.connect(partial(self.EvtLegende, RIEN))
                legende.addWidget(self.radio_nom)
                legende.addWidget(self.radio_etiquette)
                legende.addWidget(self.radio_formule)
                legende.addWidget(self.radio_aucun)
                encadre1.addWidget(QLabel(u"Afficher : "))
                encadre1.addLayout(legende)



        encadre2 = QVBoxLayout()

        objets = [objet for objet in self.objets if objet.style("style") is not None]
        # on ne peut regler les styles simultanement que pour des objets de meme categorie
        categorie = objets and objets[0].style("categorie") or None

        if objets and categorie and all(objet.style("categorie") == categorie for objet in objets):
            choix = QHBoxLayout()
            choix.addWidget(QLabel(u"Style de l'objet : "))

            #categorie = objets[0].style("categorie") or "lignes"
            self.liste_styles = getattr(param, "styles_de_" + categorie, [])
            self.style = QComboBox()
            self.style.addItems(self.liste_styles)
            self.style.currentIndexChanged.connect(self.EvtStyle)

            style = objets[0].style("style")
            if style in self.liste_styles and all(objet.style("style") == style for objet in objets):
                self.style.setCurrentIndex(self.liste_styles.index(style)) # on sélectionne le style actuel
            choix.addWidget(self.style)
            encadre2.addLayout(choix)


        objets = [objet for objet in self.objets if objet.style("hachures") is not None]
        if objets:
            choix = QHBoxLayout()
            choix.addWidget(QLabel(u"Style des hâchures : "))

            self.types_de_hachures = getattr(param, "types_de_hachures", [])
            self.hachures = QComboBox()
            self.hachures.addItems(self.types_de_hachures)
            self.hachure.currentIndexChanged.connect(self.EvtHachures)

            hachures = objets[0].style("hachures")
            if hachures in self.types_de_hachures and all(objet.style("hachures") == hachures for objet in objets):
                self.hachures.setCurrentIndex(self.types_de_hachures.index(hachures)) # on sélectionne les hachures actuelles
            choix.addWidget(self.hachures)
            encadre2.addLayout(choix)


        objets = [objet for objet in self.objets if objet.style("famille") is not None]
        categorie = objets and objets[0].style("categorie") or None

        if objets and categorie and all(objet.style("categorie") == categorie for objet in objets):
            choix = QHBoxLayout()
            choix.addWidget(QLabel("Police : "))

            #categorie = self.objet.style("categorie") or "lignes"
            self.liste_familles = getattr(param, "familles_de_" + categorie, [])
            self.famille = QComboBox()
            self.famille.addItems(self.liste_familles)
            self.famille.currentIndexChanged.connect(self.EvtFamille)

            famille = objets[0].style("famille")
            if famille in self.liste_familles and all(objet.style("famille") == famille for objet in objets):
                self.famille.setCurrentIndex(self.liste_familles.index(famille)) # on sélectionne la famille actuelle

            choix.addWidget(self.famille)
            encadre2.addLayout(choix)


        objets = [objet for objet in self.objets if objet.style("couleur") is not None]
        if objets:
            couleur = objets[0].style("couleur")
            choix = QHBoxLayout()
            choix.addWidget(QLabel(u"Couleur de l'objet : "))
            if all(objet.style("couleur") == couleur for objet in objets):
                # conversion du format matplotlib au format Qt
                r, g, b = colorConverter.to_rgb(couleur)
                couleur = QColor(int(255*r), int(255*g), int(255*b))
            else:
                couleur = None
            b = ColorSelecter(self, color=couleur)
            b.colorSelected.connect(self.OnSelectColour)
            choix.addWidget(b)
            encadre2.addLayout(choix)


        objets = [objet for objet in self.objets if objet.style("epaisseur") is not None]
        if objets:
            epaiss = objets[0].style("epaisseur")
            epaisseur = QHBoxLayout()
            epaisseur.addWidget(QLabel(u"Epaisseur (en 10e de pixels) : "))
            self.epaisseur = QSpinBox()
            self.epaisseur.setMinimumSize(30, 50)
            self.epaisseur.setRange(1,10000)
            if all(objet.style("epaisseur") == epaiss for objet in objets):
                self.epaisseur.setValue(10*epaiss)
            else:
                self.epaisseur.setSpecialValueText(' ')
                print(u'FIXME: cas non géré.')
            self.epaisseur.valueChanged.connect(self.EvtEpaisseur)
            epaisseur.addWidget(self.epaisseur)
            encadre2.addLayout(epaisseur)


        objets = [objet for objet in self.objets if objet.style("taille") is not None]
        if objets:
            tail = objets[0].style("taille")
            taille = QHBoxLayout()
            taille.addWidget(QLabel(u"Taille (en 10e de pixels) : "))
            self.taille = QSpinBox()
            self.taille.setMinimumSize(30, 50)
            self.taille.setRange(1,10000)
            if all(objet.style("taille") == tail for objet in objets):
                self.taille.setValue(10*tail)
            else:
                self.taille.setSpecialValueText(' ')
                print(u'FIXME: cas non géré.')
            self.taille.valueChanged.connect(self.EvtTaille)
            taille.addWidget(self.taille)
            encadre2.addLayout(taille)


        objets = [objet for objet in self.objets if objet.style("position") is not None]
        if objets:
            pos = objets[0].style("position")
            position = QHBoxLayout()
            position.addWidget(QLabel(u"Position de la flêche : "))
            self.position = QSpinBox()
            self.position.setMinimumSize(30, 50)
            self.position.setRange(0, 100)
            if all(objet.style("position") == pos for objet in objets):
                self.position.setValue(100*pos)
            else:
                self.position.setSpecialValueText(' ')
                print(u'FIXME: cas non géré.')
            self.position.valueChanged.connect(self.EvtPosition)
            position.addWidget(self.position)
            encadre2.addLayout(position)



        objets = [objet for objet in self.objets if objet.style("angle") is not None]
        if objets:
            ang = objets[0].style("angle")
            angle = QHBoxLayout()
            angle.addWidget(QLabel(u"Angle (en degré) : "))
            self.angle = QSpinBox()
            self.angle.setMinimumSize(30, 50)
            self.angle.setRange(0, 360)
            if all(objet.style("angle") == ang for objet in objets):
                self.angle.setValue(ang)
            else:
                self.angle.setSpecialValueText(' ')
                print(u'FIXME: cas non géré.')
            self.angle.valueChanged.connect(self.EvtAngle)
            angle.addWidget(self.angle)
            encadre2.addLayout(angle)

        self.add_checkbox(encadre, 'double_fleche', u"Flêche double")

        objets = [objet for objet in self.objets if objet.style("codage") is not None]
        # on ne peut regler les codages simultanement que pour des objets de meme categorie
        categorie = objets and objets[0].style("categorie") or None


        if objets and categorie and all(objet.style("categorie") == categorie for objet in objets):
            choix = QHBoxLayout()
            choix.addWidget(QLabel("Codage : "))

            #categorie = objets[0].style("categorie") or "lignes"
            self.liste_codages = getattr(param, "codage_des_" + categorie, [])
            self.codage = QComboBox()
            self.codage.addItems(self.liste_codages)
            self.codage.currentIndexChanged.connect(self.EvtCodage)

            codage = objets[0].style("codage")
            if codage in self.liste_codages and all(objet.style("codage") == codage for objet in objets):
                self.codage.setCurrentIndex(self.liste_codages.index(codage)) # on sélectionne le codage actuel
            choix.addWidget(self.codage)
            encadre2.addLayout(choix)


        boutons = QHBoxLayout()
        ok = QPushButton('OK')
        ok.clicked.connect(self.EvtOk)
        boutons.addWidget(ok)

        appliquer = QPushButton(u"Appliquer")
        appliquer.clicked.connect(self.EvtAppliquer)
        boutons.addWidget(appliquer)

        if not self.islabel:
            supprimer = QPushButton(u"Supprimer")
            supprimer.clicked.connect(self.EvtSupprimer)
            boutons.addWidget(supprimer)

        annuler = QPushButton(u"Annuler")
        annuler.clicked.connect(self.EvtAnnuler)
        boutons.addWidget(annuler)

        if encadre.count(): # ne pas afficher une rubrique vide !
            encadre_box = QGroupBox(u"Mode d'affichage")
            encadre_box.setLayout(encadre)
            self.sizer.addWidget(encadre_box)
        if encadre1.count():
            encadre1_box = QGroupBox(u"Etiquette")
            encadre_box.setLayout(encadre1)
            self.sizer.addWidget(encadre1_box)
        if encadre2.count():
            encadre2_box = QGroupBox(u"Styles")
            encadre_box.setLayout(encadre2)
            self.sizer.addWidget(encadre2_box)
        self.sizer.addLayout(boutons)
        self.setLayout(self.sizer)
        ##self.parent.parent.dim1 = self.sizer.CalcMin().Get()


    def add_checkbox(self, layout, propriete, titre):
        objets = [objet for objet in self.objets if objet.style(propriete) is not None]
        if objets:
            cb = QCheckBox(titre)
            cb.setTristate(True)
            layout.addWidget(cb)
            verifies = [objet.style(propriete) is True for objet in objets]
            if not any(verifies):
                etat = Qt.Unchecked
            elif all(verifies):
                etat = Qt.Checked
            else:
                etat = Qt.PartiallyChecked
            cb.setCheckState(etat)
            cb.stateChanged.connect(partial(self.checked, propriete))
            cb.stateChanged.connect(partial(cb.setTristate, False))


    def EvtLegende(self, valeur):
        self.changements["legende"] = valeur

    def checked(self, propriete, state):
        self.changements[propriete] = (state == Qt.Checked)

    def EvtEtiquette(self):
        self.changements["label"] = self.etiquette.toPlainText()

    def OnSelectColour(self, color):
        # conversion du format Qt au format matplotlib
        self.changements["couleur"] = color.getRgb()

    def EvtStyle(self, index):
        self.changements["style"] = self.liste_styles[index]

    def EvtHachures(self, index):
        self.changements["hachures"] = self.types_de_hachures[index]

    def EvtCodage(self, index):
        self.changements["codage"] = self.liste_codages[index]

    def EvtFamille(self, index):
        self.changements["famille"] = self.liste_familles[index]

    def EvtOk(self):
        self.EvtAppliquer()
        self.EvtAnnuler()

    def EvtAppliquer(self):
        with self.canvas.geler_affichage(actualiser=True, sablier=True):
            try:
                for objet in self.objets:
                    changements = self.changements.copy()
                    for key in changements.copy():
                        if objet.style(key) is None: # le style n'a pas de sens pour l'objet
                            changements.pop(key)
                    if self.islabel:
                        self.canvas.executer(u"%s.etiquette.style(**%s)" %(objet.parent.nom, changements))
                    else:
                        self.canvas.executer(u"%s.style(**%s)" %(objet.nom, changements))
            except:
                print_error()


    def EvtSupprimer(self):
        with self.canvas.geler_affichage(actualiser=True, sablier=True):
            for objet in self.objets:
                self.canvas.executer(u"del %s" %objet.nom)
        self.EvtAnnuler()

    def EvtAnnuler(self):
        # Ce qui suit corrige un genre de bug bizarre de wx:
        # quand une fenêtre de sélection de couleur a été affichée,
        # la fenêtre principale passe au second plan à la fermeture de la fenêtre de propriétés ?!?
        # (ce qui est très désagréable dès qu'un dossier est ouvert dans l'explorateur, par exemple !)
        # -> à supprimer avec Qt ?
        self.parent.parent.fenetre_principale.raise_()
        self.parent.parent.close() # fermeture de la frame

    def EvtLabelStyle(self):
        win = Proprietes(self.parent, [objet.etiquette for objet in self.objets
                                       if objet.etiquette is not None], True)
        win.show()


    def EvtEpaisseur(self):
        self.changements["epaisseur"] = self.epaisseur.value()/10

    def EvtTaille(self):
        self.changements["taille"] = self.taille.value()/10

    def EvtAngle(self):
        self.changements["angle"] = self.angle.value()

    def EvtPosition(self):
        self.changements["position"] = self.position.value()/100
class FindInFilesDialog(QDialog):
    """Dialog to configure and trigger the search in the files."""
    def __init__(self, result_widget, parent):
        super(FindInFilesDialog, self).__init__(parent)
        self._find_thread = FindInFilesThread()
        self.setWindowTitle(translations.TR_FIND_IN_FILES)
        self.resize(400, 300)
        #MAIN LAYOUT
        main_vbox = QVBoxLayout(self)

        self.pattern_line_edit = QLineEdit()
        self.pattern_line_edit.setPlaceholderText(translations.TR_FIND + "...")
        self.dir_name_root = None
        self.user_home = os.path.expanduser('~')
        self.dir_combo = QComboBox()
        self.dir_combo.addItem(self.user_home)
        self.dir_combo.setEditable(True)
        self.open_button = QPushButton(QIcon(":img/find"),
                                       translations.TR_OPEN)
        self.filters_line_edit = QLineEdit("*.py")
        self.filters_line_edit.setPlaceholderText("*.py")
        self.filters_line_edit.setCompleter(
            QCompleter([
                "*{}".format(item) for item in settings.SUPPORTED_EXTENSIONS
            ]))
        self.replace_line = QLineEdit()
        self.replace_line.setEnabled(False)
        self.replace_line.setPlaceholderText(translations.TR_TEXT_FOR_REPLACE +
                                             "...")
        self.check_replace = QCheckBox(translations.TR_REPLACE)
        self.case_checkbox = QCheckBox(translations.TR_CASE_SENSITIVE)
        self.type_checkbox = QCheckBox(translations.TR_REGULAR_EXPRESSION)
        self.recursive_checkbox = QCheckBox(translations.TR_RECURSIVE)
        self.recursive_checkbox.setCheckState(Qt.Checked)
        self.phrase_radio = QRadioButton(translations.TR_SEARCH_BY_PHRASE)
        self.phrase_radio.setChecked(True)
        self.words_radio = QRadioButton(
            translations.TR_SEARCH_FOR_ALL_THE_WORDS)
        self.find_button = QPushButton(translations.TR_FIND + "!")
        self.find_button.setMaximumWidth(150)
        self.cancel_button = QPushButton(translations.TR_CANCEL)
        self.cancel_button.setMaximumWidth(150)
        self.result_widget = result_widget

        hbox = QHBoxLayout()
        hbox.addWidget(self.find_button)
        hbox.addWidget(self.cancel_button)

        #main section
        find_group_box = QGroupBox(translations.TR_MAIN)
        grid = QGridLayout()
        grid.addWidget(QLabel(translations.TR_TEXT), 0, 0)
        grid.addWidget(self.pattern_line_edit, 0, 1)
        grid.addWidget(QLabel(translations.TR_DIRECTORY), 1, 0)
        grid.addWidget(self.dir_combo, 1, 1)
        grid.addWidget(self.open_button, 1, 2)
        grid.addWidget(QLabel(translations.TR_FILTER), 2, 0)
        grid.addWidget(self.filters_line_edit, 2, 1)
        grid.addWidget(self.check_replace, 3, 0)
        grid.addWidget(self.replace_line, 3, 1)

        find_group_box.setLayout(grid)
        #add main section to MAIN LAYOUT
        main_vbox.addWidget(find_group_box)

        #options sections
        options_group_box = QGroupBox(translations.TR_OPTIONS)
        gridOptions = QGridLayout()
        gridOptions.addWidget(self.case_checkbox, 0, 0)
        gridOptions.addWidget(self.type_checkbox, 1, 0)
        gridOptions.addWidget(self.recursive_checkbox, 2, 0)
        gridOptions.addWidget(self.phrase_radio, 0, 1)
        gridOptions.addWidget(self.words_radio, 1, 1)

        options_group_box.setLayout(gridOptions)
        #add options sections to MAIN LAYOUT
        main_vbox.addWidget(options_group_box)

        #add buttons to MAIN LAYOUT
        main_vbox.addLayout(hbox)

        #Focus
        self.pattern_line_edit.setFocus()
        self.open_button.setFocusPolicy(Qt.NoFocus)

        #signal
        self.connect(self.open_button, SIGNAL("clicked()"), self._select_dir)
        self.connect(self.find_button, SIGNAL("clicked()"),
                     self._find_in_files)
        self.connect(self.cancel_button, SIGNAL("clicked()"),
                     self._kill_thread)
        self.connect(self._find_thread, SIGNAL("found_pattern(PyQt_PyObject)"),
                     self._found_match)
        self.connect(self._find_thread, SIGNAL("finished()"),
                     self._find_thread_finished)
        self.connect(self.type_checkbox, SIGNAL("stateChanged(int)"),
                     self._change_radio_enabled)
        self.connect(self.check_replace, SIGNAL("stateChanged(int)"),
                     self._replace_activated)
        self.connect(self.words_radio, SIGNAL("clicked(bool)"),
                     self._words_radio_pressed)

    def _replace_activated(self):
        """If replace is activated, display the replace widgets."""
        self.replace_line.setEnabled(self.check_replace.isChecked())
        self.phrase_radio.setChecked(True)

    def _words_radio_pressed(self, value):
        """If search by independent words is activated, replace is not."""
        self.replace_line.setEnabled(not value)
        self.check_replace.setChecked(not value)
        self.words_radio.setChecked(True)

    def _change_radio_enabled(self, val):
        """Control the state of the radio buttons."""
        enabled = not self.type_checkbox.isChecked()
        self.phrase_radio.setEnabled(enabled)
        self.words_radio.setEnabled(enabled)

    def show(self, actual_project=None, actual=None):
        """Display the dialog and load the projects."""
        self.dir_combo.clear()
        self.dir_name_root = actual_project if \
            actual_project else [self.user_home]
        self.dir_combo.addItems(self.dir_name_root)
        if actual:
            index = self.dir_combo.findText(actual)
            self.dir_combo.setCurrentIndex(index)
        super(FindInFilesDialog, self).show()
        self.pattern_line_edit.setFocus()

    def reject(self):
        """Close the dialog and hide the tools dock."""
        self._kill_thread()
        tools_dock = IDE.get_service('tools_dock')
        if tools_dock:
            tools_dock.hide()
        super(FindInFilesDialog, self).reject()

    def _find_thread_finished(self):
        """Wait on thread finished."""
        self.emit(SIGNAL("finished()"))
        self._find_thread.wait()

    def _select_dir(self):
        """When a new folder is selected, add to the combo if needed."""
        dir_name = QFileDialog.getExistingDirectory(
            self, translations.TR_OPEN, self.dir_combo.currentText(),
            QFileDialog.ShowDirsOnly)
        index = self.dir_combo.findText(dir_name)
        if index >= 0:
            self.dir_combo.setCurrentIndex(index)
        else:
            self.dir_combo.insertItem(0, dir_name)
            self.dir_combo.setCurrentIndex(0)

    def _found_match(self, result):
        """Update the tree for each match found."""
        file_name = result[0]
        items = result[1]
        self.result_widget.update_result(self.dir_combo.currentText(),
                                         file_name, items)

    def _kill_thread(self):
        """Kill the thread."""
        if self._find_thread.isRunning():
            self._find_thread.cancel()
        self.accept()

    def _find_in_files(self):
        """Trigger the search on the files."""
        self.emit(SIGNAL("findStarted()"))
        self._kill_thread()
        self.result_widget.clear()
        pattern = self.pattern_line_edit.text()
        dir_name = self.dir_combo.currentText()

        filters = re.split("[,;]", self.filters_line_edit.text())

        #remove the spaces in the words Ex. (" *.foo"--> "*.foo")
        filters = [f.strip() for f in filters]
        case_sensitive = self.case_checkbox.isChecked()
        type_ = QRegExp.RegExp if \
            self.type_checkbox.isChecked() else QRegExp.FixedString
        recursive = self.recursive_checkbox.isChecked()
        by_phrase = True
        if self.phrase_radio.isChecked() or self.type_checkbox.isChecked():
            regExp = QRegExp(pattern, case_sensitive, type_)
        elif self.words_radio.isChecked():
            by_phrase = False
            type_ = QRegExp.RegExp
            pattern = '|'.join([word.strip() for word in pattern.split()])
            regExp = QRegExp(pattern, case_sensitive, type_)
        #save a reference to the root directory where we find
        self.dir_name_root = dir_name
        self._find_thread.find_in_files(dir_name, filters, regExp, recursive,
                                        by_phrase)
Exemple #54
0
    def __init__(self, parameter, parent=None):
        """Constructor.

        :param parameter: A GroupSelectParameter object.
        :type parameter: GroupSelectParameter
        """
        QWidget.__init__(self, parent)
        self._parameter = parameter

        # Store spin box
        self.spin_boxes = {}

        # Create elements
        # Label (name)
        self.label = QLabel(self._parameter.name)

        # Layouts
        self.main_layout = QVBoxLayout()
        self.input_layout = QVBoxLayout()

        # _inner_input_layout must be filled with widget in the child class
        self.inner_input_layout = QVBoxLayout()

        self.radio_button_layout = QGridLayout()

        # Create radio button group
        self.input_button_group = QButtonGroup()

        # List widget
        self.list_widget = QListWidget()
        self.list_widget.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.list_widget.setDragDropMode(QAbstractItemView.DragDrop)
        self.list_widget.setDefaultDropAction(Qt.MoveAction)
        self.list_widget.setEnabled(False)
        self.list_widget.setSizePolicy(QSizePolicy.Maximum,
                                       QSizePolicy.Expanding)

        for i, key in enumerate(self._parameter.options):
            value = self._parameter.options[key]
            radio_button = QRadioButton(value.get('label'))
            self.radio_button_layout.addWidget(radio_button, i, 0)
            if value.get('type') == SINGLE_DYNAMIC:
                double_spin_box = QDoubleSpinBox()
                self.radio_button_layout.addWidget(double_spin_box, i, 1)
                double_spin_box.setValue(value.get('value', 0))
                double_spin_box.setMinimum(
                    value.get('constraint', {}).get('min', 0))
                double_spin_box.setMaximum(
                    value.get('constraint', {}).get('max', 1))
                double_spin_box.setSingleStep(
                    value.get('constraint', {}).get('step', 0.01))
                step = double_spin_box.singleStep()
                if step > 1:
                    precision = 0
                else:
                    precision = len(str(step).split('.')[1])
                    if precision > 3:
                        precision = 3
                double_spin_box.setDecimals(precision)
                self.spin_boxes[key] = double_spin_box

                # Enable spin box depends on the selected option
                if self._parameter.selected == key:
                    double_spin_box.setEnabled(True)
                else:
                    double_spin_box.setEnabled(False)

            elif value.get('type') == STATIC:
                static_value = value.get('value', 0)
                if static_value is not None:
                    self.radio_button_layout.addWidget(
                        QLabel(str(static_value)), i, 1)
            elif value.get('type') == MULTIPLE_DYNAMIC:
                selected_fields = value.get('value', [])
                if self._parameter.selected == key:
                    self.list_widget.setEnabled(True)
                else:
                    self.list_widget.setEnabled(False)

            self.input_button_group.addButton(radio_button, i)
            if self._parameter.selected == key:
                radio_button.setChecked(True)

        # Help text
        self.help_label = QLabel(self._parameter.help_text)
        self.help_label.setSizePolicy(QSizePolicy.Maximum,
                                      QSizePolicy.Expanding)
        self.help_label.setWordWrap(True)
        self.help_label.setAlignment(Qt.AlignTop)

        self.inner_input_layout.addLayout(self.radio_button_layout)
        self.inner_input_layout.addWidget(self.list_widget)

        # Put elements into layouts
        self.input_layout.addWidget(self.label)
        self.input_layout.addLayout(self.inner_input_layout)

        self.help_layout = QVBoxLayout()
        self.help_layout.addWidget(self.help_label)

        self.main_layout.addLayout(self.input_layout)
        self.main_layout.addLayout(self.help_layout)

        self.setLayout(self.main_layout)

        self.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Expanding)

        # Update list widget
        self.update_list_widget()

        # Connect signal
        self.input_button_group.buttonClicked.connect(
            self.radio_buttons_clicked)
Exemple #55
0
class TidySettingsDialog(QDialog):
    " PythonTidy.py script settings dialog "

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

        self.__settings = settings
        self.__path = path

        self.__createLayout()
        self.setWindowTitle("PythonTidy settings")
        return

    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

    def __reset(self):
        " Resets the values to default "

        self.__colsEdit.setText(
            str(self.__settings.getDefaultValue("COL_LIMIT")))
        self.__assignmentEdit.setText(
            self.__settings.getDefaultValue("ASSIGNMENT"))
        self.__funcAssignEdit.setText(
            self.__settings.getDefaultValue("FUNCTION_PARAM_ASSIGNMENT"))
        self.__dictSepEdit.setText(
            self.__settings.getDefaultValue("DICT_COLON"))
        self.__sliceSepEdit.setText(
            self.__settings.getDefaultValue("SLICE_COLON"))
        self.__inEdit.setText(self.__settings.getDefaultValue("SHEBANG"))
        self.__outCodingEdit.setText(self.__settings.getDefaultValue("CODING"))
        self.__srcCodingEdit.setText(
            self.__settings.getDefaultValue("CODING_SPEC"))
        self.__boilEdit.setPlainText(
            self.__settings.getDefaultValue("BOILERPLATE"))
        self.__keepBlanks.setChecked(
            self.__settings.getDefaultValue("KEEP_BLANK_LINES"))
        self.__addBlanks.setChecked(
            self.__settings.getDefaultValue("ADD_BLANK_LINES_AROUND_COMMENTS"))
        self.__justifyDoc.setChecked(
            self.__settings.getDefaultValue("LEFTJUST_DOC_STRINGS"))
        self.__wrapDoc.setChecked(
            self.__settings.getDefaultValue("WRAP_DOC_STRINGS"))
        self.__recodeStrings.setChecked(
            self.__settings.getDefaultValue("RECODE_STRINGS"))
        self.__splitStrings.setChecked(
            self.__settings.getDefaultValue("CAN_SPLIT_STRINGS"))
        self.__keepUnassignedConst.setChecked(
            self.__settings.getDefaultValue("KEEP_UNASSIGNED_CONSTANTS"))
        self.__parenTuple.setChecked(
            self.__settings.getDefaultValue("PARENTHESIZE_TUPLE_DISPLAY"))
        self.__javaListDedent.setChecked(
            self.__settings.getDefaultValue("JAVA_STYLE_LIST_DEDENT"))

        use1 = self.__settings.getDefaultValue("SINGLE_QUOTED_STRINGS")
        use2 = self.__settings.getDefaultValue("DOUBLE_QUOTED_STRINGS")
        if use1:
            self.__use1RButton.setChecked(True)
            self.__use2RButton.setChecked(False)
            self.__useAsIsRButton.setChecked(False)
        elif use2:
            self.__use1RButton.setChecked(False)
            self.__use2RButton.setChecked(True)
            self.__useAsIsRButton.setChecked(False)
        else:
            self.__use1RButton.setChecked(False)
            self.__use2RButton.setChecked(False)
            self.__useAsIsRButton.setChecked(True)

        self.__validate()
        return

    @staticmethod
    def __setValid(field, value):
        " Changes the field background depending on the validity "
        if value:
            field.setStyleSheet("")
        else:
            if isinstance(field, QLineEdit):
                typeName = "QLineEdit"
            else:
                typeName = "QTextEdit"
            field.setStyleSheet(typeName + "{ background: #ffa07a; }")
        return

    def __saveAndAccept(self):
        " Saves the changes and accepts the values "
        self.__validate()
        if self.__tidyButton.isEnabled() == False:
            return

        self.__settings.settings["COL_LIMIT"] = int(self.__colsEdit.text())
        self.__settings.settings["ASSIGNMENT"] = self.__assignmentEdit.text()
        self.__settings.settings[
            "FUNCTION_PARAM_ASSIGNMENT"] = self.__funcAssignEdit.text()
        self.__settings.settings["DICT_COLON"] = self.__dictSepEdit.text()
        self.__settings.settings["SLICE_COLON"] = self.__sliceSepEdit.text()
        self.__settings.settings["SHEBANG"] = self.__inEdit.text()
        self.__settings.settings["CODING"] = self.__outCodingEdit.text()
        self.__settings.settings["CODING_SPEC"] = self.__srcCodingEdit.text()
        self.__settings.settings["BOILERPLATE"] = self.__boilEdit.toPlainText()
        self.__settings.settings["KEEP_BLANK_LINES"] = bool(
            self.__keepBlanks.isChecked())
        self.__settings.settings["ADD_BLANK_LINES_AROUND_COMMENTS"] = bool(
            self.__addBlanks.isChecked())
        self.__settings.settings["LEFTJUST_DOC_STRINGS"] = bool(
            self.__justifyDoc.isChecked())
        self.__settings.settings["WRAP_DOC_STRINGS"] = bool(
            self.__wrapDoc.isChecked())
        self.__settings.settings["RECODE_STRINGS"] = bool(
            self.__recodeStrings.isChecked())
        self.__settings.settings["CAN_SPLIT_STRINGS"] = bool(
            self.__splitStrings.isChecked())
        self.__settings.settings["KEEP_UNASSIGNED_CONSTANTS"] = bool(
            self.__keepUnassignedConst.isChecked())
        self.__settings.settings["PARENTHESIZE_TUPLE_DISPLAY"] = bool(
            self.__parenTuple.isChecked())
        self.__settings.settings["JAVA_STYLE_LIST_DEDENT"] = bool(
            self.__javaListDedent.isChecked())

        if self.__use1RButton.isChecked():
            self.__settings.settings["SINGLE_QUOTED_STRINGS"] = True
            self.__settings.settings["DOUBLE_QUOTED_STRINGS"] = False
        elif self.__use2RButton.isChecked():
            self.__settings.settings["SINGLE_QUOTED_STRINGS"] = False
            self.__settings.settings["DOUBLE_QUOTED_STRINGS"] = True
        else:
            self.__settings.settings["SINGLE_QUOTED_STRINGS"] = False
            self.__settings.settings["DOUBLE_QUOTED_STRINGS"] = False

        try:
            self.__settings.saveToFile(self.__path)
        except:
            logging.error( "Error saving PythonTidy settings into " + \
                           self.__path + ". Ignor and continue." )
        self.accept()
        return

    def __validate(self, text=None):
        " Validates input "
        allValid = True
        val = self.__colsEdit.text()
        try:
            intVal = int(val)
            if intVal <= 0:
                allValid = False
                self.__setValid(self.__colsEdit, False)
            else:
                self.__setValid(self.__colsEdit, True)
        except:
            allValid = False
            self.__setValid(self.__colsEdit, False)

        if '=' not in self.__assignmentEdit.text():
            allValid = False
            self.__setValid(self.__assignmentEdit, False)
        else:
            self.__setValid(self.__assignmentEdit, True)

        if '=' not in self.__funcAssignEdit.text():
            allValid = False
            self.__setValid(self.__funcAssignEdit, False)
        else:
            self.__setValid(self.__funcAssignEdit, True)

        if ':' not in self.__dictSepEdit.text():
            allValid = False
            self.__setValid(self.__dictSepEdit, False)
        else:
            self.__setValid(self.__dictSepEdit, True)

        if ':' not in self.__sliceSepEdit.text():
            allValid = False
            self.__setValid(self.__sliceSepEdit, False)
        else:
            self.__setValid(self.__sliceSepEdit, True)

        val = self.__inEdit.text()
        if val.strip() != "" and not val.strip().startswith('#!'):
            allValid = False
            self.__setValid(self.__inEdit, False)
        else:
            self.__setValid(self.__inEdit, True)

        val = self.__srcCodingEdit.text()
        if val.strip() != "" and not val.strip().startswith('#'):
            allValid = False
            self.__setValid(self.__srcCodingEdit, False)
        else:
            self.__setValid(self.__srcCodingEdit, True)

        self.__tidyButton.setEnabled(allValid)
        return
Exemple #56
0
class ShortcutEditDialog(QDialog):
    """A modal dialog to view and/or edit keyboard shortcuts."""
    def __init__(self, parent=None, conflictCallback=None, *cbArgs):
        """conflictCallback is a optional method called when a shortcut is changed.
        
        cbArgs is optional arguments of the conflictCallback method.
        it should return the name of the potential conflict or a null value """

        super(ShortcutEditDialog, self).__init__(parent)
        self.conflictCallback = conflictCallback
        self.cbArgs = cbArgs
        self.setMinimumWidth(400)
        # create gui

        layout = QVBoxLayout()
        layout.setSpacing(10)
        self.setLayout(layout)

        top = QHBoxLayout()
        top.setSpacing(4)
        p = self.toppixmap = QLabel()
        l = self.toplabel = QLabel()
        top.addWidget(p)
        top.addWidget(l, 1)
        layout.addLayout(top)
        grid = QGridLayout()
        grid.setSpacing(4)
        grid.setColumnStretch(1, 2)
        layout.addLayout(grid)

        self.buttonDefault = QRadioButton(
            self, toggled=self.slotButtonDefaultToggled)
        self.buttonNone = QRadioButton(self)
        self.lconflictDefault = QLabel('test')
        self.lconflictDefault.setStyleSheet("color : red;")
        self.lconflictDefault.setVisible(False)
        self.buttonCustom = QRadioButton(self)
        grid.addWidget(self.buttonDefault, 0, 0, 1, 2)
        grid.addWidget(self.lconflictDefault, 1, 0, 1, 2)
        grid.addWidget(self.buttonNone, 2, 0, 1, 2)
        grid.addWidget(self.buttonCustom, 3, 0, 1, 2)

        self.keybuttons = []
        self.keylabels = []
        self.conflictlabels = []
        for num in range(4):
            l = QLabel(self)
            l.setStyleSheet("margin-left: 2em;")
            l.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
            b = KeySequenceWidget(self, num)
            b.keySequenceChanged.connect(self.slotKeySequenceChanged)
            l.setBuddy(b)
            self.keylabels.append(l)
            self.keybuttons.append(b)
            grid.addWidget(l, num + 4 + num, 0)
            grid.addWidget(b, num + 4 + num, 1)
            lconflict = QLabel()
            lconflict.setStyleSheet("color : red;")
            self.conflictlabels.append(lconflict)
            lconflict.setVisible(False)
            grid.addWidget(lconflict, num + 5 + num, 0, 1, 2, Qt.AlignHCenter)

        layout.addWidget(Separator(self))

        b = QDialogButtonBox(self)
        b.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        layout.addWidget(b)
        b.accepted.connect(self.accept)
        b.rejected.connect(self.reject)
        app.translateUI(self)

    def translateUI(self):
        self.setWindowTitle(app.caption(_("window title", "Edit Shortcut")))
        self.buttonNone.setText(_("&No shortcut"))
        self.buttonCustom.setText(_("Use a &custom shortcut:"))
        for num in range(4):
            self.keylabels[num].setText(
                _("Alternative #{num}:").format(
                    num=num) if num else _("Primary shortcut:"))

    def slotKeySequenceChanged(self, num):
        """Called when one of the keysequence buttons has changed."""
        self.checkConflict(num)
        self.buttonCustom.setChecked(True)

    def slotButtonDefaultToggled(self, val):
        if self.conflictCallback is not None:
            if not val:
                self.lconflictDefault.setVisible(False)
            else:
                if self._default:
                    conflictList = []
                    for s in self._default:
                        conflictName = self.conflictCallback(s, *self.cbArgs)
                        if conflictName:
                            conflictList.append(conflictName)
                    if conflictList:
                        text = _("Conflict with: {name}").format(
                            name="<b>{0}</b>".format(', '.join(conflictList)))
                        self.lconflictDefault.setText(text)
                        self.lconflictDefault.setVisible(True)
            QTimer.singleShot(0, self.adjustSize)

    def checkConflict(self, num):
        if self.conflictCallback is not None:
            conflictName = self.conflictCallback(
                self.keybuttons[num].shortcut(), *self.cbArgs)
            if conflictName:
                text = _("Conflict with: {name}").format(
                    name="<b>{0}</b>".format(conflictName))
                self.conflictlabels[num].setText(text)
                self.conflictlabels[num].setVisible(True)
            else:
                self.conflictlabels[num].setVisible(False)
            QTimer.singleShot(0, self.adjustSize)

    def editAction(self, action, default=None):
        # load the action
        self._action = action
        self._default = default
        self.toplabel.setText('<p>{0}</p>'.format(
            _("Here you can edit the shortcuts for {name}").format(
                name='<br/><b>{0}</b>:'.format(action.text()))))
        self.toppixmap.setPixmap(action.icon().pixmap(32))
        shortcuts = action.shortcuts()
        self.buttonDefault.setVisible(bool(default))
        if default is not None and shortcuts == default:
            self.buttonDefault.setChecked(True)
        else:
            if shortcuts:
                self.buttonCustom.setChecked(True)
                for num, key in enumerate(shortcuts[:4]):
                    self.keybuttons[num].setShortcut(key)
                    self.checkConflict(num)
            else:
                self.buttonNone.setChecked(True)

        if default:
            ds = "; ".join(
                key.toString(QKeySequence.NativeText) for key in default)
        else:
            ds = _("no keyboard shortcut", "none")
        self.buttonDefault.setText(
            _("Use &default shortcut ({name})").format(name=ds))
        return self.exec_()

    def done(self, result):
        if result:
            shortcuts = []
            if self.buttonDefault.isChecked():
                shortcuts = self._default
            elif self.buttonCustom.isChecked():
                for num in range(4):
                    seq = self.keybuttons[num].shortcut()
                    if not seq.isEmpty():
                        shortcuts.append(seq)
            self._action.setShortcuts(shortcuts)
        super(ShortcutEditDialog, self).done(result)